ssl.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. domains := []string{cfg.WebDomain}
  88. for _, domain := range cfg.Domains {
  89. domains = append(domains, "smtp."+domain)
  90. domains = append(domains, "pop."+domain)
  91. }
  92. request := certificate.ObtainRequest{
  93. Domains: domains,
  94. Bundle: true,
  95. }
  96. log.Infof("wait ssl renew")
  97. certificates, err := client.Certificate.Obtain(request)
  98. if err != nil {
  99. panic(err)
  100. }
  101. err = os.WriteFile("./config/ssl/private.key", certificates.PrivateKey, 0666)
  102. if err != nil {
  103. panic(err)
  104. }
  105. err = os.WriteFile("./config/ssl/public.crt", certificates.Certificate, 0666)
  106. if err != nil {
  107. panic(err)
  108. }
  109. err = os.WriteFile("./config/ssl/issuerCert.crt", certificates.IssuerCertificate, 0666)
  110. if err != nil {
  111. panic(err)
  112. }
  113. return nil
  114. }
  115. func generateCertificate(privateKey *ecdsa.PrivateKey, cfg *config.Config, newAccount bool) error {
  116. myUser := MyUser{
  117. Email: "i@" + cfg.Domain,
  118. key: privateKey,
  119. }
  120. conf := lego.NewConfig(&myUser)
  121. conf.UserAgent = "PMail"
  122. conf.Certificate.KeyType = certcrypto.RSA2048
  123. // A client facilitates communication with the CA server.
  124. client, err := lego.NewClient(conf)
  125. if err != nil {
  126. return errors.Wrap(err)
  127. }
  128. if cfg.SSLType == config.SSLTypeAutoHTTP {
  129. err = client.Challenge.SetHTTP01Provider(GetHttpChallengeInstance())
  130. if err != nil {
  131. return errors.Wrap(err)
  132. }
  133. } else if cfg.SSLType == config.SSLTypeAutoDNS {
  134. err = client.Challenge.SetDNS01Provider(GetDnsChallengeInstance(), dns01.AddDNSTimeout(60*time.Minute))
  135. if err != nil {
  136. return errors.Wrap(err)
  137. }
  138. }
  139. var reg *registration.Resource
  140. if newAccount {
  141. reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  142. if err != nil {
  143. return errors.Wrap(err)
  144. }
  145. } else {
  146. reg, err = client.Registration.ResolveAccountByKey()
  147. if err != nil {
  148. return errors.Wrap(err)
  149. }
  150. }
  151. myUser.Registration = reg
  152. domains := []string{cfg.WebDomain}
  153. for _, domain := range cfg.Domains {
  154. domains = append(domains, "smtp."+domain)
  155. domains = append(domains, "pop."+domain)
  156. }
  157. request := certificate.ObtainRequest{
  158. Domains: domains,
  159. Bundle: true,
  160. }
  161. as := async.New(nil)
  162. as.Process(func(params any) {
  163. log.Infof("wait ssl")
  164. certificates, err := client.Certificate.Obtain(request)
  165. if err != nil {
  166. panic(err)
  167. }
  168. log.Infof("证书校验通过!")
  169. err = os.WriteFile("./config/ssl/private.key", certificates.PrivateKey, 0666)
  170. if err != nil {
  171. panic(err)
  172. }
  173. err = os.WriteFile("./config/ssl/public.crt", certificates.Certificate, 0666)
  174. if err != nil {
  175. panic(err)
  176. }
  177. err = os.WriteFile("./config/ssl/issuerCert.crt", certificates.IssuerCertificate, 0666)
  178. if err != nil {
  179. panic(err)
  180. }
  181. setup.Finish()
  182. }, nil)
  183. return nil
  184. }
  185. func GenSSL(update bool) error {
  186. cfg, err := setup.ReadConfig()
  187. if err != nil {
  188. panic(err)
  189. }
  190. if !update {
  191. privateFile, errpi := os.ReadFile(cfg.SSLPrivateKeyPath)
  192. public, errpu := os.ReadFile(cfg.SSLPublicKeyPath)
  193. // 当前存在证书数据,就不生成了
  194. if errpi == nil && errpu == nil && len(privateFile) > 0 && len(public) > 0 {
  195. return nil
  196. }
  197. }
  198. privateKey, newAccount := config.ReadPrivateKey()
  199. if !update {
  200. return generateCertificate(privateKey, cfg, newAccount)
  201. }
  202. return renewCertificate(privateKey, cfg)
  203. }
  204. // CheckSSLCrtInfo 返回证书过期剩余天数
  205. func CheckSSLCrtInfo() (int, time.Time, error) {
  206. cfg, err := setup.ReadConfig()
  207. if err != nil {
  208. panic(err)
  209. }
  210. // load cert and key by tls.LoadX509KeyPair
  211. tlsCert, err := tls.LoadX509KeyPair(cfg.SSLPublicKeyPath, cfg.SSLPrivateKeyPath)
  212. if err != nil {
  213. return -1, time.Now(), errors.Wrap(err)
  214. }
  215. cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
  216. if err != nil {
  217. return -1, time.Now(), errors.Wrap(err)
  218. }
  219. // 检查过期时间
  220. hours := cert.NotAfter.Sub(time.Now()).Hours()
  221. if hours <= 0 {
  222. return -1, time.Now(), errors.New("Certificate has expired")
  223. }
  224. return cast.ToInt(hours / 24), cert.NotAfter, nil
  225. }
  226. func Update(needRestart bool) {
  227. if config.Instance != nil && config.Instance.IsInit && (config.Instance.SSLType == config.SSLTypeAutoHTTP || config.Instance.SSLType == config.SSLTypeAutoDNS) {
  228. days, _, err := CheckSSLCrtInfo()
  229. if days < 30 || err != nil {
  230. if err != nil {
  231. log.Errorf("SSL Check Error, Update SSL Certificate. Error Info :%+v", err)
  232. } else {
  233. log.Infof("SSL certificate remaining time is only %d days, renew SSL certificate.", days)
  234. }
  235. err = GenSSL(true)
  236. if err != nil {
  237. log.Errorf("SSL Update Error! %+v", err)
  238. }
  239. if needRestart {
  240. // 更新完证书,重启服务
  241. signal.RestartChan <- true
  242. }
  243. } else {
  244. log.Debugf("SSL Check.")
  245. }
  246. }
  247. }