| 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 |
| 6 | |
| 7 | import ( |
| 8 | "crypto/rand" |
| 9 | "encoding/hex" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "regexp" |
| 13 | "strconv" |
| 14 | |
| 15 | "filippo.io/age/internal/format" |
| 16 | "golang.org/x/crypto/chacha20poly1305" |
| 17 | "golang.org/x/crypto/scrypt" |
| 18 | ) |
| 19 | |
| 20 | const scryptLabel = "age-encryption.org/v1/scrypt" |
| 21 | |
| 22 | // ScryptRecipient is a password-based recipient. Anyone with the password can |
| 23 | // decrypt the message. |
| 24 | // |
| 25 | // If a ScryptRecipient is used, it must be the only recipient for the file: it |
| 26 | // can't be mixed with other recipient types and can't be used multiple times |
| 27 | // for the same file. |
| 28 | // |
| 29 | // Its use is not recommended for automated systems, which should prefer |
| 30 | // [HybridRecipient] or [X25519Recipient]. |
| 31 | type ScryptRecipient struct { |
| 32 | password []byte |
| 33 | workFactor int |
| 34 | } |
| 35 | |
| 36 | var _ Recipient = &ScryptRecipient{} |
| 37 | |
| 38 | // NewScryptRecipient returns a new ScryptRecipient with the provided password. |
| 39 | func NewScryptRecipient(password string) (*ScryptRecipient, error) { |
| 40 | if len(password) == 0 { |
| 41 | return nil, errors.New("passphrase can't be empty") |
| 42 | } |
| 43 | r := &ScryptRecipient{ |
| 44 | password: []byte(password), |
| 45 | // TODO: automatically scale this to 1s (with a min) in the CLI. |
| 46 | workFactor: 18, // 1s on a modern machine |
| 47 | } |
| 48 | return r, nil |
| 49 | } |
| 50 | |
| 51 | // SetWorkFactor sets the scrypt work factor to 2^logN. |
| 52 | // It must be called before Wrap. |
| 53 | // |
| 54 | // If SetWorkFactor is not called, a reasonable default is used. |
| 55 | func (r *ScryptRecipient) SetWorkFactor(logN int) { |
| 56 | if logN > 30 || logN < 1 { |
| 57 | panic("age: SetWorkFactor called with illegal value") |
| 58 | } |
| 59 | r.workFactor = logN |
| 60 | } |
| 61 | |
| 62 | const scryptSaltSize = 16 |
| 63 | |
| 64 | func (r *ScryptRecipient) Wrap(fileKey []byte) ([]*Stanza, error) { |
| 65 | salt := make([]byte, scryptSaltSize) |
| 66 | if _, err := rand.Read(salt[:]); err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | |
| 70 | logN := r.workFactor |
| 71 | l := &Stanza{ |
| 72 | Type: "scrypt", |
| 73 | Args: []string{format.EncodeToString(salt), strconv.Itoa(logN)}, |
| 74 | } |
| 75 | |
| 76 | salt = append([]byte(scryptLabel), salt...) |
| 77 | k, err := scrypt.Key(r.password, salt, 1<<logN, 8, 1, chacha20poly1305.KeySize) |
| 78 | if err != nil { |
| 79 | return nil, fmt.Errorf("failed to generate scrypt hash: %v", err) |
| 80 | } |
| 81 | |
| 82 | wrappedKey, err := aeadEncrypt(k, fileKey) |
| 83 | if err != nil { |
| 84 | return nil, err |
| 85 | } |
| 86 | l.Body = wrappedKey |
| 87 | |
| 88 | return []*Stanza{l}, nil |
| 89 | } |
| 90 | |
| 91 | // WrapWithLabels implements [age.RecipientWithLabels], returning a random |
| 92 | // label. This ensures a ScryptRecipient can't be mixed with other recipients |
| 93 | // (including other ScryptRecipients). |
| 94 | // |
| 95 | // Users reasonably expect files encrypted to a passphrase to be [authenticated] |
| 96 | // by that passphrase, i.e. for it to be impossible to produce a file that |
| 97 | // decrypts successfully with a passphrase without knowing it. If a file is |
| 98 | // encrypted to other recipients, those parties can produce different files that |
| 99 | // would break that expectation. |
| 100 | // |
| 101 | // [authenticated]: https://words.filippo.io/dispatches/age-authentication/ |
| 102 | func (r *ScryptRecipient) WrapWithLabels(fileKey []byte) (stanzas []*Stanza, labels []string, err error) { |
| 103 | stanzas, err = r.Wrap(fileKey) |
| 104 | |
| 105 | random := make([]byte, 16) |
| 106 | if _, err := rand.Read(random); err != nil { |
| 107 | return nil, nil, err |
| 108 | } |
| 109 | labels = []string{hex.EncodeToString(random)} |
| 110 | |
| 111 | return |
| 112 | } |
| 113 | |
| 114 | // ScryptIdentity is a password-based identity. |
| 115 | type ScryptIdentity struct { |
| 116 | password []byte |
| 117 | maxWorkFactor int |
| 118 | } |
| 119 | |
| 120 | var _ Identity = &ScryptIdentity{} |
| 121 | |
| 122 | // NewScryptIdentity returns a new ScryptIdentity with the provided password. |
| 123 | func NewScryptIdentity(password string) (*ScryptIdentity, error) { |
| 124 | if len(password) == 0 { |
| 125 | return nil, errors.New("passphrase can't be empty") |
| 126 | } |
| 127 | i := &ScryptIdentity{ |
| 128 | password: []byte(password), |
| 129 | maxWorkFactor: 22, // 15s on a modern machine |
| 130 | } |
| 131 | return i, nil |
| 132 | } |
| 133 | |
| 134 | // SetMaxWorkFactor sets the maximum accepted scrypt work factor to 2^logN. |
| 135 | // It must be called before Unwrap. |
| 136 | // |
| 137 | // This caps the amount of work that Decrypt might have to do to process |
| 138 | // received files. If SetMaxWorkFactor is not called, a fairly high default is |
| 139 | // used, which might not be suitable for systems processing untrusted files. |
| 140 | func (i *ScryptIdentity) SetMaxWorkFactor(logN int) { |
| 141 | if logN > 30 || logN < 1 { |
| 142 | panic("age: SetMaxWorkFactor called with illegal value") |
| 143 | } |
| 144 | i.maxWorkFactor = logN |
| 145 | } |
| 146 | |
| 147 | func (i *ScryptIdentity) Unwrap(stanzas []*Stanza) ([]byte, error) { |
| 148 | for _, s := range stanzas { |
| 149 | if s.Type == "scrypt" && len(stanzas) != 1 { |
| 150 | return nil, errors.New("an scrypt recipient must be the only one") |
| 151 | } |
| 152 | } |
| 153 | for _, s := range stanzas { |
| 154 | if s.Type != "scrypt" { |
| 155 | continue |
| 156 | } |
| 157 | return i.unwrap(s) |
| 158 | } |
| 159 | return nil, fmt.Errorf("%w: file is not passphrase-encrypted", ErrIncorrectIdentity) |
| 160 | } |
| 161 | |
| 162 | var digitsRe = regexp.MustCompile(`^[1-9][0-9]*$`) |
| 163 | |
| 164 | func (i *ScryptIdentity) unwrap(block *Stanza) ([]byte, error) { |
| 165 | if block.Type != "scrypt" { |
| 166 | return nil, errors.New("internal error: unwrap called on non-scrypt stanza") |
| 167 | } |
| 168 | if len(block.Args) != 2 { |
| 169 | return nil, errors.New("invalid scrypt recipient block") |
| 170 | } |
| 171 | salt, err := format.DecodeString(block.Args[0]) |
| 172 | if err != nil { |
| 173 | return nil, fmt.Errorf("failed to parse scrypt salt: %v", err) |
| 174 | } |
| 175 | if len(salt) != scryptSaltSize { |
| 176 | return nil, errors.New("invalid scrypt recipient block") |
| 177 | } |
| 178 | if w := block.Args[1]; !digitsRe.MatchString(w) { |
| 179 | return nil, fmt.Errorf("scrypt work factor encoding invalid: %q", w) |
| 180 | } |
| 181 | logN, err := strconv.Atoi(block.Args[1]) |
| 182 | if err != nil { |
| 183 | return nil, fmt.Errorf("failed to parse scrypt work factor: %v", err) |
| 184 | } |
| 185 | if logN > i.maxWorkFactor { |
| 186 | return nil, fmt.Errorf("scrypt work factor too large: %v", logN) |
| 187 | } |
| 188 | if logN <= 0 { // unreachable |
| 189 | return nil, fmt.Errorf("invalid scrypt work factor: %v", logN) |
| 190 | } |
| 191 | |
| 192 | salt = append([]byte(scryptLabel), salt...) |
| 193 | k, err := scrypt.Key(i.password, salt, 1<<logN, 8, 1, chacha20poly1305.KeySize) |
| 194 | if err != nil { // unreachable |
| 195 | return nil, fmt.Errorf("failed to generate scrypt hash: %v", err) |
| 196 | } |
| 197 | |
| 198 | // This AEAD is not robust, so an attacker could craft a message that |
| 199 | // decrypts under two different keys (meaning two different passphrases) and |
| 200 | // then use an error side-channel in an online decryption oracle to learn if |
| 201 | // either key is correct. This is deemed acceptable because the use case (an |
| 202 | // online decryption oracle) is not recommended, and the security loss is |
| 203 | // only one bit. This also does not bypass any scrypt work, although that work |
| 204 | // can be precomputed in an online oracle scenario. |
| 205 | fileKey, err := aeadDecrypt(k, fileKeySize, block.Body) |
| 206 | if err == errIncorrectCiphertextSize { |
| 207 | return nil, errors.New("invalid scrypt recipient block: incorrect file key size") |
| 208 | } else if err != nil { |
| 209 | // Wrap [ErrIncorrectIdentity] so that multiple passphrases can be tried |
| 210 | // in sequence by passing multiple [ScryptIdentity] values to [Decrypt]. |
| 211 | return nil, fmt.Errorf("%w: incorrect passphrase", ErrIncorrectIdentity) |
| 212 | } |
| 213 | return fileKey, nil |
| 214 | } |