ssl.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package ssl
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "github.com/go-acme/lego/v4/certificate"
  8. "github.com/go-acme/lego/v4/challenge/dns01"
  9. log "github.com/sirupsen/logrus"
  10. "github.com/spf13/cast"
  11. "os"
  12. "pmail/config"
  13. "pmail/services/setup"
  14. "pmail/signal"
  15. "pmail/utils/async"
  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.SSLTypeAutoHTTP
  43. }
  44. return cfg.SSLType
  45. }
  46. func SetSSL(sslType, priKey, crtKey string) error {
  47. cfg, err := setup.ReadConfig()
  48. if err != nil {
  49. panic(err)
  50. }
  51. if sslType == config.SSLTypeAutoHTTP || sslType == config.SSLTypeUser || sslType == config.SSLTypeAutoDNS {
  52. cfg.SSLType = sslType
  53. } else {
  54. return errors.New("SSL Type Error!")
  55. }
  56. if cfg.SSLType == config.SSLTypeUser {
  57. cfg.SSLPrivateKeyPath = priKey
  58. cfg.SSLPublicKeyPath = crtKey
  59. // 手动设置证书的情况下后台地址默认不启用https
  60. cfg.HttpsEnabled = 2
  61. }
  62. err = setup.WriteConfig(cfg)
  63. if err != nil {
  64. return errors.Wrap(err)
  65. }
  66. return nil
  67. }
  68. func renewCertificate(privateKey *ecdsa.PrivateKey, cfg *config.Config) error {
  69. myUser := MyUser{
  70. Email: "i@" + cfg.Domain,
  71. key: privateKey,
  72. }
  73. conf := lego.NewConfig(&myUser)
  74. conf.UserAgent = "PMail"
  75. conf.Certificate.KeyType = certcrypto.RSA2048
  76. // A client facilitates communication with the CA server.
  77. client, err := lego.NewClient(conf)
  78. if err != nil {
  79. return errors.Wrap(err)
  80. }
  81. var reg *registration.Resource
  82. reg, err = client.Registration.ResolveAccountByKey()
  83. if err != nil {
  84. return errors.Wrap(err)
  85. }
  86. myUser.Registration = reg
  87. request := certificate.ObtainRequest{
  88. Domains: []string{"smtp." + cfg.Domain, cfg.WebDomain, "pop." + cfg.Domain},
  89. Bundle: true,
  90. }
  91. log.Infof("wait ssl renew")
  92. certificates, err := client.Certificate.Obtain(request)
  93. if err != nil {
  94. panic(err)
  95. }
  96. err = os.WriteFile("./config/ssl/private.key", certificates.PrivateKey, 0666)
  97. if err != nil {
  98. panic(err)
  99. }
  100. err = os.WriteFile("./config/ssl/public.crt", certificates.Certificate, 0666)
  101. if err != nil {
  102. panic(err)
  103. }
  104. err = os.WriteFile("./config/ssl/issuerCert.crt", certificates.IssuerCertificate, 0666)
  105. if err != nil {
  106. panic(err)
  107. }
  108. return nil
  109. }
  110. func generateCertificate(privateKey *ecdsa.PrivateKey, cfg *config.Config, newAccount bool) error {
  111. myUser := MyUser{
  112. Email: "i@" + cfg.Domain,
  113. key: privateKey,
  114. }
  115. conf := lego.NewConfig(&myUser)
  116. conf.UserAgent = "PMail"
  117. conf.Certificate.KeyType = certcrypto.RSA2048
  118. // A client facilitates communication with the CA server.
  119. client, err := lego.NewClient(conf)
  120. if err != nil {
  121. return errors.Wrap(err)
  122. }
  123. if cfg.SSLType == config.SSLTypeAutoHTTP {
  124. err = client.Challenge.SetHTTP01Provider(GetHttpChallengeInstance())
  125. if err != nil {
  126. return errors.Wrap(err)
  127. }
  128. } else if cfg.SSLType == config.SSLTypeAutoDNS {
  129. err = client.Challenge.SetDNS01Provider(GetDnsChallengeInstance(), dns01.AddDNSTimeout(60*time.Minute))
  130. if err != nil {
  131. return errors.Wrap(err)
  132. }
  133. }
  134. var reg *registration.Resource
  135. if newAccount {
  136. reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  137. if err != nil {
  138. return errors.Wrap(err)
  139. }
  140. } else {
  141. reg, err = client.Registration.ResolveAccountByKey()
  142. if err != nil {
  143. return errors.Wrap(err)
  144. }
  145. }
  146. myUser.Registration = reg
  147. request := certificate.ObtainRequest{
  148. Domains: []string{"smtp." + cfg.Domain, cfg.WebDomain, "pop." + cfg.Domain},
  149. Bundle: true,
  150. }
  151. as := async.New(nil)
  152. as.Process(func(params any) {
  153. log.Infof("wait ssl")
  154. certificates, err := client.Certificate.Obtain(request)
  155. if err != nil {
  156. panic(err)
  157. }
  158. log.Infof("证书校验通过!")
  159. err = os.WriteFile("./config/ssl/private.key", certificates.PrivateKey, 0666)
  160. if err != nil {
  161. panic(err)
  162. }
  163. err = os.WriteFile("./config/ssl/public.crt", certificates.Certificate, 0666)
  164. if err != nil {
  165. panic(err)
  166. }
  167. err = os.WriteFile("./config/ssl/issuerCert.crt", certificates.IssuerCertificate, 0666)
  168. if err != nil {
  169. panic(err)
  170. }
  171. setup.Finish()
  172. }, nil)
  173. return nil
  174. }
  175. func GenSSL(update bool) error {
  176. cfg, err := setup.ReadConfig()
  177. if err != nil {
  178. panic(err)
  179. }
  180. if !update {
  181. privateFile, errpi := os.ReadFile(cfg.SSLPrivateKeyPath)
  182. public, errpu := os.ReadFile(cfg.SSLPublicKeyPath)
  183. // 当前存在证书数据,就不生成了
  184. if errpi == nil && errpu == nil && len(privateFile) > 0 && len(public) > 0 {
  185. return nil
  186. }
  187. }
  188. privateKey, newAccount := config.ReadPrivateKey()
  189. if !update {
  190. return generateCertificate(privateKey, cfg, newAccount)
  191. }
  192. return renewCertificate(privateKey, cfg)
  193. }
  194. // CheckSSLCrtInfo 返回证书过期剩余天数
  195. func CheckSSLCrtInfo() (int, time.Time, error) {
  196. cfg, err := setup.ReadConfig()
  197. if err != nil {
  198. panic(err)
  199. }
  200. // load cert and key by tls.LoadX509KeyPair
  201. tlsCert, err := tls.LoadX509KeyPair(cfg.SSLPublicKeyPath, cfg.SSLPrivateKeyPath)
  202. if err != nil {
  203. return -1, time.Now(), errors.Wrap(err)
  204. }
  205. cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
  206. if err != nil {
  207. return -1, time.Now(), errors.Wrap(err)
  208. }
  209. // 检查过期时间
  210. hours := cert.NotAfter.Sub(time.Now()).Hours()
  211. if hours <= 0 {
  212. return -1, time.Now(), errors.New("Certificate has expired")
  213. }
  214. return cast.ToInt(hours / 24), cert.NotAfter, nil
  215. }
  216. func Update(needRestart bool) {
  217. if config.Instance != nil && config.Instance.IsInit && (config.Instance.SSLType == config.SSLTypeAutoHTTP || config.Instance.SSLType == config.SSLTypeAutoDNS) {
  218. days, _, err := CheckSSLCrtInfo()
  219. if days < 30 || err != nil {
  220. if err != nil {
  221. log.Errorf("SSL Check Error, Update SSL Certificate. Error Info :%+v", err)
  222. } else {
  223. log.Infof("SSL certificate remaining time is only %d days, renew SSL certificate.", days)
  224. }
  225. err = GenSSL(true)
  226. if err != nil {
  227. log.Errorf("SSL Update Error! %+v", err)
  228. }
  229. if needRestart {
  230. // 更新完证书,重启服务
  231. signal.RestartChan <- true
  232. }
  233. } else {
  234. log.Debugf("SSL Check.")
  235. }
  236. }
  237. }