HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/pcrlock/pcrlock.c
Git blob: c798c78489257ecc6f87eead6fa509ad2027c886
Lines 3001–4000 of 5,877
int r;
assert(f);
assert(ret_records);
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
const char *a;
const EVP_MD *md;
assert_se(a = tpm2_hash_alg_to_string(tpm2_hash_algorithms[i]));
assert_se(md = sym_EVP_get_digestbyname(a));
mdctx[i] = sym_EVP_MD_CTX_new();
if (!mdctx[i])
return log_oom();
if (sym_EVP_DigestInit_ex(mdctx[i], md, NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
"Failed to initialize message digest for %s.", a);
}
for (;;) {
uint8_t buffer[64*1024];
size_t n;
n = fread(buffer, 1, sizeof(buffer), f);
if (ferror(f))
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to read file.");
if (n == 0 && feof(f))
break;
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++)
if (sym_EVP_DigestUpdate(mdctx[i], buffer, n) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Unable to hash data.");
}
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
const char *a;
int hash_ssize;
unsigned hash_usize;
assert_se(a = tpm2_hash_alg_to_string(tpm2_hash_algorithms[i]));
hash_ssize = sym_EVP_MD_CTX_get_size(mdctx[i]);
assert(hash_ssize > 0 && hash_ssize <= EVP_MAX_MD_SIZE);
hash_usize = hash_ssize;
unsigned char hash[hash_usize];
if (sym_EVP_DigestFinal_ex(mdctx[i], hash, &hash_usize) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
"Failed to finalize hash context for algorithn '%s'.", a);
r = sd_json_variant_append_arraybo(
&digests,
SD_JSON_BUILD_PAIR_STRING("hashAlg", a),
SD_JSON_BUILD_PAIR("digest", SD_JSON_BUILD_HEX(hash, hash_usize)));
if (r < 0)
return log_error_errno(r, "Failed to build JSON digest object: %m");
}
for (uint32_t i = 0; i < TPM2_PCRS_MAX; i++) {
_cleanup_(sd_json_variant_unrefp) sd_json_variant *record = NULL;
if (!BIT_SET(pcr_mask, i))
continue;
r = sd_json_buildo(
&record,
SD_JSON_BUILD_PAIR_UNSIGNED("pcr", i),
SD_JSON_BUILD_PAIR_VARIANT("digests", digests));
if (r < 0)
return log_error_errno(r, "Failed to build record object: %m");
r = sd_json_variant_append_array(ret_records, record);
if (r < 0)
return log_error_errno(r, "Failed to append to JSON array: %m");
}
return 0;
}
static const char *pcrlock_path(const char *default_pcrlock_path) {
return arg_pcrlock_path ?: arg_pcrlock_auto ? default_pcrlock_path : NULL;
}
static int write_pcrlock(sd_json_variant *array, const char *default_pcrlock_path) {
_cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *a = NULL;
_cleanup_fclose_ FILE *f = NULL;
const char *p;
int r;
if (!array) {
r = sd_json_variant_new_array(&a, NULL, 0);
if (r < 0)
return log_error_errno(r, "Failed to allocate empty array: %m");
array = a;
}
r = sd_json_buildo(
&v,
SD_JSON_BUILD_PAIR_VARIANT("records", array));
if (r < 0)
return log_error_errno(r, "Failed to build JSON object: %m");
p = pcrlock_path(default_pcrlock_path);
if (p) {
(void) mkdir_parents_label(p, 0755);
f = fopen(p, "we");
if (!f)
return log_error_errno(errno, "Failed to open %s for writing: %m", p);
}
r = sd_json_variant_dump(v, arg_json_format_flags, f ?: stdout, /* prefix= */ NULL);
if (r < 0)
return log_error_errno(r, "Failed to output JSON object: %m");
if (p)
log_debug("%s written.", p);
return 0;
}
static int unlink_pcrlock(const char *default_pcrlock_path) {
const char *p;
p = pcrlock_path(default_pcrlock_path);
if (!p)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No .pcrlock path specified, refusing.");
if (unlink(p) < 0) {
if (errno != ENOENT)
return log_error_errno(errno, "Failed to delete %s: %m", p);
log_info("%s already deleted.", p);
} else
log_info("%s deleted.", p);
(void) rmdir_parents(p, "/var/lib");
return 0;
}
static int event_log_reduce_to_safe_pcrs(EventLog *el, uint32_t *pcrs) {
_cleanup_free_ char *dropped = NULL, *kept = NULL;
bool dropped_relevant_pcr = false;
assert(el);
assert(pcrs);
/* When we compile a new PCR policy we don't want to bind to PCRs which are fishy for one of three
* reasons:
*
* 1. The PCR value doesn't match the event log
* 2. The event log for the PCR contains measurements we don't know responsible components for
* 3. The event log for the PCR does not contain measurements for components we know
*
* This function checks for the three conditions and drops the PCR from the mask.
*/
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
if (!BIT_SET(*pcrs, pcr))
continue;
if (!event_log_pcr_checks_out(el, el->registers + pcr)) {
log_notice("PCR %" PRIu32 " (%s) value does not match event log. Removing from set of PCRs.", pcr, strna(tpm2_pcr_index_to_string(pcr)));
goto drop;
}
if (!el->registers[pcr].fully_recognized) {
log_notice("PCR %" PRIu32 " (%s) event log contains unrecognized measurements. Removing from set of PCRs.", pcr, strna(tpm2_pcr_index_to_string(pcr)));
goto drop;
}
if (BIT_SET(el->missing_component_pcrs, pcr)) {
log_notice("PCR %" PRIu32 " (%s) is touched by component we can't find in event log. Removing from set of PCRs.", pcr, strna(tpm2_pcr_index_to_string(pcr)));
goto drop;
}
log_debug("PCR %" PRIu32 " (%s) matches event log and fully consists of recognized measurements. Including in set of PCRs.", pcr, strna(tpm2_pcr_index_to_string(pcr)));
if (strextendf_with_separator(&kept, ", ", "%" PRIu32 " (%s)", pcr, tpm2_pcr_index_to_string(pcr)) < 0)
return log_oom();
continue;
drop:
if (arg_strict)
dropped_relevant_pcr = true;
*pcrs &= ~(UINT32_C(1) << pcr);
if (strextendf_with_separator(&dropped, ", ", "%" PRIu32 " (%s)", pcr, tpm2_pcr_index_to_string(pcr)) < 0)
return log_oom();
}
if (dropped)
log_full(dropped_relevant_pcr ? LOG_ERR : LOG_NOTICE, "PCRs dropped from protection mask: %s", dropped);
else
log_debug("No PCRs dropped from protection mask.");
if (kept)
log_notice("PCRs in protection mask: %s", kept);
else
log_notice("No PCRs kept in protection mask.");
return dropped_relevant_pcr ? -ENOEXEC : 0;
}
static int pcr_prediction_add_result(
Tpm2PCRPrediction *context,
Tpm2PCRPredictionResult *result,
uint32_t pcr,
const char *path) {
_cleanup_free_ Tpm2PCRPredictionResult *copy = NULL;
int r;
assert(context);
assert(result);
copy = newdup(Tpm2PCRPredictionResult, result, 1);
if (!copy)
return log_oom();
r = ordered_set_ensure_put(context->results + pcr, &tpm2_pcr_prediction_result_hash_ops, copy);
if (r == -EEXIST) /* Multiple identical results for the same PCR are totally expected */
return 0;
if (r < 0)
return log_error_errno(r, "Failed to insert result into set: %m");
log_debug("Added prediction result %u for PCR %" PRIu32 " (path: %s)", ordered_set_size(context->results[pcr]), pcr, strempty(path));
TAKE_PTR(copy);
return 0;
}
static const EVP_MD* evp_from_tpm2_alg(uint16_t alg) {
const char *name;
name = tpm2_hash_alg_to_string(alg);
if (!name)
return NULL;
return sym_EVP_get_digestbyname(name);
}
static int event_log_component_variant_calculate(
Tpm2PCRPredictionResult *result,
EventLogComponentVariant *variant,
uint32_t pcr) {
assert(result);
assert(variant);
FOREACH_ARRAY(rr, variant->records, variant->n_records) {
EventLogRecord *rec = *rr;
if (!EVENT_LOG_RECORD_IS_PCR(rec))
continue;
if (rec->pcr != pcr)
continue;
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
_cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *md_ctx = NULL;
EventLogRecordBank *b;
if (result->hash[i].size <= 0) /* already invalidated */
continue;
b = event_log_record_find_bank(rec, tpm2_hash_algorithms[i]);
if (!b) {
/* Can't calculate, hence invalidate */
result->hash[i] = (TPM2B_DIGEST) {};
continue;
}
md_ctx = sym_EVP_MD_CTX_new();
if (!md_ctx)
return log_oom();
const EVP_MD *md = ASSERT_PTR(evp_from_tpm2_alg(tpm2_hash_algorithms[i]));
int sz = sym_EVP_MD_get_size(md);
assert(sz > 0);
assert((size_t) sz <= sizeof_field(TPM2B_DIGEST, buffer));
assert(sz == tpm2_hash_alg_to_size(tpm2_hash_algorithms[i]));
assert(result->hash[i].size == (size_t) sz);
assert(b->hash.size == (size_t) sz);
if (sym_EVP_DigestInit_ex(md_ctx, md, NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to initialize message digest.");
if (sym_EVP_DigestUpdate(md_ctx, result->hash[i].buffer, sz) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash bank value.");
if (sym_EVP_DigestUpdate(md_ctx, b->hash.buffer, sz) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash data value.");
unsigned l = (unsigned) sz;
if (sym_EVP_DigestFinal_ex(md_ctx, result->hash[i].buffer, &l) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to finalize message digest.");
assert(l == (unsigned) sz);
}
}
return 0;
}
static int event_log_predict_pcrs(
EventLog *el,
Tpm2PCRPrediction *context,
Tpm2PCRPredictionResult *parent_result,
size_t component_index,
uint32_t pcr,
const char *path) {
EventLogComponent *component;
int count = 0, r;
assert(el);
assert(context);
assert(parent_result);
/* Check if we reached the end of the components, generate a result, and backtrack */
if (component_index >= el->n_components ||
(arg_location_end && strcmp(el->components[component_index]->id, arg_location_end) > 0)) {
r = pcr_prediction_add_result(context, parent_result, pcr, path);
if (r < 0)
return r;
return 1;
}
component = ASSERT_PTR(el->components[component_index]);
/* Check if we are just about to process a component after start, if so record a result and continue. */
if (arg_location_start && strcmp(component->id, arg_location_start) > 0) {
r = pcr_prediction_add_result(context, parent_result, pcr, path);
if (r < 0)
return r;
}
FOREACH_ARRAY(ii, component->variants, component->n_variants) {
_cleanup_free_ Tpm2PCRPredictionResult *result = NULL;
EventLogComponentVariant *variant = *ii;
_cleanup_free_ char *subpath = NULL;
/* Operate on a copy of the result */
if (path)
subpath = strjoin(path, ":", component->id);
else
subpath = strdup(component->id);
if (!subpath)
return log_oom();
if (!streq(component->id, variant->id))
if (!strextend(&subpath, "@", variant->id))
return log_oom();
result = newdup(Tpm2PCRPredictionResult, parent_result, 1);
if (!result)
return log_oom();
r = event_log_component_variant_calculate(
result,
variant,
pcr);
if (r < 0)
return r;
r = event_log_predict_pcrs(
el,
context,
result,
component_index + 1, /* Next component */
pcr,
subpath);
if (r < 0)
return r;
count += r;
}
return count;
}
static ssize_t event_log_calculate_component_combinations(EventLog *el) {
ssize_t count = 1;
assert(el);
FOREACH_ARRAY(cc, el->components, el->n_components) {
EventLogComponent *c = *cc;
assert(c->n_variants > 0);
/* Overflow check */
if (c->n_variants > (size_t) (SSIZE_MAX/count))
return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Too many component combinations.");
count *= c->n_variants;
}
return count;
}
static int event_log_show_predictions(Tpm2PCRPrediction *context, uint16_t alg) {
int r;
assert(context);
pager_open(arg_pager_flags);
if (sd_json_format_enabled(arg_json_format_flags)) {
_cleanup_(sd_json_variant_unrefp) sd_json_variant *j = NULL;
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
_cleanup_(sd_json_variant_unrefp) sd_json_variant *aj = NULL;
r = tpm2_pcr_prediction_to_json(
context,
tpm2_hash_algorithms[i],
&aj);
if (r < 0)
return r;
if (sd_json_variant_elements(aj) == 0)
continue;
r = sd_json_variant_set_field(
&j,
tpm2_hash_alg_to_string(tpm2_hash_algorithms[i]),
aj);
if (r < 0)
return log_error_errno(r, "Failed to add prediction bank to object: %m");
}
if (!j) {
r = sd_json_variant_new_object(&j, NULL, 0);
if (r < 0)
return log_error_errno(r, "Failed to allocated empty object: %m");
}
sd_json_variant_dump(j, arg_json_format_flags, /* f= */ NULL, /* prefix= */ NULL);
return 0;
}
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
Tpm2PCRPredictionResult *result;
if (!BIT_SET(context->pcrs, pcr))
continue;
if (ordered_set_isempty(context->results[pcr])) {
printf("No results for PCR %u (%s).\n", pcr, tpm2_pcr_index_to_string(pcr));
continue;
}
printf("%sResults for PCR %u (%s):%s\n", ansi_underline(), pcr, tpm2_pcr_index_to_string(pcr), ansi_normal());
ORDERED_SET_FOREACH(result, context->results[pcr]) {
_cleanup_free_ char *aa = NULL, *h = NULL;
const char *a;
TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(result, alg);
if (!hash)
continue;
a = ASSERT_PTR(tpm2_hash_alg_to_string(alg));
aa = strdup(a);
if (!aa)
return log_oom();
ascii_strlower(aa);
h = hexmem(hash->buffer, hash->size);
if (!h)
return log_oom();
printf(" %s%-6s:%s %s\n", ansi_grey(), aa, ansi_normal(), h);
}
}
return 0;
}
static int tpm2_pcr_prediction_run(
EventLog *el,
Tpm2PCRPrediction *context) {
int r;
assert(el);
assert(context);
for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
_cleanup_free_ Tpm2PCRPredictionResult *result = NULL;
if (!BIT_SET(context->pcrs, pcr))
continue;
result = new0(Tpm2PCRPredictionResult, 1);
if (!result)
return log_oom();
for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++)
event_log_initial_pcr_state(el, pcr, tpm2_hash_alg_to_size(tpm2_hash_algorithms[i]), result->hash + i);
r = event_log_predict_pcrs(
el,
context,
result,
/* component_index= */ 0,
pcr,
/* path= */ NULL);
if (r < 0)
return r;
}
return 0;
}
VERB_NOARG(verb_predict, "predict",
"Predict PCR values");
static int verb_predict(int argc, char *argv[], uintptr_t _data, void *userdata) {
_cleanup_(tpm2_pcr_prediction_done) Tpm2PCRPrediction context = {
arg_pcr_mask != 0 ? arg_pcr_mask : DEFAULT_PCR_MASK,
};
_cleanup_(event_log_freep) EventLog *el = NULL;
ssize_t count;
int r;
r = event_log_load_and_process(&el);
if (r < 0)
return r;
count = event_log_calculate_component_combinations(el);
if (count < 0)
return count;
log_info("%zi combinations of components.", count);
r = event_log_reduce_to_safe_pcrs(el, &context.pcrs);
if (r < 0)
return r;
r = tpm2_pcr_prediction_run(el, &context);
if (r < 0)
return r;
return event_log_show_predictions(&context, el->primary_algorithm);
}
static int remove_policy_file(const char *path) {
assert(path);
if (unlink(path) < 0) {
if (errno == ENOENT)
return 0;
return log_error_errno(errno, "Failed to remove policy file '%s': %m", path);
}
log_info("Removed policy file '%s'.", path);
return 1;
}
static int determine_boot_policy_file(char **ret_path, char **ret_credential_name) {
int r;
_cleanup_free_ char *path = NULL;
r = get_global_boot_credentials_path(&path);
if (r < 0)
return r;
if (r == 0) {
if (ret_path)
*ret_path = NULL;
if (ret_credential_name)
*ret_credential_name = NULL;
return 0; /* not found! */
}
sd_id128_t machine_id;
r = sd_id128_get_machine(&machine_id);
if (r < 0)
return log_error_errno(r, "Failed to read machine ID: %m");
r = boot_entry_token_ensure(
/* root= */ NULL,
/* conf_root= */ NULL,
machine_id,
/* machine_id_is_random= */ false,
&arg_entry_token_type,
&arg_entry_token);
if (r < 0)
return r;
_cleanup_free_ char *fn = strjoin("pcrlock.", arg_entry_token, ".cred");
if (!fn)
return log_oom();
if (!filename_is_valid(fn))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential name '%s' would not be a valid file name, refusing.", fn);
_cleanup_free_ char *joined = NULL;
if (ret_path) {
joined = path_join(path, fn);
if (!joined)
return log_oom();
}
_cleanup_free_ char *cn = NULL;
if (ret_credential_name) {
/* The .cred suffix of the file is stripped when PID 1 imports the credential, hence exclude it from
* the embedded credential name. */
cn = strjoin("pcrlock.", arg_entry_token);
if (!cn)
return log_oom();
ascii_strlower(cn); /* lowercase this file, no matter what, since stored on VFAT, and we don't want
* to run into case change incompatibilities */
}
if (ret_path)
*ret_path = TAKE_PTR(joined);
if (ret_credential_name)
*ret_credential_name = TAKE_PTR(cn);
return 1; /* found! */
}
static int write_boot_policy_file(const char *json_text) {
_cleanup_free_ char *boot_policy_file = NULL, *credential_name = NULL;
int r;
assert(json_text);
r = determine_boot_policy_file(&boot_policy_file, &credential_name);
if (r < 0)
return r;
if (r == 0) {
log_info("Did not find XBOOTLDR/ESP partition, not writing boot policy file.");
return 0;
}
_cleanup_(iovec_done) struct iovec encoded = {};
r = encrypt_credential_and_warn(
CRED_AES256_GCM_BY_NULL,
credential_name,
now(CLOCK_REALTIME),
/* not_after= */ USEC_INFINITY,
/* tpm2_device= */ NULL,
/* tpm2_hash_pcr_mask= */ 0,
/* tpm2_pubkey_path= */ NULL,
/* tpm2_pubkey_pcr_mask= */ 0,
UID_INVALID,
&IOVEC_MAKE_STRING(json_text),
CREDENTIAL_ALLOW_NULL,
&encoded);
if (r < 0)
return log_error_errno(r, "Failed to encode policy as credential: %m");
r = write_base64_file_at(
AT_FDCWD,
boot_policy_file,
&encoded,
WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_SYNC|WRITE_STRING_FILE_MKDIR_0755|WRITE_STRING_FILE_LABEL);
if (r < 0)
return log_error_errno(r, "Failed to write boot policy file to '%s': %m", boot_policy_file);
log_info("Written new boot policy to '%s'.", boot_policy_file);
return 1;
}
static int make_policy(bool force, RecoveryPinMode recovery_pin_mode) {
int r;
/* Here's how this all works: after predicting all possible PCR values for next boot (with
* alternatives) we'll calculate a policy from it as a combination of PolicyPCR + PolicyOR
* expressions. This is then stored in an NV index. When a component of the boot process is changed a
* new prediction is made and the NV index updated (which automatically invalidates any older
* policies).
*
* Whenever we want to lock an encrypted object (for example FDE) against this policy, we'll use a
* PolicyAuthorizeNV expression that pins the NV index in the policy, and permits access to any
* policies matching the current NV index contents.
*
* We grant world-readable read access to the NV index. Write access is controlled by a PIN (which we
* either generate locally or which the user can provide us with) which can also be used for
* recovery. This PIN is sealed to the TPM and is locked via PolicyAuthorizeNV to the NV index it
* protects (i.e. we dogfood 🌭 🐶 hard here). This means in order to update such a policy we need
* the policy to pass.
*
* Information about the used NV Index, the SRK of the TPM, the sealed PIN and the current PCR
* prediction data are stored in a JSON file in /var/lib/. In order to be able to unlock root disks
* this data must be also copied to the ESP so that it is available to the initrd. The data is not
* sensitive, as SRK and NV index are pinned by it, and the prediction data must match the NV index
* to be useful. */
usec_t start_usec = now(CLOCK_MONOTONIC);
_cleanup_(event_log_freep) EventLog *el = NULL;
r = event_log_load_and_process(&el);
if (r < 0)
return r;
_cleanup_(tpm2_pcr_prediction_done) Tpm2PCRPrediction new_prediction = {
arg_pcr_mask != 0 ? arg_pcr_mask : DEFAULT_PCR_MASK,
};
r = event_log_reduce_to_safe_pcrs(el, &new_prediction.pcrs);
if (r < 0)
return r;
if (!force && new_prediction.pcrs == 0)
log_notice("Set of PCRs to use for policy is empty. Generated policy will not provide any protection in its current form. Proceeding.");
usec_t predict_start_usec = now(CLOCK_MONOTONIC);
r = tpm2_pcr_prediction_run(el, &new_prediction);
if (r < 0)
return r;
log_debug("Predicted future PCRs in %s.", FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), predict_start_usec), 1));
_cleanup_(sd_json_variant_unrefp) sd_json_variant *new_prediction_json = NULL;
r = tpm2_pcr_prediction_to_json(&new_prediction, el->primary_algorithm, &new_prediction_json);
if (r < 0)
return r;
if (DEBUG_LOGGING)
(void) sd_json_variant_dump(new_prediction_json, SD_JSON_FORMAT_PRETTY_AUTO|SD_JSON_FORMAT_COLOR_AUTO, stderr, NULL);
/* v257 and older mistakenly used --pcrlock= for the path. To keep backward compatibility, let's fallback to it when
* --policy= is unspecified but --pcrlock is specified. */
if (!arg_policy_path && arg_pcrlock_path) {
log_notice("Specified --pcrlock= option for make-policy command. Please use --policy= instead.");
arg_policy_path = strdup(arg_pcrlock_path);
if (!arg_policy_path)
return log_oom();
}
_cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy old_policy = {};
r = tpm2_pcrlock_policy_load(arg_policy_path, &old_policy);
if (r < 0)
return r;
bool have_old_policy = r > 0;
/* When we update the policy the old serializations for NV, SRK, PIN remain the same */
_cleanup_(iovec_done) struct iovec
nv_blob = TAKE_STRUCT(old_policy.nv_handle),
nv_public_blob = TAKE_STRUCT(old_policy.nv_public),
srk_blob = TAKE_STRUCT(old_policy.srk_handle),
pin_public = TAKE_STRUCT(old_policy.pin_public),
pin_private = TAKE_STRUCT(old_policy.pin_private);
if (have_old_policy) {
if (arg_nv_index != 0 && old_policy.nv_index != arg_nv_index)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Stored policy references different NV index (0x%x) than specified (0x%x), refusing.", old_policy.nv_index, arg_nv_index);
if (!force &&
old_policy.algorithm == el->primary_algorithm &&
tpm2_pcr_prediction_equal(&old_policy.prediction, &new_prediction, el->primary_algorithm)) {
log_info("Prediction is identical to current policy, skipping update.");
return 0; /* NOP */
}
}
_cleanup_(tpm2_context_unrefp) Tpm2Context *tc = NULL;
r = tpm2_context_new_or_warn(/* device= */ NULL, &tc);
if (r < 0)
return r;
if (!tpm2_supports_command(tc, TPM2_CC_PolicyAuthorizeNV))
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 does not support PolicyAuthorizeNV command, refusing.");
if (!tpm2_supports_alg(tc, TPM2_ALG_SHA256))
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 does not support SHA-256 hash algorithm, refusing.");
_cleanup_(tpm2_handle_freep) Tpm2Handle *srk_handle = NULL;
r = tpm2_deserialize(
tc,
&srk_blob,
&srk_handle);
if (r < 0)
return log_error_errno(r, "Failed to deserialize SRK TR: %m");
if (r == 0) {
r = tpm2_get_or_create_srk(
tc,
/* session= */ NULL,
/* ret_public= */ NULL,
/* ret_name= */ NULL,
/* ret_qname= */ NULL,
&srk_handle);
if (r < 0)
return log_error_errno(r, "Failed to install SRK: %m");
}
_cleanup_(tpm2_handle_freep) Tpm2Handle *encryption_session = NULL;
r = tpm2_make_encryption_session(
tc,
srk_handle,
/* bind_key= */ &TPM2_HANDLE_NONE,
&encryption_session);
if (r < 0)
return log_error_errno(r, "Failed to allocate encryption session: %m");
/* Acquire a recovery PIN, either from the user, or create a randomized one */
_cleanup_(erase_and_freep) char *pin = NULL;
if (recovery_pin_mode == RECOVERY_PIN_QUERY) {
r = getenv_steal_erase("PIN", &pin);
if (r < 0)
return log_error_errno(r, "Failed to acquire PIN from environment: %m");
if (r == 0) {
_cleanup_strv_free_erase_ char **l = NULL;
AskPasswordRequest req = {
.tty_fd = -EBADF,
.message = "Recovery PIN",
.id = "pcrlock-recovery-pin",
.credential = "pcrlock.recovery-pin",
.until = USEC_INFINITY,
.hup_fd = -EBADF,
};
r = ask_password_auto(
&req,
/* flags= */ 0,
&l);
if (r < 0)
return log_error_errno(r, "Failed to query for recovery PIN: %m");
if (strv_length(l) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Expected a single PIN only.");
pin = TAKE_PTR(l[0]);
l = mfree(l);
}
} else if (!have_old_policy) {
r = make_recovery_key(&pin);
if (r < 0)
return log_error_errno(r, "Failed to generate a randomized recovery PIN: %m");
if (recovery_pin_mode == RECOVERY_PIN_SHOW)
printf("%s Selected recovery PIN is: %s%s%s\n",
glyph(GLYPH_LOCK_AND_KEY),
ansi_highlight_cyan(),
pin,
ansi_normal());
}
_cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
TPM2_HANDLE nv_index = 0;
r = tpm2_deserialize(tc, &nv_blob, &nv_handle);
if (r < 0)
return log_error_errno(r, "Failed to deserialize NV index TR: %m");
if (r > 0)
nv_index = old_policy.nv_index;
TPM2B_AUTH auth = {};
CLEANUP_ERASE(auth);
if (pin) {
r = tpm2_auth_value_from_pin(TPM2_ALG_SHA256, pin, &auth);
if (r < 0)
return log_error_errno(r, "Failed to hash PIN: %m");
} else {
assert(iovec_is_set(&pin_public));
assert(iovec_is_set(&pin_private));
log_debug("Retrieving PIN from sealed data.");
usec_t pin_start_usec = now(CLOCK_MONOTONIC);
_cleanup_(iovec_done_erase) struct iovec secret = {};
for (unsigned attempt = 0;; attempt++) {
_cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
r = tpm2_make_policy_session(
tc,
srk_handle,
encryption_session,
&policy_session);
if (r < 0)
return log_error_errno(r, "Failed to allocate policy session: %m");
r = tpm2_policy_super_pcr(
tc,
policy_session,
&old_policy.prediction,
old_policy.algorithm);
if (r == -EUCLEAN) {
if (attempt >= PCRLOCK_RETRY_UNSEAL_MAX)
return log_error_errno(r,
"PCR values kept changing while submitting the policy, giving up after %u attempts. "
"Something on this system extends a PCR continuously.",
attempt + 1);
log_debug("Trying again (attempt %u), as PCR values changed while submitting the policy.", attempt + 1);
continue;
}
if (r < 0)
return r;
r = tpm2_policy_authorize_nv(
tc,
policy_session,
nv_handle,
NULL);
if (r < 0)
return log_error_errno(r, "Failed to submit AuthorizeNV policy: %m");
r = tpm2_unseal_data(
tc,
&pin_public,
&pin_private,
srk_handle,
policy_session,
encryption_session,
&secret);
if (r < 0 && (r != -ESTALE || attempt >= PCRLOCK_RETRY_UNSEAL_MAX))
return log_error_errno(r, "Failed to unseal PIN: %m");
if (r == 0)
break;
log_debug("Trying again (attempt %u), as PCR values changed during unlock attempt.", attempt + 1);
}
if (secret.iov_len > sizeof_field(TPM2B_AUTH, buffer))
return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Decrypted PIN too large.");
auth = (TPM2B_AUTH) {
.size = secret.iov_len,
};
memcpy_safe(auth.buffer, secret.iov_base, secret.iov_len);
log_info("Retrieved PIN from TPM2 in %s.", FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), pin_start_usec), 1));
}
/* Now convert the PIN into an HMAC-SHA256 key that we can use in PolicySigned to protect access to the nvindex with */
_cleanup_(tpm2_handle_freep) Tpm2Handle *pin_handle = NULL;
r = tpm2_hmac_key_from_pin(tc, encryption_session, &auth, &pin_handle);
if (r < 0)
return r;
TPM2B_NV_PUBLIC nv_public = {};
usec_t nv_index_start_usec = now(CLOCK_MONOTONIC);
if (!iovec_is_set(&nv_blob)) {
_cleanup_(Esys_Freep) TPM2B_NAME *pin_name = NULL;
r = tpm2_get_name(
tc,
pin_handle,
&pin_name);
if (r < 0)
return log_error_errno(r, "Failed to get name of PIN from TPM2: %m");
TPM2B_DIGEST recovery_policy_digest = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
r = tpm2_calculate_policy_signed(&recovery_policy_digest, pin_name);
if (r < 0)
return log_error_errno(r, "Failed to calculate PolicySigned policy: %m");
log_debug("Allocating NV index to write PCR policy to...");
r = tpm2_define_policy_nv_index(
tc,
encryption_session,
arg_nv_index,
&recovery_policy_digest,
&nv_index,
&nv_handle,
&nv_public);
if (r == -EEXIST)
return log_error_errno(r, "NV index 0x%" PRIx32 " already allocated.", arg_nv_index);
if (r < 0)
return log_error_errno(r, "Failed to allocate NV index: %m");
}
_cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
r = tpm2_make_policy_session(
tc,
srk_handle,
encryption_session,
&policy_session);
if (r < 0)
return log_error_errno(r, "Failed to allocate policy session: %m");
r = tpm2_policy_signed_hmac_sha256(
tc,
policy_session,
pin_handle,