2021-11-24 10:29:15 +00:00
|
|
|
// Copyright 2019 The age Authors. All rights reserved.
|
2019-10-07 03:16:20 +00:00
|
|
|
// Use of this source code is governed by a BSD-style
|
2021-11-24 10:29:15 +00:00
|
|
|
// license that can be found in the LICENSE file.
|
2019-10-07 03:16:20 +00:00
|
|
|
|
2020-06-28 00:36:02 +00:00
|
|
|
// Package age implements file encryption according to the age-encryption.org/v1
|
|
|
|
|
// specification.
|
|
|
|
|
//
|
2025-05-10 12:59:20 +00:00
|
|
|
// For most use cases, use the [Encrypt] and [Decrypt] functions with
|
2025-11-17 11:32:50 +00:00
|
|
|
// [HybridRecipient] and [HybridIdentity]. If passphrase encryption is
|
|
|
|
|
// required, use [ScryptRecipient] and [ScryptIdentity]. For compatibility with
|
|
|
|
|
// existing SSH keys use the filippo.io/age/agessh package.
|
2020-06-28 00:36:02 +00:00
|
|
|
//
|
2022-07-02 14:07:19 +00:00
|
|
|
// age encrypted files are binary and not malleable. For encoding them as text,
|
2020-06-28 01:08:42 +00:00
|
|
|
// use the filippo.io/age/armor package.
|
2020-09-20 10:17:15 +00:00
|
|
|
//
|
2023-08-05 17:19:26 +00:00
|
|
|
// # Key management
|
2020-09-20 10:17:15 +00:00
|
|
|
//
|
2022-07-02 14:07:19 +00:00
|
|
|
// age does not have a global keyring. Instead, since age keys are small,
|
2022-01-01 13:02:58 +00:00
|
|
|
// textual, and cheap, you are encouraged to generate dedicated keys for each
|
2020-09-20 10:17:15 +00:00
|
|
|
// task and application.
|
|
|
|
|
//
|
|
|
|
|
// Recipient public keys can be passed around as command line flags and in
|
|
|
|
|
// config files, while secret keys should be stored in dedicated files, through
|
|
|
|
|
// secret management systems, or as environment variables.
|
|
|
|
|
//
|
|
|
|
|
// There is no default path for age keys. Instead, they should be stored at
|
|
|
|
|
// application-specific paths. The CLI supports files where private keys are
|
|
|
|
|
// listed one per line, ignoring empty lines and lines starting with "#". These
|
2025-11-17 11:32:50 +00:00
|
|
|
// files can be parsed with [ParseIdentities].
|
2020-09-20 10:17:15 +00:00
|
|
|
//
|
|
|
|
|
// When integrating age into a new system, it's recommended that you only
|
2025-11-17 11:32:50 +00:00
|
|
|
// support native (X25519 and hybrid) keys, and not SSH keys. The latter are
|
|
|
|
|
// supported for manual encryption operations. If you need to tie into existing
|
|
|
|
|
// key management infrastructure, you might want to consider implementing your
|
|
|
|
|
// own [Recipient] and [Identity].
|
2021-09-04 16:06:38 +00:00
|
|
|
//
|
2023-08-05 17:19:26 +00:00
|
|
|
// # Backwards compatibility
|
2021-09-04 16:06:38 +00:00
|
|
|
//
|
|
|
|
|
// Files encrypted with a stable version (not alpha, beta, or release candidate)
|
|
|
|
|
// of age, or with any v1.0.0 beta or release candidate, will decrypt with any
|
|
|
|
|
// later versions of the v1 API. This might change in v2, in which case v1 will
|
|
|
|
|
// be maintained with security fixes for compatibility with older files.
|
|
|
|
|
//
|
|
|
|
|
// If decrypting an older file poses a security risk, doing so might require an
|
|
|
|
|
// explicit opt-in in the API.
|
2019-10-07 01:19:04 +00:00
|
|
|
package age
|
|
|
|
|
|
|
|
|
|
import (
|
2025-05-10 13:04:56 +00:00
|
|
|
"bytes"
|
2019-10-07 01:19:04 +00:00
|
|
|
"crypto/hmac"
|
|
|
|
|
"crypto/rand"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
2025-11-17 11:32:50 +00:00
|
|
|
"slices"
|
2023-08-05 17:19:26 +00:00
|
|
|
"sort"
|
2019-10-07 01:19:04 +00:00
|
|
|
|
2019-12-07 04:00:57 +00:00
|
|
|
"filippo.io/age/internal/format"
|
|
|
|
|
"filippo.io/age/internal/stream"
|
2019-10-07 01:19:04 +00:00
|
|
|
)
|
|
|
|
|
|
2025-05-10 12:59:20 +00:00
|
|
|
// An Identity is passed to [Decrypt] to unwrap an opaque file key from a
|
2025-11-17 11:32:50 +00:00
|
|
|
// recipient stanza. It can be for example a secret key like [HybridIdentity], a
|
2021-01-31 20:59:06 +00:00
|
|
|
// plugin, or a custom implementation.
|
2019-10-07 01:19:04 +00:00
|
|
|
type Identity interface {
|
2025-05-10 12:59:20 +00:00
|
|
|
// Unwrap must return an error wrapping [ErrIncorrectIdentity] if none of
|
|
|
|
|
// the recipient stanzas match the identity, any other error will be
|
|
|
|
|
// considered fatal.
|
|
|
|
|
//
|
|
|
|
|
// Most age API users won't need to interact with this method directly, and
|
|
|
|
|
// should instead pass [Identity] implementations to [Decrypt].
|
2021-01-31 20:59:06 +00:00
|
|
|
Unwrap(stanzas []*Stanza) (fileKey []byte, err error)
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
|
|
|
|
|
2025-05-10 12:59:20 +00:00
|
|
|
// ErrIncorrectIdentity is returned by [Identity.Unwrap] if none of the
|
|
|
|
|
// recipient stanzas match the identity.
|
2019-11-25 00:15:53 +00:00
|
|
|
var ErrIncorrectIdentity = errors.New("incorrect identity for recipient block")
|
|
|
|
|
|
2025-05-10 12:59:20 +00:00
|
|
|
// A Recipient is passed to [Encrypt] to wrap an opaque file key to one or more
|
2025-11-17 11:32:50 +00:00
|
|
|
// recipient stanza(s). It can be for example a public key like [HybridRecipient],
|
2021-01-31 20:59:06 +00:00
|
|
|
// a plugin, or a custom implementation.
|
2019-10-07 01:19:04 +00:00
|
|
|
type Recipient interface {
|
2025-05-10 12:59:20 +00:00
|
|
|
// Most age API users won't need to interact with this method directly, and
|
|
|
|
|
// should instead pass [Recipient] implementations to [Encrypt].
|
2021-01-31 20:59:06 +00:00
|
|
|
Wrap(fileKey []byte) ([]*Stanza, error)
|
2020-06-27 23:44:26 +00:00
|
|
|
}
|
|
|
|
|
|
2025-05-10 12:59:20 +00:00
|
|
|
// RecipientWithLabels can be optionally implemented by a [Recipient], in which
|
|
|
|
|
// case [Encrypt] will use WrapWithLabels instead of [Recipient.Wrap].
|
2023-08-05 17:19:26 +00:00
|
|
|
//
|
|
|
|
|
// Encrypt will succeed only if the labels returned by all the recipients
|
|
|
|
|
// (assuming the empty set for those that don't implement RecipientWithLabels)
|
|
|
|
|
// are the same.
|
|
|
|
|
//
|
|
|
|
|
// This can be used to ensure a recipient is only used with other recipients
|
|
|
|
|
// with equivalent properties (for example by setting a "postquantum" label) or
|
|
|
|
|
// to ensure a recipient is always used alone (by returning a random label, for
|
|
|
|
|
// example to preserve its authentication properties).
|
|
|
|
|
type RecipientWithLabels interface {
|
|
|
|
|
WrapWithLabels(fileKey []byte) (s []*Stanza, labels []string, err error)
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-27 23:44:26 +00:00
|
|
|
// A Stanza is a section of the age header that encapsulates the file key as
|
|
|
|
|
// encrypted to a specific recipient.
|
2021-01-31 20:59:06 +00:00
|
|
|
//
|
2025-05-10 12:59:20 +00:00
|
|
|
// Most age API users won't need to interact with this type directly, and should
|
|
|
|
|
// instead pass [Recipient] implementations to [Encrypt] and [Identity]
|
|
|
|
|
// implementations to [Decrypt].
|
2020-06-27 23:44:26 +00:00
|
|
|
type Stanza struct {
|
|
|
|
|
Type string
|
|
|
|
|
Args []string
|
|
|
|
|
Body []byte
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
|
|
|
|
|
age: mitigate multi-key attacks on ChaCha20Poly1305
It's possible to craft ChaCha20Poly1305 ciphertexts that decrypt under
multiple keys. (I know, it's wild.)
The impact is different for different recipients, but in general only
applies to Chosen Ciphertext Attacks against online decryption oracles:
* With the scrypt recipient, it lets the attacker make a recipient
stanza that decrypts with multiple passwords, speeding up a bruteforce
in terms of oracle queries (but not scrypt work, which can be
precomputed) to logN by binary search.
Limiting the ciphertext size limits the keys to two, which makes this
acceptable: it's a loss of only one bit of security in a scenario
(online decryption oracles) that is not recommended.
* With the X25519 recipient, it lets the attacker search for accepted
public keys without using multiple recipient stanzas in the message.
That lets the attacker bypass the 20 recipients limit (which was not
actually intended to defend against deanonymization attacks).
This is not really in the threat model for age: we make no attempt to
provide anonymity in an online CCA scenario.
Anyway, limiting the keys to two by enforcing short ciphertexts
mitigates the attack: it only lets the attacker test 40 keys per
message instead of 20.
* With the ssh-ed25519 recipient, the attack should be irrelevant, since
the recipient stanza includes a 32-bit hash of the public key, making
it decidedly not anonymous.
Also to avoid breaking the abstraction in the agessh package, we don't
mitigate the attack for this recipient, but we document the lack of
anonymity.
This was reported by Paul Grubbs in the context of the upcoming paper
"Partitioning Oracle Attacks", USENIX Security 2021 (to appear), by
Julia Len, Paul Grubbs, and Thomas Ristenpart.
2020-09-19 16:18:59 +00:00
|
|
|
const fileKeySize = 16
|
|
|
|
|
const streamNonceSize = 16
|
|
|
|
|
|
2025-12-25 18:50:48 +00:00
|
|
|
func encryptHdr(fileKey []byte, recipients ...Recipient) (*format.Header, error) {
|
2019-10-07 01:19:04 +00:00
|
|
|
if len(recipients) == 0 {
|
|
|
|
|
return nil, errors.New("no recipients specified")
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-26 16:53:15 +00:00
|
|
|
hdr := &format.Header{}
|
2023-08-05 17:19:26 +00:00
|
|
|
var labels []string
|
2019-10-07 01:19:04 +00:00
|
|
|
for i, r := range recipients {
|
2023-08-05 17:19:26 +00:00
|
|
|
stanzas, l, err := wrapWithLabels(r, fileKey)
|
2019-10-07 01:19:04 +00:00
|
|
|
if err != nil {
|
2025-12-22 21:01:58 +00:00
|
|
|
return nil, fmt.Errorf("failed to wrap key for recipient #%d: %w", i, err)
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
2023-08-05 17:19:26 +00:00
|
|
|
sort.Strings(l)
|
|
|
|
|
if i == 0 {
|
|
|
|
|
labels = l
|
|
|
|
|
} else if !slicesEqual(labels, l) {
|
2025-11-17 11:32:50 +00:00
|
|
|
return nil, incompatibleLabelsError(labels, l)
|
2023-08-05 17:19:26 +00:00
|
|
|
}
|
2021-01-31 20:59:06 +00:00
|
|
|
for _, s := range stanzas {
|
|
|
|
|
hdr.Recipients = append(hdr.Recipients, (*format.Stanza)(s))
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-10-07 01:19:04 +00:00
|
|
|
if mac, err := headerMAC(fileKey, hdr); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to compute header MAC: %v", err)
|
|
|
|
|
} else {
|
|
|
|
|
hdr.MAC = mac
|
|
|
|
|
}
|
2025-12-25 18:50:48 +00:00
|
|
|
return hdr, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Encrypt encrypts a file to one or more recipients. Every recipient will be
|
|
|
|
|
// able to decrypt the file.
|
|
|
|
|
//
|
|
|
|
|
// Writes to the returned WriteCloser are encrypted and written to dst as an age
|
|
|
|
|
// file. The caller must call Close on the WriteCloser when done for the last
|
|
|
|
|
// chunk to be encrypted and flushed to dst.
|
|
|
|
|
func Encrypt(dst io.Writer, recipients ...Recipient) (io.WriteCloser, error) {
|
|
|
|
|
fileKey := make([]byte, fileKeySize)
|
|
|
|
|
rand.Read(fileKey)
|
|
|
|
|
|
|
|
|
|
hdr, err := encryptHdr(fileKey, recipients...)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2019-10-07 01:19:04 +00:00
|
|
|
if err := hdr.Marshal(dst); err != nil {
|
2025-12-22 21:01:58 +00:00
|
|
|
return nil, fmt.Errorf("failed to write header: %w", err)
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
|
|
|
|
|
age: mitigate multi-key attacks on ChaCha20Poly1305
It's possible to craft ChaCha20Poly1305 ciphertexts that decrypt under
multiple keys. (I know, it's wild.)
The impact is different for different recipients, but in general only
applies to Chosen Ciphertext Attacks against online decryption oracles:
* With the scrypt recipient, it lets the attacker make a recipient
stanza that decrypts with multiple passwords, speeding up a bruteforce
in terms of oracle queries (but not scrypt work, which can be
precomputed) to logN by binary search.
Limiting the ciphertext size limits the keys to two, which makes this
acceptable: it's a loss of only one bit of security in a scenario
(online decryption oracles) that is not recommended.
* With the X25519 recipient, it lets the attacker search for accepted
public keys without using multiple recipient stanzas in the message.
That lets the attacker bypass the 20 recipients limit (which was not
actually intended to defend against deanonymization attacks).
This is not really in the threat model for age: we make no attempt to
provide anonymity in an online CCA scenario.
Anyway, limiting the keys to two by enforcing short ciphertexts
mitigates the attack: it only lets the attacker test 40 keys per
message instead of 20.
* With the ssh-ed25519 recipient, the attack should be irrelevant, since
the recipient stanza includes a 32-bit hash of the public key, making
it decidedly not anonymous.
Also to avoid breaking the abstraction in the agessh package, we don't
mitigate the attack for this recipient, but we document the lack of
anonymity.
This was reported by Paul Grubbs in the context of the upcoming paper
"Partitioning Oracle Attacks", USENIX Security 2021 (to appear), by
Julia Len, Paul Grubbs, and Thomas Ristenpart.
2020-09-19 16:18:59 +00:00
|
|
|
nonce := make([]byte, streamNonceSize)
|
2025-12-25 18:50:48 +00:00
|
|
|
rand.Read(nonce)
|
2019-12-26 16:53:15 +00:00
|
|
|
if _, err := dst.Write(nonce); err != nil {
|
2025-12-22 21:01:58 +00:00
|
|
|
return nil, fmt.Errorf("failed to write nonce: %w", err)
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
|
|
|
|
|
2025-12-25 18:50:48 +00:00
|
|
|
return stream.NewEncryptWriter(streamKey(fileKey, nonce), dst)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// EncryptReader encrypts a file to one or more recipients. Every recipient will be
|
|
|
|
|
// able to decrypt the file.
|
|
|
|
|
//
|
|
|
|
|
// Reads from the returned Reader produce the encrypted file, where the plaintext
|
|
|
|
|
// is read from src.
|
|
|
|
|
func EncryptReader(src io.Reader, recipients ...Recipient) (io.Reader, error) {
|
|
|
|
|
fileKey := make([]byte, fileKeySize)
|
|
|
|
|
rand.Read(fileKey)
|
|
|
|
|
|
|
|
|
|
hdr, err := encryptHdr(fileKey, recipients...)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
|
if err := hdr.Marshal(buf); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to prepare header: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
nonce := make([]byte, streamNonceSize)
|
|
|
|
|
rand.Read(nonce)
|
|
|
|
|
|
|
|
|
|
r, err := stream.NewEncryptReader(streamKey(fileKey, nonce), src)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return io.MultiReader(buf, bytes.NewReader(nonce), r), nil
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
|
|
|
|
|
2023-08-05 17:19:26 +00:00
|
|
|
func wrapWithLabels(r Recipient, fileKey []byte) (s []*Stanza, labels []string, err error) {
|
|
|
|
|
if r, ok := r.(RecipientWithLabels); ok {
|
|
|
|
|
return r.WrapWithLabels(fileKey)
|
|
|
|
|
}
|
|
|
|
|
s, err = r.Wrap(fileKey)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func slicesEqual(s1, s2 []string) bool {
|
|
|
|
|
if len(s1) != len(s2) {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
for i := range s1 {
|
|
|
|
|
if s1[i] != s2[i] {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-17 11:32:50 +00:00
|
|
|
func incompatibleLabelsError(l1, l2 []string) error {
|
|
|
|
|
hasPQ1 := slices.Contains(l1, "postquantum")
|
|
|
|
|
hasPQ2 := slices.Contains(l2, "postquantum")
|
|
|
|
|
if hasPQ1 != hasPQ2 {
|
|
|
|
|
return fmt.Errorf("incompatible recipients: can't mix post-quantum and classic recipients, or the file would be vulnerable to quantum computers")
|
|
|
|
|
}
|
|
|
|
|
return fmt.Errorf("incompatible recipients: %q and %q can't be mixed", l1, l2)
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-10 12:59:20 +00:00
|
|
|
// NoIdentityMatchError is returned by [Decrypt] when none of the supplied
|
2021-01-17 11:09:07 +00:00
|
|
|
// identities match the encrypted file.
|
|
|
|
|
type NoIdentityMatchError struct {
|
|
|
|
|
// Errors is a slice of all the errors returned to Decrypt by the Unwrap
|
2025-05-10 12:59:20 +00:00
|
|
|
// calls it made. They all wrap [ErrIncorrectIdentity].
|
2021-01-17 11:09:07 +00:00
|
|
|
Errors []error
|
2025-12-23 12:08:56 +00:00
|
|
|
// StanzaTypes are the first argument of each recipient stanza in the
|
|
|
|
|
// encrypted file's header.
|
|
|
|
|
StanzaTypes []string
|
2021-01-17 11:09:07 +00:00
|
|
|
}
|
|
|
|
|
|
2025-12-23 13:08:52 +00:00
|
|
|
func (e *NoIdentityMatchError) Error() string {
|
|
|
|
|
if len(e.Errors) == 1 {
|
|
|
|
|
return "identity did not match any of the recipients: " + e.Errors[0].Error()
|
|
|
|
|
}
|
2021-01-17 11:09:07 +00:00
|
|
|
return "no identity matched any of the recipients"
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-22 21:01:58 +00:00
|
|
|
func (e *NoIdentityMatchError) Unwrap() []error {
|
|
|
|
|
return e.Errors
|
|
|
|
|
}
|
|
|
|
|
|
2020-09-20 10:42:43 +00:00
|
|
|
// Decrypt decrypts a file encrypted to one or more identities.
|
2025-12-26 12:54:44 +00:00
|
|
|
// All identities will be tried until one successfully decrypts the file.
|
2025-12-07 17:51:19 +00:00
|
|
|
// Native, non-interactive identities are tried before any other identities.
|
2025-05-10 12:59:20 +00:00
|
|
|
//
|
2025-12-26 12:54:44 +00:00
|
|
|
// Decrypt returns a Reader reading the decrypted plaintext of the age file read
|
|
|
|
|
// from src. If no identity matches the encrypted file, the returned error will
|
|
|
|
|
// be of type [NoIdentityMatchError].
|
2019-10-07 01:19:04 +00:00
|
|
|
func Decrypt(src io.Reader, identities ...Identity) (io.Reader, error) {
|
|
|
|
|
hdr, payload, err := format.Parse(src)
|
|
|
|
|
if err != nil {
|
2022-07-03 00:18:11 +00:00
|
|
|
return nil, fmt.Errorf("failed to read header: %w", err)
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
|
|
|
|
|
2025-05-10 13:04:56 +00:00
|
|
|
fileKey, err := decryptHdr(hdr, identities...)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
nonce := make([]byte, streamNonceSize)
|
|
|
|
|
if _, err := io.ReadFull(payload, nonce); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to read nonce: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-25 18:50:48 +00:00
|
|
|
return stream.NewDecryptReader(streamKey(fileKey, nonce), payload)
|
2025-05-10 13:04:56 +00:00
|
|
|
}
|
|
|
|
|
|
2025-12-26 12:54:44 +00:00
|
|
|
// DecryptReaderAt decrypts a file encrypted to one or more identities.
|
|
|
|
|
// All identities will be tried until one successfully decrypts the file.
|
|
|
|
|
// Native, non-interactive identities are tried before any other identities.
|
|
|
|
|
//
|
|
|
|
|
// DecryptReaderAt takes an underlying [io.ReaderAt] and its total encrypted
|
|
|
|
|
// size, and returns a ReaderAt of the decrypted plaintext and the plaintext
|
|
|
|
|
// size. These can be used for example to instantiate an [io.SectionReader],
|
2025-12-26 20:35:42 +00:00
|
|
|
// which implements [io.Reader] and [io.Seeker], or for [zip.NewReader].
|
|
|
|
|
// Note that ReaderAt by definition disregards the seek position of src.
|
2025-12-26 12:54:44 +00:00
|
|
|
//
|
|
|
|
|
// The ReadAt method of the returned ReaderAt can be called concurrently.
|
|
|
|
|
// The ReaderAt will internally cache the most recently decrypted chunk.
|
|
|
|
|
// DecryptReaderAt reads and decrypts the final chunk before returning,
|
|
|
|
|
// to authenticate the plaintext size.
|
|
|
|
|
//
|
|
|
|
|
// If no identity matches the encrypted file, the returned error will be of
|
|
|
|
|
// type [NoIdentityMatchError].
|
|
|
|
|
func DecryptReaderAt(src io.ReaderAt, encryptedSize int64, identities ...Identity) (io.ReaderAt, int64, error) {
|
|
|
|
|
srcReader := io.NewSectionReader(src, 0, encryptedSize)
|
|
|
|
|
hdr, payload, err := format.Parse(srcReader)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, fmt.Errorf("failed to read header: %w", err)
|
|
|
|
|
}
|
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
|
if err := hdr.Marshal(buf); err != nil {
|
|
|
|
|
return nil, 0, fmt.Errorf("failed to serialize header: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fileKey, err := decryptHdr(hdr, identities...)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
nonce := make([]byte, streamNonceSize)
|
|
|
|
|
if _, err := io.ReadFull(payload, nonce); err != nil {
|
|
|
|
|
return nil, 0, fmt.Errorf("failed to read nonce: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
payloadOffset := int64(buf.Len()) + int64(len(nonce))
|
|
|
|
|
payloadSize := encryptedSize - payloadOffset
|
|
|
|
|
plaintextSize, err := stream.PlaintextSize(payloadSize)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
payloadReaderAt := io.NewSectionReader(src, payloadOffset, payloadSize)
|
|
|
|
|
r, err := stream.NewDecryptReaderAt(streamKey(fileKey, nonce), payloadReaderAt, payloadSize)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, 0, err
|
|
|
|
|
}
|
|
|
|
|
return r, plaintextSize, nil
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-10 13:04:56 +00:00
|
|
|
func decryptHdr(hdr *format.Header, identities ...Identity) ([]byte, error) {
|
|
|
|
|
if len(identities) == 0 {
|
|
|
|
|
return nil, errors.New("no identities specified")
|
|
|
|
|
}
|
2025-12-07 17:51:19 +00:00
|
|
|
slices.SortStableFunc(identities, func(a, b Identity) int {
|
|
|
|
|
var aIsNative, bIsNative bool
|
|
|
|
|
switch a.(type) {
|
|
|
|
|
case *X25519Identity, *HybridIdentity, *ScryptIdentity:
|
|
|
|
|
aIsNative = true
|
|
|
|
|
}
|
|
|
|
|
switch b.(type) {
|
|
|
|
|
case *X25519Identity, *HybridIdentity, *ScryptIdentity:
|
|
|
|
|
bIsNative = true
|
|
|
|
|
}
|
|
|
|
|
if aIsNative && !bIsNative {
|
|
|
|
|
return -1
|
|
|
|
|
}
|
|
|
|
|
if !aIsNative && bIsNative {
|
|
|
|
|
return 1
|
|
|
|
|
}
|
|
|
|
|
return 0
|
|
|
|
|
})
|
2025-05-10 13:04:56 +00:00
|
|
|
|
2021-01-31 20:59:06 +00:00
|
|
|
stanzas := make([]*Stanza, 0, len(hdr.Recipients))
|
2025-12-23 12:08:56 +00:00
|
|
|
errNoMatch := &NoIdentityMatchError{}
|
2021-01-31 20:59:06 +00:00
|
|
|
for _, s := range hdr.Recipients {
|
2025-12-23 12:08:56 +00:00
|
|
|
errNoMatch.StanzaTypes = append(errNoMatch.StanzaTypes, s.Type)
|
2021-01-31 20:59:06 +00:00
|
|
|
stanzas = append(stanzas, (*Stanza)(s))
|
|
|
|
|
}
|
|
|
|
|
var fileKey []byte
|
|
|
|
|
for _, id := range identities {
|
2025-05-10 13:04:56 +00:00
|
|
|
var err error
|
2021-01-31 20:59:06 +00:00
|
|
|
fileKey, err = id.Unwrap(stanzas)
|
|
|
|
|
if errors.Is(err, ErrIncorrectIdentity) {
|
|
|
|
|
errNoMatch.Errors = append(errNoMatch.Errors, err)
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
2021-01-31 20:59:06 +00:00
|
|
|
|
|
|
|
|
break
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
|
|
|
|
if fileKey == nil {
|
2021-01-17 11:09:07 +00:00
|
|
|
return nil, errNoMatch
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if mac, err := headerMAC(fileKey, hdr); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to compute header MAC: %v", err)
|
|
|
|
|
} else if !hmac.Equal(mac, hdr.MAC) {
|
|
|
|
|
return nil, errors.New("bad header MAC")
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-10 13:04:56 +00:00
|
|
|
return fileKey, nil
|
2019-10-07 01:19:04 +00:00
|
|
|
}
|
2021-01-31 20:59:06 +00:00
|
|
|
|
|
|
|
|
// multiUnwrap is a helper that implements Identity.Unwrap in terms of a
|
|
|
|
|
// function that unwraps a single recipient stanza.
|
|
|
|
|
func multiUnwrap(unwrap func(*Stanza) ([]byte, error), stanzas []*Stanza) ([]byte, error) {
|
|
|
|
|
for _, s := range stanzas {
|
|
|
|
|
fileKey, err := unwrap(s)
|
|
|
|
|
if errors.Is(err, ErrIncorrectIdentity) {
|
|
|
|
|
// If we ever start returning something interesting wrapping
|
|
|
|
|
// ErrIncorrectIdentity, we should let it make its way up through
|
|
|
|
|
// Decrypt into NoIdentityMatchError.Errors.
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return fileKey, nil
|
|
|
|
|
}
|
|
|
|
|
return nil, ErrIncorrectIdentity
|
|
|
|
|
}
|
2025-05-10 13:04:56 +00:00
|
|
|
|
|
|
|
|
// ExtractHeader returns a detached header from the src file.
|
|
|
|
|
//
|
|
|
|
|
// The detached header can be decrypted with [DecryptHeader] (for example on a
|
|
|
|
|
// different system, without sharing the ciphertext) and then the file key can
|
|
|
|
|
// be used with [NewInjectedFileKeyIdentity].
|
|
|
|
|
//
|
|
|
|
|
// This is a low-level function that most users won't need.
|
|
|
|
|
func ExtractHeader(src io.Reader) ([]byte, error) {
|
|
|
|
|
hdr, _, err := format.Parse(src)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to read header: %w", err)
|
|
|
|
|
}
|
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
|
if err := hdr.Marshal(buf); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to serialize header: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return buf.Bytes(), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DecryptHeader decrypts a detached header and returns a file key.
|
|
|
|
|
//
|
|
|
|
|
// The detached header can be produced by [ExtractHeader], and the
|
|
|
|
|
// returned file key can be used with [NewInjectedFileKeyIdentity].
|
|
|
|
|
//
|
|
|
|
|
// This is a low-level function that most users won't need.
|
|
|
|
|
// It is the caller's responsibility to keep track of what file the
|
|
|
|
|
// returned file key decrypts, and to ensure the file key is not used
|
|
|
|
|
// for any other purpose.
|
|
|
|
|
func DecryptHeader(header []byte, identities ...Identity) ([]byte, error) {
|
|
|
|
|
hdr, _, err := format.Parse(bytes.NewReader(header))
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to read header: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return decryptHdr(hdr, identities...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type injectedFileKeyIdentity struct {
|
|
|
|
|
fileKey []byte
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewInjectedFileKeyIdentity returns an [Identity] that always produces
|
|
|
|
|
// a fixed file key, allowing the use of a file key obtained out-of-band,
|
|
|
|
|
// for example via [DecryptHeader].
|
|
|
|
|
//
|
|
|
|
|
// This is a low-level function that most users won't need.
|
|
|
|
|
func NewInjectedFileKeyIdentity(fileKey []byte) Identity {
|
|
|
|
|
return injectedFileKeyIdentity{fileKey}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (i injectedFileKeyIdentity) Unwrap(stanzas []*Stanza) (fileKey []byte, err error) {
|
|
|
|
|
return i.fileKey, nil
|
|
|
|
|
}
|