cert.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package main
  2. import (
  3. "crypto/x509"
  4. "encoding/json"
  5. "encoding/pem"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "imuslab.com/zoraxy/mod/acme"
  14. "imuslab.com/zoraxy/mod/utils"
  15. )
  16. // Check if the default certificates is correctly setup
  17. func handleDefaultCertCheck(w http.ResponseWriter, r *http.Request) {
  18. type CheckResult struct {
  19. DefaultPubExists bool
  20. DefaultPriExists bool
  21. }
  22. pub, pri := tlsCertManager.DefaultCertExistsSep()
  23. js, _ := json.Marshal(CheckResult{
  24. pub,
  25. pri,
  26. })
  27. utils.SendJSONResponse(w, string(js))
  28. }
  29. // Return a list of domains where the certificates covers
  30. func handleListCertificate(w http.ResponseWriter, r *http.Request) {
  31. filenames, err := tlsCertManager.ListCertDomains()
  32. if err != nil {
  33. http.Error(w, err.Error(), http.StatusInternalServerError)
  34. return
  35. }
  36. showDate, _ := utils.GetPara(r, "date")
  37. if showDate == "true" {
  38. type CertInfo struct {
  39. Domain string
  40. LastModifiedDate string
  41. ExpireDate string
  42. RemainingDays int
  43. UseDNS bool
  44. }
  45. results := []*CertInfo{}
  46. for _, filename := range filenames {
  47. certFilepath := filepath.Join(tlsCertManager.CertStore, filename+".pem")
  48. //keyFilepath := filepath.Join(tlsCertManager.CertStore, filename+".key")
  49. fileInfo, err := os.Stat(certFilepath)
  50. if err != nil {
  51. utils.SendErrorResponse(w, "invalid domain certificate discovered: "+filename)
  52. return
  53. }
  54. modifiedTime := fileInfo.ModTime().Format("2006-01-02 15:04:05")
  55. certExpireTime := "Unknown"
  56. certBtyes, err := os.ReadFile(certFilepath)
  57. expiredIn := 0
  58. if err != nil {
  59. //Unable to load this file
  60. continue
  61. } else {
  62. //Cert loaded. Check its expire time
  63. block, _ := pem.Decode(certBtyes)
  64. if block != nil {
  65. cert, err := x509.ParseCertificate(block.Bytes)
  66. if err == nil {
  67. certExpireTime = cert.NotAfter.Format("2006-01-02 15:04:05")
  68. duration := cert.NotAfter.Sub(time.Now())
  69. // Convert the duration to days
  70. expiredIn = int(duration.Hours() / 24)
  71. }
  72. }
  73. }
  74. certInfoFilename := filepath.Join(tlsCertManager.CertStore, filename+".json")
  75. useDNSValidation := false //Default to false for HTTP TLS certificates
  76. certInfo, err := acme.LoadCertInfoJSON(certInfoFilename) //Note: Not all certs have info json
  77. if err == nil {
  78. useDNSValidation = certInfo.UseDNS
  79. }
  80. thisCertInfo := CertInfo{
  81. Domain: filename,
  82. LastModifiedDate: modifiedTime,
  83. ExpireDate: certExpireTime,
  84. RemainingDays: expiredIn,
  85. UseDNS: useDNSValidation,
  86. }
  87. results = append(results, &thisCertInfo)
  88. }
  89. js, _ := json.Marshal(results)
  90. w.Header().Set("Content-Type", "application/json")
  91. w.Write(js)
  92. } else {
  93. response, err := json.Marshal(filenames)
  94. if err != nil {
  95. http.Error(w, err.Error(), http.StatusInternalServerError)
  96. return
  97. }
  98. w.Header().Set("Content-Type", "application/json")
  99. w.Write(response)
  100. }
  101. }
  102. // List all certificates and map all their domains to the cert filename
  103. func handleListDomains(w http.ResponseWriter, r *http.Request) {
  104. filenames, err := os.ReadDir("./conf/certs/")
  105. if err != nil {
  106. utils.SendErrorResponse(w, err.Error())
  107. return
  108. }
  109. certnameToDomainMap := map[string]string{}
  110. for _, filename := range filenames {
  111. if filename.IsDir() {
  112. continue
  113. }
  114. certFilepath := filepath.Join("./conf/certs/", filename.Name())
  115. certBtyes, err := os.ReadFile(certFilepath)
  116. if err != nil {
  117. // Unable to load this file
  118. SystemWideLogger.PrintAndLog("TLS", "Unable to load certificate: "+certFilepath, err)
  119. continue
  120. } else {
  121. // Cert loaded. Check its expiry time
  122. block, _ := pem.Decode(certBtyes)
  123. if block != nil {
  124. cert, err := x509.ParseCertificate(block.Bytes)
  125. if err == nil {
  126. certname := strings.TrimSuffix(filepath.Base(certFilepath), filepath.Ext(certFilepath))
  127. for _, dnsName := range cert.DNSNames {
  128. certnameToDomainMap[dnsName] = certname
  129. }
  130. certnameToDomainMap[cert.Subject.CommonName] = certname
  131. }
  132. }
  133. }
  134. }
  135. requireCompact, _ := utils.GetPara(r, "compact")
  136. if requireCompact == "true" {
  137. result := make(map[string][]string)
  138. for key, value := range certnameToDomainMap {
  139. if _, ok := result[value]; !ok {
  140. result[value] = make([]string, 0)
  141. }
  142. result[value] = append(result[value], key)
  143. }
  144. js, _ := json.Marshal(result)
  145. utils.SendJSONResponse(w, string(js))
  146. return
  147. }
  148. js, _ := json.Marshal(certnameToDomainMap)
  149. utils.SendJSONResponse(w, string(js))
  150. }
  151. // Handle front-end toggling TLS mode
  152. func handleToggleTLSProxy(w http.ResponseWriter, r *http.Request) {
  153. currentTlsSetting := false
  154. if sysdb.KeyExists("settings", "usetls") {
  155. sysdb.Read("settings", "usetls", &currentTlsSetting)
  156. }
  157. if r.Method == http.MethodGet {
  158. //Get the current status
  159. js, _ := json.Marshal(currentTlsSetting)
  160. utils.SendJSONResponse(w, string(js))
  161. } else if r.Method == http.MethodPost {
  162. newState, err := utils.PostBool(r, "set")
  163. if err != nil {
  164. utils.SendErrorResponse(w, "new state not set or invalid")
  165. return
  166. }
  167. if newState {
  168. sysdb.Write("settings", "usetls", true)
  169. SystemWideLogger.Println("Enabling TLS mode on reverse proxy")
  170. dynamicProxyRouter.UpdateTLSSetting(true)
  171. } else {
  172. sysdb.Write("settings", "usetls", false)
  173. SystemWideLogger.Println("Disabling TLS mode on reverse proxy")
  174. dynamicProxyRouter.UpdateTLSSetting(false)
  175. }
  176. utils.SendOK(w)
  177. } else {
  178. http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
  179. }
  180. }
  181. // Handle the GET and SET of reverse proxy TLS versions
  182. func handleSetTlsRequireLatest(w http.ResponseWriter, r *http.Request) {
  183. newState, err := utils.PostPara(r, "set")
  184. if err != nil {
  185. //GET
  186. var reqLatestTLS bool = false
  187. if sysdb.KeyExists("settings", "forceLatestTLS") {
  188. sysdb.Read("settings", "forceLatestTLS", &reqLatestTLS)
  189. }
  190. js, _ := json.Marshal(reqLatestTLS)
  191. utils.SendJSONResponse(w, string(js))
  192. } else {
  193. if newState == "true" {
  194. sysdb.Write("settings", "forceLatestTLS", true)
  195. SystemWideLogger.Println("Updating minimum TLS version to v1.2 or above")
  196. dynamicProxyRouter.UpdateTLSVersion(true)
  197. } else if newState == "false" {
  198. sysdb.Write("settings", "forceLatestTLS", false)
  199. SystemWideLogger.Println("Updating minimum TLS version to v1.0 or above")
  200. dynamicProxyRouter.UpdateTLSVersion(false)
  201. } else {
  202. utils.SendErrorResponse(w, "invalid state given")
  203. }
  204. }
  205. }
  206. // Handle download of the selected certificate
  207. func handleCertDownload(w http.ResponseWriter, r *http.Request) {
  208. // get the certificate name
  209. certname, err := utils.GetPara(r, "certname")
  210. if err != nil {
  211. utils.SendErrorResponse(w, "invalid certname given")
  212. return
  213. }
  214. certname = filepath.Base(certname) //prevent path escape
  215. // check if the cert exists
  216. pubKey := filepath.Join(filepath.Join("./conf/certs"), certname+".key")
  217. priKey := filepath.Join(filepath.Join("./conf/certs"), certname+".pem")
  218. if utils.FileExists(pubKey) && utils.FileExists(priKey) {
  219. //Zip them and serve them via http download
  220. seeking, _ := utils.GetBool(r, "seek")
  221. if seeking {
  222. //This request only check if the key exists. Do not provide download
  223. utils.SendOK(w)
  224. return
  225. }
  226. //Serve both file in zip
  227. zipTmpFolder := "./tmp/download"
  228. os.MkdirAll(zipTmpFolder, 0775)
  229. zipFileName := filepath.Join(zipTmpFolder, certname+".zip")
  230. err := utils.ZipFiles(zipFileName, pubKey, priKey)
  231. if err != nil {
  232. http.Error(w, "Failed to create zip file", http.StatusInternalServerError)
  233. return
  234. }
  235. defer os.Remove(zipFileName) // Clean up the zip file after serving
  236. // Serve the zip file
  237. w.Header().Set("Content-Disposition", "attachment; filename=\""+certname+"_export.zip\"")
  238. w.Header().Set("Content-Type", "application/zip")
  239. http.ServeFile(w, r, zipFileName)
  240. } else {
  241. //Not both key exists
  242. utils.SendErrorResponse(w, "invalid key-pairs: private key or public key not found in key store")
  243. return
  244. }
  245. }
  246. // Handle upload of the certificate
  247. func handleCertUpload(w http.ResponseWriter, r *http.Request) {
  248. // check if request method is POST
  249. if r.Method != "POST" {
  250. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  251. return
  252. }
  253. // get the key type
  254. keytype, err := utils.GetPara(r, "ktype")
  255. overWriteFilename := ""
  256. if err != nil {
  257. http.Error(w, "Not defined key type (pub / pri)", http.StatusBadRequest)
  258. return
  259. }
  260. // get the domain
  261. domain, err := utils.GetPara(r, "domain")
  262. if err != nil {
  263. //Assume localhost
  264. domain = "default"
  265. }
  266. if keytype == "pub" {
  267. overWriteFilename = domain + ".pem"
  268. } else if keytype == "pri" {
  269. overWriteFilename = domain + ".key"
  270. } else {
  271. http.Error(w, "Not supported keytype: "+keytype, http.StatusBadRequest)
  272. return
  273. }
  274. // parse multipart form data
  275. err = r.ParseMultipartForm(10 << 20) // 10 MB
  276. if err != nil {
  277. http.Error(w, "Failed to parse form data", http.StatusBadRequest)
  278. return
  279. }
  280. // get file from form data
  281. file, _, err := r.FormFile("file")
  282. if err != nil {
  283. http.Error(w, "Failed to get file", http.StatusBadRequest)
  284. return
  285. }
  286. defer file.Close()
  287. // create file in upload directory
  288. os.MkdirAll("./conf/certs", 0775)
  289. f, err := os.Create(filepath.Join("./conf/certs", overWriteFilename))
  290. if err != nil {
  291. http.Error(w, "Failed to create file", http.StatusInternalServerError)
  292. return
  293. }
  294. defer f.Close()
  295. // copy file contents to destination file
  296. _, err = io.Copy(f, file)
  297. if err != nil {
  298. http.Error(w, "Failed to save file", http.StatusInternalServerError)
  299. return
  300. }
  301. //Update cert list
  302. tlsCertManager.UpdateLoadedCertList()
  303. // send response
  304. fmt.Fprintln(w, "File upload successful!")
  305. }
  306. // Handle cert remove
  307. func handleCertRemove(w http.ResponseWriter, r *http.Request) {
  308. domain, err := utils.PostPara(r, "domain")
  309. if err != nil {
  310. utils.SendErrorResponse(w, "invalid domain given")
  311. return
  312. }
  313. err = tlsCertManager.RemoveCert(domain)
  314. if err != nil {
  315. utils.SendErrorResponse(w, err.Error())
  316. }
  317. }