blob: a8885bb10ba33ec7eb31c7d77f3db364a0e313ea [file] [log] [blame]
Lorenz Brun705a4022021-12-23 11:51:06 +01001package main
2
3import (
4 "crypto/ed25519"
5 "crypto/x509"
6 "encoding/pem"
7 "errors"
8 "fmt"
9 "os"
10 "path/filepath"
Lorenz Brun705a4022021-12-23 11:51:06 +010011)
12
13var noCredentialsError = errors.New("owner certificate or key does not exist")
14
15// getCredentials returns Metropolis credentials (if any) from the current
16// metroctl config directory.
17func getCredentials() (cert *x509.Certificate, key ed25519.PrivateKey, err error) {
Mateusz Zalega8234c162022-07-08 17:05:50 +020018 ownerPrivateKeyPEM, err := os.ReadFile(filepath.Join(flags.configPath, "owner-key.pem"))
Lorenz Brun705a4022021-12-23 11:51:06 +010019 if os.IsNotExist(err) {
20 return nil, nil, noCredentialsError
21 } else if err != nil {
22 return nil, nil, fmt.Errorf("failed to load owner private key: %w", err)
23 }
24 block, _ := pem.Decode(ownerPrivateKeyPEM)
25 if block == nil {
26 return nil, nil, errors.New("owner-key.pem contains invalid PEM armoring")
27 }
28 if block.Type != ownerKeyType {
29 return nil, nil, fmt.Errorf("owner-key.pem contains a PEM block that's not a %v", ownerKeyType)
30 }
31 if len(block.Bytes) != ed25519.PrivateKeySize {
32 return nil, nil, errors.New("owner-key.pem contains a non-Ed25519 key")
33 }
34 key = block.Bytes
Mateusz Zalega8234c162022-07-08 17:05:50 +020035 ownerCertPEM, err := os.ReadFile(filepath.Join(flags.configPath, "owner.pem"))
Lorenz Brun705a4022021-12-23 11:51:06 +010036 if os.IsNotExist(err) {
37 return nil, nil, noCredentialsError
38 } else if err != nil {
39 return nil, nil, fmt.Errorf("failed to load owner certificate: %w", err)
40 }
41 block, _ = pem.Decode(ownerCertPEM)
42 if block == nil {
43 return nil, nil, errors.New("owner.pem contains invalid PEM armoring")
44 }
45 if block.Type != "CERTIFICATE" {
46 return nil, nil, fmt.Errorf("owner.pem contains a PEM block that's not a CERTIFICATE")
47 }
48 cert, err = x509.ParseCertificate(block.Bytes)
49 if err != nil {
50 return nil, nil, fmt.Errorf("owner.pem contains an invalid X.509 certificate: %w", err)
51 }
52 return
53}