Upgrade fsverity-utils to 2151209ce1dae61c4ee7480e2c39ada1d912fcb2
am: d318ab55d3

Change-Id: I07e68a88f63dd6b2dc3cfdfb01332ee48ac9d670
diff --git a/METADATA b/METADATA
index 2f19f50..c92888e 100644
--- a/METADATA
+++ b/METADATA
@@ -5,11 +5,11 @@
     type: GIT
     value: "https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/fsverity-utils.git"
   }
-  version: "23a20ab7e8371cc29015d7d5787daa73f2ddd374"
+  version: "2151209ce1dae61c4ee7480e2c39ada1d912fcb2"
   license_type: RESTRICTED
   last_upgrade_date {
     year: 2019
-    month: 2
-    day: 11
+    month: 7
+    day: 24
   }
 }
diff --git a/README.md b/README.md
index be2a251..8a72088 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,9 @@
 # Introduction
 
-This is `fsverity`, a userspace utility for fs-verity.  fs-verity is
-a Linux kernel feature that does transparent on-demand
+This is `fsverity`, a userspace utility for fs-verity.  fs-verity is a
+Linux kernel feature that does transparent on-demand
 integrity/authenticity verification of the contents of read-only
-files, using a Merkle tree (hash tree) hidden after the end of the
+files, using a hidden Merkle tree (hash tree) associated with the
 file.  The mechanism is similar to dm-verity, but implemented at the
 file level rather than at the block device level.  The `fsverity`
 utility allows you to set up fs-verity protected files.
@@ -35,7 +35,7 @@
 ## Basic use
 
 ```bash
-    mkfs.f2fs -O verity /dev/vdc
+    mkfs.ext4 -O verity /dev/vdc
     mount /dev/vdc /vdc
     cd /vdc
 
@@ -43,18 +43,16 @@
     head -c 1000000 /dev/urandom > file
     md5sum file
 
-    # Append the Merkle tree and other metadata to the file:
-    fsverity setup file
-
-    # Enable fs-verity on the file
+    # Enable verity on the file
     fsverity enable file
 
-    # Should show the same hash that 'fsverity setup' printed.
-    # This hash can be logged, or compared to a trusted value.
+    # Show the verity file measurement
     fsverity measure file
 
-    # Contents are now transparently verified and should match the
-    # original file contents, i.e. the metadata is hidden.
+    # File should still be readable as usual.  However, all data read
+    # is now transparently checked against a hidden Merkle tree, whose
+    # root hash is incorporated into the verity file measurement.
+    # Reads of any corrupted parts of the data will fail.
     md5sum file
 ```
 
@@ -67,7 +65,7 @@
 
 With `CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y`, the filesystem supports
 automatically verifying a signed file measurement that has been
-included in the fs-verity metadata.  The signature is verified against
+included in the verity metadata.  The signature is verified against
 the set of X.509 certificates that have been loaded into the
 ".fs-verity" kernel keyring.  Here's an example:
 
@@ -85,24 +83,25 @@
     # (requires keyctl v1.5.11 or later):
     keyctl restrict_keyring %keyring:.fs-verity
 
-    # Optionally, require that all fs-verity files be signed:
+    # Optionally, require that all verity files be signed:
     sysctl fs.verity.require_signatures=1
 
     # Now set up fs-verity on a test file:
     md5sum file
-    fsverity setup file --signing-key=key.pem --signing-cert=cert.pem
-    fsverity enable file
+    fsverity sign file file.sig --key=key.pem --cert=cert.pem
+    fsverity enable file --signature=file.sig
+    rm -f file.sig
     md5sum file
 ```
 
-By default, it's not required that fs-verity files have a signature.
+By default, it's not required that verity files have a signature.
 This can be changed with `sysctl fs.verity.require_signatures=1`.
-When set, it's guaranteed that the contents of every fs-verity file
-has been signed by one of the certificates in the keyring.
+When set, it's guaranteed that the contents of every verity file has
+been signed by one of the certificates in the keyring.
 
 Note: applications generally still need to check whether the file
-they're accessing really is a fs-verity file, since an attacker could
-replace a fs-verity file with a regular one.
+they're accessing really is a verity file, since an attacker could
+replace a verity file with a regular one.
 
 ## With IMA
 
diff --git a/cmd_enable.c b/cmd_enable.c
index ed092f0..1646299 100644
--- a/cmd_enable.c
+++ b/cmd_enable.c
@@ -8,30 +8,165 @@
  */
 
 #include <fcntl.h>
+#include <getopt.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
 #include <sys/ioctl.h>
 
 #include "commands.h"
 #include "fsverity_uapi.h"
+#include "hash_algs.h"
 
+static bool parse_hash_alg_option(const char *arg, u32 *alg_ptr)
+{
+	char *end;
+	unsigned long n = strtoul(arg, &end, 10);
+	const struct fsverity_hash_alg *alg;
+
+	if (*alg_ptr != 0) {
+		error_msg("--hash-alg can only be specified once");
+		return false;
+	}
+
+	/* Specified by number? */
+	if (n > 0 && n < INT32_MAX && *end == '\0') {
+		*alg_ptr = n;
+		return true;
+	}
+
+	/* Specified by name? */
+	alg = find_hash_alg_by_name(arg);
+	if (alg != NULL) {
+		*alg_ptr = alg - fsverity_hash_algs;
+		return true;
+	}
+	return false;
+}
+
+static bool read_signature(const char *filename, u8 **sig_ret,
+			   u32 *sig_size_ret)
+{
+	struct filedes file = { .fd = -1 };
+	u64 file_size;
+	u8 *sig = NULL;
+	bool ok = false;
+
+	if (!open_file(&file, filename, O_RDONLY, 0))
+		goto out;
+	if (!get_file_size(&file, &file_size))
+		goto out;
+	if (file_size <= 0) {
+		error_msg("signature file '%s' is empty", filename);
+		goto out;
+	}
+	if (file_size > 1000000) {
+		error_msg("signature file '%s' is too large", filename);
+		goto out;
+	}
+	sig = xmalloc(file_size);
+	if (!full_read(&file, sig, file_size))
+		goto out;
+	*sig_ret = sig;
+	*sig_size_ret = file_size;
+	sig = NULL;
+	ok = true;
+out:
+	filedes_close(&file);
+	free(sig);
+	return ok;
+}
+
+enum {
+	OPT_HASH_ALG,
+	OPT_BLOCK_SIZE,
+	OPT_SALT,
+	OPT_SIGNATURE,
+};
+
+static const struct option longopts[] = {
+	{"hash-alg",	required_argument, NULL, OPT_HASH_ALG},
+	{"block-size",	required_argument, NULL, OPT_BLOCK_SIZE},
+	{"salt",	required_argument, NULL, OPT_SALT},
+	{"signature",	required_argument, NULL, OPT_SIGNATURE},
+	{NULL, 0, NULL, 0}
+};
+
+/* Enable fs-verity on a file. */
 int fsverity_cmd_enable(const struct fsverity_command *cmd,
 			int argc, char *argv[])
 {
+	struct fsverity_enable_arg arg = { .version = 1 };
+	u8 *salt = NULL;
+	u8 *sig = NULL;
 	struct filedes file;
+	int status;
+	int c;
 
-	if (argc != 2) {
-		usage(cmd, stderr);
-		return 2;
+	while ((c = getopt_long(argc, argv, "", longopts, NULL)) != -1) {
+		switch (c) {
+		case OPT_HASH_ALG:
+			if (!parse_hash_alg_option(optarg, &arg.hash_algorithm))
+				goto out_usage;
+			break;
+		case OPT_BLOCK_SIZE:
+			if (!parse_block_size_option(optarg, &arg.block_size))
+				goto out_usage;
+			break;
+		case OPT_SALT:
+			if (!parse_salt_option(optarg, &salt, &arg.salt_size))
+				goto out_usage;
+			arg.salt_ptr = (uintptr_t)salt;
+			break;
+		case OPT_SIGNATURE:
+			if (sig != NULL) {
+				error_msg("--signature can only be specified once");
+				goto out_usage;
+			}
+			if (!read_signature(optarg, &sig, &arg.sig_size))
+				goto out_err;
+			arg.sig_ptr = (uintptr_t)sig;
+			break;
+		default:
+			goto out_usage;
+		}
 	}
 
-	if (!open_file(&file, argv[1], O_RDONLY, 0))
-		return 1;
-	if (ioctl(file.fd, FS_IOC_ENABLE_VERITY, NULL) != 0) {
+	argv += optind;
+	argc -= optind;
+
+	if (argc != 1)
+		goto out_usage;
+
+	if (arg.hash_algorithm == 0)
+		arg.hash_algorithm = FS_VERITY_HASH_ALG_DEFAULT;
+
+	if (arg.block_size == 0)
+		arg.block_size = get_default_block_size();
+
+	if (!open_file(&file, argv[0], O_RDONLY, 0))
+		goto out_err;
+	if (ioctl(file.fd, FS_IOC_ENABLE_VERITY, &arg) != 0) {
 		error_msg_errno("FS_IOC_ENABLE_VERITY failed on '%s'",
 				file.name);
 		filedes_close(&file);
-		return 1;
+		goto out_err;
 	}
 	if (!filedes_close(&file))
-		return 1;
-	return 0;
+		goto out_err;
+
+	status = 0;
+out:
+	free(salt);
+	free(sig);
+	return status;
+
+out_err:
+	status = 1;
+	goto out;
+
+out_usage:
+	usage(cmd, stderr);
+	status = 2;
+	goto out;
 }
diff --git a/cmd_measure.c b/cmd_measure.c
index a5480a6..574e3ca 100644
--- a/cmd_measure.c
+++ b/cmd_measure.c
@@ -15,6 +15,7 @@
 #include "fsverity_uapi.h"
 #include "hash_algs.h"
 
+/* Display the measurement of the given verity file(s). */
 int fsverity_cmd_measure(const struct fsverity_command *cmd,
 			 int argc, char *argv[])
 {
diff --git a/cmd_setup.c b/cmd_setup.c
deleted file mode 100644
index c598a71..0000000
--- a/cmd_setup.c
+++ /dev/null
@@ -1,565 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0+
-/*
- * The 'fsverity setup' command
- *
- * Copyright (C) 2018 Google LLC
- *
- * Written by Eric Biggers.
- */
-
-#include <fcntl.h>
-#include <getopt.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "commands.h"
-#include "fsverity_uapi.h"
-#include "fsveritysetup.h"
-#include "hash_algs.h"
-
-enum {
-	OPT_HASH,
-	OPT_SALT,
-	OPT_BLOCKSIZE,
-	OPT_SIGNING_KEY,
-	OPT_SIGNING_CERT,
-	OPT_SIGNATURE,
-	OPT_ELIDE,
-	OPT_PATCH,
-};
-
-static const struct option longopts[] = {
-	{"hash",		required_argument, NULL, OPT_HASH},
-	{"salt",		required_argument, NULL, OPT_SALT},
-	{"blocksize",		required_argument, NULL, OPT_BLOCKSIZE},
-	{"signing-key",		required_argument, NULL, OPT_SIGNING_KEY},
-	{"signing-cert",	required_argument, NULL, OPT_SIGNING_CERT},
-	{"signature",		required_argument, NULL, OPT_SIGNATURE},
-	{"elide",		required_argument, NULL, OPT_ELIDE},
-	{"patch",		required_argument, NULL, OPT_PATCH},
-	{NULL, 0, NULL, 0}
-};
-
-/* Parse the --blocksize=BLOCKSIZE option */
-static bool parse_blocksize_option(const char *opt, int *blocksize_ret)
-{
-	char *end;
-	unsigned long n = strtoul(opt, &end, 10);
-
-	if (n <= 0 || n >= INT32_MAX || *end || !is_power_of_2(n)) {
-		error_msg("Invalid block size: %s.  Must be power of 2", opt);
-		return false;
-	}
-	*blocksize_ret = n;
-	return true;
-}
-
-#define FS_VERITY_MAX_LEVELS	64
-
-/*
- * Calculate the depth of the Merkle tree, then create a map from level to the
- * block offset at which that level's hash blocks start.  Level 'depth - 1' is
- * the root and is stored first in the file, in the first block following the
- * original data.  Level 0 is the "leaf" level: it's directly "above" the data
- * blocks and is stored last in the file.
- */
-static void compute_tree_layout(u64 data_size, u64 tree_offset, int blockbits,
-				unsigned int hashes_per_block,
-				u64 hash_lvl_region_idx[FS_VERITY_MAX_LEVELS],
-				int *depth_ret, u64 *tree_end_ret)
-{
-	u64 blocks = data_size >> blockbits;
-	u64 offset = tree_offset >> blockbits;
-	int depth = 0;
-	int i;
-
-	ASSERT(data_size > 0);
-	ASSERT(data_size % (1 << blockbits) == 0);
-	ASSERT(tree_offset % (1 << blockbits) == 0);
-	ASSERT(hashes_per_block >= 2);
-
-	while (blocks > 1) {
-		ASSERT(depth < FS_VERITY_MAX_LEVELS);
-		blocks = DIV_ROUND_UP(blocks, hashes_per_block);
-		hash_lvl_region_idx[depth++] = blocks;
-	}
-	for (i = depth - 1; i >= 0; i--) {
-		u64 next_count = hash_lvl_region_idx[i];
-
-		hash_lvl_region_idx[i] = offset;
-		offset += next_count;
-	}
-	*depth_ret = depth;
-	*tree_end_ret = offset << blockbits;
-}
-
-/*
- * Build a Merkle tree (hash tree) over the data of a file.
- *
- * @params: Block size, hashes per block, and salt
- * @hash: Handle for the hash algorithm
- * @data_file: input data file
- * @data_size: size of data file in bytes; must be aligned to ->blocksize
- * @tree_file: output tree file
- * @tree_offset: byte offset in tree file at which to write the tree;
- *		 must be aligned to ->blocksize
- * @tree_end_ret: On success, the byte offset in the tree file of the end of the
- *		  tree is written here
- * @root_hash_ret: On success, the Merkle tree root hash is written here
- *
- * Return: exit status code (0 on success, nonzero on failure)
- */
-static int build_merkle_tree(const struct fsveritysetup_params *params,
-			     struct hash_ctx *hash,
-			     struct filedes *data_file, u64 data_size,
-			     struct filedes *tree_file, u64 tree_offset,
-			     u64 *tree_end_ret, u8 *root_hash_ret)
-{
-	const unsigned int digest_size = hash->alg->digest_size;
-	int depth;
-	u64 hash_lvl_region_idx[FS_VERITY_MAX_LEVELS];
-	u8 *data_to_hash = NULL;
-	u8 *pending_hashes = NULL;
-	unsigned int pending_hash_bytes;
-	u64 nr_hashes_at_this_lvl;
-	int lvl;
-	int status;
-
-	compute_tree_layout(data_size, tree_offset, params->blockbits,
-			    params->hashes_per_block, hash_lvl_region_idx,
-			    &depth, tree_end_ret);
-
-	/* Allocate block buffers */
-	data_to_hash = xmalloc(params->blocksize);
-	pending_hashes = xmalloc(params->blocksize);
-	pending_hash_bytes = 0;
-	nr_hashes_at_this_lvl = data_size >> params->blockbits;
-
-	/*
-	 * Generate each level of the Merkle tree, starting at the leaf level
-	 * ('lvl == 0') and ascending to the root node ('lvl == depth - 1').
-	 * Then at the end ('lvl == depth'), calculate the root node's hash.
-	 */
-	for (lvl = 0; lvl <= depth; lvl++) {
-		u64 i;
-
-		for (i = 0; i < nr_hashes_at_this_lvl; i++) {
-			struct filedes *file;
-			u64 blk_idx;
-
-			hash_init(hash);
-			hash_update(hash, params->salt, params->saltlen);
-
-			if (lvl == 0) {
-				/* Leaf: hashing a data block */
-				file = data_file;
-				blk_idx = i;
-			} else {
-				/* Non-leaf: hashing a hash block */
-				file = tree_file;
-				blk_idx = hash_lvl_region_idx[lvl - 1] + i;
-			}
-			if (!full_pread(file, data_to_hash, params->blocksize,
-					blk_idx << params->blockbits))
-				goto out_err;
-			hash_update(hash, data_to_hash, params->blocksize);
-
-			hash_final(hash, &pending_hashes[pending_hash_bytes]);
-			pending_hash_bytes += digest_size;
-
-			if (lvl == depth) {
-				/* Root hash */
-				ASSERT(nr_hashes_at_this_lvl == 1);
-				ASSERT(pending_hash_bytes == digest_size);
-				memcpy(root_hash_ret, pending_hashes,
-				       digest_size);
-				status = 0;
-				goto out;
-			}
-
-			if (pending_hash_bytes + digest_size > params->blocksize
-			    || i + 1 == nr_hashes_at_this_lvl) {
-				/* Flush the pending hash block */
-				memset(&pending_hashes[pending_hash_bytes], 0,
-				       params->blocksize - pending_hash_bytes);
-				blk_idx = hash_lvl_region_idx[lvl] +
-					  (i / params->hashes_per_block);
-				if (!full_pwrite(tree_file,
-						 pending_hashes,
-						 params->blocksize,
-						 blk_idx << params->blockbits))
-					goto out_err;
-				pending_hash_bytes = 0;
-			}
-		}
-
-		nr_hashes_at_this_lvl = DIV_ROUND_UP(nr_hashes_at_this_lvl,
-						     params->hashes_per_block);
-	}
-	ASSERT(0); /* unreachable; should exit via "Root hash" case above */
-out_err:
-	status = 1;
-out:
-	free(data_to_hash);
-	free(pending_hashes);
-	return status;
-}
-
-/*
- * Append to the buffer @*buf_p an extension (variable-length metadata) item of
- * type @type, containing the data @ext of length @extlen bytes.
- */
-void fsverity_append_extension(void **buf_p, int type,
-			       const void *ext, size_t extlen)
-{
-	void *buf = *buf_p;
-	struct fsverity_extension *hdr = buf;
-
-	hdr->type = cpu_to_le16(type);
-	hdr->length = cpu_to_le32(sizeof(*hdr) + extlen);
-	hdr->reserved = 0;
-	buf += sizeof(*hdr);
-	memcpy(buf, ext, extlen);
-	buf += extlen;
-	memset(buf, 0, -extlen & 7);
-	buf += -extlen & 7;
-	ASSERT(buf - *buf_p == FSVERITY_EXTLEN(extlen));
-	*buf_p = buf;
-}
-
-/*
- * Append the authenticated portion of the fs-verity descriptor to 'out', in the
- * process updating 'hash' with the data written.
- */
-static int append_fsverity_descriptor(const struct fsveritysetup_params *params,
-				      u64 filesize, const u8 *root_hash,
-				      struct filedes *out,
-				      struct hash_ctx *hash)
-{
-	size_t desc_auth_len;
-	void *buf;
-	struct fsverity_descriptor *desc;
-	u16 auth_ext_count;
-	int status;
-
-	desc_auth_len = sizeof(*desc);
-	desc_auth_len += FSVERITY_EXTLEN(params->hash_alg->digest_size);
-	if (params->saltlen)
-		desc_auth_len += FSVERITY_EXTLEN(params->saltlen);
-	desc_auth_len += total_elide_patch_ext_length(params);
-	desc = buf = xzalloc(desc_auth_len);
-
-	memcpy(desc->magic, FS_VERITY_MAGIC, sizeof(desc->magic));
-	desc->major_version = 1;
-	desc->minor_version = 0;
-	desc->log_data_blocksize = params->blockbits;
-	desc->log_tree_blocksize = params->blockbits;
-	desc->data_algorithm = cpu_to_le16(params->hash_alg -
-					   fsverity_hash_algs);
-	desc->tree_algorithm = desc->data_algorithm;
-	desc->orig_file_size = cpu_to_le64(filesize);
-
-	auth_ext_count = 1; /* root hash */
-	if (params->saltlen)
-		auth_ext_count++;
-	auth_ext_count += params->num_elisions_and_patches;
-	desc->auth_ext_count = cpu_to_le16(auth_ext_count);
-
-	buf += sizeof(*desc);
-	fsverity_append_extension(&buf, FS_VERITY_EXT_ROOT_HASH,
-				  root_hash, params->hash_alg->digest_size);
-	if (params->saltlen)
-		fsverity_append_extension(&buf, FS_VERITY_EXT_SALT,
-					  params->salt, params->saltlen);
-	append_elide_patch_exts(&buf, params);
-	ASSERT(buf - (void *)desc == desc_auth_len);
-
-	hash_update(hash, desc, desc_auth_len);
-	if (!full_write(out, desc, desc_auth_len))
-		goto out_err;
-	status = 0;
-out:
-	free(desc);
-	return status;
-
-out_err:
-	status = 1;
-	goto out;
-}
-
-/*
- * Append any needed unauthenticated extension items: currently, just possibly a
- * PKCS7_SIGNATURE item containing the signed file measurement.
- */
-static int
-append_unauthenticated_extensions(struct filedes *out,
-				  const struct fsveritysetup_params *params,
-				  const u8 *measurement)
-{
-	u16 unauth_ext_count = 0;
-	struct {
-		__le16 unauth_ext_count;
-		__le16 pad[3];
-	} hdr;
-	bool have_sig = params->signing_key_file || params->signature_file;
-
-	if (have_sig)
-		unauth_ext_count++;
-
-	ASSERT(sizeof(hdr) % 8 == 0);
-	memset(&hdr, 0, sizeof(hdr));
-	hdr.unauth_ext_count = cpu_to_le16(unauth_ext_count);
-
-	if (!full_write(out, &hdr, sizeof(hdr)))
-		return 1;
-
-	if (have_sig)
-		return append_signed_measurement(out, params, measurement);
-
-	return 0;
-}
-
-static int append_footer(struct filedes *out, u64 desc_offset)
-{
-	struct fsverity_footer ftr;
-	u32 offset = (out->pos + sizeof(ftr)) - desc_offset;
-
-	ftr.desc_reverse_offset = cpu_to_le32(offset);
-	memcpy(ftr.magic, FS_VERITY_MAGIC, sizeof(ftr.magic));
-
-	if (!full_write(out, &ftr, sizeof(ftr)))
-		return 1;
-	return 0;
-}
-
-static int fsveritysetup(const char *infile, const char *outfile,
-			 const struct fsveritysetup_params *params)
-{
-	struct filedes _in = { .fd = -1 };
-	struct filedes _out = { .fd = -1 };
-	struct filedes _tmp = { .fd = -1 };
-	struct hash_ctx *hash = NULL;
-	struct filedes *in = &_in, *out = &_out, *src;
-	u64 filesize;
-	u64 aligned_filesize;
-	u64 src_filesize;
-	u64 tree_end_offset;
-	u8 root_hash[FS_VERITY_MAX_DIGEST_SIZE];
-	u8 measurement[FS_VERITY_MAX_DIGEST_SIZE];
-	char hash_hex[FS_VERITY_MAX_DIGEST_SIZE * 2 + 1];
-	int status;
-
-	if (!open_file(in, infile, (infile == outfile ? O_RDWR : O_RDONLY), 0))
-		goto out_err;
-
-	if (!get_file_size(in, &filesize))
-		goto out_err;
-
-	if (filesize <= 0) {
-		error_msg("input file is empty: '%s'", infile);
-		goto out_err;
-	}
-
-	if (infile == outfile) {
-		/*
-		 * Invoked with one file argument: we're appending verity
-		 * metadata to an existing file.
-		 */
-		out = in;
-		if (!filedes_seek(out, filesize, SEEK_SET))
-			goto out_err;
-	} else {
-		/*
-		 * Invoked with two file arguments: we're copying the first file
-		 * to the second file, then appending verity metadata to it.
-		 */
-		if (!open_file(out, outfile, O_RDWR|O_CREAT|O_TRUNC, 0644))
-			goto out_err;
-		if (!copy_file_data(in, out, filesize))
-			goto out_err;
-	}
-
-	/* Zero-pad the output file to the next block boundary */
-	aligned_filesize = ALIGN(filesize, params->blocksize);
-	if (!write_zeroes(out, aligned_filesize - filesize))
-		goto out_err;
-
-	if (params->num_elisions_and_patches) {
-		/* Merkle tree is built over temporary elided/patched file */
-		src = &_tmp;
-		if (!apply_elisions_and_patches(params, in, filesize,
-						src, &src_filesize))
-			goto out_err;
-	} else {
-		/* Merkle tree is built over original file */
-		src = out;
-		src_filesize = aligned_filesize;
-	}
-
-	hash = hash_create(params->hash_alg);
-
-	/* Build the file's Merkle tree and calculate its root hash */
-	status = build_merkle_tree(params, hash, src, src_filesize,
-				   out, aligned_filesize,
-				   &tree_end_offset, root_hash);
-	if (status)
-		goto out;
-	if (!filedes_seek(out, tree_end_offset, SEEK_SET))
-		goto out_err;
-
-	/* Append the additional needed metadata */
-
-	hash_init(hash);
-	status = append_fsverity_descriptor(params, filesize, root_hash,
-					    out, hash);
-	if (status)
-		goto out;
-	hash_final(hash, measurement);
-
-	status = append_unauthenticated_extensions(out, params, measurement);
-	if (status)
-		goto out;
-
-	status = append_footer(out, tree_end_offset);
-	if (status)
-		goto out;
-
-	bin2hex(measurement, params->hash_alg->digest_size, hash_hex);
-	printf("File measurement: %s:%s\n", params->hash_alg->name, hash_hex);
-	status = 0;
-out:
-	hash_free(hash);
-	if (status != 0 && out->fd >= 0) {
-		/* Error occurred; undo what we wrote */
-		if (in == out)
-			(void)ftruncate(out->fd, filesize);
-		else
-			out->autodelete = true;
-	}
-	filedes_close(&_in);
-	filedes_close(&_tmp);
-	if (!filedes_close(&_out) && status == 0)
-		status = 1;
-	return status;
-
-out_err:
-	status = 1;
-	goto out;
-}
-
-int fsverity_cmd_setup(const struct fsverity_command *cmd,
-		       int argc, char *argv[])
-{
-	struct fsveritysetup_params params = {
-		.hash_alg = DEFAULT_HASH_ALG,
-	};
-	STRING_LIST(elide_opts);
-	STRING_LIST(patch_opts);
-	int c;
-	int status;
-
-	while ((c = getopt_long(argc, argv, "", longopts, NULL)) != -1) {
-		switch (c) {
-		case OPT_HASH:
-			params.hash_alg = find_hash_alg_by_name(optarg);
-			if (!params.hash_alg)
-				goto out_usage;
-			break;
-		case OPT_SALT:
-			if (params.salt) {
-				error_msg("--salt can only be specified once");
-				goto out_usage;
-			}
-			params.saltlen = strlen(optarg) / 2;
-			params.salt = xmalloc(params.saltlen);
-			if (!hex2bin(optarg, params.salt, params.saltlen)) {
-				error_msg("salt is not a valid hex string");
-				goto out_usage;
-			}
-			break;
-		case OPT_BLOCKSIZE:
-			if (!parse_blocksize_option(optarg, &params.blocksize))
-				goto out_usage;
-			break;
-		case OPT_SIGNING_KEY:
-			params.signing_key_file = optarg;
-			break;
-		case OPT_SIGNING_CERT:
-			params.signing_cert_file = optarg;
-			break;
-		case OPT_SIGNATURE:
-			params.signature_file = optarg;
-			break;
-		case OPT_ELIDE:
-			string_list_append(&elide_opts, optarg);
-			break;
-		case OPT_PATCH:
-			string_list_append(&patch_opts, optarg);
-			break;
-		default:
-			goto out_usage;
-		}
-	}
-
-	argv += optind;
-	argc -= optind;
-
-	if (argc != 1 && argc != 2)
-		goto out_usage;
-
-	ASSERT(params.hash_alg->digest_size <= FS_VERITY_MAX_DIGEST_SIZE);
-
-	if (params.blocksize == 0) {
-		params.blocksize = sysconf(_SC_PAGESIZE);
-		if (params.blocksize <= 0 || !is_power_of_2(params.blocksize)) {
-			fprintf(stderr,
-				"Warning: invalid _SC_PAGESIZE (%d).  Assuming 4K blocks.\n",
-				params.blocksize);
-			params.blocksize = 4096;
-		}
-	}
-	params.blockbits = ilog2(params.blocksize);
-
-	params.hashes_per_block = params.blocksize /
-				  params.hash_alg->digest_size;
-	if (params.hashes_per_block < 2) {
-		error_msg("block size of %d bytes is too small for %s hash",
-			  params.blocksize, params.hash_alg->name);
-		goto out_err;
-	}
-
-	if (params.signing_cert_file && !params.signing_key_file) {
-		error_msg("--signing-cert was given, but --signing-key was not.\n"
-"       You must provide the certificate's private key file using --signing-key.");
-		goto out_err;
-	}
-
-	if ((params.signing_key_file || params.signature_file) &&
-	    !params.hash_alg->cryptographic) {
-		error_msg("Signing a file using '%s' checksums does not make sense\n"
-			  "       because '%s' is not a cryptographically secure hash algorithm.",
-			  params.hash_alg->name, params.hash_alg->name);
-		goto out_err;
-	}
-
-	if (!load_elisions_and_patches(&elide_opts, &patch_opts, &params))
-		goto out_err;
-
-	status = fsveritysetup(argv[0], argv[argc - 1], &params);
-out:
-	free(params.salt);
-	free_elisions_and_patches(&params);
-	string_list_destroy(&elide_opts);
-	string_list_destroy(&patch_opts);
-	return status;
-
-out_err:
-	status = 1;
-	goto out;
-
-out_usage:
-	usage(cmd, stderr);
-	status = 2;
-	goto out;
-}
diff --git a/cmd_sign.c b/cmd_sign.c
new file mode 100644
index 0000000..dcb37ce
--- /dev/null
+++ b/cmd_sign.c
@@ -0,0 +1,635 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * The 'fsverity sign' command
+ *
+ * Copyright (C) 2018 Google LLC
+ *
+ * Written by Eric Biggers.
+ */
+
+#include <fcntl.h>
+#include <getopt.h>
+#include <limits.h>
+#include <openssl/bio.h>
+#include <openssl/err.h>
+#include <openssl/pem.h>
+#include <openssl/pkcs7.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "commands.h"
+#include "fsverity_uapi.h"
+#include "hash_algs.h"
+
+/*
+ * Merkle tree properties.  The file measurement is the hash of this structure
+ * excluding the signature and with the sig_size field set to 0.
+ */
+struct fsverity_descriptor {
+	__u8 version;		/* must be 1 */
+	__u8 hash_algorithm;	/* Merkle tree hash algorithm */
+	__u8 log_blocksize;	/* log2 of size of data and tree blocks */
+	__u8 salt_size;		/* size of salt in bytes; 0 if none */
+	__le32 sig_size;	/* size of signature in bytes; 0 if none */
+	__le64 data_size;	/* size of file the Merkle tree is built over */
+	__u8 root_hash[64];	/* Merkle tree root hash */
+	__u8 salt[32];		/* salt prepended to each hashed block */
+	__u8 __reserved[144];	/* must be 0's */
+	__u8 signature[];	/* optional PKCS#7 signature */
+};
+
+/*
+ * Format in which verity file measurements are signed.  This is the same as
+ * 'struct fsverity_digest', except here some magic bytes are prepended to
+ * provide some context about what is being signed in case the same key is used
+ * for non-fsverity purposes, and here the fields have fixed endianness.
+ */
+struct fsverity_signed_digest {
+	char magic[8];			/* must be "FSVerity" */
+	__le16 digest_algorithm;
+	__le16 digest_size;
+	__u8 digest[];
+};
+
+static void __printf(1, 2) __cold
+error_msg_openssl(const char *format, ...)
+{
+	va_list va;
+
+	va_start(va, format);
+	do_error_msg(format, va, 0);
+	va_end(va);
+
+	if (ERR_peek_error() == 0)
+		return;
+
+	fprintf(stderr, "OpenSSL library errors:\n");
+	ERR_print_errors_fp(stderr);
+}
+
+/* Read a PEM PKCS#8 formatted private key */
+static EVP_PKEY *read_private_key(const char *keyfile)
+{
+	BIO *bio;
+	EVP_PKEY *pkey;
+
+	bio = BIO_new_file(keyfile, "r");
+	if (!bio) {
+		error_msg_openssl("can't open '%s' for reading", keyfile);
+		return NULL;
+	}
+
+	pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
+	if (!pkey) {
+		error_msg_openssl("Failed to parse private key file '%s'.\n"
+				  "       Note: it must be in PEM PKCS#8 format.",
+				  keyfile);
+	}
+	BIO_free(bio);
+	return pkey;
+}
+
+/* Read a PEM X.509 formatted certificate */
+static X509 *read_certificate(const char *certfile)
+{
+	BIO *bio;
+	X509 *cert;
+
+	bio = BIO_new_file(certfile, "r");
+	if (!bio) {
+		error_msg_openssl("can't open '%s' for reading", certfile);
+		return NULL;
+	}
+	cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
+	if (!cert) {
+		error_msg_openssl("Failed to parse X.509 certificate file '%s'.\n"
+				  "       Note: it must be in PEM format.",
+				  certfile);
+	}
+	BIO_free(bio);
+	return cert;
+}
+
+#ifdef OPENSSL_IS_BORINGSSL
+
+static bool sign_pkcs7(const void *data_to_sign, size_t data_size,
+		       EVP_PKEY *pkey, X509 *cert, const EVP_MD *md,
+		       u8 **sig_ret, u32 *sig_size_ret)
+{
+	CBB out, outer_seq, wrapped_seq, seq, digest_algos_set, digest_algo,
+		null, content_info, issuer_and_serial, signer_infos,
+		signer_info, sign_algo, signature;
+	EVP_MD_CTX md_ctx;
+	u8 *name_der = NULL, *sig = NULL, *pkcs7_data = NULL;
+	size_t pkcs7_data_len, sig_len;
+	int name_der_len, sig_nid;
+	bool ok = false;
+
+	EVP_MD_CTX_init(&md_ctx);
+	BIGNUM *serial = ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), NULL);
+
+	if (!CBB_init(&out, 1024)) {
+		error_msg("out of memory");
+		goto out;
+	}
+
+	name_der_len = i2d_X509_NAME(X509_get_subject_name(cert), &name_der);
+	if (name_der_len < 0) {
+		error_msg_openssl("i2d_X509_NAME failed");
+		goto out;
+	}
+
+	if (!EVP_DigestSignInit(&md_ctx, NULL, md, NULL, pkey)) {
+		error_msg_openssl("EVP_DigestSignInit failed");
+		goto out;
+	}
+
+	sig_len = EVP_PKEY_size(pkey);
+	sig = xmalloc(sig_len);
+	if (!EVP_DigestSign(&md_ctx, sig, &sig_len, data_to_sign, data_size)) {
+		error_msg_openssl("EVP_DigestSign failed");
+		goto out;
+	}
+
+	sig_nid = EVP_PKEY_id(pkey);
+	/* To mirror OpenSSL behaviour, always use |NID_rsaEncryption| with RSA
+	 * rather than the combined hash+pkey NID. */
+	if (sig_nid != NID_rsaEncryption) {
+		OBJ_find_sigid_by_algs(&sig_nid, EVP_MD_type(md),
+				       EVP_PKEY_id(pkey));
+	}
+
+	// See https://tools.ietf.org/html/rfc2315#section-7
+	if (!CBB_add_asn1(&out, &outer_seq, CBS_ASN1_SEQUENCE) ||
+	    !OBJ_nid2cbb(&outer_seq, NID_pkcs7_signed) ||
+	    !CBB_add_asn1(&outer_seq, &wrapped_seq, CBS_ASN1_CONTEXT_SPECIFIC |
+			  CBS_ASN1_CONSTRUCTED | 0) ||
+	    // See https://tools.ietf.org/html/rfc2315#section-9.1
+	    !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) ||
+	    !CBB_add_asn1_uint64(&seq, 1 /* version */) ||
+	    !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) ||
+	    !CBB_add_asn1(&digest_algos_set, &digest_algo, CBS_ASN1_SEQUENCE) ||
+	    !OBJ_nid2cbb(&digest_algo, EVP_MD_type(md)) ||
+	    !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
+	    !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) ||
+	    !OBJ_nid2cbb(&content_info, NID_pkcs7_data) ||
+	    !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) ||
+	    !CBB_add_asn1(&signer_infos, &signer_info, CBS_ASN1_SEQUENCE) ||
+	    !CBB_add_asn1_uint64(&signer_info, 1 /* version */) ||
+	    !CBB_add_asn1(&signer_info, &issuer_and_serial,
+			  CBS_ASN1_SEQUENCE) ||
+	    !CBB_add_bytes(&issuer_and_serial, name_der, name_der_len) ||
+	    !BN_marshal_asn1(&issuer_and_serial, serial) ||
+	    !CBB_add_asn1(&signer_info, &digest_algo, CBS_ASN1_SEQUENCE) ||
+	    !OBJ_nid2cbb(&digest_algo, EVP_MD_type(md)) ||
+	    !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
+	    !CBB_add_asn1(&signer_info, &sign_algo, CBS_ASN1_SEQUENCE) ||
+	    !OBJ_nid2cbb(&sign_algo, sig_nid) ||
+	    !CBB_add_asn1(&sign_algo, &null, CBS_ASN1_NULL) ||
+	    !CBB_add_asn1(&signer_info, &signature, CBS_ASN1_OCTETSTRING) ||
+	    !CBB_add_bytes(&signature, sig, sig_len) ||
+	    !CBB_finish(&out, &pkcs7_data, &pkcs7_data_len)) {
+		error_msg_openssl("failed to construct PKCS#7 data");
+		goto out;
+	}
+
+	*sig_ret = xmemdup(pkcs7_data, pkcs7_data_len);
+	*sig_size_ret = pkcs7_data_len;
+	ok = true;
+out:
+	BN_free(serial);
+	EVP_MD_CTX_cleanup(&md_ctx);
+	CBB_cleanup(&out);
+	free(sig);
+	OPENSSL_free(name_der);
+	OPENSSL_free(pkcs7_data);
+	return ok;
+}
+
+#else /* OPENSSL_IS_BORINGSSL */
+
+static BIO *new_mem_buf(const void *buf, size_t size)
+{
+	BIO *bio;
+
+	ASSERT(size <= INT_MAX);
+	/*
+	 * Prior to OpenSSL 1.1.0, BIO_new_mem_buf() took a non-const pointer,
+	 * despite still marking the resulting bio as read-only.  So cast away
+	 * the const to avoid a compiler warning with older OpenSSL versions.
+	 */
+	bio = BIO_new_mem_buf((void *)buf, size);
+	if (!bio)
+		error_msg_openssl("out of memory");
+	return bio;
+}
+
+static bool sign_pkcs7(const void *data_to_sign, size_t data_size,
+		       EVP_PKEY *pkey, X509 *cert, const EVP_MD *md,
+		       u8 **sig_ret, u32 *sig_size_ret)
+{
+	/*
+	 * PKCS#7 signing flags:
+	 *
+	 * - PKCS7_BINARY	signing binary data, so skip MIME translation
+	 *
+	 * - PKCS7_DETACHED	omit the signed data (include signature only)
+	 *
+	 * - PKCS7_NOATTR	omit extra authenticated attributes, such as
+	 *			SMIMECapabilities
+	 *
+	 * - PKCS7_NOCERTS	omit the signer's certificate
+	 *
+	 * - PKCS7_PARTIAL	PKCS7_sign() creates a handle only, then
+	 *			PKCS7_sign_add_signer() can add a signer later.
+	 *			This is necessary to change the message digest
+	 *			algorithm from the default of SHA-1.  Requires
+	 *			OpenSSL 1.0.0 or later.
+	 */
+	int pkcs7_flags = PKCS7_BINARY | PKCS7_DETACHED | PKCS7_NOATTR |
+			  PKCS7_NOCERTS | PKCS7_PARTIAL;
+	u8 *sig;
+	u32 sig_size;
+	BIO *bio = NULL;
+	PKCS7 *p7 = NULL;
+	bool ok = false;
+
+	bio = new_mem_buf(data_to_sign, data_size);
+	if (!bio)
+		goto out;
+
+	p7 = PKCS7_sign(NULL, NULL, NULL, bio, pkcs7_flags);
+	if (!p7) {
+		error_msg_openssl("failed to initialize PKCS#7 signature object");
+		goto out;
+	}
+
+	if (!PKCS7_sign_add_signer(p7, cert, pkey, md, pkcs7_flags)) {
+		error_msg_openssl("failed to add signer to PKCS#7 signature object");
+		goto out;
+	}
+
+	if (PKCS7_final(p7, bio, pkcs7_flags) != 1) {
+		error_msg_openssl("failed to finalize PKCS#7 signature");
+		goto out;
+	}
+
+	BIO_free(bio);
+	bio = BIO_new(BIO_s_mem());
+	if (!bio) {
+		error_msg_openssl("out of memory");
+		goto out;
+	}
+
+	if (i2d_PKCS7_bio(bio, p7) != 1) {
+		error_msg_openssl("failed to DER-encode PKCS#7 signature object");
+		goto out;
+	}
+
+	sig_size = BIO_get_mem_data(bio, &sig);
+	*sig_ret = xmemdup(sig, sig_size);
+	*sig_size_ret = sig_size;
+	ok = true;
+out:
+	PKCS7_free(p7);
+	BIO_free(bio);
+	return ok;
+}
+
+#endif /* !OPENSSL_IS_BORINGSSL */
+
+/*
+ * Sign the specified @data_to_sign of length @data_size bytes using the private
+ * key in @keyfile, the certificate in @certfile, and the hash algorithm
+ * @hash_alg.  Returns the DER-formatted PKCS#7 signature in @sig_ret and
+ * @sig_size_ret.
+ */
+static bool sign_data(const void *data_to_sign, size_t data_size,
+		      const char *keyfile, const char *certfile,
+		      const struct fsverity_hash_alg *hash_alg,
+		      u8 **sig_ret, u32 *sig_size_ret)
+{
+	EVP_PKEY *pkey = NULL;
+	X509 *cert = NULL;
+	const EVP_MD *md;
+	bool ok = false;
+
+	pkey = read_private_key(keyfile);
+	if (!pkey)
+		goto out;
+
+	cert = read_certificate(certfile);
+	if (!cert)
+		goto out;
+
+	OpenSSL_add_all_digests();
+	md = EVP_get_digestbyname(hash_alg->name);
+	if (!md) {
+		fprintf(stderr,
+			"Warning: '%s' algorithm not found in OpenSSL library.\n"
+			"         Falling back to SHA-256 signature.\n",
+			hash_alg->name);
+		md = EVP_sha256();
+	}
+
+	ok = sign_pkcs7(data_to_sign, data_size, pkey, cert, md,
+			sig_ret, sig_size_ret);
+out:
+	EVP_PKEY_free(pkey);
+	X509_free(cert);
+	return ok;
+}
+
+static bool write_signature(const char *filename, const u8 *sig, u32 sig_size)
+{
+	struct filedes file;
+	bool ok;
+
+	if (!open_file(&file, filename, O_WRONLY|O_CREAT|O_TRUNC, 0644))
+		return false;
+	ok = full_write(&file, sig, sig_size);
+	ok &= filedes_close(&file);
+	return ok;
+}
+
+#define FS_VERITY_MAX_LEVELS	64
+
+struct block_buffer {
+	u32 filled;
+	u8 *data;
+};
+
+/*
+ * Hash a block, writing the result to the next level's pending block buffer.
+ * Returns true if the next level's block became full, else false.
+ */
+static bool hash_one_block(struct hash_ctx *hash, struct block_buffer *cur,
+			   u32 block_size, const u8 *salt, u32 salt_size)
+{
+	struct block_buffer *next = cur + 1;
+
+	/* Zero-pad the block if it's shorter than block_size. */
+	memset(&cur->data[cur->filled], 0, block_size - cur->filled);
+
+	hash_init(hash);
+	hash_update(hash, salt, salt_size);
+	hash_update(hash, cur->data, block_size);
+	hash_final(hash, &next->data[next->filled]);
+
+	next->filled += hash->alg->digest_size;
+	cur->filled = 0;
+
+	return next->filled + hash->alg->digest_size > block_size;
+}
+
+/*
+ * Compute the file's Merkle tree root hash using the given hash algorithm,
+ * block size, and salt.
+ */
+static bool compute_root_hash(struct filedes *file, u64 file_size,
+			      struct hash_ctx *hash, u32 block_size,
+			      const u8 *salt, u32 salt_size, u8 *root_hash)
+{
+	const u32 hashes_per_block = block_size / hash->alg->digest_size;
+	const u32 padded_salt_size = roundup(salt_size, hash->alg->block_size);
+	u8 *padded_salt = xzalloc(padded_salt_size);
+	u64 blocks;
+	int num_levels = 0;
+	int level;
+	struct block_buffer _buffers[1 + FS_VERITY_MAX_LEVELS + 1] = {};
+	struct block_buffer *buffers = &_buffers[1];
+	u64 offset;
+	bool ok = false;
+
+	if (salt_size != 0)
+		memcpy(padded_salt, salt, salt_size);
+
+	/* Compute number of levels */
+	for (blocks = DIV_ROUND_UP(file_size, block_size); blocks > 1;
+	     blocks = DIV_ROUND_UP(blocks, hashes_per_block)) {
+		ASSERT(num_levels < FS_VERITY_MAX_LEVELS);
+		num_levels++;
+	}
+
+	/*
+	 * Allocate the block buffers.  Buffer "-1" is for data blocks.
+	 * Buffers 0 <= level < num_levels are for the actual tree levels.
+	 * Buffer 'num_levels' is for the root hash.
+	 */
+	for (level = -1; level < num_levels; level++)
+		buffers[level].data = xmalloc(block_size);
+	buffers[num_levels].data = root_hash;
+
+	/* Hash each data block, also hashing the tree blocks as they fill up */
+	for (offset = 0; offset < file_size; offset += block_size) {
+		buffers[-1].filled = min(block_size, file_size - offset);
+
+		if (!full_read(file, buffers[-1].data, buffers[-1].filled))
+			goto out;
+
+		level = -1;
+		while (hash_one_block(hash, &buffers[level], block_size,
+				      padded_salt, padded_salt_size)) {
+			level++;
+			ASSERT(level < num_levels);
+		}
+	}
+	/* Finish all nonempty pending tree blocks */
+	for (level = 0; level < num_levels; level++) {
+		if (buffers[level].filled != 0)
+			hash_one_block(hash, &buffers[level], block_size,
+				       padded_salt, padded_salt_size);
+	}
+
+	/* Root hash was filled by the last call to hash_one_block() */
+	ASSERT(buffers[num_levels].filled == hash->alg->digest_size);
+	ok = true;
+out:
+	for (level = -1; level < num_levels; level++)
+		free(buffers[level].data);
+	free(padded_salt);
+	return ok;
+}
+
+/*
+ * Compute the fs-verity measurement of the given file.
+ *
+ * The fs-verity measurement is the hash of the fsverity_descriptor, which
+ * contains the Merkle tree properties including the root hash.
+ */
+static bool compute_file_measurement(const char *filename,
+				     const struct fsverity_hash_alg *hash_alg,
+				     u32 block_size, const u8 *salt,
+				     u32 salt_size, u8 *measurement)
+{
+	struct filedes file = { .fd = -1 };
+	struct hash_ctx *hash = hash_create(hash_alg);
+	u64 file_size;
+	struct fsverity_descriptor desc;
+	bool ok = false;
+
+	if (!open_file(&file, filename, O_RDONLY, 0))
+		goto out;
+
+	if (!get_file_size(&file, &file_size))
+		goto out;
+
+	memset(&desc, 0, sizeof(desc));
+	desc.version = 1;
+	desc.hash_algorithm = hash_alg - fsverity_hash_algs;
+
+	ASSERT(is_power_of_2(block_size));
+	desc.log_blocksize = ilog2(block_size);
+
+	if (salt_size != 0) {
+		if (salt_size > sizeof(desc.salt)) {
+			error_msg("Salt too long (got %u bytes; max is %zu bytes)",
+				  salt_size, sizeof(desc.salt));
+			goto out;
+		}
+		memcpy(desc.salt, salt, salt_size);
+		desc.salt_size = salt_size;
+	}
+
+	desc.data_size = cpu_to_le64(file_size);
+
+	/* Root hash of empty file is all 0's */
+	if (file_size != 0 &&
+	    !compute_root_hash(&file, file_size, hash, block_size, salt,
+			       salt_size, desc.root_hash))
+		goto out;
+
+	hash_full(hash, &desc, sizeof(desc), measurement);
+	ok = true;
+out:
+	filedes_close(&file);
+	hash_free(hash);
+	return ok;
+}
+
+enum {
+	OPT_HASH_ALG,
+	OPT_BLOCK_SIZE,
+	OPT_SALT,
+	OPT_KEY,
+	OPT_CERT,
+};
+
+static const struct option longopts[] = {
+	{"hash-alg",	required_argument, NULL, OPT_HASH_ALG},
+	{"block-size",	required_argument, NULL, OPT_BLOCK_SIZE},
+	{"salt",	required_argument, NULL, OPT_SALT},
+	{"key",		required_argument, NULL, OPT_KEY},
+	{"cert",	required_argument, NULL, OPT_CERT},
+	{NULL, 0, NULL, 0}
+};
+
+/* Sign a file for fs-verity by computing its measurement, then signing it. */
+int fsverity_cmd_sign(const struct fsverity_command *cmd,
+		      int argc, char *argv[])
+{
+	const struct fsverity_hash_alg *hash_alg = NULL;
+	u32 block_size = 0;
+	u8 *salt = NULL;
+	u32 salt_size = 0;
+	const char *keyfile = NULL;
+	const char *certfile = NULL;
+	struct fsverity_signed_digest *digest = NULL;
+	char digest_hex[FS_VERITY_MAX_DIGEST_SIZE * 2 + 1];
+	u8 *sig = NULL;
+	u32 sig_size;
+	int status;
+	int c;
+
+	while ((c = getopt_long(argc, argv, "", longopts, NULL)) != -1) {
+		switch (c) {
+		case OPT_HASH_ALG:
+			if (hash_alg != NULL) {
+				error_msg("--hash-alg can only be specified once");
+				goto out_usage;
+			}
+			hash_alg = find_hash_alg_by_name(optarg);
+			if (hash_alg == NULL)
+				goto out_usage;
+			break;
+		case OPT_BLOCK_SIZE:
+			if (!parse_block_size_option(optarg, &block_size))
+				goto out_usage;
+			break;
+		case OPT_SALT:
+			if (!parse_salt_option(optarg, &salt, &salt_size))
+				goto out_usage;
+			break;
+		case OPT_KEY:
+			if (keyfile != NULL) {
+				error_msg("--key can only be specified once");
+				goto out_usage;
+			}
+			keyfile = optarg;
+			break;
+		case OPT_CERT:
+			if (certfile != NULL) {
+				error_msg("--cert can only be specified once");
+				goto out_usage;
+			}
+			certfile = optarg;
+			break;
+		default:
+			goto out_usage;
+		}
+	}
+
+	argv += optind;
+	argc -= optind;
+
+	if (argc != 2)
+		goto out_usage;
+
+	if (hash_alg == NULL)
+		hash_alg = &fsverity_hash_algs[FS_VERITY_HASH_ALG_DEFAULT];
+
+	if (block_size == 0)
+		block_size = get_default_block_size();
+
+	if (keyfile == NULL) {
+		error_msg("Missing --key argument");
+		goto out_usage;
+	}
+	if (certfile == NULL)
+		certfile = keyfile;
+
+	digest = xzalloc(sizeof(*digest) + hash_alg->digest_size);
+	memcpy(digest->magic, "FSVerity", 8);
+	digest->digest_algorithm = cpu_to_le16(hash_alg - fsverity_hash_algs);
+	digest->digest_size = cpu_to_le16(hash_alg->digest_size);
+
+	if (!compute_file_measurement(argv[0], hash_alg, block_size,
+				      salt, salt_size, digest->digest))
+		goto out_err;
+
+	if (!sign_data(digest, sizeof(*digest) + hash_alg->digest_size,
+		       keyfile, certfile, hash_alg, &sig, &sig_size))
+		goto out_err;
+
+	if (!write_signature(argv[1], sig, sig_size))
+		goto out_err;
+
+	bin2hex(digest->digest, hash_alg->digest_size, digest_hex);
+	printf("Signed file '%s' (%s:%s)\n", argv[0], hash_alg->name,
+	       digest_hex);
+	status = 0;
+out:
+	free(salt);
+	free(digest);
+	free(sig);
+	return status;
+
+out_err:
+	status = 1;
+	goto out;
+
+out_usage:
+	usage(cmd, stderr);
+	status = 2;
+	goto out;
+}
diff --git a/commands.h b/commands.h
index cc87368..98f9745 100644
--- a/commands.h
+++ b/commands.h
@@ -12,9 +12,13 @@
 
 int fsverity_cmd_enable(const struct fsverity_command *cmd,
 			int argc, char *argv[]);
-int fsverity_cmd_setup(const struct fsverity_command *cmd,
-		       int argc, char *argv[]);
 int fsverity_cmd_measure(const struct fsverity_command *cmd,
 			 int argc, char *argv[]);
+int fsverity_cmd_sign(const struct fsverity_command *cmd,
+		      int argc, char *argv[]);
+
+bool parse_block_size_option(const char *arg, u32 *size_ptr);
+u32 get_default_block_size(void);
+bool parse_salt_option(const char *arg, u8 **salt_ptr, u32 *salt_size_ptr);
 
 #endif /* COMMANDS_H */
diff --git a/crc32c_table.h b/crc32c_table.h
deleted file mode 100644
index 822c0a6..0000000
--- a/crc32c_table.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * crc32c_table.h - data table to accelerate CRC-32C computation
- *
- * This file was automatically generated by scripts/gen_crc32c_table.c
- */
-
-#include <stdint.h>
-
-static const uint32_t crc32c_table[] = {
-	0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4,
-	0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb,
-	0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b,
-	0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24,
-	0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b,
-	0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384,
-	0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54,
-	0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b,
-	0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a,
-	0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35,
-	0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5,
-	0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa,
-	0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45,
-	0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a,
-	0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a,
-	0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595,
-	0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48,
-	0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957,
-	0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687,
-	0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198,
-	0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927,
-	0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38,
-	0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8,
-	0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7,
-	0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096,
-	0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789,
-	0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859,
-	0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46,
-	0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9,
-	0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6,
-	0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36,
-	0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829,
-	0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c,
-	0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93,
-	0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043,
-	0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c,
-	0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3,
-	0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc,
-	0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c,
-	0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033,
-	0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652,
-	0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d,
-	0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d,
-	0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982,
-	0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d,
-	0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622,
-	0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2,
-	0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed,
-	0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530,
-	0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f,
-	0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff,
-	0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0,
-	0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f,
-	0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540,
-	0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90,
-	0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f,
-	0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee,
-	0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1,
-	0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321,
-	0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e,
-	0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81,
-	0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e,
-	0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e,
-	0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351,
-};
diff --git a/debian/changelog b/debian/changelog
deleted file mode 100644
index a2e894d..0000000
--- a/debian/changelog
+++ /dev/null
@@ -1,5 +0,0 @@
-fsverity-utils (0.1-1) experimental; urgency=low
-
-  * Experimental: debian package for xfstests test appliances
-
- -- Eric Biggers <ebiggers@google.com>  Mon, 02 Apr 2018 10:18:21 -0700
diff --git a/debian/compat b/debian/compat
deleted file mode 100644
index f599e28..0000000
--- a/debian/compat
+++ /dev/null
@@ -1 +0,0 @@
-10
diff --git a/debian/control b/debian/control
deleted file mode 100644
index aaa4ac3..0000000
--- a/debian/control
+++ /dev/null
@@ -1,14 +0,0 @@
-Source: fsverity-utils
-Priority: optional
-Maintainer: Eric Biggers <ebiggers@google.com>
-Build-Depends: debhelper (>= 10), libssl-dev (>= 1.0.0)
-Standards-Version: 4.0.0
-Vcs-Git: git://git.kernel.org/pub/scm/linux/kernel/git/mhalcrow/fsverity
-
-Package: fsverity-utils
-Section: utils
-Architecture: any
-Depends: ${shlibs:Depends}, ${misc:Depends}
-Description: fs-verity userspace utility.  This program allows you to set up
- read-only, integrity and/or authenticity-protected files when supported by the
- underlying filesystem.
diff --git a/debian/copyright b/debian/copyright
deleted file mode 100644
index a728656..0000000
--- a/debian/copyright
+++ /dev/null
@@ -1,7 +0,0 @@
-Format: http://dep.debian.net/deps/dep5
-Upstream-Name: fsverity
-Source: git://git.kernel.org/pub/scm/linux/kernel/git/mhalcrow/fsverity
-
-Files: *
-Copyright: 2018 Google LLC
-License: GPL-2+
diff --git a/debian/rules b/debian/rules
deleted file mode 100755
index 9b694a1..0000000
--- a/debian/rules
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/usr/bin/make -f
-
-export DH_VERBOSE=1
-
-include /usr/share/dpkg/default.mk
-
-%:
-	dh $@
diff --git a/elide_patch.c b/elide_patch.c
deleted file mode 100644
index 3eed416..0000000
--- a/elide_patch.c
+++ /dev/null
@@ -1,307 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0+
-/*
- * Elide and patch handling for 'fsverity setup'
- *
- * Copyright (C) 2018 Google LLC
- *
- * Written by Eric Biggers.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "fsverity_uapi.h"
-#include "fsveritysetup.h"
-
-/* An elision or a patch */
-struct fsverity_elide_patch {
-	u64 offset;	/* byte offset within the original data */
-	u64 length;	/* length in bytes */
-	bool patch;	/* false if elision, true if patch */
-	u8 data[];	/* replacement data (if patch=true) */
-};
-
-/* Maximum supported patch size, in bytes */
-#define FS_VERITY_MAX_PATCH_SIZE	255
-
-/* Parse an --elide=OFFSET,LENGTH option */
-static struct fsverity_elide_patch *parse_elide_option(const char *optarg)
-{
-	struct fsverity_elide_patch *ext = NULL;
-	char *sep, *end;
-	unsigned long long offset;
-	unsigned long long length;
-
-	sep = strchr(optarg, ',');
-	if (!sep || sep == optarg)
-		goto invalid;
-	errno = 0;
-	*sep = '\0';
-	offset = strtoull(optarg, &end, 10);
-	*sep = ',';
-	if (errno || end != sep)
-		goto invalid;
-	length = strtoull(sep + 1, &end, 10);
-	if (errno || *end)
-		goto invalid;
-	if (length <= 0 || length > UINT64_MAX - offset) {
-		error_msg("Invalid length in '--elide=%s'", optarg);
-		return NULL;
-	}
-	ext = xzalloc(sizeof(*ext));
-	ext->offset = offset;
-	ext->length = length;
-	ext->patch = false;
-	return ext;
-
-invalid:
-	error_msg("Invalid --elide option: '%s'.  Must be formatted as OFFSET,LENGTH",
-		  optarg);
-	return NULL;
-}
-
-/* Parse a --patch=OFFSET,PATCHFILE option */
-static struct fsverity_elide_patch *parse_patch_option(const char *optarg)
-{
-	struct fsverity_elide_patch *ext = NULL;
-	struct filedes patchfile = { .fd = -1 };
-	char *sep, *end;
-	unsigned long long offset;
-	u64 length;
-
-	sep = strchr(optarg, ',');
-	if (!sep || sep == optarg)
-		goto invalid;
-	errno = 0;
-	*sep = '\0';
-	offset = strtoull(optarg, &end, 10);
-	*sep = ',';
-	if (errno || end != sep)
-		goto invalid;
-	if (!open_file(&patchfile, sep + 1, O_RDONLY, 0))
-		goto out;
-	if (!get_file_size(&patchfile, &length))
-		goto out;
-	if (length <= 0) {
-		error_msg("patch file '%s' is empty", patchfile.name);
-		goto out;
-	}
-	if (length > FS_VERITY_MAX_PATCH_SIZE) {
-		error_msg("Patch file '%s' is too long.  Max patch size is %d bytes.",
-			  patchfile.name, FS_VERITY_MAX_PATCH_SIZE);
-		goto out;
-	}
-	ext = xzalloc(sizeof(*ext) + length);
-	ext->offset = offset;
-	ext->length = length;
-	ext->patch = true;
-	if (!full_read(&patchfile, ext->data, length)) {
-		free(ext);
-		ext = NULL;
-	}
-out:
-	filedes_close(&patchfile);
-	return ext;
-
-invalid:
-	error_msg("Invalid --patch option: '%s'.  Must be formatted as OFFSET,PATCHFILE",
-		  optarg);
-	goto out;
-}
-
-/* Sort by increasing offset */
-static int cmp_elide_patch_exts(const void *_p1, const void *_p2)
-{
-	const struct fsverity_elide_patch *ext1, *ext2;
-
-	ext1 = *(const struct fsverity_elide_patch **)_p1;
-	ext2 = *(const struct fsverity_elide_patch **)_p2;
-
-	if (ext1->offset > ext2->offset)
-		return 1;
-	if (ext1->offset < ext2->offset)
-		return -1;
-	return 0;
-}
-
-/*
- * Given the lists of --elide and --patch options, validate and load the
- * elisions and patches into @params.
- */
-bool load_elisions_and_patches(const struct string_list *elide_opts,
-			       const struct string_list *patch_opts,
-			       struct fsveritysetup_params *params)
-{
-	const size_t num_exts = elide_opts->length + patch_opts->length;
-	struct fsverity_elide_patch **exts;
-	size_t i, j;
-
-	if (num_exts == 0)	/* Normal case: no elisions or patches */
-		return true;
-	params->num_elisions_and_patches = num_exts;
-	exts = xzalloc(num_exts * sizeof(exts[0]));
-	params->elisions_and_patches = exts;
-	j = 0;
-
-	/* Parse the --elide options */
-	for (i = 0; i < elide_opts->length; i++) {
-		exts[j] = parse_elide_option(elide_opts->strings[i]);
-		if (!exts[j++])
-			return false;
-	}
-
-	/* Parse the --patch options */
-	for (i = 0; i < patch_opts->length; i++) {
-		exts[j] = parse_patch_option(patch_opts->strings[i]);
-		if (!exts[j++])
-			return false;
-	}
-
-	/* Sort the elisions and patches by increasing offset */
-	qsort(exts, num_exts, sizeof(exts[0]), cmp_elide_patch_exts);
-
-	/* Verify that no elisions or patches overlap */
-	for (j = 1; j < num_exts; j++) {
-		if (exts[j]->offset <
-		    exts[j - 1]->offset + exts[j - 1]->length) {
-			error_msg("%s at [%"PRIu64", %"PRIu64") overlaps "
-				  "%s at [%"PRIu64", %"PRIu64")",
-				  exts[j - 1]->patch ? "Patch" : "Elision",
-				  exts[j - 1]->offset,
-				  exts[j - 1]->offset + exts[j - 1]->length,
-				  exts[j]->patch ? "patch" : "elision",
-				  exts[j]->offset,
-				  exts[j]->offset + exts[j]->length);
-			return false;
-		}
-	}
-	return true;
-}
-
-void free_elisions_and_patches(struct fsveritysetup_params *params)
-{
-	size_t i;
-
-	for (i = 0; i < params->num_elisions_and_patches; i++)
-		free(params->elisions_and_patches[i]);
-	free(params->elisions_and_patches);
-}
-
-/*
- * Given the original file @in of length @in_length bytes, create a temporary
- * file @out_ret and write to it the data with the elisions and patches applied,
- * with the end zero-padded to the next block boundary.  Returns in
- * @out_length_ret the length of the elided/patched file in bytes.
- */
-bool apply_elisions_and_patches(const struct fsveritysetup_params *params,
-				struct filedes *in, u64 in_length,
-				struct filedes *out_ret, u64 *out_length_ret)
-{
-	struct fsverity_elide_patch **exts = params->elisions_and_patches;
-	struct filedes *out = out_ret;
-	size_t i;
-
-	for (i = 0; i < params->num_elisions_and_patches; i++) {
-		if (exts[i]->offset + exts[i]->length > in_length) {
-			error_msg("%s at [%"PRIu64", %"PRIu64") extends beyond end of input file",
-				  exts[i]->patch ? "Patch" : "Elision",
-				  exts[i]->offset,
-				  exts[i]->offset + exts[i]->length);
-			return false;
-		}
-	}
-
-	if (!filedes_seek(in, 0, SEEK_SET))
-		return false;
-
-	if (!open_tempfile(out))
-		return false;
-
-	for (i = 0; i < params->num_elisions_and_patches; i++) {
-		printf("Applying %s: offset=%"PRIu64", length=%"PRIu64"\n",
-		       exts[i]->patch ? "patch" : "elision",
-		       exts[i]->offset, exts[i]->length);
-
-		if (!copy_file_data(in, out, exts[i]->offset - in->pos))
-			return false;
-
-		if (exts[i]->patch &&
-		    !full_write(out, exts[i]->data, exts[i]->length))
-			return false;
-
-		if (!filedes_seek(in, exts[i]->length, SEEK_CUR))
-			return false;
-	}
-	if (!copy_file_data(in, out, in_length - in->pos))
-		return false;
-	if (!write_zeroes(out, ALIGN(out->pos, params->blocksize) - out->pos))
-		return false;
-	*out_length_ret = out->pos;
-	return true;
-}
-
-/* Calculate the size the elisions and patches will take up when serialized */
-size_t total_elide_patch_ext_length(const struct fsveritysetup_params *params)
-{
-	size_t total = 0;
-	size_t i;
-
-	for (i = 0; i < params->num_elisions_and_patches; i++) {
-		const struct fsverity_elide_patch *ext =
-			params->elisions_and_patches[i];
-		size_t inner_len;
-
-		if (ext->patch) {
-			inner_len = sizeof(struct fsverity_extension_patch) +
-				    ext->length;
-		} else {
-			inner_len = sizeof(struct fsverity_extension_elide);
-		}
-		total += FSVERITY_EXTLEN(inner_len);
-	}
-	return total;
-}
-
-/*
- * Append the elide and patch extensions (if any) to the given buffer.
- * The buffer must have enough space; call total_elide_patch_ext_length() first.
- */
-void append_elide_patch_exts(void **buf_p,
-			     const struct fsveritysetup_params *params)
-{
-	void *buf = *buf_p;
-	size_t i;
-	union {
-		struct {
-			struct fsverity_extension_patch hdr;
-			u8 data[FS_VERITY_MAX_PATCH_SIZE];
-		} patch;
-		struct fsverity_extension_elide elide;
-	} u;
-
-	for (i = 0; i < params->num_elisions_and_patches; i++) {
-		const struct fsverity_elide_patch *ext =
-			params->elisions_and_patches[i];
-		int type;
-		size_t extlen;
-
-		if (ext->patch) {
-			type = FS_VERITY_EXT_PATCH;
-			u.patch.hdr.offset = cpu_to_le64(ext->offset);
-			ASSERT(ext->length <= sizeof(u.patch.data));
-			memcpy(u.patch.data, ext->data, ext->length);
-			extlen = sizeof(u.patch.hdr) + ext->length;
-		} else {
-			type = FS_VERITY_EXT_ELIDE;
-			u.elide.offset = cpu_to_le64(ext->offset),
-			u.elide.length = cpu_to_le64(ext->length);
-			extlen = sizeof(u.elide);
-		}
-		fsverity_append_extension(&buf, type, &u, extlen);
-	}
-
-	*buf_p = buf;
-}
diff --git a/fsverity.c b/fsverity.c
index a463c7f..6fabfa4 100644
--- a/fsverity.c
+++ b/fsverity.c
@@ -7,8 +7,10 @@
  * Written by Eric Biggers.
  */
 
+#include <limits.h>
 #include <stdlib.h>
 #include <string.h>
+#include <unistd.h>
 
 #include "commands.h"
 #include "hash_algs.h"
@@ -22,26 +24,26 @@
 	{
 		.name = "enable",
 		.func = fsverity_cmd_enable,
-		.short_desc =
-"Enable fs-verity on a file with verity metadata",
+		.short_desc = "Enable fs-verity on a file",
 		.usage_str =
 "    fsverity enable FILE\n"
+"               [--hash-alg=HASH_ALG] [--block-size=BLOCK_SIZE] [--salt=SALT]\n"
+"               [--signature=SIGFILE]\n"
 	}, {
 		.name = "measure",
 		.func = fsverity_cmd_measure,
 		.short_desc =
-"Display the measurement of the given fs-verity file(s)",
+"Display the measurement of the given verity file(s)",
 		.usage_str =
 "    fsverity measure FILE...\n"
 	}, {
-		.name = "setup",
-		.func = fsverity_cmd_setup,
-		.short_desc = "Create the verity metadata for a file",
+		.name = "sign",
+		.func = fsverity_cmd_sign,
+		.short_desc = "Sign a file for fs-verity",
 		.usage_str =
-"    fsverity setup INFILE [OUTFILE]\n"
-"                   [--hash=HASH_ALG] [--salt=SALT] [--signing-key=KEYFILE]\n"
-"                   [--signing-cert=CERTFILE] [--signature=SIGFILE]\n"
-"                   [--patch=OFFSET,PATCHFILE] [--elide=OFFSET,LENGTH]\n"
+"    fsverity sign FILE OUT_SIGFILE --key=KEYFILE\n"
+"               [--hash-alg=HASH_ALG] [--block-size=BLOCK_SIZE] [--salt=SALT]\n"
+"               [--cert=CERTFILE]\n"
 	}
 };
 
@@ -125,6 +127,52 @@
 	return NULL;
 }
 
+bool parse_block_size_option(const char *arg, u32 *size_ptr)
+{
+	char *end;
+	unsigned long n = strtoul(arg, &end, 10);
+
+	if (*size_ptr != 0) {
+		error_msg("--block-size can only be specified once");
+		return false;
+	}
+
+	if (n <= 0 || n >= INT_MAX || !is_power_of_2(n) || *end != '\0') {
+		error_msg("Invalid block size: %s.  Must be power of 2", arg);
+		return false;
+	}
+	*size_ptr = n;
+	return true;
+}
+
+bool parse_salt_option(const char *arg, u8 **salt_ptr, u32 *salt_size_ptr)
+{
+	if (*salt_ptr != NULL) {
+		error_msg("--salt can only be specified once");
+		return false;
+	}
+	*salt_size_ptr = strlen(arg) / 2;
+	*salt_ptr = xmalloc(*salt_size_ptr);
+	if (!hex2bin(arg, *salt_ptr, *salt_size_ptr)) {
+		error_msg("salt is not a valid hex string");
+		return false;
+	}
+	return true;
+}
+
+u32 get_default_block_size(void)
+{
+	long n = sysconf(_SC_PAGESIZE);
+
+	if (n <= 0 || n >= INT_MAX || !is_power_of_2(n)) {
+		fprintf(stderr,
+			"Warning: invalid _SC_PAGESIZE (%ld).  Assuming 4K blocks.\n",
+			n);
+		return 4096;
+	}
+	return n;
+}
+
 int main(int argc, char *argv[])
 {
 	const struct fsverity_command *cmd;
diff --git a/fsverity_uapi.h b/fsverity_uapi.h
index 00c64f9..da0daf6 100644
--- a/fsverity_uapi.h
+++ b/fsverity_uapi.h
@@ -1,17 +1,32 @@
 /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
 /*
- * fs-verity (file-based verity) support
+ * fs-verity user API
  *
- * Copyright (C) 2018 Google LLC
+ * These ioctls can be used on filesystems that support fs-verity.  See the
+ * "User API" section of Documentation/filesystems/fsverity.rst.
+ *
+ * Copyright 2019 Google LLC
  */
 #ifndef _UAPI_LINUX_FSVERITY_H
 #define _UAPI_LINUX_FSVERITY_H
 
-#include <linux/limits.h>
 #include <linux/ioctl.h>
 #include <linux/types.h>
 
-/* ========== Ioctls ========== */
+#define FS_VERITY_HASH_ALG_SHA256	1
+#define FS_VERITY_HASH_ALG_SHA512	2
+
+struct fsverity_enable_arg {
+	__u32 version;
+	__u32 hash_algorithm;
+	__u32 block_size;
+	__u32 salt_size;
+	__u64 salt_ptr;
+	__u32 sig_size;
+	__u32 __reserved1;
+	__u64 sig_ptr;
+	__u64 __reserved2[11];
+};
 
 struct fsverity_digest {
 	__u16 digest_algorithm;
@@ -19,94 +34,7 @@
 	__u8 digest[];
 };
 
-#define FS_IOC_ENABLE_VERITY	_IO('f', 133)
+#define FS_IOC_ENABLE_VERITY	_IOW('f', 133, struct fsverity_enable_arg)
 #define FS_IOC_MEASURE_VERITY	_IOWR('f', 134, struct fsverity_digest)
 
-/* ========== On-disk format ========== */
-
-#define FS_VERITY_MAGIC		"FSVerity"
-
-/* Supported hash algorithms */
-#define FS_VERITY_ALG_SHA256	1
-#define FS_VERITY_ALG_SHA512	2
-#define FS_VERITY_ALG_CRC32C	3	/* for integrity only */
-
-/* Metadata stored near the end of fs-verity files, after the Merkle tree */
-/* This structure is 64 bytes long */
-struct fsverity_descriptor {
-	__u8 magic[8];		/* must be FS_VERITY_MAGIC */
-	__u8 major_version;	/* must be 1 */
-	__u8 minor_version;	/* must be 0 */
-	__u8 log_data_blocksize;/* log2(data-bytes-per-hash), e.g. 12 for 4KB */
-	__u8 log_tree_blocksize;/* log2(tree-bytes-per-hash), e.g. 12 for 4KB */
-	__le16 data_algorithm;	/* hash algorithm for data blocks */
-	__le16 tree_algorithm;	/* hash algorithm for tree blocks */
-	__le32 flags;		/* flags */
-	__le32 reserved1;	/* must be 0 */
-	__le64 orig_file_size;	/* size of the original, unpadded data */
-	__le16 auth_ext_count;	/* number of authenticated extensions */
-	__u8 reserved2[30];	/* must be 0 */
-};
-/* followed by list of 'auth_ext_count' authenticated extensions */
-/*
- * then followed by '__le16 unauth_ext_count' padded to next 8-byte boundary,
- * then a list of 'unauth_ext_count' (may be 0) unauthenticated extensions
- */
-
-/* Extension types */
-#define FS_VERITY_EXT_ROOT_HASH		1
-#define FS_VERITY_EXT_SALT		2
-#define FS_VERITY_EXT_PKCS7_SIGNATURE	3
-#define FS_VERITY_EXT_ELIDE		4
-#define FS_VERITY_EXT_PATCH		5
-
-/* Header of each extension (variable-length metadata item) */
-struct fsverity_extension {
-	/*
-	 * Length in bytes, including this header but excluding padding to next
-	 * 8-byte boundary that is applied when advancing to the next extension.
-	 */
-	__le32 length;
-	__le16 type;		/* Type of this extension (see codes above) */
-	__le16 reserved;	/* Reserved, must be 0 */
-};
-/* followed by the payload of 'length - 8' bytes */
-
-/* Extension payload formats */
-
-/*
- * FS_VERITY_EXT_ROOT_HASH payload is just a byte array, with size equal to the
- * digest size of the hash algorithm given in the fsverity_descriptor
- */
-
-/* FS_VERITY_EXT_SALT payload is just a byte array, any size */
-
-/*
- * FS_VERITY_EXT_PKCS7_SIGNATURE payload is a DER-encoded PKCS#7 message
- * containing the signed file measurement in the following format:
- */
-struct fsverity_digest_disk {
-	__le16 digest_algorithm;
-	__le16 digest_size;
-	__u8 digest[];
-};
-
-/* FS_VERITY_EXT_ELIDE payload */
-struct fsverity_extension_elide {
-	__le64 offset;
-	__le64 length;
-};
-
-/* FS_VERITY_EXT_PATCH payload */
-struct fsverity_extension_patch {
-	__le64 offset;
-	/* followed by variable-length patch data */
-};
-
-/* Fields stored at the very end of the file */
-struct fsverity_footer {
-	__le32 desc_reverse_offset;	/* distance to fsverity_descriptor */
-	__u8 magic[8];			/* FS_VERITY_MAGIC */
-} __attribute__((packed));
-
 #endif /* _UAPI_LINUX_FSVERITY_H */
diff --git a/fsveritysetup.h b/fsveritysetup.h
deleted file mode 100644
index 282aabd..0000000
--- a/fsveritysetup.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0+ */
-#ifndef FSVERITYSETUP_H
-#define FSVERITYSETUP_H
-
-#include "util.h"
-
-struct fsveritysetup_params {
-	const struct fsverity_hash_alg *hash_alg;
-	u8 *salt;
-	size_t saltlen;
-	int blocksize;
-	int blockbits;			/* ilog2(blocksize) */
-	unsigned int hashes_per_block;	/* blocksize / digest_size */
-	const char *signing_key_file;
-	const char *signing_cert_file;
-	const char *signature_file;
-	struct fsverity_elide_patch **elisions_and_patches;
-	size_t num_elisions_and_patches;
-};
-
-void fsverity_append_extension(void **buf_p, int type,
-			       const void *ext, size_t extlen);
-
-#define FSVERITY_EXTLEN(inner_len)	\
-	ALIGN(sizeof(struct fsverity_extension) + (inner_len), 8)
-
-/* elide_patch.c */
-bool load_elisions_and_patches(const struct string_list *elide_opts,
-			       const struct string_list *patch_opts,
-			       struct fsveritysetup_params *params);
-void free_elisions_and_patches(struct fsveritysetup_params *params);
-bool apply_elisions_and_patches(const struct fsveritysetup_params *params,
-				struct filedes *in, u64 in_length,
-				struct filedes *out_ret, u64 *out_length_ret);
-size_t total_elide_patch_ext_length(const struct fsveritysetup_params *params);
-void append_elide_patch_exts(void **buf_p,
-			     const struct fsveritysetup_params *params);
-/* sign.c */
-int append_signed_measurement(struct filedes *out,
-			      const struct fsveritysetup_params *params,
-			      const u8 *measurement);
-
-#endif /* FSVERITYSETUP_H */
diff --git a/hash_algs.c b/hash_algs.c
index 1e46924..7251bf2 100644
--- a/hash_algs.c
+++ b/hash_algs.c
@@ -14,11 +14,6 @@
 #include "fsverity_uapi.h"
 #include "hash_algs.h"
 
-static void free_hash_ctx(struct hash_ctx *ctx)
-{
-	free(ctx);
-}
-
 /* ========== libcrypto (OpenSSL) wrappers ========== */
 
 struct openssl_hash_ctx {
@@ -104,79 +99,21 @@
 	return openssl_digest_ctx_create(alg, EVP_sha512());
 }
 
-/* ========== CRC-32C ========== */
-
-/*
- * There are faster ways to calculate CRC's, but for now we just use the
- * 256-entry table method as it's portable and not too complex.
- */
-
-#include "crc32c_table.h"
-
-struct crc32c_hash_ctx {
-	struct hash_ctx base;	/* must be first */
-	u32 remainder;
-};
-
-static void crc32c_init(struct hash_ctx *_ctx)
-{
-	struct crc32c_hash_ctx *ctx = (void *)_ctx;
-
-	ctx->remainder = ~0;
-}
-
-static void crc32c_update(struct hash_ctx *_ctx, const void *data, size_t size)
-{
-	struct crc32c_hash_ctx *ctx = (void *)_ctx;
-	const u8 *p = data;
-	u32 r = ctx->remainder;
-
-	while (size--)
-		r = (r >> 8) ^ crc32c_table[(u8)r ^ *p++];
-
-	ctx->remainder = r;
-}
-
-static void crc32c_final(struct hash_ctx *_ctx, u8 *digest)
-{
-	struct crc32c_hash_ctx *ctx = (void *)_ctx;
-	__le32 remainder = cpu_to_le32(~ctx->remainder);
-
-	memcpy(digest, &remainder, sizeof(remainder));
-}
-
-static struct hash_ctx *create_crc32c_ctx(const struct fsverity_hash_alg *alg)
-{
-	struct crc32c_hash_ctx *ctx = xzalloc(sizeof(*ctx));
-
-	ctx->base.alg = alg;
-	ctx->base.init = crc32c_init;
-	ctx->base.update = crc32c_update;
-	ctx->base.final = crc32c_final;
-	ctx->base.free = free_hash_ctx;
-	return &ctx->base;
-}
-
 /* ========== Hash algorithm definitions ========== */
 
 const struct fsverity_hash_alg fsverity_hash_algs[] = {
-	[FS_VERITY_ALG_SHA256] = {
+	[FS_VERITY_HASH_ALG_SHA256] = {
 		.name = "sha256",
 		.digest_size = 32,
-		.cryptographic = true,
+		.block_size = 64,
 		.create_ctx = create_sha256_ctx,
 	},
-	[FS_VERITY_ALG_SHA512] = {
+	[FS_VERITY_HASH_ALG_SHA512] = {
 		.name = "sha512",
 		.digest_size = 64,
-		.cryptographic = true,
+		.block_size = 128,
 		.create_ctx = create_sha512_ctx,
 	},
-	[FS_VERITY_ALG_CRC32C] = {
-		.name = "crc32c",
-		.digest_size = 4,
-		.create_ctx = create_crc32c_ctx,
-	},
 };
 
 const struct fsverity_hash_alg *find_hash_alg_by_name(const char *name)
@@ -216,3 +153,11 @@
 		}
 	}
 }
+
+/* ->init(), ->update(), and ->final() all in one step */
+void hash_full(struct hash_ctx *ctx, const void *data, size_t size, u8 *digest)
+{
+	hash_init(ctx);
+	hash_update(ctx, data, size);
+	hash_final(ctx, digest);
+}
diff --git a/hash_algs.h b/hash_algs.h
index 3cb0a98..3e90f49 100644
--- a/hash_algs.h
+++ b/hash_algs.h
@@ -9,7 +9,7 @@
 struct fsverity_hash_alg {
 	const char *name;
 	unsigned int digest_size;
-	bool cryptographic;
+	unsigned int block_size;
 	struct hash_ctx *(*create_ctx)(const struct fsverity_hash_alg *alg);
 };
 
@@ -26,7 +26,9 @@
 const struct fsverity_hash_alg *find_hash_alg_by_name(const char *name);
 const struct fsverity_hash_alg *find_hash_alg_by_num(unsigned int num);
 void show_all_hash_algs(FILE *fp);
-#define DEFAULT_HASH_ALG (&fsverity_hash_algs[FS_VERITY_ALG_SHA256])
+
+/* The hash algorithm that fsverity-utils assumes when none is specified */
+#define FS_VERITY_HASH_ALG_DEFAULT	FS_VERITY_HASH_ALG_SHA256
 
 /*
  * Largest digest size among all hash algorithms supported by fs-verity.
@@ -61,4 +63,6 @@
 		ctx->free(ctx);
 }
 
+void hash_full(struct hash_ctx *ctx, const void *data, size_t size, u8 *digest);
+
 #endif /* HASH_ALGS_H */
diff --git a/scripts/gen_crc32c_table.c b/scripts/gen_crc32c_table.c
deleted file mode 100644
index 656a349..0000000
--- a/scripts/gen_crc32c_table.c
+++ /dev/null
@@ -1,64 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0+
-/*
- * Generate a table for CRC-32C calculation.
- *
- * Copyright (C) 2018 Google LLC
- *
- * Written by Eric Biggers.
- */
-
-#include <stdint.h>
-#include <stdio.h>
-
-/*
- * This is the CRC-32C (Castagnoli) polynomial: x^32+x^28+x^27+x^26+x^25+x^23+
- * x^22+x^20+x^19+x^18+x^14+x^13+x^11+x^10+x^9+x^8+x^6+x^0, with the polynomial
- * coefficients mapped to bits using the "little endian" convention.
- */
-#define CRC32C_POLY_LE	0x82F63B78
-
-static uint32_t crc32c_update_bit(uint32_t remainder, uint8_t bit)
-{
-	return (remainder >> 1) ^
-		(((remainder ^ bit) & 1) ? CRC32C_POLY_LE : 0);
-}
-
-static uint32_t crc32c_update_byte(uint32_t remainder, uint8_t byte)
-{
-	int bit;
-
-	for (bit = 0; bit < 8; bit++, byte >>= 1)
-		remainder = crc32c_update_bit(remainder, byte & 1);
-	return remainder;
-}
-
-static uint32_t crc32c_table[256];
-
-int main(void)
-{
-	int i, j;
-
-	for (i = 0; i < 256; i++)
-		crc32c_table[i] = crc32c_update_byte(0, i);
-
-	printf("/*\n");
-	printf(" * crc32c_table.h - data table to accelerate CRC-32C computation\n");
-	printf(" *\n");
-	printf(" * This file was automatically generated by scripts/gen_crc32c_table.c\n");
-	printf(" */\n");
-	printf("\n");
-	printf("#include <stdint.h>\n");
-	printf("\n");
-	printf("static const uint32_t crc32c_table[] = {\n");
-	for (i = 0; i < 64; i++) {
-		printf("\t");
-		for (j = 0; j < 4; j++) {
-			printf("0x%08x,", crc32c_table[i * 4 + j]);
-			if (j != 3)
-				printf(" ");
-		}
-		printf("\n");
-	}
-	printf("};\n");
-	return 0;
-}
diff --git a/sign.c b/sign.c
deleted file mode 100644
index 20fecfa..0000000
--- a/sign.c
+++ /dev/null
@@ -1,552 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0+
-/*
- * Signature support for 'fsverity setup'
- *
- * Copyright (C) 2018 Google LLC
- *
- * Written by Eric Biggers.
- */
-
-#include <fcntl.h>
-#include <limits.h>
-#include <openssl/bio.h>
-#include <openssl/err.h>
-#include <openssl/pem.h>
-#include <openssl/pkcs7.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "fsverity_uapi.h"
-#include "fsveritysetup.h"
-#include "hash_algs.h"
-
-static void __printf(1, 2) __cold
-error_msg_openssl(const char *format, ...)
-{
-	va_list va;
-
-	va_start(va, format);
-	do_error_msg(format, va, 0);
-	va_end(va);
-
-	if (ERR_peek_error() == 0)
-		return;
-
-	fprintf(stderr, "OpenSSL library errors:\n");
-	ERR_print_errors_fp(stderr);
-}
-
-/* Read a PEM PKCS#8 formatted private key */
-static EVP_PKEY *read_private_key(const char *keyfile)
-{
-	BIO *bio;
-	EVP_PKEY *pkey;
-
-	bio = BIO_new_file(keyfile, "r");
-	if (!bio) {
-		error_msg_openssl("can't open '%s' for reading", keyfile);
-		return NULL;
-	}
-
-	pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
-	if (!pkey) {
-		error_msg_openssl("Failed to parse private key file '%s'.\n"
-				  "       Note: it must be in PEM PKCS#8 format.",
-				  keyfile);
-	}
-	BIO_free(bio);
-	return pkey;
-}
-
-/* Read a PEM X.509 formatted certificate */
-static X509 *read_certificate(const char *certfile)
-{
-	BIO *bio;
-	X509 *cert;
-
-	bio = BIO_new_file(certfile, "r");
-	if (!bio) {
-		error_msg_openssl("can't open '%s' for reading", certfile);
-		return NULL;
-	}
-	cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
-	if (!cert) {
-		error_msg_openssl("Failed to parse X.509 certificate file '%s'.\n"
-				  "       Note: it must be in PEM format.",
-				  certfile);
-	}
-	BIO_free(bio);
-	return cert;
-}
-
-/*
- * Check that the given data is a valid 'struct fsverity_digest_disk' that
- * matches the given @expected_digest and @hash_alg.
- *
- * Return: NULL if the digests match, else a string describing the difference.
- */
-static const char *
-compare_fsverity_digest(const void *data, size_t size,
-			const u8 *expected_digest,
-			const struct fsverity_hash_alg *hash_alg)
-{
-	const struct fsverity_digest_disk *d = data;
-
-	if (size != sizeof(*d) + hash_alg->digest_size)
-		return "unexpected length";
-
-	if (le16_to_cpu(d->digest_algorithm) != hash_alg - fsverity_hash_algs)
-		return "unexpected hash algorithm";
-
-	if (le16_to_cpu(d->digest_size) != hash_alg->digest_size)
-		return "wrong digest size for hash algorithm";
-
-	if (memcmp(expected_digest, d->digest, hash_alg->digest_size))
-		return "wrong digest";
-
-	return NULL;
-}
-
-#ifdef OPENSSL_IS_BORINGSSL
-
-static bool sign_pkcs7(const void *data_to_sign, size_t data_size,
-		       EVP_PKEY *pkey, X509 *cert, const EVP_MD *md,
-		       void **sig_ret, int *sig_size_ret)
-{
-	CBB out, outer_seq, wrapped_seq, seq, digest_algos_set, digest_algo,
-		null, content_info, issuer_and_serial, signed_data,
-		wrapped_signed_data, signer_infos, signer_info, sign_algo,
-		signature;
-	EVP_MD_CTX md_ctx;
-	u8 *name_der = NULL, *sig = NULL, *pkcs7_data = NULL;
-	size_t pkcs7_data_len, sig_len;
-	int name_der_len, sig_nid;
-	bool ok = false;
-
-	EVP_MD_CTX_init(&md_ctx);
-	BIGNUM *serial = ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), NULL);
-
-	if (!CBB_init(&out, 1024)) {
-		error_msg("out of memory");
-		goto out;
-	}
-
-	name_der_len = i2d_X509_NAME(X509_get_subject_name(cert), &name_der);
-	if (name_der_len < 0) {
-		error_msg_openssl("i2d_X509_NAME failed");
-		goto out;
-	}
-
-	if (!EVP_DigestSignInit(&md_ctx, NULL, md, NULL, pkey)) {
-		error_msg_openssl("EVP_DigestSignInit failed");
-		goto out;
-	}
-
-	sig_len = EVP_PKEY_size(pkey);
-	sig = xmalloc(sig_len);
-	if (!EVP_DigestSign(&md_ctx, sig, &sig_len, data_to_sign, data_size)) {
-		error_msg_openssl("EVP_DigestSign failed");
-		goto out;
-	}
-
-	sig_nid = EVP_PKEY_id(pkey);
-	/* To mirror OpenSSL behaviour, always use |NID_rsaEncryption| with RSA
-	 * rather than the combined hash+pkey NID. */
-	if (sig_nid != NID_rsaEncryption) {
-		OBJ_find_sigid_by_algs(&sig_nid, EVP_MD_type(md),
-				       EVP_PKEY_id(pkey));
-	}
-
-	// See https://tools.ietf.org/html/rfc2315#section-7
-	if (!CBB_add_asn1(&out, &outer_seq, CBS_ASN1_SEQUENCE) ||
-	    !OBJ_nid2cbb(&outer_seq, NID_pkcs7_signed) ||
-	    !CBB_add_asn1(&outer_seq, &wrapped_seq, CBS_ASN1_CONTEXT_SPECIFIC |
-			  CBS_ASN1_CONSTRUCTED | 0) ||
-	    // See https://tools.ietf.org/html/rfc2315#section-9.1
-	    !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) ||
-	    !CBB_add_asn1_uint64(&seq, 1 /* version */) ||
-	    !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) ||
-	    !CBB_add_asn1(&digest_algos_set, &digest_algo, CBS_ASN1_SEQUENCE) ||
-	    !OBJ_nid2cbb(&digest_algo, EVP_MD_type(md)) ||
-	    !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
-	    !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) ||
-	    !OBJ_nid2cbb(&content_info, NID_pkcs7_data) ||
-	    !CBB_add_asn1(
-		&content_info, &signed_data,
-		CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
-	    !CBB_add_asn1(&signed_data, &wrapped_signed_data,
-			  CBS_ASN1_OCTETSTRING) ||
-	    !CBB_add_bytes(&wrapped_signed_data, (const u8 *)data_to_sign,
-			   data_size) ||
-	    !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) ||
-	    !CBB_add_asn1(&signer_infos, &signer_info, CBS_ASN1_SEQUENCE) ||
-	    !CBB_add_asn1_uint64(&signer_info, 1 /* version */) ||
-	    !CBB_add_asn1(&signer_info, &issuer_and_serial,
-			  CBS_ASN1_SEQUENCE) ||
-	    !CBB_add_bytes(&issuer_and_serial, name_der, name_der_len) ||
-	    !BN_marshal_asn1(&issuer_and_serial, serial) ||
-	    !CBB_add_asn1(&signer_info, &digest_algo, CBS_ASN1_SEQUENCE) ||
-	    !OBJ_nid2cbb(&digest_algo, EVP_MD_type(md)) ||
-	    !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
-	    !CBB_add_asn1(&signer_info, &sign_algo, CBS_ASN1_SEQUENCE) ||
-	    !OBJ_nid2cbb(&sign_algo, sig_nid) ||
-	    !CBB_add_asn1(&sign_algo, &null, CBS_ASN1_NULL) ||
-	    !CBB_add_asn1(&signer_info, &signature, CBS_ASN1_OCTETSTRING) ||
-	    !CBB_add_bytes(&signature, sig, sig_len) ||
-	    !CBB_finish(&out, &pkcs7_data, &pkcs7_data_len)) {
-		error_msg_openssl("failed to construct PKCS#7 data");
-		goto out;
-	}
-
-	*sig_ret = xmemdup(pkcs7_data, pkcs7_data_len);
-	*sig_size_ret = pkcs7_data_len;
-	ok = true;
-out:
-	BN_free(serial);
-	EVP_MD_CTX_cleanup(&md_ctx);
-	CBB_cleanup(&out);
-	free(sig);
-	OPENSSL_free(name_der);
-	OPENSSL_free(pkcs7_data);
-	return ok;
-}
-
-static const char *
-compare_fsverity_digest_pkcs7(const void *sig, size_t sig_len,
-			      const u8 *expected_measurement,
-			      const struct fsverity_hash_alg *hash_alg)
-{
-	CBS in, content_info, content_type, wrapped_signed_data, signed_data,
-		content, wrapped_data, data;
-	u64 version;
-
-	CBS_init(&in, sig, sig_len);
-	if (!CBS_get_asn1(&in, &content_info, CBS_ASN1_SEQUENCE) ||
-	    !CBS_get_asn1(&content_info, &content_type, CBS_ASN1_OBJECT) ||
-	    (OBJ_cbs2nid(&content_type) != NID_pkcs7_signed) ||
-	    !CBS_get_asn1(
-		&content_info, &wrapped_signed_data,
-		CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
-	    !CBS_get_asn1(&wrapped_signed_data, &signed_data,
-			  CBS_ASN1_SEQUENCE) ||
-	    !CBS_get_asn1_uint64(&signed_data, &version) ||
-	    (version < 1) ||
-	    !CBS_get_asn1(&signed_data, NULL /* digests */, CBS_ASN1_SET) ||
-	    !CBS_get_asn1(&signed_data, &content, CBS_ASN1_SEQUENCE) ||
-	    !CBS_get_asn1(&content, &content_type, CBS_ASN1_OBJECT) ||
-	    (OBJ_cbs2nid(&content_type) != NID_pkcs7_data) ||
-	    !CBS_get_asn1(&content, &wrapped_data, CBS_ASN1_CONTEXT_SPECIFIC |
-						   CBS_ASN1_CONSTRUCTED | 0) ||
-	    !CBS_get_asn1(&wrapped_data, &data, CBS_ASN1_OCTETSTRING)) {
-		return "invalid PKCS#7 data";
-	}
-
-	return compare_fsverity_digest(CBS_data(&data), CBS_len(&data),
-				       expected_measurement, hash_alg);
-}
-
-#else /* OPENSSL_IS_BORINGSSL */
-
-static BIO *new_mem_buf(const void *buf, size_t size)
-{
-	BIO *bio;
-
-	ASSERT(size <= INT_MAX);
-	/*
-	 * Prior to OpenSSL 1.1.0, BIO_new_mem_buf() took a non-const pointer,
-	 * despite still marking the resulting bio as read-only.  So cast away
-	 * the const to avoid a compiler warning with older OpenSSL versions.
-	 */
-	bio = BIO_new_mem_buf((void *)buf, size);
-	if (!bio)
-		error_msg_openssl("out of memory");
-	return bio;
-}
-
-static bool sign_pkcs7(const void *data_to_sign, size_t data_size,
-		       EVP_PKEY *pkey, X509 *cert, const EVP_MD *md,
-		       void **sig_ret, int *sig_size_ret)
-{
-	/*
-	 * PKCS#7 signing flags:
-	 *
-	 * - PKCS7_BINARY	signing binary data, so skip MIME translation
-	 *
-	 * - PKCS7_NOATTR	omit extra authenticated attributes, such as
-	 *			SMIMECapabilities
-	 *
-	 * - PKCS7_NOCERTS	omit the signer's certificate
-	 *
-	 * - PKCS7_PARTIAL	PKCS7_sign() creates a handle only, then
-	 *			PKCS7_sign_add_signer() can add a signer later.
-	 *			This is necessary to change the message digest
-	 *			algorithm from the default of SHA-1.  Requires
-	 *			OpenSSL 1.0.0 or later.
-	 */
-	int pkcs7_flags = PKCS7_BINARY | PKCS7_NOATTR | PKCS7_NOCERTS |
-			  PKCS7_PARTIAL;
-	void *sig;
-	int sig_size;
-	BIO *bio = NULL;
-	PKCS7 *p7 = NULL;
-	bool ok = false;
-
-	bio = new_mem_buf(data_to_sign, data_size);
-	if (!bio)
-		goto out;
-
-	p7 = PKCS7_sign(NULL, NULL, NULL, bio, pkcs7_flags);
-	if (!p7) {
-		error_msg_openssl("failed to initialize PKCS#7 signature object");
-		goto out;
-	}
-
-	if (!PKCS7_sign_add_signer(p7, cert, pkey, md, pkcs7_flags)) {
-		error_msg_openssl("failed to add signer to PKCS#7 signature object");
-		goto out;
-	}
-
-	if (PKCS7_final(p7, bio, pkcs7_flags) != 1) {
-		error_msg_openssl("failed to finalize PKCS#7 signature");
-		goto out;
-	}
-
-	BIO_free(bio);
-	bio = BIO_new(BIO_s_mem());
-	if (!bio) {
-		error_msg_openssl("out of memory");
-		goto out;
-	}
-
-	if (i2d_PKCS7_bio(bio, p7) != 1) {
-		error_msg_openssl("failed to DER-encode PKCS#7 signature object");
-		goto out;
-	}
-
-	sig_size = BIO_get_mem_data(bio, &sig);
-	*sig_ret = xmemdup(sig, sig_size);
-	*sig_size_ret = sig_size;
-	ok = true;
-out:
-	PKCS7_free(p7);
-	BIO_free(bio);
-	return ok;
-}
-
-static const char *
-compare_fsverity_digest_pkcs7(const void *sig, size_t sig_len,
-			      const u8 *expected_measurement,
-			      const struct fsverity_hash_alg *hash_alg)
-{
-	BIO *bio = NULL;
-	PKCS7 *p7 = NULL;
-	const char *reason = NULL;
-
-	bio = new_mem_buf(sig, sig_len);
-	if (!bio)
-		return "out of memory";
-
-	p7 = d2i_PKCS7_bio(bio, NULL);
-	if (!p7) {
-		reason = "failed to decode PKCS#7 signature";
-		goto out;
-	}
-
-	if (OBJ_obj2nid(p7->type) != NID_pkcs7_signed ||
-	    OBJ_obj2nid(p7->d.sign->contents->type) != NID_pkcs7_data) {
-		reason = "unexpected PKCS#7 content type";
-	} else {
-		const ASN1_OCTET_STRING *o = p7->d.sign->contents->d.data;
-
-		reason = compare_fsverity_digest(o->data, o->length,
-						 expected_measurement,
-						 hash_alg);
-	}
-out:
-	BIO_free(bio);
-	PKCS7_free(p7);
-	return reason;
-}
-
-#endif /* !OPENSSL_IS_BORINGSSL */
-
-/*
- * Sign the specified @data_to_sign of length @data_size bytes using the private
- * key in @keyfile, the certificate in @certfile, and the hash algorithm
- * @hash_alg.  Returns the DER-formatted PKCS#7 signature, with the signed data
- * included (not detached), in @sig_ret and @sig_size_ret.
- */
-static bool sign_data(const void *data_to_sign, size_t data_size,
-		      const char *keyfile, const char *certfile,
-		      const struct fsverity_hash_alg *hash_alg,
-		      void **sig_ret, int *sig_size_ret)
-{
-	EVP_PKEY *pkey = NULL;
-	X509 *cert = NULL;
-	const EVP_MD *md;
-	bool ok = false;
-
-	pkey = read_private_key(keyfile);
-	if (!pkey)
-		goto out;
-
-	cert = read_certificate(certfile);
-	if (!cert)
-		goto out;
-
-	OpenSSL_add_all_digests();
-	ASSERT(hash_alg->cryptographic);
-	md = EVP_get_digestbyname(hash_alg->name);
-	if (!md) {
-		fprintf(stderr,
-			"Warning: '%s' algorithm not found in OpenSSL library.\n"
-			"         Falling back to SHA-256 signature.\n",
-			hash_alg->name);
-		md = EVP_sha256();
-	}
-
-	ok = sign_pkcs7(data_to_sign, data_size, pkey, cert, md,
-			sig_ret, sig_size_ret);
-out:
-	EVP_PKEY_free(pkey);
-	X509_free(cert);
-	return ok;
-}
-
-/*
- * Read a file measurement signature in PKCS#7 DER format from @signature_file,
- * validate that the signed data matches the expected measurement, then return
- * the PKCS#7 DER message in @sig_ret and @sig_size_ret.
- */
-static bool read_signature(const char *signature_file,
-			   const u8 *expected_measurement,
-			   const struct fsverity_hash_alg *hash_alg,
-			   void **sig_ret, int *sig_size_ret)
-{
-	struct filedes file = { .fd = -1 };
-	u64 filesize;
-	void *sig = NULL;
-	bool ok = false;
-	const char *reason;
-
-	if (!open_file(&file, signature_file, O_RDONLY, 0))
-		goto out;
-	if (!get_file_size(&file, &filesize))
-		goto out;
-	if (filesize <= 0) {
-		error_msg("signature file '%s' is empty", signature_file);
-		goto out;
-	}
-	if (filesize > 1000000) {
-		error_msg("signature file '%s' is too large", signature_file);
-		goto out;
-	}
-	sig = xmalloc(filesize);
-	if (!full_read(&file, sig, filesize))
-		goto out;
-
-	reason = compare_fsverity_digest_pkcs7(sig, filesize,
-					       expected_measurement, hash_alg);
-	if (reason) {
-		error_msg("signed file measurement from '%s' is invalid (%s)",
-			  signature_file, reason);
-		goto out;
-	}
-
-	printf("Using existing signed file measurement from '%s'\n",
-	       signature_file);
-	*sig_ret = sig;
-	*sig_size_ret = filesize;
-	sig = NULL;
-	ok = true;
-out:
-	filedes_close(&file);
-	free(sig);
-	return ok;
-}
-
-static bool write_signature(const char *signature_file,
-			    const void *sig, int sig_size)
-{
-	struct filedes file;
-	bool ok;
-
-	if (!open_file(&file, signature_file, O_WRONLY|O_CREAT|O_TRUNC, 0644))
-		return false;
-	ok = full_write(&file, sig, sig_size);
-	ok &= filedes_close(&file);
-	if (ok)
-		printf("Wrote signed file measurement to '%s'\n",
-		       signature_file);
-	return ok;
-}
-
-/*
- * Append the signed file measurement to the output file as a PKCS7_SIGNATURE
- * extension item.
- *
- * Return: exit status code (0 on success, nonzero on failure)
- */
-int append_signed_measurement(struct filedes *out,
-			      const struct fsveritysetup_params *params,
-			      const u8 *measurement)
-{
-	struct fsverity_digest_disk *data_to_sign = NULL;
-	void *sig = NULL;
-	void *extbuf = NULL;
-	void *tmp;
-	int sig_size;
-	int status;
-
-	if (params->signing_key_file) {
-		size_t data_size = sizeof(*data_to_sign) +
-				   params->hash_alg->digest_size;
-
-		/* Sign the file measurement using the given key */
-
-		data_to_sign = xzalloc(data_size);
-		data_to_sign->digest_algorithm =
-			cpu_to_le16(params->hash_alg - fsverity_hash_algs);
-		data_to_sign->digest_size =
-			cpu_to_le16(params->hash_alg->digest_size);
-		memcpy(data_to_sign->digest, measurement,
-		       params->hash_alg->digest_size);
-
-		ASSERT(compare_fsverity_digest(data_to_sign, data_size,
-					measurement, params->hash_alg) == NULL);
-
-		if (!sign_data(data_to_sign, data_size,
-			       params->signing_key_file,
-			       params->signing_cert_file ?:
-			       params->signing_key_file,
-			       params->hash_alg,
-			       &sig, &sig_size))
-			goto out_err;
-
-		if (params->signature_file &&
-		    !write_signature(params->signature_file, sig, sig_size))
-			goto out_err;
-	} else {
-		/* Using a signature that was already created */
-		if (!read_signature(params->signature_file, measurement,
-				    params->hash_alg, &sig, &sig_size))
-			goto out_err;
-	}
-
-	tmp = extbuf = xzalloc(FSVERITY_EXTLEN(sig_size));
-	fsverity_append_extension(&tmp, FS_VERITY_EXT_PKCS7_SIGNATURE,
-				  sig, sig_size);
-	ASSERT(tmp == extbuf + FSVERITY_EXTLEN(sig_size));
-	if (!full_write(out, extbuf, FSVERITY_EXTLEN(sig_size)))
-		goto out_err;
-	status = 0;
-out:
-	free(data_to_sign);
-	free(sig);
-	free(extbuf);
-	return status;
-
-out_err:
-	status = 1;
-	goto out;
-}
diff --git a/util.c b/util.c
index 58a2a60..2218f2e 100644
--- a/util.c
+++ b/util.c
@@ -45,26 +45,6 @@
 	return xmemdup(s, strlen(s) + 1);
 }
 
-char *xasprintf(const char *format, ...)
-{
-	va_list va1, va2;
-	int size;
-	char *s;
-
-	va_start(va1, format);
-
-	va_copy(va2, va1);
-	size = vsnprintf(NULL, 0, format, va2);
-	va_end(va2);
-
-	ASSERT(size >= 0);
-	s = xmalloc(size + 1);
-	vsprintf(s, format, va1);
-
-	va_end(va1);
-	return s;
-}
-
 /* ========== Error messages and assertions ========== */
 
 void do_error_msg(const char *format, va_list va, int err)
@@ -121,26 +101,7 @@
 				"reading and writing");
 		return false;
 	}
-	file->autodelete = false;
 	file->name = xstrdup(filename);
-	file->pos = 0;
-	return true;
-}
-
-bool open_tempfile(struct filedes *file)
-{
-	const char *tmpdir = getenv("TMPDIR") ?: P_tmpdir;
-	char *name = xasprintf("%s/fsverity-XXXXXX", tmpdir);
-
-	file->fd = mkstemp(name);
-	if (file->fd < 0) {
-		error_msg_errno("can't create temporary file");
-		free(name);
-		return false;
-	}
-	file->autodelete = true;
-	file->name = name;
-	file->pos = 0;
 	return true;
 }
 
@@ -156,19 +117,6 @@
 	return true;
 }
 
-bool filedes_seek(struct filedes *file, u64 pos, int whence)
-{
-	off_t res;
-
-	res = lseek(file->fd, pos, whence);
-	if (res < 0) {
-		error_msg_errno("seek error on '%s'", file->name);
-		return false;
-	}
-	file->pos = res;
-	return true;
-}
-
 bool full_read(struct filedes *file, void *buf, size_t count)
 {
 	while (count) {
@@ -184,27 +132,6 @@
 		}
 		buf += n;
 		count -= n;
-		file->pos += n;
-	}
-	return true;
-}
-
-bool full_pread(struct filedes *file, void *buf, size_t count, u64 offset)
-{
-	while (count) {
-		int n = pread(file->fd, buf, min(count, INT_MAX), offset);
-
-		if (n < 0) {
-			error_msg_errno("reading from '%s'", file->name);
-			return false;
-		}
-		if (n == 0) {
-			error_msg("unexpected end-of-file on '%s'", file->name);
-			return false;
-		}
-		buf += n;
-		count -= n;
-		offset += n;
 	}
 	return true;
 }
@@ -220,58 +147,6 @@
 		}
 		buf += n;
 		count -= n;
-		file->pos += n;
-	}
-	return true;
-}
-
-bool full_pwrite(struct filedes *file, const void *buf, size_t count,
-		 u64 offset)
-{
-	while (count) {
-		int n = pwrite(file->fd, buf, min(count, INT_MAX), offset);
-
-		if (n < 0) {
-			error_msg_errno("writing to '%s'", file->name);
-			return false;
-		}
-		buf += n;
-		count -= n;
-		offset += n;
-	}
-	return true;
-}
-
-/* Copy 'count' bytes of data from 'src' to 'dst' */
-bool copy_file_data(struct filedes *src, struct filedes *dst, u64 count)
-{
-	char buf[4096];
-
-	while (count) {
-		size_t n = min(count, sizeof(buf));
-
-		if (!full_read(src, buf, n))
-			return false;
-		if (!full_write(dst, buf, n))
-			return false;
-		count -= n;
-	}
-	return true;
-}
-
-/* Write 'count' bytes of zeroes to the file */
-bool write_zeroes(struct filedes *file, u64 count)
-{
-	char buf[4096];
-
-	memset(buf, 0, min(count, sizeof(buf)));
-
-	while (count) {
-		size_t n = min(count, sizeof(buf));
-
-		if (!full_write(file, buf, n))
-			return false;
-		count -= n;
 	}
 	return true;
 }
@@ -285,8 +160,6 @@
 	res = close(file->fd);
 	if (res != 0)
 		error_msg_errno("closing '%s'", file->name);
-	if (file->autodelete)
-		(void)unlink(file->name);
 	file->fd = -1;
 	free(file->name);
 	file->name = NULL;
@@ -340,23 +213,3 @@
 	}
 	*hex = '\0';
 }
-
-void string_list_append(struct string_list *list, char *string)
-{
-	ASSERT(list->length <= list->capacity);
-	if (list->length == list->capacity) {
-		list->capacity = (list->capacity * 2) + 4;
-		list->strings = realloc(list->strings,
-					sizeof(list->strings[0]) *
-					list->capacity);
-		if (!list->strings)
-			fatal_error("out of memory");
-	}
-	list->strings[list->length++] = string;
-}
-
-void string_list_destroy(struct string_list *list)
-{
-	free(list->strings);
-	memset(list, 0, sizeof(*list));
-}
diff --git a/util.h b/util.h
index c4cbe48..dfa10f2 100644
--- a/util.h
+++ b/util.h
@@ -49,16 +49,15 @@
 	_a > _b ? _a : _b;		\
 })
 
+#define roundup(x, y) ({		\
+	__typeof__(y) _y = (y);		\
+	(((x) + _y - 1) / _y) * _y;	\
+})
+
 #define ARRAY_SIZE(A)		(sizeof(A) / sizeof((A)[0]))
 
 #define DIV_ROUND_UP(n, d)	(((n) + (d) - 1) / (d))
 
-/*
- * Round 'v' up to the next 'alignment'-byte aligned boundary.
- * 'alignment' must be a power of 2.
- */
-#define ALIGN(v, alignment)	(((v) + ((alignment) - 1)) & ~((alignment) - 1))
-
 static inline bool is_power_of_2(unsigned long n)
 {
 	return n != 0 && ((n & (n - 1)) == 0);
@@ -78,12 +77,6 @@
 #  define le32_to_cpu(v)	((__force u32)(__le32)(v))
 #  define cpu_to_le64(v)	((__force __le64)(u64)(v))
 #  define le64_to_cpu(v)	((__force u64)(__le64)(v))
-#  define cpu_to_be16(v)	((__force __be16)__builtin_bswap16(v))
-#  define be16_to_cpu(v)	(__builtin_bswap16((__force u16)(v)))
-#  define cpu_to_be32(v)	((__force __be32)__builtin_bswap32(v))
-#  define be32_to_cpu(v)	(__builtin_bswap32((__force u32)(v)))
-#  define cpu_to_be64(v)	((__force __be64)__builtin_bswap64(v))
-#  define be64_to_cpu(v)	(__builtin_bswap64((__force u64)(v)))
 #else
 #  define cpu_to_le16(v)	((__force __le16)__builtin_bswap16(v))
 #  define le16_to_cpu(v)	(__builtin_bswap16((__force u16)(v)))
@@ -91,12 +84,6 @@
 #  define le32_to_cpu(v)	(__builtin_bswap32((__force u32)(v)))
 #  define cpu_to_le64(v)	((__force __le64)__builtin_bswap64(v))
 #  define le64_to_cpu(v)	(__builtin_bswap64((__force u64)(v)))
-#  define cpu_to_be16(v)	((__force __be16)(u16)(v))
-#  define be16_to_cpu(v)	((__force u16)(__be16)(v))
-#  define cpu_to_be32(v)	((__force __be32)(u32)(v))
-#  define be32_to_cpu(v)	((__force u32)(__be32)(v))
-#  define cpu_to_be64(v)	((__force __be64)(u64)(v))
-#  define be64_to_cpu(v)	((__force u64)(__be64)(v))
 #endif
 
 /* ========== Memory allocation ========== */
@@ -105,7 +92,6 @@
 void *xzalloc(size_t size);
 void *xmemdup(const void *mem, size_t size);
 char *xstrdup(const char *s);
-__printf(1, 2) char *xasprintf(const char *format, ...);
 
 /* ========== Error messages and assertions ========== */
 
@@ -122,22 +108,13 @@
 
 struct filedes {
 	int fd;
-	bool autodelete;	/* unlink when closed? */
 	char *name;		/* filename, for logging or error messages */
-	u64 pos;		/* lseek() position */
 };
 
 bool open_file(struct filedes *file, const char *filename, int flags, int mode);
-bool open_tempfile(struct filedes *file);
 bool get_file_size(struct filedes *file, u64 *size_ret);
-bool filedes_seek(struct filedes *file, u64 pos, int whence);
 bool full_read(struct filedes *file, void *buf, size_t count);
-bool full_pread(struct filedes *file, void *buf, size_t count, u64 offset);
 bool full_write(struct filedes *file, const void *buf, size_t count);
-bool full_pwrite(struct filedes *file, const void *buf, size_t count,
-		 u64 offset);
-bool copy_file_data(struct filedes *src, struct filedes *dst, u64 length);
-bool write_zeroes(struct filedes *file, u64 length);
 bool filedes_close(struct filedes *file);
 
 /* ========== String utilities ========== */
@@ -145,16 +122,4 @@
 bool hex2bin(const char *hex, u8 *bin, size_t bin_len);
 void bin2hex(const u8 *bin, size_t bin_len, char *hex);
 
-struct string_list {
-	char **strings;
-	size_t length;
-	size_t capacity;
-};
-
-#define STRING_LIST_INITIALIZER { .strings = NULL, .length = 0, .capacity = 0 }
-#define STRING_LIST(_list) struct string_list _list = STRING_LIST_INITIALIZER
-
-void string_list_append(struct string_list *list, char *string);
-void string_list_destroy(struct string_list *list);
-
 #endif /* UTIL_H */