1// SPDX-License-Identifier: GPL-2.0
2/* Copyright (c) 2024 Meta Platforms, Inc. and affiliates. */
3
4#include "vmlinux.h"
5#include "bpf_tracing_net.h"
6#include <bpf/bpf_helpers.h>
7#include <bpf/bpf_endian.h>
8#include <bpf/bpf_tracing.h>
9#include "bpf_misc.h"
10#include "bpf_kfuncs.h"
11#include "crypto_common.h"
12
13const volatile unsigned int len = 16;
14char cipher[128] = {};
15u32 key_len, authsize;
16char dst[256] = {};
17u8 key[256] = {};
18long hits = 0;
19int status;
20
21SEC("syscall")
22int crypto_setup(void *args)
23{
24	struct bpf_crypto_ctx *cctx;
25	struct bpf_crypto_params params = {
26		.type = "skcipher",
27		.key_len = key_len,
28		.authsize = authsize,
29	};
30	int err = 0;
31
32	status = 0;
33
34	if (!cipher[0] || !key_len || key_len > 256) {
35		status = -EINVAL;
36		return 0;
37	}
38
39	__builtin_memcpy(&params.algo, cipher, sizeof(cipher));
40	__builtin_memcpy(&params.key, key, sizeof(key));
41	cctx = bpf_crypto_ctx_create(&params, sizeof(params), &err);
42
43	if (!cctx) {
44		status = err;
45		return 0;
46	}
47
48	err = crypto_ctx_insert(cctx);
49	if (err && err != -EEXIST)
50		status = err;
51
52	return 0;
53}
54
55SEC("tc")
56int crypto_encrypt(struct __sk_buff *skb)
57{
58	struct __crypto_ctx_value *v;
59	struct bpf_crypto_ctx *ctx;
60	struct bpf_dynptr psrc, pdst, iv;
61
62	v = crypto_ctx_value_lookup();
63	if (!v) {
64		status = -ENOENT;
65		return 0;
66	}
67
68	ctx = v->ctx;
69	if (!ctx) {
70		status = -ENOENT;
71		return 0;
72	}
73
74	bpf_dynptr_from_skb(skb, 0, &psrc);
75	bpf_dynptr_from_mem(dst, len, 0, &pdst);
76	bpf_dynptr_from_mem(dst, 0, 0, &iv);
77
78	status = bpf_crypto_encrypt(ctx, &psrc, &pdst, &iv);
79	__sync_add_and_fetch(&hits, 1);
80
81	return 0;
82}
83
84SEC("tc")
85int crypto_decrypt(struct __sk_buff *skb)
86{
87	struct bpf_dynptr psrc, pdst, iv;
88	struct __crypto_ctx_value *v;
89	struct bpf_crypto_ctx *ctx;
90
91	v = crypto_ctx_value_lookup();
92	if (!v)
93		return -ENOENT;
94
95	ctx = v->ctx;
96	if (!ctx)
97		return -ENOENT;
98
99	bpf_dynptr_from_skb(skb, 0, &psrc);
100	bpf_dynptr_from_mem(dst, len, 0, &pdst);
101	bpf_dynptr_from_mem(dst, 0, 0, &iv);
102
103	status = bpf_crypto_decrypt(ctx, &psrc, &pdst, &iv);
104	__sync_add_and_fetch(&hits, 1);
105
106	return 0;
107}
108
109char __license[] SEC("license") = "GPL";
110