cert.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. package cert
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/rand"
  6. "crypto/sha256"
  7. "encoding/binary"
  8. "encoding/hex"
  9. "encoding/json"
  10. "encoding/pem"
  11. "errors"
  12. "fmt"
  13. "math"
  14. "net"
  15. "time"
  16. "golang.org/x/crypto/curve25519"
  17. "golang.org/x/crypto/ed25519"
  18. "google.golang.org/protobuf/proto"
  19. )
  20. const publicKeyLen = 32
  21. const (
  22. CertBanner = "NEBULA CERTIFICATE"
  23. X25519PrivateKeyBanner = "NEBULA X25519 PRIVATE KEY"
  24. X25519PublicKeyBanner = "NEBULA X25519 PUBLIC KEY"
  25. EncryptedEd25519PrivateKeyBanner = "NEBULA ED25519 ENCRYPTED PRIVATE KEY"
  26. Ed25519PrivateKeyBanner = "NEBULA ED25519 PRIVATE KEY"
  27. Ed25519PublicKeyBanner = "NEBULA ED25519 PUBLIC KEY"
  28. )
  29. type NebulaCertificate struct {
  30. Details NebulaCertificateDetails
  31. Signature []byte
  32. }
  33. type NebulaCertificateDetails struct {
  34. Name string
  35. Ips []*net.IPNet
  36. Subnets []*net.IPNet
  37. Groups []string
  38. NotBefore time.Time
  39. NotAfter time.Time
  40. PublicKey []byte
  41. IsCA bool
  42. Issuer string
  43. // Map of groups for faster lookup
  44. InvertedGroups map[string]struct{}
  45. }
  46. type NebulaEncryptedData struct {
  47. EncryptionMetadata NebulaEncryptionMetadata
  48. Ciphertext []byte
  49. }
  50. type NebulaEncryptionMetadata struct {
  51. EncryptionAlgorithm string
  52. Argon2Parameters Argon2Parameters
  53. }
  54. type m map[string]interface{}
  55. // Returned if we try to unmarshal an encrypted private key without a passphrase
  56. var ErrPrivateKeyEncrypted = errors.New("private key must be decrypted")
  57. // UnmarshalNebulaCertificate will unmarshal a protobuf byte representation of a nebula cert
  58. func UnmarshalNebulaCertificate(b []byte) (*NebulaCertificate, error) {
  59. if len(b) == 0 {
  60. return nil, fmt.Errorf("nil byte array")
  61. }
  62. var rc RawNebulaCertificate
  63. err := proto.Unmarshal(b, &rc)
  64. if err != nil {
  65. return nil, err
  66. }
  67. if rc.Details == nil {
  68. return nil, fmt.Errorf("encoded Details was nil")
  69. }
  70. if len(rc.Details.Ips)%2 != 0 {
  71. return nil, fmt.Errorf("encoded IPs should be in pairs, an odd number was found")
  72. }
  73. if len(rc.Details.Subnets)%2 != 0 {
  74. return nil, fmt.Errorf("encoded Subnets should be in pairs, an odd number was found")
  75. }
  76. nc := NebulaCertificate{
  77. Details: NebulaCertificateDetails{
  78. Name: rc.Details.Name,
  79. Groups: make([]string, len(rc.Details.Groups)),
  80. Ips: make([]*net.IPNet, len(rc.Details.Ips)/2),
  81. Subnets: make([]*net.IPNet, len(rc.Details.Subnets)/2),
  82. NotBefore: time.Unix(rc.Details.NotBefore, 0),
  83. NotAfter: time.Unix(rc.Details.NotAfter, 0),
  84. PublicKey: make([]byte, len(rc.Details.PublicKey)),
  85. IsCA: rc.Details.IsCA,
  86. InvertedGroups: make(map[string]struct{}),
  87. },
  88. Signature: make([]byte, len(rc.Signature)),
  89. }
  90. copy(nc.Signature, rc.Signature)
  91. copy(nc.Details.Groups, rc.Details.Groups)
  92. nc.Details.Issuer = hex.EncodeToString(rc.Details.Issuer)
  93. if len(rc.Details.PublicKey) < publicKeyLen {
  94. return nil, fmt.Errorf("Public key was fewer than 32 bytes; %v", len(rc.Details.PublicKey))
  95. }
  96. copy(nc.Details.PublicKey, rc.Details.PublicKey)
  97. for i, rawIp := range rc.Details.Ips {
  98. if i%2 == 0 {
  99. nc.Details.Ips[i/2] = &net.IPNet{IP: int2ip(rawIp)}
  100. } else {
  101. nc.Details.Ips[i/2].Mask = net.IPMask(int2ip(rawIp))
  102. }
  103. }
  104. for i, rawIp := range rc.Details.Subnets {
  105. if i%2 == 0 {
  106. nc.Details.Subnets[i/2] = &net.IPNet{IP: int2ip(rawIp)}
  107. } else {
  108. nc.Details.Subnets[i/2].Mask = net.IPMask(int2ip(rawIp))
  109. }
  110. }
  111. for _, g := range rc.Details.Groups {
  112. nc.Details.InvertedGroups[g] = struct{}{}
  113. }
  114. return &nc, nil
  115. }
  116. // UnmarshalNebulaCertificateFromPEM will unmarshal the first pem block in a byte array, returning any non consumed data
  117. // or an error on failure
  118. func UnmarshalNebulaCertificateFromPEM(b []byte) (*NebulaCertificate, []byte, error) {
  119. p, r := pem.Decode(b)
  120. if p == nil {
  121. return nil, r, fmt.Errorf("input did not contain a valid PEM encoded block")
  122. }
  123. if p.Type != CertBanner {
  124. return nil, r, fmt.Errorf("bytes did not contain a proper nebula certificate banner")
  125. }
  126. nc, err := UnmarshalNebulaCertificate(p.Bytes)
  127. return nc, r, err
  128. }
  129. // MarshalX25519PrivateKey is a simple helper to PEM encode an X25519 private key
  130. func MarshalX25519PrivateKey(b []byte) []byte {
  131. return pem.EncodeToMemory(&pem.Block{Type: X25519PrivateKeyBanner, Bytes: b})
  132. }
  133. // MarshalEd25519PrivateKey is a simple helper to PEM encode an Ed25519 private key
  134. func MarshalEd25519PrivateKey(key ed25519.PrivateKey) []byte {
  135. return pem.EncodeToMemory(&pem.Block{Type: Ed25519PrivateKeyBanner, Bytes: key})
  136. }
  137. // EncryptAndMarshalX25519PrivateKey is a simple helper to encrypt and PEM encode an X25519 private key
  138. func EncryptAndMarshalEd25519PrivateKey(b []byte, passphrase []byte, kdfParams *Argon2Parameters) ([]byte, error) {
  139. ciphertext, err := aes256Encrypt(passphrase, kdfParams, b)
  140. if err != nil {
  141. return nil, err
  142. }
  143. b, err = proto.Marshal(&RawNebulaEncryptedData{
  144. EncryptionMetadata: &RawNebulaEncryptionMetadata{
  145. EncryptionAlgorithm: "AES-256-GCM",
  146. Argon2Parameters: &RawNebulaArgon2Parameters{
  147. Version: kdfParams.version,
  148. Memory: kdfParams.Memory,
  149. Parallelism: uint32(kdfParams.Parallelism),
  150. Iterations: kdfParams.Iterations,
  151. Salt: kdfParams.salt,
  152. },
  153. },
  154. Ciphertext: ciphertext,
  155. })
  156. return pem.EncodeToMemory(&pem.Block{Type: EncryptedEd25519PrivateKeyBanner, Bytes: b}), nil
  157. }
  158. // UnmarshalX25519PrivateKey will try to pem decode an X25519 private key, returning any other bytes b
  159. // or an error on failure
  160. func UnmarshalX25519PrivateKey(b []byte) ([]byte, []byte, error) {
  161. k, r := pem.Decode(b)
  162. if k == nil {
  163. return nil, r, fmt.Errorf("input did not contain a valid PEM encoded block")
  164. }
  165. if k.Type != X25519PrivateKeyBanner {
  166. return nil, r, fmt.Errorf("bytes did not contain a proper nebula X25519 private key banner")
  167. }
  168. if len(k.Bytes) != publicKeyLen {
  169. return nil, r, fmt.Errorf("key was not 32 bytes, is invalid X25519 private key")
  170. }
  171. return k.Bytes, r, nil
  172. }
  173. // UnmarshalEd25519PrivateKey will try to pem decode an Ed25519 private key, returning any other bytes b
  174. // or an error on failure
  175. func UnmarshalEd25519PrivateKey(b []byte) (ed25519.PrivateKey, []byte, error) {
  176. k, r := pem.Decode(b)
  177. if k == nil {
  178. return nil, r, fmt.Errorf("input did not contain a valid PEM encoded block")
  179. }
  180. if k.Type == EncryptedEd25519PrivateKeyBanner {
  181. return nil, r, ErrPrivateKeyEncrypted
  182. } else if k.Type != Ed25519PrivateKeyBanner {
  183. return nil, r, fmt.Errorf("bytes did not contain a proper nebula Ed25519 private key banner")
  184. }
  185. if len(k.Bytes) != ed25519.PrivateKeySize {
  186. return nil, r, fmt.Errorf("key was not 64 bytes, is invalid ed25519 private key")
  187. }
  188. return k.Bytes, r, nil
  189. }
  190. // UnmarshalNebulaCertificate will unmarshal a protobuf byte representation of a nebula cert into its
  191. // protobuf-generated struct.
  192. func UnmarshalNebulaEncryptedData(b []byte) (*NebulaEncryptedData, error) {
  193. if len(b) == 0 {
  194. return nil, fmt.Errorf("nil byte array")
  195. }
  196. var rned RawNebulaEncryptedData
  197. err := proto.Unmarshal(b, &rned)
  198. if err != nil {
  199. return nil, err
  200. }
  201. if rned.EncryptionMetadata == nil {
  202. return nil, fmt.Errorf("encoded EncryptionMetadata was nil")
  203. }
  204. if rned.EncryptionMetadata.Argon2Parameters == nil {
  205. return nil, fmt.Errorf("encoded Argon2Parameters was nil")
  206. }
  207. params, err := unmarshalArgon2Parameters(rned.EncryptionMetadata.Argon2Parameters)
  208. if err != nil {
  209. return nil, err
  210. }
  211. ned := NebulaEncryptedData{
  212. EncryptionMetadata: NebulaEncryptionMetadata{
  213. EncryptionAlgorithm: rned.EncryptionMetadata.EncryptionAlgorithm,
  214. Argon2Parameters: *params,
  215. },
  216. Ciphertext: rned.Ciphertext,
  217. }
  218. return &ned, nil
  219. }
  220. func unmarshalArgon2Parameters(params *RawNebulaArgon2Parameters) (*Argon2Parameters, error) {
  221. if params.Version < math.MinInt32 || params.Version > math.MaxInt32 {
  222. return nil, fmt.Errorf("Argon2Parameters Version must be at least %d and no more than %d", math.MinInt32, math.MaxInt32)
  223. }
  224. if params.Memory <= 0 || params.Memory > math.MaxUint32 {
  225. return nil, fmt.Errorf("Argon2Parameters Memory must be be greater than 0 and no more than %d KiB", uint32(math.MaxUint32))
  226. }
  227. if params.Parallelism <= 0 || params.Parallelism > math.MaxUint8 {
  228. return nil, fmt.Errorf("Argon2Parameters Parallelism must be be greater than 0 and no more than %d", math.MaxUint8)
  229. }
  230. if params.Iterations <= 0 || params.Iterations > math.MaxUint32 {
  231. return nil, fmt.Errorf("-argon-iterations must be be greater than 0 and no more than %d", uint32(math.MaxUint32))
  232. }
  233. return &Argon2Parameters{
  234. version: rune(params.Version),
  235. Memory: uint32(params.Memory),
  236. Parallelism: uint8(params.Parallelism),
  237. Iterations: uint32(params.Iterations),
  238. salt: params.Salt,
  239. }, nil
  240. }
  241. // DecryptAndUnmarshalEd25519PrivateKey will try to pem decode and decrypt an Ed25519 private key with
  242. // the given passphrase, returning any other bytes b or an error on failure
  243. func DecryptAndUnmarshalEd25519PrivateKey(passphrase, b []byte) (ed25519.PrivateKey, []byte, error) {
  244. k, r := pem.Decode(b)
  245. if k == nil {
  246. return nil, r, fmt.Errorf("input did not contain a valid PEM encoded block")
  247. }
  248. if k.Type != EncryptedEd25519PrivateKeyBanner {
  249. return nil, r, fmt.Errorf("bytes did not contain a proper nebula encrypted Ed25519 private key banner")
  250. }
  251. ned, err := UnmarshalNebulaEncryptedData(k.Bytes)
  252. if err != nil {
  253. return nil, r, err
  254. }
  255. var bytes []byte
  256. switch ned.EncryptionMetadata.EncryptionAlgorithm {
  257. case "AES-256-GCM":
  258. bytes, err = aes256Decrypt(passphrase, &ned.EncryptionMetadata.Argon2Parameters, ned.Ciphertext)
  259. if err != nil {
  260. return nil, r, err
  261. }
  262. default:
  263. return nil, r, fmt.Errorf("unsupported encryption algorithm: %s", ned.EncryptionMetadata.EncryptionAlgorithm)
  264. }
  265. if len(bytes) != ed25519.PrivateKeySize {
  266. return nil, r, fmt.Errorf("key was not 64 bytes, is invalid ed25519 private key")
  267. }
  268. return bytes, r, nil
  269. }
  270. // MarshalX25519PublicKey is a simple helper to PEM encode an X25519 public key
  271. func MarshalX25519PublicKey(b []byte) []byte {
  272. return pem.EncodeToMemory(&pem.Block{Type: X25519PublicKeyBanner, Bytes: b})
  273. }
  274. // MarshalEd25519PublicKey is a simple helper to PEM encode an Ed25519 public key
  275. func MarshalEd25519PublicKey(key ed25519.PublicKey) []byte {
  276. return pem.EncodeToMemory(&pem.Block{Type: Ed25519PublicKeyBanner, Bytes: key})
  277. }
  278. // UnmarshalX25519PublicKey will try to pem decode an X25519 public key, returning any other bytes b
  279. // or an error on failure
  280. func UnmarshalX25519PublicKey(b []byte) ([]byte, []byte, error) {
  281. k, r := pem.Decode(b)
  282. if k == nil {
  283. return nil, r, fmt.Errorf("input did not contain a valid PEM encoded block")
  284. }
  285. if k.Type != X25519PublicKeyBanner {
  286. return nil, r, fmt.Errorf("bytes did not contain a proper nebula X25519 public key banner")
  287. }
  288. if len(k.Bytes) != publicKeyLen {
  289. return nil, r, fmt.Errorf("key was not 32 bytes, is invalid X25519 public key")
  290. }
  291. return k.Bytes, r, nil
  292. }
  293. // UnmarshalEd25519PublicKey will try to pem decode an Ed25519 public key, returning any other bytes b
  294. // or an error on failure
  295. func UnmarshalEd25519PublicKey(b []byte) (ed25519.PublicKey, []byte, error) {
  296. k, r := pem.Decode(b)
  297. if k == nil {
  298. return nil, r, fmt.Errorf("input did not contain a valid PEM encoded block")
  299. }
  300. if k.Type != Ed25519PublicKeyBanner {
  301. return nil, r, fmt.Errorf("bytes did not contain a proper nebula Ed25519 public key banner")
  302. }
  303. if len(k.Bytes) != ed25519.PublicKeySize {
  304. return nil, r, fmt.Errorf("key was not 32 bytes, is invalid ed25519 public key")
  305. }
  306. return k.Bytes, r, nil
  307. }
  308. // Sign signs a nebula cert with the provided private key
  309. func (nc *NebulaCertificate) Sign(key ed25519.PrivateKey) error {
  310. b, err := proto.Marshal(nc.getRawDetails())
  311. if err != nil {
  312. return err
  313. }
  314. sig, err := key.Sign(rand.Reader, b, crypto.Hash(0))
  315. if err != nil {
  316. return err
  317. }
  318. nc.Signature = sig
  319. return nil
  320. }
  321. // CheckSignature verifies the signature against the provided public key
  322. func (nc *NebulaCertificate) CheckSignature(key ed25519.PublicKey) bool {
  323. b, err := proto.Marshal(nc.getRawDetails())
  324. if err != nil {
  325. return false
  326. }
  327. return ed25519.Verify(key, b, nc.Signature)
  328. }
  329. // Expired will return true if the nebula cert is too young or too old compared to the provided time, otherwise false
  330. func (nc *NebulaCertificate) Expired(t time.Time) bool {
  331. return nc.Details.NotBefore.After(t) || nc.Details.NotAfter.Before(t)
  332. }
  333. // Verify will ensure a certificate is good in all respects (expiry, group membership, signature, cert blocklist, etc)
  334. func (nc *NebulaCertificate) Verify(t time.Time, ncp *NebulaCAPool) (bool, error) {
  335. if ncp.IsBlocklisted(nc) {
  336. return false, fmt.Errorf("certificate has been blocked")
  337. }
  338. signer, err := ncp.GetCAForCert(nc)
  339. if err != nil {
  340. return false, err
  341. }
  342. if signer.Expired(t) {
  343. return false, fmt.Errorf("root certificate is expired")
  344. }
  345. if nc.Expired(t) {
  346. return false, fmt.Errorf("certificate is expired")
  347. }
  348. if !nc.CheckSignature(signer.Details.PublicKey) {
  349. return false, fmt.Errorf("certificate signature did not match")
  350. }
  351. if err := nc.CheckRootConstrains(signer); err != nil {
  352. return false, err
  353. }
  354. return true, nil
  355. }
  356. // CheckRootConstrains returns an error if the certificate violates constraints set on the root (groups, ips, subnets)
  357. func (nc *NebulaCertificate) CheckRootConstrains(signer *NebulaCertificate) error {
  358. // Make sure this cert wasn't valid before the root
  359. if signer.Details.NotAfter.Before(nc.Details.NotAfter) {
  360. return fmt.Errorf("certificate expires after signing certificate")
  361. }
  362. // Make sure this cert isn't valid after the root
  363. if signer.Details.NotBefore.After(nc.Details.NotBefore) {
  364. return fmt.Errorf("certificate is valid before the signing certificate")
  365. }
  366. // If the signer has a limited set of groups make sure the cert only contains a subset
  367. if len(signer.Details.InvertedGroups) > 0 {
  368. for _, g := range nc.Details.Groups {
  369. if _, ok := signer.Details.InvertedGroups[g]; !ok {
  370. return fmt.Errorf("certificate contained a group not present on the signing ca: %s", g)
  371. }
  372. }
  373. }
  374. // If the signer has a limited set of ip ranges to issue from make sure the cert only contains a subset
  375. if len(signer.Details.Ips) > 0 {
  376. for _, ip := range nc.Details.Ips {
  377. if !netMatch(ip, signer.Details.Ips) {
  378. return fmt.Errorf("certificate contained an ip assignment outside the limitations of the signing ca: %s", ip.String())
  379. }
  380. }
  381. }
  382. // If the signer has a limited set of subnet ranges to issue from make sure the cert only contains a subset
  383. if len(signer.Details.Subnets) > 0 {
  384. for _, subnet := range nc.Details.Subnets {
  385. if !netMatch(subnet, signer.Details.Subnets) {
  386. return fmt.Errorf("certificate contained a subnet assignment outside the limitations of the signing ca: %s", subnet)
  387. }
  388. }
  389. }
  390. return nil
  391. }
  392. // VerifyPrivateKey checks that the public key in the Nebula certificate and a supplied private key match
  393. func (nc *NebulaCertificate) VerifyPrivateKey(key []byte) error {
  394. if nc.Details.IsCA {
  395. // the call to PublicKey below will panic slice bounds out of range otherwise
  396. if len(key) != ed25519.PrivateKeySize {
  397. return fmt.Errorf("key was not 64 bytes, is invalid ed25519 private key")
  398. }
  399. if !ed25519.PublicKey(nc.Details.PublicKey).Equal(ed25519.PrivateKey(key).Public()) {
  400. return fmt.Errorf("public key in cert and private key supplied don't match")
  401. }
  402. return nil
  403. }
  404. pub, err := curve25519.X25519(key, curve25519.Basepoint)
  405. if err != nil {
  406. return err
  407. }
  408. if !bytes.Equal(pub, nc.Details.PublicKey) {
  409. return fmt.Errorf("public key in cert and private key supplied don't match")
  410. }
  411. return nil
  412. }
  413. // String will return a pretty printed representation of a nebula cert
  414. func (nc *NebulaCertificate) String() string {
  415. if nc == nil {
  416. return "NebulaCertificate {}\n"
  417. }
  418. s := "NebulaCertificate {\n"
  419. s += "\tDetails {\n"
  420. s += fmt.Sprintf("\t\tName: %v\n", nc.Details.Name)
  421. if len(nc.Details.Ips) > 0 {
  422. s += "\t\tIps: [\n"
  423. for _, ip := range nc.Details.Ips {
  424. s += fmt.Sprintf("\t\t\t%v\n", ip.String())
  425. }
  426. s += "\t\t]\n"
  427. } else {
  428. s += "\t\tIps: []\n"
  429. }
  430. if len(nc.Details.Subnets) > 0 {
  431. s += "\t\tSubnets: [\n"
  432. for _, ip := range nc.Details.Subnets {
  433. s += fmt.Sprintf("\t\t\t%v\n", ip.String())
  434. }
  435. s += "\t\t]\n"
  436. } else {
  437. s += "\t\tSubnets: []\n"
  438. }
  439. if len(nc.Details.Groups) > 0 {
  440. s += "\t\tGroups: [\n"
  441. for _, g := range nc.Details.Groups {
  442. s += fmt.Sprintf("\t\t\t\"%v\"\n", g)
  443. }
  444. s += "\t\t]\n"
  445. } else {
  446. s += "\t\tGroups: []\n"
  447. }
  448. s += fmt.Sprintf("\t\tNot before: %v\n", nc.Details.NotBefore)
  449. s += fmt.Sprintf("\t\tNot After: %v\n", nc.Details.NotAfter)
  450. s += fmt.Sprintf("\t\tIs CA: %v\n", nc.Details.IsCA)
  451. s += fmt.Sprintf("\t\tIssuer: %s\n", nc.Details.Issuer)
  452. s += fmt.Sprintf("\t\tPublic key: %x\n", nc.Details.PublicKey)
  453. s += "\t}\n"
  454. fp, err := nc.Sha256Sum()
  455. if err == nil {
  456. s += fmt.Sprintf("\tFingerprint: %s\n", fp)
  457. }
  458. s += fmt.Sprintf("\tSignature: %x\n", nc.Signature)
  459. s += "}"
  460. return s
  461. }
  462. // getRawDetails marshals the raw details into protobuf ready struct
  463. func (nc *NebulaCertificate) getRawDetails() *RawNebulaCertificateDetails {
  464. rd := &RawNebulaCertificateDetails{
  465. Name: nc.Details.Name,
  466. Groups: nc.Details.Groups,
  467. NotBefore: nc.Details.NotBefore.Unix(),
  468. NotAfter: nc.Details.NotAfter.Unix(),
  469. PublicKey: make([]byte, len(nc.Details.PublicKey)),
  470. IsCA: nc.Details.IsCA,
  471. }
  472. for _, ipNet := range nc.Details.Ips {
  473. rd.Ips = append(rd.Ips, ip2int(ipNet.IP), ip2int(ipNet.Mask))
  474. }
  475. for _, ipNet := range nc.Details.Subnets {
  476. rd.Subnets = append(rd.Subnets, ip2int(ipNet.IP), ip2int(ipNet.Mask))
  477. }
  478. copy(rd.PublicKey, nc.Details.PublicKey[:])
  479. // I know, this is terrible
  480. rd.Issuer, _ = hex.DecodeString(nc.Details.Issuer)
  481. return rd
  482. }
  483. // Marshal will marshal a nebula cert into a protobuf byte array
  484. func (nc *NebulaCertificate) Marshal() ([]byte, error) {
  485. rc := RawNebulaCertificate{
  486. Details: nc.getRawDetails(),
  487. Signature: nc.Signature,
  488. }
  489. return proto.Marshal(&rc)
  490. }
  491. // MarshalToPEM will marshal a nebula cert into a protobuf byte array and pem encode the result
  492. func (nc *NebulaCertificate) MarshalToPEM() ([]byte, error) {
  493. b, err := nc.Marshal()
  494. if err != nil {
  495. return nil, err
  496. }
  497. return pem.EncodeToMemory(&pem.Block{Type: CertBanner, Bytes: b}), nil
  498. }
  499. // Sha256Sum calculates a sha-256 sum of the marshaled certificate
  500. func (nc *NebulaCertificate) Sha256Sum() (string, error) {
  501. b, err := nc.Marshal()
  502. if err != nil {
  503. return "", err
  504. }
  505. sum := sha256.Sum256(b)
  506. return hex.EncodeToString(sum[:]), nil
  507. }
  508. func (nc *NebulaCertificate) MarshalJSON() ([]byte, error) {
  509. toString := func(ips []*net.IPNet) []string {
  510. s := []string{}
  511. for _, ip := range ips {
  512. s = append(s, ip.String())
  513. }
  514. return s
  515. }
  516. fp, _ := nc.Sha256Sum()
  517. jc := m{
  518. "details": m{
  519. "name": nc.Details.Name,
  520. "ips": toString(nc.Details.Ips),
  521. "subnets": toString(nc.Details.Subnets),
  522. "groups": nc.Details.Groups,
  523. "notBefore": nc.Details.NotBefore,
  524. "notAfter": nc.Details.NotAfter,
  525. "publicKey": fmt.Sprintf("%x", nc.Details.PublicKey),
  526. "isCa": nc.Details.IsCA,
  527. "issuer": nc.Details.Issuer,
  528. },
  529. "fingerprint": fp,
  530. "signature": fmt.Sprintf("%x", nc.Signature),
  531. }
  532. return json.Marshal(jc)
  533. }
  534. //func (nc *NebulaCertificate) Copy() *NebulaCertificate {
  535. // r, err := nc.Marshal()
  536. // if err != nil {
  537. // //TODO
  538. // return nil
  539. // }
  540. //
  541. // c, err := UnmarshalNebulaCertificate(r)
  542. // return c
  543. //}
  544. func (nc *NebulaCertificate) Copy() *NebulaCertificate {
  545. c := &NebulaCertificate{
  546. Details: NebulaCertificateDetails{
  547. Name: nc.Details.Name,
  548. Groups: make([]string, len(nc.Details.Groups)),
  549. Ips: make([]*net.IPNet, len(nc.Details.Ips)),
  550. Subnets: make([]*net.IPNet, len(nc.Details.Subnets)),
  551. NotBefore: nc.Details.NotBefore,
  552. NotAfter: nc.Details.NotAfter,
  553. PublicKey: make([]byte, len(nc.Details.PublicKey)),
  554. IsCA: nc.Details.IsCA,
  555. Issuer: nc.Details.Issuer,
  556. InvertedGroups: make(map[string]struct{}, len(nc.Details.InvertedGroups)),
  557. },
  558. Signature: make([]byte, len(nc.Signature)),
  559. }
  560. copy(c.Signature, nc.Signature)
  561. copy(c.Details.Groups, nc.Details.Groups)
  562. copy(c.Details.PublicKey, nc.Details.PublicKey)
  563. for i, p := range nc.Details.Ips {
  564. c.Details.Ips[i] = &net.IPNet{
  565. IP: make(net.IP, len(p.IP)),
  566. Mask: make(net.IPMask, len(p.Mask)),
  567. }
  568. copy(c.Details.Ips[i].IP, p.IP)
  569. copy(c.Details.Ips[i].Mask, p.Mask)
  570. }
  571. for i, p := range nc.Details.Subnets {
  572. c.Details.Subnets[i] = &net.IPNet{
  573. IP: make(net.IP, len(p.IP)),
  574. Mask: make(net.IPMask, len(p.Mask)),
  575. }
  576. copy(c.Details.Subnets[i].IP, p.IP)
  577. copy(c.Details.Subnets[i].Mask, p.Mask)
  578. }
  579. for g := range nc.Details.InvertedGroups {
  580. c.Details.InvertedGroups[g] = struct{}{}
  581. }
  582. return c
  583. }
  584. func netMatch(certIp *net.IPNet, rootIps []*net.IPNet) bool {
  585. for _, net := range rootIps {
  586. if net.Contains(certIp.IP) && maskContains(net.Mask, certIp.Mask) {
  587. return true
  588. }
  589. }
  590. return false
  591. }
  592. func maskContains(caMask, certMask net.IPMask) bool {
  593. caM := maskTo4(caMask)
  594. cM := maskTo4(certMask)
  595. // Make sure forcing to ipv4 didn't nuke us
  596. if caM == nil || cM == nil {
  597. return false
  598. }
  599. // Make sure the cert mask is not greater than the ca mask
  600. for i := 0; i < len(caMask); i++ {
  601. if caM[i] > cM[i] {
  602. return false
  603. }
  604. }
  605. return true
  606. }
  607. func maskTo4(ip net.IPMask) net.IPMask {
  608. if len(ip) == net.IPv4len {
  609. return ip
  610. }
  611. if len(ip) == net.IPv6len && isZeros(ip[0:10]) && ip[10] == 0xff && ip[11] == 0xff {
  612. return ip[12:16]
  613. }
  614. return nil
  615. }
  616. func isZeros(b []byte) bool {
  617. for i := 0; i < len(b); i++ {
  618. if b[i] != 0 {
  619. return false
  620. }
  621. }
  622. return true
  623. }
  624. func ip2int(ip []byte) uint32 {
  625. if len(ip) == 16 {
  626. return binary.BigEndian.Uint32(ip[12:16])
  627. }
  628. return binary.BigEndian.Uint32(ip)
  629. }
  630. func int2ip(nn uint32) net.IP {
  631. ip := make(net.IP, net.IPv4len)
  632. binary.BigEndian.PutUint32(ip, nn)
  633. return ip
  634. }