1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2026 Isovalent */ 3 4 #include <linux/bpf.h> 5 #include <linux/cred.h> 6 #include <linux/err.h> 7 #include <linux/init.h> 8 #include <linux/key.h> 9 #include <linux/moduleparam.h> 10 #include <linux/slab.h> 11 12 #undef MODULE_PARAM_PREFIX 13 #define MODULE_PARAM_PREFIX "bpf." 14 15 static struct key *bpf_keyring; 16 17 static bool bpf_keyring_unsealed __ro_after_init; 18 module_param_named(keyring_unsealed, bpf_keyring_unsealed, bool, 0444); 19 MODULE_PARM_DESC(keyring_unsealed, "Leave the bpf keyring unsealed"); 20 21 bool bpf_keyring_enforced(void) 22 { 23 return bpf_keyring_unsealed; 24 } 25 26 struct bpf_key *bpf_lookup_keyring(void) 27 { 28 struct bpf_key *bkey; 29 30 if (!bpf_keyring) 31 return NULL; 32 if (!READ_ONCE(bpf_keyring->keys.nr_leaves_on_tree) || 33 !READ_ONCE(bpf_keyring->restrict_link)) 34 return NULL; 35 36 bkey = kmalloc_obj(*bkey); 37 if (!bkey) 38 return NULL; 39 40 bkey->key = bpf_keyring; 41 bkey->has_ref = false; 42 return bkey; 43 } 44 45 static int __init bpf_keyring_init(void) 46 { 47 struct key *keyring; 48 49 keyring = keyring_alloc(".bpf", 50 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, 51 current_cred(), KEY_POS_SEARCH | 52 KEY_USR_VIEW | KEY_USR_READ | 53 KEY_USR_WRITE | KEY_USR_SEARCH | 54 KEY_USR_SETATTR, KEY_ALLOC_NOT_IN_QUOTA, 55 NULL, NULL); 56 if (IS_ERR(keyring)) { 57 pr_err("bpf: cannot allocate bpf keyring: %ld\n", 58 PTR_ERR(keyring)); 59 return 0; 60 } 61 if (!bpf_keyring_unsealed && 62 keyring_restrict(make_key_ref(keyring, true), NULL, NULL)) { 63 pr_err("bpf: cannot seal bpf keyring\n"); 64 key_revoke(keyring); 65 key_put(keyring); 66 return 0; 67 } 68 69 bpf_keyring = keyring; 70 key_register_bpf_keyring(keyring); 71 return 0; 72 } 73 late_initcall(bpf_keyring_init); 74