acme.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "math/rand"
  7. "net/http"
  8. "regexp"
  9. "strconv"
  10. "time"
  11. "imuslab.com/zoraxy/mod/acme"
  12. "imuslab.com/zoraxy/mod/dynamicproxy"
  13. "imuslab.com/zoraxy/mod/utils"
  14. )
  15. /*
  16. acme.go
  17. This script handle special routing required for acme auto cert renew functions
  18. */
  19. // Helper function to generate a random port above a specified value
  20. func getRandomPort(minPort int) int {
  21. return rand.Intn(65535-minPort) + minPort
  22. }
  23. // init the new ACME instance
  24. func initACME() *acme.ACMEHandler {
  25. SystemWideLogger.Println("Starting ACME handler")
  26. rand.Seed(time.Now().UnixNano())
  27. // Generate a random port above 30000
  28. port := getRandomPort(30000)
  29. // Check if the port is already in use
  30. for acme.IsPortInUse(port) {
  31. port = getRandomPort(30000)
  32. }
  33. return acme.NewACME("https://acme-staging-v02.api.letsencrypt.org/directory", strconv.Itoa(port), sysdb, SystemWideLogger)
  34. //return acme.NewACME("https://acme-v02.api.letsencrypt.org/directory", strconv.Itoa(port), sysdb, SystemWideLogger)
  35. }
  36. // Restart ACME handler and auto renewer
  37. func restartACMEHandler() {
  38. SystemWideLogger.Println("Restarting ACME handler")
  39. //Clos the current handler and auto renewer
  40. acmeHandler.Close()
  41. acmeAutoRenewer.Close()
  42. acmeDeregisterSpecialRoutingRule()
  43. //Reinit the handler with a new random port
  44. acmeHandler = initACME()
  45. acmeRegisterSpecialRoutingRule()
  46. }
  47. // create the special routing rule for ACME
  48. func acmeRegisterSpecialRoutingRule() {
  49. SystemWideLogger.Println("Assigned temporary port:" + acmeHandler.Getport())
  50. err := dynamicProxyRouter.AddRoutingRules(&dynamicproxy.RoutingRule{
  51. ID: "acme-autorenew",
  52. MatchRule: func(r *http.Request) bool {
  53. found, _ := regexp.MatchString("/.well-known/acme-challenge/*", r.RequestURI)
  54. return found
  55. },
  56. RoutingHandler: func(w http.ResponseWriter, r *http.Request) {
  57. req, err := http.NewRequest(http.MethodGet, "http://localhost:"+acmeHandler.Getport()+r.RequestURI, nil)
  58. req.Host = r.Host
  59. if err != nil {
  60. fmt.Printf("client: could not create request: %s\n", err)
  61. return
  62. }
  63. res, err := http.DefaultClient.Do(req)
  64. if err != nil {
  65. fmt.Printf("client: error making http request: %s\n", err)
  66. return
  67. }
  68. resBody, err := io.ReadAll(res.Body)
  69. defer res.Body.Close()
  70. if err != nil {
  71. fmt.Printf("error reading: %s\n", err)
  72. return
  73. }
  74. w.Write(resBody)
  75. },
  76. Enabled: true,
  77. UseSystemAccessControl: false,
  78. })
  79. if err != nil {
  80. SystemWideLogger.PrintAndLog("ACME", "Unable register temp port for DNS resolver", err)
  81. }
  82. }
  83. // remove the special routing rule for ACME
  84. func acmeDeregisterSpecialRoutingRule() {
  85. SystemWideLogger.Println("Removing ACME routing rule")
  86. dynamicProxyRouter.RemoveRoutingRule("acme-autorenew")
  87. }
  88. // This function check if the renew setup is satisfied. If not, toggle them automatically
  89. func AcmeCheckAndHandleRenewCertificate(w http.ResponseWriter, r *http.Request) {
  90. isForceHttpsRedirectEnabledOriginally := false
  91. requireRestorePort80 := false
  92. dnsPara, _ := utils.PostBool(r, "dns")
  93. if !dnsPara {
  94. if dynamicProxyRouter.Option.Port == 443 {
  95. //Check if port 80 is enabled
  96. if !dynamicProxyRouter.Option.ListenOnPort80 {
  97. //Enable port 80 temporarily
  98. SystemWideLogger.PrintAndLog("ACME", "Temporarily enabling port 80 listener to handle ACME request ", nil)
  99. dynamicProxyRouter.UpdatePort80ListenerState(true)
  100. requireRestorePort80 = true
  101. time.Sleep(2 * time.Second)
  102. }
  103. //Enable port 80 to 443 redirect
  104. if !dynamicProxyRouter.Option.ForceHttpsRedirect {
  105. SystemWideLogger.Println("Temporary enabling HTTP to HTTPS redirect for ACME certificate renew requests")
  106. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
  107. } else {
  108. //Set this to true, so after renew, do not turn it off
  109. isForceHttpsRedirectEnabledOriginally = true
  110. }
  111. } else if dynamicProxyRouter.Option.Port == 80 {
  112. //Go ahead
  113. } else {
  114. //This port do not support ACME
  115. utils.SendErrorResponse(w, "ACME renew only support web server listening on port 80 (http) or 443 (https)")
  116. return
  117. }
  118. }
  119. //Add a 2 second delay to make sure everything is settle down
  120. time.Sleep(2 * time.Second)
  121. // Pass over to the acmeHandler to deal with the communication
  122. acmeHandler.HandleRenewCertificate(w, r)
  123. //Update the TLS cert store buffer
  124. tlsCertManager.UpdateLoadedCertList()
  125. //Restore original settings
  126. if requireRestorePort80 {
  127. //Restore port 80 listener
  128. SystemWideLogger.PrintAndLog("ACME", "Restoring previous port 80 listener settings", nil)
  129. dynamicProxyRouter.UpdatePort80ListenerState(false)
  130. }
  131. if !isForceHttpsRedirectEnabledOriginally {
  132. //Default is off. Turn the redirection off
  133. SystemWideLogger.PrintAndLog("ACME", "Restoring HTTP to HTTPS redirect settings", nil)
  134. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
  135. }
  136. }
  137. // HandleACMEPreferredCA return the user preferred / default CA for new subdomain auto creation
  138. func HandleACMEPreferredCA(w http.ResponseWriter, r *http.Request) {
  139. ca, err := utils.PostPara(r, "set")
  140. if err != nil {
  141. //Return the current ca to user
  142. prefCA := "Let's Encrypt"
  143. sysdb.Read("acmepref", "prefca", &prefCA)
  144. js, _ := json.Marshal(prefCA)
  145. utils.SendJSONResponse(w, string(js))
  146. } else {
  147. //Check if the CA is supported
  148. acme.IsSupportedCA(ca)
  149. //Set the new config
  150. sysdb.Write("acmepref", "prefca", ca)
  151. SystemWideLogger.Println("Updating prefered ACME CA to " + ca)
  152. utils.SendOK(w)
  153. }
  154. }