ssl.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. package ssl
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "github.com/go-acme/lego/v4/certificate"
  10. log "github.com/sirupsen/logrus"
  11. "github.com/spf13/cast"
  12. "os"
  13. "pmail/config"
  14. "pmail/services/setup"
  15. "pmail/signal"
  16. "pmail/utils/errors"
  17. "time"
  18. "github.com/go-acme/lego/v4/certcrypto"
  19. "github.com/go-acme/lego/v4/lego"
  20. "github.com/go-acme/lego/v4/registration"
  21. )
  22. type MyUser struct {
  23. Email string
  24. Registration *registration.Resource
  25. key crypto.PrivateKey
  26. }
  27. func (u *MyUser) GetEmail() string {
  28. return u.Email
  29. }
  30. func (u MyUser) GetRegistration() *registration.Resource {
  31. return u.Registration
  32. }
  33. func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
  34. return u.key
  35. }
  36. func GetSSL() string {
  37. cfg, err := setup.ReadConfig()
  38. if err != nil {
  39. panic(err)
  40. }
  41. if cfg.SSLType == "" {
  42. return config.SSLTypeAuto
  43. }
  44. return cfg.SSLType
  45. }
  46. func SetSSL(sslType string) error {
  47. cfg, err := setup.ReadConfig()
  48. if err != nil {
  49. panic(err)
  50. }
  51. if sslType == config.SSLTypeAuto || sslType == config.SSLTypeUser {
  52. cfg.SSLType = sslType
  53. } else {
  54. return errors.New("SSL Type Error!")
  55. }
  56. err = setup.WriteConfig(cfg)
  57. if err != nil {
  58. return errors.Wrap(err)
  59. }
  60. return nil
  61. }
  62. func GenSSL(update bool) error {
  63. cfg, err := setup.ReadConfig()
  64. if err != nil {
  65. panic(err)
  66. }
  67. if !update {
  68. privateFile, errpi := os.ReadFile(cfg.SSLPrivateKeyPath)
  69. public, errpu := os.ReadFile(cfg.SSLPublicKeyPath)
  70. // 当前存在证书数据,就不生成了
  71. if errpi == nil && errpu == nil && len(privateFile) > 0 && len(public) > 0 {
  72. return nil
  73. }
  74. }
  75. // Create a user. New accounts need an email and private key to start.
  76. privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  77. if err != nil {
  78. return errors.Wrap(err)
  79. }
  80. myUser := MyUser{
  81. Email: "i@" + cfg.Domain,
  82. key: privateKey,
  83. }
  84. config := lego.NewConfig(&myUser)
  85. config.Certificate.KeyType = certcrypto.RSA2048
  86. // A client facilitates communication with the CA server.
  87. client, err := lego.NewClient(config)
  88. if err != nil {
  89. return errors.Wrap(err)
  90. }
  91. err = client.Challenge.SetHTTP01Provider(GetHttpChallengeInstance())
  92. if err != nil {
  93. return errors.Wrap(err)
  94. }
  95. reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  96. if err != nil {
  97. return errors.Wrap(err)
  98. }
  99. myUser.Registration = reg
  100. request := certificate.ObtainRequest{
  101. Domains: []string{"smtp." + cfg.Domain, cfg.WebDomain, "pop." + cfg.Domain},
  102. Bundle: true,
  103. }
  104. certificates, err := client.Certificate.Obtain(request)
  105. if err != nil {
  106. return errors.Wrap(err)
  107. }
  108. err = os.WriteFile("./config/ssl/private.key", certificates.PrivateKey, 0666)
  109. if err != nil {
  110. return errors.Wrap(err)
  111. }
  112. err = os.WriteFile("./config/ssl/public.crt", certificates.Certificate, 0666)
  113. if err != nil {
  114. return errors.Wrap(err)
  115. }
  116. err = os.WriteFile("./config/ssl/issuerCert.crt", certificates.IssuerCertificate, 0666)
  117. if err != nil {
  118. return errors.Wrap(err)
  119. }
  120. return nil
  121. }
  122. // CheckSSLCrtInfo 返回证书过期剩余天数
  123. func CheckSSLCrtInfo() (int, time.Time, error) {
  124. cfg, err := setup.ReadConfig()
  125. if err != nil {
  126. panic(err)
  127. }
  128. // load cert and key by tls.LoadX509KeyPair
  129. tlsCert, err := tls.LoadX509KeyPair(cfg.SSLPublicKeyPath, cfg.SSLPrivateKeyPath)
  130. if err != nil {
  131. return -1, time.Now(), errors.Wrap(err)
  132. }
  133. cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
  134. if err != nil {
  135. return -1, time.Now(), errors.Wrap(err)
  136. }
  137. // 检查过期时间
  138. hours := cert.NotAfter.Sub(time.Now()).Hours()
  139. if hours <= 0 {
  140. return -1, time.Now(), errors.New("Certificate has expired")
  141. }
  142. return cast.ToInt(hours / 24), cert.NotAfter, nil
  143. }
  144. func Update(needRestart bool) {
  145. if config.Instance != nil && config.Instance.IsInit && config.Instance.SSLType == "0" {
  146. days, _, err := CheckSSLCrtInfo()
  147. if days < 30 || err != nil {
  148. if err != nil {
  149. log.Errorf("SSL Check Error, Update SSL Certificate. Error Info :%+v", err)
  150. } else {
  151. log.Infof("SSL certificate remaining time is only %d days, renew SSL certificate.", days)
  152. }
  153. err = GenSSL(true)
  154. if err != nil {
  155. log.Errorf("SSL Update Error! %+v", err)
  156. }
  157. if needRestart {
  158. // 更新完证书,重启服务
  159. signal.RestartChan <- true
  160. }
  161. } else {
  162. log.Debugf("SSL Check.")
  163. }
  164. }
  165. }