Debian Codegraph @

cert/pem.go

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