acme.go 6.6 KB

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