ssl.go 7.6 KB

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