cert.go 5.9 KB

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