node_mtls.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package service
  2. import (
  3. "crypto/tls"
  4. "strings"
  5. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  6. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  7. )
  8. // NodeMtlsCaCert returns the PEM of this panel's node-auth CA certificate (the
  9. // public half) to copy into a node's mTLS trust setting, minting the CA and the
  10. // master client cert on first call so the panel is ready to present a client
  11. // certificate to mtls nodes.
  12. func (s *NodeService) NodeMtlsCaCert() (string, error) {
  13. settings := SettingService{}
  14. ca, err := settings.EnsureNodeMtlsCA()
  15. if err != nil {
  16. return "", err
  17. }
  18. if _, err := settings.EnsureMasterClientCert(); err != nil {
  19. return "", err
  20. }
  21. return string(ca.CertPEM), nil
  22. }
  23. // ReloadMasterMtlsClient validates the master credential currently stored by
  24. // the panel and drops cached mTLS connection pools. This makes an intentional
  25. // out-of-process credential rotation take effect without restarting x-ui (and
  26. // therefore without stopping the xray child process in the same service).
  27. func (s *NodeService) ReloadMasterMtlsClient() error {
  28. stored, err := (&SettingService{}).LoadMasterClientCert()
  29. if err != nil {
  30. return err
  31. }
  32. if _, err := tls.X509KeyPair(stored.CertPEM, stored.KeyPEM); err != nil {
  33. return err
  34. }
  35. runtime.InvalidateMasterClientConnections()
  36. return nil
  37. }
  38. // SetNodeMtlsTrustCA stores the CA certificate bundle trusted for incoming
  39. // node-API clients. An empty value clears it; changes apply after restart.
  40. func (s *NodeService) SetNodeMtlsTrustCA(caPem string) error {
  41. caPem = strings.TrimSpace(caPem)
  42. if caPem != "" {
  43. if _, err := parseCertificateBundlePEM([]byte(caPem)); err != nil {
  44. return common.NewError("invalid trust CA certificate bundle: ", err)
  45. }
  46. }
  47. return (&SettingService{}).setString(settingNodeMtlsClientCA, caPem)
  48. }