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 struct bpf_key *bpf_lookup_keyring(void) 22 { 23 struct bpf_key *bkey; 24 25 if (!bpf_keyring) 26 return NULL; 27 if (!READ_ONCE(bpf_keyring->keys.nr_leaves_on_tree) || 28 !READ_ONCE(bpf_keyring->restrict_link)) 29 return NULL; 30 31 bkey = kmalloc_obj(*bkey); 32 if (!bkey) 33 return NULL; 34 35 bkey->key = bpf_keyring; 36 bkey->has_ref = false; 37 return bkey; 38 } 39 40 static int __init bpf_keyring_init(void) 41 { 42 struct key *keyring; 43 44 keyring = keyring_alloc(".bpf", 45 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, 46 current_cred(), KEY_POS_SEARCH | 47 KEY_USR_VIEW | KEY_USR_READ | 48 KEY_USR_WRITE | KEY_USR_SEARCH | 49 KEY_USR_SETATTR, KEY_ALLOC_NOT_IN_QUOTA, 50 NULL, NULL); 51 if (IS_ERR(keyring)) { 52 pr_err("bpf: cannot allocate bpf keyring: %ld\n", 53 PTR_ERR(keyring)); 54 return 0; 55 } 56 if (!bpf_keyring_unsealed && 57 keyring_restrict(make_key_ref(keyring, true), NULL, NULL)) { 58 pr_err("bpf: cannot seal bpf keyring\n"); 59 key_revoke(keyring); 60 key_put(keyring); 61 return 0; 62 } 63 64 bpf_keyring = keyring; 65 key_register_bpf_keyring(keyring); 66 return 0; 67 } 68 late_initcall(bpf_keyring_init); 69