acme.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "math/rand"
  8. "net/http"
  9. "regexp"
  10. "strconv"
  11. "time"
  12. "imuslab.com/zoraxy/mod/acme"
  13. "imuslab.com/zoraxy/mod/dynamicproxy"
  14. "imuslab.com/zoraxy/mod/utils"
  15. )
  16. /*
  17. acme.go
  18. This script handle special routing required for acme auto cert renew functions
  19. */
  20. // Helper function to generate a random port above a specified value
  21. func getRandomPort(minPort int) int {
  22. return rand.Intn(65535-minPort) + minPort
  23. }
  24. // init the new ACME instance
  25. func initACME() *acme.ACMEHandler {
  26. log.Println("Starting ACME handler")
  27. rand.Seed(time.Now().UnixNano())
  28. // Generate a random port above 30000
  29. port := getRandomPort(30000)
  30. // Check if the port is already in use
  31. for acme.IsPortInUse(port) {
  32. port = getRandomPort(30000)
  33. }
  34. return acme.NewACME("https://acme-v02.api.letsencrypt.org/directory", strconv.Itoa(port))
  35. }
  36. // create the special routing rule for ACME
  37. func acmeRegisterSpecialRoutingRule() {
  38. log.Println("Assigned temporary port:" + acmeHandler.Getport())
  39. err := dynamicProxyRouter.AddRoutingRules(&dynamicproxy.RoutingRule{
  40. ID: "acme-autorenew",
  41. MatchRule: func(r *http.Request) bool {
  42. found, _ := regexp.MatchString("/.well-known/acme-challenge/*", r.RequestURI)
  43. return found
  44. },
  45. RoutingHandler: func(w http.ResponseWriter, r *http.Request) {
  46. req, err := http.NewRequest(http.MethodGet, "http://localhost:"+acmeHandler.Getport()+r.RequestURI, nil)
  47. req.Host = r.Host
  48. if err != nil {
  49. fmt.Printf("client: could not create request: %s\n", err)
  50. return
  51. }
  52. res, err := http.DefaultClient.Do(req)
  53. if err != nil {
  54. fmt.Printf("client: error making http request: %s\n", err)
  55. return
  56. }
  57. resBody, err := io.ReadAll(res.Body)
  58. defer res.Body.Close()
  59. if err != nil {
  60. fmt.Printf("error reading: %s\n", err)
  61. return
  62. }
  63. w.Write(resBody)
  64. },
  65. Enabled: true,
  66. UseSystemAccessControl: false,
  67. })
  68. if err != nil {
  69. log.Println("[Err] " + err.Error())
  70. }
  71. }
  72. // This function check if the renew setup is satisfied. If not, toggle them automatically
  73. func AcmeCheckAndHandleRenewCertificate(w http.ResponseWriter, r *http.Request) {
  74. isForceHttpsRedirectEnabledOriginally := false
  75. if dynamicProxyRouter.Option.Port == 443 {
  76. //Enable port 80 to 443 redirect
  77. if !dynamicProxyRouter.Option.ForceHttpsRedirect {
  78. log.Println("Temporary enabling HTTP to HTTPS redirect for ACME certificate renew requests")
  79. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
  80. } else {
  81. //Set this to true, so after renew, do not turn it off
  82. isForceHttpsRedirectEnabledOriginally = true
  83. }
  84. } else if dynamicProxyRouter.Option.Port == 80 {
  85. //Go ahead
  86. } else {
  87. //This port do not support ACME
  88. utils.SendErrorResponse(w, "ACME renew only support web server listening on port 80 (http) or 443 (https)")
  89. }
  90. // Pass over to the acmeHandler to deal with the communication
  91. acmeHandler.HandleRenewCertificate(w, r)
  92. if dynamicProxyRouter.Option.Port == 443 {
  93. if !isForceHttpsRedirectEnabledOriginally {
  94. //Default is off. Turn the redirection off
  95. log.Println("Restoring HTTP to HTTPS redirect settings")
  96. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
  97. }
  98. }
  99. }
  100. // HandleACMEPreferredCA return the user preferred / default CA for new subdomain auto creation
  101. func HandleACMEPreferredCA(w http.ResponseWriter, r *http.Request) {
  102. ca, err := utils.PostPara(r, "set")
  103. if err != nil {
  104. //Return the current ca to user
  105. prefCA := "Let's Encrypt"
  106. sysdb.Read("acmepref", "prefca", &prefCA)
  107. js, _ := json.Marshal(prefCA)
  108. utils.SendJSONResponse(w, string(js))
  109. } else {
  110. //Check if the CA is supported
  111. acme.IsSupportedCA(ca)
  112. //Set the new config
  113. sysdb.Write("acmepref", "prefca", ca)
  114. log.Println("Updating prefered ACME CA to " + ca)
  115. utils.SendOK(w)
  116. }
  117. }