Debian Codegraph @

age.go

raw symbols SCIP
1 // Copyright 2019 The age Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package age implements file encryption according to the age-encryption.org/v1
6 // specification.
7 //
8 // For most use cases, use the [Encrypt] and [Decrypt] functions with
9 // [HybridRecipient] and [HybridIdentity]. If passphrase encryption is
10 // required, use [ScryptRecipient] and [ScryptIdentity]. For compatibility with
11 // existing SSH keys use the filippo.io/age/agessh package.
12 //
13 // age encrypted files are binary and not malleable. For encoding them as text,
14 // use the filippo.io/age/armor package.
15 //
16 // # Key management
17 //
18 // age does not have a global keyring. Instead, since age keys are small,
19 // textual, and cheap, you are encouraged to generate dedicated keys for each
20 // task and application.
21 //
22 // Recipient public keys can be passed around as command line flags and in
23 // config files, while secret keys should be stored in dedicated files, through
24 // secret management systems, or as environment variables.
25 //
26 // There is no default path for age keys. Instead, they should be stored at
27 // application-specific paths. The CLI supports files where private keys are
28 // listed one per line, ignoring empty lines and lines starting with "#". These
29 // files can be parsed with [ParseIdentities].
30 //
31 // When integrating age into a new system, it's recommended that you only
32 // support native (X25519 and hybrid) keys, and not SSH keys. The latter are
33 // supported for manual encryption operations. If you need to tie into existing
34 // key management infrastructure, you might want to consider implementing your
35 // own [Recipient] and [Identity].
36 //
37 // # Backwards compatibility
38 //
39 // Files encrypted with a stable version (not alpha, beta, or release candidate)
40 // of age, or with any v1.0.0 beta or release candidate, will decrypt with any
41 // later versions of the v1 API. This might change in v2, in which case v1 will
42 // be maintained with security fixes for compatibility with older files.
43 //
44 // If decrypting an older file poses a security risk, doing so might require an
45 // explicit opt-in in the API.
46 package age
47
48 import (
49 "bytes"
50 "crypto/hmac"
51 "crypto/rand"
52 "errors"
53 "fmt"
54 "io"
55 "slices"
56 "sort"
57
58 "filippo.io/age/internal/format"
59 "filippo.io/age/internal/stream"
60 )
61
62 // An Identity is passed to [Decrypt] to unwrap an opaque file key from a
63 // recipient stanza. It can be for example a secret key like [HybridIdentity], a
64 // plugin, or a custom implementation.
65 type Identity interface {
66 // Unwrap must return an error wrapping [ErrIncorrectIdentity] if none of
67 // the recipient stanzas match the identity, any other error will be
68 // considered fatal.
69 //
70 // Most age API users won't need to interact with this method directly, and
71 // should instead pass [Identity] implementations to [Decrypt].
72 Unwrap(stanzas []*Stanza) (fileKey []byte, err error)
73 }
74
75 // ErrIncorrectIdentity is returned by [Identity.Unwrap] if none of the
76 // recipient stanzas match the identity.
77 var ErrIncorrectIdentity = errors.New("incorrect identity for recipient block")
78
79 // A Recipient is passed to [Encrypt] to wrap an opaque file key to one or more
80 // recipient stanza(s). It can be for example a public key like [HybridRecipient],
81 // a plugin, or a custom implementation.
82 type Recipient interface {
83 // Most age API users won't need to interact with this method directly, and
84 // should instead pass [Recipient] implementations to [Encrypt].
85 Wrap(fileKey []byte) ([]*Stanza, error)
86 }
87
88 // RecipientWithLabels can be optionally implemented by a [Recipient], in which
89 // case [Encrypt] will use WrapWithLabels instead of [Recipient.Wrap].
90 //
91 // Encrypt will succeed only if the labels returned by all the recipients
92 // (assuming the empty set for those that don't implement RecipientWithLabels)
93 // are the same.
94 //
95 // This can be used to ensure a recipient is only used with other recipients
96 // with equivalent properties (for example by setting a "postquantum" label) or
97 // to ensure a recipient is always used alone (by returning a random label, for
98 // example to preserve its authentication properties).
99 type RecipientWithLabels interface {
100 WrapWithLabels(fileKey []byte) (s []*Stanza, labels []string, err error)
101 }
102
103 // A Stanza is a section of the age header that encapsulates the file key as
104 // encrypted to a specific recipient.
105 //
106 // Most age API users won't need to interact with this type directly, and should
107 // instead pass [Recipient] implementations to [Encrypt] and [Identity]
108 // implementations to [Decrypt].
109 type Stanza struct {
110 Type string
111 Args []string
112 Body []byte
113 }
114
115 const fileKeySize = 16
116 const streamNonceSize = 16
117
118 func encryptHdr(fileKey []byte, recipients ...Recipient) (*format.Header, error) {
119 if len(recipients) == 0 {
120 return nil, errors.New("no recipients specified")
121 }
122
123 hdr := &format.Header{}
124 var labels []string
125 for i, r := range recipients {
126 stanzas, l, err := wrapWithLabels(r, fileKey)
127 if err != nil {
128 return nil, fmt.Errorf("failed to wrap key for recipient #%d: %w", i, err)
129 }
130 sort.Strings(l)
131 if i == 0 {
132 labels = l
133 } else if !slices.Equal(labels, l) {
134 return nil, incompatibleLabelsError(labels, l)
135 }
136 for _, s := range stanzas {
137 hdr.Recipients = append(hdr.Recipients, (*format.Stanza)(s))
138 }
139 }
140 if mac, err := headerMAC(fileKey, hdr); err != nil {
141 return nil, fmt.Errorf("failed to compute header MAC: %v", err)
142 } else {
143 hdr.MAC = mac
144 }
145 return hdr, nil
146 }
147
148 // Encrypt encrypts a file to one or more recipients. Every recipient will be
149 // able to decrypt the file.
150 //
151 // Writes to the returned WriteCloser are encrypted and written to dst as an age
152 // file. The caller must call Close on the WriteCloser when done for the last
153 // chunk to be encrypted and flushed to dst.
154 func Encrypt(dst io.Writer, recipients ...Recipient) (io.WriteCloser, error) {
155 fileKey := make([]byte, fileKeySize)
156 rand.Read(fileKey)
157
158 hdr, err := encryptHdr(fileKey, recipients...)
159 if err != nil {
160 return nil, err
161 }
162 if err := hdr.Marshal(dst); err != nil {
163 return nil, fmt.Errorf("failed to write header: %w", err)
164 }
165
166 nonce := make([]byte, streamNonceSize)
167 rand.Read(nonce)
168 if _, err := dst.Write(nonce); err != nil {
169 return nil, fmt.Errorf("failed to write nonce: %w", err)
170 }
171
172 return stream.NewEncryptWriter(streamKey(fileKey, nonce), dst)
173 }
174
175 // EncryptReader encrypts a file to one or more recipients. Every recipient will be
176 // able to decrypt the file.
177 //
178 // Reads from the returned Reader produce the encrypted file, where the plaintext
179 // is read from src.
180 func EncryptReader(src io.Reader, recipients ...Recipient) (io.Reader, error) {
181 fileKey := make([]byte, fileKeySize)
182 rand.Read(fileKey)
183
184 hdr, err := encryptHdr(fileKey, recipients...)
185 if err != nil {
186 return nil, err
187 }
188 buf := &bytes.Buffer{}
189 if err := hdr.Marshal(buf); err != nil {
190 return nil, fmt.Errorf("failed to prepare header: %w", err)
191 }
192
193 nonce := make([]byte, streamNonceSize)
194 rand.Read(nonce)
195
196 r, err := stream.NewEncryptReader(streamKey(fileKey, nonce), src)
197 if err != nil {
198 return nil, err
199 }
200 return io.MultiReader(buf, bytes.NewReader(nonce), r), nil
201 }
202
203 func wrapWithLabels(r Recipient, fileKey []byte) (s []*Stanza, labels []string, err error) {
204 if r, ok := r.(RecipientWithLabels); ok {
205 return r.WrapWithLabels(fileKey)
206 }
207 s, err = r.Wrap(fileKey)
208 return
209 }
210
211 func incompatibleLabelsError(l1, l2 []string) error {
212 hasPQ1 := slices.Contains(l1, "postquantum")
213 hasPQ2 := slices.Contains(l2, "postquantum")
214 if hasPQ1 != hasPQ2 {
215 return fmt.Errorf("incompatible recipients: can't mix post-quantum and classic recipients, or the file would be vulnerable to quantum computers")
216 }
217 return fmt.Errorf("incompatible recipients: %q and %q can't be mixed", l1, l2)
218 }
219
220 // NoIdentityMatchError is returned by [Decrypt] when none of the supplied
221 // identities match the encrypted file.
222 type NoIdentityMatchError struct {
223 // Errors is a slice of all the errors returned to Decrypt by the Unwrap
224 // calls it made. They all wrap [ErrIncorrectIdentity].
225 Errors []error
226 // StanzaTypes are the first argument of each recipient stanza in the
227 // encrypted file's header.
228 StanzaTypes []string
229 }
230
231 func (e *NoIdentityMatchError) Error() string {
232 if len(e.Errors) == 1 {
233 return "identity did not match any of the recipients: " + e.Errors[0].Error()
234 }
235 return "no identity matched any of the recipients"
236 }
237
238 func (e *NoIdentityMatchError) Unwrap() []error {
239 return e.Errors
240 }
241
242 // Decrypt decrypts a file encrypted to one or more identities.
243 // All identities will be tried until one successfully decrypts the file.
244 // Native, non-interactive identities are tried before any other identities.
245 //
246 // Decrypt returns a Reader reading the decrypted plaintext of the age file read
247 // from src. If no identity matches the encrypted file, the returned error will
248 // be of type [NoIdentityMatchError].
249 func Decrypt(src io.Reader, identities ...Identity) (io.Reader, error) {
250 hdr, payload, err := format.Parse(src)
251 if err != nil {
252 return nil, fmt.Errorf("failed to read header: %w", err)
253 }
254
255 fileKey, err := decryptHdr(hdr, identities...)
256 if err != nil {
257 return nil, err
258 }
259
260 nonce := make([]byte, streamNonceSize)
261 if _, err := io.ReadFull(payload, nonce); err != nil {
262 return nil, fmt.Errorf("failed to read nonce: %w", err)
263 }
264
265 return stream.NewDecryptReader(streamKey(fileKey, nonce), payload)
266 }
267
268 // DecryptReaderAt decrypts a file encrypted to one or more identities.
269 // All identities will be tried until one successfully decrypts the file.
270 // Native, non-interactive identities are tried before any other identities.
271 //
272 // DecryptReaderAt takes an underlying [io.ReaderAt] and its total encrypted
273 // size, and returns a ReaderAt of the decrypted plaintext and the plaintext
274 // size. These can be used for example to instantiate an [io.SectionReader],
275 // which implements [io.Reader] and [io.Seeker], or for [zip.NewReader].
276 // Note that ReaderAt by definition disregards the seek position of src.
277 //
278 // The ReadAt method of the returned ReaderAt can be called concurrently.
279 // The ReaderAt will internally cache the most recently decrypted chunk.
280 // DecryptReaderAt reads and decrypts the final chunk before returning,
281 // to authenticate the plaintext size.
282 //
283 // If no identity matches the encrypted file, the returned error will be of
284 // type [NoIdentityMatchError].
285 func DecryptReaderAt(src io.ReaderAt, encryptedSize int64, identities ...Identity) (io.ReaderAt, int64, error) {
286 srcReader := io.NewSectionReader(src, 0, encryptedSize)
287 hdr, payload, err := format.Parse(srcReader)
288 if err != nil {
289 return nil, 0, fmt.Errorf("failed to read header: %w", err)
290 }
291 buf := &bytes.Buffer{}
292 if err := hdr.Marshal(buf); err != nil {
293 return nil, 0, fmt.Errorf("failed to serialize header: %w", err)
294 }
295
296 fileKey, err := decryptHdr(hdr, identities...)
297 if err != nil {
298 return nil, 0, err
299 }
300
301 nonce := make([]byte, streamNonceSize)
302 if _, err := io.ReadFull(payload, nonce); err != nil {
303 return nil, 0, fmt.Errorf("failed to read nonce: %w", err)
304 }
305
306 payloadOffset := int64(buf.Len()) + int64(len(nonce))
307 payloadSize := encryptedSize - payloadOffset
308 plaintextSize, err := stream.PlaintextSize(payloadSize)
309 if err != nil {
310 return nil, 0, err
311 }
312 payloadReaderAt := io.NewSectionReader(src, payloadOffset, payloadSize)
313 r, err := stream.NewDecryptReaderAt(streamKey(fileKey, nonce), payloadReaderAt, payloadSize)
314 if err != nil {
315 return nil, 0, err
316 }
317 return r, plaintextSize, nil
318 }
319
320 func decryptHdr(hdr *format.Header, identities ...Identity) ([]byte, error) {
321 if len(identities) == 0 {
322 return nil, errors.New("no identities specified")
323 }
324 // Don't sort the caller's slice in place.
325 identities = slices.Clone(identities)
326 slices.SortStableFunc(identities, func(a, b Identity) int {
327 var aIsNative, bIsNative bool
328 switch a.(type) {
329 case *X25519Identity, *HybridIdentity, *ScryptIdentity:
330 aIsNative = true
331 }
332 switch b.(type) {
333 case *X25519Identity, *HybridIdentity, *ScryptIdentity:
334 bIsNative = true
335 }
336 if aIsNative && !bIsNative {
337 return -1
338 }
339 if !aIsNative && bIsNative {
340 return 1
341 }
342 return 0
343 })
344
345 stanzas := make([]*Stanza, 0, len(hdr.Recipients))
346 errNoMatch := &NoIdentityMatchError{}
347 for _, s := range hdr.Recipients {
348 errNoMatch.StanzaTypes = append(errNoMatch.StanzaTypes, s.Type)
349 stanzas = append(stanzas, (*Stanza)(s))
350 }
351 var fileKey []byte
352 for _, id := range identities {
353 var err error
354 fileKey, err = id.Unwrap(stanzas)
355 if errors.Is(err, ErrIncorrectIdentity) {
356 errNoMatch.Errors = append(errNoMatch.Errors, err)
357 continue
358 }
359 if err != nil {
360 return nil, err
361 }
362
363 break
364 }
365 if fileKey == nil {
366 return nil, errNoMatch
367 }
368
369 if mac, err := headerMAC(fileKey, hdr); err != nil {
370 return nil, fmt.Errorf("failed to compute header MAC: %v", err)
371 } else if !hmac.Equal(mac, hdr.MAC) {
372 return nil, errors.New("bad header MAC")
373 }
374
375 return fileKey, nil
376 }
377
378 // multiUnwrap is a helper that implements Identity.Unwrap in terms of a
379 // function that unwraps a single recipient stanza.
380 func multiUnwrap(unwrap func(*Stanza) ([]byte, error), stanzas []*Stanza) ([]byte, error) {
381 for _, s := range stanzas {
382 fileKey, err := unwrap(s)
383 if errors.Is(err, ErrIncorrectIdentity) {
384 // If we ever start returning something interesting wrapping
385 // ErrIncorrectIdentity, we should let it make its way up through
386 // Decrypt into NoIdentityMatchError.Errors.
387 continue
388 }
389 if err != nil {
390 return nil, err
391 }
392 return fileKey, nil
393 }
394 return nil, ErrIncorrectIdentity
395 }
396
397 // ExtractHeader returns a detached header from the src file.
398 //
399 // The detached header can be decrypted with [DecryptHeader] (for example on a
400 // different system, without sharing the ciphertext) and then the file key can
401 // be used with [NewInjectedFileKeyIdentity].
402 //
403 // This is a low-level function that most users won't need.
404 func ExtractHeader(src io.Reader) ([]byte, error) {
405 hdr, _, err := format.Parse(src)
406 if err != nil {
407 return nil, fmt.Errorf("failed to read header: %w", err)
408 }
409 buf := &bytes.Buffer{}
410 if err := hdr.Marshal(buf); err != nil {
411 return nil, fmt.Errorf("failed to serialize header: %w", err)
412 }
413 return buf.Bytes(), nil
414 }
415
416 // DecryptHeader decrypts a detached header and returns a file key.
417 //
418 // The detached header can be produced by [ExtractHeader], and the
419 // returned file key can be used with [NewInjectedFileKeyIdentity].
420 //
421 // This is a low-level function that most users won't need.
422 // It is the caller's responsibility to keep track of what file the
423 // returned file key decrypts, and to ensure the file key is not used
424 // for any other purpose.
425 func DecryptHeader(header []byte, identities ...Identity) ([]byte, error) {
426 hdr, _, err := format.Parse(bytes.NewReader(header))
427 if err != nil {
428 return nil, fmt.Errorf("failed to read header: %w", err)
429 }
430 return decryptHdr(hdr, identities...)
431 }
432
433 type injectedFileKeyIdentity struct {
434 fileKey []byte
435 }
436
437 // NewInjectedFileKeyIdentity returns an [Identity] that always produces
438 // a fixed file key, allowing the use of a file key obtained out-of-band,
439 // for example via [DecryptHeader].
440 //
441 // This is a low-level function that most users won't need.
442 func NewInjectedFileKeyIdentity(fileKey []byte) Identity {
443 return injectedFileKeyIdentity{fileKey}
444 }
445
446 func (i injectedFileKeyIdentity) Unwrap(stanzas []*Stanza) (fileKey []byte, err error) {
447 return i.fileKey, nil
448 }