pem.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package cert
  2. import (
  3. "bytes"
  4. "encoding/pem"
  5. "errors"
  6. "fmt"
  7. "golang.org/x/crypto/ed25519"
  8. )
  9. var ErrTruncatedPEMBlock = errors.New("truncated PEM block")
  10. // SplitPEM is a split function for bufio.Scanner that returns each PEM block.
  11. func SplitPEM(data []byte, atEOF bool) (advance int, token []byte, err error) {
  12. // Look for the start of a PEM block
  13. start := bytes.Index(data, []byte("-----BEGIN "))
  14. if start == -1 {
  15. if atEOF && len(bytes.TrimSpace(data)) > 0 {
  16. // Non-whitespace content with no PEM block
  17. return 0, nil, ErrTruncatedPEMBlock
  18. }
  19. if atEOF {
  20. return len(data), nil, nil
  21. }
  22. // Request more data
  23. return 0, nil, nil
  24. }
  25. // Look for the end marker
  26. endMarkerStart := bytes.Index(data[start:], []byte("-----END "))
  27. if endMarkerStart == -1 {
  28. if atEOF {
  29. // Incomplete PEM block at EOF
  30. return 0, nil, ErrTruncatedPEMBlock
  31. }
  32. // Need more data to find the end
  33. return 0, nil, nil
  34. }
  35. // Find the actual end of the END line (after the newline)
  36. endMarkerStart += start
  37. endLineEnd := bytes.IndexByte(data[endMarkerStart:], '\n')
  38. var end int
  39. if endLineEnd == -1 {
  40. if atEOF {
  41. // END marker without newline at EOF - take it anyway
  42. end = len(data)
  43. } else {
  44. // Need more data
  45. return 0, nil, nil
  46. }
  47. } else {
  48. end = endMarkerStart + endLineEnd + 1
  49. }
  50. // Extract the PEM block
  51. pemBlock := data[start:end]
  52. // Return the valid PEM block
  53. return end, pemBlock, nil
  54. }
  55. const ( //cert banners
  56. CertificateBanner = "NEBULA CERTIFICATE"
  57. CertificateV2Banner = "NEBULA CERTIFICATE V2"
  58. )
  59. const ( //key-agreement-key banners
  60. X25519PrivateKeyBanner = "NEBULA X25519 PRIVATE KEY"
  61. X25519PublicKeyBanner = "NEBULA X25519 PUBLIC KEY"
  62. P256PrivateKeyBanner = "NEBULA P256 PRIVATE KEY"
  63. P256PublicKeyBanner = "NEBULA P256 PUBLIC KEY"
  64. )
  65. /* including "ECDSA" in the P256 banners is a clue that these keys should be used only for signing */
  66. const ( //signing key banners
  67. EncryptedECDSAP256PrivateKeyBanner = "NEBULA ECDSA P256 ENCRYPTED PRIVATE KEY"
  68. ECDSAP256PrivateKeyBanner = "NEBULA ECDSA P256 PRIVATE KEY"
  69. ECDSAP256PublicKeyBanner = "NEBULA ECDSA P256 PUBLIC KEY"
  70. EncryptedEd25519PrivateKeyBanner = "NEBULA ED25519 ENCRYPTED PRIVATE KEY"
  71. Ed25519PrivateKeyBanner = "NEBULA ED25519 PRIVATE KEY"
  72. Ed25519PublicKeyBanner = "NEBULA ED25519 PUBLIC KEY"
  73. )
  74. // UnmarshalCertificateFromPEM will try to unmarshal the first pem block in a byte array, returning any non consumed
  75. // data or an error on failure
  76. func UnmarshalCertificateFromPEM(b []byte) (Certificate, []byte, error) {
  77. p, r := pem.Decode(b)
  78. if p == nil {
  79. return nil, r, ErrInvalidPEMBlock
  80. }
  81. c, err := unmarshalCertificateBlock(p)
  82. if err != nil {
  83. return nil, r, err
  84. }
  85. return c, r, nil
  86. }
  87. // unmarshalCertificateBlock decodes a single PEM block into a certificate.
  88. // It expects a Nebula certificate banner and returns ErrInvalidPEMCertificateBanner otherwise.
  89. func unmarshalCertificateBlock(block *pem.Block) (Certificate, error) {
  90. switch block.Type {
  91. // Implementations must validate the resulting certificate contains valid information
  92. case CertificateBanner:
  93. return unmarshalCertificateV1(block.Bytes, nil)
  94. case CertificateV2Banner:
  95. return unmarshalCertificateV2(block.Bytes, nil, Curve_CURVE25519)
  96. default:
  97. return nil, ErrInvalidPEMCertificateBanner
  98. }
  99. }
  100. func marshalCertPublicKeyToPEM(c Certificate) []byte {
  101. if c.IsCA() {
  102. return MarshalSigningPublicKeyToPEM(c.Curve(), c.PublicKey())
  103. } else {
  104. return MarshalPublicKeyToPEM(c.Curve(), c.PublicKey())
  105. }
  106. }
  107. // MarshalPublicKeyToPEM returns a PEM representation of a public key used for ECDH.
  108. // if your public key came from a certificate, prefer Certificate.PublicKeyPEM() if possible, to avoid mistakes!
  109. func MarshalPublicKeyToPEM(curve Curve, b []byte) []byte {
  110. switch curve {
  111. case Curve_CURVE25519:
  112. return pem.EncodeToMemory(&pem.Block{Type: X25519PublicKeyBanner, Bytes: b})
  113. case Curve_P256:
  114. return pem.EncodeToMemory(&pem.Block{Type: P256PublicKeyBanner, Bytes: b})
  115. default:
  116. return nil
  117. }
  118. }
  119. // MarshalSigningPublicKeyToPEM returns a PEM representation of a public key used for signing.
  120. // if your public key came from a certificate, prefer Certificate.PublicKeyPEM() if possible, to avoid mistakes!
  121. func MarshalSigningPublicKeyToPEM(curve Curve, b []byte) []byte {
  122. switch curve {
  123. case Curve_CURVE25519:
  124. return pem.EncodeToMemory(&pem.Block{Type: Ed25519PublicKeyBanner, Bytes: b})
  125. case Curve_P256:
  126. return pem.EncodeToMemory(&pem.Block{Type: ECDSAP256PublicKeyBanner, Bytes: b})
  127. default:
  128. return nil
  129. }
  130. }
  131. func UnmarshalPublicKeyFromPEM(b []byte) ([]byte, []byte, Curve, error) {
  132. k, r := pem.Decode(b)
  133. if k == nil {
  134. return nil, r, 0, fmt.Errorf("input did not contain a valid PEM encoded block")
  135. }
  136. var expectedLen int
  137. var curve Curve
  138. switch k.Type {
  139. case X25519PublicKeyBanner, Ed25519PublicKeyBanner:
  140. expectedLen = 32
  141. curve = Curve_CURVE25519
  142. case P256PublicKeyBanner, ECDSAP256PublicKeyBanner:
  143. // Uncompressed
  144. expectedLen = 65
  145. curve = Curve_P256
  146. default:
  147. return nil, r, 0, fmt.Errorf("bytes did not contain a proper public key banner")
  148. }
  149. if len(k.Bytes) != expectedLen {
  150. return nil, r, 0, fmt.Errorf("key was not %d bytes, is invalid %s public key", expectedLen, curve)
  151. }
  152. return k.Bytes, r, curve, nil
  153. }
  154. func MarshalPrivateKeyToPEM(curve Curve, b []byte) []byte {
  155. switch curve {
  156. case Curve_CURVE25519:
  157. return pem.EncodeToMemory(&pem.Block{Type: X25519PrivateKeyBanner, Bytes: b})
  158. case Curve_P256:
  159. return pem.EncodeToMemory(&pem.Block{Type: P256PrivateKeyBanner, Bytes: b})
  160. default:
  161. return nil
  162. }
  163. }
  164. func MarshalSigningPrivateKeyToPEM(curve Curve, b []byte) []byte {
  165. switch curve {
  166. case Curve_CURVE25519:
  167. return pem.EncodeToMemory(&pem.Block{Type: Ed25519PrivateKeyBanner, Bytes: b})
  168. case Curve_P256:
  169. return pem.EncodeToMemory(&pem.Block{Type: ECDSAP256PrivateKeyBanner, Bytes: b})
  170. default:
  171. return nil
  172. }
  173. }
  174. // UnmarshalPrivateKeyFromPEM will try to unmarshal the first pem block in a byte array, returning any non
  175. // consumed data or an error on failure
  176. func UnmarshalPrivateKeyFromPEM(b []byte) ([]byte, []byte, Curve, error) {
  177. k, r := pem.Decode(b)
  178. if k == nil {
  179. return nil, r, 0, fmt.Errorf("input did not contain a valid PEM encoded block")
  180. }
  181. var expectedLen int
  182. var curve Curve
  183. switch k.Type {
  184. case X25519PrivateKeyBanner:
  185. expectedLen = 32
  186. curve = Curve_CURVE25519
  187. case P256PrivateKeyBanner:
  188. expectedLen = 32
  189. curve = Curve_P256
  190. default:
  191. return nil, r, 0, fmt.Errorf("bytes did not contain a proper private key banner")
  192. }
  193. if len(k.Bytes) != expectedLen {
  194. return nil, r, 0, fmt.Errorf("key was not %d bytes, is invalid %s private key", expectedLen, curve)
  195. }
  196. return k.Bytes, r, curve, nil
  197. }
  198. func UnmarshalSigningPrivateKeyFromPEM(b []byte) ([]byte, []byte, Curve, error) {
  199. k, r := pem.Decode(b)
  200. if k == nil {
  201. return nil, r, 0, fmt.Errorf("input did not contain a valid PEM encoded block")
  202. }
  203. var curve Curve
  204. switch k.Type {
  205. case EncryptedEd25519PrivateKeyBanner:
  206. return nil, nil, Curve_CURVE25519, ErrPrivateKeyEncrypted
  207. case EncryptedECDSAP256PrivateKeyBanner:
  208. return nil, nil, Curve_P256, ErrPrivateKeyEncrypted
  209. case Ed25519PrivateKeyBanner:
  210. curve = Curve_CURVE25519
  211. if len(k.Bytes) != ed25519.PrivateKeySize {
  212. return nil, r, 0, fmt.Errorf("key was not %d bytes, is invalid Ed25519 private key", ed25519.PrivateKeySize)
  213. }
  214. case ECDSAP256PrivateKeyBanner:
  215. curve = Curve_P256
  216. if len(k.Bytes) != 32 {
  217. return nil, r, 0, fmt.Errorf("key was not 32 bytes, is invalid ECDSA P256 private key")
  218. }
  219. default:
  220. return nil, r, 0, fmt.Errorf("bytes did not contain a proper Ed25519/ECDSA private key banner")
  221. }
  222. return k.Bytes, r, curve, nil
  223. }