### SELinux Module Management with C Source: https://context7.com/topjohnwu/selinux/llms.txt Provides C code for managing SELinux policy modules using libsemanage. It demonstrates listing installed modules, retrieving their properties (name, priority, enabled status, language extension), and installing a module from a file. Dependencies include ``, ``, ``, and ``. The output shows an example of listed modules. ```c #include #include #include #include int main(int argc, char *argv[]) { semanage_handle_t *handle; semanage_module_info_t *modinfos = NULL; int modinfos_len = 0; handle = semanage_handle_create(); if (handle == NULL || semanage_connect(handle) < 0) { fprintf(stderr, "Failed to connect\n"); return 1; } /* List all installed modules */ if (semanage_module_list_all(handle, &modinfos, &modinfos_len) == 0) { printf("Installed modules (%d):\n", modinfos_len); for (int i = 0; i < modinfos_len && i < 10; i++) { const char *name = NULL; uint16_t priority = 0; int enabled = 0; const char *lang_ext = NULL; semanage_module_info_get_name(handle, &modinfos[i], &name); semanage_module_info_get_priority(handle, &modinfos[i], &priority); semanage_module_info_get_enabled(handle, &modinfos[i], &enabled); semanage_module_info_get_lang_ext(handle, &modinfos[i], &lang_ext); printf(" %s (priority=%u, enabled=%d, lang=%s)\n", name, priority, enabled, lang_ext); semanage_module_info_destroy(handle, &modinfos[i]); } free(modinfos); } /* Install a module from file (if provided) */ if (argc > 1) { printf("\nInstalling module: %s\n", argv[1]); if (semanage_begin_transaction(handle) >= 0) { if (semanage_module_install_file(handle, argv[1]) == 0) { printf("Module staged for installation\n"); semanage_commit(handle); } else { fprintf(stderr, "Failed to install module\n"); } } } semanage_disconnect(handle); semanage_handle_destroy(handle); return 0; } /* Output: Installed modules (245): base (priority=100, enabled=1, lang=cil) abrt (priority=400, enabled=1, lang=pp) */ ``` -------------------------------- ### Manage Process Security Context with libselinux (C) Source: https://context7.com/topjohnwu/selinux/llms.txt Provides C code examples for retrieving and setting the security context of the current process using `getcon()` and `setcon()`. It also shows how to get the context of another process by PID using `getpidcon()` and the previous context using `getprevcon()`. Remember to free the returned context strings using `freecon()`. ```c #include #include int main(void) { char *context = NULL; /* Get current process context */ if (getcon(&context) == 0) { printf("Current context: %s\n", context); freecon(context); } /* Get context of another process by PID */ char *pid_context = NULL; if (getpidcon(1, &pid_context) == 0) { /* PID 1 = init */ printf("Init process context: %s\n", pid_context); freecon(pid_context); } /* Get previous context (before last exec) */ char *prev_context = NULL; if (getprevcon(&prev_context) == 0 && prev_context != NULL) { printf("Previous context: %s\n", prev_context); freecon(prev_context); } return 0; } /* Output: Current context: unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 */ ``` -------------------------------- ### SELinux roletransition Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_role_statements.md An example demonstrating the roletransition statement in SELinux policy. This example authorizes the 'unconfined.role' to assume the 'msg_filter.role' role and then transition to it when dealing with 'process' types. It includes necessary type and roleallow definitions. ```secil (block ext_gateway (type process) (type exec) (roletype msg_filter.role process) (roleallow unconfined.role msg_filter.role) (roletransition unconfined.role exec process msg_filter.role) ) ``` -------------------------------- ### Manage File Security Context with libselinux (C) Source: https://context7.com/topjohnwu/selinux/llms.txt Illustrates how to get and set the SELinux security context of files using libselinux functions. Examples include `getfilecon()` for following symlinks, `lgetfilecon()` for operating on symlinks directly, and `setfilecon()` for applying a new context. Note that `setfilecon()` requires appropriate permissions. ```c #include #include #include int main(void) { const char *filepath = "/etc/passwd"; char *context = NULL; /* Get file context */ if (getfilecon(filepath, &context) > 0) { printf("Context of %s: %s\n", filepath, context); freecon(context); } /* Get context without following symlinks */ const char *link = "/etc/localtime"; if (lgetfilecon(link, &context) > 0) { printf("Context of symlink %s: %s\n", link, context); freecon(context); } /* Set file context (requires appropriate permissions) */ const char *newfile = "/tmp/selinux_test"; FILE *f = fopen(newfile, "w"); if (f) { fclose(f); if (setfilecon(newfile, "system_u:object_r:tmp_t:s0") == 0) { printf("Successfully set context on %s\n", newfile); } } return 0; } /* Output: Context of /etc/passwd: system_u:object_r:passwd_file_t:s0 */ ``` -------------------------------- ### Compile and Install SELinux Userspace Tools Source: https://github.com/topjohnwu/selinux/blob/master/CONTRIBUTING.md Builds and installs the SELinux userspace tools and libraries under a specified directory using make. The DESTDIR variable allows for staging installations. ```bash $ make DESTDIR=~/obj install install-pywrap ``` -------------------------------- ### Selinux permissionx Examples (ioctl kind) Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_class_and_permission_statements.md Provides examples of using the 'permissionx' statement with the 'ioctl' kind. These examples demonstrate defining ioctl permission sets using individual values, ranges, and logical expressions. ```secil (permissionx ioctl_1 (ioctl tcp_socket (0x2000 0x3000 0x4000))) (permissionx ioctl_2 (ioctl tcp_socket (range 0x6000 0x60FF))) (permissionx ioctl_3 (ioctl tcp_socket (and (range 0x8000 0x90FF) (not (range 0x8100 0x82FF))))) ``` -------------------------------- ### SELinux rolebounds Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_role_statements.md An example illustrating the rolebounds statement in SELinux policy. This example sets up a hierarchy where the 'test' role cannot have greater privileges than the 'unconfined.role'. It defines the 'test' role and then uses rolebounds within an 'unconfined' block. ```secil (role test) (block unconfined (role role) (rolebounds role .test) ) ``` -------------------------------- ### SELinux Rangetransition Rule Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_mls_labeling_statements.md This example demonstrates how to define sensitivities, levels, and level ranges, and then apply them in a rangetransition rule. It shows the transition of the range for 'sshd.exec' from 'init.process'. ```secil (sensitivity s0) (sensitivity s1) (sensitivityorder s0 s1) (category c0) ... (level systemlow (s0)) (level systemhigh (s1 (c0 c1 c2))) (levelrange low_high (systemlow systemhigh)) (rangetransition init.process sshd.exec process low_high) ``` -------------------------------- ### Selinux Allow Rule Examples Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_access_vector_rules.md Illustrates various permutations of Selinux 'allow' rules, demonstrating the use of different class definitions, classpermissionsets, classmaps, and classmappings. These examples cover anonymous and named class permissions. ```secil (class binder (impersonate call set_context_mgr transfer receive)) (class property_service (set)) (class zygote (specifyids specifyrlimits specifycapabilities specifyinvokewith specifyseinfo)) (classpermission cps_zygote) (classpermissionset cps_zygote (zygote (not (specifyids)))) (classmap android_classes (set_1 set_2 set_3)) (classmapping android_classes set_1 (binder (all))) (classmapping android_classes set_1 (property_service (set))) (classmapping android_classes set_1 (zygote (not (specifycapabilities)))) (classmapping android_classes set_2 (binder (impersonate call set_context_mgr transfer))) (classmapping android_classes set_2 (zygote (specifyids specifyrlimits specifycapabilities specifyinvokewith))) (classmapping android_classes set_3 cps_zygote) (classmapping android_classes set_3 (binder (impersonate call set_context_mgr))) (block av_rules (type type_1) (type type_2) (type type_3) (type type_4) (type type_5) (typeattribute all_types) (typeattributeset all_types (all)) ; These examples have named and anonymous classpermissionset's and ; classmap/classmapping statements (allow type_1 self (property_service (set))) ; anonymous (allow type_2 self (zygote (specifyids))) ; anonymous (allow type_3 self cps_zygote) ; named (allow type_4 self (android_classes (set_3))) ; classmap/classmapping (allow all_types all_types (android_classes (set_2))) ; classmap/classmapping ;; This rule will cause the build to fail unless --disable-neverallow ; (neverallow type_5 all_types (property_service (set))) (allow type_5 type_5 (property_service (set))) ``` -------------------------------- ### Install SELinux System-Wide (32-bit) Source: https://github.com/topjohnwu/selinux/blob/master/README.md Installs SELinux libraries, Python wrappers, and relabels the system for 32-bit architecture, potentially overwriting existing installations. This is a dangerous operation. ```shell make install install-pywrap relabel ``` -------------------------------- ### Build and Install SELinux Under a Private Directory Source: https://github.com/topjohnwu/selinux/blob/master/README.md Cleans previous builds, then compiles and installs SELinux libraries, utilities, and Python/Ruby wrappers into a specified private directory using make. ```shell make clean distclean make DESTDIR=~/obj install install-rubywrap install-pywrap ``` -------------------------------- ### Install SELinux System-Wide (x86_64) Source: https://github.com/topjohnwu/selinux/blob/master/README.md Installs SELinux libraries, Python wrappers, and relabels the system for x86_64 architecture, potentially overwriting existing installations. This is a dangerous operation. ```shell make LIBDIR=/usr/lib64 SHLIBDIR=/lib64 install install-pywrap relabel ``` -------------------------------- ### Selinux CIL Tunableif Example with Conditional Statements Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_conditional_statements.md An example demonstrating the 'tunableif' statement in CIL. This specific example conditionally includes a 'rangetransition' rule based on the 'range_trans_rule' tunable, preventing its addition to the policy if the tunable is false. ```secil (tunable range_trans_rule false) (block init (class process (process)) (type process) (tunableif range_trans_rule (true (rangetransition process sshd.exec process low_high) ) ) ; End tunableif ) ; End block ``` -------------------------------- ### Selinux Allow Rules Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_class_and_permission_statements.md Illustrates Selinux 'allow' rules within a 'block' context, demonstrating how different types are granted access to specific classes and sets. The comments show the resolved AV rules. ```secil (block map_example (type type_1) (type type_2) (type type_3) (allow type_1 self (android_classes (set_1))) (allow type_2 self (android_classes (set_2))) (allow type_3 self (android_classes (set_3))) ) ; The above will resolve to the following AV rules: ;; allow map_example.type_1 map_example.type_1 : binder { impersonate call set_context_mgr transfer receive } ; ;; allow map_example.type_1 map_example.type_1 : property_service set ; ;; allow map_example.type_1 map_example.type_1 : zygote { specifyids specifyrlimits specifyinvokewith specifyseinfo } ; ;; allow map_example.type_2 map_example.type_2 : binder { impersonate call set_context_mgr transfer } ; ;; allow map_example.type_2 map_example.type_2 : zygote { specifyids specifyrlimits specifycapabilities specifyinvokewith } ; ;; allow map_example.type_3 map_example.type_3 : binder { impersonate call set_context_mgr } ; ;; allow map_example.type_3 map_example.type_3 : zygote { specifyrlimits specifycapabilities specifyinvokewith specifyseinfo } ; ``` -------------------------------- ### CIL Global and Local Namespace Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_reference_guide.md Illustrates the use of global and local namespaces in CIL. It shows how to declare types within blocks and reference them using local prefixes (e.g., `file.tmpfs`) or global prefixes (e.g., `.tmpfs`). ```secil ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; This example has three namespace 'tmpfs' types declared: ; 1) Global .tmpfs ; 2) file.tmpfs ; 3) other_ns.tmpfs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; This type is the global tmpfs: (type tmpfs) (block file ; file namespace tmpfs (type tmpfs) (class file (open read write getattr)) ; This rule will reference the local namespace for src and tgt: (allow tmpfs tmpfs (file (open))) ; Resulting policy rule: ; allow file.tmpfs file.tmpfs : file.file open; ; This rule will reference the local namespace for src and global for tgt: (allow tmpfs .tmpfs (file (read))) ; Resulting policy rule: ; allow file.tmpfs tmpfs : file.file read; ; This rule will reference the global namespace for src and tgt: (allow .tmpfs .tmpfs (file (write))) ; Resulting policy rule: ; allow tmpfs tmpfs : file.file write; ; This rule will reference the other_ns namespace for src and ; local namespace for tgt: (allow other_ns.tmpfs tmpfs (file (getattr))) ; Resulting policy rule: ; allow other_ns.tmpfs file.tmpfs : file.file getattr; ) (block other_ns (type tmpfs) ) ``` -------------------------------- ### Selinux CIL booleanif Example with Kernel Policy Equivalence Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_conditional_statements.md Demonstrates the usage of the 'booleanif' statement in Selinux CIL, showing how to conditionally apply access rules based on boolean states. The example includes a direct translation to kernel policy language for comparison. ```secil (boolean disableAudio false) (booleanif disableAudio (false (allow process mediaserver.audio_device (chr_file_set (rw_file_perms))) ) ) (boolean disableAudioCapture false) ;;; if(!disableAudio && !disableAudioCapture) { (booleanif (and (not disableAudio) (not disableAudioCapture)) (true (allow process mediaserver.audio_capture_device (chr_file_set (rw_file_perms))) ) ) ``` -------------------------------- ### SELinux CIL Example Class and Property Service Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_class_and_permission_statements.md Illustrates the definition of a 'class' for binder operations and another for property service. These definitions are foundational for creating 'classpermissionset's and subsequently 'classmapping's. ```secil (class binder (impersonate call set_context_mgr transfer receive)) (class property_service (set)) ``` -------------------------------- ### Install SELinux Build Dependencies on Debian Source: https://github.com/topjohnwu/selinux/blob/master/README.md Installs essential development libraries and tools for compiling SELinux C libraries, programs, and Python/Ruby bindings on Debian-based systems using apt-get. ```shell # For C libraries and programs apt-get install --no-install-recommends --no-install-suggests \ bison \ flex \ gawk \ gcc \ gettext \ make \ libaudit-dev \ libbz2-dev \ libcap-dev \ libcap-ng-dev \ libcunit1-dev \ libglib2.0-dev \ libpcre2-dev \ pkgconf \ python3 \ systemd \ xmlto # For Python and Ruby bindings apt-get install --no-install-recommends --no-install-suggests \ python3-dev \ python3-pip \ python3-setuptools \ python3-wheel \ ruby-dev \ swig ``` -------------------------------- ### Selinux Typetransition Rule Examples Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_type_statements.md Demonstrates the 'typetransition' keyword in Selinux policy language for defining how types change based on source, target, class, and object name. Includes examples for process transitions, file object transitions, and name transitions. ```secil (macro domain_auto_trans ((type ARG1) (type ARG2) (type ARG3)) ; Allow the necessary permissions. (call domain_trans (ARG1 ARG2 ARG3)) ; Make the transition occur by default. (typetransition ARG1 ARG2 process ARG3) ) ``` ```secil (macro tmpfs_domain ((type ARG1)) (type tmpfs) (typeattributeset file_type (tmpfs)) (typetransition ARG1 file.tmpfs file tmpfs) (allow ARG1 tmpfs (file (read write execute execmod))) ) ``` ```secil (macro write_klog ((type ARG1)) (typetransition ARG1 device.device chr_file "__kmsg__" device.klog_device) (allow ARG1 device.klog_device (chr_file (create open write unlink))) (allow ARG1 device.device (dir (write add_name remove_name))) ) ``` -------------------------------- ### SELinux CIL 'in' Statement Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_container_statements.md An example demonstrating how to use the SELinux CIL 'in' statement to add rules to a specific container. This example adds 'dontaudit' and 'allow' rules for DNS packet operations to the 'system_server' container. ```secil (in system_server (dontaudit process secmark_demo.dns_packet (packet (send recv))) (allow process secmark_demo.dns_packet (packet (send recv))) ) ``` -------------------------------- ### Selinux MLS Validate Transition Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_constraint_statements.md Provides an example of an MLS validate transition statement in Selinux policy and its equivalent kernel policy language representation. ```secil ;; mlsvalidatetrans { file } ( l1 domby h2 ); ``` ```selinux (mlsvalidatetrans file (domby l1 h2)) ``` -------------------------------- ### Install SELinux Build Dependencies on Fedora Source: https://github.com/topjohnwu/selinux/blob/master/README.md Installs necessary development libraries and tools for building SELinux C libraries, programs, and Python/Ruby bindings on Fedora systems using dnf. ```shell # For C libraries and programs dnf install \ audit-libs-devel \ bison \ bzip2-devel \ CUnit-devel \ diffutils \ flex \ gcc \ gettext \ glib2-devel \ make \ libcap-devel \ libcap-ng-devel \ pam-devel \ pcre2-devel \ xmlto # For Python and Ruby bindings dnf install \ python3-devel \ python3-pip \ python3-setuptools \ python3-wheel \ ruby-devel \ swig ``` -------------------------------- ### Instantiate binder_call Macro in Selinux Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_call_macro_statements.md This example demonstrates how to instantiate the 'binder_call' macro within a CIL block. It shows how to replace macro arguments (ARG1, ARG2) with specific domain types. ```secil (block my_domain (call binder_call (appdomain binderservicedomain)) ) (macro binder_call ((type ARG1) (type ARG2)) (allow ARG1 ARG2 (binder (call transfer))) (allow ARG2 ARG1 (binder (transfer))) (allow ARG1 ARG2 (fd (use))) ) ``` -------------------------------- ### Selinux expandtypeattribute Example: Force Expansion Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_type_statements.md An example demonstrating how to use expandtypeattribute to forcibly expand a previously declared 'domain' type attribute by setting the expand_value to 'true'. ```secil (expandtypeattribute domain true) ``` -------------------------------- ### SELinux Context Example: Named Context for File Labeling (SECIL) Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_context_statement.md An example demonstrating the declaration of a named SELinux context 'runas_exec_context' and its subsequent use in a 'filecon' statement to label the '/system/bin/run-as' file. This illustrates how a named context resolves to a specific SELinux label. ```secil (context runas_exec_context (u object_r exec low_low)) (filecon "/system/bin/run-as" file runas_exec_context) ``` -------------------------------- ### Install SELinux Dependencies on Fedora Source: https://github.com/topjohnwu/selinux/blob/master/CONTRIBUTING.md Installs necessary development libraries and tools for building SELinux userspace components on a Fedora system using yum. This ensures all prerequisites are met before compilation. ```bash # yum install audit-libs-devel bison bzip2-devel dbus-devel dbus-glib-devel flex flex-devel flex-static glib2-devel libcap-devel libcap-ng-devel pam-devel pcre2-devel python-devel setools-devel swig ustr-devel ``` -------------------------------- ### Example SELinux CIL Policy with MLS Labeling Statements Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_mls_labeling_statements.md This example policy demonstrates the usage of various MLS labeling statements in SELinux CIL, including 'levelrange', 'level', 'sensitivitycategory', and others. It provides a comprehensive illustration of how these statements are defined and interconnected within a policy. ```secil (handleunknown allow) (mls true) ; There must be least one set of SID statements in a policy: (sid kernel) (sidorder (kernel)) (sidcontext kernel unconfined.context_1) (sensitivitycategory s0 (c4 c2 c3 c1 c0 c3)) (category c0) (categoryalias documents) (categoryaliasactual documents c0) (category c1) (category c2) (category c3) (category c4) (categoryalias spreadsheets) (categoryaliasactual spreadsheets c4) (categoryorder (c0 c1 c2 c3 spreadsheets)) (categoryset catrange_1 (range c2 c3)) (categoryset all_cats (range c0 c4)) (categoryset all_cats1 (all)) (categoryset catset_1 (documents c1)) (categoryset catset_2 (c2 c3)) (categoryset catset_3 (c4)) (categoryset just_c0 (xor (c1 c2) (documents c1 c2))) (sensitivity s0) (sensitivityalias unclassified) (sensitivityaliasactual unclassified s0) (sensitivityorder (s0)) (sensitivitycategory s0 (c0)) (sensitivitycategory s0 catrange_1) (sensitivitycategory s0 catset_1) (sensitivitycategory s0 catset_3) (sensitivitycategory s0 (all)) (sensitivitycategory s0 (range documents c2)) (level systemLow (s0)) (level level_1 (s0)) (level level_2 (s0 (catrange_1))) (level level_3 (s0 (all_cats))) (level level_4 (unclassified (c2 c3 c4))) (levelrange levelrange_2 (level_2 level_2)) (levelrange levelrange_1 ((s0) level_2)) (levelrange low_low (systemLow systemLow)) (context context_2 (unconfined.user object_r unconfined.object (level_1 level_3))) ; Define object_r role. This must be assigned in CIL. (role object_r) (block unconfined (user user) (role role) (type process) (type object) (userrange user (systemLow systemLow)) (userlevel user systemLow) (userrole user role) (userrole user object_r) (roletype role process) (roletype role object) (roletype object_r object) (class file (open execute read write)) ; There must be least one allow rule in a policy: (allow process self (file (read))) (context context_1 (user object_r object low_low)) ) ; End unconfined namespace ``` -------------------------------- ### CIL Namespace Resolution Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_reference_guide.md Demonstrates how CIL namespaces are resolved using block statements. It shows how nested types within blocks are prefixed with the block name in the generated kernel policy language, and how global namespace symbols are referenced. ```secil (block example_ns (type process) (type object) (class file (open read write getattr)) (allow process object (file (open read getattr))) ) ``` ```policy allow example_ns.process example_ns.object : example_ns.file { open read getattr }; ``` -------------------------------- ### Instantiate add_type Macro in Selinux Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_call_macro_statements.md This example shows the instantiation of the 'add_type' macro without any parameters. It highlights how macros can be used to add type identifiers to the current namespace. ```secil (block unconfined (call add_type) .... (macro add_type () (type exec) ) ) ``` -------------------------------- ### Validate Transition Statement in Selinux Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_constraint_statements.md Demonstrates how to validate transitions in Selinux policy. It shows the equivalent kernel policy language statement for a given SECIL example. ```secil ; validatetrans { file } ( t1 == unconfined.process ); ``` ```kernel (validatetrans file (eq t1 unconfined.process)) ``` -------------------------------- ### SELinux CIL Optional Block Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_container_statements.md Illustrates the use of an 'optional' CIL block in SELinux policy. Statements within an optional block are only included in the binary policy if all conditions are met. This example shows an 'optional move_file' block within 'ext_gateway' that defines typetransitions and allow rules for file operations. ```secil (block ext_gateway ...... (optional move_file (typetransition process msg_filter.move_file.in_queue file msg_filter.move_file.in_file) (allow process msg_filter.move_file.in_queue (dir (read getattr write search add_name))) (allow process msg_filter.move_file.in_file (file (write create getattr))) (allow msg_filter.move_file.in_file unconfined.object (filesystem (associate))) (typetransition msg_filter.int_gateway.process msg_filter.move_file.out_queue file msg_filter.move_file.out_file) (allow msg_filter.int_gateway.process msg_filter.move_file.out_queue (dir (read write search))) (allow msg_filter.int_gateway.process msg_filter.move_file.out_file (file (read getattr unlink))) ) ; End optional block ..... ) ; End block ``` -------------------------------- ### CIL Anonymous Declarations Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_reference_guide.md Demonstrates anonymous declarations of sensitivity, category, role, user, and type, followed by a portcon statement that utilizes these declared components to define a network context. ```secil (sensitivity s0) (category c0) (role object_r) (block unconfined (user user) (type object) ) (portcon udp 12345 (unconfined.user object_r unconfined.object ((s0) (s0(c0))))) ``` -------------------------------- ### Instantiate build_nodecon Macro with IP Addresses in Selinux Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_call_macro_statements.md This example illustrates the instantiation of the 'build_nodecon' macro, passing both an anonymous and a named IP address as arguments. It demonstrates the use of 'ipaddr' type for macro parameters. ```secil (ipaddr netmask_1 255.255.255.0) (context netlabel_1 (system.user object_r unconfined.object low_low)) (call build_nodecon ((192.168.1.64) netmask_1)) (macro build_nodecon ((ipaddr ARG1) (ipaddr ARG2)) (nodecon ARG1 ARG2 netlabel_1) ) ``` -------------------------------- ### SELinux userprefix Statement Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_user_statements.md Associates an SELinux user with a prefix string for file labeling utilities. This statement is part of the SELinux CIL policy language. ```secil (block unconfined (user admin) (userprefix admin user) ) ``` -------------------------------- ### SELinux AllowX Rule Examples Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_access_vector_rules.md The allowx statement specifies extended access permissions between source and target types. Unlike 'allow', 'allowx' is not limited by constraint statements like 'validatetrans'. It requires a corresponding 'allow' rule to be present. ```secil (allow type_1 type_2 (tcp_socket (ioctl))) ;; pre-requisite (allowx type_1 type_2 (ioctl tcp_socket (range 0x2000 0x20FF))) (permissionx ioctl_nodebug (ioctl udp_socket (not (range 0x4000 0x4010)))) (allow type_3 type_4 (udp_socket (ioctl))) ;; pre-requisite (allowx type_3 type_4 ioctl_nodebug) ``` -------------------------------- ### Manage SELinux Modules with semodule Source: https://context7.com/topjohnwu/selinux/llms.txt The semodule command manages SELinux policy modules at the system level. It allows listing installed modules, installing, removing, enabling, disabling, and extracting modules. It can also rebuild the policy from installed modules and specify installation priorities. ```bash # List all installed modules semodule -l # Install a policy module semodule -i mymodule.pp # Remove a module semodule -r mymodule # Enable/disable a module semodule -e mymodule semodule -d mymodule # Extract a module semodule -E mymodule # Rebuild policy from installed modules semodule -B # Install module with specific priority (higher = takes precedence) semodule -i mymodule.pp -X 500 ``` -------------------------------- ### Transactional SELinux Policy Management with C Source: https://context7.com/topjohnwu/selinux/llms.txt Demonstrates how to use the libsemanage C API to create a management handle, connect to the policy store, check policy management status, and perform transactional modifications. It includes steps for starting a transaction, committing changes, and handling connection errors. Dependencies include `` and ``. ```c #include #include int main(void) { semanage_handle_t *handle; /* Create management handle */ handle = semanage_handle_create(); if (handle == NULL) { fprintf(stderr, "Failed to create semanage handle\n"); return 1; } /* Check if policy is managed by semanage */ int managed = semanage_is_managed(handle); if (managed != 1) { fprintf(stderr, "Policy is not managed by libsemanage\n"); semanage_handle_destroy(handle); return 1; } /* Connect to the policy store */ if (semanage_connect(handle) < 0) { fprintf(stderr, "Failed to connect to policy store\n"); semanage_handle_destroy(handle); return 1; } printf("Connected to SELinux policy store\n"); printf("MLS enabled: %s\n", semanage_mls_enabled(handle) ? "yes" : "no"); /* Check access level */ int access = semanage_access_check(handle); printf("Access level: %s\n", (access & SEMANAGE_CAN_WRITE) ? "read/write" : "read-only"); /* Begin transaction for modifications */ if (semanage_begin_transaction(handle) >= 0) { printf("Transaction started\n"); /* Make modifications here... */ /* Commit changes */ int rc = semanage_commit(handle); if (rc >= 0) { printf("Changes committed (policy revision: %d)\n", rc); } } semanage_disconnect(handle); semanage_handle_destroy(handle); return 0; } ``` -------------------------------- ### Open and Lookup File Contexts with SELinux C API Source: https://context7.com/topjohnwu/selinux/llms.txt Demonstrates how to open the file context labeling backend and look up security contexts for files and directories using the selabel_open and selinux_lookup functions. It includes error handling and freeing allocated context memory. ```c #include #include #include #include int main(void) { struct selabel_handle *hnd; struct selinux_opt opts[] = { { SELABEL_OPT_VALIDATE, (char *)1 }, /* Validate contexts */ }; /* Open the file contexts backend */ hnd = selabel_open(SELABEL_CTX_FILE, opts, 1); if (hnd == NULL) { perror("selabel_open failed"); return 1; } /* Look up context for various paths */ const char *paths[] = { "/var/www/html/index.html", "/etc/passwd", "/home/user/.bashrc", "/var/log/messages" }; for (int i = 0; i < 4; i++) { char *context = NULL; int ret = selabel_lookup(hnd, &context, paths[i], S_IFREG); if (ret == 0) { printf("%s -> %s\n", paths[i], context); freecon(context); } else { printf("%s -> (no match)\n", paths[i]); } } /* Look up context for a directory */ char *dir_context = NULL; if (selabel_lookup(hnd, &dir_context, "/var/www", S_IFDIR) == 0) { printf("/var/www (dir) -> %s\n", dir_context); freecon(dir_context); } selabel_close(hnd); return 0; } /* Output: /var/www/html/index.html -> system_u:object_r:httpd_sys_content_t:s0 /etc/passwd -> system_u:object_r:passwd_file_t:s0 */ ``` -------------------------------- ### Selinux expandtypeattribute Example: Prevent Expansion Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_type_statements.md An example showing how to prevent the expansion of 'file_type' and 'port_type' type attributes, regardless of compiler defaults, by setting expand_value to 'false'. ```secil (expandtypeattribute (file_type port_type) false) ``` -------------------------------- ### Read/Write SELinux Binary Policy Files with sepol (C) Source: https://context7.com/topjohnwu/selinux/llms.txt Demonstrates reading and writing SELinux binary policy files using the sepol library. It covers creating policy structures, reading from a file, checking policy properties like MLS enablement, and optimizing the policy. Dependencies include sepol headers and standard C libraries. ```c #include #include #include int main(void) { sepol_policydb_t *policydb = NULL; sepol_policy_file_t *pf = NULL; FILE *fp; /* Create policy structures */ if (sepol_policydb_create(&policydb) < 0) { fprintf(stderr, "Failed to create policydb\n"); return 1; } if (sepol_policy_file_create(&pf) < 0) { fprintf(stderr, "Failed to create policy file\n"); sepol_policydb_free(policydb); return 1; } /* Read policy from file */ fp = fopen("/etc/selinux/targeted/policy/policy.33", "rb"); if (fp == NULL) { perror("Cannot open policy file"); goto cleanup; } sepol_policy_file_set_fp(pf, fp); if (sepol_policydb_read(policydb, pf) < 0) { fprintf(stderr, "Failed to read policy\n"); fclose(fp); goto cleanup; } fclose(fp); /* Check policy properties */ printf("MLS enabled: %s\n", sepol_policydb_mls_enabled(policydb) ? "yes" : "no"); /* Get supported policy version range */ printf("Kernel policy version range: %d - %d\n", sepol_policy_kern_vers_min(), sepol_policy_kern_vers_max()); /* Optimize policy (remove redundant rules) */ if (sepol_policydb_optimize(policydb) == 0) { printf("Policy optimized successfully\n"); } cleanup: sepol_policy_file_free(pf); sepol_policydb_free(policydb); return 0; } /* Output: MLS enabled: yes Kernel policy version range: 15 - 33 */ ``` -------------------------------- ### SELinux Policy Management with 'semanage' CLI Source: https://context7.com/topjohnwu/selinux/llms.txt Illustrates common operations using the 'semanage' command-line interface for managing SELinux policies. This includes listing and adding file contexts, managing port labels, mapping users, controlling booleans, listing modules, and exporting/importing policy customizations. These commands provide a high-level interface for policy configuration. ```bash # List all file context mappings semanage fcontext -l # Add a custom file context semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?" # Apply the new context to files restorecon -Rv /web # Manage port labels semanage port -l | grep http semanage port -a -t http_port_t -p tcp 8080 # Map Linux users to SELinux users semanage login -l semanage login -a -s staff_u username # Manage SELinux booleans semanage boolean -l | grep httpd semanage boolean -m --on httpd_can_network_connect # List installed modules semanage module -l # Export all local customizations semanage export -f /root/selinux-customizations.txt # Import customizations semanage import -f /root/selinux-customizations.txt ``` -------------------------------- ### Selinux typebounds Hierarchical Permissions Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_type_statements.md An example illustrating the typebounds statement where a child domain ('httpd.child.process') inherits limitations from its parent domain ('httpd.process'). This ensures the child cannot exceed the parent's permissions. ```secil (class file (getattr read write)) (block httpd (type process) (type object) (typebounds process child.process) ; The parent is allowed file 'getattr' and 'read': (allow process object (file (getattr read))) (block child (type process) (type object) ; However the child process has been given 'write' access that will be denied. (allow process httpd.object (file (read write))) ) ) ``` -------------------------------- ### Selinux Type Attribute Exclusion Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_type_statements.md An example of using typeattributeset to exclude specific types from a type attribute, similar to '~appdomain' in kernel policy language. This is useful for creating negative sets of permissions. ```secil (typeattribute not_in_appdomain) (typeattributeset not_in_appdomain (not (appdomain))) ``` -------------------------------- ### LIBSELINUX_36 Functions Source: https://github.com/topjohnwu/selinux/blob/master/libselinux/exported.map.txt This section details the functions available in the LIBSELINUX_36 library, introduced in version 36, including TEE service context handling. ```APIDOC ## SELinux API Functions (LIBSELINUX_36) ### Description This group of functions provides SELinux operations, including retrieving previous contexts and handling Trusted Execution Environment (TEE) service contexts, introduced in version 36. ### Functions - **getprevcon**: Retrieves the previous SELinux security context. - **selinux_android_tee_service_context_handle**: Handles SELinux contexts for Android TEE services. ``` -------------------------------- ### SELinux CIL Block Inheritance Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_container_statements.md Demonstrates how SELinux CIL blocks can inherit policies from parent blocks. The 'client_server' block acts as a template, and 'netclient_app' and 'netserver_app' inherit its rules for labeling log files and processes. It also shows nested block inheritance and how contents are resolved. ```secil (block client_server (blockabstract client_server) ; Log file labeling (type log_file) (typeattributeset file_type (log_file)) (typeattributeset data_file_type (log_file)) (allow process log_file (dir (write search create setattr add_name))) (allow process log_file (file (create open append getattr setattr))) (roletype object_r log_file) (context log_file_context (u object_r log_file low_low)) ; Process labeling (type process) (typeattributeset domain (process)) (call app_domain (process)) (call net_domain (process)) ) ; This is a policy block that will inherit the abstract block above: (block netclient_app ; Add common policy rules to namespace: (blockinherit client_server) ; Label the log files (filecon "/data/data/com.se4android.netclient/.*" file log_file_context) ) ; This is another policy block that will inherit the abstract block above: (block netserver_app ; Add common policy rules to namespace: (blockinherit client_server) ; Label the log files (filecon "/data/data/com.se4android.netserver/.*" file log_file_context) ) ; This is an example of how blockinherits resolve inherits before copying (block a (type one)) (block b ; Notice that block a is declared here as well (block a (type two))) ; This will first copy the contents of block b, which results in type b.a.two being copied. ; Next, the contents of block a will be copied which will result in type a.one. (block ab (blockinherit b) (blockinherit a)) ``` -------------------------------- ### Apply genfscon to Filesystems Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_file_labeling_statements.md This example shows how to use `genfscon` within an `in file` block to assign security contexts to various filesystems. It demonstrates assigning a general context to `rootfs` and more specific contexts to the `/proc` filesystem and its subdirectories, as well as `selinuxfs`. ```secil (file (type rootfs) (roletype object_r rootfs) (context rootfs_context (u object_r rootfs low_low)) (type proc) (roletype object_r proc) (context rootfs_context (u object_r proc low_low)) ... ) (in file (genfscon rootfs / rootfs_context) ; proc labeling can be further refined (longest matching prefix). (genfscon proc / proc_context) (genfscon proc /net/xt_qtaguid/ctrl qtaguid_proc_context) (genfscon proc /sysrq-trigger sysrq_proc_context) (genfscon selinuxfs / selinuxfs_context) ) ``` -------------------------------- ### SELinux Context Example: Anonymous Context for Network Labeling (SECIL) Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_context_statement.md This example shows the use of anonymous SELinux contexts within 'portcon' statements. The user, role, type, and level range identifiers are directly embedded in the statement, defining specific network port labels. ```secil (portcon udp 1024 (test.user object_r test.process ((s0) (s1)))) (portcon tcp 1024 (test.user object_r test.process (system_low system_high))) ``` -------------------------------- ### SELinux Typechange Rule Definition and Example Source: https://github.com/topjohnwu/selinux/blob/master/secilc/docs/cil_type_statements.md Defines how to use the typechange rule in SELinux policy to specify a new label for an object. It requires an allow rule for authorization and is used with functions like security_compute_relabel. The example shows a basic typechange for file objects within an unconfined block. ```secil (typechange source_type_id target_type_id class_id change_type_id) (class file (getattr read write)) (block unconfined (type process) (type object) (type change_label) (typechange object object file change_label) ) ```