// SPDX-License-Identifier: GPL-2.01/*2* Copyright (C) 2020-2024 Microsoft Corporation. All rights reserved.3*/45#include "digest.h"67/**8* ipe_digest_parse() - parse a digest in IPE's policy.9* @valstr: Supplies the string parsed from the policy.10*11* Digests in IPE are defined in a standard way:12* <alg_name>:<hex>13*14* Use this function to create a property to parse the digest15* consistently. The parsed digest will be saved in @value in IPE's16* policy.17*18* Return: The parsed digest_info structure on success. If an error occurs,19* the function will return the error value (via ERR_PTR).20*/21struct digest_info *ipe_digest_parse(const char *valstr)22{23struct digest_info *info = NULL;24char *sep, *raw_digest;25size_t raw_digest_len;26u8 *digest = NULL;27char *alg = NULL;28int rc = 0;2930info = kzalloc(sizeof(*info), GFP_KERNEL);31if (!info)32return ERR_PTR(-ENOMEM);3334sep = strchr(valstr, ':');35if (!sep) {36rc = -EBADMSG;37goto err;38}3940alg = kstrndup(valstr, sep - valstr, GFP_KERNEL);41if (!alg) {42rc = -ENOMEM;43goto err;44}4546raw_digest = sep + 1;47raw_digest_len = strlen(raw_digest);4849info->digest_len = (raw_digest_len + 1) / 2;50digest = kzalloc(info->digest_len, GFP_KERNEL);51if (!digest) {52rc = -ENOMEM;53goto err;54}5556rc = hex2bin(digest, raw_digest, info->digest_len);57if (rc < 0) {58rc = -EINVAL;59goto err;60}6162info->alg = alg;63info->digest = digest;64return info;6566err:67kfree(alg);68kfree(digest);69kfree(info);70return ERR_PTR(rc);71}7273/**74* ipe_digest_eval() - evaluate an IPE digest against another digest.75* @expected: Supplies the policy-provided digest value.76* @digest: Supplies the digest to compare against the policy digest value.77*78* Return:79* * %true - digests match80* * %false - digests do not match81*/82bool ipe_digest_eval(const struct digest_info *expected,83const struct digest_info *digest)84{85return (expected->digest_len == digest->digest_len) &&86(!strcmp(expected->alg, digest->alg)) &&87(!memcmp(expected->digest, digest->digest, expected->digest_len));88}8990/**91* ipe_digest_free() - free an IPE digest.92* @info: Supplies a pointer the policy-provided digest to free.93*/94void ipe_digest_free(struct digest_info *info)95{96if (IS_ERR_OR_NULL(info))97return;9899kfree(info->alg);100kfree(info->digest);101kfree(info);102}103104/**105* ipe_digest_audit() - audit a digest that was sourced from IPE's policy.106* @ab: Supplies the audit_buffer to append the formatted result.107* @info: Supplies a pointer to source the audit record from.108*109* Digests in IPE are audited in this format:110* <alg_name>:<hex>111*/112void ipe_digest_audit(struct audit_buffer *ab, const struct digest_info *info)113{114audit_log_untrustedstring(ab, info->alg);115audit_log_format(ab, ":");116audit_log_n_hex(ab, info->digest, info->digest_len);117}118119120