acme.go 9.8 KB

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