ssl.go 5.2 KB

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