| 1 |
/* |
| 2 |
* key.go - Cryptographic key management for fscrypt. Ensures that sensitive |
| 3 |
* material is properly handled throughout the program. |
| 4 |
* |
| 5 |
* Copyright 2017 Google Inc. |
| 6 |
* Author: Joe Richey ([email protected]) |
| 7 |
* |
| 8 |
* Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 9 |
* use this file except in compliance with the License. You may obtain a copy of |
| 10 |
* the License at |
| 11 |
* |
| 12 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 13 |
* |
| 14 |
* Unless required by applicable law or agreed to in writing, software |
| 15 |
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 16 |
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 17 |
* License for the specific language governing permissions and limitations under |
| 18 |
* the License. |
| 19 |
*/ |
| 20 |
|
| 21 |
package crypto |
| 22 |
|
| 23 |
/* |
| 24 |
#include <stdlib.h> |
| 25 |
#include <string.h> |
| 26 |
*/ |
| 27 |
import "C" |
| 28 |
|
| 29 |
import ( |
| 30 |
"bytes" |
| 31 |
"crypto/subtle" |
| 32 |
"encoding/base32" |
| 33 |
"io" |
| 34 |
"log" |
| 35 |
"os" |
| 36 |
"runtime" |
| 37 |
"unsafe" |
| 38 |
|
| 39 |
"github.com/pkg/errors" |
| 40 |
"golang.org/x/sys/unix" |
| 41 |
|
| 42 |
"github.com/google/fscrypt/metadata" |
| 43 |
"github.com/google/fscrypt/util" |
| 44 |
) |
| 45 |
|
| 46 |
const ( |
| 47 |
// Keys need to readable and writable, but hidden from other processes. |
| 48 |
keyProtection = unix.PROT_READ | unix.PROT_WRITE |
| 49 |
keyMmapFlags = unix.MAP_PRIVATE | unix.MAP_ANONYMOUS |
| 50 |
) |
| 51 |
|
| 52 |
/* |
| 53 |
UseMlock determines whether we should use the mlock/munlock syscalls to |
| 54 |
prevent sensitive data like keys and passphrases from being paged to disk. |
| 55 |
UseMlock defaults to true, but can be set to false if the application calling |
| 56 |
into this library has insufficient privileges to lock memory. Code using this |
| 57 |
package could also bind this setting to a flag by using: |
| 58 |
|
| 59 |
flag.BoolVar(&crypto.UseMlock, "lock-memory", true, "lock keys in memory") |
| 60 |
*/ |
| 61 |
var UseMlock = true |
| 62 |
|
| 63 |
/* |
| 64 |
Key protects some arbitrary buffer of cryptographic material. Its methods |
| 65 |
ensure that the Key's data is locked in memory before being used (if |
| 66 |
UseMlock is set to true), and is wiped and unlocked after use (via the Wipe() |
| 67 |
method). This data is never accessed outside of the fscrypt/crypto package |
| 68 |
(except for the UnsafeData method). If a key is successfully created, the |
| 69 |
Wipe() method should be called after it's use. For example: |
| 70 |
|
| 71 |
func UseKeyFromStdin() error { |
| 72 |
key, err := NewKeyFromReader(os.Stdin) |
| 73 |
if err != nil { |
| 74 |
return err |
| 75 |
} |
| 76 |
defer key.Wipe() |
| 77 |
|
| 78 |
// Do stuff with key |
| 79 |
|
| 80 |
return nil |
| 81 |
} |
| 82 |
|
| 83 |
The Wipe() method will also be called when a key is garbage collected; however, |
| 84 |
it is best practice to clear the key as soon as possible, so it spends a minimal |
| 85 |
amount of time in memory. |
| 86 |
|
| 87 |
Note that Key is not thread safe, as a key could be wiped while another thread |
| 88 |
is using it. Also, calling Wipe() from two threads could cause an error as |
| 89 |
memory could be freed twice. |
| 90 |
*/ |
| 91 |
type Key struct { |
| 92 |
data []byte |
| 93 |
} |
| 94 |
|
| 95 |
// NewBlankKey constructs a blank key of a specified length and returns an error |
| 96 |
// if we are unable to allocate or lock the necessary memory. |
| 97 |
func NewBlankKey(length int) (*Key, error) { |
| 98 |
if length == 0 { |
| 99 |
return &Key{data: nil}, nil |
| 100 |
} else if length < 0 { |
| 101 |
return nil, errors.Errorf("requested key length %d is negative", length) |
| 102 |
} |
| 103 |
|
| 104 |
flags := keyMmapFlags |
| 105 |
if UseMlock { |
| 106 |
flags |= unix.MAP_LOCKED |
| 107 |
} |
| 108 |
|
| 109 |
// See MAP_ANONYMOUS in http://man7.org/linux/man-pages/man2/mmap.2.html |
| 110 |
data, err := unix.Mmap(-1, 0, length, keyProtection, flags) |
| 111 |
if err == unix.EAGAIN { |
| 112 |
return nil, ErrMlockUlimit |
| 113 |
} |
| 114 |
if err != nil { |
| 115 |
return nil, errors.Wrapf(err, |
| 116 |
"failed to allocate (mmap) key buffer of length %d", length) |
| 117 |
} |
| 118 |
|
| 119 |
key := &Key{data: data} |
| 120 |
|
| 121 |
// Backup finalizer in case user forgets to "defer key.Wipe()" |
| 122 |
runtime.SetFinalizer(key, (*Key).Wipe) |
| 123 |
return key, nil |
| 124 |
} |
| 125 |
|
| 126 |
// Wipe destroys a Key by zeroing and freeing the memory. The data is zeroed |
| 127 |
// even if Wipe returns an error, which occurs if we are unable to unlock or |
| 128 |
// free the key memory. Wipe does nothing if the key is already wiped or is nil. |
| 129 |
func (key *Key) Wipe() error { |
| 130 |
// We do nothing if key or key.data is nil so that Wipe() is idempotent |
| 131 |
// and so Wipe() can be called on keys which have already been cleared. |
| 132 |
if key != nil && key.data != nil { |
| 133 |
data := key.data |
| 134 |
key.data = nil |
| 135 |
|
| 136 |
for i := range data { |
| 137 |
data[i] = 0 |
| 138 |
} |
| 139 |
|
| 140 |
if err := unix.Munmap(data); err != nil { |
| 141 |
log.Printf("unix.Munmap() failed: %v", err) |
| 142 |
return errors.Wrapf(err, "failed to free (munmap) key buffer") |
| 143 |
} |
| 144 |
} |
| 145 |
return nil |
| 146 |
} |
| 147 |
|
| 148 |
// Len is the underlying data buffer's length. |
| 149 |
func (key *Key) Len() int { |
| 150 |
return len(key.data) |
| 151 |
} |
| 152 |
|
| 153 |
// Equals compares the contents of two keys, returning true if they have the same |
| 154 |
// key data. This function runs in constant time. |
| 155 |
func (key *Key) Equals(key2 *Key) bool { |
| 156 |
return subtle.ConstantTimeCompare(key.data, key2.data) == 1 |
| 157 |
} |
| 158 |
|
| 159 |
// resize returns a new key with size requestedSize and the appropriate data |
| 160 |
// copied over. The original data is wiped. This method does nothing and returns |
| 161 |
// itself if the key's length equals requestedSize. |
| 162 |
func (key *Key) resize(requestedSize int) (*Key, error) { |
| 163 |
if key.Len() == requestedSize { |
| 164 |
return key, nil |
| 165 |
} |
| 166 |
defer key.Wipe() |
| 167 |
|
| 168 |
resizedKey, err := NewBlankKey(requestedSize) |
| 169 |
if err != nil { |
| 170 |
return nil, err |
| 171 |
} |
| 172 |
copy(resizedKey.data, key.data) |
| 173 |
return resizedKey, nil |
| 174 |
} |
| 175 |
|
| 176 |
// Data returns a slice of the key's underlying data. Note that this may become |
| 177 |
// outdated if the key is resized. |
| 178 |
func (key *Key) Data() []byte { |
| 179 |
return key.data |
| 180 |
} |
| 181 |
|
| 182 |
// UnsafePtr returns an unsafe pointer to the key's underlying data. Note that |
| 183 |
// this will only be valid as long as the key is not resized. |
| 184 |
func (key *Key) UnsafePtr() unsafe.Pointer { |
| 185 |
return util.Ptr(key.data) |
| 186 |
} |
| 187 |
|
| 188 |
// UnsafeToCString makes a copy of the string's data into a null-terminated C |
| 189 |
// string allocated by C. Note that this method is unsafe as this C copy has no |
| 190 |
// locking or wiping functionality. The key shouldn't contain any `\0` bytes. |
| 191 |
func (key *Key) UnsafeToCString() unsafe.Pointer { |
| 192 |
size := C.size_t(key.Len()) |
| 193 |
data := C.calloc(size+1, 1) |
| 194 |
C.memcpy(data, util.Ptr(key.data), size) |
| 195 |
return data |
| 196 |
} |
| 197 |
|
| 198 |
// Clone creates a key as a copy of another one. |
| 199 |
func (key *Key) Clone() (*Key, error) { |
| 200 |
newKey, err := NewBlankKey(key.Len()) |
| 201 |
if err != nil { |
| 202 |
return nil, err |
| 203 |
} |
| 204 |
copy(newKey.data, key.data) |
| 205 |
return newKey, nil |
| 206 |
} |
| 207 |
|
| 208 |
// NewKeyFromCString creates of a copy of some C string's data in a key. Note |
| 209 |
// that the original C string is not modified at all, so steps must be taken to |
| 210 |
// ensure that this original copy is secured. |
| 211 |
func NewKeyFromCString(str unsafe.Pointer) (*Key, error) { |
| 212 |
size := C.strlen((*C.char)(str)) |
| 213 |
key, err := NewBlankKey(int(size)) |
| 214 |
if err != nil { |
| 215 |
return nil, err |
| 216 |
} |
| 217 |
C.memcpy(util.Ptr(key.data), str, size) |
| 218 |
return key, nil |
| 219 |
} |
| 220 |
|
| 221 |
// NewKeyFromReader constructs a key of arbitrary length by reading from reader |
| 222 |
// until hitting EOF. |
| 223 |
func NewKeyFromReader(reader io.Reader) (*Key, error) { |
| 224 |
// Use an initial key size of a page. As Mmap allocates a page anyway, |
| 225 |
// there isn't much additional overhead from starting with a whole page. |
| 226 |
key, err := NewBlankKey(os.Getpagesize()) |
| 227 |
if err != nil { |
| 228 |
return nil, err |
| 229 |
} |
| 230 |
|
| 231 |
totalBytesRead := 0 |
| 232 |
for { |
| 233 |
bytesRead, err := reader.Read(key.data[totalBytesRead:]) |
| 234 |
totalBytesRead += bytesRead |
| 235 |
|
| 236 |
switch err { |
| 237 |
case nil: |
| 238 |
// Need to continue reading. Grow key if necessary |
| 239 |
if key.Len() == totalBytesRead { |
| 240 |
if key, err = key.resize(2 * key.Len()); err != nil { |
| 241 |
return nil, err |
| 242 |
} |
| 243 |
} |
| 244 |
case io.EOF: |
| 245 |
// Getting the EOF error means we are done |
| 246 |
return key.resize(totalBytesRead) |
| 247 |
default: |
| 248 |
// Fail if Read() has a failure |
| 249 |
key.Wipe() |
| 250 |
return nil, err |
| 251 |
} |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
// NewFixedLengthKeyFromReader constructs a key with a specified length by |
| 256 |
// reading exactly length bytes from reader. |
| 257 |
func NewFixedLengthKeyFromReader(reader io.Reader, length int) (*Key, error) { |
| 258 |
key, err := NewBlankKey(length) |
| 259 |
if err != nil { |
| 260 |
return nil, err |
| 261 |
} |
| 262 |
if _, err := io.ReadFull(reader, key.data); err != nil { |
| 263 |
key.Wipe() |
| 264 |
return nil, err |
| 265 |
} |
| 266 |
return key, nil |
| 267 |
} |
| 268 |
|
| 269 |
var ( |
| 270 |
// The recovery code is base32 with a dash between each block of 8 characters. |
| 271 |
encoding = base32.StdEncoding |
| 272 |
blockSize = 8 |
| 273 |
separator = []byte("-") |
| 274 |
encodedLength = encoding.EncodedLen(metadata.PolicyKeyLen) |
| 275 |
decodedLength = encoding.DecodedLen(encodedLength) |
| 276 |
// RecoveryCodeLength is the number of bytes in every recovery code |
| 277 |
RecoveryCodeLength = (encodedLength/blockSize)*(blockSize+len(separator)) - len(separator) |
| 278 |
) |
| 279 |
|
| 280 |
// WriteRecoveryCode outputs key's recovery code to the provided writer. |
| 281 |
// WARNING: This recovery key is enough to derive the original key, so it must |
| 282 |
// be given the same level of protection as a raw cryptographic key. |
| 283 |
func WriteRecoveryCode(key *Key, writer io.Writer) error { |
| 284 |
if err := util.CheckValidLength(metadata.PolicyKeyLen, key.Len()); err != nil { |
| 285 |
return errors.Wrap(err, "recovery key") |
| 286 |
} |
| 287 |
|
| 288 |
// We store the base32 encoded data (without separators) in a temp key |
| 289 |
encodedKey, err := NewBlankKey(encodedLength) |
| 290 |
if err != nil { |
| 291 |
return err |
| 292 |
} |
| 293 |
defer encodedKey.Wipe() |
| 294 |
encoding.Encode(encodedKey.data, key.data) |
| 295 |
|
| 296 |
w := util.NewErrWriter(writer) |
| 297 |
|
| 298 |
// Write the blocks with separators between them |
| 299 |
w.Write(encodedKey.data[:blockSize]) |
| 300 |
for blockStart := blockSize; blockStart < encodedLength; blockStart += blockSize { |
| 301 |
w.Write(separator) |
| 302 |
|
| 303 |
blockEnd := util.MinInt(blockStart+blockSize, encodedLength) |
| 304 |
w.Write(encodedKey.data[blockStart:blockEnd]) |
| 305 |
} |
| 306 |
|
| 307 |
// If any writes have failed, return the error |
| 308 |
return w.Err() |
| 309 |
} |
| 310 |
|
| 311 |
// ReadRecoveryCode gets the recovery code from the provided reader and returns |
| 312 |
// the corresponding cryptographic key. |
| 313 |
// WARNING: This recovery key is enough to derive the original key, so it must |
| 314 |
// be given the same level of protection as a raw cryptographic key. |
| 315 |
func ReadRecoveryCode(reader io.Reader) (*Key, error) { |
| 316 |
// We store the base32 encoded data (without separators) in a temp key |
| 317 |
encodedKey, err := NewBlankKey(encodedLength) |
| 318 |
if err != nil { |
| 319 |
return nil, err |
| 320 |
} |
| 321 |
defer encodedKey.Wipe() |
| 322 |
|
| 323 |
r := util.NewErrReader(reader) |
| 324 |
|
| 325 |
// Read the other blocks, checking the separators between them |
| 326 |
r.Read(encodedKey.data[:blockSize]) |
| 327 |
inputSeparator := make([]byte, len(separator)) |
| 328 |
|
| 329 |
for blockStart := blockSize; blockStart < encodedLength; blockStart += blockSize { |
| 330 |
r.Read(inputSeparator) |
| 331 |
if r.Err() == nil && !bytes.Equal(separator, inputSeparator) { |
| 332 |
err = errors.Wrapf(ErrRecoveryCode, "invalid separator %q", inputSeparator) |
| 333 |
return nil, err |
| 334 |
} |
| 335 |
|
| 336 |
blockEnd := util.MinInt(blockStart+blockSize, encodedLength) |
| 337 |
r.Read(encodedKey.data[blockStart:blockEnd]) |
| 338 |
} |
| 339 |
|
| 340 |
// If any reads have failed, return the error |
| 341 |
if r.Err() != nil { |
| 342 |
return nil, errors.Wrapf(ErrRecoveryCode, "read error %v", r.Err()) |
| 343 |
} |
| 344 |
|
| 345 |
// Now we decode the key, resizing if necessary |
| 346 |
decodedKey, err := NewBlankKey(decodedLength) |
| 347 |
if err != nil { |
| 348 |
return nil, err |
| 349 |
} |
| 350 |
if _, err = encoding.Decode(decodedKey.data, encodedKey.data); err != nil { |
| 351 |
return nil, errors.Wrap(ErrRecoveryCode, err.Error()) |
| 352 |
} |
| 353 |
return decodedKey.resize(metadata.PolicyKeyLen) |
| 354 |
} |