cert.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 := true //Default to true
  154. if dynamicProxyRouter.Option != nil {
  155. currentTlsSetting = dynamicProxyRouter.Option.UseTls
  156. }
  157. if sysdb.KeyExists("settings", "usetls") {
  158. sysdb.Read("settings", "usetls", &currentTlsSetting)
  159. }
  160. if r.Method == http.MethodGet {
  161. //Get the current status
  162. js, _ := json.Marshal(currentTlsSetting)
  163. utils.SendJSONResponse(w, string(js))
  164. } else if r.Method == http.MethodPost {
  165. newState, err := utils.PostBool(r, "set")
  166. if err != nil {
  167. utils.SendErrorResponse(w, "new state not set or invalid")
  168. return
  169. }
  170. if newState {
  171. sysdb.Write("settings", "usetls", true)
  172. SystemWideLogger.Println("Enabling TLS mode on reverse proxy")
  173. dynamicProxyRouter.UpdateTLSSetting(true)
  174. } else {
  175. sysdb.Write("settings", "usetls", false)
  176. SystemWideLogger.Println("Disabling TLS mode on reverse proxy")
  177. dynamicProxyRouter.UpdateTLSSetting(false)
  178. }
  179. utils.SendOK(w)
  180. } else {
  181. http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
  182. }
  183. }
  184. // Handle the GET and SET of reverse proxy TLS versions
  185. func handleSetTlsRequireLatest(w http.ResponseWriter, r *http.Request) {
  186. newState, err := utils.PostPara(r, "set")
  187. if err != nil {
  188. //GET
  189. var reqLatestTLS bool = false
  190. if sysdb.KeyExists("settings", "forceLatestTLS") {
  191. sysdb.Read("settings", "forceLatestTLS", &reqLatestTLS)
  192. }
  193. js, _ := json.Marshal(reqLatestTLS)
  194. utils.SendJSONResponse(w, string(js))
  195. } else {
  196. if newState == "true" {
  197. sysdb.Write("settings", "forceLatestTLS", true)
  198. SystemWideLogger.Println("Updating minimum TLS version to v1.2 or above")
  199. dynamicProxyRouter.UpdateTLSVersion(true)
  200. } else if newState == "false" {
  201. sysdb.Write("settings", "forceLatestTLS", false)
  202. SystemWideLogger.Println("Updating minimum TLS version to v1.0 or above")
  203. dynamicProxyRouter.UpdateTLSVersion(false)
  204. } else {
  205. utils.SendErrorResponse(w, "invalid state given")
  206. }
  207. }
  208. }
  209. // Handle download of the selected certificate
  210. func handleCertDownload(w http.ResponseWriter, r *http.Request) {
  211. // get the certificate name
  212. certname, err := utils.GetPara(r, "certname")
  213. if err != nil {
  214. utils.SendErrorResponse(w, "invalid certname given")
  215. return
  216. }
  217. certname = filepath.Base(certname) //prevent path escape
  218. // check if the cert exists
  219. pubKey := filepath.Join(filepath.Join("./conf/certs"), certname+".key")
  220. priKey := filepath.Join(filepath.Join("./conf/certs"), certname+".pem")
  221. if utils.FileExists(pubKey) && utils.FileExists(priKey) {
  222. //Zip them and serve them via http download
  223. seeking, _ := utils.GetBool(r, "seek")
  224. if seeking {
  225. //This request only check if the key exists. Do not provide download
  226. utils.SendOK(w)
  227. return
  228. }
  229. //Serve both file in zip
  230. zipTmpFolder := "./tmp/download"
  231. os.MkdirAll(zipTmpFolder, 0775)
  232. zipFileName := filepath.Join(zipTmpFolder, certname+".zip")
  233. err := utils.ZipFiles(zipFileName, pubKey, priKey)
  234. if err != nil {
  235. http.Error(w, "Failed to create zip file", http.StatusInternalServerError)
  236. return
  237. }
  238. defer os.Remove(zipFileName) // Clean up the zip file after serving
  239. // Serve the zip file
  240. w.Header().Set("Content-Disposition", "attachment; filename=\""+certname+"_export.zip\"")
  241. w.Header().Set("Content-Type", "application/zip")
  242. http.ServeFile(w, r, zipFileName)
  243. } else {
  244. //Not both key exists
  245. utils.SendErrorResponse(w, "invalid key-pairs: private key or public key not found in key store")
  246. return
  247. }
  248. }
  249. // Handle upload of the certificate
  250. func handleCertUpload(w http.ResponseWriter, r *http.Request) {
  251. // check if request method is POST
  252. if r.Method != "POST" {
  253. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  254. return
  255. }
  256. // get the key type
  257. keytype, err := utils.GetPara(r, "ktype")
  258. overWriteFilename := ""
  259. if err != nil {
  260. http.Error(w, "Not defined key type (pub / pri)", http.StatusBadRequest)
  261. return
  262. }
  263. // get the domain
  264. domain, err := utils.GetPara(r, "domain")
  265. if err != nil {
  266. //Assume localhost
  267. domain = "default"
  268. }
  269. if keytype == "pub" {
  270. overWriteFilename = domain + ".pem"
  271. } else if keytype == "pri" {
  272. overWriteFilename = domain + ".key"
  273. } else {
  274. http.Error(w, "Not supported keytype: "+keytype, http.StatusBadRequest)
  275. return
  276. }
  277. // parse multipart form data
  278. err = r.ParseMultipartForm(10 << 20) // 10 MB
  279. if err != nil {
  280. http.Error(w, "Failed to parse form data", http.StatusBadRequest)
  281. return
  282. }
  283. // get file from form data
  284. file, _, err := r.FormFile("file")
  285. if err != nil {
  286. http.Error(w, "Failed to get file", http.StatusBadRequest)
  287. return
  288. }
  289. defer file.Close()
  290. // create file in upload directory
  291. os.MkdirAll("./conf/certs", 0775)
  292. f, err := os.Create(filepath.Join("./conf/certs", overWriteFilename))
  293. if err != nil {
  294. http.Error(w, "Failed to create file", http.StatusInternalServerError)
  295. return
  296. }
  297. defer f.Close()
  298. // copy file contents to destination file
  299. _, err = io.Copy(f, file)
  300. if err != nil {
  301. http.Error(w, "Failed to save file", http.StatusInternalServerError)
  302. return
  303. }
  304. //Update cert list
  305. tlsCertManager.UpdateLoadedCertList()
  306. // send response
  307. fmt.Fprintln(w, "File upload successful!")
  308. }
  309. // Handle cert remove
  310. func handleCertRemove(w http.ResponseWriter, r *http.Request) {
  311. domain, err := utils.PostPara(r, "domain")
  312. if err != nil {
  313. utils.SendErrorResponse(w, "invalid domain given")
  314. return
  315. }
  316. err = tlsCertManager.RemoveCert(domain)
  317. if err != nil {
  318. utils.SendErrorResponse(w, err.Error())
  319. }
  320. }