tools/testing/selftests/bpf/progs/lsm_cgroup.c

Source file repositories/reference/linux-study-clean/tools/testing/selftests/bpf/progs/lsm_cgroup.c

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/bpf/progs/lsm_cgroup.c
Extension
.c
Size
4929 bytes
Lines
223
Domain
Support Tooling And Documentation
Bucket
tools
Inferred role
Support Tooling And Documentation: implementation source
Status
source implementation candidate

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

// SPDX-License-Identifier: GPL-2.0

#include "vmlinux.h"
#include "bpf_tracing_net.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

char _license[] SEC("license") = "GPL";

extern bool CONFIG_SECURITY_SELINUX __kconfig __weak;
extern bool CONFIG_SECURITY_SMACK __kconfig __weak;
extern bool CONFIG_SECURITY_APPARMOR __kconfig __weak;

#ifndef AF_PACKET
#define AF_PACKET 17
#endif

#ifndef AF_UNIX
#define AF_UNIX 1
#endif

#ifndef EPERM
#define EPERM 1
#endif

struct {
	__uint(type, BPF_MAP_TYPE_CGROUP_STORAGE);
	__type(key, __u64);
	__type(value, __u64);
} cgroup_storage SEC(".maps");

int called_socket_post_create;
int called_socket_post_create2;
int called_socket_bind;
int called_socket_bind2;
int called_socket_alloc;
int called_socket_clone;
int skipcap_retval = -4095;
int socket_retval = -4095;

static __always_inline int test_local_storage(void)
{
	__u64 *val;

	val = bpf_get_local_storage(&cgroup_storage, 0);
	if (!val)
		return 0;
	*val += 1;

	return 1;
}

static __always_inline int real_create(struct socket *sock, int family,
				       int protocol)
{
	struct sock *sk;
	int prio = 123;

	/* Reject non-tx-only AF_PACKET. */
	if (family == AF_PACKET && protocol != 0)
		return 0; /* EPERM */

	sk = sock->sk;
	if (!sk)
		return 1;

	/* The rest of the sockets get default policy. */
	if (bpf_setsockopt(sk, SOL_SOCKET, SO_PRIORITY, &prio, sizeof(prio)))
		return 0; /* EPERM */

	/* Make sure bpf_getsockopt is allowed and works. */
	prio = 0;
	if (bpf_getsockopt(sk, SOL_SOCKET, SO_PRIORITY, &prio, sizeof(prio)))
		return 0; /* EPERM */
	if (prio != 123)
		return 0; /* EPERM */

	/* Can access cgroup local storage. */
	if (!test_local_storage())
		return 0; /* EPERM */

	return 1;
}

/* __cgroup_bpf_run_lsm_socket */
SEC("lsm_cgroup/socket_post_create")
int BPF_PROG(socket_post_create, struct socket *sock, int family,
	     int type, int protocol, int kern)
{
	called_socket_post_create++;

Annotation

Implementation Notes