ssl.go 5.2 KB

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