acme.go 5.2 KB

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