acme.go 7.3 KB

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