acme.go 8.8 KB

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