tls_manager_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. package lnd
  2. import (
  3. "bytes"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "crypto/x509/pkix"
  10. "encoding/pem"
  11. "math/big"
  12. "net"
  13. "os"
  14. "testing"
  15. "time"
  16. "github.com/btcsuite/btcd/btcec/v2"
  17. "github.com/lightningnetwork/lnd/cert"
  18. "github.com/lightningnetwork/lnd/keychain"
  19. "github.com/lightningnetwork/lnd/lnencrypt"
  20. "github.com/lightningnetwork/lnd/lntest/channels"
  21. "github.com/lightningnetwork/lnd/lntest/mock"
  22. "github.com/stretchr/testify/require"
  23. )
  24. const (
  25. testTLSCertDuration = 42 * time.Hour
  26. )
  27. var (
  28. privKeyBytes = channels.AlicesPrivKey
  29. privKey, _ = btcec.PrivKeyFromBytes(privKeyBytes)
  30. )
  31. // TestGenerateOrRenewCert creates an expired TLS certificate, to test that a
  32. // new TLS certificate pair is regenerated when the old pair expires. This is
  33. // necessary because the pair expires after a little over a year.
  34. func TestGenerateOrRenewCert(t *testing.T) {
  35. t.Parallel()
  36. // Write an expired certificate to disk.
  37. certPath, keyPath, expiredCert := writeTestCertFiles(
  38. t, true, false, nil,
  39. )
  40. // Now let's run the TLSManager's getConfig. If it works properly, it
  41. // should delete the cert and create a new one.
  42. cfg := &TLSManagerCfg{
  43. TLSCertPath: certPath,
  44. TLSKeyPath: keyPath,
  45. TLSCertDuration: testTLSCertDuration,
  46. }
  47. tlsManager := NewTLSManager(cfg)
  48. _, err := tlsManager.generateOrRenewCert()
  49. require.NoError(t, err)
  50. _, _, _, cleanUp, err := tlsManager.getConfig()
  51. require.NoError(t, err, "couldn't retrieve TLS config")
  52. t.Cleanup(cleanUp)
  53. // Grab the certificate to test that getTLSConfig did its job correctly
  54. // and generated a new cert.
  55. newCertData, err := tls.LoadX509KeyPair(certPath, keyPath)
  56. require.NoError(t, err, "couldn't grab new certificate")
  57. newCert, err := x509.ParseCertificate(newCertData.Certificate[0])
  58. require.NoError(t, err, "couldn't parse new certificate")
  59. // Check that the expired certificate was successfully deleted and
  60. // replaced with a new one.
  61. require.True(t, newCert.NotAfter.After(expiredCert.NotAfter),
  62. "New certificate expiration is too old")
  63. }
  64. // TestTLSManagerGenCert tests that the new TLS Manager loads correctly,
  65. // whether the encrypted TLS key flag is set or not.
  66. func TestTLSManagerGenCert(t *testing.T) {
  67. t.Parallel()
  68. _, certPath, keyPath := newTestDirectory(t)
  69. cfg := &TLSManagerCfg{
  70. TLSCertPath: certPath,
  71. TLSKeyPath: keyPath,
  72. }
  73. tlsManager := NewTLSManager(cfg)
  74. _, err := tlsManager.generateOrRenewCert()
  75. require.NoError(t, err, "failed to generate new certificate")
  76. // After this is run, a new certificate should be created and written
  77. // to disk. Since the TLSEncryptKey flag isn't set, we should be able
  78. // to read it in plaintext from disk.
  79. _, keyBytes, err := cert.GetCertBytesFromPath(
  80. cfg.TLSCertPath, cfg.TLSKeyPath,
  81. )
  82. require.NoError(t, err, "unable to load certificate")
  83. require.True(t, bytes.HasPrefix(keyBytes, privateKeyPrefix),
  84. "key is encrypted, but shouldn't be")
  85. // Now test that if the TLSEncryptKey flag is set, an encrypted key is
  86. // created and written to disk.
  87. _, certPath, keyPath = newTestDirectory(t)
  88. cfg = &TLSManagerCfg{
  89. TLSEncryptKey: true,
  90. TLSCertPath: certPath,
  91. TLSKeyPath: keyPath,
  92. TLSCertDuration: testTLSCertDuration,
  93. }
  94. tlsManager = NewTLSManager(cfg)
  95. keyRing := &mock.SecretKeyRing{
  96. RootKey: privKey,
  97. }
  98. err = tlsManager.generateCertPair(keyRing)
  99. require.NoError(t, err, "failed to generate new certificate")
  100. _, keyBytes, err = cert.GetCertBytesFromPath(
  101. certPath, keyPath,
  102. )
  103. require.NoError(t, err, "unable to load certificate")
  104. require.False(t, bytes.HasPrefix(keyBytes, privateKeyPrefix),
  105. "key isn't encrypted, but should be")
  106. }
  107. // TestEnsureEncryption tests that ensureEncryption does a couple of things:
  108. // 1) If we have cfg.TLSEncryptKey set, but the tls file saved to disk is not
  109. // encrypted, generateOrRenewCert encrypts the file and rewrites it to disk.
  110. // 2) If cfg.TLSEncryptKey is not set, but the file *is* encrypted, then we
  111. // need to return an error to the user.
  112. func TestEnsureEncryption(t *testing.T) {
  113. t.Parallel()
  114. keyRing := &mock.SecretKeyRing{
  115. RootKey: privKey,
  116. }
  117. // Write an unencrypted cert file to disk.
  118. certPath, keyPath, _ := writeTestCertFiles(
  119. t, false, false, keyRing,
  120. )
  121. cfg := &TLSManagerCfg{
  122. TLSEncryptKey: true,
  123. TLSCertPath: certPath,
  124. TLSKeyPath: keyPath,
  125. }
  126. tlsManager := NewTLSManager(cfg)
  127. // Check that the keyBytes are initially plaintext.
  128. _, newKeyBytes, err := cert.GetCertBytesFromPath(
  129. cfg.TLSCertPath, cfg.TLSKeyPath,
  130. )
  131. require.NoError(t, err, "unable to load certificate files")
  132. require.True(t, bytes.HasPrefix(newKeyBytes, privateKeyPrefix),
  133. "key doesn't have correct plaintext prefix")
  134. // ensureEncryption should detect that the TLS key is in plaintext,
  135. // encrypt it, and rewrite the encrypted version to disk.
  136. err = tlsManager.ensureEncryption(keyRing)
  137. require.NoError(t, err, "failed to generate new certificate")
  138. // Grab the file from disk to check that the key is no longer
  139. // plaintext.
  140. _, newKeyBytes, err = cert.GetCertBytesFromPath(
  141. cfg.TLSCertPath, cfg.TLSKeyPath,
  142. )
  143. require.NoError(t, err, "unable to load certificate")
  144. require.False(t, bytes.HasPrefix(newKeyBytes, privateKeyPrefix),
  145. "key isn't encrypted, but should be")
  146. // Now let's flip the cfg.TLSEncryptKey to false. Since the key on file
  147. // is encrypted, ensureEncryption should error out.
  148. tlsManager.cfg.TLSEncryptKey = false
  149. err = tlsManager.ensureEncryption(keyRing)
  150. require.Error(t, err)
  151. }
  152. // TestGenerateEphemeralCert tests that an ephemeral certificate is created and
  153. // stored to disk in a .tmp file and that LoadPermanentCertificate deletes
  154. // file and replaces it with a fresh certificate pair.
  155. func TestGenerateEphemeralCert(t *testing.T) {
  156. t.Parallel()
  157. _, certPath, keyPath := newTestDirectory(t)
  158. tmpCertPath := certPath + ".tmp"
  159. cfg := &TLSManagerCfg{
  160. TLSCertPath: certPath,
  161. TLSKeyPath: keyPath,
  162. TLSEncryptKey: true,
  163. TLSCertDuration: testTLSCertDuration,
  164. }
  165. tlsManager := NewTLSManager(cfg)
  166. keyBytes, err := tlsManager.loadEphemeralCertificate()
  167. require.NoError(t, err, "failed to generate new certificate")
  168. certBytes, err := os.ReadFile(tmpCertPath)
  169. require.NoError(t, err)
  170. tlsr, err := cert.NewTLSReloader(certBytes, keyBytes)
  171. require.NoError(t, err)
  172. tlsManager.tlsReloader = tlsr
  173. // Make sure .tmp file is created at the tmp cert path.
  174. _, err = os.ReadFile(tmpCertPath)
  175. require.NoError(t, err, "couldn't find temp cert file")
  176. // But no key should be stored.
  177. _, err = os.ReadFile(cfg.TLSKeyPath)
  178. require.Error(t, err, "shouldn't have found file")
  179. // And no permanent cert file should be stored.
  180. _, err = os.ReadFile(cfg.TLSCertPath)
  181. require.Error(t, err, "shouldn't have found a permanent cert file")
  182. // Now test that when we reload the certificate it generates the new
  183. // certificate properly.
  184. keyRing := &mock.SecretKeyRing{
  185. RootKey: privKey,
  186. }
  187. err = tlsManager.LoadPermanentCertificate(keyRing)
  188. require.NoError(t, err, "unable to reload certificate")
  189. // Make sure .tmp file is deleted.
  190. _, _, err = cert.GetCertBytesFromPath(
  191. tmpCertPath, cfg.TLSKeyPath,
  192. )
  193. require.Error(t, err, ".tmp file should have been deleted")
  194. // Make sure a certificate now exists at the permanent cert path.
  195. _, _, err = cert.GetCertBytesFromPath(
  196. cfg.TLSCertPath, cfg.TLSKeyPath,
  197. )
  198. require.NoError(t, err, "error loading permanent certificate")
  199. }
  200. // genCertPair generates a key/cert pair, with the option of generating expired
  201. // certificates to make sure they are being regenerated correctly.
  202. func genCertPair(t *testing.T, expired bool) ([]byte, []byte) {
  203. t.Helper()
  204. // Max serial number.
  205. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  206. // Generate a serial number that's below the serialNumberLimit.
  207. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  208. require.NoError(t, err, "failed to generate serial number")
  209. host := "lightning"
  210. // Create a simple ip address for the fake certificate.
  211. ipAddresses := []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}
  212. dnsNames := []string{host, "unix", "unixpacket"}
  213. var notBefore, notAfter time.Time
  214. if expired {
  215. notBefore = time.Now().Add(-time.Hour * 24)
  216. notAfter = time.Now()
  217. } else {
  218. notBefore = time.Now()
  219. notAfter = time.Now().Add(time.Hour * 24)
  220. }
  221. // Construct the certificate template.
  222. template := x509.Certificate{
  223. SerialNumber: serialNumber,
  224. Subject: pkix.Name{
  225. Organization: []string{"lnd autogenerated cert"},
  226. CommonName: host,
  227. },
  228. NotBefore: notBefore,
  229. NotAfter: notAfter,
  230. KeyUsage: x509.KeyUsageKeyEncipherment |
  231. x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
  232. IsCA: true, // so can sign self.
  233. BasicConstraintsValid: true,
  234. DNSNames: dnsNames,
  235. IPAddresses: ipAddresses,
  236. }
  237. // Generate a private key for the certificate.
  238. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  239. if err != nil {
  240. t.Fatalf("failed to generate a private key")
  241. }
  242. certDerBytes, err := x509.CreateCertificate(
  243. rand.Reader, &template, &template, &priv.PublicKey, priv,
  244. )
  245. require.NoError(t, err, "failed to create certificate")
  246. keyBytes, err := x509.MarshalECPrivateKey(priv)
  247. require.NoError(t, err, "unable to encode privkey")
  248. return certDerBytes, keyBytes
  249. }
  250. // writeTestCertFiles creates test files and writes them to a temporary testing
  251. // directory.
  252. func writeTestCertFiles(t *testing.T, expiredCert, encryptTLSKey bool,
  253. keyRing keychain.KeyRing) (string, string, *x509.Certificate) {
  254. t.Helper()
  255. tempDir, certPath, keyPath := newTestDirectory(t)
  256. var certDerBytes, keyBytes []byte
  257. // Either create a valid certificate or an expired certificate pair,
  258. // depending on the test.
  259. if expiredCert {
  260. certDerBytes, keyBytes = genCertPair(t, true)
  261. } else {
  262. certDerBytes, keyBytes = genCertPair(t, false)
  263. }
  264. parsedCert, err := x509.ParseCertificate(certDerBytes)
  265. require.NoError(t, err, "failed to parse certificate")
  266. certBuf := bytes.Buffer{}
  267. err = pem.Encode(
  268. &certBuf, &pem.Block{
  269. Type: "CERTIFICATE",
  270. Bytes: certDerBytes,
  271. },
  272. )
  273. require.NoError(t, err, "failed to encode certificate")
  274. var keyBuf *bytes.Buffer
  275. if !encryptTLSKey {
  276. keyBuf = &bytes.Buffer{}
  277. err = pem.Encode(
  278. keyBuf, &pem.Block{
  279. Type: "EC PRIVATE KEY",
  280. Bytes: keyBytes,
  281. },
  282. )
  283. require.NoError(t, err, "failed to encode private key")
  284. } else {
  285. e, err := lnencrypt.KeyRingEncrypter(keyRing)
  286. require.NoError(t, err, "unable to generate key encrypter")
  287. err = e.EncryptPayloadToWriter(
  288. keyBytes, keyBuf,
  289. )
  290. require.NoError(t, err, "failed to encrypt private key")
  291. }
  292. err = os.WriteFile(tempDir+"/tls.cert", certBuf.Bytes(), 0644)
  293. require.NoError(t, err, "failed to write cert file")
  294. err = os.WriteFile(tempDir+"/tls.key", keyBuf.Bytes(), 0600)
  295. require.NoError(t, err, "failed to write key file")
  296. return certPath, keyPath, parsedCert
  297. }
  298. // newTestDirectory creates a new test directory and returns the location of
  299. // the test tls.cert and tls.key files.
  300. func newTestDirectory(t *testing.T) (string, string, string) {
  301. t.Helper()
  302. tempDir := t.TempDir()
  303. certPath := tempDir + "/tls.cert"
  304. keyPath := tempDir + "/tls.key"
  305. return tempDir, certPath, keyPath
  306. }