tlscert.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package tlscert
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "embed"
  6. "encoding/pem"
  7. "io"
  8. "log"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "imuslab.com/zoraxy/mod/utils"
  13. )
  14. type CertCache struct {
  15. Cert *x509.Certificate
  16. PubKey string
  17. PriKey string
  18. }
  19. type Manager struct {
  20. CertStore string //Path where all the certs are stored
  21. LoadedCerts []*CertCache //A list of loaded certs
  22. verbal bool
  23. }
  24. //go:embed localhost.pem localhost.key
  25. var buildinCertStore embed.FS
  26. func NewManager(certStore string, verbal bool) (*Manager, error) {
  27. if !utils.FileExists(certStore) {
  28. os.MkdirAll(certStore, 0775)
  29. }
  30. pubKey := "./tmp/localhost.pem"
  31. priKey := "./tmp/localhost.key"
  32. //Check if this is initial setup
  33. if !utils.FileExists(pubKey) {
  34. buildInPubKey, _ := buildinCertStore.ReadFile(filepath.Base(pubKey))
  35. os.WriteFile(pubKey, buildInPubKey, 0775)
  36. }
  37. if !utils.FileExists(priKey) {
  38. buildInPriKey, _ := buildinCertStore.ReadFile(filepath.Base(priKey))
  39. os.WriteFile(priKey, buildInPriKey, 0775)
  40. }
  41. thisManager := Manager{
  42. CertStore: certStore,
  43. LoadedCerts: []*CertCache{},
  44. verbal: verbal,
  45. }
  46. err := thisManager.UpdateLoadedCertList()
  47. if err != nil {
  48. return nil, err
  49. }
  50. return &thisManager, nil
  51. }
  52. // Update domain mapping from file
  53. func (m *Manager) UpdateLoadedCertList() error {
  54. //Get a list of certificates from file
  55. domainList, err := m.ListCertDomains()
  56. if err != nil {
  57. return err
  58. }
  59. //Load each of the certificates into memory
  60. certList := []*CertCache{}
  61. for _, certname := range domainList {
  62. //Read their certificate into memory
  63. pubKey := filepath.Join(m.CertStore, certname+".pem")
  64. priKey := filepath.Join(m.CertStore, certname+".key")
  65. certificate, err := tls.LoadX509KeyPair(pubKey, priKey)
  66. if err != nil {
  67. log.Println("Certificate loaded failed: " + certname)
  68. continue
  69. }
  70. for _, thisCert := range certificate.Certificate {
  71. loadedCert, err := x509.ParseCertificate(thisCert)
  72. if err != nil {
  73. //Error pasring cert, skip this byte segment
  74. continue
  75. }
  76. thisCacheEntry := CertCache{
  77. Cert: loadedCert,
  78. PubKey: pubKey,
  79. PriKey: priKey,
  80. }
  81. certList = append(certList, &thisCacheEntry)
  82. }
  83. }
  84. //Replace runtime cert array
  85. m.LoadedCerts = certList
  86. return nil
  87. }
  88. // Match cert by CN
  89. func (m *Manager) CertMatchExists(serverName string) bool {
  90. for _, certCacheEntry := range m.LoadedCerts {
  91. if certCacheEntry.Cert.VerifyHostname(serverName) == nil || certCacheEntry.Cert.Issuer.CommonName == serverName {
  92. return true
  93. }
  94. }
  95. return false
  96. }
  97. // Get cert entry by matching server name, return pubKey and priKey if found
  98. // check with CertMatchExists before calling to the load function
  99. func (m *Manager) GetCertByX509CNHostname(serverName string) (string, string) {
  100. for _, certCacheEntry := range m.LoadedCerts {
  101. if certCacheEntry.Cert.VerifyHostname(serverName) == nil || certCacheEntry.Cert.Issuer.CommonName == serverName {
  102. return certCacheEntry.PubKey, certCacheEntry.PriKey
  103. }
  104. }
  105. return "", ""
  106. }
  107. // Return a list of domains by filename
  108. func (m *Manager) ListCertDomains() ([]string, error) {
  109. filenames, err := m.ListCerts()
  110. if err != nil {
  111. return []string{}, err
  112. }
  113. //Remove certificates where there are missing public key or private key
  114. filenames = getCertPairs(filenames)
  115. return filenames, nil
  116. }
  117. // Return a list of cert files (public and private keys)
  118. func (m *Manager) ListCerts() ([]string, error) {
  119. certs, err := os.ReadDir(m.CertStore)
  120. if err != nil {
  121. return []string{}, err
  122. }
  123. filenames := make([]string, 0, len(certs))
  124. for _, cert := range certs {
  125. if !cert.IsDir() {
  126. filenames = append(filenames, cert.Name())
  127. }
  128. }
  129. return filenames, nil
  130. }
  131. // Get a certificate from disk where its certificate matches with the helloinfo
  132. func (m *Manager) GetCert(helloInfo *tls.ClientHelloInfo) (*tls.Certificate, error) {
  133. //Check if the domain corrisponding cert exists
  134. pubKey := "./tmp/localhost.pem"
  135. priKey := "./tmp/localhost.key"
  136. if utils.FileExists(filepath.Join(m.CertStore, helloInfo.ServerName+".pem")) && utils.FileExists(filepath.Join(m.CertStore, helloInfo.ServerName+".key")) {
  137. //Direct hit
  138. pubKey = filepath.Join(m.CertStore, helloInfo.ServerName+".pem")
  139. priKey = filepath.Join(m.CertStore, helloInfo.ServerName+".key")
  140. } else if m.CertMatchExists(helloInfo.ServerName) {
  141. //Use x509
  142. pubKey, priKey = m.GetCertByX509CNHostname(helloInfo.ServerName)
  143. } else {
  144. //Fallback to legacy method of matching certificates
  145. /*
  146. domainCerts, _ := m.ListCertDomains()
  147. cloestDomainCert := matchClosestDomainCertificate(helloInfo.ServerName, domainCerts)
  148. if cloestDomainCert != "" {
  149. //There is a matching parent domain for this subdomain. Use this instead.
  150. pubKey = filepath.Join(m.CertStore, cloestDomainCert+".pem")
  151. priKey = filepath.Join(m.CertStore, cloestDomainCert+".key")
  152. } else if m.DefaultCertExists() {
  153. //Use default.pem and default.key
  154. pubKey = filepath.Join(m.CertStore, "default.pem")
  155. priKey = filepath.Join(m.CertStore, "default.key")
  156. if m.verbal {
  157. log.Println("No matching certificate found. Serving with default")
  158. }
  159. } else {
  160. if m.verbal {
  161. log.Println("Matching certificate not found. Serving with build-in certificate. Requesting server name: ", helloInfo.ServerName)
  162. }
  163. }*/
  164. if m.DefaultCertExists() {
  165. //Use default.pem and default.key
  166. pubKey = filepath.Join(m.CertStore, "default.pem")
  167. priKey = filepath.Join(m.CertStore, "default.key")
  168. //if m.verbal {
  169. // log.Println("No matching certificate found. Serving with default")
  170. //}
  171. } else {
  172. //if m.verbal {
  173. // log.Println("Matching certificate not found. Serving with build-in certificate. Requesting server name: ", helloInfo.ServerName)
  174. //}
  175. }
  176. }
  177. //Load the cert and serve it
  178. cer, err := tls.LoadX509KeyPair(pubKey, priKey)
  179. if err != nil {
  180. log.Println(err)
  181. return nil, nil
  182. }
  183. return &cer, nil
  184. }
  185. // Check if both the default cert public key and private key exists
  186. func (m *Manager) DefaultCertExists() bool {
  187. return utils.FileExists(filepath.Join(m.CertStore, "default.pem")) && utils.FileExists(filepath.Join(m.CertStore, "default.key"))
  188. }
  189. // Check if the default cert exists returning seperate results for pubkey and prikey
  190. func (m *Manager) DefaultCertExistsSep() (bool, bool) {
  191. return utils.FileExists(filepath.Join(m.CertStore, "default.pem")), utils.FileExists(filepath.Join(m.CertStore, "default.key"))
  192. }
  193. // Delete the cert if exists
  194. func (m *Manager) RemoveCert(domain string) error {
  195. pubKey := filepath.Join(m.CertStore, domain+".pem")
  196. priKey := filepath.Join(m.CertStore, domain+".key")
  197. if utils.FileExists(pubKey) {
  198. err := os.Remove(pubKey)
  199. if err != nil {
  200. return err
  201. }
  202. }
  203. if utils.FileExists(priKey) {
  204. err := os.Remove(priKey)
  205. if err != nil {
  206. return err
  207. }
  208. }
  209. //Update the cert list
  210. m.UpdateLoadedCertList()
  211. return nil
  212. }
  213. // Check if the given file is a valid TLS file
  214. func IsValidTLSFile(file io.Reader) bool {
  215. // Read the contents of the uploaded file
  216. contents, err := io.ReadAll(file)
  217. if err != nil {
  218. // Handle the error
  219. return false
  220. }
  221. // Parse the contents of the file as a PEM-encoded certificate or key
  222. block, _ := pem.Decode(contents)
  223. if block == nil {
  224. // The file is not a valid PEM-encoded certificate or key
  225. return false
  226. }
  227. // Parse the certificate or key
  228. if strings.Contains(block.Type, "CERTIFICATE") {
  229. // The file contains a certificate
  230. cert, err := x509.ParseCertificate(block.Bytes)
  231. if err != nil {
  232. // Handle the error
  233. return false
  234. }
  235. // Check if the certificate is a valid TLS/SSL certificate
  236. return !cert.IsCA && cert.KeyUsage&x509.KeyUsageDigitalSignature != 0 && cert.KeyUsage&x509.KeyUsageKeyEncipherment != 0
  237. } else if strings.Contains(block.Type, "PRIVATE KEY") {
  238. // The file contains a private key
  239. _, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  240. return err == nil
  241. } else {
  242. return false
  243. }
  244. }