cert_v1.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. package cert
  2. import (
  3. "bytes"
  4. "crypto/ecdh"
  5. "crypto/ecdsa"
  6. "crypto/ed25519"
  7. "crypto/elliptic"
  8. "crypto/sha256"
  9. "encoding/binary"
  10. "encoding/hex"
  11. "encoding/json"
  12. "encoding/pem"
  13. "fmt"
  14. "net"
  15. "net/netip"
  16. "time"
  17. "golang.org/x/crypto/curve25519"
  18. "google.golang.org/protobuf/proto"
  19. )
  20. const publicKeyLen = 32
  21. type certificateV1 struct {
  22. details detailsV1
  23. signature []byte
  24. }
  25. type detailsV1 struct {
  26. name string
  27. networks []netip.Prefix
  28. unsafeNetworks []netip.Prefix
  29. groups []string
  30. notBefore time.Time
  31. notAfter time.Time
  32. publicKey []byte
  33. isCA bool
  34. issuer string
  35. curve Curve
  36. }
  37. type m = map[string]any
  38. func (c *certificateV1) Version() Version {
  39. return Version1
  40. }
  41. func (c *certificateV1) Curve() Curve {
  42. return c.details.curve
  43. }
  44. func (c *certificateV1) Groups() []string {
  45. return c.details.groups
  46. }
  47. func (c *certificateV1) IsCA() bool {
  48. return c.details.isCA
  49. }
  50. func (c *certificateV1) Issuer() string {
  51. return c.details.issuer
  52. }
  53. func (c *certificateV1) Name() string {
  54. return c.details.name
  55. }
  56. func (c *certificateV1) Networks() []netip.Prefix {
  57. return c.details.networks
  58. }
  59. func (c *certificateV1) NotAfter() time.Time {
  60. return c.details.notAfter
  61. }
  62. func (c *certificateV1) NotBefore() time.Time {
  63. return c.details.notBefore
  64. }
  65. func (c *certificateV1) PublicKey() []byte {
  66. return c.details.publicKey
  67. }
  68. func (c *certificateV1) Signature() []byte {
  69. return c.signature
  70. }
  71. func (c *certificateV1) UnsafeNetworks() []netip.Prefix {
  72. return c.details.unsafeNetworks
  73. }
  74. func (c *certificateV1) Fingerprint() (string, error) {
  75. b, err := c.Marshal()
  76. if err != nil {
  77. return "", err
  78. }
  79. sum := sha256.Sum256(b)
  80. return hex.EncodeToString(sum[:]), nil
  81. }
  82. func (c *certificateV1) CheckSignature(key []byte) bool {
  83. b, err := proto.Marshal(c.getRawDetails())
  84. if err != nil {
  85. return false
  86. }
  87. switch c.details.curve {
  88. case Curve_CURVE25519:
  89. return ed25519.Verify(key, b, c.signature)
  90. case Curve_P256:
  91. pubKey, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), key)
  92. if err != nil {
  93. return false
  94. }
  95. hashed := sha256.Sum256(b)
  96. return ecdsa.VerifyASN1(pubKey, hashed[:], c.signature)
  97. default:
  98. return false
  99. }
  100. }
  101. func (c *certificateV1) Expired(t time.Time) bool {
  102. return c.details.notBefore.After(t) || c.details.notAfter.Before(t)
  103. }
  104. func (c *certificateV1) VerifyPrivateKey(curve Curve, key []byte) error {
  105. if curve != c.details.curve {
  106. return fmt.Errorf("curve in cert and private key supplied don't match")
  107. }
  108. if c.details.isCA {
  109. switch curve {
  110. case Curve_CURVE25519:
  111. // the call to PublicKey below will panic slice bounds out of range otherwise
  112. if len(key) != ed25519.PrivateKeySize {
  113. return fmt.Errorf("key was not 64 bytes, is invalid ed25519 private key")
  114. }
  115. if !ed25519.PublicKey(c.details.publicKey).Equal(ed25519.PrivateKey(key).Public()) {
  116. return fmt.Errorf("public key in cert and private key supplied don't match")
  117. }
  118. case Curve_P256:
  119. privkey, err := ecdh.P256().NewPrivateKey(key)
  120. if err != nil {
  121. return fmt.Errorf("cannot parse private key as P256: %w", err)
  122. }
  123. pub := privkey.PublicKey().Bytes()
  124. if !bytes.Equal(pub, c.details.publicKey) {
  125. return fmt.Errorf("public key in cert and private key supplied don't match")
  126. }
  127. default:
  128. return fmt.Errorf("invalid curve: %s", curve)
  129. }
  130. return nil
  131. }
  132. var pub []byte
  133. switch curve {
  134. case Curve_CURVE25519:
  135. var err error
  136. pub, err = curve25519.X25519(key, curve25519.Basepoint)
  137. if err != nil {
  138. return err
  139. }
  140. case Curve_P256:
  141. privkey, err := ecdh.P256().NewPrivateKey(key)
  142. if err != nil {
  143. return err
  144. }
  145. pub = privkey.PublicKey().Bytes()
  146. default:
  147. return fmt.Errorf("invalid curve: %s", curve)
  148. }
  149. if !bytes.Equal(pub, c.details.publicKey) {
  150. return fmt.Errorf("public key in cert and private key supplied don't match")
  151. }
  152. return nil
  153. }
  154. // getRawDetails marshals the raw details into protobuf ready struct
  155. func (c *certificateV1) getRawDetails() *RawNebulaCertificateDetails {
  156. rd := &RawNebulaCertificateDetails{
  157. Name: c.details.name,
  158. Groups: c.details.groups,
  159. NotBefore: c.details.notBefore.Unix(),
  160. NotAfter: c.details.notAfter.Unix(),
  161. PublicKey: make([]byte, len(c.details.publicKey)),
  162. IsCA: c.details.isCA,
  163. Curve: c.details.curve,
  164. }
  165. for _, ipNet := range c.details.networks {
  166. mask := net.CIDRMask(ipNet.Bits(), ipNet.Addr().BitLen())
  167. rd.Ips = append(rd.Ips, addr2int(ipNet.Addr()), ip2int(mask))
  168. }
  169. for _, ipNet := range c.details.unsafeNetworks {
  170. mask := net.CIDRMask(ipNet.Bits(), ipNet.Addr().BitLen())
  171. rd.Subnets = append(rd.Subnets, addr2int(ipNet.Addr()), ip2int(mask))
  172. }
  173. copy(rd.PublicKey, c.details.publicKey[:])
  174. // I know, this is terrible
  175. rd.Issuer, _ = hex.DecodeString(c.details.issuer)
  176. return rd
  177. }
  178. func (c *certificateV1) String() string {
  179. b, err := json.MarshalIndent(c.marshalJSON(), "", "\t")
  180. if err != nil {
  181. return fmt.Sprintf("<error marshalling certificate: %v>", err)
  182. }
  183. return string(b)
  184. }
  185. func (c *certificateV1) MarshalForHandshakes() ([]byte, error) {
  186. pubKey := c.details.publicKey
  187. c.details.publicKey = nil
  188. rawCertNoKey, err := c.Marshal()
  189. if err != nil {
  190. return nil, err
  191. }
  192. c.details.publicKey = pubKey
  193. return rawCertNoKey, nil
  194. }
  195. func (c *certificateV1) Marshal() ([]byte, error) {
  196. rc := RawNebulaCertificate{
  197. Details: c.getRawDetails(),
  198. Signature: c.signature,
  199. }
  200. return proto.Marshal(&rc)
  201. }
  202. func (c *certificateV1) MarshalPEM() ([]byte, error) {
  203. b, err := c.Marshal()
  204. if err != nil {
  205. return nil, err
  206. }
  207. return pem.EncodeToMemory(&pem.Block{Type: CertificateBanner, Bytes: b}), nil
  208. }
  209. func (c *certificateV1) MarshalJSON() ([]byte, error) {
  210. return json.Marshal(c.marshalJSON())
  211. }
  212. func (c *certificateV1) marshalJSON() m {
  213. fp, _ := c.Fingerprint()
  214. return m{
  215. "version": Version1,
  216. "details": m{
  217. "name": c.details.name,
  218. "networks": c.details.networks,
  219. "unsafeNetworks": c.details.unsafeNetworks,
  220. "groups": c.details.groups,
  221. "notBefore": c.details.notBefore,
  222. "notAfter": c.details.notAfter,
  223. "publicKey": fmt.Sprintf("%x", c.details.publicKey),
  224. "isCa": c.details.isCA,
  225. "issuer": c.details.issuer,
  226. "curve": c.details.curve.String(),
  227. },
  228. "fingerprint": fp,
  229. "signature": fmt.Sprintf("%x", c.Signature()),
  230. }
  231. }
  232. func (c *certificateV1) Copy() Certificate {
  233. nc := &certificateV1{
  234. details: detailsV1{
  235. name: c.details.name,
  236. notBefore: c.details.notBefore,
  237. notAfter: c.details.notAfter,
  238. publicKey: make([]byte, len(c.details.publicKey)),
  239. isCA: c.details.isCA,
  240. issuer: c.details.issuer,
  241. curve: c.details.curve,
  242. },
  243. signature: make([]byte, len(c.signature)),
  244. }
  245. if c.details.groups != nil {
  246. nc.details.groups = make([]string, len(c.details.groups))
  247. copy(nc.details.groups, c.details.groups)
  248. }
  249. if c.details.networks != nil {
  250. nc.details.networks = make([]netip.Prefix, len(c.details.networks))
  251. copy(nc.details.networks, c.details.networks)
  252. }
  253. if c.details.unsafeNetworks != nil {
  254. nc.details.unsafeNetworks = make([]netip.Prefix, len(c.details.unsafeNetworks))
  255. copy(nc.details.unsafeNetworks, c.details.unsafeNetworks)
  256. }
  257. copy(nc.signature, c.signature)
  258. copy(nc.details.publicKey, c.details.publicKey)
  259. return nc
  260. }
  261. func (c *certificateV1) fromTBSCertificate(t *TBSCertificate) error {
  262. c.details = detailsV1{
  263. name: t.Name,
  264. networks: t.Networks,
  265. unsafeNetworks: t.UnsafeNetworks,
  266. groups: t.Groups,
  267. notBefore: t.NotBefore,
  268. notAfter: t.NotAfter,
  269. publicKey: t.PublicKey,
  270. isCA: t.IsCA,
  271. curve: t.Curve,
  272. issuer: t.issuer,
  273. }
  274. return c.validate()
  275. }
  276. func (c *certificateV1) validate() error {
  277. // Empty names are allowed
  278. if len(c.details.publicKey) == 0 {
  279. return ErrInvalidPublicKey
  280. }
  281. // Original v1 rules allowed multiple networks to be present but ignored all but the first one.
  282. // Continue to allow this behavior
  283. if !c.details.isCA && len(c.details.networks) == 0 {
  284. return NewErrInvalidCertificateProperties("non-CA certificates must contain exactly one network")
  285. }
  286. for _, network := range c.details.networks {
  287. if !network.IsValid() || !network.Addr().IsValid() {
  288. return NewErrInvalidCertificateProperties("invalid network: %s", network)
  289. }
  290. if network.Addr().Is6() {
  291. return NewErrInvalidCertificateProperties("certificate may not contain IPv6 networks: %v", network)
  292. }
  293. if network.Addr().IsUnspecified() {
  294. return NewErrInvalidCertificateProperties("non-CA certificates must not use the zero address as a network: %s", network)
  295. }
  296. if network.Addr().Zone() != "" {
  297. return NewErrInvalidCertificateProperties("networks may not contain zones: %s", network)
  298. }
  299. }
  300. for _, network := range c.details.unsafeNetworks {
  301. if !network.IsValid() || !network.Addr().IsValid() {
  302. return NewErrInvalidCertificateProperties("invalid unsafe network: %s", network)
  303. }
  304. if network.Addr().Is6() {
  305. return NewErrInvalidCertificateProperties("certificate may not contain IPv6 unsafe networks: %v", network)
  306. }
  307. if network.Addr().Zone() != "" {
  308. return NewErrInvalidCertificateProperties("unsafe networks may not contain zones: %s", network)
  309. }
  310. }
  311. // v1 doesn't bother with sort order or uniqueness of networks or unsafe networks.
  312. // We can't modify the unmarshalled data because verification requires re-marshalling and a re-ordered
  313. // unsafe networks would result in a different signature.
  314. return nil
  315. }
  316. func (c *certificateV1) marshalForSigning() ([]byte, error) {
  317. b, err := proto.Marshal(c.getRawDetails())
  318. if err != nil {
  319. return nil, err
  320. }
  321. return b, nil
  322. }
  323. func (c *certificateV1) setSignature(b []byte) error {
  324. if len(b) == 0 {
  325. return ErrEmptySignature
  326. }
  327. c.signature = b
  328. return nil
  329. }
  330. // unmarshalCertificateV1 will unmarshal a protobuf byte representation of a nebula cert
  331. // if the publicKey is provided here then it is not required to be present in `b`
  332. func unmarshalCertificateV1(b []byte, publicKey []byte) (*certificateV1, error) {
  333. if len(b) == 0 {
  334. return nil, fmt.Errorf("nil byte array")
  335. }
  336. var rc RawNebulaCertificate
  337. err := proto.Unmarshal(b, &rc)
  338. if err != nil {
  339. return nil, err
  340. }
  341. if rc.Details == nil {
  342. return nil, fmt.Errorf("encoded Details was nil")
  343. }
  344. if len(rc.Details.Ips)%2 != 0 {
  345. return nil, fmt.Errorf("encoded IPs should be in pairs, an odd number was found")
  346. }
  347. if len(rc.Details.Subnets)%2 != 0 {
  348. return nil, fmt.Errorf("encoded Subnets should be in pairs, an odd number was found")
  349. }
  350. nc := certificateV1{
  351. details: detailsV1{
  352. name: rc.Details.Name,
  353. groups: make([]string, len(rc.Details.Groups)),
  354. networks: make([]netip.Prefix, len(rc.Details.Ips)/2),
  355. unsafeNetworks: make([]netip.Prefix, len(rc.Details.Subnets)/2),
  356. notBefore: time.Unix(rc.Details.NotBefore, 0),
  357. notAfter: time.Unix(rc.Details.NotAfter, 0),
  358. publicKey: make([]byte, len(rc.Details.PublicKey)),
  359. isCA: rc.Details.IsCA,
  360. curve: rc.Details.Curve,
  361. },
  362. signature: make([]byte, len(rc.Signature)),
  363. }
  364. copy(nc.signature, rc.Signature)
  365. copy(nc.details.groups, rc.Details.Groups)
  366. nc.details.issuer = hex.EncodeToString(rc.Details.Issuer)
  367. if len(publicKey) > 0 {
  368. nc.details.publicKey = publicKey
  369. }
  370. copy(nc.details.publicKey, rc.Details.PublicKey)
  371. var ip netip.Addr
  372. for i, rawIp := range rc.Details.Ips {
  373. if i%2 == 0 {
  374. ip = int2addr(rawIp)
  375. } else {
  376. ones, _ := net.IPMask(int2ip(rawIp)).Size()
  377. nc.details.networks[i/2] = netip.PrefixFrom(ip, ones)
  378. }
  379. }
  380. for i, rawIp := range rc.Details.Subnets {
  381. if i%2 == 0 {
  382. ip = int2addr(rawIp)
  383. } else {
  384. ones, _ := net.IPMask(int2ip(rawIp)).Size()
  385. nc.details.unsafeNetworks[i/2] = netip.PrefixFrom(ip, ones)
  386. }
  387. }
  388. err = nc.validate()
  389. if err != nil {
  390. return nil, err
  391. }
  392. return &nc, nil
  393. }
  394. func ip2int(ip []byte) uint32 {
  395. if len(ip) == 16 {
  396. return binary.BigEndian.Uint32(ip[12:16])
  397. }
  398. return binary.BigEndian.Uint32(ip)
  399. }
  400. func int2ip(nn uint32) net.IP {
  401. ip := make(net.IP, net.IPv4len)
  402. binary.BigEndian.PutUint32(ip, nn)
  403. return ip
  404. }
  405. func addr2int(addr netip.Addr) uint32 {
  406. b := addr.Unmap().As4()
  407. return binary.BigEndian.Uint32(b[:])
  408. }
  409. func int2addr(nn uint32) netip.Addr {
  410. ip := [4]byte{}
  411. binary.BigEndian.PutUint32(ip[:], nn)
  412. return netip.AddrFrom4(ip).Unmap()
  413. }