cert.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package main
  2. import (
  3. "crypto/x509"
  4. "encoding/json"
  5. "encoding/pem"
  6. "fmt"
  7. "io"
  8. "log"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "imuslab.com/zoraxy/mod/utils"
  13. )
  14. // Check if the default certificates is correctly setup
  15. func handleDefaultCertCheck(w http.ResponseWriter, r *http.Request) {
  16. type CheckResult struct {
  17. DefaultPubExists bool
  18. DefaultPriExists bool
  19. }
  20. pub, pri := tlsCertManager.DefaultCertExistsSep()
  21. js, _ := json.Marshal(CheckResult{
  22. pub,
  23. pri,
  24. })
  25. utils.SendJSONResponse(w, string(js))
  26. }
  27. // Return a list of domains where the certificates covers
  28. func handleListCertificate(w http.ResponseWriter, r *http.Request) {
  29. filenames, err := tlsCertManager.ListCertDomains()
  30. if err != nil {
  31. http.Error(w, err.Error(), http.StatusInternalServerError)
  32. return
  33. }
  34. showDate, _ := utils.GetPara(r, "date")
  35. if showDate == "true" {
  36. type CertInfo struct {
  37. Domain string
  38. LastModifiedDate string
  39. ExpireDate string
  40. }
  41. results := []*CertInfo{}
  42. for _, filename := range filenames {
  43. certFilepath := filepath.Join(tlsCertManager.CertStore, filename+".crt")
  44. //keyFilepath := filepath.Join(tlsCertManager.CertStore, filename+".key")
  45. fileInfo, err := os.Stat(certFilepath)
  46. if err != nil {
  47. utils.SendErrorResponse(w, "invalid domain certificate discovered: "+filename)
  48. return
  49. }
  50. modifiedTime := fileInfo.ModTime().Format("2006-01-02 15:04:05")
  51. certExpireTime := "Unknown"
  52. certBtyes, err := os.ReadFile(certFilepath)
  53. if err != nil {
  54. //Unable to load this file
  55. continue
  56. } else {
  57. //Cert loaded. Check its expire time
  58. block, _ := pem.Decode(certBtyes)
  59. if block != nil {
  60. cert, err := x509.ParseCertificate(block.Bytes)
  61. if err == nil {
  62. certExpireTime = cert.NotAfter.Format("2006-01-02 15:04:05")
  63. }
  64. }
  65. }
  66. thisCertInfo := CertInfo{
  67. Domain: filename,
  68. LastModifiedDate: modifiedTime,
  69. ExpireDate: certExpireTime,
  70. }
  71. results = append(results, &thisCertInfo)
  72. }
  73. js, _ := json.Marshal(results)
  74. w.Header().Set("Content-Type", "application/json")
  75. w.Write(js)
  76. } else {
  77. response, err := json.Marshal(filenames)
  78. if err != nil {
  79. http.Error(w, err.Error(), http.StatusInternalServerError)
  80. return
  81. }
  82. w.Header().Set("Content-Type", "application/json")
  83. w.Write(response)
  84. }
  85. }
  86. // Handle front-end toggling TLS mode
  87. func handleToggleTLSProxy(w http.ResponseWriter, r *http.Request) {
  88. currentTlsSetting := false
  89. if sysdb.KeyExists("settings", "usetls") {
  90. sysdb.Read("settings", "usetls", &currentTlsSetting)
  91. }
  92. newState, err := utils.PostPara(r, "set")
  93. if err != nil {
  94. //No setting. Get the current status
  95. js, _ := json.Marshal(currentTlsSetting)
  96. utils.SendJSONResponse(w, string(js))
  97. } else {
  98. if newState == "true" {
  99. sysdb.Write("settings", "usetls", true)
  100. log.Println("Enabling TLS mode on reverse proxy")
  101. dynamicProxyRouter.UpdateTLSSetting(true)
  102. } else if newState == "false" {
  103. sysdb.Write("settings", "usetls", false)
  104. log.Println("Disabling TLS mode on reverse proxy")
  105. dynamicProxyRouter.UpdateTLSSetting(false)
  106. } else {
  107. utils.SendErrorResponse(w, "invalid state given. Only support true or false")
  108. return
  109. }
  110. utils.SendOK(w)
  111. }
  112. }
  113. // Handle upload of the certificate
  114. func handleCertUpload(w http.ResponseWriter, r *http.Request) {
  115. // check if request method is POST
  116. if r.Method != "POST" {
  117. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  118. return
  119. }
  120. // get the key type
  121. keytype, err := utils.GetPara(r, "ktype")
  122. overWriteFilename := ""
  123. if err != nil {
  124. http.Error(w, "Not defined key type (pub / pri)", http.StatusBadRequest)
  125. return
  126. }
  127. // get the domain
  128. domain, err := utils.GetPara(r, "domain")
  129. if err != nil {
  130. //Assume localhost
  131. domain = "default"
  132. }
  133. if keytype == "pub" {
  134. overWriteFilename = domain + ".crt"
  135. } else if keytype == "pri" {
  136. overWriteFilename = domain + ".key"
  137. } else {
  138. http.Error(w, "Not supported keytype: "+keytype, http.StatusBadRequest)
  139. return
  140. }
  141. // parse multipart form data
  142. err = r.ParseMultipartForm(10 << 20) // 10 MB
  143. if err != nil {
  144. http.Error(w, "Failed to parse form data", http.StatusBadRequest)
  145. return
  146. }
  147. // get file from form data
  148. file, _, err := r.FormFile("file")
  149. if err != nil {
  150. http.Error(w, "Failed to get file", http.StatusBadRequest)
  151. return
  152. }
  153. defer file.Close()
  154. // create file in upload directory
  155. os.MkdirAll("./certs", 0775)
  156. f, err := os.Create(filepath.Join("./certs", overWriteFilename))
  157. if err != nil {
  158. http.Error(w, "Failed to create file", http.StatusInternalServerError)
  159. return
  160. }
  161. defer f.Close()
  162. // copy file contents to destination file
  163. _, err = io.Copy(f, file)
  164. if err != nil {
  165. http.Error(w, "Failed to save file", http.StatusInternalServerError)
  166. return
  167. }
  168. // send response
  169. fmt.Fprintln(w, "File upload successful!")
  170. }
  171. // Handle cert remove
  172. func handleCertRemove(w http.ResponseWriter, r *http.Request) {
  173. domain, err := utils.PostPara(r, "domain")
  174. if err != nil {
  175. utils.SendErrorResponse(w, "invalid domain given")
  176. return
  177. }
  178. err = tlsCertManager.RemoveCert(domain)
  179. if err != nil {
  180. utils.SendErrorResponse(w, err.Error())
  181. }
  182. }