acme.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package acme
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "crypto/x509"
  8. "encoding/json"
  9. "encoding/pem"
  10. "io/ioutil"
  11. "log"
  12. "net/http"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/go-acme/lego/v4/certcrypto"
  19. "github.com/go-acme/lego/v4/certificate"
  20. "github.com/go-acme/lego/v4/challenge/http01"
  21. "github.com/go-acme/lego/v4/lego"
  22. "github.com/go-acme/lego/v4/registration"
  23. "imuslab.com/zoraxy/mod/utils"
  24. )
  25. // ACMEUser represents a user in the ACME system.
  26. type ACMEUser struct {
  27. Email string
  28. Registration *registration.Resource
  29. key crypto.PrivateKey
  30. }
  31. // GetEmail returns the email of the ACMEUser.
  32. func (u *ACMEUser) GetEmail() string {
  33. return u.Email
  34. }
  35. // GetRegistration returns the registration resource of the ACMEUser.
  36. func (u ACMEUser) GetRegistration() *registration.Resource {
  37. return u.Registration
  38. }
  39. // GetPrivateKey returns the private key of the ACMEUser.
  40. func (u *ACMEUser) GetPrivateKey() crypto.PrivateKey {
  41. return u.key
  42. }
  43. // ACMEHandler handles ACME-related operations.
  44. type ACMEHandler struct {
  45. email string
  46. acmeServer string
  47. port string
  48. }
  49. // NewACME creates a new ACMEHandler instance.
  50. func NewACME(email string, acmeServer string, port string) *ACMEHandler {
  51. return &ACMEHandler{
  52. email: email,
  53. acmeServer: acmeServer,
  54. port: port,
  55. }
  56. }
  57. // ObtainCert obtains a certificate for the specified domains.
  58. func (a *ACMEHandler) ObtainCert(domains []string, certificateName string) (bool, error) {
  59. log.Println("Obtaining certificate...")
  60. // generate private key
  61. privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  62. if err != nil {
  63. log.Println(err)
  64. return false, err
  65. }
  66. // create a admin user for our new generation
  67. adminUser := ACMEUser{
  68. Email: a.email,
  69. key: privateKey,
  70. }
  71. // create config
  72. config := lego.NewConfig(&adminUser)
  73. // setup who is the issuer and the key type
  74. config.CADirURL = a.acmeServer
  75. config.Certificate.KeyType = certcrypto.RSA2048
  76. client, err := lego.NewClient(config)
  77. if err != nil {
  78. log.Println(err)
  79. return false, err
  80. }
  81. // setup how to receive challenge
  82. err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", a.port))
  83. if err != nil {
  84. log.Println(err)
  85. return false, err
  86. }
  87. // New users will need to register
  88. reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  89. if err != nil {
  90. log.Println(err)
  91. return false, err
  92. }
  93. adminUser.Registration = reg
  94. // obtain the certificate
  95. request := certificate.ObtainRequest{
  96. Domains: domains,
  97. Bundle: true,
  98. }
  99. certificates, err := client.Certificate.Obtain(request)
  100. if err != nil {
  101. log.Println(err)
  102. return false, err
  103. }
  104. // Each certificate comes back with the cert bytes, the bytes of the client's
  105. // private key, and a certificate URL.
  106. err = ioutil.WriteFile("./certs/"+certificateName+".crt", certificates.Certificate, 0777)
  107. if err != nil {
  108. log.Println(err)
  109. return false, err
  110. }
  111. err = ioutil.WriteFile("./certs/"+certificateName+".key", certificates.PrivateKey, 0777)
  112. if err != nil {
  113. log.Println(err)
  114. return false, err
  115. }
  116. return true, nil
  117. }
  118. // CheckCertificate returns a list of domains that are in expired certificates.
  119. // It will return all domains that is in expired certificates
  120. // *** if there is a vaild certificate contains the domain and there is a expired certificate contains the same domain
  121. // it will said expired as well!
  122. func (a *ACMEHandler) CheckCertificate() []string {
  123. // read from dir
  124. filenames, err := os.ReadDir("./certs/")
  125. expiredCerts := []string{}
  126. if err != nil {
  127. log.Println(err)
  128. return []string{}
  129. }
  130. for _, filename := range filenames {
  131. certFilepath := filepath.Join("./certs/", filename.Name())
  132. certBtyes, err := os.ReadFile(certFilepath)
  133. if err != nil {
  134. // Unable to load this file
  135. continue
  136. } else {
  137. // Cert loaded. Check its expiry time
  138. block, _ := pem.Decode(certBtyes)
  139. if block != nil {
  140. cert, err := x509.ParseCertificate(block.Bytes)
  141. if err == nil {
  142. elapsed := time.Since(cert.NotAfter)
  143. if elapsed > 0 {
  144. // if it is expired then add it in
  145. // make sure it's uniqueless
  146. for _, dnsName := range cert.DNSNames {
  147. if !contains(expiredCerts, dnsName) {
  148. expiredCerts = append(expiredCerts, dnsName)
  149. }
  150. }
  151. if !contains(expiredCerts, cert.Subject.CommonName) {
  152. expiredCerts = append(expiredCerts, cert.Subject.CommonName)
  153. }
  154. }
  155. }
  156. }
  157. }
  158. }
  159. return expiredCerts
  160. }
  161. // return the current port number
  162. func (a *ACMEHandler) Getport() string {
  163. return a.port
  164. }
  165. // contains checks if a string is present in a slice.
  166. func contains(slice []string, str string) bool {
  167. for _, s := range slice {
  168. if s == str {
  169. return true
  170. }
  171. }
  172. return false
  173. }
  174. // HandleGetExpiredDomains handles the HTTP GET request to retrieve the list of expired domains.
  175. // It calls the CheckCertificate method to obtain the expired domains and sends a JSON response
  176. // containing the list of expired domains.
  177. func (a *ACMEHandler) HandleGetExpiredDomains(w http.ResponseWriter, r *http.Request) {
  178. type ExpiredDomains struct {
  179. Domain []string `json:"domain"`
  180. }
  181. info := ExpiredDomains{
  182. Domain: a.CheckCertificate(),
  183. }
  184. js, _ := json.MarshalIndent(info, "", " ")
  185. utils.SendJSONResponse(w, string(js))
  186. }
  187. // HandleRenewCertificate handles the HTTP GET request to renew a certificate for the provided domains.
  188. // It retrieves the domains and filename parameters from the request, calls the ObtainCert method
  189. // to renew the certificate, and sends a JSON response indicating the result of the renewal process.
  190. func (a *ACMEHandler) HandleRenewCertificate(w http.ResponseWriter, r *http.Request) {
  191. domainPara, err := utils.GetPara(r, "domains")
  192. if err != nil {
  193. utils.SendErrorResponse(w, jsonEscape(err.Error()))
  194. return
  195. }
  196. filename, err := utils.GetPara(r, "filename")
  197. if err != nil {
  198. utils.SendErrorResponse(w, jsonEscape(err.Error()))
  199. return
  200. }
  201. domains := strings.Split(domainPara, ",")
  202. result, err := a.ObtainCert(domains, filename)
  203. if err != nil {
  204. utils.SendErrorResponse(w, jsonEscape(err.Error()))
  205. return
  206. }
  207. utils.SendJSONResponse(w, strconv.FormatBool(result))
  208. }
  209. // Escape JSON string
  210. func jsonEscape(i string) string {
  211. b, err := json.Marshal(i)
  212. if err != nil {
  213. panic(err)
  214. }
  215. s := string(b)
  216. return s[1 : len(s)-1]
  217. }