Lorenz Brun | 705a402 | 2021-12-23 11:51:06 +0100 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "crypto/ed25519" |
| 5 | "crypto/x509" |
| 6 | "encoding/pem" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "path/filepath" |
Lorenz Brun | 705a402 | 2021-12-23 11:51:06 +0100 | [diff] [blame] | 11 | ) |
| 12 | |
| 13 | var 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. |
| 17 | func getCredentials() (cert *x509.Certificate, key ed25519.PrivateKey, err error) { |
Mateusz Zalega | 8234c16 | 2022-07-08 17:05:50 +0200 | [diff] [blame] | 18 | ownerPrivateKeyPEM, err := os.ReadFile(filepath.Join(flags.configPath, "owner-key.pem")) |
Lorenz Brun | 705a402 | 2021-12-23 11:51:06 +0100 | [diff] [blame] | 19 | 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 Zalega | 8234c16 | 2022-07-08 17:05:50 +0200 | [diff] [blame] | 35 | ownerCertPEM, err := os.ReadFile(filepath.Join(flags.configPath, "owner.pem")) |
Lorenz Brun | 705a402 | 2021-12-23 11:51:06 +0100 | [diff] [blame] | 36 | 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 | } |