summaryrefslogtreecommitdiffstats
path: root/internal/profile/vault.go
blob: 5b819b44d1a49e2258021c6e5d3ae3eac78309bd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Package profile stores the optional VFace identity in an age-encrypted vault.
package profile

import (
	"bytes"
	"crypto/ed25519"
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"

	"aegis/internal/cryptokit"
	"filippo.io/age"
	agearmor "filippo.io/age/armor"
)

const (
	Version           = 1
	MinPasswordLength = 12
	maxVaultBytes     = 1 << 20
)

type Profile struct {
	Version            int       `json:"version"`
	Username           string    `json:"username"`
	Email              string    `json:"email"`
	PublicKey          string    `json:"ed25519_public_key"`
	PrivateKey         string    `json:"ed25519_private_key"`
	AgeIdentity        string    `json:"age_identity,omitempty"`
	YubiKeyFingerprint string    `json:"yubikey_signing_fingerprint,omitempty"`
	CreatedAt          time.Time `json:"created_at"`
}

func DefaultPath() (string, error) {
	directory, err := os.UserConfigDir()
	if err != nil {
		return "", fmt.Errorf("locate profile directory: %w", err)
	}
	return filepath.Join(directory, "aegis", "profile.json.age"), nil
}

func Generate(username, email string) (Profile, error) {
	username = strings.TrimSpace(username)
	email = strings.TrimSpace(email)
	if username == "" || email == "" {
		return Profile{}, errors.New("VFace username and email are required")
	}
	if strings.ContainsAny(username+email, "\x00\r\n|") {
		return Profile{}, errors.New("VFace username and email contain forbidden characters")
	}
	publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		return Profile{}, fmt.Errorf("generate VFace Ed25519 key pair: %w", err)
	}
	return Profile{
		Version:    Version,
		Username:   username,
		Email:      email,
		PublicKey:  base64.StdEncoding.EncodeToString(publicKey),
		PrivateKey: base64.StdEncoding.EncodeToString(privateKey),
		CreatedAt:  time.Now().UTC(),
	}, nil
}

func Save(path string, value Profile, password string) error {
	if err := validatePassword(password); err != nil {
		return err
	}
	if err := Validate(value); err != nil {
		return err
	}
	plaintext, err := json.MarshalIndent(value, "", "  ")
	if err != nil {
		return fmt.Errorf("encode VFace profile: %w", err)
	}
	recipient, err := age.NewScryptRecipient(password)
	if err != nil {
		return fmt.Errorf("create profile password recipient: %w", err)
	}
	var encrypted bytes.Buffer
	armor := agearmor.NewWriter(&encrypted)
	writer, err := age.Encrypt(armor, recipient)
	if err != nil {
		_ = armor.Close()
		return fmt.Errorf("create profile vault: %w", err)
	}
	if _, err := writer.Write(plaintext); err != nil {
		_ = writer.Close()
		_ = armor.Close()
		return fmt.Errorf("write profile vault: %w", err)
	}
	if err := writer.Close(); err != nil {
		_ = armor.Close()
		return fmt.Errorf("close profile vault: %w", err)
	}
	if err := armor.Close(); err != nil {
		return fmt.Errorf("close profile armor: %w", err)
	}
	return atomicWrite(path, encrypted.Bytes())
}

func Load(path string, password string) (Profile, error) {
	if err := validatePassword(password); err != nil {
		return Profile{}, err
	}
	ciphertext, err := os.ReadFile(path)
	if err != nil {
		return Profile{}, fmt.Errorf("read profile vault: %w", err)
	}
	if len(ciphertext) > maxVaultBytes {
		return Profile{}, errors.New("profile vault is too large")
	}
	identity, err := age.NewScryptIdentity(password)
	if err != nil {
		return Profile{}, fmt.Errorf("create profile password identity: %w", err)
	}
	reader, err := age.Decrypt(agearmor.NewReader(bytes.NewReader(ciphertext)), identity)
	if err != nil {
		return Profile{}, errors.New("cannot unlock profile vault")
	}
	plaintext, err := io.ReadAll(io.LimitReader(reader, maxVaultBytes+1))
	if err != nil {
		return Profile{}, fmt.Errorf("read profile vault: %w", err)
	}
	if len(plaintext) > maxVaultBytes {
		return Profile{}, errors.New("profile vault contents are too large")
	}
	var value Profile
	if err := json.Unmarshal(plaintext, &value); err != nil {
		return Profile{}, errors.New("profile vault contains invalid data")
	}
	if err := Validate(value); err != nil {
		return Profile{}, fmt.Errorf("validate profile vault: %w", err)
	}
	return value, nil
}

func Validate(value Profile) error {
	if value.Version != Version {
		return fmt.Errorf("unsupported VFace profile version %d", value.Version)
	}
	if value.Username == "" || value.Email == "" || strings.ContainsAny(value.Username+value.Email, "\x00\r\n|") {
		return errors.New("invalid VFace username or email")
	}
	publicKey, err := decodePublicKey(value.PublicKey)
	if err != nil {
		return err
	}
	if strings.TrimSpace(value.PrivateKey) == "" {
		if strings.TrimSpace(value.YubiKeyFingerprint) == "" {
			return errors.New("profile needs an encrypted private key or a YubiKey signing fingerprint")
		}
		return nil
	}
	privateKey, err := decodePrivateKey(value.PrivateKey)
	if err != nil {
		return err
	}
	derived := privateKey.Public().(ed25519.PublicKey)
	if !bytes.Equal(publicKey, derived) {
		return errors.New("VFace public and private keys do not match")
	}
	return nil
}

func validatePassword(password string) error {
	if len([]rune(password)) < MinPasswordLength {
		return fmt.Errorf("profile password must contain at least %d characters", MinPasswordLength)
	}
	return nil
}

func decodePublicKey(value string) (ed25519.PublicKey, error) {
	canonical, err := cryptokit.CanonicalEd25519PublicKey(value)
	if err != nil {
		return nil, fmt.Errorf("invalid VFace public key: %w", err)
	}
	decoded, err := base64.StdEncoding.DecodeString(canonical)
	if err != nil {
		return nil, errors.New("invalid VFace public key encoding")
	}
	return ed25519.PublicKey(decoded), nil
}

func decodePrivateKey(value string) (ed25519.PrivateKey, error) {
	decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
	if err != nil || len(decoded) != ed25519.PrivateKeySize {
		return nil, errors.New("invalid VFace private key")
	}
	return ed25519.PrivateKey(decoded), nil
}

func atomicWrite(path string, data []byte) error {
	if path == "" {
		return errors.New("profile vault path is required")
	}
	directory := filepath.Dir(path)
	if err := os.MkdirAll(directory, 0o700); err != nil {
		return fmt.Errorf("create profile directory: %w", err)
	}
	if err := os.Chmod(directory, 0o700); err != nil {
		return fmt.Errorf("protect profile directory: %w", err)
	}
	temporary, err := os.CreateTemp(directory, ".profile-*.tmp")
	if err != nil {
		return fmt.Errorf("create profile temporary file: %w", err)
	}
	temporaryName := temporary.Name()
	defer os.Remove(temporaryName)
	if err := temporary.Chmod(0o600); err != nil {
		_ = temporary.Close()
		return err
	}
	if _, err := temporary.Write(data); err != nil {
		_ = temporary.Close()
		return fmt.Errorf("write profile vault: %w", err)
	}
	if err := temporary.Sync(); err != nil {
		_ = temporary.Close()
		return fmt.Errorf("sync profile vault: %w", err)
	}
	if err := temporary.Close(); err != nil {
		return err
	}
	if err := os.Rename(temporaryName, path); err != nil {
		return fmt.Errorf("commit profile vault: %w", err)
	}
	return nil
}