ssl.go 7.3 KB

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