[PATCH 01/12] bpf: Implement an internal helper for SHA256 hashing
Eric Biggers
ebiggers at kernel.org
Thu Jun 12 19:07:39 UTC 2025
On Sat, Jun 07, 2025 at 01:29:03AM +0200, KP Singh wrote:
> This patch introduces bpf_sha256, an internal helper function
> that wraps the standard kernel crypto API to compute SHA256 digests of
> the program insns and map content
>
> Signed-off-by: KP Singh <kpsingh at kernel.org>
> ---
> include/linux/bpf.h | 1 +
> kernel/bpf/core.c | 39 +++++++++++++++++++++++++++++++++++++++
> 2 files changed, 40 insertions(+)
>
> diff --git a/include/linux/bpf.h b/include/linux/bpf.h
> index 5b25d278409b..d5ae43b36e68 100644
> --- a/include/linux/bpf.h
> +++ b/include/linux/bpf.h
> @@ -2086,6 +2086,7 @@ static inline bool map_type_contains_progs(struct bpf_map *map)
> }
>
> bool bpf_prog_map_compatible(struct bpf_map *map, const struct bpf_prog *fp);
> +int bpf_sha256(u8 *data, size_t data_size, u8 *output_digest);
> int bpf_prog_calc_tag(struct bpf_prog *fp);
>
> const struct bpf_func_proto *bpf_get_trace_printk_proto(void);
> diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
> index a3e571688421..607d5322ef94 100644
> --- a/kernel/bpf/core.c
> +++ b/kernel/bpf/core.c
> @@ -17,6 +17,7 @@
> * Kris Katterjohn - Added many additional checks in bpf_check_classic()
> */
>
> +#include <crypto/hash.h>
> #include <uapi/linux/btf.h>
> #include <linux/filter.h>
> #include <linux/skbuff.h>
> @@ -287,6 +288,44 @@ void __bpf_prog_free(struct bpf_prog *fp)
> vfree(fp);
> }
>
> +int bpf_sha256(u8 *data, size_t data_size, u8 *output_digest)
> +{
> + struct crypto_shash *tfm;
> + struct shash_desc *shash_desc;
> + size_t desc_size;
> + int ret = 0;
> +
> + tfm = crypto_alloc_shash("sha256", 0, 0);
> + if (IS_ERR(tfm))
> + return PTR_ERR(tfm);
> +
> +
> + desc_size = crypto_shash_descsize(tfm) + sizeof(*shash_desc);
> + shash_desc = kmalloc(desc_size, GFP_KERNEL);
> + if (!shash_desc) {
> + crypto_free_shash(tfm);
> + return -ENOMEM;
> + }
> +
> + shash_desc->tfm = tfm;
> + ret = crypto_shash_init(shash_desc);
> + if (ret)
> + goto out_free_desc;
> +
> + ret = crypto_shash_update(shash_desc, data, data_size);
> + if (ret)
> + goto out_free_desc;
> +
> + ret = crypto_shash_final(shash_desc, output_digest);
> + if (ret)
> + goto out_free_desc;
> +
> +out_free_desc:
> + kfree(shash_desc);
> + crypto_free_shash(tfm);
> + return ret;
> +}
> +
You're looking for sha256() from <crypto/sha2.h>. Just use that instead.
You'll just need to select CRYPTO_LIB_SHA256.
- Eric
More information about the Linux-security-module-archive
mailing list