File Index
Files and directories
Sign in
FILE

keystore.c

File preview with syntax highlighting.

linux-6.19.14/fs/ecryptfs/keystore.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 * eCryptfs: Linux filesystem encryption layer
   4 * In-kernel key management code.  Includes functions to parse and
   5 * write authentication token-related packets with the underlying
   6 * file.
   7 *
   8 * Copyright (C) 2004-2006 International Business Machines Corp.
   9 *   Author(s): Michael A. Halcrow <mhalcrow@us.ibm.com>
  10 *              Michael C. Thompson <mcthomps@us.ibm.com>
  11 *              Trevor S. Highland <trevor.highland@gmail.com>
  12 */
  13
  14#include <crypto/skcipher.h>
  15#include <linux/string.h>
  16#include <linux/pagemap.h>
  17#include <linux/key.h>
  18#include <linux/random.h>
  19#include <linux/scatterlist.h>
  20#include <linux/slab.h>
  21#include "ecryptfs_kernel.h"
  22
  23/*
  24 * request_key returned an error instead of a valid key address;
  25 * determine the type of error, make appropriate log entries, and
  26 * return an error code.
  27 */
  28static int process_request_key_err(long err_code)
  29{
  30	int rc = 0;
  31
  32	switch (err_code) {
  33	case -ENOKEY:
  34		ecryptfs_printk(KERN_WARNING, "No key\n");
  35		rc = -ENOENT;
  36		break;
  37	case -EKEYEXPIRED:
  38		ecryptfs_printk(KERN_WARNING, "Key expired\n");
  39		rc = -ETIME;
  40		break;
  41	case -EKEYREVOKED:
  42		ecryptfs_printk(KERN_WARNING, "Key revoked\n");
  43		rc = -EINVAL;
  44		break;
  45	default:
  46		ecryptfs_printk(KERN_WARNING, "Unknown error code: "
  47				"[0x%.16lx]\n", err_code);
  48		rc = -EINVAL;
  49	}
  50	return rc;
  51}
  52
  53static int process_find_global_auth_tok_for_sig_err(int err_code)
  54{
  55	int rc = err_code;
  56
  57	switch (err_code) {
  58	case -ENOENT:
  59		ecryptfs_printk(KERN_WARNING, "Missing auth tok\n");
  60		break;
  61	case -EINVAL:
  62		ecryptfs_printk(KERN_WARNING, "Invalid auth tok\n");
  63		break;
  64	default:
  65		rc = process_request_key_err(err_code);
  66		break;
  67	}
  68	return rc;
  69}
  70
  71/**
  72 * ecryptfs_parse_packet_length
  73 * @data: Pointer to memory containing length at offset
  74 * @size: This function writes the decoded size to this memory
  75 *        address; zero on error
  76 * @length_size: The number of bytes occupied by the encoded length
  77 *
  78 * Returns zero on success; non-zero on error
  79 */
  80int ecryptfs_parse_packet_length(unsigned char *data, size_t *size,
  81				 size_t *length_size)
  82{
  83	int rc = 0;
  84
  85	(*length_size) = 0;
  86	(*size) = 0;
  87	if (data[0] < 192) {
  88		/* One-byte length */
  89		(*size) = data[0];
  90		(*length_size) = 1;
  91	} else if (data[0] < 224) {
  92		/* Two-byte length */
  93		(*size) = (data[0] - 192) * 256;
  94		(*size) += data[1] + 192;
  95		(*length_size) = 2;
  96	} else if (data[0] == 255) {
  97		/* If support is added, adjust ECRYPTFS_MAX_PKT_LEN_SIZE */
  98		ecryptfs_printk(KERN_ERR, "Five-byte packet length not "
  99				"supported\n");
 100		rc = -EINVAL;
 101		goto out;
 102	} else {
 103		ecryptfs_printk(KERN_ERR, "Error parsing packet length\n");
 104		rc = -EINVAL;
 105		goto out;
 106	}
 107out:
 108	return rc;
 109}
 110
 111/**
 112 * ecryptfs_write_packet_length
 113 * @dest: The byte array target into which to write the length. Must
 114 *        have at least ECRYPTFS_MAX_PKT_LEN_SIZE bytes allocated.
 115 * @size: The length to write.
 116 * @packet_size_length: The number of bytes used to encode the packet
 117 *                      length is written to this address.
 118 *
 119 * Returns zero on success; non-zero on error.
 120 */
 121int ecryptfs_write_packet_length(char *dest, size_t size,
 122				 size_t *packet_size_length)
 123{
 124	int rc = 0;
 125
 126	if (size < 192) {
 127		dest[0] = size;
 128		(*packet_size_length) = 1;
 129	} else if (size < 65536) {
 130		dest[0] = (((size - 192) / 256) + 192);
 131		dest[1] = ((size - 192) % 256);
 132		(*packet_size_length) = 2;
 133	} else {
 134		/* If support is added, adjust ECRYPTFS_MAX_PKT_LEN_SIZE */
 135		rc = -EINVAL;
 136		ecryptfs_printk(KERN_WARNING,
 137				"Unsupported packet size: [%zd]\n", size);
 138	}
 139	return rc;
 140}
 141
 142static int
 143write_tag_64_packet(char *signature, struct ecryptfs_session_key *session_key,
 144		    char **packet, size_t *packet_len)
 145{
 146	size_t i = 0;
 147	size_t data_len;
 148	size_t packet_size_len;
 149	char *message;
 150	int rc;
 151
 152	/*
 153	 *              ***** TAG 64 Packet Format *****
 154	 *    | Content Type                       | 1 byte       |
 155	 *    | Key Identifier Size                | 1 or 2 bytes |
 156	 *    | Key Identifier                     | arbitrary    |
 157	 *    | Encrypted File Encryption Key Size | 1 or 2 bytes |
 158	 *    | Encrypted File Encryption Key      | arbitrary    |
 159	 */
 160	data_len = (5 + ECRYPTFS_SIG_SIZE_HEX
 161		    + session_key->encrypted_key_size);
 162	*packet = kmalloc(data_len, GFP_KERNEL);
 163	message = *packet;
 164	if (!message) {
 165		ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
 166		rc = -ENOMEM;
 167		goto out;
 168	}
 169	message[i++] = ECRYPTFS_TAG_64_PACKET_TYPE;
 170	rc = ecryptfs_write_packet_length(&message[i], ECRYPTFS_SIG_SIZE_HEX,
 171					  &packet_size_len);
 172	if (rc) {
 173		ecryptfs_printk(KERN_ERR, "Error generating tag 64 packet "
 174				"header; cannot generate packet length\n");
 175		goto out;
 176	}
 177	i += packet_size_len;
 178	memcpy(&message[i], signature, ECRYPTFS_SIG_SIZE_HEX);
 179	i += ECRYPTFS_SIG_SIZE_HEX;
 180	rc = ecryptfs_write_packet_length(&message[i],
 181					  session_key->encrypted_key_size,
 182					  &packet_size_len);
 183	if (rc) {
 184		ecryptfs_printk(KERN_ERR, "Error generating tag 64 packet "
 185				"header; cannot generate packet length\n");
 186		goto out;
 187	}
 188	i += packet_size_len;
 189	memcpy(&message[i], session_key->encrypted_key,
 190	       session_key->encrypted_key_size);
 191	i += session_key->encrypted_key_size;
 192	*packet_len = i;
 193out:
 194	return rc;
 195}
 196
 197static int
 198parse_tag_65_packet(struct ecryptfs_session_key *session_key, u8 *cipher_code,
 199		    struct ecryptfs_message *msg)
 200{
 201	size_t i = 0;
 202	char *data;
 203	size_t data_len;
 204	size_t m_size;
 205	size_t message_len;
 206	u16 checksum = 0;
 207	u16 expected_checksum = 0;
 208	int rc;
 209
 210	/*
 211	 *              ***** TAG 65 Packet Format *****
 212	 *         | Content Type             | 1 byte       |
 213	 *         | Status Indicator         | 1 byte       |
 214	 *         | File Encryption Key Size | 1 or 2 bytes |
 215	 *         | File Encryption Key      | arbitrary    |
 216	 */
 217	message_len = msg->data_len;
 218	data = msg->data;
 219	if (message_len < 4) {
 220		rc = -EIO;
 221		goto out;
 222	}
 223	if (data[i++] != ECRYPTFS_TAG_65_PACKET_TYPE) {
 224		ecryptfs_printk(KERN_ERR, "Type should be ECRYPTFS_TAG_65\n");
 225		rc = -EIO;
 226		goto out;
 227	}
 228	if (data[i++]) {
 229		ecryptfs_printk(KERN_ERR, "Status indicator has non-zero value "
 230				"[%d]\n", data[i-1]);
 231		rc = -EIO;
 232		goto out;
 233	}
 234	rc = ecryptfs_parse_packet_length(&data[i], &m_size, &data_len);
 235	if (rc) {
 236		ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
 237				"rc = [%d]\n", rc);
 238		goto out;
 239	}
 240	i += data_len;
 241	if (message_len < (i + m_size)) {
 242		ecryptfs_printk(KERN_ERR, "The message received from ecryptfsd "
 243				"is shorter than expected\n");
 244		rc = -EIO;
 245		goto out;
 246	}
 247	if (m_size < 3) {
 248		ecryptfs_printk(KERN_ERR,
 249				"The decrypted key is not long enough to "
 250				"include a cipher code and checksum\n");
 251		rc = -EIO;
 252		goto out;
 253	}
 254	*cipher_code = data[i++];
 255	/* The decrypted key includes 1 byte cipher code and 2 byte checksum */
 256	session_key->decrypted_key_size = m_size - 3;
 257	if (session_key->decrypted_key_size > ECRYPTFS_MAX_KEY_BYTES) {
 258		ecryptfs_printk(KERN_ERR, "key_size [%d] larger than "
 259				"the maximum key size [%d]\n",
 260				session_key->decrypted_key_size,
 261				ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES);
 262		rc = -EIO;
 263		goto out;
 264	}
 265	memcpy(session_key->decrypted_key, &data[i],
 266	       session_key->decrypted_key_size);
 267	i += session_key->decrypted_key_size;
 268	expected_checksum += (unsigned char)(data[i++]) << 8;
 269	expected_checksum += (unsigned char)(data[i++]);
 270	for (i = 0; i < session_key->decrypted_key_size; i++)
 271		checksum += session_key->decrypted_key[i];
 272	if (expected_checksum != checksum) {
 273		ecryptfs_printk(KERN_ERR, "Invalid checksum for file "
 274				"encryption  key; expected [%x]; calculated "
 275				"[%x]\n", expected_checksum, checksum);
 276		rc = -EIO;
 277	}
 278out:
 279	return rc;
 280}
 281
 282
 283static int
 284write_tag_66_packet(char *signature, u8 cipher_code,
 285		    struct ecryptfs_crypt_stat *crypt_stat, char **packet,
 286		    size_t *packet_len)
 287{
 288	size_t i = 0;
 289	size_t j;
 290	size_t data_len;
 291	size_t checksum = 0;
 292	size_t packet_size_len;
 293	char *message;
 294	int rc;
 295
 296	/*
 297	 *              ***** TAG 66 Packet Format *****
 298	 *         | Content Type             | 1 byte       |
 299	 *         | Key Identifier Size      | 1 or 2 bytes |
 300	 *         | Key Identifier           | arbitrary    |
 301	 *         | File Encryption Key Size | 1 or 2 bytes |
 302	 *         | Cipher Code              | 1 byte       |
 303	 *         | File Encryption Key      | arbitrary    |
 304	 *         | Checksum                 | 2 bytes      |
 305	 */
 306	data_len = (8 + ECRYPTFS_SIG_SIZE_HEX + crypt_stat->key_size);
 307	*packet = kmalloc(data_len, GFP_KERNEL);
 308	message = *packet;
 309	if (!message) {
 310		ecryptfs_printk(KERN_ERR, "Unable to allocate memory\n");
 311		rc = -ENOMEM;
 312		goto out;
 313	}
 314	message[i++] = ECRYPTFS_TAG_66_PACKET_TYPE;
 315	rc = ecryptfs_write_packet_length(&message[i], ECRYPTFS_SIG_SIZE_HEX,
 316					  &packet_size_len);
 317	if (rc) {
 318		ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet "
 319				"header; cannot generate packet length\n");
 320		goto out;
 321	}
 322	i += packet_size_len;
 323	memcpy(&message[i], signature, ECRYPTFS_SIG_SIZE_HEX);
 324	i += ECRYPTFS_SIG_SIZE_HEX;
 325	/* The encrypted key includes 1 byte cipher code and 2 byte checksum */
 326	rc = ecryptfs_write_packet_length(&message[i], crypt_stat->key_size + 3,
 327					  &packet_size_len);
 328	if (rc) {
 329		ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet "
 330				"header; cannot generate packet length\n");
 331		goto out;
 332	}
 333	i += packet_size_len;
 334	message[i++] = cipher_code;
 335	memcpy(&message[i], crypt_stat->key, crypt_stat->key_size);
 336	i += crypt_stat->key_size;
 337	for (j = 0; j < crypt_stat->key_size; j++)
 338		checksum += crypt_stat->key[j];
 339	message[i++] = (checksum / 256) % 256;
 340	message[i++] = (checksum % 256);
 341	*packet_len = i;
 342out:
 343	return rc;
 344}
 345
 346static int
 347parse_tag_67_packet(struct ecryptfs_key_record *key_rec,
 348		    struct ecryptfs_message *msg)
 349{
 350	size_t i = 0;
 351	char *data;
 352	size_t data_len;
 353	size_t message_len;
 354	int rc;
 355
 356	/*
 357	 *              ***** TAG 65 Packet Format *****
 358	 *    | Content Type                       | 1 byte       |
 359	 *    | Status Indicator                   | 1 byte       |
 360	 *    | Encrypted File Encryption Key Size | 1 or 2 bytes |
 361	 *    | Encrypted File Encryption Key      | arbitrary    |
 362	 */
 363	message_len = msg->data_len;
 364	data = msg->data;
 365	/* verify that everything through the encrypted FEK size is present */
 366	if (message_len < 4) {
 367		rc = -EIO;
 368		printk(KERN_ERR "%s: message_len is [%zd]; minimum acceptable "
 369		       "message length is [%d]\n", __func__, message_len, 4);
 370		goto out;
 371	}
 372	if (data[i++] != ECRYPTFS_TAG_67_PACKET_TYPE) {
 373		rc = -EIO;
 374		printk(KERN_ERR "%s: Type should be ECRYPTFS_TAG_67\n",
 375		       __func__);
 376		goto out;
 377	}
 378	if (data[i++]) {
 379		rc = -EIO;
 380		printk(KERN_ERR "%s: Status indicator has non zero "
 381		       "value [%d]\n", __func__, data[i-1]);
 382
 383		goto out;
 384	}
 385	rc = ecryptfs_parse_packet_length(&data[i], &key_rec->enc_key_size,
 386					  &data_len);
 387	if (rc) {
 388		ecryptfs_printk(KERN_WARNING, "Error parsing packet length; "
 389				"rc = [%d]\n", rc);
 390		goto out;
 391	}
 392	i += data_len;
 393	if (message_len < (i + key_rec->enc_key_size)) {
 394		rc = -EIO;
 395		printk(KERN_ERR "%s: message_len [%zd]; max len is [%zd]\n",
 396		       __func__, message_len, (i + key_rec->enc_key_size));
 397		goto out;
 398	}
 399	if (key_rec->enc_key_size > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
 400		rc = -EIO;
 401		printk(KERN_ERR "%s: Encrypted key_size [%zd] larger than "
 402		       "the maximum key size [%d]\n", __func__,
 403		       key_rec->enc_key_size,
 404		       ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES);
 405		goto out;
 406	}
 407	memcpy(key_rec->enc_key, &data[i], key_rec->enc_key_size);
 408out:
 409	return rc;
 410}
 411
 412/**
 413 * ecryptfs_verify_version
 414 * @version: The version number to confirm
 415 *
 416 * Returns zero on good version; non-zero otherwise
 417 */
 418static int ecryptfs_verify_version(u16 version)
 419{
 420	int rc = 0;
 421	unsigned char major;
 422	unsigned char minor;
 423
 424	major = ((version >> 8) & 0xFF);
 425	minor = (version & 0xFF);
 426	if (major != ECRYPTFS_VERSION_MAJOR) {
 427		ecryptfs_printk(KERN_ERR, "Major version number mismatch. "
 428				"Expected [%d]; got [%d]\n",
 429				ECRYPTFS_VERSION_MAJOR, major);
 430		rc = -EINVAL;
 431		goto out;
 432	}
 433	if (minor != ECRYPTFS_VERSION_MINOR) {
 434		ecryptfs_printk(KERN_ERR, "Minor version number mismatch. "
 435				"Expected [%d]; got [%d]\n",
 436				ECRYPTFS_VERSION_MINOR, minor);
 437		rc = -EINVAL;
 438		goto out;
 439	}
 440out:
 441	return rc;
 442}
 443
 444/**
 445 * ecryptfs_verify_auth_tok_from_key
 446 * @auth_tok_key: key containing the authentication token
 447 * @auth_tok: authentication token
 448 *
 449 * Returns zero on valid auth tok; -EINVAL if the payload is invalid; or
 450 * -EKEYREVOKED if the key was revoked before we acquired its semaphore.
 451 */
 452static int
 453ecryptfs_verify_auth_tok_from_key(struct key *auth_tok_key,
 454				  struct ecryptfs_auth_tok **auth_tok)
 455{
 456	int rc = 0;
 457
 458	(*auth_tok) = ecryptfs_get_key_payload_data(auth_tok_key);
 459	if (IS_ERR(*auth_tok)) {
 460		rc = PTR_ERR(*auth_tok);
 461		*auth_tok = NULL;
 462		goto out;
 463	}
 464
 465	if (ecryptfs_verify_version((*auth_tok)->version)) {
 466		printk(KERN_ERR "Data structure version mismatch. Userspace "
 467		       "tools must match eCryptfs kernel module with major "
 468		       "version [%d] and minor version [%d]\n",
 469		       ECRYPTFS_VERSION_MAJOR, ECRYPTFS_VERSION_MINOR);
 470		rc = -EINVAL;
 471		goto out;
 472	}
 473	if ((*auth_tok)->token_type != ECRYPTFS_PASSWORD
 474	    && (*auth_tok)->token_type != ECRYPTFS_PRIVATE_KEY) {
 475		printk(KERN_ERR "Invalid auth_tok structure "
 476		       "returned from key query\n");
 477		rc = -EINVAL;
 478		goto out;
 479	}
 480out:
 481	return rc;
 482}
 483
 484static int
 485ecryptfs_find_global_auth_tok_for_sig(
 486	struct key **auth_tok_key,
 487	struct ecryptfs_auth_tok **auth_tok,
 488	struct ecryptfs_mount_crypt_stat *mount_crypt_stat, char *sig)
 489{
 490	struct ecryptfs_global_auth_tok *walker;
 491	int rc = 0;
 492
 493	(*auth_tok_key) = NULL;
 494	(*auth_tok) = NULL;
 495	mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
 496	list_for_each_entry(walker,
 497			    &mount_crypt_stat->global_auth_tok_list,
 498			    mount_crypt_stat_list) {
 499		if (memcmp(walker->sig, sig, ECRYPTFS_SIG_SIZE_HEX))
 500			continue;
 501
 502		if (walker->flags & ECRYPTFS_AUTH_TOK_INVALID) {
 503			rc = -EINVAL;
 504			goto out;
 505		}
 506
 507		rc = key_validate(walker->global_auth_tok_key);
 508		if (rc) {
 509			if (rc == -EKEYEXPIRED)
 510				goto out;
 511			goto out_invalid_auth_tok;
 512		}
 513
 514		down_write(&(walker->global_auth_tok_key->sem));
 515		rc = ecryptfs_verify_auth_tok_from_key(
 516				walker->global_auth_tok_key, auth_tok);
 517		if (rc)
 518			goto out_invalid_auth_tok_unlock;
 519
 520		(*auth_tok_key) = walker->global_auth_tok_key;
 521		key_get(*auth_tok_key);
 522		goto out;
 523	}
 524	rc = -ENOENT;
 525	goto out;
 526out_invalid_auth_tok_unlock:
 527	up_write(&(walker->global_auth_tok_key->sem));
 528out_invalid_auth_tok:
 529	printk(KERN_WARNING "Invalidating auth tok with sig = [%s]\n", sig);
 530	walker->flags |= ECRYPTFS_AUTH_TOK_INVALID;
 531	key_put(walker->global_auth_tok_key);
 532	walker->global_auth_tok_key = NULL;
 533out:
 534	mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
 535	return rc;
 536}
 537
 538/**
 539 * ecryptfs_find_auth_tok_for_sig
 540 * @auth_tok_key: key containing the authentication token
 541 * @auth_tok: Set to the matching auth_tok; NULL if not found
 542 * @mount_crypt_stat: inode crypt_stat crypto context
 543 * @sig: Sig of auth_tok to find
 544 *
 545 * For now, this function simply looks at the registered auth_tok's
 546 * linked off the mount_crypt_stat, so all the auth_toks that can be
 547 * used must be registered at mount time. This function could
 548 * potentially try a lot harder to find auth_tok's (e.g., by calling
 549 * out to ecryptfsd to dynamically retrieve an auth_tok object) so
 550 * that static registration of auth_tok's will no longer be necessary.
 551 *
 552 * Returns zero on no error; non-zero on error
 553 */
 554static int
 555ecryptfs_find_auth_tok_for_sig(
 556	struct key **auth_tok_key,
 557	struct ecryptfs_auth_tok **auth_tok,
 558	struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
 559	char *sig)
 560{
 561	int rc = 0;
 562
 563	rc = ecryptfs_find_global_auth_tok_for_sig(auth_tok_key, auth_tok,
 564						   mount_crypt_stat, sig);
 565	if (rc == -ENOENT) {
 566		/* if the flag ECRYPTFS_GLOBAL_MOUNT_AUTH_TOK_ONLY is set in the
 567		 * mount_crypt_stat structure, we prevent to use auth toks that
 568		 * are not inserted through the ecryptfs_add_global_auth_tok
 569		 * function.
 570		 */
 571		if (mount_crypt_stat->flags
 572				& ECRYPTFS_GLOBAL_MOUNT_AUTH_TOK_ONLY)
 573			return -EINVAL;
 574
 575		rc = ecryptfs_keyring_auth_tok_for_sig(auth_tok_key, auth_tok,
 576						       sig);
 577	}
 578	return rc;
 579}
 580
 581/*
 582 * write_tag_70_packet can gobble a lot of stack space. We stuff most
 583 * of the function's parameters in a kmalloc'd struct to help reduce
 584 * eCryptfs' overall stack usage.
 585 */
 586struct ecryptfs_write_tag_70_packet_silly_stack {
 587	u8 cipher_code;
 588	size_t max_packet_size;
 589	size_t packet_size_len;
 590	size_t block_aligned_filename_size;
 591	size_t block_size;
 592	size_t i;
 593	size_t j;
 594	size_t num_rand_bytes;
 595	struct mutex *tfm_mutex;
 596	char *block_aligned_filename;
 597	struct ecryptfs_auth_tok *auth_tok;
 598	struct scatterlist src_sg[2];
 599	struct scatterlist dst_sg[2];
 600	struct crypto_skcipher *skcipher_tfm;
 601	struct skcipher_request *skcipher_req;
 602	char iv[ECRYPTFS_MAX_IV_BYTES];
 603	char hash[MD5_DIGEST_SIZE];
 604};
 605
 606/*
 607 * write_tag_70_packet - Write encrypted filename (EFN) packet against FNEK
 608 * @filename: NULL-terminated filename string
 609 *
 610 * This is the simplest mechanism for achieving filename encryption in
 611 * eCryptfs. It encrypts the given filename with the mount-wide
 612 * filename encryption key (FNEK) and stores it in a packet to @dest,
 613 * which the callee will encode and write directly into the dentry
 614 * name.
 615 */
 616int
 617ecryptfs_write_tag_70_packet(char *dest, size_t *remaining_bytes,
 618			     size_t *packet_size,
 619			     struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
 620			     char *filename, size_t filename_size)
 621{
 622	struct ecryptfs_write_tag_70_packet_silly_stack *s;
 623	struct key *auth_tok_key = NULL;
 624	int rc = 0;
 625
 626	s = kzalloc(sizeof(*s), GFP_KERNEL);
 627	if (!s)
 628		return -ENOMEM;
 629
 630	(*packet_size) = 0;
 631	rc = ecryptfs_find_auth_tok_for_sig(
 632		&auth_tok_key,
 633		&s->auth_tok, mount_crypt_stat,
 634		mount_crypt_stat->global_default_fnek_sig);
 635	if (rc) {
 636		printk(KERN_ERR "%s: Error attempting to find auth tok for "
 637		       "fnek sig [%s]; rc = [%d]\n", __func__,
 638		       mount_crypt_stat->global_default_fnek_sig, rc);
 639		goto out;
 640	}
 641	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(
 642		&s->skcipher_tfm,
 643		&s->tfm_mutex, mount_crypt_stat->global_default_fn_cipher_name);
 644	if (unlikely(rc)) {
 645		printk(KERN_ERR "Internal error whilst attempting to get "
 646		       "tfm and mutex for cipher name [%s]; rc = [%d]\n",
 647		       mount_crypt_stat->global_default_fn_cipher_name, rc);
 648		goto out;
 649	}
 650	mutex_lock(s->tfm_mutex);
 651	s->block_size = crypto_skcipher_blocksize(s->skcipher_tfm);
 652	/* Plus one for the \0 separator between the random prefix
 653	 * and the plaintext filename */
 654	s->num_rand_bytes = (ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES + 1);
 655	s->block_aligned_filename_size = (s->num_rand_bytes + filename_size);
 656	if ((s->block_aligned_filename_size % s->block_size) != 0) {
 657		s->num_rand_bytes += (s->block_size
 658				      - (s->block_aligned_filename_size
 659					 % s->block_size));
 660		s->block_aligned_filename_size = (s->num_rand_bytes
 661						  + filename_size);
 662	}
 663	/* Octet 0: Tag 70 identifier
 664	 * Octets 1-N1: Tag 70 packet size (includes cipher identifier
 665	 *              and block-aligned encrypted filename size)
 666	 * Octets N1-N2: FNEK sig (ECRYPTFS_SIG_SIZE)
 667	 * Octet N2-N3: Cipher identifier (1 octet)
 668	 * Octets N3-N4: Block-aligned encrypted filename
 669	 *  - Consists of a minimum number of random characters, a \0
 670	 *    separator, and then the filename */
 671	s->max_packet_size = (ECRYPTFS_TAG_70_MAX_METADATA_SIZE
 672			      + s->block_aligned_filename_size);
 673	if (!dest) {
 674		(*packet_size) = s->max_packet_size;
 675		goto out_unlock;
 676	}
 677	if (s->max_packet_size > (*remaining_bytes)) {
 678		printk(KERN_WARNING "%s: Require [%zd] bytes to write; only "
 679		       "[%zd] available\n", __func__, s->max_packet_size,
 680		       (*remaining_bytes));
 681		rc = -EINVAL;
 682		goto out_unlock;
 683	}
 684
 685	s->skcipher_req = skcipher_request_alloc(s->skcipher_tfm, GFP_KERNEL);
 686	if (!s->skcipher_req) {
 687		printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
 688		       "skcipher_request_alloc for %s\n", __func__,
 689		       crypto_skcipher_driver_name(s->skcipher_tfm));
 690		rc = -ENOMEM;
 691		goto out_unlock;
 692	}
 693
 694	skcipher_request_set_callback(s->skcipher_req,
 695				      CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
 696
 697	s->block_aligned_filename = kzalloc(s->block_aligned_filename_size,
 698					    GFP_KERNEL);
 699	if (!s->block_aligned_filename) {
 700		rc = -ENOMEM;
 701		goto out_unlock;
 702	}
 703	dest[s->i++] = ECRYPTFS_TAG_70_PACKET_TYPE;
 704	rc = ecryptfs_write_packet_length(&dest[s->i],
 705					  (ECRYPTFS_SIG_SIZE
 706					   + 1 /* Cipher code */
 707					   + s->block_aligned_filename_size),
 708					  &s->packet_size_len);
 709	if (rc) {
 710		printk(KERN_ERR "%s: Error generating tag 70 packet "
 711		       "header; cannot generate packet length; rc = [%d]\n",
 712		       __func__, rc);
 713		goto out_free_unlock;
 714	}
 715	s->i += s->packet_size_len;
 716	ecryptfs_from_hex(&dest[s->i],
 717			  mount_crypt_stat->global_default_fnek_sig,
 718			  ECRYPTFS_SIG_SIZE);
 719	s->i += ECRYPTFS_SIG_SIZE;
 720	s->cipher_code = ecryptfs_code_for_cipher_string(
 721		mount_crypt_stat->global_default_fn_cipher_name,
 722		mount_crypt_stat->global_default_fn_cipher_key_bytes);
 723	if (s->cipher_code == 0) {
 724		printk(KERN_WARNING "%s: Unable to generate code for "
 725		       "cipher [%s] with key bytes [%zd]\n", __func__,
 726		       mount_crypt_stat->global_default_fn_cipher_name,
 727		       mount_crypt_stat->global_default_fn_cipher_key_bytes);
 728		rc = -EINVAL;
 729		goto out_free_unlock;
 730	}
 731	dest[s->i++] = s->cipher_code;
 732	/* TODO: Support other key modules than passphrase for
 733	 * filename encryption */
 734	if (s->auth_tok->token_type != ECRYPTFS_PASSWORD) {
 735		rc = -EOPNOTSUPP;
 736		printk(KERN_INFO "%s: Filename encryption only supports "
 737		       "password tokens\n", __func__);
 738		goto out_free_unlock;
 739	}
 740
 741	md5(s->auth_tok->token.password.session_key_encryption_key,
 742	    s->auth_tok->token.password.session_key_encryption_key_bytes,
 743	    s->hash);
 744	for (s->j = 0; s->j < (s->num_rand_bytes - 1); s->j++) {
 745		s->block_aligned_filename[s->j] =
 746			s->hash[s->j % MD5_DIGEST_SIZE];
 747		if ((s->j % MD5_DIGEST_SIZE) == (MD5_DIGEST_SIZE - 1))
 748			md5(s->hash, MD5_DIGEST_SIZE, s->hash);
 749		if (s->block_aligned_filename[s->j] == '\0')
 750			s->block_aligned_filename[s->j] = ECRYPTFS_NON_NULL;
 751	}
 752	memcpy(&s->block_aligned_filename[s->num_rand_bytes], filename,
 753	       filename_size);
 754	rc = virt_to_scatterlist(s->block_aligned_filename,
 755				 s->block_aligned_filename_size, s->src_sg, 2);
 756	if (rc < 1) {
 757		printk(KERN_ERR "%s: Internal error whilst attempting to "
 758		       "convert filename memory to scatterlist; rc = [%d]. "
 759		       "block_aligned_filename_size = [%zd]\n", __func__, rc,
 760		       s->block_aligned_filename_size);
 761		goto out_free_unlock;
 762	}
 763	rc = virt_to_scatterlist(&dest[s->i], s->block_aligned_filename_size,
 764				 s->dst_sg, 2);
 765	if (rc < 1) {
 766		printk(KERN_ERR "%s: Internal error whilst attempting to "
 767		       "convert encrypted filename memory to scatterlist; "
 768		       "rc = [%d]. block_aligned_filename_size = [%zd]\n",
 769		       __func__, rc, s->block_aligned_filename_size);
 770		goto out_free_unlock;
 771	}
 772	/* The characters in the first block effectively do the job
 773	 * of the IV here, so we just use 0's for the IV. Note the
 774	 * constraint that ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES
 775	 * >= ECRYPTFS_MAX_IV_BYTES. */
 776	rc = crypto_skcipher_setkey(
 777		s->skcipher_tfm,
 778		s->auth_tok->token.password.session_key_encryption_key,
 779		mount_crypt_stat->global_default_fn_cipher_key_bytes);
 780	if (rc < 0) {
 781		printk(KERN_ERR "%s: Error setting key for crypto context; "
 782		       "rc = [%d]. s->auth_tok->token.password.session_key_"
 783		       "encryption_key = [0x%p]; mount_crypt_stat->"
 784		       "global_default_fn_cipher_key_bytes = [%zd]\n", __func__,
 785		       rc,
 786		       s->auth_tok->token.password.session_key_encryption_key,
 787		       mount_crypt_stat->global_default_fn_cipher_key_bytes);
 788		goto out_free_unlock;
 789	}
 790	skcipher_request_set_crypt(s->skcipher_req, s->src_sg, s->dst_sg,
 791				   s->block_aligned_filename_size, s->iv);
 792	rc = crypto_skcipher_encrypt(s->skcipher_req);
 793	if (rc) {
 794		printk(KERN_ERR "%s: Error attempting to encrypt filename; "
 795		       "rc = [%d]\n", __func__, rc);
 796		goto out_free_unlock;
 797	}
 798	s->i += s->block_aligned_filename_size;
 799	(*packet_size) = s->i;
 800	(*remaining_bytes) -= (*packet_size);
 801out_free_unlock:
 802	kfree_sensitive(s->block_aligned_filename);
 803out_unlock:
 804	mutex_unlock(s->tfm_mutex);
 805out:
 806	if (auth_tok_key) {
 807		up_write(&(auth_tok_key->sem));
 808		key_put(auth_tok_key);
 809	}
 810	skcipher_request_free(s->skcipher_req);
 811	kfree(s);
 812	return rc;
 813}
 814
 815struct ecryptfs_parse_tag_70_packet_silly_stack {
 816	u8 cipher_code;
 817	size_t max_packet_size;
 818	size_t packet_size_len;
 819	size_t parsed_tag_70_packet_size;
 820	size_t block_aligned_filename_size;
 821	size_t block_size;
 822	size_t i;
 823	struct mutex *tfm_mutex;
 824	char *decrypted_filename;
 825	struct ecryptfs_auth_tok *auth_tok;
 826	struct scatterlist src_sg[2];
 827	struct scatterlist dst_sg[2];
 828	struct crypto_skcipher *skcipher_tfm;
 829	struct skcipher_request *skcipher_req;
 830	char fnek_sig_hex[ECRYPTFS_SIG_SIZE_HEX + 1];
 831	char iv[ECRYPTFS_MAX_IV_BYTES];
 832	char cipher_string[ECRYPTFS_MAX_CIPHER_NAME_SIZE + 1];
 833};
 834
 835/**
 836 * ecryptfs_parse_tag_70_packet - Parse and process FNEK-encrypted passphrase packet
 837 * @filename: This function kmalloc's the memory for the filename
 838 * @filename_size: This function sets this to the amount of memory
 839 *                 kmalloc'd for the filename
 840 * @packet_size: This function sets this to the the number of octets
 841 *               in the packet parsed
 842 * @mount_crypt_stat: The mount-wide cryptographic context
 843 * @data: The memory location containing the start of the tag 70
 844 *        packet
 845 * @max_packet_size: The maximum legal size of the packet to be parsed
 846 *                   from @data
 847 *
 848 * Returns zero on success; non-zero otherwise
 849 */
 850int
 851ecryptfs_parse_tag_70_packet(char **filename, size_t *filename_size,
 852			     size_t *packet_size,
 853			     struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
 854			     char *data, size_t max_packet_size)
 855{
 856	struct ecryptfs_parse_tag_70_packet_silly_stack *s;
 857	struct key *auth_tok_key = NULL;
 858	int rc = 0;
 859
 860	(*packet_size) = 0;
 861	(*filename_size) = 0;
 862	(*filename) = NULL;
 863	s = kzalloc(sizeof(*s), GFP_KERNEL);
 864	if (!s)
 865		return -ENOMEM;
 866
 867	if (max_packet_size < ECRYPTFS_TAG_70_MIN_METADATA_SIZE) {
 868		printk(KERN_WARNING "%s: max_packet_size is [%zd]; it must be "
 869		       "at least [%d]\n", __func__, max_packet_size,
 870		       ECRYPTFS_TAG_70_MIN_METADATA_SIZE);
 871		rc = -EINVAL;
 872		goto out;
 873	}
 874	/* Octet 0: Tag 70 identifier
 875	 * Octets 1-N1: Tag 70 packet size (includes cipher identifier
 876	 *              and block-aligned encrypted filename size)
 877	 * Octets N1-N2: FNEK sig (ECRYPTFS_SIG_SIZE)
 878	 * Octet N2-N3: Cipher identifier (1 octet)
 879	 * Octets N3-N4: Block-aligned encrypted filename
 880	 *  - Consists of a minimum number of random numbers, a \0
 881	 *    separator, and then the filename */
 882	if (data[(*packet_size)++] != ECRYPTFS_TAG_70_PACKET_TYPE) {
 883		printk(KERN_WARNING "%s: Invalid packet tag [0x%.2x]; must be "
 884		       "tag [0x%.2x]\n", __func__,
 885		       data[((*packet_size) - 1)], ECRYPTFS_TAG_70_PACKET_TYPE);
 886		rc = -EINVAL;
 887		goto out;
 888	}
 889	rc = ecryptfs_parse_packet_length(&data[(*packet_size)],
 890					  &s->parsed_tag_70_packet_size,
 891					  &s->packet_size_len);
 892	if (rc) {
 893		printk(KERN_WARNING "%s: Error parsing packet length; "
 894		       "rc = [%d]\n", __func__, rc);
 895		goto out;
 896	}
 897	s->block_aligned_filename_size = (s->parsed_tag_70_packet_size
 898					  - ECRYPTFS_SIG_SIZE - 1);
 899	if ((1 + s->packet_size_len + s->parsed_tag_70_packet_size)
 900	    > max_packet_size) {
 901		printk(KERN_WARNING "%s: max_packet_size is [%zd]; real packet "
 902		       "size is [%zd]\n", __func__, max_packet_size,
 903		       (1 + s->packet_size_len + 1
 904			+ s->block_aligned_filename_size));
 905		rc = -EINVAL;
 906		goto out;
 907	}
 908	(*packet_size) += s->packet_size_len;
 909	ecryptfs_to_hex(s->fnek_sig_hex, &data[(*packet_size)],
 910			ECRYPTFS_SIG_SIZE);
 911	s->fnek_sig_hex[ECRYPTFS_SIG_SIZE_HEX] = '\0';
 912	(*packet_size) += ECRYPTFS_SIG_SIZE;
 913	s->cipher_code = data[(*packet_size)++];
 914	rc = ecryptfs_cipher_code_to_string(s->cipher_string, s->cipher_code);
 915	if (rc) {
 916		printk(KERN_WARNING "%s: Cipher code [%d] is invalid\n",
 917		       __func__, s->cipher_code);
 918		goto out;
 919	}
 920	rc = ecryptfs_find_auth_tok_for_sig(&auth_tok_key,
 921					    &s->auth_tok, mount_crypt_stat,
 922					    s->fnek_sig_hex);
 923	if (rc) {
 924		printk(KERN_ERR "%s: Error attempting to find auth tok for "
 925		       "fnek sig [%s]; rc = [%d]\n", __func__, s->fnek_sig_hex,
 926		       rc);
 927		goto out;
 928	}
 929	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&s->skcipher_tfm,
 930							&s->tfm_mutex,
 931							s->cipher_string);
 932	if (unlikely(rc)) {
 933		printk(KERN_ERR "Internal error whilst attempting to get "
 934		       "tfm and mutex for cipher name [%s]; rc = [%d]\n",
 935		       s->cipher_string, rc);
 936		goto out;
 937	}
 938	mutex_lock(s->tfm_mutex);
 939	rc = virt_to_scatterlist(&data[(*packet_size)],
 940				 s->block_aligned_filename_size, s->src_sg, 2);
 941	if (rc < 1) {
 942		printk(KERN_ERR "%s: Internal error whilst attempting to "
 943		       "convert encrypted filename memory to scatterlist; "
 944		       "rc = [%d]. block_aligned_filename_size = [%zd]\n",
 945		       __func__, rc, s->block_aligned_filename_size);
 946		goto out_unlock;
 947	}
 948	(*packet_size) += s->block_aligned_filename_size;
 949	s->decrypted_filename = kmalloc(s->block_aligned_filename_size,
 950					GFP_KERNEL);
 951	if (!s->decrypted_filename) {
 952		rc = -ENOMEM;
 953		goto out_unlock;
 954	}
 955	rc = virt_to_scatterlist(s->decrypted_filename,
 956				 s->block_aligned_filename_size, s->dst_sg, 2);
 957	if (rc < 1) {
 958		printk(KERN_ERR "%s: Internal error whilst attempting to "
 959		       "convert decrypted filename memory to scatterlist; "
 960		       "rc = [%d]. block_aligned_filename_size = [%zd]\n",
 961		       __func__, rc, s->block_aligned_filename_size);
 962		goto out_free_unlock;
 963	}
 964
 965	s->skcipher_req = skcipher_request_alloc(s->skcipher_tfm, GFP_KERNEL);
 966	if (!s->skcipher_req) {
 967		printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
 968		       "skcipher_request_alloc for %s\n", __func__,
 969		       crypto_skcipher_driver_name(s->skcipher_tfm));
 970		rc = -ENOMEM;
 971		goto out_free_unlock;
 972	}
 973
 974	skcipher_request_set_callback(s->skcipher_req,
 975				      CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
 976
 977	/* The characters in the first block effectively do the job of
 978	 * the IV here, so we just use 0's for the IV. Note the
 979	 * constraint that ECRYPTFS_FILENAME_MIN_RANDOM_PREPEND_BYTES
 980	 * >= ECRYPTFS_MAX_IV_BYTES. */
 981	/* TODO: Support other key modules than passphrase for
 982	 * filename encryption */
 983	if (s->auth_tok->token_type != ECRYPTFS_PASSWORD) {
 984		rc = -EOPNOTSUPP;
 985		printk(KERN_INFO "%s: Filename encryption only supports "
 986		       "password tokens\n", __func__);
 987		goto out_free_unlock;
 988	}
 989	rc = crypto_skcipher_setkey(
 990		s->skcipher_tfm,
 991		s->auth_tok->token.password.session_key_encryption_key,
 992		mount_crypt_stat->global_default_fn_cipher_key_bytes);
 993	if (rc < 0) {
 994		printk(KERN_ERR "%s: Error setting key for crypto context; "
 995		       "rc = [%d]. s->auth_tok->token.password.session_key_"
 996		       "encryption_key = [0x%p]; mount_crypt_stat->"
 997		       "global_default_fn_cipher_key_bytes = [%zd]\n", __func__,
 998		       rc,
 999		       s->auth_tok->token.password.session_key_encryption_key,
1000		       mount_crypt_stat->global_default_fn_cipher_key_bytes);
1001		goto out_free_unlock;
1002	}
1003	skcipher_request_set_crypt(s->skcipher_req, s->src_sg, s->dst_sg,
1004				   s->block_aligned_filename_size, s->iv);
1005	rc = crypto_skcipher_decrypt(s->skcipher_req);
1006	if (rc) {
1007		printk(KERN_ERR "%s: Error attempting to decrypt filename; "
1008		       "rc = [%d]\n", __func__, rc);
1009		goto out_free_unlock;
1010	}
1011
1012	while (s->i < s->block_aligned_filename_size &&
1013	       s->decrypted_filename[s->i] != '\0')
1014		s->i++;
1015	if (s->i == s->block_aligned_filename_size) {
1016		printk(KERN_WARNING "%s: Invalid tag 70 packet; could not "
1017		       "find valid separator between random characters and "
1018		       "the filename\n", __func__);
1019		rc = -EINVAL;
1020		goto out_free_unlock;
1021	}
1022	s->i++;
1023	(*filename_size) = (s->block_aligned_filename_size - s->i);
1024	if (!((*filename_size) > 0 && (*filename_size < PATH_MAX))) {
1025		printk(KERN_WARNING "%s: Filename size is [%zd], which is "
1026		       "invalid\n", __func__, (*filename_size));
1027		rc = -EINVAL;
1028		goto out_free_unlock;
1029	}
1030	(*filename) = kmalloc(((*filename_size) + 1), GFP_KERNEL);
1031	if (!(*filename)) {
1032		rc = -ENOMEM;
1033		goto out_free_unlock;
1034	}
1035	memcpy((*filename), &s->decrypted_filename[s->i], (*filename_size));
1036	(*filename)[(*filename_size)] = '\0';
1037out_free_unlock:
1038	kfree(s->decrypted_filename);
1039out_unlock:
1040	mutex_unlock(s->tfm_mutex);
1041out:
1042	if (rc) {
1043		(*packet_size) = 0;
1044		(*filename_size) = 0;
1045		(*filename) = NULL;
1046	}
1047	if (auth_tok_key) {
1048		up_write(&(auth_tok_key->sem));
1049		key_put(auth_tok_key);
1050	}
1051	skcipher_request_free(s->skcipher_req);
1052	kfree(s);
1053	return rc;
1054}
1055
1056static int
1057ecryptfs_get_auth_tok_sig(char **sig, struct ecryptfs_auth_tok *auth_tok)
1058{
1059	int rc = 0;
1060
1061	(*sig) = NULL;
1062	switch (auth_tok->token_type) {
1063	case ECRYPTFS_PASSWORD:
1064		(*sig) = auth_tok->token.password.signature;
1065		break;
1066	case ECRYPTFS_PRIVATE_KEY:
1067		(*sig) = auth_tok->token.private_key.signature;
1068		break;
1069	default:
1070		printk(KERN_ERR "Cannot get sig for auth_tok of type [%d]\n",
1071		       auth_tok->token_type);
1072		rc = -EINVAL;
1073	}
1074	return rc;
1075}
1076
1077/**
1078 * decrypt_pki_encrypted_session_key - Decrypt the session key with the given auth_tok.
1079 * @auth_tok: The key authentication token used to decrypt the session key
1080 * @crypt_stat: The cryptographic context
1081 *
1082 * Returns zero on success; non-zero error otherwise.
1083 */
1084static int
1085decrypt_pki_encrypted_session_key(struct ecryptfs_auth_tok *auth_tok,
1086				  struct ecryptfs_crypt_stat *crypt_stat)
1087{
1088	u8 cipher_code = 0;
1089	struct ecryptfs_msg_ctx *msg_ctx;
1090	struct ecryptfs_message *msg = NULL;
1091	char *auth_tok_sig;
1092	char *payload = NULL;
1093	size_t payload_len = 0;
1094	int rc;
1095
1096	rc = ecryptfs_get_auth_tok_sig(&auth_tok_sig, auth_tok);
1097	if (rc) {
1098		printk(KERN_ERR "Unrecognized auth tok type: [%d]\n",
1099		       auth_tok->token_type);
1100		goto out;
1101	}
1102	rc = write_tag_64_packet(auth_tok_sig, &(auth_tok->session_key),
1103				 &payload, &payload_len);
1104	if (rc) {
1105		ecryptfs_printk(KERN_ERR, "Failed to write tag 64 packet\n");
1106		goto out;
1107	}
1108	rc = ecryptfs_send_message(payload, payload_len, &msg_ctx);
1109	if (rc) {
1110		ecryptfs_printk(KERN_ERR, "Error sending message to "
1111				"ecryptfsd: %d\n", rc);
1112		goto out;
1113	}
1114	rc = ecryptfs_wait_for_response(msg_ctx, &msg);
1115	if (rc) {
1116		ecryptfs_printk(KERN_ERR, "Failed to receive tag 65 packet "
1117				"from the user space daemon\n");
1118		rc = -EIO;
1119		goto out;
1120	}
1121	rc = parse_tag_65_packet(&(auth_tok->session_key),
1122				 &cipher_code, msg);
1123	if (rc) {
1124		printk(KERN_ERR "Failed to parse tag 65 packet; rc = [%d]\n",
1125		       rc);
1126		goto out;
1127	}
1128	auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1129	memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
1130	       auth_tok->session_key.decrypted_key_size);
1131	crypt_stat->key_size = auth_tok->session_key.decrypted_key_size;
1132	rc = ecryptfs_cipher_code_to_string(crypt_stat->cipher, cipher_code);
1133	if (rc) {
1134		ecryptfs_printk(KERN_ERR, "Cipher code [%d] is invalid\n",
1135				cipher_code);
1136		goto out;
1137	}
1138	crypt_stat->flags |= ECRYPTFS_KEY_VALID;
1139	if (ecryptfs_verbosity > 0) {
1140		ecryptfs_printk(KERN_DEBUG, "Decrypted session key:\n");
1141		ecryptfs_dump_hex(crypt_stat->key,
1142				  crypt_stat->key_size);
1143	}
1144out:
1145	kfree(msg);
1146	kfree(payload);
1147	return rc;
1148}
1149
1150static void wipe_auth_tok_list(struct list_head *auth_tok_list_head)
1151{
1152	struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1153	struct ecryptfs_auth_tok_list_item *auth_tok_list_item_tmp;
1154
1155	list_for_each_entry_safe(auth_tok_list_item, auth_tok_list_item_tmp,
1156				 auth_tok_list_head, list) {
1157		list_del(&auth_tok_list_item->list);
1158		kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1159				auth_tok_list_item);
1160	}
1161}
1162
1163struct kmem_cache *ecryptfs_auth_tok_list_item_cache;
1164
1165/**
1166 * parse_tag_1_packet
1167 * @crypt_stat: The cryptographic context to modify based on packet contents
1168 * @data: The raw bytes of the packet.
1169 * @auth_tok_list: eCryptfs parses packets into authentication tokens;
1170 *                 a new authentication token will be placed at the
1171 *                 end of this list for this packet.
1172 * @new_auth_tok: Pointer to a pointer to memory that this function
1173 *                allocates; sets the memory address of the pointer to
1174 *                NULL on error. This object is added to the
1175 *                auth_tok_list.
1176 * @packet_size: This function writes the size of the parsed packet
1177 *               into this memory location; zero on error.
1178 * @max_packet_size: The maximum allowable packet size
1179 *
1180 * Returns zero on success; non-zero on error.
1181 */
1182static int
1183parse_tag_1_packet(struct ecryptfs_crypt_stat *crypt_stat,
1184		   unsigned char *data, struct list_head *auth_tok_list,
1185		   struct ecryptfs_auth_tok **new_auth_tok,
1186		   size_t *packet_size, size_t max_packet_size)
1187{
1188	size_t body_size;
1189	struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1190	size_t length_size;
1191	int rc = 0;
1192
1193	(*packet_size) = 0;
1194	(*new_auth_tok) = NULL;
1195	/**
1196	 * This format is inspired by OpenPGP; see RFC 2440
1197	 * packet tag 1
1198	 *
1199	 * Tag 1 identifier (1 byte)
1200	 * Max Tag 1 packet size (max 3 bytes)
1201	 * Version (1 byte)
1202	 * Key identifier (8 bytes; ECRYPTFS_SIG_SIZE)
1203	 * Cipher identifier (1 byte)
1204	 * Encrypted key size (arbitrary)
1205	 *
1206	 * 12 bytes minimum packet size
1207	 */
1208	if (unlikely(max_packet_size < 12)) {
1209		printk(KERN_ERR "Invalid max packet size; must be >=12\n");
1210		rc = -EINVAL;
1211		goto out;
1212	}
1213	if (data[(*packet_size)++] != ECRYPTFS_TAG_1_PACKET_TYPE) {
1214		printk(KERN_ERR "Enter w/ first byte != 0x%.2x\n",
1215		       ECRYPTFS_TAG_1_PACKET_TYPE);
1216		rc = -EINVAL;
1217		goto out;
1218	}
1219	/* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
1220	 * at end of function upon failure */
1221	auth_tok_list_item =
1222		kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache,
1223				  GFP_KERNEL);
1224	if (!auth_tok_list_item) {
1225		printk(KERN_ERR "Unable to allocate memory\n");
1226		rc = -ENOMEM;
1227		goto out;
1228	}
1229	(*new_auth_tok) = &auth_tok_list_item->auth_tok;
1230	rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1231					  &length_size);
1232	if (rc) {
1233		printk(KERN_WARNING "Error parsing packet length; "
1234		       "rc = [%d]\n", rc);
1235		goto out_free;
1236	}
1237	if (unlikely(body_size < (ECRYPTFS_SIG_SIZE + 2))) {
1238		printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1239		rc = -EINVAL;
1240		goto out_free;
1241	}
1242	(*packet_size) += length_size;
1243	if (unlikely((*packet_size) + body_size > max_packet_size)) {
1244		printk(KERN_WARNING "Packet size exceeds max\n");
1245		rc = -EINVAL;
1246		goto out_free;
1247	}
1248	if (unlikely(data[(*packet_size)++] != 0x03)) {
1249		printk(KERN_WARNING "Unknown version number [%d]\n",
1250		       data[(*packet_size) - 1]);
1251		rc = -EINVAL;
1252		goto out_free;
1253	}
1254	ecryptfs_to_hex((*new_auth_tok)->token.private_key.signature,
1255			&data[(*packet_size)], ECRYPTFS_SIG_SIZE);
1256	*packet_size += ECRYPTFS_SIG_SIZE;
1257	/* This byte is skipped because the kernel does not need to
1258	 * know which public key encryption algorithm was used */
1259	(*packet_size)++;
1260	(*new_auth_tok)->session_key.encrypted_key_size =
1261		body_size - (ECRYPTFS_SIG_SIZE + 2);
1262	if ((*new_auth_tok)->session_key.encrypted_key_size
1263	    > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
1264		printk(KERN_WARNING "Tag 1 packet contains key larger "
1265		       "than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES\n");
1266		rc = -EINVAL;
1267		goto out_free;
1268	}
1269	memcpy((*new_auth_tok)->session_key.encrypted_key,
1270	       &data[(*packet_size)], (body_size - (ECRYPTFS_SIG_SIZE + 2)));
1271	(*packet_size) += (*new_auth_tok)->session_key.encrypted_key_size;
1272	(*new_auth_tok)->session_key.flags &=
1273		~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1274	(*new_auth_tok)->session_key.flags |=
1275		ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
1276	(*new_auth_tok)->token_type = ECRYPTFS_PRIVATE_KEY;
1277	(*new_auth_tok)->flags = 0;
1278	(*new_auth_tok)->session_key.flags &=
1279		~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
1280	(*new_auth_tok)->session_key.flags &=
1281		~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
1282	list_add(&auth_tok_list_item->list, auth_tok_list);
1283	goto out;
1284out_free:
1285	(*new_auth_tok) = NULL;
1286	memset(auth_tok_list_item, 0,
1287	       sizeof(struct ecryptfs_auth_tok_list_item));
1288	kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1289			auth_tok_list_item);
1290out:
1291	if (rc)
1292		(*packet_size) = 0;
1293	return rc;
1294}
1295
1296/**
1297 * parse_tag_3_packet
1298 * @crypt_stat: The cryptographic context to modify based on packet
1299 *              contents.
1300 * @data: The raw bytes of the packet.
1301 * @auth_tok_list: eCryptfs parses packets into authentication tokens;
1302 *                 a new authentication token will be placed at the end
1303 *                 of this list for this packet.
1304 * @new_auth_tok: Pointer to a pointer to memory that this function
1305 *                allocates; sets the memory address of the pointer to
1306 *                NULL on error. This object is added to the
1307 *                auth_tok_list.
1308 * @packet_size: This function writes the size of the parsed packet
1309 *               into this memory location; zero on error.
1310 * @max_packet_size: maximum number of bytes to parse
1311 *
1312 * Returns zero on success; non-zero on error.
1313 */
1314static int
1315parse_tag_3_packet(struct ecryptfs_crypt_stat *crypt_stat,
1316		   unsigned char *data, struct list_head *auth_tok_list,
1317		   struct ecryptfs_auth_tok **new_auth_tok,
1318		   size_t *packet_size, size_t max_packet_size)
1319{
1320	size_t body_size;
1321	struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1322	size_t length_size;
1323	int rc = 0;
1324
1325	(*packet_size) = 0;
1326	(*new_auth_tok) = NULL;
1327	/**
1328	 *This format is inspired by OpenPGP; see RFC 2440
1329	 * packet tag 3
1330	 *
1331	 * Tag 3 identifier (1 byte)
1332	 * Max Tag 3 packet size (max 3 bytes)
1333	 * Version (1 byte)
1334	 * Cipher code (1 byte)
1335	 * S2K specifier (1 byte)
1336	 * Hash identifier (1 byte)
1337	 * Salt (ECRYPTFS_SALT_SIZE)
1338	 * Hash iterations (1 byte)
1339	 * Encrypted key (arbitrary)
1340	 *
1341	 * (ECRYPTFS_SALT_SIZE + 7) minimum packet size
1342	 */
1343	if (max_packet_size < (ECRYPTFS_SALT_SIZE + 7)) {
1344		printk(KERN_ERR "Max packet size too large\n");
1345		rc = -EINVAL;
1346		goto out;
1347	}
1348	if (data[(*packet_size)++] != ECRYPTFS_TAG_3_PACKET_TYPE) {
1349		printk(KERN_ERR "First byte != 0x%.2x; invalid packet\n",
1350		       ECRYPTFS_TAG_3_PACKET_TYPE);
1351		rc = -EINVAL;
1352		goto out;
1353	}
1354	/* Released: wipe_auth_tok_list called in ecryptfs_parse_packet_set or
1355	 * at end of function upon failure */
1356	auth_tok_list_item =
1357	    kmem_cache_zalloc(ecryptfs_auth_tok_list_item_cache, GFP_KERNEL);
1358	if (!auth_tok_list_item) {
1359		printk(KERN_ERR "Unable to allocate memory\n");
1360		rc = -ENOMEM;
1361		goto out;
1362	}
1363	(*new_auth_tok) = &auth_tok_list_item->auth_tok;
1364	rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1365					  &length_size);
1366	if (rc) {
1367		printk(KERN_WARNING "Error parsing packet length; rc = [%d]\n",
1368		       rc);
1369		goto out_free;
1370	}
1371	if (unlikely(body_size < (ECRYPTFS_SALT_SIZE + 5))) {
1372		printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1373		rc = -EINVAL;
1374		goto out_free;
1375	}
1376	(*packet_size) += length_size;
1377	if (unlikely((*packet_size) + body_size > max_packet_size)) {
1378		printk(KERN_ERR "Packet size exceeds max\n");
1379		rc = -EINVAL;
1380		goto out_free;
1381	}
1382	(*new_auth_tok)->session_key.encrypted_key_size =
1383		(body_size - (ECRYPTFS_SALT_SIZE + 5));
1384	if ((*new_auth_tok)->session_key.encrypted_key_size
1385	    > ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES) {
1386		printk(KERN_WARNING "Tag 3 packet contains key larger "
1387		       "than ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES\n");
1388		rc = -EINVAL;
1389		goto out_free;
1390	}
1391	if (unlikely(data[(*packet_size)++] != 0x04)) {
1392		printk(KERN_WARNING "Unknown version number [%d]\n",
1393		       data[(*packet_size) - 1]);
1394		rc = -EINVAL;
1395		goto out_free;
1396	}
1397	rc = ecryptfs_cipher_code_to_string(crypt_stat->cipher,
1398					    (u16)data[(*packet_size)]);
1399	if (rc)
1400		goto out_free;
1401	/* A little extra work to differentiate among the AES key
1402	 * sizes; see RFC2440 */
1403	switch(data[(*packet_size)++]) {
1404	case RFC2440_CIPHER_AES_192:
1405		crypt_stat->key_size = 24;
1406		break;
1407	default:
1408		crypt_stat->key_size =
1409			(*new_auth_tok)->session_key.encrypted_key_size;
1410	}
1411	rc = ecryptfs_init_crypt_ctx(crypt_stat);
1412	if (rc)
1413		goto out_free;
1414	if (unlikely(data[(*packet_size)++] != 0x03)) {
1415		printk(KERN_WARNING "Only S2K ID 3 is currently supported\n");
1416		rc = -ENOSYS;
1417		goto out_free;
1418	}
1419	/* TODO: finish the hash mapping */
1420	switch (data[(*packet_size)++]) {
1421	case 0x01: /* See RFC2440 for these numbers and their mappings */
1422		/* Choose MD5 */
1423		memcpy((*new_auth_tok)->token.password.salt,
1424		       &data[(*packet_size)], ECRYPTFS_SALT_SIZE);
1425		(*packet_size) += ECRYPTFS_SALT_SIZE;
1426		/* This conversion was taken straight from RFC2440 */
1427		(*new_auth_tok)->token.password.hash_iterations =
1428			((u32) 16 + (data[(*packet_size)] & 15))
1429				<< ((data[(*packet_size)] >> 4) + 6);
1430		(*packet_size)++;
1431		/* Friendly reminder:
1432		 * (*new_auth_tok)->session_key.encrypted_key_size =
1433		 *         (body_size - (ECRYPTFS_SALT_SIZE + 5)); */
1434		memcpy((*new_auth_tok)->session_key.encrypted_key,
1435		       &data[(*packet_size)],
1436		       (*new_auth_tok)->session_key.encrypted_key_size);
1437		(*packet_size) +=
1438			(*new_auth_tok)->session_key.encrypted_key_size;
1439		(*new_auth_tok)->session_key.flags &=
1440			~ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1441		(*new_auth_tok)->session_key.flags |=
1442			ECRYPTFS_CONTAINS_ENCRYPTED_KEY;
1443		(*new_auth_tok)->token.password.hash_algo = 0x01; /* MD5 */
1444		break;
1445	default:
1446		ecryptfs_printk(KERN_ERR, "Unsupported hash algorithm: "
1447				"[%d]\n", data[(*packet_size) - 1]);
1448		rc = -ENOSYS;
1449		goto out_free;
1450	}
1451	(*new_auth_tok)->token_type = ECRYPTFS_PASSWORD;
1452	/* TODO: Parametarize; we might actually want userspace to
1453	 * decrypt the session key. */
1454	(*new_auth_tok)->session_key.flags &=
1455			    ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_DECRYPT);
1456	(*new_auth_tok)->session_key.flags &=
1457			    ~(ECRYPTFS_USERSPACE_SHOULD_TRY_TO_ENCRYPT);
1458	list_add(&auth_tok_list_item->list, auth_tok_list);
1459	goto out;
1460out_free:
1461	(*new_auth_tok) = NULL;
1462	memset(auth_tok_list_item, 0,
1463	       sizeof(struct ecryptfs_auth_tok_list_item));
1464	kmem_cache_free(ecryptfs_auth_tok_list_item_cache,
1465			auth_tok_list_item);
1466out:
1467	if (rc)
1468		(*packet_size) = 0;
1469	return rc;
1470}
1471
1472/**
1473 * parse_tag_11_packet
1474 * @data: The raw bytes of the packet
1475 * @contents: This function writes the data contents of the literal
1476 *            packet into this memory location
1477 * @max_contents_bytes: The maximum number of bytes that this function
1478 *                      is allowed to write into contents
1479 * @tag_11_contents_size: This function writes the size of the parsed
1480 *                        contents into this memory location; zero on
1481 *                        error
1482 * @packet_size: This function writes the size of the parsed packet
1483 *               into this memory location; zero on error
1484 * @max_packet_size: maximum number of bytes to parse
1485 *
1486 * Returns zero on success; non-zero on error.
1487 */
1488static int
1489parse_tag_11_packet(unsigned char *data, unsigned char *contents,
1490		    size_t max_contents_bytes, size_t *tag_11_contents_size,
1491		    size_t *packet_size, size_t max_packet_size)
1492{
1493	size_t body_size;
1494	size_t length_size;
1495	int rc = 0;
1496
1497	(*packet_size) = 0;
1498	(*tag_11_contents_size) = 0;
1499	/* This format is inspired by OpenPGP; see RFC 2440
1500	 * packet tag 11
1501	 *
1502	 * Tag 11 identifier (1 byte)
1503	 * Max Tag 11 packet size (max 3 bytes)
1504	 * Binary format specifier (1 byte)
1505	 * Filename length (1 byte)
1506	 * Filename ("_CONSOLE") (8 bytes)
1507	 * Modification date (4 bytes)
1508	 * Literal data (arbitrary)
1509	 *
1510	 * We need at least 16 bytes of data for the packet to even be
1511	 * valid.
1512	 */
1513	if (max_packet_size < 16) {
1514		printk(KERN_ERR "Maximum packet size too small\n");
1515		rc = -EINVAL;
1516		goto out;
1517	}
1518	if (data[(*packet_size)++] != ECRYPTFS_TAG_11_PACKET_TYPE) {
1519		printk(KERN_WARNING "Invalid tag 11 packet format\n");
1520		rc = -EINVAL;
1521		goto out;
1522	}
1523	rc = ecryptfs_parse_packet_length(&data[(*packet_size)], &body_size,
1524					  &length_size);
1525	if (rc) {
1526		printk(KERN_WARNING "Invalid tag 11 packet format\n");
1527		goto out;
1528	}
1529	if (body_size < 14) {
1530		printk(KERN_WARNING "Invalid body size ([%td])\n", body_size);
1531		rc = -EINVAL;
1532		goto out;
1533	}
1534	(*packet_size) += length_size;
1535	(*tag_11_contents_size) = (body_size - 14);
1536	if (unlikely((*packet_size) + body_size + 1 > max_packet_size)) {
1537		printk(KERN_ERR "Packet size exceeds max\n");
1538		rc = -EINVAL;
1539		goto out;
1540	}
1541	if (unlikely((*tag_11_contents_size) > max_contents_bytes)) {
1542		printk(KERN_ERR "Literal data section in tag 11 packet exceeds "
1543		       "expected size\n");
1544		rc = -EINVAL;
1545		goto out;
1546	}
1547	if (data[(*packet_size)++] != 0x62) {
1548		printk(KERN_WARNING "Unrecognizable packet\n");
1549		rc = -EINVAL;
1550		goto out;
1551	}
1552	if (data[(*packet_size)++] != 0x08) {
1553		printk(KERN_WARNING "Unrecognizable packet\n");
1554		rc = -EINVAL;
1555		goto out;
1556	}
1557	(*packet_size) += 12; /* Ignore filename and modification date */
1558	memcpy(contents, &data[(*packet_size)], (*tag_11_contents_size));
1559	(*packet_size) += (*tag_11_contents_size);
1560out:
1561	if (rc) {
1562		(*packet_size) = 0;
1563		(*tag_11_contents_size) = 0;
1564	}
1565	return rc;
1566}
1567
1568int ecryptfs_keyring_auth_tok_for_sig(struct key **auth_tok_key,
1569				      struct ecryptfs_auth_tok **auth_tok,
1570				      char *sig)
1571{
1572	int rc = 0;
1573
1574	(*auth_tok_key) = request_key(&key_type_user, sig, NULL);
1575	if (IS_ERR(*auth_tok_key)) {
1576		(*auth_tok_key) = ecryptfs_get_encrypted_key(sig);
1577		if (IS_ERR(*auth_tok_key)) {
1578			printk(KERN_ERR "Could not find key with description: [%s]\n",
1579			      sig);
1580			rc = process_request_key_err(PTR_ERR(*auth_tok_key));
1581			(*auth_tok_key) = NULL;
1582			goto out;
1583		}
1584	}
1585	down_write(&(*auth_tok_key)->sem);
1586	rc = ecryptfs_verify_auth_tok_from_key(*auth_tok_key, auth_tok);
1587	if (rc) {
1588		up_write(&(*auth_tok_key)->sem);
1589		key_put(*auth_tok_key);
1590		(*auth_tok_key) = NULL;
1591		goto out;
1592	}
1593out:
1594	return rc;
1595}
1596
1597/**
1598 * decrypt_passphrase_encrypted_session_key - Decrypt the session key with the given auth_tok.
1599 * @auth_tok: The passphrase authentication token to use to encrypt the FEK
1600 * @crypt_stat: The cryptographic context
1601 *
1602 * Returns zero on success; non-zero error otherwise
1603 */
1604static int
1605decrypt_passphrase_encrypted_session_key(struct ecryptfs_auth_tok *auth_tok,
1606					 struct ecryptfs_crypt_stat *crypt_stat)
1607{
1608	struct scatterlist dst_sg[2];
1609	struct scatterlist src_sg[2];
1610	struct mutex *tfm_mutex;
1611	struct crypto_skcipher *tfm;
1612	struct skcipher_request *req = NULL;
1613	int rc = 0;
1614
1615	if (unlikely(ecryptfs_verbosity > 0)) {
1616		ecryptfs_printk(
1617			KERN_DEBUG, "Session key encryption key (size [%d]):\n",
1618			auth_tok->token.password.session_key_encryption_key_bytes);
1619		ecryptfs_dump_hex(
1620			auth_tok->token.password.session_key_encryption_key,
1621			auth_tok->token.password.session_key_encryption_key_bytes);
1622	}
1623	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&tfm, &tfm_mutex,
1624							crypt_stat->cipher);
1625	if (unlikely(rc)) {
1626		printk(KERN_ERR "Internal error whilst attempting to get "
1627		       "tfm and mutex for cipher name [%s]; rc = [%d]\n",
1628		       crypt_stat->cipher, rc);
1629		goto out;
1630	}
1631	rc = virt_to_scatterlist(auth_tok->session_key.encrypted_key,
1632				 auth_tok->session_key.encrypted_key_size,
1633				 src_sg, 2);
1634	if (rc < 1 || rc > 2) {
1635		printk(KERN_ERR "Internal error whilst attempting to convert "
1636			"auth_tok->session_key.encrypted_key to scatterlist; "
1637			"expected rc = 1; got rc = [%d]. "
1638		       "auth_tok->session_key.encrypted_key_size = [%d]\n", rc,
1639			auth_tok->session_key.encrypted_key_size);
1640		goto out;
1641	}
1642	auth_tok->session_key.decrypted_key_size =
1643		auth_tok->session_key.encrypted_key_size;
1644	rc = virt_to_scatterlist(auth_tok->session_key.decrypted_key,
1645				 auth_tok->session_key.decrypted_key_size,
1646				 dst_sg, 2);
1647	if (rc < 1 || rc > 2) {
1648		printk(KERN_ERR "Internal error whilst attempting to convert "
1649			"auth_tok->session_key.decrypted_key to scatterlist; "
1650			"expected rc = 1; got rc = [%d]\n", rc);
1651		goto out;
1652	}
1653	mutex_lock(tfm_mutex);
1654	req = skcipher_request_alloc(tfm, GFP_KERNEL);
1655	if (!req) {
1656		mutex_unlock(tfm_mutex);
1657		printk(KERN_ERR "%s: Out of kernel memory whilst attempting to "
1658		       "skcipher_request_alloc for %s\n", __func__,
1659		       crypto_skcipher_driver_name(tfm));
1660		rc = -ENOMEM;
1661		goto out;
1662	}
1663
1664	skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP,
1665				      NULL, NULL);
1666	rc = crypto_skcipher_setkey(
1667		tfm, auth_tok->token.password.session_key_encryption_key,
1668		crypt_stat->key_size);
1669	if (unlikely(rc < 0)) {
1670		mutex_unlock(tfm_mutex);
1671		printk(KERN_ERR "Error setting key for crypto context\n");
1672		rc = -EINVAL;
1673		goto out;
1674	}
1675	skcipher_request_set_crypt(req, src_sg, dst_sg,
1676				   auth_tok->session_key.encrypted_key_size,
1677				   NULL);
1678	rc = crypto_skcipher_decrypt(req);
1679	mutex_unlock(tfm_mutex);
1680	if (unlikely(rc)) {
1681		printk(KERN_ERR "Error decrypting; rc = [%d]\n", rc);
1682		goto out;
1683	}
1684	auth_tok->session_key.flags |= ECRYPTFS_CONTAINS_DECRYPTED_KEY;
1685	memcpy(crypt_stat->key, auth_tok->session_key.decrypted_key,
1686	       auth_tok->session_key.decrypted_key_size);
1687	crypt_stat->flags |= ECRYPTFS_KEY_VALID;
1688	if (unlikely(ecryptfs_verbosity > 0)) {
1689		ecryptfs_printk(KERN_DEBUG, "FEK of size [%zd]:\n",
1690				crypt_stat->key_size);
1691		ecryptfs_dump_hex(crypt_stat->key,
1692				  crypt_stat->key_size);
1693	}
1694out:
1695	skcipher_request_free(req);
1696	return rc;
1697}
1698
1699/**
1700 * ecryptfs_parse_packet_set
1701 * @crypt_stat: The cryptographic context
1702 * @src: Virtual address of region of memory containing the packets
1703 * @ecryptfs_dentry: The eCryptfs dentry associated with the packet set
1704 *
1705 * Get crypt_stat to have the file's session key if the requisite key
1706 * is available to decrypt the session key.
1707 *
1708 * Returns Zero if a valid authentication token was retrieved and
1709 * processed; negative value for file not encrypted or for error
1710 * conditions.
1711 */
1712int ecryptfs_parse_packet_set(struct ecryptfs_crypt_stat *crypt_stat,
1713			      unsigned char *src,
1714			      struct dentry *ecryptfs_dentry)
1715{
1716	size_t i = 0;
1717	size_t found_auth_tok;
1718	size_t next_packet_is_auth_tok_packet;
1719	struct list_head auth_tok_list;
1720	struct ecryptfs_auth_tok *matching_auth_tok;
1721	struct ecryptfs_auth_tok *candidate_auth_tok;
1722	char *candidate_auth_tok_sig;
1723	size_t packet_size;
1724	struct ecryptfs_auth_tok *new_auth_tok;
1725	unsigned char sig_tmp_space[ECRYPTFS_SIG_SIZE];
1726	struct ecryptfs_auth_tok_list_item *auth_tok_list_item;
1727	size_t tag_11_contents_size;
1728	size_t tag_11_packet_size;
1729	struct key *auth_tok_key = NULL;
1730	int rc = 0;
1731
1732	INIT_LIST_HEAD(&auth_tok_list);
1733	/* Parse the header to find as many packets as we can; these will be
1734	 * added the our &auth_tok_list */
1735	next_packet_is_auth_tok_packet = 1;
1736	while (next_packet_is_auth_tok_packet) {
1737		size_t max_packet_size = ((PAGE_SIZE - 8) - i);
1738
1739		switch (src[i]) {
1740		case ECRYPTFS_TAG_3_PACKET_TYPE:
1741			rc = parse_tag_3_packet(crypt_stat,
1742						(unsigned char *)&src[i],
1743						&auth_tok_list, &new_auth_tok,
1744						&packet_size, max_packet_size);
1745			if (rc) {
1746				ecryptfs_printk(KERN_ERR, "Error parsing "
1747						"tag 3 packet\n");
1748				rc = -EIO;
1749				goto out_wipe_list;
1750			}
1751			i += packet_size;
1752			rc = parse_tag_11_packet((unsigned char *)&src[i],
1753						 sig_tmp_space,
1754						 ECRYPTFS_SIG_SIZE,
1755						 &tag_11_contents_size,
1756						 &tag_11_packet_size,
1757						 max_packet_size);
1758			if (rc) {
1759				ecryptfs_printk(KERN_ERR, "No valid "
1760						"(ecryptfs-specific) literal "
1761						"packet containing "
1762						"authentication token "
1763						"signature found after "
1764						"tag 3 packet\n");
1765				rc = -EIO;
1766				goto out_wipe_list;
1767			}
1768			i += tag_11_packet_size;
1769			if (ECRYPTFS_SIG_SIZE != tag_11_contents_size) {
1770				ecryptfs_printk(KERN_ERR, "Expected "
1771						"signature of size [%d]; "
1772						"read size [%zd]\n",
1773						ECRYPTFS_SIG_SIZE,
1774						tag_11_contents_size);
1775				rc = -EIO;
1776				goto out_wipe_list;
1777			}
1778			ecryptfs_to_hex(new_auth_tok->token.password.signature,
1779					sig_tmp_space, tag_11_contents_size);
1780			new_auth_tok->token.password.signature[
1781				ECRYPTFS_PASSWORD_SIG_SIZE] = '\0';
1782			crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1783			break;
1784		case ECRYPTFS_TAG_1_PACKET_TYPE:
1785			rc = parse_tag_1_packet(crypt_stat,
1786						(unsigned char *)&src[i],
1787						&auth_tok_list, &new_auth_tok,
1788						&packet_size, max_packet_size);
1789			if (rc) {
1790				ecryptfs_printk(KERN_ERR, "Error parsing "
1791						"tag 1 packet\n");
1792				rc = -EIO;
1793				goto out_wipe_list;
1794			}
1795			i += packet_size;
1796			crypt_stat->flags |= ECRYPTFS_ENCRYPTED;
1797			break;
1798		case ECRYPTFS_TAG_11_PACKET_TYPE:
1799			ecryptfs_printk(KERN_WARNING, "Invalid packet set "
1800					"(Tag 11 not allowed by itself)\n");
1801			rc = -EIO;
1802			goto out_wipe_list;
1803		default:
1804			ecryptfs_printk(KERN_DEBUG, "No packet at offset [%zd] "
1805					"of the file header; hex value of "
1806					"character is [0x%.2x]\n", i, src[i]);
1807			next_packet_is_auth_tok_packet = 0;
1808		}
1809	}
1810	if (list_empty(&auth_tok_list)) {
1811		printk(KERN_ERR "The lower file appears to be a non-encrypted "
1812		       "eCryptfs file; this is not supported in this version "
1813		       "of the eCryptfs kernel module\n");
1814		rc = -EINVAL;
1815		goto out;
1816	}
1817	/* auth_tok_list contains the set of authentication tokens
1818	 * parsed from the metadata. We need to find a matching
1819	 * authentication token that has the secret component(s)
1820	 * necessary to decrypt the EFEK in the auth_tok parsed from
1821	 * the metadata. There may be several potential matches, but
1822	 * just one will be sufficient to decrypt to get the FEK. */
1823find_next_matching_auth_tok:
1824	found_auth_tok = 0;
1825	list_for_each_entry(auth_tok_list_item, &auth_tok_list, list) {
1826		candidate_auth_tok = &auth_tok_list_item->auth_tok;
1827		if (unlikely(ecryptfs_verbosity > 0)) {
1828			ecryptfs_printk(KERN_DEBUG,
1829					"Considering candidate auth tok:\n");
1830			ecryptfs_dump_auth_tok(candidate_auth_tok);
1831		}
1832		rc = ecryptfs_get_auth_tok_sig(&candidate_auth_tok_sig,
1833					       candidate_auth_tok);
1834		if (rc) {
1835			printk(KERN_ERR
1836			       "Unrecognized candidate auth tok type: [%d]\n",
1837			       candidate_auth_tok->token_type);
1838			rc = -EINVAL;
1839			goto out_wipe_list;
1840		}
1841		rc = ecryptfs_find_auth_tok_for_sig(&auth_tok_key,
1842					       &matching_auth_tok,
1843					       crypt_stat->mount_crypt_stat,
1844					       candidate_auth_tok_sig);
1845		if (!rc) {
1846			found_auth_tok = 1;
1847			goto found_matching_auth_tok;
1848		}
1849	}
1850	if (!found_auth_tok) {
1851		ecryptfs_printk(KERN_ERR, "Could not find a usable "
1852				"authentication token\n");
1853		rc = -EIO;
1854		goto out_wipe_list;
1855	}
1856found_matching_auth_tok:
1857	if (candidate_auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
1858		memcpy(&(candidate_auth_tok->token.private_key),
1859		       &(matching_auth_tok->token.private_key),
1860		       sizeof(struct ecryptfs_private_key));
1861		up_write(&(auth_tok_key->sem));
1862		key_put(auth_tok_key);
1863		rc = decrypt_pki_encrypted_session_key(candidate_auth_tok,
1864						       crypt_stat);
1865	} else if (candidate_auth_tok->token_type == ECRYPTFS_PASSWORD) {
1866		memcpy(&(candidate_auth_tok->token.password),
1867		       &(matching_auth_tok->token.password),
1868		       sizeof(struct ecryptfs_password));
1869		up_write(&(auth_tok_key->sem));
1870		key_put(auth_tok_key);
1871		rc = decrypt_passphrase_encrypted_session_key(
1872			candidate_auth_tok, crypt_stat);
1873	} else {
1874		up_write(&(auth_tok_key->sem));
1875		key_put(auth_tok_key);
1876		rc = -EINVAL;
1877	}
1878	if (rc) {
1879		struct ecryptfs_auth_tok_list_item *auth_tok_list_item_tmp;
1880
1881		ecryptfs_printk(KERN_WARNING, "Error decrypting the "
1882				"session key for authentication token with sig "
1883				"[%.*s]; rc = [%d]. Removing auth tok "
1884				"candidate from the list and searching for "
1885				"the next match.\n", ECRYPTFS_SIG_SIZE_HEX,
1886				candidate_auth_tok_sig,	rc);
1887		list_for_each_entry_safe(auth_tok_list_item,
1888					 auth_tok_list_item_tmp,
1889					 &auth_tok_list, list) {
1890			if (candidate_auth_tok
1891			    == &auth_tok_list_item->auth_tok) {
1892				list_del(&auth_tok_list_item->list);
1893				kmem_cache_free(
1894					ecryptfs_auth_tok_list_item_cache,
1895					auth_tok_list_item);
1896				goto find_next_matching_auth_tok;
1897			}
1898		}
1899		BUG();
1900	}
1901	rc = ecryptfs_compute_root_iv(crypt_stat);
1902	if (rc) {
1903		ecryptfs_printk(KERN_ERR, "Error computing "
1904				"the root IV\n");
1905		goto out_wipe_list;
1906	}
1907	rc = ecryptfs_init_crypt_ctx(crypt_stat);
1908	if (rc) {
1909		ecryptfs_printk(KERN_ERR, "Error initializing crypto "
1910				"context for cipher [%s]; rc = [%d]\n",
1911				crypt_stat->cipher, rc);
1912	}
1913out_wipe_list:
1914	wipe_auth_tok_list(&auth_tok_list);
1915out:
1916	return rc;
1917}
1918
1919static int
1920pki_encrypt_session_key(struct key *auth_tok_key,
1921			struct ecryptfs_auth_tok *auth_tok,
1922			struct ecryptfs_crypt_stat *crypt_stat,
1923			struct ecryptfs_key_record *key_rec)
1924{
1925	struct ecryptfs_msg_ctx *msg_ctx = NULL;
1926	char *payload = NULL;
1927	size_t payload_len = 0;
1928	struct ecryptfs_message *msg;
1929	int rc;
1930
1931	rc = write_tag_66_packet(auth_tok->token.private_key.signature,
1932				 ecryptfs_code_for_cipher_string(
1933					 crypt_stat->cipher,
1934					 crypt_stat->key_size),
1935				 crypt_stat, &payload, &payload_len);
1936	up_write(&(auth_tok_key->sem));
1937	key_put(auth_tok_key);
1938	if (rc) {
1939		ecryptfs_printk(KERN_ERR, "Error generating tag 66 packet\n");
1940		goto out;
1941	}
1942	rc = ecryptfs_send_message(payload, payload_len, &msg_ctx);
1943	if (rc) {
1944		ecryptfs_printk(KERN_ERR, "Error sending message to "
1945				"ecryptfsd: %d\n", rc);
1946		goto out;
1947	}
1948	rc = ecryptfs_wait_for_response(msg_ctx, &msg);
1949	if (rc) {
1950		ecryptfs_printk(KERN_ERR, "Failed to receive tag 67 packet "
1951				"from the user space daemon\n");
1952		rc = -EIO;
1953		goto out;
1954	}
1955	rc = parse_tag_67_packet(key_rec, msg);
1956	if (rc)
1957		ecryptfs_printk(KERN_ERR, "Error parsing tag 67 packet\n");
1958	kfree(msg);
1959out:
1960	kfree(payload);
1961	return rc;
1962}
1963/**
1964 * write_tag_1_packet - Write an RFC2440-compatible tag 1 (public key) packet
1965 * @dest: Buffer into which to write the packet
1966 * @remaining_bytes: Maximum number of bytes that can be writtn
1967 * @auth_tok_key: The authentication token key to unlock and put when done with
1968 *                @auth_tok
1969 * @auth_tok: The authentication token used for generating the tag 1 packet
1970 * @crypt_stat: The cryptographic context
1971 * @key_rec: The key record struct for the tag 1 packet
1972 * @packet_size: This function will write the number of bytes that end
1973 *               up constituting the packet; set to zero on error
1974 *
1975 * Returns zero on success; non-zero on error.
1976 */
1977static int
1978write_tag_1_packet(char *dest, size_t *remaining_bytes,
1979		   struct key *auth_tok_key, struct ecryptfs_auth_tok *auth_tok,
1980		   struct ecryptfs_crypt_stat *crypt_stat,
1981		   struct ecryptfs_key_record *key_rec, size_t *packet_size)
1982{
1983	size_t i;
1984	size_t encrypted_session_key_valid = 0;
1985	size_t packet_size_length;
1986	size_t max_packet_size;
1987	int rc = 0;
1988
1989	(*packet_size) = 0;
1990	ecryptfs_from_hex(key_rec->sig, auth_tok->token.private_key.signature,
1991			  ECRYPTFS_SIG_SIZE);
1992	encrypted_session_key_valid = 0;
1993	for (i = 0; i < crypt_stat->key_size; i++)
1994		encrypted_session_key_valid |=
1995			auth_tok->session_key.encrypted_key[i];
1996	if (encrypted_session_key_valid) {
1997		memcpy(key_rec->enc_key,
1998		       auth_tok->session_key.encrypted_key,
1999		       auth_tok->session_key.encrypted_key_size);
2000		up_write(&(auth_tok_key->sem));
2001		key_put(auth_tok_key);
2002		goto encrypted_session_key_set;
2003	}
2004	if (auth_tok->session_key.encrypted_key_size == 0)
2005		auth_tok->session_key.encrypted_key_size =
2006			auth_tok->token.private_key.key_size;
2007	rc = pki_encrypt_session_key(auth_tok_key, auth_tok, crypt_stat,
2008				     key_rec);
2009	if (rc) {
2010		printk(KERN_ERR "Failed to encrypt session key via a key "
2011		       "module; rc = [%d]\n", rc);
2012		goto out;
2013	}
2014	if (ecryptfs_verbosity > 0) {
2015		ecryptfs_printk(KERN_DEBUG, "Encrypted key:\n");
2016		ecryptfs_dump_hex(key_rec->enc_key, key_rec->enc_key_size);
2017	}
2018encrypted_session_key_set:
2019	/* This format is inspired by OpenPGP; see RFC 2440
2020	 * packet tag 1 */
2021	max_packet_size = (1                         /* Tag 1 identifier */
2022			   + 3                       /* Max Tag 1 packet size */
2023			   + 1                       /* Version */
2024			   + ECRYPTFS_SIG_SIZE       /* Key identifier */
2025			   + 1                       /* Cipher identifier */
2026			   + key_rec->enc_key_size); /* Encrypted key size */
2027	if (max_packet_size > (*remaining_bytes)) {
2028		printk(KERN_ERR "Packet length larger than maximum allowable; "
2029		       "need up to [%td] bytes, but there are only [%td] "
2030		       "available\n", max_packet_size, (*remaining_bytes));
2031		rc = -EINVAL;
2032		goto out;
2033	}
2034	dest[(*packet_size)++] = ECRYPTFS_TAG_1_PACKET_TYPE;
2035	rc = ecryptfs_write_packet_length(&dest[(*packet_size)],
2036					  (max_packet_size - 4),
2037					  &packet_size_length);
2038	if (rc) {
2039		ecryptfs_printk(KERN_ERR, "Error generating tag 1 packet "
2040				"header; cannot generate packet length\n");
2041		goto out;
2042	}
2043	(*packet_size) += packet_size_length;
2044	dest[(*packet_size)++] = 0x03; /* version 3 */
2045	memcpy(&dest[(*packet_size)], key_rec->sig, ECRYPTFS_SIG_SIZE);
2046	(*packet_size) += ECRYPTFS_SIG_SIZE;
2047	dest[(*packet_size)++] = RFC2440_CIPHER_RSA;
2048	memcpy(&dest[(*packet_size)], key_rec->enc_key,
2049	       key_rec->enc_key_size);
2050	(*packet_size) += key_rec->enc_key_size;
2051out:
2052	if (rc)
2053		(*packet_size) = 0;
2054	else
2055		(*remaining_bytes) -= (*packet_size);
2056	return rc;
2057}
2058
2059/**
2060 * write_tag_11_packet
2061 * @dest: Target into which Tag 11 packet is to be written
2062 * @remaining_bytes: Maximum packet length
2063 * @contents: Byte array of contents to copy in
2064 * @contents_length: Number of bytes in contents
2065 * @packet_length: Length of the Tag 11 packet written; zero on error
2066 *
2067 * Returns zero on success; non-zero on error.
2068 */
2069static int
2070write_tag_11_packet(char *dest, size_t *remaining_bytes, char *contents,
2071		    size_t contents_length, size_t *packet_length)
2072{
2073	size_t packet_size_length;
2074	size_t max_packet_size;
2075	int rc = 0;
2076
2077	(*packet_length) = 0;
2078	/* This format is inspired by OpenPGP; see RFC 2440
2079	 * packet tag 11 */
2080	max_packet_size = (1                   /* Tag 11 identifier */
2081			   + 3                 /* Max Tag 11 packet size */
2082			   + 1                 /* Binary format specifier */
2083			   + 1                 /* Filename length */
2084			   + 8                 /* Filename ("_CONSOLE") */
2085			   + 4                 /* Modification date */
2086			   + contents_length); /* Literal data */
2087	if (max_packet_size > (*remaining_bytes)) {
2088		printk(KERN_ERR "Packet length larger than maximum allowable; "
2089		       "need up to [%td] bytes, but there are only [%td] "
2090		       "available\n", max_packet_size, (*remaining_bytes));
2091		rc = -EINVAL;
2092		goto out;
2093	}
2094	dest[(*packet_length)++] = ECRYPTFS_TAG_11_PACKET_TYPE;
2095	rc = ecryptfs_write_packet_length(&dest[(*packet_length)],
2096					  (max_packet_size - 4),
2097					  &packet_size_length);
2098	if (rc) {
2099		printk(KERN_ERR "Error generating tag 11 packet header; cannot "
2100		       "generate packet length. rc = [%d]\n", rc);
2101		goto out;
2102	}
2103	(*packet_length) += packet_size_length;
2104	dest[(*packet_length)++] = 0x62; /* binary data format specifier */
2105	dest[(*packet_length)++] = 8;
2106	memcpy(&dest[(*packet_length)], "_CONSOLE", 8);
2107	(*packet_length) += 8;
2108	memset(&dest[(*packet_length)], 0x00, 4);
2109	(*packet_length) += 4;
2110	memcpy(&dest[(*packet_length)], contents, contents_length);
2111	(*packet_length) += contents_length;
2112 out:
2113	if (rc)
2114		(*packet_length) = 0;
2115	else
2116		(*remaining_bytes) -= (*packet_length);
2117	return rc;
2118}
2119
2120/**
2121 * write_tag_3_packet
2122 * @dest: Buffer into which to write the packet
2123 * @remaining_bytes: Maximum number of bytes that can be written
2124 * @auth_tok: Authentication token
2125 * @crypt_stat: The cryptographic context
2126 * @key_rec: encrypted key
2127 * @packet_size: This function will write the number of bytes that end
2128 *               up constituting the packet; set to zero on error
2129 *
2130 * Returns zero on success; non-zero on error.
2131 */
2132static int
2133write_tag_3_packet(char *dest, size_t *remaining_bytes,
2134		   struct ecryptfs_auth_tok *auth_tok,
2135		   struct ecryptfs_crypt_stat *crypt_stat,
2136		   struct ecryptfs_key_record *key_rec, size_t *packet_size)
2137{
2138	size_t i;
2139	size_t encrypted_session_key_valid = 0;
2140	char session_key_encryption_key[ECRYPTFS_MAX_KEY_BYTES];
2141	struct scatterlist dst_sg[2];
2142	struct scatterlist src_sg[2];
2143	struct mutex *tfm_mutex = NULL;
2144	u8 cipher_code;
2145	size_t packet_size_length;
2146	size_t max_packet_size;
2147	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
2148		crypt_stat->mount_crypt_stat;
2149	struct crypto_skcipher *tfm;
2150	struct skcipher_request *req;
2151	int rc = 0;
2152
2153	(*packet_size) = 0;
2154	ecryptfs_from_hex(key_rec->sig, auth_tok->token.password.signature,
2155			  ECRYPTFS_SIG_SIZE);
2156	rc = ecryptfs_get_tfm_and_mutex_for_cipher_name(&tfm, &tfm_mutex,
2157							crypt_stat->cipher);
2158	if (unlikely(rc)) {
2159		printk(KERN_ERR "Internal error whilst attempting to get "
2160		       "tfm and mutex for cipher name [%s]; rc = [%d]\n",
2161		       crypt_stat->cipher, rc);
2162		goto out;
2163	}
2164	if (mount_crypt_stat->global_default_cipher_key_size == 0) {
2165		printk(KERN_WARNING "No key size specified at mount; "
2166		       "defaulting to [%d]\n",
2167		       crypto_skcipher_max_keysize(tfm));
2168		mount_crypt_stat->global_default_cipher_key_size =
2169			crypto_skcipher_max_keysize(tfm);
2170	}
2171	if (crypt_stat->key_size == 0)
2172		crypt_stat->key_size =
2173			mount_crypt_stat->global_default_cipher_key_size;
2174	if (auth_tok->session_key.encrypted_key_size == 0)
2175		auth_tok->session_key.encrypted_key_size =
2176			crypt_stat->key_size;
2177	if (crypt_stat->key_size == 24
2178	    && strcmp("aes", crypt_stat->cipher) == 0) {
2179		memset((crypt_stat->key + 24), 0, 8);
2180		auth_tok->session_key.encrypted_key_size = 32;
2181	} else
2182		auth_tok->session_key.encrypted_key_size = crypt_stat->key_size;
2183	key_rec->enc_key_size =
2184		auth_tok->session_key.encrypted_key_size;
2185	encrypted_session_key_valid = 0;
2186	for (i = 0; i < auth_tok->session_key.encrypted_key_size; i++)
2187		encrypted_session_key_valid |=
2188			auth_tok->session_key.encrypted_key[i];
2189	if (encrypted_session_key_valid) {
2190		ecryptfs_printk(KERN_DEBUG, "encrypted_session_key_valid != 0; "
2191				"using auth_tok->session_key.encrypted_key, "
2192				"where key_rec->enc_key_size = [%zd]\n",
2193				key_rec->enc_key_size);
2194		memcpy(key_rec->enc_key,
2195		       auth_tok->session_key.encrypted_key,
2196		       key_rec->enc_key_size);
2197		goto encrypted_session_key_set;
2198	}
2199	if (auth_tok->token.password.flags &
2200	    ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET) {
2201		ecryptfs_printk(KERN_DEBUG, "Using previously generated "
2202				"session key encryption key of size [%d]\n",
2203				auth_tok->token.password.
2204				session_key_encryption_key_bytes);
2205		memcpy(session_key_encryption_key,
2206		       auth_tok->token.password.session_key_encryption_key,
2207		       crypt_stat->key_size);
2208		ecryptfs_printk(KERN_DEBUG,
2209				"Cached session key encryption key:\n");
2210		if (ecryptfs_verbosity > 0)
2211			ecryptfs_dump_hex(session_key_encryption_key, 16);
2212	}
2213	if (unlikely(ecryptfs_verbosity > 0)) {
2214		ecryptfs_printk(KERN_DEBUG, "Session key encryption key:\n");
2215		ecryptfs_dump_hex(session_key_encryption_key, 16);
2216	}
2217	rc = virt_to_scatterlist(crypt_stat->key, key_rec->enc_key_size,
2218				 src_sg, 2);
2219	if (rc < 1 || rc > 2) {
2220		ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
2221				"for crypt_stat session key; expected rc = 1; "
2222				"got rc = [%d]. key_rec->enc_key_size = [%zd]\n",
2223				rc, key_rec->enc_key_size);
2224		rc = -ENOMEM;
2225		goto out;
2226	}
2227	rc = virt_to_scatterlist(key_rec->enc_key, key_rec->enc_key_size,
2228				 dst_sg, 2);
2229	if (rc < 1 || rc > 2) {
2230		ecryptfs_printk(KERN_ERR, "Error generating scatterlist "
2231				"for crypt_stat encrypted session key; "
2232				"expected rc = 1; got rc = [%d]. "
2233				"key_rec->enc_key_size = [%zd]\n", rc,
2234				key_rec->enc_key_size);
2235		rc = -ENOMEM;
2236		goto out;
2237	}
2238	mutex_lock(tfm_mutex);
2239	rc = crypto_skcipher_setkey(tfm, session_key_encryption_key,
2240				    crypt_stat->key_size);
2241	if (rc < 0) {
2242		mutex_unlock(tfm_mutex);
2243		ecryptfs_printk(KERN_ERR, "Error setting key for crypto "
2244				"context; rc = [%d]\n", rc);
2245		goto out;
2246	}
2247
2248	req = skcipher_request_alloc(tfm, GFP_KERNEL);
2249	if (!req) {
2250		mutex_unlock(tfm_mutex);
2251		ecryptfs_printk(KERN_ERR, "Out of kernel memory whilst "
2252				"attempting to skcipher_request_alloc for "
2253				"%s\n", crypto_skcipher_driver_name(tfm));
2254		rc = -ENOMEM;
2255		goto out;
2256	}
2257
2258	skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP,
2259				      NULL, NULL);
2260
2261	rc = 0;
2262	ecryptfs_printk(KERN_DEBUG, "Encrypting [%zd] bytes of the key\n",
2263			crypt_stat->key_size);
2264	skcipher_request_set_crypt(req, src_sg, dst_sg,
2265				   (*key_rec).enc_key_size, NULL);
2266	rc = crypto_skcipher_encrypt(req);
2267	mutex_unlock(tfm_mutex);
2268	skcipher_request_free(req);
2269	if (rc) {
2270		printk(KERN_ERR "Error encrypting; rc = [%d]\n", rc);
2271		goto out;
2272	}
2273	ecryptfs_printk(KERN_DEBUG, "This should be the encrypted key:\n");
2274	if (ecryptfs_verbosity > 0) {
2275		ecryptfs_printk(KERN_DEBUG, "EFEK of size [%zd]:\n",
2276				key_rec->enc_key_size);
2277		ecryptfs_dump_hex(key_rec->enc_key,
2278				  key_rec->enc_key_size);
2279	}
2280encrypted_session_key_set:
2281	/* This format is inspired by OpenPGP; see RFC 2440
2282	 * packet tag 3 */
2283	max_packet_size = (1                         /* Tag 3 identifier */
2284			   + 3                       /* Max Tag 3 packet size */
2285			   + 1                       /* Version */
2286			   + 1                       /* Cipher code */
2287			   + 1                       /* S2K specifier */
2288			   + 1                       /* Hash identifier */
2289			   + ECRYPTFS_SALT_SIZE      /* Salt */
2290			   + 1                       /* Hash iterations */
2291			   + key_rec->enc_key_size); /* Encrypted key size */
2292	if (max_packet_size > (*remaining_bytes)) {
2293		printk(KERN_ERR "Packet too large; need up to [%td] bytes, but "
2294		       "there are only [%td] available\n", max_packet_size,
2295		       (*remaining_bytes));
2296		rc = -EINVAL;
2297		goto out;
2298	}
2299	dest[(*packet_size)++] = ECRYPTFS_TAG_3_PACKET_TYPE;
2300	/* Chop off the Tag 3 identifier(1) and Tag 3 packet size(3)
2301	 * to get the number of octets in the actual Tag 3 packet */
2302	rc = ecryptfs_write_packet_length(&dest[(*packet_size)],
2303					  (max_packet_size - 4),
2304					  &packet_size_length);
2305	if (rc) {
2306		printk(KERN_ERR "Error generating tag 3 packet header; cannot "
2307		       "generate packet length. rc = [%d]\n", rc);
2308		goto out;
2309	}
2310	(*packet_size) += packet_size_length;
2311	dest[(*packet_size)++] = 0x04; /* version 4 */
2312	/* TODO: Break from RFC2440 so that arbitrary ciphers can be
2313	 * specified with strings */
2314	cipher_code = ecryptfs_code_for_cipher_string(crypt_stat->cipher,
2315						      crypt_stat->key_size);
2316	if (cipher_code == 0) {
2317		ecryptfs_printk(KERN_WARNING, "Unable to generate code for "
2318				"cipher [%s]\n", crypt_stat->cipher);
2319		rc = -EINVAL;
2320		goto out;
2321	}
2322	dest[(*packet_size)++] = cipher_code;
2323	dest[(*packet_size)++] = 0x03;	/* S2K */
2324	dest[(*packet_size)++] = 0x01;	/* MD5 (TODO: parameterize) */
2325	memcpy(&dest[(*packet_size)], auth_tok->token.password.salt,
2326	       ECRYPTFS_SALT_SIZE);
2327	(*packet_size) += ECRYPTFS_SALT_SIZE;	/* salt */
2328	dest[(*packet_size)++] = 0x60;	/* hash iterations (65536) */
2329	memcpy(&dest[(*packet_size)], key_rec->enc_key,
2330	       key_rec->enc_key_size);
2331	(*packet_size) += key_rec->enc_key_size;
2332out:
2333	if (rc)
2334		(*packet_size) = 0;
2335	else
2336		(*remaining_bytes) -= (*packet_size);
2337	return rc;
2338}
2339
2340struct kmem_cache *ecryptfs_key_record_cache;
2341
2342/**
2343 * ecryptfs_generate_key_packet_set
2344 * @dest_base: Virtual address from which to write the key record set
2345 * @crypt_stat: The cryptographic context from which the
2346 *              authentication tokens will be retrieved
2347 * @ecryptfs_dentry: The dentry, used to retrieve the mount crypt stat
2348 *                   for the global parameters
2349 * @len: The amount written
2350 * @max: The maximum amount of data allowed to be written
2351 *
2352 * Generates a key packet set and writes it to the virtual address
2353 * passed in.
2354 *
2355 * Returns zero on success; non-zero on error.
2356 */
2357int
2358ecryptfs_generate_key_packet_set(char *dest_base,
2359				 struct ecryptfs_crypt_stat *crypt_stat,
2360				 struct dentry *ecryptfs_dentry, size_t *len,
2361				 size_t max)
2362{
2363	struct ecryptfs_auth_tok *auth_tok;
2364	struct key *auth_tok_key = NULL;
2365	struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
2366		&ecryptfs_superblock_to_private(
2367			ecryptfs_dentry->d_sb)->mount_crypt_stat;
2368	size_t written;
2369	struct ecryptfs_key_record *key_rec;
2370	struct ecryptfs_key_sig *key_sig;
2371	int rc = 0;
2372
2373	(*len) = 0;
2374	mutex_lock(&crypt_stat->keysig_list_mutex);
2375	key_rec = kmem_cache_alloc(ecryptfs_key_record_cache, GFP_KERNEL);
2376	if (!key_rec) {
2377		rc = -ENOMEM;
2378		goto out;
2379	}
2380	list_for_each_entry(key_sig, &crypt_stat->keysig_list,
2381			    crypt_stat_list) {
2382		memset(key_rec, 0, sizeof(*key_rec));
2383		rc = ecryptfs_find_global_auth_tok_for_sig(&auth_tok_key,
2384							   &auth_tok,
2385							   mount_crypt_stat,
2386							   key_sig->keysig);
2387		if (rc) {
2388			printk(KERN_WARNING "Unable to retrieve auth tok with "
2389			       "sig = [%s]\n", key_sig->keysig);
2390			rc = process_find_global_auth_tok_for_sig_err(rc);
2391			goto out_free;
2392		}
2393		if (auth_tok->token_type == ECRYPTFS_PASSWORD) {
2394			rc = write_tag_3_packet((dest_base + (*len)),
2395						&max, auth_tok,
2396						crypt_stat, key_rec,
2397						&written);
2398			up_write(&(auth_tok_key->sem));
2399			key_put(auth_tok_key);
2400			if (rc) {
2401				ecryptfs_printk(KERN_WARNING, "Error "
2402						"writing tag 3 packet\n");
2403				goto out_free;
2404			}
2405			(*len) += written;
2406			/* Write auth tok signature packet */
2407			rc = write_tag_11_packet((dest_base + (*len)), &max,
2408						 key_rec->sig,
2409						 ECRYPTFS_SIG_SIZE, &written);
2410			if (rc) {
2411				ecryptfs_printk(KERN_ERR, "Error writing "
2412						"auth tok signature packet\n");
2413				goto out_free;
2414			}
2415			(*len) += written;
2416		} else if (auth_tok->token_type == ECRYPTFS_PRIVATE_KEY) {
2417			rc = write_tag_1_packet(dest_base + (*len), &max,
2418						auth_tok_key, auth_tok,
2419						crypt_stat, key_rec, &written);
2420			if (rc) {
2421				ecryptfs_printk(KERN_WARNING, "Error "
2422						"writing tag 1 packet\n");
2423				goto out_free;
2424			}
2425			(*len) += written;
2426		} else {
2427			up_write(&(auth_tok_key->sem));
2428			key_put(auth_tok_key);
2429			ecryptfs_printk(KERN_WARNING, "Unsupported "
2430					"authentication token type\n");
2431			rc = -EINVAL;
2432			goto out_free;
2433		}
2434	}
2435	if (likely(max > 0)) {
2436		dest_base[(*len)] = 0x00;
2437	} else {
2438		ecryptfs_printk(KERN_ERR, "Error writing boundary byte\n");
2439		rc = -EIO;
2440	}
2441out_free:
2442	kmem_cache_free(ecryptfs_key_record_cache, key_rec);
2443out:
2444	if (rc)
2445		(*len) = 0;
2446	mutex_unlock(&crypt_stat->keysig_list_mutex);
2447	return rc;
2448}
2449
2450struct kmem_cache *ecryptfs_key_sig_cache;
2451
2452int ecryptfs_add_keysig(struct ecryptfs_crypt_stat *crypt_stat, char *sig)
2453{
2454	struct ecryptfs_key_sig *new_key_sig;
2455
2456	new_key_sig = kmem_cache_alloc(ecryptfs_key_sig_cache, GFP_KERNEL);
2457	if (!new_key_sig)
2458		return -ENOMEM;
2459
2460	memcpy(new_key_sig->keysig, sig, ECRYPTFS_SIG_SIZE_HEX);
2461	new_key_sig->keysig[ECRYPTFS_SIG_SIZE_HEX] = '\0';
2462	/* Caller must hold keysig_list_mutex */
2463	list_add(&new_key_sig->crypt_stat_list, &crypt_stat->keysig_list);
2464
2465	return 0;
2466}
2467
2468struct kmem_cache *ecryptfs_global_auth_tok_cache;
2469
2470int
2471ecryptfs_add_global_auth_tok(struct ecryptfs_mount_crypt_stat *mount_crypt_stat,
2472			     char *sig, u32 global_auth_tok_flags)
2473{
2474	struct ecryptfs_global_auth_tok *new_auth_tok;
2475
2476	new_auth_tok = kmem_cache_zalloc(ecryptfs_global_auth_tok_cache,
2477					GFP_KERNEL);
2478	if (!new_auth_tok)
2479		return -ENOMEM;
2480
2481	memcpy(new_auth_tok->sig, sig, ECRYPTFS_SIG_SIZE_HEX);
2482	new_auth_tok->flags = global_auth_tok_flags;
2483	new_auth_tok->sig[ECRYPTFS_SIG_SIZE_HEX] = '\0';
2484	mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
2485	list_add(&new_auth_tok->mount_crypt_stat_list,
2486		 &mount_crypt_stat->global_auth_tok_list);
2487	mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
2488	return 0;
2489}
2490
~/ Read-only file preview.