|
43 | 43 | #include <sys/vfs.h>
|
44 | 44 | #include <sys/utsname.h>
|
45 | 45 | #include <sys/resource.h>
|
| 46 | +#include <sys/socket.h> |
| 47 | +#include <linux/if_alg.h> |
| 48 | +#include <linux/socket.h> |
46 | 49 | #include <libelf.h>
|
47 | 50 | #include <gelf.h>
|
48 | 51 | #include <zlib.h>
|
@@ -14217,3 +14220,59 @@ void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
|
14217 | 14220 | free(s->progs);
|
14218 | 14221 | free(s);
|
14219 | 14222 | }
|
| 14223 | + |
| 14224 | +int libbpf_sha256(const void *data, size_t data_sz, void *sha_out, size_t sha_out_sz) |
| 14225 | +{ |
| 14226 | + struct sockaddr_alg sa = { |
| 14227 | + .salg_family = AF_ALG, |
| 14228 | + .salg_type = "hash", |
| 14229 | + .salg_name = "sha256" |
| 14230 | + }; |
| 14231 | + int sock_fd = -1; |
| 14232 | + int op_fd = -1; |
| 14233 | + int err = 0; |
| 14234 | + |
| 14235 | + if (sha_out_sz != SHA256_DIGEST_LENGTH) { |
| 14236 | + pr_warn("sha_out_sz should be exactly 32 bytes for a SHA256 digest"); |
| 14237 | + return -EINVAL; |
| 14238 | + } |
| 14239 | + |
| 14240 | + sock_fd = socket(AF_ALG, SOCK_SEQPACKET, 0); |
| 14241 | + if (sock_fd < 0) { |
| 14242 | + err = -errno; |
| 14243 | + pr_warn("failed to create AF_ALG socket for SHA256: %s\n", errstr(err)); |
| 14244 | + return err; |
| 14245 | + } |
| 14246 | + |
| 14247 | + if (bind(sock_fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) { |
| 14248 | + err = -errno; |
| 14249 | + pr_warn("failed to bind to AF_ALG socket for SHA256: %s\n", errstr(err)); |
| 14250 | + goto out; |
| 14251 | + } |
| 14252 | + |
| 14253 | + op_fd = accept(sock_fd, NULL, 0); |
| 14254 | + if (op_fd < 0) { |
| 14255 | + err = -errno; |
| 14256 | + pr_warn("failed to accept from AF_ALG socket for SHA256: %s\n", errstr(err)); |
| 14257 | + goto out; |
| 14258 | + } |
| 14259 | + |
| 14260 | + if (write(op_fd, data, data_sz) != data_sz) { |
| 14261 | + err = -errno; |
| 14262 | + pr_warn("failed to write data to AF_ALG socket for SHA256: %s\n", errstr(err)); |
| 14263 | + goto out; |
| 14264 | + } |
| 14265 | + |
| 14266 | + if (read(op_fd, sha_out, SHA256_DIGEST_LENGTH) != SHA256_DIGEST_LENGTH) { |
| 14267 | + err = -errno; |
| 14268 | + pr_warn("failed to read SHA256 from AF_ALG socket: %s\n", errstr(err)); |
| 14269 | + goto out; |
| 14270 | + } |
| 14271 | + |
| 14272 | +out: |
| 14273 | + if (op_fd >= 0) |
| 14274 | + close(op_fd); |
| 14275 | + if (sock_fd >= 0) |
| 14276 | + close(sock_fd); |
| 14277 | + return err; |
| 14278 | +} |
0 commit comments