acme.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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, ca 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. //Overwrite the CADir URL if set
  78. if ca != "" {
  79. caLinkOverwrite, err := loadCAApiServerFromName(ca)
  80. if err == nil {
  81. config.CADirURL = caLinkOverwrite
  82. log.Println("[INFO] Using " + caLinkOverwrite + " for CA Directory URL")
  83. }
  84. }
  85. config.Certificate.KeyType = certcrypto.RSA2048
  86. client, err := lego.NewClient(config)
  87. if err != nil {
  88. log.Println(err)
  89. return false, err
  90. }
  91. // setup how to receive challenge
  92. err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", a.port))
  93. if err != nil {
  94. log.Println(err)
  95. return false, err
  96. }
  97. // New users will need to register
  98. reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  99. if err != nil {
  100. log.Println(err)
  101. return false, err
  102. }
  103. adminUser.Registration = reg
  104. // obtain the certificate
  105. request := certificate.ObtainRequest{
  106. Domains: domains,
  107. Bundle: true,
  108. }
  109. certificates, err := client.Certificate.Obtain(request)
  110. if err != nil {
  111. log.Println(err)
  112. return false, err
  113. }
  114. // Each certificate comes back with the cert bytes, the bytes of the client's
  115. // private key, and a certificate URL.
  116. err = ioutil.WriteFile("./certs/"+certificateName+".crt", certificates.Certificate, 0777)
  117. if err != nil {
  118. log.Println(err)
  119. return false, err
  120. }
  121. err = ioutil.WriteFile("./certs/"+certificateName+".key", certificates.PrivateKey, 0777)
  122. if err != nil {
  123. log.Println(err)
  124. return false, err
  125. }
  126. return true, nil
  127. }
  128. // CheckCertificate returns a list of domains that are in expired certificates.
  129. // It will return all domains that is in expired certificates
  130. // *** if there is a vaild certificate contains the domain and there is a expired certificate contains the same domain
  131. // it will said expired as well!
  132. func (a *ACMEHandler) CheckCertificate() []string {
  133. // read from dir
  134. filenames, err := os.ReadDir("./certs/")
  135. expiredCerts := []string{}
  136. if err != nil {
  137. log.Println(err)
  138. return []string{}
  139. }
  140. for _, filename := range filenames {
  141. certFilepath := filepath.Join("./certs/", filename.Name())
  142. certBtyes, err := os.ReadFile(certFilepath)
  143. if err != nil {
  144. // Unable to load this file
  145. continue
  146. } else {
  147. // Cert loaded. Check its expiry time
  148. block, _ := pem.Decode(certBtyes)
  149. if block != nil {
  150. cert, err := x509.ParseCertificate(block.Bytes)
  151. if err == nil {
  152. elapsed := time.Since(cert.NotAfter)
  153. if elapsed > 0 {
  154. // if it is expired then add it in
  155. // make sure it's uniqueless
  156. for _, dnsName := range cert.DNSNames {
  157. if !contains(expiredCerts, dnsName) {
  158. expiredCerts = append(expiredCerts, dnsName)
  159. }
  160. }
  161. if !contains(expiredCerts, cert.Subject.CommonName) {
  162. expiredCerts = append(expiredCerts, cert.Subject.CommonName)
  163. }
  164. }
  165. }
  166. }
  167. }
  168. }
  169. return expiredCerts
  170. }
  171. // return the current port number
  172. func (a *ACMEHandler) Getport() string {
  173. return a.port
  174. }
  175. // contains checks if a string is present in a slice.
  176. func contains(slice []string, str string) bool {
  177. for _, s := range slice {
  178. if s == str {
  179. return true
  180. }
  181. }
  182. return false
  183. }
  184. // HandleGetExpiredDomains handles the HTTP GET request to retrieve the list of expired domains.
  185. // It calls the CheckCertificate method to obtain the expired domains and sends a JSON response
  186. // containing the list of expired domains.
  187. func (a *ACMEHandler) HandleGetExpiredDomains(w http.ResponseWriter, r *http.Request) {
  188. type ExpiredDomains struct {
  189. Domain []string `json:"domain"`
  190. }
  191. info := ExpiredDomains{
  192. Domain: a.CheckCertificate(),
  193. }
  194. js, _ := json.MarshalIndent(info, "", " ")
  195. utils.SendJSONResponse(w, string(js))
  196. }
  197. // HandleRenewCertificate handles the HTTP GET request to renew a certificate for the provided domains.
  198. // It retrieves the domains and filename parameters from the request, calls the ObtainCert method
  199. // to renew the certificate, and sends a JSON response indicating the result of the renewal process.
  200. func (a *ACMEHandler) HandleRenewCertificate(w http.ResponseWriter, r *http.Request) {
  201. domainPara, err := utils.PostPara(r, "domains")
  202. if err != nil {
  203. utils.SendErrorResponse(w, jsonEscape(err.Error()))
  204. return
  205. }
  206. filename, err := utils.PostPara(r, "filename")
  207. if err != nil {
  208. utils.SendErrorResponse(w, jsonEscape(err.Error()))
  209. return
  210. }
  211. ca, err := utils.PostPara(r, "ca")
  212. if err != nil {
  213. log.Println("CA not set. Using default (Let's Encrypt)")
  214. ca = "Let's Encrypt"
  215. }
  216. domains := strings.Split(domainPara, ",")
  217. result, err := a.ObtainCert(domains, filename, ca)
  218. if err != nil {
  219. utils.SendErrorResponse(w, jsonEscape(err.Error()))
  220. return
  221. }
  222. utils.SendJSONResponse(w, strconv.FormatBool(result))
  223. }
  224. // Escape JSON string
  225. func jsonEscape(i string) string {
  226. b, err := json.Marshal(i)
  227. if err != nil {
  228. log.Println("Unable to escape json data: " + err.Error())
  229. return i
  230. }
  231. s := string(b)
  232. return s[1 : len(s)-1]
  233. }
  234. // Helper function to check if a port is in use
  235. func IsPortInUse(port int) bool {
  236. address := fmt.Sprintf(":%d", port)
  237. listener, err := net.Listen("tcp", address)
  238. if err != nil {
  239. return true // Port is in use
  240. }
  241. defer listener.Close()
  242. return false // Port is not in use
  243. }