Debian Codegraph @

crypto/crypto.go

raw
1 /*
2 * crypto.go - Cryptographic algorithms used by the rest of fscrypt.
3 *
4 * Copyright 2017 Google Inc.
5 * Author: Joe Richey ([email protected])
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
8 * use this file except in compliance with the License. You may obtain a copy of
9 * the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 * License for the specific language governing permissions and limitations under
17 * the License.
18 */
19
20 // Package crypto manages all the cryptography for fscrypt. This includes:
21 // 1. Key management (key.go)
22 // - Securely holding keys in memory
23 // - Making recovery keys
24 // 2. Randomness (rand.go)
25 // 3. Cryptographic algorithms (crypto.go)
26 // - encryption (AES256-CTR)
27 // - authentication (SHA256-based HMAC)
28 // - key stretching (SHA256-based HKDF)
29 // - key wrapping/unwrapping (Encrypt then MAC)
30 // - passphrase-based key derivation (Argon2id)
31 // - key descriptor computation (double SHA512, or HKDF-SHA512)
32 package crypto
33
34 import (
35 "crypto/aes"
36 "crypto/cipher"
37 "crypto/hmac"
38 "crypto/sha256"
39 "crypto/sha512"
40 "encoding/hex"
41 "io"
42
43 "github.com/pkg/errors"
44 "golang.org/x/crypto/argon2"
45 "golang.org/x/crypto/hkdf"
46
47 "github.com/google/fscrypt/metadata"
48 "github.com/google/fscrypt/util"
49 )
50
51 // Crypto error values
52 var (
53 ErrBadAuth = errors.New("key authentication check failed")
54 ErrRecoveryCode = errors.New("invalid recovery code")
55 ErrMlockUlimit = errors.New("could not lock key in memory")
56 )
57
58 // panicInputLength panics if "name" has invalid length (expected != actual)
59 func panicInputLength(name string, expected, actual int) {
60 if err := util.CheckValidLength(expected, actual); err != nil {
61 panic(errors.Wrap(err, name))
62 }
63 }
64
65 // checkWrappingKey returns an error if the wrapping key has the wrong length
66 func checkWrappingKey(wrappingKey *Key) error {
67 err := util.CheckValidLength(metadata.InternalKeyLen, wrappingKey.Len())
68 return errors.Wrap(err, "wrapping key")
69 }
70
71 // stretchKey stretches a key of length InternalKeyLen using unsalted HKDF to
72 // make two keys of length InternalKeyLen.
73 func stretchKey(key *Key) (encKey, authKey *Key) {
74 panicInputLength("hkdf key", metadata.InternalKeyLen, key.Len())
75
76 // The new hkdf function uses the hash and key to create a reader that
77 // can be used to securely initialize multiple keys. This means that
78 // reads on the hkdf give independent cryptographic keys. The hkdf will
79 // also always have enough entropy to read two keys.
80 hkdf := hkdf.New(sha256.New, key.data, nil, nil)
81
82 encKey, err := NewFixedLengthKeyFromReader(hkdf, metadata.InternalKeyLen)
83 util.NeverError(err)
84 authKey, err = NewFixedLengthKeyFromReader(hkdf, metadata.InternalKeyLen)
85 util.NeverError(err)
86
87 return
88 }
89
90 // aesCTR runs AES256-CTR on the input using the provided key and iv. This
91 // function can be used to either encrypt or decrypt input of any size. Note
92 // that input and output must be the same size.
93 func aesCTR(key *Key, iv, input, output []byte) {
94 panicInputLength("aesCTR key", metadata.InternalKeyLen, key.Len())
95 panicInputLength("aesCTR iv", metadata.IVLen, len(iv))
96 panicInputLength("aesCTR output", len(input), len(output))
97
98 blockCipher, err := aes.NewCipher(key.data)
99 util.NeverError(err) // Key is checked to have correct length
100
101 stream := cipher.NewCTR(blockCipher, iv)
102 stream.XORKeyStream(output, input)
103 }
104
105 // getHMAC returns the SHA256-based HMAC of some data using the provided key.
106 func getHMAC(key *Key, data ...[]byte) []byte {
107 panicInputLength("hmac key", metadata.InternalKeyLen, key.Len())
108
109 mac := hmac.New(sha256.New, key.data)
110 for _, buffer := range data {
111 // SHA256 HMAC should never be unable to write the data
112 _, err := mac.Write(buffer)
113 util.NeverError(err)
114 }
115
116 return mac.Sum(nil)
117 }
118
119 // Wrap takes a wrapping Key of length InternalKeyLen, and uses it to wrap a
120 // secret Key of any length. This wrapping uses a random IV, the encrypted data,
121 // and an HMAC to verify the wrapping key was correct. All of this is included
122 // in the returned WrappedKeyData structure.
123 func Wrap(wrappingKey, secretKey *Key) (*metadata.WrappedKeyData, error) {
124 if err := checkWrappingKey(wrappingKey); err != nil {
125 return nil, err
126 }
127
128 data := &metadata.WrappedKeyData{EncryptedKey: make([]byte, secretKey.Len())}
129
130 // Get random IV
131 var err error
132 if data.IV, err = NewRandomBuffer(metadata.IVLen); err != nil {
133 return nil, err
134 }
135
136 // Stretch key for encryption and authentication (unsalted).
137 encKey, authKey := stretchKey(wrappingKey)
138 defer encKey.Wipe()
139 defer authKey.Wipe()
140
141 // Encrypt the secret and include the HMAC of the output ("Encrypt-then-MAC").
142 aesCTR(encKey, data.IV, secretKey.data, data.EncryptedKey)
143
144 data.Hmac = getHMAC(authKey, data.IV, data.EncryptedKey)
145 return data, nil
146 }
147
148 // Unwrap takes a wrapping Key of length InternalKeyLen, and uses it to unwrap
149 // the WrappedKeyData to get the unwrapped secret Key. The Wrapped Key data
150 // includes an authentication check, so an error will be returned if that check
151 // fails.
152 func Unwrap(wrappingKey *Key, data *metadata.WrappedKeyData) (*Key, error) {
153 if err := checkWrappingKey(wrappingKey); err != nil {
154 return nil, err
155 }
156
157 // Stretch key for encryption and authentication (unsalted).
158 encKey, authKey := stretchKey(wrappingKey)
159 defer encKey.Wipe()
160 defer authKey.Wipe()
161
162 // Check validity of the HMAC
163 if !hmac.Equal(getHMAC(authKey, data.IV, data.EncryptedKey), data.Hmac) {
164 return nil, ErrBadAuth
165 }
166
167 secretKey, err := NewBlankKey(len(data.EncryptedKey))
168 if err != nil {
169 return nil, err
170 }
171 aesCTR(encKey, data.IV, data.EncryptedKey, secretKey.data)
172
173 return secretKey, nil
174 }
175
176 func computeKeyDescriptorV1(key *Key) string {
177 h1 := sha512.Sum512(key.data)
178 h2 := sha512.Sum512(h1[:])
179 length := hex.DecodedLen(metadata.PolicyDescriptorLenV1)
180 return hex.EncodeToString(h2[:length])
181 }
182
183 func computeKeyDescriptorV2(key *Key) (string, error) {
184 // This algorithm is specified by the kernel. It uses unsalted
185 // HKDF-SHA512, where the application-information string is the prefix
186 // "fscrypt\0" followed by the HKDF_CONTEXT_KEY_IDENTIFIER byte.
187 hkdf := hkdf.New(sha512.New, key.data, nil, []byte("fscrypt\x00\x01"))
188 h := make([]byte, hex.DecodedLen(metadata.PolicyDescriptorLenV2))
189 if _, err := io.ReadFull(hkdf, h); err != nil {
190 return "", err
191 }
192 return hex.EncodeToString(h), nil
193 }
194
195 // ComputeKeyDescriptor computes the descriptor for a given cryptographic key.
196 // If policyVersion=1, it uses the first 8 bytes of the double application of
197 // SHA512 on the key. Use this for protectors and v1 policy keys.
198 // If policyVersion=2, it uses HKDF-SHA512 to compute a key identifier that's
199 // compatible with the kernel's key identifiers for v2 policy keys.
200 // In both cases, the resulting bytes are formatted as hex.
201 func ComputeKeyDescriptor(key *Key, policyVersion int64) (string, error) {
202 switch policyVersion {
203 case 1:
204 return computeKeyDescriptorV1(key), nil
205 case 2:
206 return computeKeyDescriptorV2(key)
207 default:
208 return "", errors.Errorf("policy version of %d is invalid", policyVersion)
209 }
210 }
211
212 // PassphraseHash uses Argon2id to produce a Key given the passphrase, salt, and
213 // hashing costs. This method is designed to take a long time and consume
214 // considerable memory. For more information, see the documentation at
215 // https://godoc.org/golang.org/x/crypto/argon2.
216 func PassphraseHash(passphrase *Key, salt []byte, costs *metadata.HashingCosts) (*Key, error) {
217 t := uint32(costs.Time)
218 m := uint32(costs.Memory)
219 p := uint8(costs.Parallelism)
220 key := argon2.IDKey(passphrase.data, salt, t, m, p, metadata.InternalKeyLen)
221
222 hash, err := NewBlankKey(metadata.InternalKeyLen)
223 if err != nil {
224 return nil, err
225 }
226 copy(hash.data, key)
227 return hash, nil
228 }