cert.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package cert
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "crypto/tls"
  8. dns2 "github.com/0xJacky/Nginx-UI/server/pkg/cert/dns"
  9. "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
  10. "github.com/0xJacky/Nginx-UI/server/query"
  11. "github.com/0xJacky/Nginx-UI/server/settings"
  12. "github.com/go-acme/lego/v4/certcrypto"
  13. "github.com/go-acme/lego/v4/certificate"
  14. "github.com/go-acme/lego/v4/challenge/http01"
  15. "github.com/go-acme/lego/v4/lego"
  16. "github.com/go-acme/lego/v4/providers/dns"
  17. "github.com/go-acme/lego/v4/registration"
  18. "github.com/pkg/errors"
  19. "log"
  20. "net/http"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. )
  25. const (
  26. HTTP01 = "http01"
  27. DNS01 = "dns01"
  28. )
  29. // MyUser You'll need a user or account type that implements acme.User
  30. type MyUser struct {
  31. Email string
  32. Registration *registration.Resource
  33. Key crypto.PrivateKey
  34. }
  35. func (u *MyUser) GetEmail() string {
  36. return u.Email
  37. }
  38. func (u *MyUser) GetRegistration() *registration.Resource {
  39. return u.Registration
  40. }
  41. func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
  42. return u.Key
  43. }
  44. type ConfigPayload struct {
  45. ServerName []string `json:"server_name"`
  46. ChallengeMethod string `json:"challenge_method"`
  47. DNSCredentialID int `json:"dns_credential_id"`
  48. }
  49. func IssueCert(payload *ConfigPayload, logChan chan string, errChan chan error) {
  50. defer func() {
  51. if err := recover(); err != nil {
  52. log.Println("Issue Cert recover", err)
  53. }
  54. }()
  55. domain := payload.ServerName
  56. // Create a user. New accounts need an email and private key to start.
  57. logChan <- "Generating private key for registering account"
  58. privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  59. if err != nil {
  60. errChan <- errors.Wrap(err, "issue cert generate key error")
  61. return
  62. }
  63. logChan <- "Preparing lego configurations"
  64. myUser := MyUser{
  65. Email: settings.ServerSettings.Email,
  66. Key: privateKey,
  67. }
  68. config := lego.NewConfig(&myUser)
  69. if settings.ServerSettings.Demo {
  70. config.CADirURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
  71. }
  72. if settings.ServerSettings.CADir != "" {
  73. config.CADirURL = settings.ServerSettings.CADir
  74. if config.HTTPClient != nil {
  75. config.HTTPClient.Transport = &http.Transport{
  76. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  77. }
  78. }
  79. }
  80. config.Certificate.KeyType = certcrypto.RSA2048
  81. logChan <- "Creating client facilitates communication with the CA server"
  82. // A client facilitates communication with the CA server.
  83. client, err := lego.NewClient(config)
  84. if err != nil {
  85. errChan <- errors.Wrap(err, "issue cert new client error")
  86. return
  87. }
  88. switch payload.ChallengeMethod {
  89. case HTTP01:
  90. logChan <- "Using HTTP01 challenge provider"
  91. err = client.Challenge.SetHTTP01Provider(
  92. http01.NewProviderServer("",
  93. settings.ServerSettings.HTTPChallengePort,
  94. ),
  95. )
  96. case DNS01:
  97. d := query.DnsCredential
  98. dnsCredential, err := d.FirstByID(payload.DNSCredentialID)
  99. if err != nil {
  100. errChan <- errors.Wrap(err, "get dns credential error")
  101. return
  102. }
  103. logChan <- "Using DNS01 challenge provider"
  104. code := dnsCredential.Config.Code
  105. pConfig, ok := dns2.GetProvider(code)
  106. if !ok {
  107. errChan <- errors.Wrap(err, "provider not found")
  108. }
  109. logChan <- "Setting environment variables"
  110. if dnsCredential.Config.Configuration != nil {
  111. err = pConfig.SetEnv(*dnsCredential.Config.Configuration)
  112. if err != nil {
  113. break
  114. }
  115. defer func() {
  116. logChan <- "Cleaning environment variables"
  117. pConfig.CleanEnv()
  118. }()
  119. provider, err := dns.NewDNSChallengeProviderByName(code)
  120. if err != nil {
  121. break
  122. }
  123. err = client.Challenge.SetDNS01Provider(provider)
  124. } else {
  125. errChan <- errors.Wrap(err, "environment configuration is empty")
  126. return
  127. }
  128. }
  129. if err != nil {
  130. errChan <- errors.Wrap(err, "fail to challenge")
  131. return
  132. }
  133. // New users will need to register
  134. logChan <- "Registering user"
  135. reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  136. if err != nil {
  137. errChan <- errors.Wrap(err, "fail to register")
  138. return
  139. }
  140. myUser.Registration = reg
  141. request := certificate.ObtainRequest{
  142. Domains: domain,
  143. Bundle: true,
  144. }
  145. logChan <- "Obtaining certificate"
  146. certificates, err := client.Certificate.Obtain(request)
  147. if err != nil {
  148. errChan <- errors.Wrap(err, "fail to obtain")
  149. return
  150. }
  151. name := strings.Join(domain, "_")
  152. saveDir := nginx.GetConfPath("ssl/" + name)
  153. if _, err = os.Stat(saveDir); os.IsNotExist(err) {
  154. err = os.MkdirAll(saveDir, 0755)
  155. if err != nil {
  156. errChan <- errors.Wrap(err, "fail to mkdir")
  157. return
  158. }
  159. }
  160. // Each certificate comes back with the cert bytes, the bytes of the client's
  161. // private key, and a certificate URL. SAVE THESE TO DISK.
  162. logChan <- "Writing certificate to disk"
  163. err = os.WriteFile(filepath.Join(saveDir, "fullchain.cer"),
  164. certificates.Certificate, 0644)
  165. if err != nil {
  166. errChan <- errors.Wrap(err, "error issue cert write fullchain.cer")
  167. return
  168. }
  169. logChan <- "Writing certificate private key to disk"
  170. err = os.WriteFile(filepath.Join(saveDir, "private.key"),
  171. certificates.PrivateKey, 0644)
  172. if err != nil {
  173. errChan <- errors.Wrap(err, "fail to write key")
  174. return
  175. }
  176. close(errChan)
  177. logChan <- "Reloading nginx"
  178. nginx.Reload()
  179. logChan <- "Finished"
  180. close(logChan)
  181. }