Debian Codegraph @

crypto/pemutil/pem.go

raw symbols SCIP
1 package pemutil
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/ecdsa"
7 "crypto/ed25519"
8 "crypto/elliptic"
9 "crypto/rand"
10 "crypto/rsa"
11 "crypto/x509"
12 "encoding/pem"
13 "fmt"
14 "io/ioutil"
15 "math/big"
16 "os"
17
18 "github.com/pkg/errors"
19 "github.com/smallstep/cli/crypto/keys"
20 "github.com/smallstep/cli/errs"
21 "github.com/smallstep/cli/ui"
22 "github.com/smallstep/cli/utils"
23 "golang.org/x/crypto/ssh"
24 )
25
26 // DefaultEncCipher is the default algorithm used when encrypting sensitive
27 // data in the PEM format.
28 var DefaultEncCipher = x509.PEMCipherAES256
29
30 // context add options to the pem methods.
31 type context struct {
32 filename string
33 perm os.FileMode
34 password []byte
35 pkcs8 bool
36 openSSH bool
37 comment string
38 firstBlock bool
39 }
40
41 // newContext initializes the context with a filename.
42 func newContext(name string) *context {
43 return &context{
44 filename: name,
45 perm: 0600,
46 }
47 }
48
49 // apply the context options and return the first error if exists.
50 func (c *context) apply(opts []Options) error {
51 for _, fn := range opts {
52 if err := fn(c); err != nil {
53 return err
54 }
55 }
56 return nil
57 }
58
59 // Options is the type to add attributes to the context.
60 type Options func(o *context) error
61
62 // withContext replaces the context with the given one.
63 func withContext(c *context) Options {
64 return func(ctx *context) error {
65 *ctx = *c
66 return nil
67 }
68 }
69
70 // WithFilename is a method that adds the given filename to the context.
71 func WithFilename(name string) Options {
72 return func(ctx *context) error {
73 ctx.filename = name
74 // Default perm mode if not set
75 if ctx.perm == 0 {
76 ctx.perm = 0600
77 }
78 return nil
79 }
80 }
81
82 // ToFile is a method that adds the given filename and permissions to the
83 // context. It is used in the Serialize to store PEM in disk.
84 func ToFile(name string, perm os.FileMode) Options {
85 return func(ctx *context) error {
86 ctx.filename = name
87 ctx.perm = perm
88 return nil
89 }
90 }
91
92 // WithPassword is a method that adds the given password to the context.
93 func WithPassword(pass []byte) Options {
94 return func(ctx *context) error {
95 ctx.password = pass
96 return nil
97 }
98 }
99
100 // WithPasswordFile is a method that adds the password in a file to the context.
101 func WithPasswordFile(filename string) Options {
102 return func(ctx *context) error {
103 b, err := utils.ReadPasswordFromFile(filename)
104 if err != nil {
105 return err
106 }
107 ctx.password = b
108 return nil
109 }
110 }
111
112 // WithPasswordPrompt ask the user for a password and adds it to the context.
113 func WithPasswordPrompt(prompt string) Options {
114 return func(ctx *context) error {
115 b, err := ui.PromptPassword(prompt, ui.WithValidateNotEmpty())
116 if err != nil {
117 return err
118 }
119 ctx.password = b
120 return nil
121 }
122 }
123
124 // WithPKCS8 with v set to true returns an option used in the Serialize method
125 // to use the PKCS#8 encoding form on the private keys. With v set to false
126 // default form will be used.
127 func WithPKCS8(v bool) Options {
128 return func(ctx *context) error {
129 ctx.pkcs8 = v
130 return nil
131 }
132 }
133
134 // WithOpenSSH is an option used in the Serialize method to use OpenSSH encoding
135 // form on the private keys. With v set to false default form will be used.
136 func WithOpenSSH(v bool) Options {
137 return func(ctx *context) error {
138 ctx.openSSH = v
139 return nil
140 }
141 }
142
143 // WithComment is an option used in the Serialize method to add a comment in the
144 // OpenSSH private keys. WithOpenSSH must be set to true too.
145 func WithComment(comment string) Options {
146 return func(ctx *context) error {
147 ctx.comment = comment
148 return nil
149 }
150 }
151
152 // WithFirstBlock will avoid failing if a PEM contains more than one block or
153 // certificate and it will only look at the first.
154 func WithFirstBlock() Options {
155 return func(ctx *context) error {
156 ctx.firstBlock = true
157 return nil
158 }
159 }
160
161 // ReadCertificate returns a *x509.Certificate from the given filename. It
162 // supports certificates formats PEM and DER.
163 func ReadCertificate(filename string, opts ...Options) (*x509.Certificate, error) {
164 b, err := ioutil.ReadFile(filename)
165 if err != nil {
166 return nil, errs.FileError(err, filename)
167 }
168
169 // PEM format
170 if bytes.HasPrefix(b, []byte("-----BEGIN ")) {
171 var crt interface{}
172 crt, err = Read(filename, opts...)
173 if err != nil {
174 return nil, err
175 }
176 switch crt := crt.(type) {
177 case *x509.Certificate:
178 return crt, nil
179 default:
180 return nil, errors.Errorf("error decoding PEM: file '%s' does not contain a certificate", filename)
181 }
182 }
183
184 // DER format (binary)
185 crt, err := x509.ParseCertificate(b)
186 return crt, errors.Wrapf(err, "error parsing %s", filename)
187 }
188
189 // ReadCertificateBundle returns a list of *x509.Certificate from the given
190 // filename. It supports certificates formats PEM and DER. If a DER-formatted
191 // file is given only one certificate will be returned.
192 func ReadCertificateBundle(filename string) ([]*x509.Certificate, error) {
193 b, err := ioutil.ReadFile(filename)
194 if err != nil {
195 return nil, errs.FileError(err, filename)
196 }
197
198 // PEM format
199 if bytes.HasPrefix(b, []byte("-----BEGIN ")) {
200 var block *pem.Block
201 var bundle []*x509.Certificate
202 for len(b) > 0 {
203 block, b = pem.Decode(b)
204 if block == nil {
205 break
206 }
207 if block.Type != "CERTIFICATE" {
208 return nil, errors.Errorf("error decoding PEM: file '%s' is not a certificate bundle", filename)
209 }
210 var crt *x509.Certificate
211 crt, err = x509.ParseCertificate(block.Bytes)
212 if err != nil {
213 return nil, errors.Wrapf(err, "error parsing %s", filename)
214 }
215 bundle = append(bundle, crt)
216 }
217 if len(b) > 0 {
218 return nil, errors.Errorf("error decoding PEM: file '%s' contains unexpected data", filename)
219 }
220 return bundle, nil
221 }
222
223 // DER format (binary)
224 crt, err := x509.ParseCertificate(b)
225 if err != nil {
226 return nil, errors.Wrapf(err, "error parsing %s", filename)
227 }
228 return []*x509.Certificate{crt}, nil
229 }
230
231 // Parse returns the key or certificate PEM-encoded in the given bytes.
232 func Parse(b []byte, opts ...Options) (interface{}, error) {
233 // Populate options
234 ctx := newContext("PEM")
235 if err := ctx.apply(opts); err != nil {
236 return nil, err
237 }
238
239 block, rest := pem.Decode(b)
240 switch {
241 case block == nil:
242 return nil, errors.Errorf("error decoding %s: not a valid PEM encoded block", ctx.filename)
243 case len(rest) > 0 && !ctx.firstBlock:
244 return nil, errors.Errorf("error decoding %s: contains more than one PEM encoded block", ctx.filename)
245 }
246
247 // PEM is encrypted: ask for password
248 if block.Headers["Proc-Type"] == "4,ENCRYPTED" || block.Type == "ENCRYPTED PRIVATE KEY" {
249 var err error
250 var pass []byte
251
252 if len(ctx.password) > 0 {
253 pass = ctx.password
254 } else {
255 pass, err = ui.PromptPassword(fmt.Sprintf("Please enter the password to decrypt %s", ctx.filename))
256 if err != nil {
257 return nil, err
258 }
259 }
260
261 block.Bytes, err = DecryptPEMBlock(block, pass)
262 if err != nil {
263 return nil, errors.Wrapf(err, "error decrypting %s", ctx.filename)
264 }
265 }
266
267 switch block.Type {
268 case "PUBLIC KEY":
269 pub, err := ParsePKIXPublicKey(block.Bytes)
270 return pub, errors.Wrapf(err, "error parsing %s", ctx.filename)
271 case "RSA PRIVATE KEY":
272 priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
273 return priv, errors.Wrapf(err, "error parsing %s", ctx.filename)
274 case "EC PRIVATE KEY":
275 priv, err := x509.ParseECPrivateKey(block.Bytes)
276 return priv, errors.Wrapf(err, "error parsing %s", ctx.filename)
277 case "PRIVATE KEY", "ENCRYPTED PRIVATE KEY":
278 priv, err := ParsePKCS8PrivateKey(block.Bytes)
279 return priv, errors.Wrapf(err, "error parsing %s", ctx.filename)
280 case "OPENSSH PRIVATE KEY":
281 priv, err := ParseOpenSSHPrivateKey(block.Bytes, withContext(ctx))
282 return priv, errors.Wrapf(err, "error parsing %s", ctx.filename)
283 case "CERTIFICATE":
284 crt, err := x509.ParseCertificate(block.Bytes)
285 return crt, errors.Wrapf(err, "error parsing %s", ctx.filename)
286 case "CERTIFICATE REQUEST", "NEW CERTIFICATE REQUEST":
287 csr, err := x509.ParseCertificateRequest(block.Bytes)
288 return csr, errors.Wrapf(err, "error parsing %s", ctx.filename)
289 default:
290 return nil, errors.Errorf("error decoding %s: contains an unexpected header '%s'", ctx.filename, block.Type)
291 }
292 }
293
294 // ParseKey returns the key or the public key of a certificate or certificate
295 // signing request in the given PEM-encoded bytes.
296 func ParseKey(b []byte, opts ...Options) (interface{}, error) {
297 k, err := Parse(b, opts...)
298 if err != nil {
299 return nil, err
300 }
301 return keys.ExtractKey(k)
302 }
303
304 // Read returns the key or certificate encoded in the given PEM file.
305 // If the file is encrypted it will ask for a password and it will try
306 // to decrypt it.
307 //
308 // Supported keys algorithms are RSA and EC. Supported standards for private
309 // keys are PKCS#1, PKCS#8, RFC5915 for EC, and base64-encoded DER for
310 // certificates and public keys.
311 func Read(filename string, opts ...Options) (interface{}, error) {
312 b, err := ioutil.ReadFile(filename)
313 if err != nil {
314 return nil, errs.FileError(err, filename)
315 }
316
317 // force given filename
318 opts = append(opts, WithFilename(filename))
319 return Parse(b, opts...)
320 }
321
322 // Serialize will serialize the input to a PEM formatted block and apply
323 // modifiers.
324 func Serialize(in interface{}, opts ...Options) (*pem.Block, error) {
325 ctx := new(context)
326 if err := ctx.apply(opts); err != nil {
327 return nil, err
328 }
329
330 var p *pem.Block
331 switch k := in.(type) {
332 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
333 b, err := MarshalPKIXPublicKey(k)
334 if err != nil {
335 return nil, errors.WithStack(err)
336 }
337 p = &pem.Block{
338 Type: "PUBLIC KEY",
339 Bytes: b,
340 }
341 case *rsa.PrivateKey:
342 switch {
343 case ctx.pkcs8:
344 b, err := MarshalPKCS8PrivateKey(k)
345 if err != nil {
346 return nil, err
347 }
348 p = &pem.Block{
349 Type: "PRIVATE KEY",
350 Bytes: b,
351 }
352 case ctx.openSSH:
353 return SerializeOpenSSHPrivateKey(k, withContext(ctx))
354 default:
355 p = &pem.Block{
356 Type: "RSA PRIVATE KEY",
357 Bytes: x509.MarshalPKCS1PrivateKey(k),
358 }
359 }
360 case *ecdsa.PrivateKey:
361 switch {
362 case ctx.pkcs8:
363 b, err := MarshalPKCS8PrivateKey(k)
364 if err != nil {
365 return nil, err
366 }
367 p = &pem.Block{
368 Type: "PRIVATE KEY",
369 Bytes: b,
370 }
371 case ctx.openSSH:
372 return SerializeOpenSSHPrivateKey(k, withContext(ctx))
373 default:
374 b, err := x509.MarshalECPrivateKey(k)
375 if err != nil {
376 return nil, errors.Wrap(err, "failed to marshal private key")
377 }
378 p = &pem.Block{
379 Type: "EC PRIVATE KEY",
380 Bytes: b,
381 }
382 }
383 case ed25519.PrivateKey:
384 switch {
385 case !ctx.pkcs8 && ctx.openSSH:
386 return SerializeOpenSSHPrivateKey(k, withContext(ctx))
387 default: // Ed25519 keys will use pkcs8 by default
388 ctx.pkcs8 = true
389 b, err := MarshalPKCS8PrivateKey(k)
390 if err != nil {
391 return nil, err
392 }
393 p = &pem.Block{
394 Type: "PRIVATE KEY",
395 Bytes: b,
396 }
397 }
398 case *x509.Certificate:
399 p = &pem.Block{
400 Type: "CERTIFICATE",
401 Bytes: k.Raw,
402 }
403 case *x509.CertificateRequest:
404 p = &pem.Block{
405 Type: "CERTIFICATE REQUEST",
406 Bytes: k.Raw,
407 }
408 default:
409 return nil, errors.Errorf("cannot serialize type '%T', value '%v'", k, k)
410 }
411
412 // Apply options on the PEM blocks.
413 if ctx.password != nil {
414 if _, ok := in.(crypto.PrivateKey); ok && ctx.pkcs8 {
415 var err error
416 p, err = EncryptPKCS8PrivateKey(rand.Reader, p.Bytes, ctx.password, DefaultEncCipher)
417 if err != nil {
418 return nil, err
419 }
420 } else {
421 var err error
422 //nolint
423 p, err = x509.EncryptPEMBlock(rand.Reader, p.Type, p.Bytes, ctx.password, DefaultEncCipher)
424 if err != nil {
425 return nil, errors.Wrap(err, "failed to serialize to PEM")
426 }
427 }
428 }
429
430 if ctx.filename != "" {
431 if err := utils.WriteFile(ctx.filename, pem.EncodeToMemory(p), ctx.perm); err != nil {
432 return nil, errs.FileError(err, ctx.filename)
433 }
434 }
435
436 return p, nil
437 }
438
439 // ParseDER parses the given DER-encoded bytes and results the public or private
440 // key encoded.
441 func ParseDER(b []byte) (interface{}, error) {
442 // Try private keys
443 key, err := ParsePKCS8PrivateKey(b)
444 if err != nil {
445 if key, err = x509.ParseECPrivateKey(b); err != nil {
446 key, err = x509.ParsePKCS1PrivateKey(b)
447 }
448 }
449
450 // Try public key
451 if err != nil {
452 if key, err = ParsePKIXPublicKey(b); err != nil {
453 if key, err = x509.ParsePKCS1PublicKey(b); err != nil {
454 return nil, errors.New("error decoding DER; bad format")
455 }
456 }
457 }
458
459 return key, nil
460 }
461
462 // ParseSSH parses parses a public key from an authorized_keys file used in
463 // OpenSSH according to the sshd(8) manual page.
464 func ParseSSH(b []byte) (interface{}, error) {
465 key, _, _, _, err := ssh.ParseAuthorizedKey(b)
466 if err != nil {
467 return nil, errors.Wrap(err, "error parsing OpenSSH key")
468 }
469
470 if cert, ok := key.(*ssh.Certificate); ok {
471 key = cert.Key
472 }
473
474 switch key.Type() {
475 case ssh.KeyAlgoRSA:
476 var w struct {
477 Name string
478 E *big.Int
479 N *big.Int
480 }
481 if err := ssh.Unmarshal(key.Marshal(), &w); err != nil {
482 return nil, errors.Wrap(err, "error unmarshaling key")
483 }
484
485 if w.E.BitLen() > 24 {
486 return nil, errors.New("error unmarshaling key: exponent too large")
487 }
488 e := w.E.Int64()
489 if e < 3 || e&1 == 0 {
490 return nil, errors.New("error unmarshaling key: incorrect exponent")
491 }
492
493 key := new(rsa.PublicKey)
494 key.E = int(e)
495 key.N = w.N
496 return key, nil
497
498 case ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521:
499 var w struct {
500 Name string
501 ID string
502 KeyBytes []byte
503 }
504 if err := ssh.Unmarshal(key.Marshal(), &w); err != nil {
505 return nil, errors.Wrap(err, "error unmarshaling key")
506 }
507
508 key := new(ecdsa.PublicKey)
509 switch w.Name {
510 case ssh.KeyAlgoECDSA256:
511 key.Curve = elliptic.P256()
512 case ssh.KeyAlgoECDSA384:
513 key.Curve = elliptic.P384()
514 case ssh.KeyAlgoECDSA521:
515 key.Curve = elliptic.P521()
516 default:
517 return nil, errors.Errorf("unsupported ecdsa curve %s", w.Name)
518 }
519
520 key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
521 if key.X == nil || key.Y == nil {
522 return nil, errors.New("invalid ecdsa curve point")
523 }
524 return key, nil
525
526 case ssh.KeyAlgoED25519:
527 var w struct {
528 Name string
529 KeyBytes []byte
530 }
531 if err := ssh.Unmarshal(key.Marshal(), &w); err != nil {
532 return nil, errors.Wrap(err, "error unmarshaling key")
533 }
534 return ed25519.PublicKey(w.KeyBytes), nil
535
536 case ssh.KeyAlgoDSA:
537 return nil, errors.Errorf("step does not support DSA keys")
538
539 default:
540 return nil, errors.Errorf("unsupported key type %T", key)
541 }
542 }