acme.go 9.6 KB

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