From 0c88a0410e57c9be5484a5e1b66ffccfc587fe07 Mon Sep 17 00:00:00 2001 From: Mauro Carvalho Chehab Date: Sun, 14 May 2017 11:52:08 -0300 Subject: MAINTAINERS: update old references for DocBook directory As everything was converted, update the references to point to the new places. Signed-off-by: Mauro Carvalho Chehab --- MAINTAINERS | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'MAINTAINERS') diff --git a/MAINTAINERS b/MAINTAINERS index f42daf74f541..8609dba03cbc 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -3567,7 +3567,6 @@ T: git git://git.kernel.org/pub/scm/linux/kernel/git/herbert/crypto-2.6.git S: Maintained F: Documentation/crypto/ F: Documentation/devicetree/bindings/crypto/ -F: Documentation/DocBook/crypto-API.tmpl F: arch/*/crypto/ F: crypto/ F: drivers/crypto/ @@ -7364,7 +7363,7 @@ W: http://kgdb.wiki.kernel.org/ L: kgdb-bugreport@lists.sourceforge.net T: git git://git.kernel.org/pub/scm/linux/kernel/git/jwessel/kgdb.git S: Maintained -F: Documentation/DocBook/kgdb.tmpl +F: Documentation/dev-tools/kgdb.rst F: drivers/misc/kgdbts.c F: drivers/tty/serial/kgdboc.c F: include/linux/kdb.h @@ -10971,7 +10970,7 @@ S: Supported F: arch/s390/ F: drivers/s390/ F: Documentation/s390/ -F: Documentation/DocBook/s390* +F: Documentation/driver-api/s390-drivers.rst S390 COMMON I/O LAYER M: Sebastian Ott -- cgit v1.2.3-59-g8ed1b From c061f33f35be0ccc80f4b8e0aea5dfd2ed7e01a3 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Sat, 13 May 2017 04:51:37 -0700 Subject: doc: ReSTify seccomp_filter.txt This updates seccomp_filter.txt for ReST markup, and moves it under the user-space API index, since it describes how application author can use seccomp. Signed-off-by: Kees Cook Signed-off-by: Jonathan Corbet --- Documentation/prctl/seccomp_filter.txt | 225 ------------------------ Documentation/userspace-api/index.rst | 1 + Documentation/userspace-api/seccomp_filter.rst | 229 +++++++++++++++++++++++++ MAINTAINERS | 1 + 4 files changed, 231 insertions(+), 225 deletions(-) delete mode 100644 Documentation/prctl/seccomp_filter.txt create mode 100644 Documentation/userspace-api/seccomp_filter.rst (limited to 'MAINTAINERS') diff --git a/Documentation/prctl/seccomp_filter.txt b/Documentation/prctl/seccomp_filter.txt deleted file mode 100644 index 1e469ef75778..000000000000 --- a/Documentation/prctl/seccomp_filter.txt +++ /dev/null @@ -1,225 +0,0 @@ - SECure COMPuting with filters - ============================= - -Introduction ------------- - -A large number of system calls are exposed to every userland process -with many of them going unused for the entire lifetime of the process. -As system calls change and mature, bugs are found and eradicated. A -certain subset of userland applications benefit by having a reduced set -of available system calls. The resulting set reduces the total kernel -surface exposed to the application. System call filtering is meant for -use with those applications. - -Seccomp filtering provides a means for a process to specify a filter for -incoming system calls. The filter is expressed as a Berkeley Packet -Filter (BPF) program, as with socket filters, except that the data -operated on is related to the system call being made: system call -number and the system call arguments. This allows for expressive -filtering of system calls using a filter program language with a long -history of being exposed to userland and a straightforward data set. - -Additionally, BPF makes it impossible for users of seccomp to fall prey -to time-of-check-time-of-use (TOCTOU) attacks that are common in system -call interposition frameworks. BPF programs may not dereference -pointers which constrains all filters to solely evaluating the system -call arguments directly. - -What it isn't -------------- - -System call filtering isn't a sandbox. It provides a clearly defined -mechanism for minimizing the exposed kernel surface. It is meant to be -a tool for sandbox developers to use. Beyond that, policy for logical -behavior and information flow should be managed with a combination of -other system hardening techniques and, potentially, an LSM of your -choosing. Expressive, dynamic filters provide further options down this -path (avoiding pathological sizes or selecting which of the multiplexed -system calls in socketcall() is allowed, for instance) which could be -construed, incorrectly, as a more complete sandboxing solution. - -Usage ------ - -An additional seccomp mode is added and is enabled using the same -prctl(2) call as the strict seccomp. If the architecture has -CONFIG_HAVE_ARCH_SECCOMP_FILTER, then filters may be added as below: - -PR_SET_SECCOMP: - Now takes an additional argument which specifies a new filter - using a BPF program. - The BPF program will be executed over struct seccomp_data - reflecting the system call number, arguments, and other - metadata. The BPF program must then return one of the - acceptable values to inform the kernel which action should be - taken. - - Usage: - prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, prog); - - The 'prog' argument is a pointer to a struct sock_fprog which - will contain the filter program. If the program is invalid, the - call will return -1 and set errno to EINVAL. - - If fork/clone and execve are allowed by @prog, any child - processes will be constrained to the same filters and system - call ABI as the parent. - - Prior to use, the task must call prctl(PR_SET_NO_NEW_PRIVS, 1) or - run with CAP_SYS_ADMIN privileges in its namespace. If these are not - true, -EACCES will be returned. This requirement ensures that filter - programs cannot be applied to child processes with greater privileges - than the task that installed them. - - Additionally, if prctl(2) is allowed by the attached filter, - additional filters may be layered on which will increase evaluation - time, but allow for further decreasing the attack surface during - execution of a process. - -The above call returns 0 on success and non-zero on error. - -Return values -------------- -A seccomp filter may return any of the following values. If multiple -filters exist, the return value for the evaluation of a given system -call will always use the highest precedent value. (For example, -SECCOMP_RET_KILL will always take precedence.) - -In precedence order, they are: - -SECCOMP_RET_KILL: - Results in the task exiting immediately without executing the - system call. The exit status of the task (status & 0x7f) will - be SIGSYS, not SIGKILL. - -SECCOMP_RET_TRAP: - Results in the kernel sending a SIGSYS signal to the triggering - task without executing the system call. siginfo->si_call_addr - will show the address of the system call instruction, and - siginfo->si_syscall and siginfo->si_arch will indicate which - syscall was attempted. The program counter will be as though - the syscall happened (i.e. it will not point to the syscall - instruction). The return value register will contain an arch- - dependent value -- if resuming execution, set it to something - sensible. (The architecture dependency is because replacing - it with -ENOSYS could overwrite some useful information.) - - The SECCOMP_RET_DATA portion of the return value will be passed - as si_errno. - - SIGSYS triggered by seccomp will have a si_code of SYS_SECCOMP. - -SECCOMP_RET_ERRNO: - Results in the lower 16-bits of the return value being passed - to userland as the errno without executing the system call. - -SECCOMP_RET_TRACE: - When returned, this value will cause the kernel to attempt to - notify a ptrace()-based tracer prior to executing the system - call. If there is no tracer present, -ENOSYS is returned to - userland and the system call is not executed. - - A tracer will be notified if it requests PTRACE_O_TRACESECCOMP - using ptrace(PTRACE_SETOPTIONS). The tracer will be notified - of a PTRACE_EVENT_SECCOMP and the SECCOMP_RET_DATA portion of - the BPF program return value will be available to the tracer - via PTRACE_GETEVENTMSG. - - The tracer can skip the system call by changing the syscall number - to -1. Alternatively, the tracer can change the system call - requested by changing the system call to a valid syscall number. If - the tracer asks to skip the system call, then the system call will - appear to return the value that the tracer puts in the return value - register. - - The seccomp check will not be run again after the tracer is - notified. (This means that seccomp-based sandboxes MUST NOT - allow use of ptrace, even of other sandboxed processes, without - extreme care; ptracers can use this mechanism to escape.) - -SECCOMP_RET_ALLOW: - Results in the system call being executed. - -If multiple filters exist, the return value for the evaluation of a -given system call will always use the highest precedent value. - -Precedence is only determined using the SECCOMP_RET_ACTION mask. When -multiple filters return values of the same precedence, only the -SECCOMP_RET_DATA from the most recently installed filter will be -returned. - -Pitfalls --------- - -The biggest pitfall to avoid during use is filtering on system call -number without checking the architecture value. Why? On any -architecture that supports multiple system call invocation conventions, -the system call numbers may vary based on the specific invocation. If -the numbers in the different calling conventions overlap, then checks in -the filters may be abused. Always check the arch value! - -Example -------- - -The samples/seccomp/ directory contains both an x86-specific example -and a more generic example of a higher level macro interface for BPF -program generation. - - - -Adding architecture support ------------------------ - -See arch/Kconfig for the authoritative requirements. In general, if an -architecture supports both ptrace_event and seccomp, it will be able to -support seccomp filter with minor fixup: SIGSYS support and seccomp return -value checking. Then it must just add CONFIG_HAVE_ARCH_SECCOMP_FILTER -to its arch-specific Kconfig. - - - -Caveats -------- - -The vDSO can cause some system calls to run entirely in userspace, -leading to surprises when you run programs on different machines that -fall back to real syscalls. To minimize these surprises on x86, make -sure you test with -/sys/devices/system/clocksource/clocksource0/current_clocksource set to -something like acpi_pm. - -On x86-64, vsyscall emulation is enabled by default. (vsyscalls are -legacy variants on vDSO calls.) Currently, emulated vsyscalls will honor seccomp, with a few oddities: - -- A return value of SECCOMP_RET_TRAP will set a si_call_addr pointing to - the vsyscall entry for the given call and not the address after the - 'syscall' instruction. Any code which wants to restart the call - should be aware that (a) a ret instruction has been emulated and (b) - trying to resume the syscall will again trigger the standard vsyscall - emulation security checks, making resuming the syscall mostly - pointless. - -- A return value of SECCOMP_RET_TRACE will signal the tracer as usual, - but the syscall may not be changed to another system call using the - orig_rax register. It may only be changed to -1 order to skip the - currently emulated call. Any other change MAY terminate the process. - The rip value seen by the tracer will be the syscall entry address; - this is different from normal behavior. The tracer MUST NOT modify - rip or rsp. (Do not rely on other changes terminating the process. - They might work. For example, on some kernels, choosing a syscall - that only exists in future kernels will be correctly emulated (by - returning -ENOSYS). - -To detect this quirky behavior, check for addr & ~0x0C00 == -0xFFFFFFFFFF600000. (For SECCOMP_RET_TRACE, use rip. For -SECCOMP_RET_TRAP, use siginfo->si_call_addr.) Do not check any other -condition: future kernels may improve vsyscall emulation and current -kernels in vsyscall=native mode will behave differently, but the -instructions at 0xF...F600{0,4,8,C}00 will not be system calls in these -cases. - -Note that modern systems are unlikely to use vsyscalls at all -- they -are a legacy feature and they are considerably slower than standard -syscalls. New code will use the vDSO, and vDSO-issued system calls -are indistinguishable from normal system calls. diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst index a9d01b44a659..15ff12342db8 100644 --- a/Documentation/userspace-api/index.rst +++ b/Documentation/userspace-api/index.rst @@ -16,6 +16,7 @@ place where this information is gathered. .. toctree:: :maxdepth: 2 + seccomp_filter unshare .. only:: subproject and html diff --git a/Documentation/userspace-api/seccomp_filter.rst b/Documentation/userspace-api/seccomp_filter.rst new file mode 100644 index 000000000000..f71eb5ef1f2d --- /dev/null +++ b/Documentation/userspace-api/seccomp_filter.rst @@ -0,0 +1,229 @@ +=========================================== +Seccomp BPF (SECure COMPuting with filters) +=========================================== + +Introduction +============ + +A large number of system calls are exposed to every userland process +with many of them going unused for the entire lifetime of the process. +As system calls change and mature, bugs are found and eradicated. A +certain subset of userland applications benefit by having a reduced set +of available system calls. The resulting set reduces the total kernel +surface exposed to the application. System call filtering is meant for +use with those applications. + +Seccomp filtering provides a means for a process to specify a filter for +incoming system calls. The filter is expressed as a Berkeley Packet +Filter (BPF) program, as with socket filters, except that the data +operated on is related to the system call being made: system call +number and the system call arguments. This allows for expressive +filtering of system calls using a filter program language with a long +history of being exposed to userland and a straightforward data set. + +Additionally, BPF makes it impossible for users of seccomp to fall prey +to time-of-check-time-of-use (TOCTOU) attacks that are common in system +call interposition frameworks. BPF programs may not dereference +pointers which constrains all filters to solely evaluating the system +call arguments directly. + +What it isn't +============= + +System call filtering isn't a sandbox. It provides a clearly defined +mechanism for minimizing the exposed kernel surface. It is meant to be +a tool for sandbox developers to use. Beyond that, policy for logical +behavior and information flow should be managed with a combination of +other system hardening techniques and, potentially, an LSM of your +choosing. Expressive, dynamic filters provide further options down this +path (avoiding pathological sizes or selecting which of the multiplexed +system calls in socketcall() is allowed, for instance) which could be +construed, incorrectly, as a more complete sandboxing solution. + +Usage +===== + +An additional seccomp mode is added and is enabled using the same +prctl(2) call as the strict seccomp. If the architecture has +``CONFIG_HAVE_ARCH_SECCOMP_FILTER``, then filters may be added as below: + +``PR_SET_SECCOMP``: + Now takes an additional argument which specifies a new filter + using a BPF program. + The BPF program will be executed over struct seccomp_data + reflecting the system call number, arguments, and other + metadata. The BPF program must then return one of the + acceptable values to inform the kernel which action should be + taken. + + Usage:: + + prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, prog); + + The 'prog' argument is a pointer to a struct sock_fprog which + will contain the filter program. If the program is invalid, the + call will return -1 and set errno to ``EINVAL``. + + If ``fork``/``clone`` and ``execve`` are allowed by @prog, any child + processes will be constrained to the same filters and system + call ABI as the parent. + + Prior to use, the task must call ``prctl(PR_SET_NO_NEW_PRIVS, 1)`` or + run with ``CAP_SYS_ADMIN`` privileges in its namespace. If these are not + true, ``-EACCES`` will be returned. This requirement ensures that filter + programs cannot be applied to child processes with greater privileges + than the task that installed them. + + Additionally, if ``prctl(2)`` is allowed by the attached filter, + additional filters may be layered on which will increase evaluation + time, but allow for further decreasing the attack surface during + execution of a process. + +The above call returns 0 on success and non-zero on error. + +Return values +============= + +A seccomp filter may return any of the following values. If multiple +filters exist, the return value for the evaluation of a given system +call will always use the highest precedent value. (For example, +``SECCOMP_RET_KILL`` will always take precedence.) + +In precedence order, they are: + +``SECCOMP_RET_KILL``: + Results in the task exiting immediately without executing the + system call. The exit status of the task (``status & 0x7f``) will + be ``SIGSYS``, not ``SIGKILL``. + +``SECCOMP_RET_TRAP``: + Results in the kernel sending a ``SIGSYS`` signal to the triggering + task without executing the system call. ``siginfo->si_call_addr`` + will show the address of the system call instruction, and + ``siginfo->si_syscall`` and ``siginfo->si_arch`` will indicate which + syscall was attempted. The program counter will be as though + the syscall happened (i.e. it will not point to the syscall + instruction). The return value register will contain an arch- + dependent value -- if resuming execution, set it to something + sensible. (The architecture dependency is because replacing + it with ``-ENOSYS`` could overwrite some useful information.) + + The ``SECCOMP_RET_DATA`` portion of the return value will be passed + as ``si_errno``. + + ``SIGSYS`` triggered by seccomp will have a si_code of ``SYS_SECCOMP``. + +``SECCOMP_RET_ERRNO``: + Results in the lower 16-bits of the return value being passed + to userland as the errno without executing the system call. + +``SECCOMP_RET_TRACE``: + When returned, this value will cause the kernel to attempt to + notify a ``ptrace()``-based tracer prior to executing the system + call. If there is no tracer present, ``-ENOSYS`` is returned to + userland and the system call is not executed. + + A tracer will be notified if it requests ``PTRACE_O_TRACESECCOM``P + using ``ptrace(PTRACE_SETOPTIONS)``. The tracer will be notified + of a ``PTRACE_EVENT_SECCOMP`` and the ``SECCOMP_RET_DATA`` portion of + the BPF program return value will be available to the tracer + via ``PTRACE_GETEVENTMSG``. + + The tracer can skip the system call by changing the syscall number + to -1. Alternatively, the tracer can change the system call + requested by changing the system call to a valid syscall number. If + the tracer asks to skip the system call, then the system call will + appear to return the value that the tracer puts in the return value + register. + + The seccomp check will not be run again after the tracer is + notified. (This means that seccomp-based sandboxes MUST NOT + allow use of ptrace, even of other sandboxed processes, without + extreme care; ptracers can use this mechanism to escape.) + +``SECCOMP_RET_ALLOW``: + Results in the system call being executed. + +If multiple filters exist, the return value for the evaluation of a +given system call will always use the highest precedent value. + +Precedence is only determined using the ``SECCOMP_RET_ACTION`` mask. When +multiple filters return values of the same precedence, only the +``SECCOMP_RET_DATA`` from the most recently installed filter will be +returned. + +Pitfalls +======== + +The biggest pitfall to avoid during use is filtering on system call +number without checking the architecture value. Why? On any +architecture that supports multiple system call invocation conventions, +the system call numbers may vary based on the specific invocation. If +the numbers in the different calling conventions overlap, then checks in +the filters may be abused. Always check the arch value! + +Example +======= + +The ``samples/seccomp/`` directory contains both an x86-specific example +and a more generic example of a higher level macro interface for BPF +program generation. + + + +Adding architecture support +=========================== + +See ``arch/Kconfig`` for the authoritative requirements. In general, if an +architecture supports both ptrace_event and seccomp, it will be able to +support seccomp filter with minor fixup: ``SIGSYS`` support and seccomp return +value checking. Then it must just add ``CONFIG_HAVE_ARCH_SECCOMP_FILTER`` +to its arch-specific Kconfig. + + + +Caveats +======= + +The vDSO can cause some system calls to run entirely in userspace, +leading to surprises when you run programs on different machines that +fall back to real syscalls. To minimize these surprises on x86, make +sure you test with +``/sys/devices/system/clocksource/clocksource0/current_clocksource`` set to +something like ``acpi_pm``. + +On x86-64, vsyscall emulation is enabled by default. (vsyscalls are +legacy variants on vDSO calls.) Currently, emulated vsyscalls will +honor seccomp, with a few oddities: + +- A return value of ``SECCOMP_RET_TRAP`` will set a ``si_call_addr`` pointing to + the vsyscall entry for the given call and not the address after the + 'syscall' instruction. Any code which wants to restart the call + should be aware that (a) a ret instruction has been emulated and (b) + trying to resume the syscall will again trigger the standard vsyscall + emulation security checks, making resuming the syscall mostly + pointless. + +- A return value of ``SECCOMP_RET_TRACE`` will signal the tracer as usual, + but the syscall may not be changed to another system call using the + orig_rax register. It may only be changed to -1 order to skip the + currently emulated call. Any other change MAY terminate the process. + The rip value seen by the tracer will be the syscall entry address; + this is different from normal behavior. The tracer MUST NOT modify + rip or rsp. (Do not rely on other changes terminating the process. + They might work. For example, on some kernels, choosing a syscall + that only exists in future kernels will be correctly emulated (by + returning ``-ENOSYS``). + +To detect this quirky behavior, check for ``addr & ~0x0C00 == +0xFFFFFFFFFF600000``. (For ``SECCOMP_RET_TRACE``, use rip. For +``SECCOMP_RET_TRAP``, use ``siginfo->si_call_addr``.) Do not check any other +condition: future kernels may improve vsyscall emulation and current +kernels in vsyscall=native mode will behave differently, but the +instructions at ``0xF...F600{0,4,8,C}00`` will not be system calls in these +cases. + +Note that modern systems are unlikely to use vsyscalls at all -- they +are a legacy feature and they are considerably slower than standard +syscalls. New code will use the vDSO, and vDSO-issued system calls +are indistinguishable from normal system calls. diff --git a/MAINTAINERS b/MAINTAINERS index f7d568b8f133..752916d1461c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11492,6 +11492,7 @@ F: kernel/seccomp.c F: include/uapi/linux/seccomp.h F: include/linux/seccomp.h F: tools/testing/selftests/seccomp/* +F: Documentation/userspace-api/seccomp_filter.rst K: \bsecure_computing K: \bTIF_SECCOMP\b -- cgit v1.2.3-59-g8ed1b From 229fd05c565eb931aa7c59c9d740e2047701a4ad Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Sat, 13 May 2017 04:51:44 -0700 Subject: doc: ReSTify SELinux.txt Adjusts for ReST markup and moves under LSM admin guide. Cc: Paul Moore Signed-off-by: Kees Cook Signed-off-by: Jonathan Corbet --- Documentation/admin-guide/LSM/SELinux.rst | 33 +++++++++++++++++++++++++++++++ Documentation/admin-guide/LSM/index.rst | 5 +++++ Documentation/security/00-INDEX | 2 -- Documentation/security/SELinux.txt | 27 ------------------------- MAINTAINERS | 1 + scripts/selinux/README | 2 +- 6 files changed, 40 insertions(+), 30 deletions(-) create mode 100644 Documentation/admin-guide/LSM/SELinux.rst delete mode 100644 Documentation/security/SELinux.txt (limited to 'MAINTAINERS') diff --git a/Documentation/admin-guide/LSM/SELinux.rst b/Documentation/admin-guide/LSM/SELinux.rst new file mode 100644 index 000000000000..f722c9b4173a --- /dev/null +++ b/Documentation/admin-guide/LSM/SELinux.rst @@ -0,0 +1,33 @@ +======= +SELinux +======= + +If you want to use SELinux, chances are you will want +to use the distro-provided policies, or install the +latest reference policy release from + + http://oss.tresys.com/projects/refpolicy + +However, if you want to install a dummy policy for +testing, you can do using ``mdp`` provided under +scripts/selinux. Note that this requires the selinux +userspace to be installed - in particular you will +need checkpolicy to compile a kernel, and setfiles and +fixfiles to label the filesystem. + + 1. Compile the kernel with selinux enabled. + 2. Type ``make`` to compile ``mdp``. + 3. Make sure that you are not running with + SELinux enabled and a real policy. If + you are, reboot with selinux disabled + before continuing. + 4. Run install_policy.sh:: + + cd scripts/selinux + sh install_policy.sh + +Step 4 will create a new dummy policy valid for your +kernel, with a single selinux user, role, and type. +It will compile the policy, will set your ``SELINUXTYPE`` to +``dummy`` in ``/etc/selinux/config``, install the compiled policy +as ``dummy``, and relabel your filesystem. diff --git a/Documentation/admin-guide/LSM/index.rst b/Documentation/admin-guide/LSM/index.rst index 7e892b9b58aa..cc0e04d63bf9 100644 --- a/Documentation/admin-guide/LSM/index.rst +++ b/Documentation/admin-guide/LSM/index.rst @@ -29,3 +29,8 @@ will always include the capability module. The list reflects the order in which checks are made. The capability module will always be first, followed by any "minor" modules (e.g. Yama) and then the one "major" module (e.g. SELinux) if there is one configured. + +.. toctree:: + :maxdepth: 1 + + SELinux diff --git a/Documentation/security/00-INDEX b/Documentation/security/00-INDEX index 190a023a7e72..aaa0195418b3 100644 --- a/Documentation/security/00-INDEX +++ b/Documentation/security/00-INDEX @@ -1,7 +1,5 @@ 00-INDEX - this file. -SELinux.txt - - how to get started with the SELinux security enhancement. Smack.txt - documentation on the Smack Linux Security Module. Yama.txt diff --git a/Documentation/security/SELinux.txt b/Documentation/security/SELinux.txt deleted file mode 100644 index 07eae00f3314..000000000000 --- a/Documentation/security/SELinux.txt +++ /dev/null @@ -1,27 +0,0 @@ -If you want to use SELinux, chances are you will want -to use the distro-provided policies, or install the -latest reference policy release from - http://oss.tresys.com/projects/refpolicy - -However, if you want to install a dummy policy for -testing, you can do using 'mdp' provided under -scripts/selinux. Note that this requires the selinux -userspace to be installed - in particular you will -need checkpolicy to compile a kernel, and setfiles and -fixfiles to label the filesystem. - - 1. Compile the kernel with selinux enabled. - 2. Type 'make' to compile mdp. - 3. Make sure that you are not running with - SELinux enabled and a real policy. If - you are, reboot with selinux disabled - before continuing. - 4. Run install_policy.sh: - cd scripts/selinux - sh install_policy.sh - -Step 4 will create a new dummy policy valid for your -kernel, with a single selinux user, role, and type. -It will compile the policy, will set your SELINUXTYPE to -dummy in /etc/selinux/config, install the compiled policy -as 'dummy', and relabel your filesystem. diff --git a/MAINTAINERS b/MAINTAINERS index 752916d1461c..e0dabbfff283 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11551,6 +11551,7 @@ S: Supported F: include/linux/selinux* F: security/selinux/ F: scripts/selinux/ +F: Documentation/admin-guide/LSM/SELinux.rst APPARMOR SECURITY MODULE M: John Johansen diff --git a/scripts/selinux/README b/scripts/selinux/README index 4d020ecb7524..5ba679c5be18 100644 --- a/scripts/selinux/README +++ b/scripts/selinux/README @@ -1,2 +1,2 @@ -Please see Documentation/security/SELinux.txt for information on +Please see Documentation/admin-guide/LSM/SELinux.rst for information on installing a dummy SELinux policy. -- cgit v1.2.3-59-g8ed1b From 26fccd9ed2e283add2849858c28bd14f84d9c48e Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Sat, 13 May 2017 04:51:45 -0700 Subject: doc: ReSTify apparmor.txt Adjusts for ReST markup and moves under LSM admin guide. Acked-by: John Johansen Signed-off-by: Kees Cook Signed-off-by: Jonathan Corbet --- Documentation/admin-guide/LSM/apparmor.rst | 51 ++++++++++++++++++++++++++++++ Documentation/admin-guide/LSM/index.rst | 1 + Documentation/security/00-INDEX | 2 -- Documentation/security/apparmor.txt | 39 ----------------------- MAINTAINERS | 1 + security/apparmor/match.c | 2 +- security/apparmor/policy_unpack.c | 2 +- 7 files changed, 55 insertions(+), 43 deletions(-) create mode 100644 Documentation/admin-guide/LSM/apparmor.rst delete mode 100644 Documentation/security/apparmor.txt (limited to 'MAINTAINERS') diff --git a/Documentation/admin-guide/LSM/apparmor.rst b/Documentation/admin-guide/LSM/apparmor.rst new file mode 100644 index 000000000000..3e9734bd0e05 --- /dev/null +++ b/Documentation/admin-guide/LSM/apparmor.rst @@ -0,0 +1,51 @@ +======== +AppArmor +======== + +What is AppArmor? +================= + +AppArmor is MAC style security extension for the Linux kernel. It implements +a task centered policy, with task "profiles" being created and loaded +from user space. Tasks on the system that do not have a profile defined for +them run in an unconfined state which is equivalent to standard Linux DAC +permissions. + +How to enable/disable +===================== + +set ``CONFIG_SECURITY_APPARMOR=y`` + +If AppArmor should be selected as the default security module then set:: + + CONFIG_DEFAULT_SECURITY="apparmor" + CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1 + +Build the kernel + +If AppArmor is not the default security module it can be enabled by passing +``security=apparmor`` on the kernel's command line. + +If AppArmor is the default security module it can be disabled by passing +``apparmor=0, security=XXXX`` (where ``XXXX`` is valid security module), on the +kernel's command line. + +For AppArmor to enforce any restrictions beyond standard Linux DAC permissions +policy must be loaded into the kernel from user space (see the Documentation +and tools links). + +Documentation +============= + +Documentation can be found on the wiki, linked below. + +Links +===== + +Mailing List - apparmor@lists.ubuntu.com + +Wiki - http://apparmor.wiki.kernel.org/ + +User space tools - https://launchpad.net/apparmor + +Kernel module - git://git.kernel.org/pub/scm/linux/kernel/git/jj/apparmor-dev.git diff --git a/Documentation/admin-guide/LSM/index.rst b/Documentation/admin-guide/LSM/index.rst index cc0e04d63bf9..a4db29410ea0 100644 --- a/Documentation/admin-guide/LSM/index.rst +++ b/Documentation/admin-guide/LSM/index.rst @@ -33,4 +33,5 @@ the one "major" module (e.g. SELinux) if there is one configured. .. toctree:: :maxdepth: 1 + apparmor SELinux diff --git a/Documentation/security/00-INDEX b/Documentation/security/00-INDEX index aaa0195418b3..22ebdc02f0dc 100644 --- a/Documentation/security/00-INDEX +++ b/Documentation/security/00-INDEX @@ -4,8 +4,6 @@ Smack.txt - documentation on the Smack Linux Security Module. Yama.txt - documentation on the Yama Linux Security Module. -apparmor.txt - - documentation on the AppArmor security extension. keys-ecryptfs.txt - description of the encryption keys for the ecryptfs filesystem. keys-request-key.txt diff --git a/Documentation/security/apparmor.txt b/Documentation/security/apparmor.txt deleted file mode 100644 index 93c1fd7d0635..000000000000 --- a/Documentation/security/apparmor.txt +++ /dev/null @@ -1,39 +0,0 @@ ---- What is AppArmor? --- - -AppArmor is MAC style security extension for the Linux kernel. It implements -a task centered policy, with task "profiles" being created and loaded -from user space. Tasks on the system that do not have a profile defined for -them run in an unconfined state which is equivalent to standard Linux DAC -permissions. - ---- How to enable/disable --- - -set CONFIG_SECURITY_APPARMOR=y - -If AppArmor should be selected as the default security module then - set CONFIG_DEFAULT_SECURITY="apparmor" - and CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1 - -Build the kernel - -If AppArmor is not the default security module it can be enabled by passing -security=apparmor on the kernel's command line. - -If AppArmor is the default security module it can be disabled by passing -apparmor=0, security=XXXX (where XXX is valid security module), on the -kernel's command line - -For AppArmor to enforce any restrictions beyond standard Linux DAC permissions -policy must be loaded into the kernel from user space (see the Documentation -and tools links). - ---- Documentation --- - -Documentation can be found on the wiki. - ---- Links --- - -Mailing List - apparmor@lists.ubuntu.com -Wiki - http://apparmor.wiki.kernel.org/ -User space tools - https://launchpad.net/apparmor -Kernel module - git://git.kernel.org/pub/scm/linux/kernel/git/jj/apparmor-dev.git diff --git a/MAINTAINERS b/MAINTAINERS index e0dabbfff283..4d8914ad710a 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11560,6 +11560,7 @@ W: apparmor.wiki.kernel.org T: git git://git.kernel.org/pub/scm/linux/kernel/git/jj/apparmor-dev.git S: Supported F: security/apparmor/ +F: Documentation/admin-guide/LSM/apparmor.rst LOADPIN SECURITY MODULE M: Kees Cook diff --git a/security/apparmor/match.c b/security/apparmor/match.c index 960c913381e2..72c604350e80 100644 --- a/security/apparmor/match.c +++ b/security/apparmor/match.c @@ -226,7 +226,7 @@ void aa_dfa_free_kref(struct kref *kref) * @flags: flags controlling what type of accept tables are acceptable * * Unpack a dfa that has been serialized. To find information on the dfa - * format look in Documentation/security/apparmor.txt + * format look in Documentation/admin-guide/LSM/apparmor.rst * Assumes the dfa @blob stream has been aligned on a 8 byte boundary * * Returns: an unpacked dfa ready for matching or ERR_PTR on failure diff --git a/security/apparmor/policy_unpack.c b/security/apparmor/policy_unpack.c index f3422a91353c..981d570eebba 100644 --- a/security/apparmor/policy_unpack.c +++ b/security/apparmor/policy_unpack.c @@ -13,7 +13,7 @@ * License. * * AppArmor uses a serialized binary format for loading policy. To find - * policy format documentation look in Documentation/security/apparmor.txt + * policy format documentation see Documentation/admin-guide/LSM/apparmor.rst * All policy is validated before it is used. */ -- cgit v1.2.3-59-g8ed1b From 90bb766440f2147486a2acc3e793d7b8348b0c22 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Sat, 13 May 2017 04:51:47 -0700 Subject: doc: ReSTify Yama.txt Adjusts for ReST markup and moves under LSM admin guide. Signed-off-by: Kees Cook Signed-off-by: Jonathan Corbet --- Documentation/admin-guide/LSM/Yama.rst | 74 +++++++++++++++++++++++++++++++++ Documentation/admin-guide/LSM/index.rst | 1 + Documentation/security/00-INDEX | 2 - Documentation/security/Yama.txt | 71 ------------------------------- MAINTAINERS | 1 + security/yama/Kconfig | 3 +- 6 files changed, 78 insertions(+), 74 deletions(-) create mode 100644 Documentation/admin-guide/LSM/Yama.rst delete mode 100644 Documentation/security/Yama.txt (limited to 'MAINTAINERS') diff --git a/Documentation/admin-guide/LSM/Yama.rst b/Documentation/admin-guide/LSM/Yama.rst new file mode 100644 index 000000000000..13468ea696b7 --- /dev/null +++ b/Documentation/admin-guide/LSM/Yama.rst @@ -0,0 +1,74 @@ +==== +Yama +==== + +Yama is a Linux Security Module that collects system-wide DAC security +protections that are not handled by the core kernel itself. This is +selectable at build-time with ``CONFIG_SECURITY_YAMA``, and can be controlled +at run-time through sysctls in ``/proc/sys/kernel/yama``: + +ptrace_scope +============ + +As Linux grows in popularity, it will become a larger target for +malware. One particularly troubling weakness of the Linux process +interfaces is that a single user is able to examine the memory and +running state of any of their processes. For example, if one application +(e.g. Pidgin) was compromised, it would be possible for an attacker to +attach to other running processes (e.g. Firefox, SSH sessions, GPG agent, +etc) to extract additional credentials and continue to expand the scope +of their attack without resorting to user-assisted phishing. + +This is not a theoretical problem. SSH session hijacking +(http://www.storm.net.nz/projects/7) and arbitrary code injection +(http://c-skills.blogspot.com/2007/05/injectso.html) attacks already +exist and remain possible if ptrace is allowed to operate as before. +Since ptrace is not commonly used by non-developers and non-admins, system +builders should be allowed the option to disable this debugging system. + +For a solution, some applications use ``prctl(PR_SET_DUMPABLE, ...)`` to +specifically disallow such ptrace attachment (e.g. ssh-agent), but many +do not. A more general solution is to only allow ptrace directly from a +parent to a child process (i.e. direct "gdb EXE" and "strace EXE" still +work), or with ``CAP_SYS_PTRACE`` (i.e. "gdb --pid=PID", and "strace -p PID" +still work as root). + +In mode 1, software that has defined application-specific relationships +between a debugging process and its inferior (crash handlers, etc), +``prctl(PR_SET_PTRACER, pid, ...)`` can be used. An inferior can declare which +other process (and its descendants) are allowed to call ``PTRACE_ATTACH`` +against it. Only one such declared debugging process can exists for +each inferior at a time. For example, this is used by KDE, Chromium, and +Firefox's crash handlers, and by Wine for allowing only Wine processes +to ptrace each other. If a process wishes to entirely disable these ptrace +restrictions, it can call ``prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, ...)`` +so that any otherwise allowed process (even those in external pid namespaces) +may attach. + +The sysctl settings (writable only with ``CAP_SYS_PTRACE``) are: + +0 - classic ptrace permissions: + a process can ``PTRACE_ATTACH`` to any other + process running under the same uid, as long as it is dumpable (i.e. + did not transition uids, start privileged, or have called + ``prctl(PR_SET_DUMPABLE...)`` already). Similarly, ``PTRACE_TRACEME`` is + unchanged. + +1 - restricted ptrace: + a process must have a predefined relationship + with the inferior it wants to call ``PTRACE_ATTACH`` on. By default, + this relationship is that of only its descendants when the above + classic criteria is also met. To change the relationship, an + inferior can call ``prctl(PR_SET_PTRACER, debugger, ...)`` to declare + an allowed debugger PID to call ``PTRACE_ATTACH`` on the inferior. + Using ``PTRACE_TRACEME`` is unchanged. + +2 - admin-only attach: + only processes with ``CAP_SYS_PTRACE`` may use ptrace + with ``PTRACE_ATTACH``, or through children calling ``PTRACE_TRACEME``. + +3 - no attach: + no processes may use ptrace with ``PTRACE_ATTACH`` nor via + ``PTRACE_TRACEME``. Once set, this sysctl value cannot be changed. + +The original children-only logic was based on the restrictions in grsecurity. diff --git a/Documentation/admin-guide/LSM/index.rst b/Documentation/admin-guide/LSM/index.rst index 6aa4e0dc588b..e5ba2c69b8ef 100644 --- a/Documentation/admin-guide/LSM/index.rst +++ b/Documentation/admin-guide/LSM/index.rst @@ -36,3 +36,4 @@ the one "major" module (e.g. SELinux) if there is one configured. apparmor SELinux tomoyo + Yama diff --git a/Documentation/security/00-INDEX b/Documentation/security/00-INDEX index 04ef62511ea1..a55f781be0dd 100644 --- a/Documentation/security/00-INDEX +++ b/Documentation/security/00-INDEX @@ -2,8 +2,6 @@ - this file. Smack.txt - documentation on the Smack Linux Security Module. -Yama.txt - - documentation on the Yama Linux Security Module. keys-ecryptfs.txt - description of the encryption keys for the ecryptfs filesystem. keys-request-key.txt diff --git a/Documentation/security/Yama.txt b/Documentation/security/Yama.txt deleted file mode 100644 index d9ee7d7a6c7f..000000000000 --- a/Documentation/security/Yama.txt +++ /dev/null @@ -1,71 +0,0 @@ -Yama is a Linux Security Module that collects system-wide DAC security -protections that are not handled by the core kernel itself. This is -selectable at build-time with CONFIG_SECURITY_YAMA, and can be controlled -at run-time through sysctls in /proc/sys/kernel/yama: - -- ptrace_scope - -============================================================== - -ptrace_scope: - -As Linux grows in popularity, it will become a larger target for -malware. One particularly troubling weakness of the Linux process -interfaces is that a single user is able to examine the memory and -running state of any of their processes. For example, if one application -(e.g. Pidgin) was compromised, it would be possible for an attacker to -attach to other running processes (e.g. Firefox, SSH sessions, GPG agent, -etc) to extract additional credentials and continue to expand the scope -of their attack without resorting to user-assisted phishing. - -This is not a theoretical problem. SSH session hijacking -(http://www.storm.net.nz/projects/7) and arbitrary code injection -(http://c-skills.blogspot.com/2007/05/injectso.html) attacks already -exist and remain possible if ptrace is allowed to operate as before. -Since ptrace is not commonly used by non-developers and non-admins, system -builders should be allowed the option to disable this debugging system. - -For a solution, some applications use prctl(PR_SET_DUMPABLE, ...) to -specifically disallow such ptrace attachment (e.g. ssh-agent), but many -do not. A more general solution is to only allow ptrace directly from a -parent to a child process (i.e. direct "gdb EXE" and "strace EXE" still -work), or with CAP_SYS_PTRACE (i.e. "gdb --pid=PID", and "strace -p PID" -still work as root). - -In mode 1, software that has defined application-specific relationships -between a debugging process and its inferior (crash handlers, etc), -prctl(PR_SET_PTRACER, pid, ...) can be used. An inferior can declare which -other process (and its descendants) are allowed to call PTRACE_ATTACH -against it. Only one such declared debugging process can exists for -each inferior at a time. For example, this is used by KDE, Chromium, and -Firefox's crash handlers, and by Wine for allowing only Wine processes -to ptrace each other. If a process wishes to entirely disable these ptrace -restrictions, it can call prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, ...) -so that any otherwise allowed process (even those in external pid namespaces) -may attach. - -The sysctl settings (writable only with CAP_SYS_PTRACE) are: - -0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other - process running under the same uid, as long as it is dumpable (i.e. - did not transition uids, start privileged, or have called - prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is - unchanged. - -1 - restricted ptrace: a process must have a predefined relationship - with the inferior it wants to call PTRACE_ATTACH on. By default, - this relationship is that of only its descendants when the above - classic criteria is also met. To change the relationship, an - inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare - an allowed debugger PID to call PTRACE_ATTACH on the inferior. - Using PTRACE_TRACEME is unchanged. - -2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace - with PTRACE_ATTACH, or through children calling PTRACE_TRACEME. - -3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via - PTRACE_TRACEME. Once set, this sysctl value cannot be changed. - -The original children-only logic was based on the restrictions in grsecurity. - -============================================================== diff --git a/MAINTAINERS b/MAINTAINERS index 4d8914ad710a..816947653ea2 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11573,6 +11573,7 @@ M: Kees Cook T: git git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux.git yama/tip S: Supported F: security/yama/ +F: Documentation/admin-guide/LSM/Yama.rst SENSABLE PHANTOM M: Jiri Slaby diff --git a/security/yama/Kconfig b/security/yama/Kconfig index 90c605eea892..96b27405558a 100644 --- a/security/yama/Kconfig +++ b/security/yama/Kconfig @@ -7,6 +7,7 @@ config SECURITY_YAMA system-wide security settings beyond regular Linux discretionary access controls. Currently available is ptrace scope restriction. Like capabilities, this security module stacks with other LSMs. - Further information can be found in Documentation/security/Yama.txt. + Further information can be found in + Documentation/admin-guide/LSM/Yama.rst. If you are unsure how to answer this question, answer N. -- cgit v1.2.3-59-g8ed1b From 30da4f77aae99bf9ae5905d0ef89668391eea315 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Sat, 13 May 2017 04:51:48 -0700 Subject: doc: ReSTify LoadPin.txt Adjusts for ReST markup and moves under LSM admin guide. Signed-off-by: Kees Cook Signed-off-by: Jonathan Corbet --- Documentation/admin-guide/LSM/LoadPin.rst | 21 +++++++++++++++++++++ Documentation/admin-guide/LSM/index.rst | 1 + Documentation/security/LoadPin.txt | 17 ----------------- MAINTAINERS | 1 + 4 files changed, 23 insertions(+), 17 deletions(-) create mode 100644 Documentation/admin-guide/LSM/LoadPin.rst delete mode 100644 Documentation/security/LoadPin.txt (limited to 'MAINTAINERS') diff --git a/Documentation/admin-guide/LSM/LoadPin.rst b/Documentation/admin-guide/LSM/LoadPin.rst new file mode 100644 index 000000000000..32070762d24c --- /dev/null +++ b/Documentation/admin-guide/LSM/LoadPin.rst @@ -0,0 +1,21 @@ +======= +LoadPin +======= + +LoadPin is a Linux Security Module that ensures all kernel-loaded files +(modules, firmware, etc) all originate from the same filesystem, with +the expectation that such a filesystem is backed by a read-only device +such as dm-verity or CDROM. This allows systems that have a verified +and/or unchangeable filesystem to enforce module and firmware loading +restrictions without needing to sign the files individually. + +The LSM is selectable at build-time with ``CONFIG_SECURITY_LOADPIN``, and +can be controlled at boot-time with the kernel command line option +"``loadpin.enabled``". By default, it is enabled, but can be disabled at +boot ("``loadpin.enabled=0``"). + +LoadPin starts pinning when it sees the first file loaded. If the +block device backing the filesystem is not read-only, a sysctl is +created to toggle pinning: ``/proc/sys/kernel/loadpin/enabled``. (Having +a mutable filesystem means pinning is mutable too, but having the +sysctl allows for easy testing on systems with a mutable filesystem.) diff --git a/Documentation/admin-guide/LSM/index.rst b/Documentation/admin-guide/LSM/index.rst index e5ba2c69b8ef..41f5262359f9 100644 --- a/Documentation/admin-guide/LSM/index.rst +++ b/Documentation/admin-guide/LSM/index.rst @@ -34,6 +34,7 @@ the one "major" module (e.g. SELinux) if there is one configured. :maxdepth: 1 apparmor + LoadPin SELinux tomoyo Yama diff --git a/Documentation/security/LoadPin.txt b/Documentation/security/LoadPin.txt deleted file mode 100644 index e11877f5d3d4..000000000000 --- a/Documentation/security/LoadPin.txt +++ /dev/null @@ -1,17 +0,0 @@ -LoadPin is a Linux Security Module that ensures all kernel-loaded files -(modules, firmware, etc) all originate from the same filesystem, with -the expectation that such a filesystem is backed by a read-only device -such as dm-verity or CDROM. This allows systems that have a verified -and/or unchangeable filesystem to enforce module and firmware loading -restrictions without needing to sign the files individually. - -The LSM is selectable at build-time with CONFIG_SECURITY_LOADPIN, and -can be controlled at boot-time with the kernel command line option -"loadpin.enabled". By default, it is enabled, but can be disabled at -boot ("loadpin.enabled=0"). - -LoadPin starts pinning when it sees the first file loaded. If the -block device backing the filesystem is not read-only, a sysctl is -created to toggle pinning: /proc/sys/kernel/loadpin/enabled. (Having -a mutable filesystem means pinning is mutable too, but having the -sysctl allows for easy testing on systems with a mutable filesystem.) diff --git a/MAINTAINERS b/MAINTAINERS index 816947653ea2..38a3d95d2d63 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11567,6 +11567,7 @@ M: Kees Cook T: git git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux.git lsm/loadpin S: Supported F: security/loadpin/ +F: Documentation/admin-guide/LSM/LoadPin.rst YAMA SECURITY MODULE M: Kees Cook -- cgit v1.2.3-59-g8ed1b From a5606ced286197cc280dbf3b880c6167bba9462d Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Sat, 13 May 2017 04:51:49 -0700 Subject: doc: ReSTify Smack.txt Adjusts for ReST markup and moves under LSM admin guide. Acked-by: Casey Schaufler Signed-off-by: Kees Cook Signed-off-by: Jonathan Corbet --- Documentation/admin-guide/LSM/Smack.rst | 857 ++++++++++++++++++++++++++++++++ Documentation/admin-guide/LSM/index.rst | 1 + Documentation/security/00-INDEX | 2 - Documentation/security/Smack.txt | 752 ---------------------------- MAINTAINERS | 2 +- 5 files changed, 859 insertions(+), 755 deletions(-) create mode 100644 Documentation/admin-guide/LSM/Smack.rst delete mode 100644 Documentation/security/Smack.txt (limited to 'MAINTAINERS') diff --git a/Documentation/admin-guide/LSM/Smack.rst b/Documentation/admin-guide/LSM/Smack.rst new file mode 100644 index 000000000000..6a5826a13aea --- /dev/null +++ b/Documentation/admin-guide/LSM/Smack.rst @@ -0,0 +1,857 @@ +===== +Smack +===== + + + "Good for you, you've decided to clean the elevator!" + - The Elevator, from Dark Star + +Smack is the Simplified Mandatory Access Control Kernel. +Smack is a kernel based implementation of mandatory access +control that includes simplicity in its primary design goals. + +Smack is not the only Mandatory Access Control scheme +available for Linux. Those new to Mandatory Access Control +are encouraged to compare Smack with the other mechanisms +available to determine which is best suited to the problem +at hand. + +Smack consists of three major components: + + - The kernel + - Basic utilities, which are helpful but not required + - Configuration data + +The kernel component of Smack is implemented as a Linux +Security Modules (LSM) module. It requires netlabel and +works best with file systems that support extended attributes, +although xattr support is not strictly required. +It is safe to run a Smack kernel under a "vanilla" distribution. + +Smack kernels use the CIPSO IP option. Some network +configurations are intolerant of IP options and can impede +access to systems that use them as Smack does. + +Smack is used in the Tizen operating system. Please +go to http://wiki.tizen.org for information about how +Smack is used in Tizen. + +The current git repository for Smack user space is: + + git://github.com/smack-team/smack.git + +This should make and install on most modern distributions. +There are five commands included in smackutil: + +chsmack: + display or set Smack extended attribute values + +smackctl: + load the Smack access rules + +smackaccess: + report if a process with one label has access + to an object with another + +These two commands are obsolete with the introduction of +the smackfs/load2 and smackfs/cipso2 interfaces. + +smackload: + properly formats data for writing to smackfs/load + +smackcipso: + properly formats data for writing to smackfs/cipso + +In keeping with the intent of Smack, configuration data is +minimal and not strictly required. The most important +configuration step is mounting the smackfs pseudo filesystem. +If smackutil is installed the startup script will take care +of this, but it can be manually as well. + +Add this line to ``/etc/fstab``:: + + smackfs /sys/fs/smackfs smackfs defaults 0 0 + +The ``/sys/fs/smackfs`` directory is created by the kernel. + +Smack uses extended attributes (xattrs) to store labels on filesystem +objects. The attributes are stored in the extended attribute security +name space. A process must have ``CAP_MAC_ADMIN`` to change any of these +attributes. + +The extended attributes that Smack uses are: + +SMACK64 + Used to make access control decisions. In almost all cases + the label given to a new filesystem object will be the label + of the process that created it. + +SMACK64EXEC + The Smack label of a process that execs a program file with + this attribute set will run with this attribute's value. + +SMACK64MMAP + Don't allow the file to be mmapped by a process whose Smack + label does not allow all of the access permitted to a process + with the label contained in this attribute. This is a very + specific use case for shared libraries. + +SMACK64TRANSMUTE + Can only have the value "TRUE". If this attribute is present + on a directory when an object is created in the directory and + the Smack rule (more below) that permitted the write access + to the directory includes the transmute ("t") mode the object + gets the label of the directory instead of the label of the + creating process. If the object being created is a directory + the SMACK64TRANSMUTE attribute is set as well. + +SMACK64IPIN + This attribute is only available on file descriptors for sockets. + Use the Smack label in this attribute for access control + decisions on packets being delivered to this socket. + +SMACK64IPOUT + This attribute is only available on file descriptors for sockets. + Use the Smack label in this attribute for access control + decisions on packets coming from this socket. + +There are multiple ways to set a Smack label on a file:: + + # attr -S -s SMACK64 -V "value" path + # chsmack -a value path + +A process can see the Smack label it is running with by +reading ``/proc/self/attr/current``. A process with ``CAP_MAC_ADMIN`` +can set the process Smack by writing there. + +Most Smack configuration is accomplished by writing to files +in the smackfs filesystem. This pseudo-filesystem is mounted +on ``/sys/fs/smackfs``. + +access + Provided for backward compatibility. The access2 interface + is preferred and should be used instead. + This interface reports whether a subject with the specified + Smack label has a particular access to an object with a + specified Smack label. Write a fixed format access rule to + this file. The next read will indicate whether the access + would be permitted. The text will be either "1" indicating + access, or "0" indicating denial. + +access2 + This interface reports whether a subject with the specified + Smack label has a particular access to an object with a + specified Smack label. Write a long format access rule to + this file. The next read will indicate whether the access + would be permitted. The text will be either "1" indicating + access, or "0" indicating denial. + +ambient + This contains the Smack label applied to unlabeled network + packets. + +change-rule + This interface allows modification of existing access control rules. + The format accepted on write is:: + + "%s %s %s %s" + + where the first string is the subject label, the second the + object label, the third the access to allow and the fourth the + access to deny. The access strings may contain only the characters + "rwxat-". If a rule for a given subject and object exists it will be + modified by enabling the permissions in the third string and disabling + those in the fourth string. If there is no such rule it will be + created using the access specified in the third and the fourth strings. + +cipso + Provided for backward compatibility. The cipso2 interface + is preferred and should be used instead. + This interface allows a specific CIPSO header to be assigned + to a Smack label. The format accepted on write is:: + + "%24s%4d%4d"["%4d"]... + + The first string is a fixed Smack label. The first number is + the level to use. The second number is the number of categories. + The following numbers are the categories:: + + "level-3-cats-5-19 3 2 5 19" + +cipso2 + This interface allows a specific CIPSO header to be assigned + to a Smack label. The format accepted on write is:: + + "%s%4d%4d"["%4d"]... + + The first string is a long Smack label. The first number is + the level to use. The second number is the number of categories. + The following numbers are the categories:: + + "level-3-cats-5-19 3 2 5 19" + +direct + This contains the CIPSO level used for Smack direct label + representation in network packets. + +doi + This contains the CIPSO domain of interpretation used in + network packets. + +ipv6host + This interface allows specific IPv6 internet addresses to be + treated as single label hosts. Packets are sent to single + label hosts only from processes that have Smack write access + to the host label. All packets received from single label hosts + are given the specified label. The format accepted on write is:: + + "%h:%h:%h:%h:%h:%h:%h:%h label" or + "%h:%h:%h:%h:%h:%h:%h:%h/%d label". + + The "::" address shortcut is not supported. + If label is "-DELETE" a matched entry will be deleted. + +load + Provided for backward compatibility. The load2 interface + is preferred and should be used instead. + This interface allows access control rules in addition to + the system defined rules to be specified. The format accepted + on write is:: + + "%24s%24s%5s" + + where the first string is the subject label, the second the + object label, and the third the requested access. The access + string may contain only the characters "rwxat-", and specifies + which sort of access is allowed. The "-" is a placeholder for + permissions that are not allowed. The string "r-x--" would + specify read and execute access. Labels are limited to 23 + characters in length. + +load2 + This interface allows access control rules in addition to + the system defined rules to be specified. The format accepted + on write is:: + + "%s %s %s" + + where the first string is the subject label, the second the + object label, and the third the requested access. The access + string may contain only the characters "rwxat-", and specifies + which sort of access is allowed. The "-" is a placeholder for + permissions that are not allowed. The string "r-x--" would + specify read and execute access. + +load-self + Provided for backward compatibility. The load-self2 interface + is preferred and should be used instead. + This interface allows process specific access rules to be + defined. These rules are only consulted if access would + otherwise be permitted, and are intended to provide additional + restrictions on the process. The format is the same as for + the load interface. + +load-self2 + This interface allows process specific access rules to be + defined. These rules are only consulted if access would + otherwise be permitted, and are intended to provide additional + restrictions on the process. The format is the same as for + the load2 interface. + +logging + This contains the Smack logging state. + +mapped + This contains the CIPSO level used for Smack mapped label + representation in network packets. + +netlabel + This interface allows specific internet addresses to be + treated as single label hosts. Packets are sent to single + label hosts without CIPSO headers, but only from processes + that have Smack write access to the host label. All packets + received from single label hosts are given the specified + label. The format accepted on write is:: + + "%d.%d.%d.%d label" or "%d.%d.%d.%d/%d label". + + If the label specified is "-CIPSO" the address is treated + as a host that supports CIPSO headers. + +onlycap + This contains labels processes must have for CAP_MAC_ADMIN + and ``CAP_MAC_OVERRIDE`` to be effective. If this file is empty + these capabilities are effective at for processes with any + label. The values are set by writing the desired labels, separated + by spaces, to the file or cleared by writing "-" to the file. + +ptrace + This is used to define the current ptrace policy + + 0 - default: + this is the policy that relies on Smack access rules. + For the ``PTRACE_READ`` a subject needs to have a read access on + object. For the ``PTRACE_ATTACH`` a read-write access is required. + + 1 - exact: + this is the policy that limits ``PTRACE_ATTACH``. Attach is + only allowed when subject's and object's labels are equal. + ``PTRACE_READ`` is not affected. Can be overridden with ``CAP_SYS_PTRACE``. + + 2 - draconian: + this policy behaves like the 'exact' above with an + exception that it can't be overridden with ``CAP_SYS_PTRACE``. + +revoke-subject + Writing a Smack label here sets the access to '-' for all access + rules with that subject label. + +unconfined + If the kernel is configured with ``CONFIG_SECURITY_SMACK_BRINGUP`` + a process with ``CAP_MAC_ADMIN`` can write a label into this interface. + Thereafter, accesses that involve that label will be logged and + the access permitted if it wouldn't be otherwise. Note that this + is dangerous and can ruin the proper labeling of your system. + It should never be used in production. + +relabel-self + This interface contains a list of labels to which the process can + transition to, by writing to ``/proc/self/attr/current``. + Normally a process can change its own label to any legal value, but only + if it has ``CAP_MAC_ADMIN``. This interface allows a process without + ``CAP_MAC_ADMIN`` to relabel itself to one of labels from predefined list. + A process without ``CAP_MAC_ADMIN`` can change its label only once. When it + does, this list will be cleared. + The values are set by writing the desired labels, separated + by spaces, to the file or cleared by writing "-" to the file. + +If you are using the smackload utility +you can add access rules in ``/etc/smack/accesses``. They take the form:: + + subjectlabel objectlabel access + +access is a combination of the letters rwxatb which specify the +kind of access permitted a subject with subjectlabel on an +object with objectlabel. If there is no rule no access is allowed. + +Look for additional programs on http://schaufler-ca.com + +The Simplified Mandatory Access Control Kernel (Whitepaper) +=========================================================== + +Casey Schaufler +casey@schaufler-ca.com + +Mandatory Access Control +------------------------ + +Computer systems employ a variety of schemes to constrain how information is +shared among the people and services using the machine. Some of these schemes +allow the program or user to decide what other programs or users are allowed +access to pieces of data. These schemes are called discretionary access +control mechanisms because the access control is specified at the discretion +of the user. Other schemes do not leave the decision regarding what a user or +program can access up to users or programs. These schemes are called mandatory +access control mechanisms because you don't have a choice regarding the users +or programs that have access to pieces of data. + +Bell & LaPadula +--------------- + +From the middle of the 1980's until the turn of the century Mandatory Access +Control (MAC) was very closely associated with the Bell & LaPadula security +model, a mathematical description of the United States Department of Defense +policy for marking paper documents. MAC in this form enjoyed a following +within the Capital Beltway and Scandinavian supercomputer centers but was +often sited as failing to address general needs. + +Domain Type Enforcement +----------------------- + +Around the turn of the century Domain Type Enforcement (DTE) became popular. +This scheme organizes users, programs, and data into domains that are +protected from each other. This scheme has been widely deployed as a component +of popular Linux distributions. The administrative overhead required to +maintain this scheme and the detailed understanding of the whole system +necessary to provide a secure domain mapping leads to the scheme being +disabled or used in limited ways in the majority of cases. + +Smack +----- + +Smack is a Mandatory Access Control mechanism designed to provide useful MAC +while avoiding the pitfalls of its predecessors. The limitations of Bell & +LaPadula are addressed by providing a scheme whereby access can be controlled +according to the requirements of the system and its purpose rather than those +imposed by an arcane government policy. The complexity of Domain Type +Enforcement and avoided by defining access controls in terms of the access +modes already in use. + +Smack Terminology +----------------- + +The jargon used to talk about Smack will be familiar to those who have dealt +with other MAC systems and shouldn't be too difficult for the uninitiated to +pick up. There are four terms that are used in a specific way and that are +especially important: + + Subject: + A subject is an active entity on the computer system. + On Smack a subject is a task, which is in turn the basic unit + of execution. + + Object: + An object is a passive entity on the computer system. + On Smack files of all types, IPC, and tasks can be objects. + + Access: + Any attempt by a subject to put information into or get + information from an object is an access. + + Label: + Data that identifies the Mandatory Access Control + characteristics of a subject or an object. + +These definitions are consistent with the traditional use in the security +community. There are also some terms from Linux that are likely to crop up: + + Capability: + A task that possesses a capability has permission to + violate an aspect of the system security policy, as identified by + the specific capability. A task that possesses one or more + capabilities is a privileged task, whereas a task with no + capabilities is an unprivileged task. + + Privilege: + A task that is allowed to violate the system security + policy is said to have privilege. As of this writing a task can + have privilege either by possessing capabilities or by having an + effective user of root. + +Smack Basics +------------ + +Smack is an extension to a Linux system. It enforces additional restrictions +on what subjects can access which objects, based on the labels attached to +each of the subject and the object. + +Labels +~~~~~~ + +Smack labels are ASCII character strings. They can be up to 255 characters +long, but keeping them to twenty-three characters is recommended. +Single character labels using special characters, that being anything +other than a letter or digit, are reserved for use by the Smack development +team. Smack labels are unstructured, case sensitive, and the only operation +ever performed on them is comparison for equality. Smack labels cannot +contain unprintable characters, the "/" (slash), the "\" (backslash), the "'" +(quote) and '"' (double-quote) characters. +Smack labels cannot begin with a '-'. This is reserved for special options. + +There are some predefined labels:: + + _ Pronounced "floor", a single underscore character. + ^ Pronounced "hat", a single circumflex character. + * Pronounced "star", a single asterisk character. + ? Pronounced "huh", a single question mark character. + @ Pronounced "web", a single at sign character. + +Every task on a Smack system is assigned a label. The Smack label +of a process will usually be assigned by the system initialization +mechanism. + +Access Rules +~~~~~~~~~~~~ + +Smack uses the traditional access modes of Linux. These modes are read, +execute, write, and occasionally append. There are a few cases where the +access mode may not be obvious. These include: + + Signals: + A signal is a write operation from the subject task to + the object task. + + Internet Domain IPC: + Transmission of a packet is considered a + write operation from the source task to the destination task. + +Smack restricts access based on the label attached to a subject and the label +attached to the object it is trying to access. The rules enforced are, in +order: + + 1. Any access requested by a task labeled "*" is denied. + 2. A read or execute access requested by a task labeled "^" + is permitted. + 3. A read or execute access requested on an object labeled "_" + is permitted. + 4. Any access requested on an object labeled "*" is permitted. + 5. Any access requested by a task on an object with the same + label is permitted. + 6. Any access requested that is explicitly defined in the loaded + rule set is permitted. + 7. Any other access is denied. + +Smack Access Rules +~~~~~~~~~~~~~~~~~~ + +With the isolation provided by Smack access separation is simple. There are +many interesting cases where limited access by subjects to objects with +different labels is desired. One example is the familiar spy model of +sensitivity, where a scientist working on a highly classified project would be +able to read documents of lower classifications and anything she writes will +be "born" highly classified. To accommodate such schemes Smack includes a +mechanism for specifying rules allowing access between labels. + +Access Rule Format +~~~~~~~~~~~~~~~~~~ + +The format of an access rule is:: + + subject-label object-label access + +Where subject-label is the Smack label of the task, object-label is the Smack +label of the thing being accessed, and access is a string specifying the sort +of access allowed. The access specification is searched for letters that +describe access modes: + + a: indicates that append access should be granted. + r: indicates that read access should be granted. + w: indicates that write access should be granted. + x: indicates that execute access should be granted. + t: indicates that the rule requests transmutation. + b: indicates that the rule should be reported for bring-up. + +Uppercase values for the specification letters are allowed as well. +Access mode specifications can be in any order. Examples of acceptable rules +are:: + + TopSecret Secret rx + Secret Unclass R + Manager Game x + User HR w + Snap Crackle rwxatb + New Old rRrRr + Closed Off - + +Examples of unacceptable rules are:: + + Top Secret Secret rx + Ace Ace r + Odd spells waxbeans + +Spaces are not allowed in labels. Since a subject always has access to files +with the same label specifying a rule for that case is pointless. Only +valid letters (rwxatbRWXATB) and the dash ('-') character are allowed in +access specifications. The dash is a placeholder, so "a-r" is the same +as "ar". A lone dash is used to specify that no access should be allowed. + +Applying Access Rules +~~~~~~~~~~~~~~~~~~~~~ + +The developers of Linux rarely define new sorts of things, usually importing +schemes and concepts from other systems. Most often, the other systems are +variants of Unix. Unix has many endearing properties, but consistency of +access control models is not one of them. Smack strives to treat accesses as +uniformly as is sensible while keeping with the spirit of the underlying +mechanism. + +File system objects including files, directories, named pipes, symbolic links, +and devices require access permissions that closely match those used by mode +bit access. To open a file for reading read access is required on the file. To +search a directory requires execute access. Creating a file with write access +requires both read and write access on the containing directory. Deleting a +file requires read and write access to the file and to the containing +directory. It is possible that a user may be able to see that a file exists +but not any of its attributes by the circumstance of having read access to the +containing directory but not to the differently labeled file. This is an +artifact of the file name being data in the directory, not a part of the file. + +If a directory is marked as transmuting (SMACK64TRANSMUTE=TRUE) and the +access rule that allows a process to create an object in that directory +includes 't' access the label assigned to the new object will be that +of the directory, not the creating process. This makes it much easier +for two processes with different labels to share data without granting +access to all of their files. + +IPC objects, message queues, semaphore sets, and memory segments exist in flat +namespaces and access requests are only required to match the object in +question. + +Process objects reflect tasks on the system and the Smack label used to access +them is the same Smack label that the task would use for its own access +attempts. Sending a signal via the kill() system call is a write operation +from the signaler to the recipient. Debugging a process requires both reading +and writing. Creating a new task is an internal operation that results in two +tasks with identical Smack labels and requires no access checks. + +Sockets are data structures attached to processes and sending a packet from +one process to another requires that the sender have write access to the +receiver. The receiver is not required to have read access to the sender. + +Setting Access Rules +~~~~~~~~~~~~~~~~~~~~ + +The configuration file /etc/smack/accesses contains the rules to be set at +system startup. The contents are written to the special file +/sys/fs/smackfs/load2. Rules can be added at any time and take effect +immediately. For any pair of subject and object labels there can be only +one rule, with the most recently specified overriding any earlier +specification. + +Task Attribute +~~~~~~~~~~~~~~ + +The Smack label of a process can be read from /proc//attr/current. A +process can read its own Smack label from /proc/self/attr/current. A +privileged process can change its own Smack label by writing to +/proc/self/attr/current but not the label of another process. + +File Attribute +~~~~~~~~~~~~~~ + +The Smack label of a filesystem object is stored as an extended attribute +named SMACK64 on the file. This attribute is in the security namespace. It can +only be changed by a process with privilege. + +Privilege +~~~~~~~~~ + +A process with CAP_MAC_OVERRIDE or CAP_MAC_ADMIN is privileged. +CAP_MAC_OVERRIDE allows the process access to objects it would +be denied otherwise. CAP_MAC_ADMIN allows a process to change +Smack data, including rules and attributes. + +Smack Networking +~~~~~~~~~~~~~~~~ + +As mentioned before, Smack enforces access control on network protocol +transmissions. Every packet sent by a Smack process is tagged with its Smack +label. This is done by adding a CIPSO tag to the header of the IP packet. Each +packet received is expected to have a CIPSO tag that identifies the label and +if it lacks such a tag the network ambient label is assumed. Before the packet +is delivered a check is made to determine that a subject with the label on the +packet has write access to the receiving process and if that is not the case +the packet is dropped. + +CIPSO Configuration +~~~~~~~~~~~~~~~~~~~ + +It is normally unnecessary to specify the CIPSO configuration. The default +values used by the system handle all internal cases. Smack will compose CIPSO +label values to match the Smack labels being used without administrative +intervention. Unlabeled packets that come into the system will be given the +ambient label. + +Smack requires configuration in the case where packets from a system that is +not Smack that speaks CIPSO may be encountered. Usually this will be a Trusted +Solaris system, but there are other, less widely deployed systems out there. +CIPSO provides 3 important values, a Domain Of Interpretation (DOI), a level, +and a category set with each packet. The DOI is intended to identify a group +of systems that use compatible labeling schemes, and the DOI specified on the +Smack system must match that of the remote system or packets will be +discarded. The DOI is 3 by default. The value can be read from +/sys/fs/smackfs/doi and can be changed by writing to /sys/fs/smackfs/doi. + +The label and category set are mapped to a Smack label as defined in +/etc/smack/cipso. + +A Smack/CIPSO mapping has the form:: + + smack level [category [category]*] + +Smack does not expect the level or category sets to be related in any +particular way and does not assume or assign accesses based on them. Some +examples of mappings:: + + TopSecret 7 + TS:A,B 7 1 2 + SecBDE 5 2 4 6 + RAFTERS 7 12 26 + +The ":" and "," characters are permitted in a Smack label but have no special +meaning. + +The mapping of Smack labels to CIPSO values is defined by writing to +/sys/fs/smackfs/cipso2. + +In addition to explicit mappings Smack supports direct CIPSO mappings. One +CIPSO level is used to indicate that the category set passed in the packet is +in fact an encoding of the Smack label. The level used is 250 by default. The +value can be read from /sys/fs/smackfs/direct and changed by writing to +/sys/fs/smackfs/direct. + +Socket Attributes +~~~~~~~~~~~~~~~~~ + +There are two attributes that are associated with sockets. These attributes +can only be set by privileged tasks, but any task can read them for their own +sockets. + + SMACK64IPIN: + The Smack label of the task object. A privileged + program that will enforce policy may set this to the star label. + + SMACK64IPOUT: + The Smack label transmitted with outgoing packets. + A privileged program may set this to match the label of another + task with which it hopes to communicate. + +Smack Netlabel Exceptions +~~~~~~~~~~~~~~~~~~~~~~~~~ + +You will often find that your labeled application has to talk to the outside, +unlabeled world. To do this there's a special file /sys/fs/smackfs/netlabel +where you can add some exceptions in the form of:: + + @IP1 LABEL1 or + @IP2/MASK LABEL2 + +It means that your application will have unlabeled access to @IP1 if it has +write access on LABEL1, and access to the subnet @IP2/MASK if it has write +access on LABEL2. + +Entries in the /sys/fs/smackfs/netlabel file are matched by longest mask +first, like in classless IPv4 routing. + +A special label '@' and an option '-CIPSO' can be used there:: + + @ means Internet, any application with any label has access to it + -CIPSO means standard CIPSO networking + +If you don't know what CIPSO is and don't plan to use it, you can just do:: + + echo 127.0.0.1 -CIPSO > /sys/fs/smackfs/netlabel + echo 0.0.0.0/0 @ > /sys/fs/smackfs/netlabel + +If you use CIPSO on your 192.168.0.0/16 local network and need also unlabeled +Internet access, you can have:: + + echo 127.0.0.1 -CIPSO > /sys/fs/smackfs/netlabel + echo 192.168.0.0/16 -CIPSO > /sys/fs/smackfs/netlabel + echo 0.0.0.0/0 @ > /sys/fs/smackfs/netlabel + +Writing Applications for Smack +------------------------------ + +There are three sorts of applications that will run on a Smack system. How an +application interacts with Smack will determine what it will have to do to +work properly under Smack. + +Smack Ignorant Applications +--------------------------- + +By far the majority of applications have no reason whatever to care about the +unique properties of Smack. Since invoking a program has no impact on the +Smack label associated with the process the only concern likely to arise is +whether the process has execute access to the program. + +Smack Relevant Applications +--------------------------- + +Some programs can be improved by teaching them about Smack, but do not make +any security decisions themselves. The utility ls(1) is one example of such a +program. + +Smack Enforcing Applications +---------------------------- + +These are special programs that not only know about Smack, but participate in +the enforcement of system policy. In most cases these are the programs that +set up user sessions. There are also network services that provide information +to processes running with various labels. + +File System Interfaces +---------------------- + +Smack maintains labels on file system objects using extended attributes. The +Smack label of a file, directory, or other file system object can be obtained +using getxattr(2):: + + len = getxattr("/", "security.SMACK64", value, sizeof (value)); + +will put the Smack label of the root directory into value. A privileged +process can set the Smack label of a file system object with setxattr(2):: + + len = strlen("Rubble"); + rc = setxattr("/foo", "security.SMACK64", "Rubble", len, 0); + +will set the Smack label of /foo to "Rubble" if the program has appropriate +privilege. + +Socket Interfaces +----------------- + +The socket attributes can be read using fgetxattr(2). + +A privileged process can set the Smack label of outgoing packets with +fsetxattr(2):: + + len = strlen("Rubble"); + rc = fsetxattr(fd, "security.SMACK64IPOUT", "Rubble", len, 0); + +will set the Smack label "Rubble" on packets going out from the socket if the +program has appropriate privilege:: + + rc = fsetxattr(fd, "security.SMACK64IPIN, "*", strlen("*"), 0); + +will set the Smack label "*" as the object label against which incoming +packets will be checked if the program has appropriate privilege. + +Administration +-------------- + +Smack supports some mount options: + + smackfsdef=label: + specifies the label to give files that lack + the Smack label extended attribute. + + smackfsroot=label: + specifies the label to assign the root of the + file system if it lacks the Smack extended attribute. + + smackfshat=label: + specifies a label that must have read access to + all labels set on the filesystem. Not yet enforced. + + smackfsfloor=label: + specifies a label to which all labels set on the + filesystem must have read access. Not yet enforced. + +These mount options apply to all file system types. + +Smack auditing +-------------- + +If you want Smack auditing of security events, you need to set CONFIG_AUDIT +in your kernel configuration. +By default, all denied events will be audited. You can change this behavior by +writing a single character to the /sys/fs/smackfs/logging file:: + + 0 : no logging + 1 : log denied (default) + 2 : log accepted + 3 : log denied & accepted + +Events are logged as 'key=value' pairs, for each event you at least will get +the subject, the object, the rights requested, the action, the kernel function +that triggered the event, plus other pairs depending on the type of event +audited. + +Bringup Mode +------------ + +Bringup mode provides logging features that can make application +configuration and system bringup easier. Configure the kernel with +CONFIG_SECURITY_SMACK_BRINGUP to enable these features. When bringup +mode is enabled accesses that succeed due to rules marked with the "b" +access mode will logged. When a new label is introduced for processes +rules can be added aggressively, marked with the "b". The logging allows +tracking of which rules actual get used for that label. + +Another feature of bringup mode is the "unconfined" option. Writing +a label to /sys/fs/smackfs/unconfined makes subjects with that label +able to access any object, and objects with that label accessible to +all subjects. Any access that is granted because a label is unconfined +is logged. This feature is dangerous, as files and directories may +be created in places they couldn't if the policy were being enforced. diff --git a/Documentation/admin-guide/LSM/index.rst b/Documentation/admin-guide/LSM/index.rst index 41f5262359f9..c980dfe9abf1 100644 --- a/Documentation/admin-guide/LSM/index.rst +++ b/Documentation/admin-guide/LSM/index.rst @@ -36,5 +36,6 @@ the one "major" module (e.g. SELinux) if there is one configured. apparmor LoadPin SELinux + Smack tomoyo Yama diff --git a/Documentation/security/00-INDEX b/Documentation/security/00-INDEX index a55f781be0dd..cdb2294ec047 100644 --- a/Documentation/security/00-INDEX +++ b/Documentation/security/00-INDEX @@ -1,7 +1,5 @@ 00-INDEX - this file. -Smack.txt - - documentation on the Smack Linux Security Module. keys-ecryptfs.txt - description of the encryption keys for the ecryptfs filesystem. keys-request-key.txt diff --git a/Documentation/security/Smack.txt b/Documentation/security/Smack.txt deleted file mode 100644 index 945cc633d883..000000000000 --- a/Documentation/security/Smack.txt +++ /dev/null @@ -1,752 +0,0 @@ - - - "Good for you, you've decided to clean the elevator!" - - The Elevator, from Dark Star - -Smack is the Simplified Mandatory Access Control Kernel. -Smack is a kernel based implementation of mandatory access -control that includes simplicity in its primary design goals. - -Smack is not the only Mandatory Access Control scheme -available for Linux. Those new to Mandatory Access Control -are encouraged to compare Smack with the other mechanisms -available to determine which is best suited to the problem -at hand. - -Smack consists of three major components: - - The kernel - - Basic utilities, which are helpful but not required - - Configuration data - -The kernel component of Smack is implemented as a Linux -Security Modules (LSM) module. It requires netlabel and -works best with file systems that support extended attributes, -although xattr support is not strictly required. -It is safe to run a Smack kernel under a "vanilla" distribution. - -Smack kernels use the CIPSO IP option. Some network -configurations are intolerant of IP options and can impede -access to systems that use them as Smack does. - -Smack is used in the Tizen operating system. Please -go to http://wiki.tizen.org for information about how -Smack is used in Tizen. - -The current git repository for Smack user space is: - - git://github.com/smack-team/smack.git - -This should make and install on most modern distributions. -There are five commands included in smackutil: - -chsmack - display or set Smack extended attribute values -smackctl - load the Smack access rules -smackaccess - report if a process with one label has access - to an object with another - -These two commands are obsolete with the introduction of -the smackfs/load2 and smackfs/cipso2 interfaces. - -smackload - properly formats data for writing to smackfs/load -smackcipso - properly formats data for writing to smackfs/cipso - -In keeping with the intent of Smack, configuration data is -minimal and not strictly required. The most important -configuration step is mounting the smackfs pseudo filesystem. -If smackutil is installed the startup script will take care -of this, but it can be manually as well. - -Add this line to /etc/fstab: - - smackfs /sys/fs/smackfs smackfs defaults 0 0 - -The /sys/fs/smackfs directory is created by the kernel. - -Smack uses extended attributes (xattrs) to store labels on filesystem -objects. The attributes are stored in the extended attribute security -name space. A process must have CAP_MAC_ADMIN to change any of these -attributes. - -The extended attributes that Smack uses are: - -SMACK64 - Used to make access control decisions. In almost all cases - the label given to a new filesystem object will be the label - of the process that created it. -SMACK64EXEC - The Smack label of a process that execs a program file with - this attribute set will run with this attribute's value. -SMACK64MMAP - Don't allow the file to be mmapped by a process whose Smack - label does not allow all of the access permitted to a process - with the label contained in this attribute. This is a very - specific use case for shared libraries. -SMACK64TRANSMUTE - Can only have the value "TRUE". If this attribute is present - on a directory when an object is created in the directory and - the Smack rule (more below) that permitted the write access - to the directory includes the transmute ("t") mode the object - gets the label of the directory instead of the label of the - creating process. If the object being created is a directory - the SMACK64TRANSMUTE attribute is set as well. -SMACK64IPIN - This attribute is only available on file descriptors for sockets. - Use the Smack label in this attribute for access control - decisions on packets being delivered to this socket. -SMACK64IPOUT - This attribute is only available on file descriptors for sockets. - Use the Smack label in this attribute for access control - decisions on packets coming from this socket. - -There are multiple ways to set a Smack label on a file: - - # attr -S -s SMACK64 -V "value" path - # chsmack -a value path - -A process can see the Smack label it is running with by -reading /proc/self/attr/current. A process with CAP_MAC_ADMIN -can set the process Smack by writing there. - -Most Smack configuration is accomplished by writing to files -in the smackfs filesystem. This pseudo-filesystem is mounted -on /sys/fs/smackfs. - -access - Provided for backward compatibility. The access2 interface - is preferred and should be used instead. - This interface reports whether a subject with the specified - Smack label has a particular access to an object with a - specified Smack label. Write a fixed format access rule to - this file. The next read will indicate whether the access - would be permitted. The text will be either "1" indicating - access, or "0" indicating denial. -access2 - This interface reports whether a subject with the specified - Smack label has a particular access to an object with a - specified Smack label. Write a long format access rule to - this file. The next read will indicate whether the access - would be permitted. The text will be either "1" indicating - access, or "0" indicating denial. -ambient - This contains the Smack label applied to unlabeled network - packets. -change-rule - This interface allows modification of existing access control rules. - The format accepted on write is: - "%s %s %s %s" - where the first string is the subject label, the second the - object label, the third the access to allow and the fourth the - access to deny. The access strings may contain only the characters - "rwxat-". If a rule for a given subject and object exists it will be - modified by enabling the permissions in the third string and disabling - those in the fourth string. If there is no such rule it will be - created using the access specified in the third and the fourth strings. -cipso - Provided for backward compatibility. The cipso2 interface - is preferred and should be used instead. - This interface allows a specific CIPSO header to be assigned - to a Smack label. The format accepted on write is: - "%24s%4d%4d"["%4d"]... - The first string is a fixed Smack label. The first number is - the level to use. The second number is the number of categories. - The following numbers are the categories. - "level-3-cats-5-19 3 2 5 19" -cipso2 - This interface allows a specific CIPSO header to be assigned - to a Smack label. The format accepted on write is: - "%s%4d%4d"["%4d"]... - The first string is a long Smack label. The first number is - the level to use. The second number is the number of categories. - The following numbers are the categories. - "level-3-cats-5-19 3 2 5 19" -direct - This contains the CIPSO level used for Smack direct label - representation in network packets. -doi - This contains the CIPSO domain of interpretation used in - network packets. -ipv6host - This interface allows specific IPv6 internet addresses to be - treated as single label hosts. Packets are sent to single - label hosts only from processes that have Smack write access - to the host label. All packets received from single label hosts - are given the specified label. The format accepted on write is: - "%h:%h:%h:%h:%h:%h:%h:%h label" or - "%h:%h:%h:%h:%h:%h:%h:%h/%d label". - The "::" address shortcut is not supported. - If label is "-DELETE" a matched entry will be deleted. -load - Provided for backward compatibility. The load2 interface - is preferred and should be used instead. - This interface allows access control rules in addition to - the system defined rules to be specified. The format accepted - on write is: - "%24s%24s%5s" - where the first string is the subject label, the second the - object label, and the third the requested access. The access - string may contain only the characters "rwxat-", and specifies - which sort of access is allowed. The "-" is a placeholder for - permissions that are not allowed. The string "r-x--" would - specify read and execute access. Labels are limited to 23 - characters in length. -load2 - This interface allows access control rules in addition to - the system defined rules to be specified. The format accepted - on write is: - "%s %s %s" - where the first string is the subject label, the second the - object label, and the third the requested access. The access - string may contain only the characters "rwxat-", and specifies - which sort of access is allowed. The "-" is a placeholder for - permissions that are not allowed. The string "r-x--" would - specify read and execute access. -load-self - Provided for backward compatibility. The load-self2 interface - is preferred and should be used instead. - This interface allows process specific access rules to be - defined. These rules are only consulted if access would - otherwise be permitted, and are intended to provide additional - restrictions on the process. The format is the same as for - the load interface. -load-self2 - This interface allows process specific access rules to be - defined. These rules are only consulted if access would - otherwise be permitted, and are intended to provide additional - restrictions on the process. The format is the same as for - the load2 interface. -logging - This contains the Smack logging state. -mapped - This contains the CIPSO level used for Smack mapped label - representation in network packets. -netlabel - This interface allows specific internet addresses to be - treated as single label hosts. Packets are sent to single - label hosts without CIPSO headers, but only from processes - that have Smack write access to the host label. All packets - received from single label hosts are given the specified - label. The format accepted on write is: - "%d.%d.%d.%d label" or "%d.%d.%d.%d/%d label". - If the label specified is "-CIPSO" the address is treated - as a host that supports CIPSO headers. -onlycap - This contains labels processes must have for CAP_MAC_ADMIN - and CAP_MAC_OVERRIDE to be effective. If this file is empty - these capabilities are effective at for processes with any - label. The values are set by writing the desired labels, separated - by spaces, to the file or cleared by writing "-" to the file. -ptrace - This is used to define the current ptrace policy - 0 - default: this is the policy that relies on Smack access rules. - For the PTRACE_READ a subject needs to have a read access on - object. For the PTRACE_ATTACH a read-write access is required. - 1 - exact: this is the policy that limits PTRACE_ATTACH. Attach is - only allowed when subject's and object's labels are equal. - PTRACE_READ is not affected. Can be overridden with CAP_SYS_PTRACE. - 2 - draconian: this policy behaves like the 'exact' above with an - exception that it can't be overridden with CAP_SYS_PTRACE. -revoke-subject - Writing a Smack label here sets the access to '-' for all access - rules with that subject label. -unconfined - If the kernel is configured with CONFIG_SECURITY_SMACK_BRINGUP - a process with CAP_MAC_ADMIN can write a label into this interface. - Thereafter, accesses that involve that label will be logged and - the access permitted if it wouldn't be otherwise. Note that this - is dangerous and can ruin the proper labeling of your system. - It should never be used in production. -relabel-self - This interface contains a list of labels to which the process can - transition to, by writing to /proc/self/attr/current. - Normally a process can change its own label to any legal value, but only - if it has CAP_MAC_ADMIN. This interface allows a process without - CAP_MAC_ADMIN to relabel itself to one of labels from predefined list. - A process without CAP_MAC_ADMIN can change its label only once. When it - does, this list will be cleared. - The values are set by writing the desired labels, separated - by spaces, to the file or cleared by writing "-" to the file. - -If you are using the smackload utility -you can add access rules in /etc/smack/accesses. They take the form: - - subjectlabel objectlabel access - -access is a combination of the letters rwxatb which specify the -kind of access permitted a subject with subjectlabel on an -object with objectlabel. If there is no rule no access is allowed. - -Look for additional programs on http://schaufler-ca.com - -From the Smack Whitepaper: - -The Simplified Mandatory Access Control Kernel - -Casey Schaufler -casey@schaufler-ca.com - -Mandatory Access Control - -Computer systems employ a variety of schemes to constrain how information is -shared among the people and services using the machine. Some of these schemes -allow the program or user to decide what other programs or users are allowed -access to pieces of data. These schemes are called discretionary access -control mechanisms because the access control is specified at the discretion -of the user. Other schemes do not leave the decision regarding what a user or -program can access up to users or programs. These schemes are called mandatory -access control mechanisms because you don't have a choice regarding the users -or programs that have access to pieces of data. - -Bell & LaPadula - -From the middle of the 1980's until the turn of the century Mandatory Access -Control (MAC) was very closely associated with the Bell & LaPadula security -model, a mathematical description of the United States Department of Defense -policy for marking paper documents. MAC in this form enjoyed a following -within the Capital Beltway and Scandinavian supercomputer centers but was -often sited as failing to address general needs. - -Domain Type Enforcement - -Around the turn of the century Domain Type Enforcement (DTE) became popular. -This scheme organizes users, programs, and data into domains that are -protected from each other. This scheme has been widely deployed as a component -of popular Linux distributions. The administrative overhead required to -maintain this scheme and the detailed understanding of the whole system -necessary to provide a secure domain mapping leads to the scheme being -disabled or used in limited ways in the majority of cases. - -Smack - -Smack is a Mandatory Access Control mechanism designed to provide useful MAC -while avoiding the pitfalls of its predecessors. The limitations of Bell & -LaPadula are addressed by providing a scheme whereby access can be controlled -according to the requirements of the system and its purpose rather than those -imposed by an arcane government policy. The complexity of Domain Type -Enforcement and avoided by defining access controls in terms of the access -modes already in use. - -Smack Terminology - -The jargon used to talk about Smack will be familiar to those who have dealt -with other MAC systems and shouldn't be too difficult for the uninitiated to -pick up. There are four terms that are used in a specific way and that are -especially important: - - Subject: A subject is an active entity on the computer system. - On Smack a subject is a task, which is in turn the basic unit - of execution. - - Object: An object is a passive entity on the computer system. - On Smack files of all types, IPC, and tasks can be objects. - - Access: Any attempt by a subject to put information into or get - information from an object is an access. - - Label: Data that identifies the Mandatory Access Control - characteristics of a subject or an object. - -These definitions are consistent with the traditional use in the security -community. There are also some terms from Linux that are likely to crop up: - - Capability: A task that possesses a capability has permission to - violate an aspect of the system security policy, as identified by - the specific capability. A task that possesses one or more - capabilities is a privileged task, whereas a task with no - capabilities is an unprivileged task. - - Privilege: A task that is allowed to violate the system security - policy is said to have privilege. As of this writing a task can - have privilege either by possessing capabilities or by having an - effective user of root. - -Smack Basics - -Smack is an extension to a Linux system. It enforces additional restrictions -on what subjects can access which objects, based on the labels attached to -each of the subject and the object. - -Labels - -Smack labels are ASCII character strings. They can be up to 255 characters -long, but keeping them to twenty-three characters is recommended. -Single character labels using special characters, that being anything -other than a letter or digit, are reserved for use by the Smack development -team. Smack labels are unstructured, case sensitive, and the only operation -ever performed on them is comparison for equality. Smack labels cannot -contain unprintable characters, the "/" (slash), the "\" (backslash), the "'" -(quote) and '"' (double-quote) characters. -Smack labels cannot begin with a '-'. This is reserved for special options. - -There are some predefined labels: - - _ Pronounced "floor", a single underscore character. - ^ Pronounced "hat", a single circumflex character. - * Pronounced "star", a single asterisk character. - ? Pronounced "huh", a single question mark character. - @ Pronounced "web", a single at sign character. - -Every task on a Smack system is assigned a label. The Smack label -of a process will usually be assigned by the system initialization -mechanism. - -Access Rules - -Smack uses the traditional access modes of Linux. These modes are read, -execute, write, and occasionally append. There are a few cases where the -access mode may not be obvious. These include: - - Signals: A signal is a write operation from the subject task to - the object task. - Internet Domain IPC: Transmission of a packet is considered a - write operation from the source task to the destination task. - -Smack restricts access based on the label attached to a subject and the label -attached to the object it is trying to access. The rules enforced are, in -order: - - 1. Any access requested by a task labeled "*" is denied. - 2. A read or execute access requested by a task labeled "^" - is permitted. - 3. A read or execute access requested on an object labeled "_" - is permitted. - 4. Any access requested on an object labeled "*" is permitted. - 5. Any access requested by a task on an object with the same - label is permitted. - 6. Any access requested that is explicitly defined in the loaded - rule set is permitted. - 7. Any other access is denied. - -Smack Access Rules - -With the isolation provided by Smack access separation is simple. There are -many interesting cases where limited access by subjects to objects with -different labels is desired. One example is the familiar spy model of -sensitivity, where a scientist working on a highly classified project would be -able to read documents of lower classifications and anything she writes will -be "born" highly classified. To accommodate such schemes Smack includes a -mechanism for specifying rules allowing access between labels. - -Access Rule Format - -The format of an access rule is: - - subject-label object-label access - -Where subject-label is the Smack label of the task, object-label is the Smack -label of the thing being accessed, and access is a string specifying the sort -of access allowed. The access specification is searched for letters that -describe access modes: - - a: indicates that append access should be granted. - r: indicates that read access should be granted. - w: indicates that write access should be granted. - x: indicates that execute access should be granted. - t: indicates that the rule requests transmutation. - b: indicates that the rule should be reported for bring-up. - -Uppercase values for the specification letters are allowed as well. -Access mode specifications can be in any order. Examples of acceptable rules -are: - - TopSecret Secret rx - Secret Unclass R - Manager Game x - User HR w - Snap Crackle rwxatb - New Old rRrRr - Closed Off - - -Examples of unacceptable rules are: - - Top Secret Secret rx - Ace Ace r - Odd spells waxbeans - -Spaces are not allowed in labels. Since a subject always has access to files -with the same label specifying a rule for that case is pointless. Only -valid letters (rwxatbRWXATB) and the dash ('-') character are allowed in -access specifications. The dash is a placeholder, so "a-r" is the same -as "ar". A lone dash is used to specify that no access should be allowed. - -Applying Access Rules - -The developers of Linux rarely define new sorts of things, usually importing -schemes and concepts from other systems. Most often, the other systems are -variants of Unix. Unix has many endearing properties, but consistency of -access control models is not one of them. Smack strives to treat accesses as -uniformly as is sensible while keeping with the spirit of the underlying -mechanism. - -File system objects including files, directories, named pipes, symbolic links, -and devices require access permissions that closely match those used by mode -bit access. To open a file for reading read access is required on the file. To -search a directory requires execute access. Creating a file with write access -requires both read and write access on the containing directory. Deleting a -file requires read and write access to the file and to the containing -directory. It is possible that a user may be able to see that a file exists -but not any of its attributes by the circumstance of having read access to the -containing directory but not to the differently labeled file. This is an -artifact of the file name being data in the directory, not a part of the file. - -If a directory is marked as transmuting (SMACK64TRANSMUTE=TRUE) and the -access rule that allows a process to create an object in that directory -includes 't' access the label assigned to the new object will be that -of the directory, not the creating process. This makes it much easier -for two processes with different labels to share data without granting -access to all of their files. - -IPC objects, message queues, semaphore sets, and memory segments exist in flat -namespaces and access requests are only required to match the object in -question. - -Process objects reflect tasks on the system and the Smack label used to access -them is the same Smack label that the task would use for its own access -attempts. Sending a signal via the kill() system call is a write operation -from the signaler to the recipient. Debugging a process requires both reading -and writing. Creating a new task is an internal operation that results in two -tasks with identical Smack labels and requires no access checks. - -Sockets are data structures attached to processes and sending a packet from -one process to another requires that the sender have write access to the -receiver. The receiver is not required to have read access to the sender. - -Setting Access Rules - -The configuration file /etc/smack/accesses contains the rules to be set at -system startup. The contents are written to the special file -/sys/fs/smackfs/load2. Rules can be added at any time and take effect -immediately. For any pair of subject and object labels there can be only -one rule, with the most recently specified overriding any earlier -specification. - -Task Attribute - -The Smack label of a process can be read from /proc//attr/current. A -process can read its own Smack label from /proc/self/attr/current. A -privileged process can change its own Smack label by writing to -/proc/self/attr/current but not the label of another process. - -File Attribute - -The Smack label of a filesystem object is stored as an extended attribute -named SMACK64 on the file. This attribute is in the security namespace. It can -only be changed by a process with privilege. - -Privilege - -A process with CAP_MAC_OVERRIDE or CAP_MAC_ADMIN is privileged. -CAP_MAC_OVERRIDE allows the process access to objects it would -be denied otherwise. CAP_MAC_ADMIN allows a process to change -Smack data, including rules and attributes. - -Smack Networking - -As mentioned before, Smack enforces access control on network protocol -transmissions. Every packet sent by a Smack process is tagged with its Smack -label. This is done by adding a CIPSO tag to the header of the IP packet. Each -packet received is expected to have a CIPSO tag that identifies the label and -if it lacks such a tag the network ambient label is assumed. Before the packet -is delivered a check is made to determine that a subject with the label on the -packet has write access to the receiving process and if that is not the case -the packet is dropped. - -CIPSO Configuration - -It is normally unnecessary to specify the CIPSO configuration. The default -values used by the system handle all internal cases. Smack will compose CIPSO -label values to match the Smack labels being used without administrative -intervention. Unlabeled packets that come into the system will be given the -ambient label. - -Smack requires configuration in the case where packets from a system that is -not Smack that speaks CIPSO may be encountered. Usually this will be a Trusted -Solaris system, but there are other, less widely deployed systems out there. -CIPSO provides 3 important values, a Domain Of Interpretation (DOI), a level, -and a category set with each packet. The DOI is intended to identify a group -of systems that use compatible labeling schemes, and the DOI specified on the -Smack system must match that of the remote system or packets will be -discarded. The DOI is 3 by default. The value can be read from -/sys/fs/smackfs/doi and can be changed by writing to /sys/fs/smackfs/doi. - -The label and category set are mapped to a Smack label as defined in -/etc/smack/cipso. - -A Smack/CIPSO mapping has the form: - - smack level [category [category]*] - -Smack does not expect the level or category sets to be related in any -particular way and does not assume or assign accesses based on them. Some -examples of mappings: - - TopSecret 7 - TS:A,B 7 1 2 - SecBDE 5 2 4 6 - RAFTERS 7 12 26 - -The ":" and "," characters are permitted in a Smack label but have no special -meaning. - -The mapping of Smack labels to CIPSO values is defined by writing to -/sys/fs/smackfs/cipso2. - -In addition to explicit mappings Smack supports direct CIPSO mappings. One -CIPSO level is used to indicate that the category set passed in the packet is -in fact an encoding of the Smack label. The level used is 250 by default. The -value can be read from /sys/fs/smackfs/direct and changed by writing to -/sys/fs/smackfs/direct. - -Socket Attributes - -There are two attributes that are associated with sockets. These attributes -can only be set by privileged tasks, but any task can read them for their own -sockets. - - SMACK64IPIN: The Smack label of the task object. A privileged - program that will enforce policy may set this to the star label. - - SMACK64IPOUT: The Smack label transmitted with outgoing packets. - A privileged program may set this to match the label of another - task with which it hopes to communicate. - -Smack Netlabel Exceptions - -You will often find that your labeled application has to talk to the outside, -unlabeled world. To do this there's a special file /sys/fs/smackfs/netlabel -where you can add some exceptions in the form of : -@IP1 LABEL1 or -@IP2/MASK LABEL2 - -It means that your application will have unlabeled access to @IP1 if it has -write access on LABEL1, and access to the subnet @IP2/MASK if it has write -access on LABEL2. - -Entries in the /sys/fs/smackfs/netlabel file are matched by longest mask -first, like in classless IPv4 routing. - -A special label '@' and an option '-CIPSO' can be used there : -@ means Internet, any application with any label has access to it --CIPSO means standard CIPSO networking - -If you don't know what CIPSO is and don't plan to use it, you can just do : -echo 127.0.0.1 -CIPSO > /sys/fs/smackfs/netlabel -echo 0.0.0.0/0 @ > /sys/fs/smackfs/netlabel - -If you use CIPSO on your 192.168.0.0/16 local network and need also unlabeled -Internet access, you can have : -echo 127.0.0.1 -CIPSO > /sys/fs/smackfs/netlabel -echo 192.168.0.0/16 -CIPSO > /sys/fs/smackfs/netlabel -echo 0.0.0.0/0 @ > /sys/fs/smackfs/netlabel - - -Writing Applications for Smack - -There are three sorts of applications that will run on a Smack system. How an -application interacts with Smack will determine what it will have to do to -work properly under Smack. - -Smack Ignorant Applications - -By far the majority of applications have no reason whatever to care about the -unique properties of Smack. Since invoking a program has no impact on the -Smack label associated with the process the only concern likely to arise is -whether the process has execute access to the program. - -Smack Relevant Applications - -Some programs can be improved by teaching them about Smack, but do not make -any security decisions themselves. The utility ls(1) is one example of such a -program. - -Smack Enforcing Applications - -These are special programs that not only know about Smack, but participate in -the enforcement of system policy. In most cases these are the programs that -set up user sessions. There are also network services that provide information -to processes running with various labels. - -File System Interfaces - -Smack maintains labels on file system objects using extended attributes. The -Smack label of a file, directory, or other file system object can be obtained -using getxattr(2). - - len = getxattr("/", "security.SMACK64", value, sizeof (value)); - -will put the Smack label of the root directory into value. A privileged -process can set the Smack label of a file system object with setxattr(2). - - len = strlen("Rubble"); - rc = setxattr("/foo", "security.SMACK64", "Rubble", len, 0); - -will set the Smack label of /foo to "Rubble" if the program has appropriate -privilege. - -Socket Interfaces - -The socket attributes can be read using fgetxattr(2). - -A privileged process can set the Smack label of outgoing packets with -fsetxattr(2). - - len = strlen("Rubble"); - rc = fsetxattr(fd, "security.SMACK64IPOUT", "Rubble", len, 0); - -will set the Smack label "Rubble" on packets going out from the socket if the -program has appropriate privilege. - - rc = fsetxattr(fd, "security.SMACK64IPIN, "*", strlen("*"), 0); - -will set the Smack label "*" as the object label against which incoming -packets will be checked if the program has appropriate privilege. - -Administration - -Smack supports some mount options: - - smackfsdef=label: specifies the label to give files that lack - the Smack label extended attribute. - - smackfsroot=label: specifies the label to assign the root of the - file system if it lacks the Smack extended attribute. - - smackfshat=label: specifies a label that must have read access to - all labels set on the filesystem. Not yet enforced. - - smackfsfloor=label: specifies a label to which all labels set on the - filesystem must have read access. Not yet enforced. - -These mount options apply to all file system types. - -Smack auditing - -If you want Smack auditing of security events, you need to set CONFIG_AUDIT -in your kernel configuration. -By default, all denied events will be audited. You can change this behavior by -writing a single character to the /sys/fs/smackfs/logging file : -0 : no logging -1 : log denied (default) -2 : log accepted -3 : log denied & accepted - -Events are logged as 'key=value' pairs, for each event you at least will get -the subject, the object, the rights requested, the action, the kernel function -that triggered the event, plus other pairs depending on the type of event -audited. - -Bringup Mode - -Bringup mode provides logging features that can make application -configuration and system bringup easier. Configure the kernel with -CONFIG_SECURITY_SMACK_BRINGUP to enable these features. When bringup -mode is enabled accesses that succeed due to rules marked with the "b" -access mode will logged. When a new label is introduced for processes -rules can be added aggressively, marked with the "b". The logging allows -tracking of which rules actual get used for that label. - -Another feature of bringup mode is the "unconfined" option. Writing -a label to /sys/fs/smackfs/unconfined makes subjects with that label -able to access any object, and objects with that label accessible to -all subjects. Any access that is granted because a label is unconfined -is logged. This feature is dangerous, as files and directories may -be created in places they couldn't if the policy were being enforced. diff --git a/MAINTAINERS b/MAINTAINERS index 38a3d95d2d63..ce6744ee83e2 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11876,7 +11876,7 @@ L: linux-security-module@vger.kernel.org W: http://schaufler-ca.com T: git git://github.com/cschaufler/smack-next S: Maintained -F: Documentation/security/Smack.txt +F: Documentation/admin-guide/LSM/Smack.rst F: security/smack/ DRIVERS FOR ADAPTIVE VOLTAGE SCALING (AVS) -- cgit v1.2.3-59-g8ed1b From b68101a1e8f0263dbc7b8375d2a7c57c6216fb76 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Sat, 13 May 2017 04:51:50 -0700 Subject: doc: ReSTify keys.txt This creates a new section in the security development index for kernel keys, and adjusts for ReST markup. Cc: David Howells Signed-off-by: Kees Cook Signed-off-by: Jonathan Corbet --- Documentation/crypto/asymmetric-keys.txt | 2 +- Documentation/security/00-INDEX | 2 - Documentation/security/index.rst | 1 + Documentation/security/keys.txt | 1562 ------------------------------ Documentation/security/keys/core.rst | 1550 +++++++++++++++++++++++++++++ Documentation/security/keys/index.rst | 8 + MAINTAINERS | 2 +- include/linux/key.h | 2 +- 8 files changed, 1562 insertions(+), 1567 deletions(-) delete mode 100644 Documentation/security/keys.txt create mode 100644 Documentation/security/keys/core.rst create mode 100644 Documentation/security/keys/index.rst (limited to 'MAINTAINERS') diff --git a/Documentation/crypto/asymmetric-keys.txt b/Documentation/crypto/asymmetric-keys.txt index 5ad6480e3fb9..b82b6ad48488 100644 --- a/Documentation/crypto/asymmetric-keys.txt +++ b/Documentation/crypto/asymmetric-keys.txt @@ -265,7 +265,7 @@ mandatory: The caller passes a pointer to the following struct with all of the fields cleared, except for data, datalen and quotalen [see - Documentation/security/keys.txt]. + Documentation/security/keys/core.rst]. struct key_preparsed_payload { char *description; diff --git a/Documentation/security/00-INDEX b/Documentation/security/00-INDEX index cdb2294ec047..a840095bb11c 100644 --- a/Documentation/security/00-INDEX +++ b/Documentation/security/00-INDEX @@ -6,5 +6,3 @@ keys-request-key.txt - description of the kernel key request service. keys-trusted-encrypted.txt - info on the Trusted and Encrypted keys in the kernel key ring service. -keys.txt - - description of the kernel key retention service. diff --git a/Documentation/security/index.rst b/Documentation/security/index.rst index 94ba1cfc01c5..298a94a33f05 100644 --- a/Documentation/security/index.rst +++ b/Documentation/security/index.rst @@ -7,6 +7,7 @@ Security Documentation credentials IMA-templates + keys/index LSM self-protection tpm/index diff --git a/Documentation/security/keys.txt b/Documentation/security/keys.txt deleted file mode 100644 index cd5019934d7f..000000000000 --- a/Documentation/security/keys.txt +++ /dev/null @@ -1,1562 +0,0 @@ - ============================ - KERNEL KEY RETENTION SERVICE - ============================ - -This service allows cryptographic keys, authentication tokens, cross-domain -user mappings, and similar to be cached in the kernel for the use of -filesystems and other kernel services. - -Keyrings are permitted; these are a special type of key that can hold links to -other keys. Processes each have three standard keyring subscriptions that a -kernel service can search for relevant keys. - -The key service can be configured on by enabling: - - "Security options"/"Enable access key retention support" (CONFIG_KEYS) - -This document has the following sections: - - - Key overview - - Key service overview - - Key access permissions - - SELinux support - - New procfs files - - Userspace system call interface - - Kernel services - - Notes on accessing payload contents - - Defining a key type - - Request-key callback service - - Garbage collection - - -============ -KEY OVERVIEW -============ - -In this context, keys represent units of cryptographic data, authentication -tokens, keyrings, etc.. These are represented in the kernel by struct key. - -Each key has a number of attributes: - - - A serial number. - - A type. - - A description (for matching a key in a search). - - Access control information. - - An expiry time. - - A payload. - - State. - - - (*) Each key is issued a serial number of type key_serial_t that is unique for - the lifetime of that key. All serial numbers are positive non-zero 32-bit - integers. - - Userspace programs can use a key's serial numbers as a way to gain access - to it, subject to permission checking. - - (*) Each key is of a defined "type". Types must be registered inside the - kernel by a kernel service (such as a filesystem) before keys of that type - can be added or used. Userspace programs cannot define new types directly. - - Key types are represented in the kernel by struct key_type. This defines a - number of operations that can be performed on a key of that type. - - Should a type be removed from the system, all the keys of that type will - be invalidated. - - (*) Each key has a description. This should be a printable string. The key - type provides an operation to perform a match between the description on a - key and a criterion string. - - (*) Each key has an owner user ID, a group ID and a permissions mask. These - are used to control what a process may do to a key from userspace, and - whether a kernel service will be able to find the key. - - (*) Each key can be set to expire at a specific time by the key type's - instantiation function. Keys can also be immortal. - - (*) Each key can have a payload. This is a quantity of data that represent the - actual "key". In the case of a keyring, this is a list of keys to which - the keyring links; in the case of a user-defined key, it's an arbitrary - blob of data. - - Having a payload is not required; and the payload can, in fact, just be a - value stored in the struct key itself. - - When a key is instantiated, the key type's instantiation function is - called with a blob of data, and that then creates the key's payload in - some way. - - Similarly, when userspace wants to read back the contents of the key, if - permitted, another key type operation will be called to convert the key's - attached payload back into a blob of data. - - (*) Each key can be in one of a number of basic states: - - (*) Uninstantiated. The key exists, but does not have any data attached. - Keys being requested from userspace will be in this state. - - (*) Instantiated. This is the normal state. The key is fully formed, and - has data attached. - - (*) Negative. This is a relatively short-lived state. The key acts as a - note saying that a previous call out to userspace failed, and acts as - a throttle on key lookups. A negative key can be updated to a normal - state. - - (*) Expired. Keys can have lifetimes set. If their lifetime is exceeded, - they traverse to this state. An expired key can be updated back to a - normal state. - - (*) Revoked. A key is put in this state by userspace action. It can't be - found or operated upon (apart from by unlinking it). - - (*) Dead. The key's type was unregistered, and so the key is now useless. - -Keys in the last three states are subject to garbage collection. See the -section on "Garbage collection". - - -==================== -KEY SERVICE OVERVIEW -==================== - -The key service provides a number of features besides keys: - - (*) The key service defines three special key types: - - (+) "keyring" - - Keyrings are special keys that contain a list of other keys. Keyring - lists can be modified using various system calls. Keyrings should not - be given a payload when created. - - (+) "user" - - A key of this type has a description and a payload that are arbitrary - blobs of data. These can be created, updated and read by userspace, - and aren't intended for use by kernel services. - - (+) "logon" - - Like a "user" key, a "logon" key has a payload that is an arbitrary - blob of data. It is intended as a place to store secrets which are - accessible to the kernel but not to userspace programs. - - The description can be arbitrary, but must be prefixed with a non-zero - length string that describes the key "subclass". The subclass is - separated from the rest of the description by a ':'. "logon" keys can - be created and updated from userspace, but the payload is only - readable from kernel space. - - (*) Each process subscribes to three keyrings: a thread-specific keyring, a - process-specific keyring, and a session-specific keyring. - - The thread-specific keyring is discarded from the child when any sort of - clone, fork, vfork or execve occurs. A new keyring is created only when - required. - - The process-specific keyring is replaced with an empty one in the child on - clone, fork, vfork unless CLONE_THREAD is supplied, in which case it is - shared. execve also discards the process's process keyring and creates a - new one. - - The session-specific keyring is persistent across clone, fork, vfork and - execve, even when the latter executes a set-UID or set-GID binary. A - process can, however, replace its current session keyring with a new one - by using PR_JOIN_SESSION_KEYRING. It is permitted to request an anonymous - new one, or to attempt to create or join one of a specific name. - - The ownership of the thread keyring changes when the real UID and GID of - the thread changes. - - (*) Each user ID resident in the system holds two special keyrings: a user - specific keyring and a default user session keyring. The default session - keyring is initialised with a link to the user-specific keyring. - - When a process changes its real UID, if it used to have no session key, it - will be subscribed to the default session key for the new UID. - - If a process attempts to access its session key when it doesn't have one, - it will be subscribed to the default for its current UID. - - (*) Each user has two quotas against which the keys they own are tracked. One - limits the total number of keys and keyrings, the other limits the total - amount of description and payload space that can be consumed. - - The user can view information on this and other statistics through procfs - files. The root user may also alter the quota limits through sysctl files - (see the section "New procfs files"). - - Process-specific and thread-specific keyrings are not counted towards a - user's quota. - - If a system call that modifies a key or keyring in some way would put the - user over quota, the operation is refused and error EDQUOT is returned. - - (*) There's a system call interface by which userspace programs can create and - manipulate keys and keyrings. - - (*) There's a kernel interface by which services can register types and search - for keys. - - (*) There's a way for the a search done from the kernel to call back to - userspace to request a key that can't be found in a process's keyrings. - - (*) An optional filesystem is available through which the key database can be - viewed and manipulated. - - -====================== -KEY ACCESS PERMISSIONS -====================== - -Keys have an owner user ID, a group access ID, and a permissions mask. The mask -has up to eight bits each for possessor, user, group and other access. Only -six of each set of eight bits are defined. These permissions granted are: - - (*) View - - This permits a key or keyring's attributes to be viewed - including key - type and description. - - (*) Read - - This permits a key's payload to be viewed or a keyring's list of linked - keys. - - (*) Write - - This permits a key's payload to be instantiated or updated, or it allows a - link to be added to or removed from a keyring. - - (*) Search - - This permits keyrings to be searched and keys to be found. Searches can - only recurse into nested keyrings that have search permission set. - - (*) Link - - This permits a key or keyring to be linked to. To create a link from a - keyring to a key, a process must have Write permission on the keyring and - Link permission on the key. - - (*) Set Attribute - - This permits a key's UID, GID and permissions mask to be changed. - -For changing the ownership, group ID or permissions mask, being the owner of -the key or having the sysadmin capability is sufficient. - - -=============== -SELINUX SUPPORT -=============== - -The security class "key" has been added to SELinux so that mandatory access -controls can be applied to keys created within various contexts. This support -is preliminary, and is likely to change quite significantly in the near future. -Currently, all of the basic permissions explained above are provided in SELinux -as well; SELinux is simply invoked after all basic permission checks have been -performed. - -The value of the file /proc/self/attr/keycreate influences the labeling of -newly-created keys. If the contents of that file correspond to an SELinux -security context, then the key will be assigned that context. Otherwise, the -key will be assigned the current context of the task that invoked the key -creation request. Tasks must be granted explicit permission to assign a -particular context to newly-created keys, using the "create" permission in the -key security class. - -The default keyrings associated with users will be labeled with the default -context of the user if and only if the login programs have been instrumented to -properly initialize keycreate during the login process. Otherwise, they will -be labeled with the context of the login program itself. - -Note, however, that the default keyrings associated with the root user are -labeled with the default kernel context, since they are created early in the -boot process, before root has a chance to log in. - -The keyrings associated with new threads are each labeled with the context of -their associated thread, and both session and process keyrings are handled -similarly. - - -================ -NEW PROCFS FILES -================ - -Two files have been added to procfs by which an administrator can find out -about the status of the key service: - - (*) /proc/keys - - This lists the keys that are currently viewable by the task reading the - file, giving information about their type, description and permissions. - It is not possible to view the payload of the key this way, though some - information about it may be given. - - The only keys included in the list are those that grant View permission to - the reading process whether or not it possesses them. Note that LSM - security checks are still performed, and may further filter out keys that - the current process is not authorised to view. - - The contents of the file look like this: - - SERIAL FLAGS USAGE EXPY PERM UID GID TYPE DESCRIPTION: SUMMARY - 00000001 I----- 39 perm 1f3f0000 0 0 keyring _uid_ses.0: 1/4 - 00000002 I----- 2 perm 1f3f0000 0 0 keyring _uid.0: empty - 00000007 I----- 1 perm 1f3f0000 0 0 keyring _pid.1: empty - 0000018d I----- 1 perm 1f3f0000 0 0 keyring _pid.412: empty - 000004d2 I--Q-- 1 perm 1f3f0000 32 -1 keyring _uid.32: 1/4 - 000004d3 I--Q-- 3 perm 1f3f0000 32 -1 keyring _uid_ses.32: empty - 00000892 I--QU- 1 perm 1f000000 0 0 user metal:copper: 0 - 00000893 I--Q-N 1 35s 1f3f0000 0 0 user metal:silver: 0 - 00000894 I--Q-- 1 10h 003f0000 0 0 user metal:gold: 0 - - The flags are: - - I Instantiated - R Revoked - D Dead - Q Contributes to user's quota - U Under construction by callback to userspace - N Negative key - - - (*) /proc/key-users - - This file lists the tracking data for each user that has at least one key - on the system. Such data includes quota information and statistics: - - [root@andromeda root]# cat /proc/key-users - 0: 46 45/45 1/100 13/10000 - 29: 2 2/2 2/100 40/10000 - 32: 2 2/2 2/100 40/10000 - 38: 2 2/2 2/100 40/10000 - - The format of each line is - : User ID to which this applies - Structure refcount - / Total number of keys and number instantiated - / Key count quota - / Key size quota - - -Four new sysctl files have been added also for the purpose of controlling the -quota limits on keys: - - (*) /proc/sys/kernel/keys/root_maxkeys - /proc/sys/kernel/keys/root_maxbytes - - These files hold the maximum number of keys that root may have and the - maximum total number of bytes of data that root may have stored in those - keys. - - (*) /proc/sys/kernel/keys/maxkeys - /proc/sys/kernel/keys/maxbytes - - These files hold the maximum number of keys that each non-root user may - have and the maximum total number of bytes of data that each of those - users may have stored in their keys. - -Root may alter these by writing each new limit as a decimal number string to -the appropriate file. - - -=============================== -USERSPACE SYSTEM CALL INTERFACE -=============================== - -Userspace can manipulate keys directly through three new syscalls: add_key, -request_key and keyctl. The latter provides a number of functions for -manipulating keys. - -When referring to a key directly, userspace programs should use the key's -serial number (a positive 32-bit integer). However, there are some special -values available for referring to special keys and keyrings that relate to the -process making the call: - - CONSTANT VALUE KEY REFERENCED - ============================== ====== =========================== - KEY_SPEC_THREAD_KEYRING -1 thread-specific keyring - KEY_SPEC_PROCESS_KEYRING -2 process-specific keyring - KEY_SPEC_SESSION_KEYRING -3 session-specific keyring - KEY_SPEC_USER_KEYRING -4 UID-specific keyring - KEY_SPEC_USER_SESSION_KEYRING -5 UID-session keyring - KEY_SPEC_GROUP_KEYRING -6 GID-specific keyring - KEY_SPEC_REQKEY_AUTH_KEY -7 assumed request_key() - authorisation key - - -The main syscalls are: - - (*) Create a new key of given type, description and payload and add it to the - nominated keyring: - - key_serial_t add_key(const char *type, const char *desc, - const void *payload, size_t plen, - key_serial_t keyring); - - If a key of the same type and description as that proposed already exists - in the keyring, this will try to update it with the given payload, or it - will return error EEXIST if that function is not supported by the key - type. The process must also have permission to write to the key to be able - to update it. The new key will have all user permissions granted and no - group or third party permissions. - - Otherwise, this will attempt to create a new key of the specified type and - description, and to instantiate it with the supplied payload and attach it - to the keyring. In this case, an error will be generated if the process - does not have permission to write to the keyring. - - If the key type supports it, if the description is NULL or an empty - string, the key type will try and generate a description from the content - of the payload. - - The payload is optional, and the pointer can be NULL if not required by - the type. The payload is plen in size, and plen can be zero for an empty - payload. - - A new keyring can be generated by setting type "keyring", the keyring name - as the description (or NULL) and setting the payload to NULL. - - User defined keys can be created by specifying type "user". It is - recommended that a user defined key's description by prefixed with a type - ID and a colon, such as "krb5tgt:" for a Kerberos 5 ticket granting - ticket. - - Any other type must have been registered with the kernel in advance by a - kernel service such as a filesystem. - - The ID of the new or updated key is returned if successful. - - - (*) Search the process's keyrings for a key, potentially calling out to - userspace to create it. - - key_serial_t request_key(const char *type, const char *description, - const char *callout_info, - key_serial_t dest_keyring); - - This function searches all the process's keyrings in the order thread, - process, session for a matching key. This works very much like - KEYCTL_SEARCH, including the optional attachment of the discovered key to - a keyring. - - If a key cannot be found, and if callout_info is not NULL, then - /sbin/request-key will be invoked in an attempt to obtain a key. The - callout_info string will be passed as an argument to the program. - - See also Documentation/security/keys-request-key.txt. - - -The keyctl syscall functions are: - - (*) Map a special key ID to a real key ID for this process: - - key_serial_t keyctl(KEYCTL_GET_KEYRING_ID, key_serial_t id, - int create); - - The special key specified by "id" is looked up (with the key being created - if necessary) and the ID of the key or keyring thus found is returned if - it exists. - - If the key does not yet exist, the key will be created if "create" is - non-zero; and the error ENOKEY will be returned if "create" is zero. - - - (*) Replace the session keyring this process subscribes to with a new one: - - key_serial_t keyctl(KEYCTL_JOIN_SESSION_KEYRING, const char *name); - - If name is NULL, an anonymous keyring is created attached to the process - as its session keyring, displacing the old session keyring. - - If name is not NULL, if a keyring of that name exists, the process - attempts to attach it as the session keyring, returning an error if that - is not permitted; otherwise a new keyring of that name is created and - attached as the session keyring. - - To attach to a named keyring, the keyring must have search permission for - the process's ownership. - - The ID of the new session keyring is returned if successful. - - - (*) Update the specified key: - - long keyctl(KEYCTL_UPDATE, key_serial_t key, const void *payload, - size_t plen); - - This will try to update the specified key with the given payload, or it - will return error EOPNOTSUPP if that function is not supported by the key - type. The process must also have permission to write to the key to be able - to update it. - - The payload is of length plen, and may be absent or empty as for - add_key(). - - - (*) Revoke a key: - - long keyctl(KEYCTL_REVOKE, key_serial_t key); - - This makes a key unavailable for further operations. Further attempts to - use the key will be met with error EKEYREVOKED, and the key will no longer - be findable. - - - (*) Change the ownership of a key: - - long keyctl(KEYCTL_CHOWN, key_serial_t key, uid_t uid, gid_t gid); - - This function permits a key's owner and group ID to be changed. Either one - of uid or gid can be set to -1 to suppress that change. - - Only the superuser can change a key's owner to something other than the - key's current owner. Similarly, only the superuser can change a key's - group ID to something other than the calling process's group ID or one of - its group list members. - - - (*) Change the permissions mask on a key: - - long keyctl(KEYCTL_SETPERM, key_serial_t key, key_perm_t perm); - - This function permits the owner of a key or the superuser to change the - permissions mask on a key. - - Only bits the available bits are permitted; if any other bits are set, - error EINVAL will be returned. - - - (*) Describe a key: - - long keyctl(KEYCTL_DESCRIBE, key_serial_t key, char *buffer, - size_t buflen); - - This function returns a summary of the key's attributes (but not its - payload data) as a string in the buffer provided. - - Unless there's an error, it always returns the amount of data it could - produce, even if that's too big for the buffer, but it won't copy more - than requested to userspace. If the buffer pointer is NULL then no copy - will take place. - - A process must have view permission on the key for this function to be - successful. - - If successful, a string is placed in the buffer in the following format: - - ;;;; - - Where type and description are strings, uid and gid are decimal, and perm - is hexadecimal. A NUL character is included at the end of the string if - the buffer is sufficiently big. - - This can be parsed with - - sscanf(buffer, "%[^;];%d;%d;%o;%s", type, &uid, &gid, &mode, desc); - - - (*) Clear out a keyring: - - long keyctl(KEYCTL_CLEAR, key_serial_t keyring); - - This function clears the list of keys attached to a keyring. The calling - process must have write permission on the keyring, and it must be a - keyring (or else error ENOTDIR will result). - - This function can also be used to clear special kernel keyrings if they - are appropriately marked if the user has CAP_SYS_ADMIN capability. The - DNS resolver cache keyring is an example of this. - - - (*) Link a key into a keyring: - - long keyctl(KEYCTL_LINK, key_serial_t keyring, key_serial_t key); - - This function creates a link from the keyring to the key. The process must - have write permission on the keyring and must have link permission on the - key. - - Should the keyring not be a keyring, error ENOTDIR will result; and if the - keyring is full, error ENFILE will result. - - The link procedure checks the nesting of the keyrings, returning ELOOP if - it appears too deep or EDEADLK if the link would introduce a cycle. - - Any links within the keyring to keys that match the new key in terms of - type and description will be discarded from the keyring as the new one is - added. - - - (*) Unlink a key or keyring from another keyring: - - long keyctl(KEYCTL_UNLINK, key_serial_t keyring, key_serial_t key); - - This function looks through the keyring for the first link to the - specified key, and removes it if found. Subsequent links to that key are - ignored. The process must have write permission on the keyring. - - If the keyring is not a keyring, error ENOTDIR will result; and if the key - is not present, error ENOENT will be the result. - - - (*) Search a keyring tree for a key: - - key_serial_t keyctl(KEYCTL_SEARCH, key_serial_t keyring, - const char *type, const char *description, - key_serial_t dest_keyring); - - This searches the keyring tree headed by the specified keyring until a key - is found that matches the type and description criteria. Each keyring is - checked for keys before recursion into its children occurs. - - The process must have search permission on the top level keyring, or else - error EACCES will result. Only keyrings that the process has search - permission on will be recursed into, and only keys and keyrings for which - a process has search permission can be matched. If the specified keyring - is not a keyring, ENOTDIR will result. - - If the search succeeds, the function will attempt to link the found key - into the destination keyring if one is supplied (non-zero ID). All the - constraints applicable to KEYCTL_LINK apply in this case too. - - Error ENOKEY, EKEYREVOKED or EKEYEXPIRED will be returned if the search - fails. On success, the resulting key ID will be returned. - - - (*) Read the payload data from a key: - - long keyctl(KEYCTL_READ, key_serial_t keyring, char *buffer, - size_t buflen); - - This function attempts to read the payload data from the specified key - into the buffer. The process must have read permission on the key to - succeed. - - The returned data will be processed for presentation by the key type. For - instance, a keyring will return an array of key_serial_t entries - representing the IDs of all the keys to which it is subscribed. The user - defined key type will return its data as is. If a key type does not - implement this function, error EOPNOTSUPP will result. - - As much of the data as can be fitted into the buffer will be copied to - userspace if the buffer pointer is not NULL. - - On a successful return, the function will always return the amount of data - available rather than the amount copied. - - - (*) Instantiate a partially constructed key. - - long keyctl(KEYCTL_INSTANTIATE, key_serial_t key, - const void *payload, size_t plen, - key_serial_t keyring); - long keyctl(KEYCTL_INSTANTIATE_IOV, key_serial_t key, - const struct iovec *payload_iov, unsigned ioc, - key_serial_t keyring); - - If the kernel calls back to userspace to complete the instantiation of a - key, userspace should use this call to supply data for the key before the - invoked process returns, or else the key will be marked negative - automatically. - - The process must have write access on the key to be able to instantiate - it, and the key must be uninstantiated. - - If a keyring is specified (non-zero), the key will also be linked into - that keyring, however all the constraints applying in KEYCTL_LINK apply in - this case too. - - The payload and plen arguments describe the payload data as for add_key(). - - The payload_iov and ioc arguments describe the payload data in an iovec - array instead of a single buffer. - - - (*) Negatively instantiate a partially constructed key. - - long keyctl(KEYCTL_NEGATE, key_serial_t key, - unsigned timeout, key_serial_t keyring); - long keyctl(KEYCTL_REJECT, key_serial_t key, - unsigned timeout, unsigned error, key_serial_t keyring); - - If the kernel calls back to userspace to complete the instantiation of a - key, userspace should use this call mark the key as negative before the - invoked process returns if it is unable to fulfill the request. - - The process must have write access on the key to be able to instantiate - it, and the key must be uninstantiated. - - If a keyring is specified (non-zero), the key will also be linked into - that keyring, however all the constraints applying in KEYCTL_LINK apply in - this case too. - - If the key is rejected, future searches for it will return the specified - error code until the rejected key expires. Negating the key is the same - as rejecting the key with ENOKEY as the error code. - - - (*) Set the default request-key destination keyring. - - long keyctl(KEYCTL_SET_REQKEY_KEYRING, int reqkey_defl); - - This sets the default keyring to which implicitly requested keys will be - attached for this thread. reqkey_defl should be one of these constants: - - CONSTANT VALUE NEW DEFAULT KEYRING - ====================================== ====== ======================= - KEY_REQKEY_DEFL_NO_CHANGE -1 No change - KEY_REQKEY_DEFL_DEFAULT 0 Default[1] - KEY_REQKEY_DEFL_THREAD_KEYRING 1 Thread keyring - KEY_REQKEY_DEFL_PROCESS_KEYRING 2 Process keyring - KEY_REQKEY_DEFL_SESSION_KEYRING 3 Session keyring - KEY_REQKEY_DEFL_USER_KEYRING 4 User keyring - KEY_REQKEY_DEFL_USER_SESSION_KEYRING 5 User session keyring - KEY_REQKEY_DEFL_GROUP_KEYRING 6 Group keyring - - The old default will be returned if successful and error EINVAL will be - returned if reqkey_defl is not one of the above values. - - The default keyring can be overridden by the keyring indicated to the - request_key() system call. - - Note that this setting is inherited across fork/exec. - - [1] The default is: the thread keyring if there is one, otherwise - the process keyring if there is one, otherwise the session keyring if - there is one, otherwise the user default session keyring. - - - (*) Set the timeout on a key. - - long keyctl(KEYCTL_SET_TIMEOUT, key_serial_t key, unsigned timeout); - - This sets or clears the timeout on a key. The timeout can be 0 to clear - the timeout or a number of seconds to set the expiry time that far into - the future. - - The process must have attribute modification access on a key to set its - timeout. Timeouts may not be set with this function on negative, revoked - or expired keys. - - - (*) Assume the authority granted to instantiate a key - - long keyctl(KEYCTL_ASSUME_AUTHORITY, key_serial_t key); - - This assumes or divests the authority required to instantiate the - specified key. Authority can only be assumed if the thread has the - authorisation key associated with the specified key in its keyrings - somewhere. - - Once authority is assumed, searches for keys will also search the - requester's keyrings using the requester's security label, UID, GID and - groups. - - If the requested authority is unavailable, error EPERM will be returned, - likewise if the authority has been revoked because the target key is - already instantiated. - - If the specified key is 0, then any assumed authority will be divested. - - The assumed authoritative key is inherited across fork and exec. - - - (*) Get the LSM security context attached to a key. - - long keyctl(KEYCTL_GET_SECURITY, key_serial_t key, char *buffer, - size_t buflen) - - This function returns a string that represents the LSM security context - attached to a key in the buffer provided. - - Unless there's an error, it always returns the amount of data it could - produce, even if that's too big for the buffer, but it won't copy more - than requested to userspace. If the buffer pointer is NULL then no copy - will take place. - - A NUL character is included at the end of the string if the buffer is - sufficiently big. This is included in the returned count. If no LSM is - in force then an empty string will be returned. - - A process must have view permission on the key for this function to be - successful. - - - (*) Install the calling process's session keyring on its parent. - - long keyctl(KEYCTL_SESSION_TO_PARENT); - - This functions attempts to install the calling process's session keyring - on to the calling process's parent, replacing the parent's current session - keyring. - - The calling process must have the same ownership as its parent, the - keyring must have the same ownership as the calling process, the calling - process must have LINK permission on the keyring and the active LSM module - mustn't deny permission, otherwise error EPERM will be returned. - - Error ENOMEM will be returned if there was insufficient memory to complete - the operation, otherwise 0 will be returned to indicate success. - - The keyring will be replaced next time the parent process leaves the - kernel and resumes executing userspace. - - - (*) Invalidate a key. - - long keyctl(KEYCTL_INVALIDATE, key_serial_t key); - - This function marks a key as being invalidated and then wakes up the - garbage collector. The garbage collector immediately removes invalidated - keys from all keyrings and deletes the key when its reference count - reaches zero. - - Keys that are marked invalidated become invisible to normal key operations - immediately, though they are still visible in /proc/keys until deleted - (they're marked with an 'i' flag). - - A process must have search permission on the key for this function to be - successful. - - (*) Compute a Diffie-Hellman shared secret or public key - - long keyctl(KEYCTL_DH_COMPUTE, struct keyctl_dh_params *params, - char *buffer, size_t buflen, - struct keyctl_kdf_params *kdf); - - The params struct contains serial numbers for three keys: - - - The prime, p, known to both parties - - The local private key - - The base integer, which is either a shared generator or the - remote public key - - The value computed is: - - result = base ^ private (mod prime) - - If the base is the shared generator, the result is the local - public key. If the base is the remote public key, the result is - the shared secret. - - If the parameter kdf is NULL, the following applies: - - - The buffer length must be at least the length of the prime, or zero. - - - If the buffer length is nonzero, the length of the result is - returned when it is successfully calculated and copied in to the - buffer. When the buffer length is zero, the minimum required - buffer length is returned. - - The kdf parameter allows the caller to apply a key derivation function - (KDF) on the Diffie-Hellman computation where only the result - of the KDF is returned to the caller. The KDF is characterized with - struct keyctl_kdf_params as follows: - - - char *hashname specifies the NUL terminated string identifying - the hash used from the kernel crypto API and applied for the KDF - operation. The KDF implemenation complies with SP800-56A as well - as with SP800-108 (the counter KDF). - - - char *otherinfo specifies the OtherInfo data as documented in - SP800-56A section 5.8.1.2. The length of the buffer is given with - otherinfolen. The format of OtherInfo is defined by the caller. - The otherinfo pointer may be NULL if no OtherInfo shall be used. - - This function will return error EOPNOTSUPP if the key type is not - supported, error ENOKEY if the key could not be found, or error - EACCES if the key is not readable by the caller. In addition, the - function will return EMSGSIZE when the parameter kdf is non-NULL - and either the buffer length or the OtherInfo length exceeds the - allowed length. - - (*) Restrict keyring linkage - - long keyctl(KEYCTL_RESTRICT_KEYRING, key_serial_t keyring, - const char *type, const char *restriction); - - An existing keyring can restrict linkage of additional keys by evaluating - the contents of the key according to a restriction scheme. - - "keyring" is the key ID for an existing keyring to apply a restriction - to. It may be empty or may already have keys linked. Existing linked keys - will remain in the keyring even if the new restriction would reject them. - - "type" is a registered key type. - - "restriction" is a string describing how key linkage is to be restricted. - The format varies depending on the key type, and the string is passed to - the lookup_restriction() function for the requested type. It may specify - a method and relevant data for the restriction such as signature - verification or constraints on key payload. If the requested key type is - later unregistered, no keys may be added to the keyring after the key type - is removed. - - To apply a keyring restriction the process must have Set Attribute - permission and the keyring must not be previously restricted. - -=============== -KERNEL SERVICES -=============== - -The kernel services for key management are fairly simple to deal with. They can -be broken down into two areas: keys and key types. - -Dealing with keys is fairly straightforward. Firstly, the kernel service -registers its type, then it searches for a key of that type. It should retain -the key as long as it has need of it, and then it should release it. For a -filesystem or device file, a search would probably be performed during the open -call, and the key released upon close. How to deal with conflicting keys due to -two different users opening the same file is left to the filesystem author to -solve. - -To access the key manager, the following header must be #included: - - - -Specific key types should have a header file under include/keys/ that should be -used to access that type. For keys of type "user", for example, that would be: - - - -Note that there are two different types of pointers to keys that may be -encountered: - - (*) struct key * - - This simply points to the key structure itself. Key structures will be at - least four-byte aligned. - - (*) key_ref_t - - This is equivalent to a struct key *, but the least significant bit is set - if the caller "possesses" the key. By "possession" it is meant that the - calling processes has a searchable link to the key from one of its - keyrings. There are three functions for dealing with these: - - key_ref_t make_key_ref(const struct key *key, bool possession); - - struct key *key_ref_to_ptr(const key_ref_t key_ref); - - bool is_key_possessed(const key_ref_t key_ref); - - The first function constructs a key reference from a key pointer and - possession information (which must be true or false). - - The second function retrieves the key pointer from a reference and the - third retrieves the possession flag. - -When accessing a key's payload contents, certain precautions must be taken to -prevent access vs modification races. See the section "Notes on accessing -payload contents" for more information. - -(*) To search for a key, call: - - struct key *request_key(const struct key_type *type, - const char *description, - const char *callout_info); - - This is used to request a key or keyring with a description that matches - the description specified according to the key type's match_preparse() - method. This permits approximate matching to occur. If callout_string is - not NULL, then /sbin/request-key will be invoked in an attempt to obtain - the key from userspace. In that case, callout_string will be passed as an - argument to the program. - - Should the function fail error ENOKEY, EKEYEXPIRED or EKEYREVOKED will be - returned. - - If successful, the key will have been attached to the default keyring for - implicitly obtained request-key keys, as set by KEYCTL_SET_REQKEY_KEYRING. - - See also Documentation/security/keys-request-key.txt. - - -(*) To search for a key, passing auxiliary data to the upcaller, call: - - struct key *request_key_with_auxdata(const struct key_type *type, - const char *description, - const void *callout_info, - size_t callout_len, - void *aux); - - This is identical to request_key(), except that the auxiliary data is - passed to the key_type->request_key() op if it exists, and the callout_info - is a blob of length callout_len, if given (the length may be 0). - - -(*) A key can be requested asynchronously by calling one of: - - struct key *request_key_async(const struct key_type *type, - const char *description, - const void *callout_info, - size_t callout_len); - - or: - - struct key *request_key_async_with_auxdata(const struct key_type *type, - const char *description, - const char *callout_info, - size_t callout_len, - void *aux); - - which are asynchronous equivalents of request_key() and - request_key_with_auxdata() respectively. - - These two functions return with the key potentially still under - construction. To wait for construction completion, the following should be - called: - - int wait_for_key_construction(struct key *key, bool intr); - - The function will wait for the key to finish being constructed and then - invokes key_validate() to return an appropriate value to indicate the state - of the key (0 indicates the key is usable). - - If intr is true, then the wait can be interrupted by a signal, in which - case error ERESTARTSYS will be returned. - - -(*) When it is no longer required, the key should be released using: - - void key_put(struct key *key); - - Or: - - void key_ref_put(key_ref_t key_ref); - - These can be called from interrupt context. If CONFIG_KEYS is not set then - the argument will not be parsed. - - -(*) Extra references can be made to a key by calling one of the following - functions: - - struct key *__key_get(struct key *key); - struct key *key_get(struct key *key); - - Keys so references will need to be disposed of by calling key_put() when - they've been finished with. The key pointer passed in will be returned. - - In the case of key_get(), if the pointer is NULL or CONFIG_KEYS is not set - then the key will not be dereferenced and no increment will take place. - - -(*) A key's serial number can be obtained by calling: - - key_serial_t key_serial(struct key *key); - - If key is NULL or if CONFIG_KEYS is not set then 0 will be returned (in the - latter case without parsing the argument). - - -(*) If a keyring was found in the search, this can be further searched by: - - key_ref_t keyring_search(key_ref_t keyring_ref, - const struct key_type *type, - const char *description) - - This searches the keyring tree specified for a matching key. Error ENOKEY - is returned upon failure (use IS_ERR/PTR_ERR to determine). If successful, - the returned key will need to be released. - - The possession attribute from the keyring reference is used to control - access through the permissions mask and is propagated to the returned key - reference pointer if successful. - - -(*) A keyring can be created by: - - struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid, - const struct cred *cred, - key_perm_t perm, - struct key_restriction *restrict_link, - unsigned long flags, - struct key *dest); - - This creates a keyring with the given attributes and returns it. If dest - is not NULL, the new keyring will be linked into the keyring to which it - points. No permission checks are made upon the destination keyring. - - Error EDQUOT can be returned if the keyring would overload the quota (pass - KEY_ALLOC_NOT_IN_QUOTA in flags if the keyring shouldn't be accounted - towards the user's quota). Error ENOMEM can also be returned. - - If restrict_link is not NULL, it should point to a structure that contains - the function that will be called each time an attempt is made to link a - key into the new keyring. The structure may also contain a key pointer - and an associated key type. The function is called to check whether a key - may be added into the keyring or not. The key type is used by the garbage - collector to clean up function or data pointers in this structure if the - given key type is unregistered. Callers of key_create_or_update() within - the kernel can pass KEY_ALLOC_BYPASS_RESTRICTION to suppress the check. - An example of using this is to manage rings of cryptographic keys that are - set up when the kernel boots where userspace is also permitted to add keys - - provided they can be verified by a key the kernel already has. - - When called, the restriction function will be passed the keyring being - added to, the key type, the payload of the key being added, and data to be - used in the restriction check. Note that when a new key is being created, - this is called between payload preparsing and actual key creation. The - function should return 0 to allow the link or an error to reject it. - - A convenience function, restrict_link_reject, exists to always return - -EPERM to in this case. - - -(*) To check the validity of a key, this function can be called: - - int validate_key(struct key *key); - - This checks that the key in question hasn't expired or and hasn't been - revoked. Should the key be invalid, error EKEYEXPIRED or EKEYREVOKED will - be returned. If the key is NULL or if CONFIG_KEYS is not set then 0 will be - returned (in the latter case without parsing the argument). - - -(*) To register a key type, the following function should be called: - - int register_key_type(struct key_type *type); - - This will return error EEXIST if a type of the same name is already - present. - - -(*) To unregister a key type, call: - - void unregister_key_type(struct key_type *type); - - -Under some circumstances, it may be desirable to deal with a bundle of keys. -The facility provides access to the keyring type for managing such a bundle: - - struct key_type key_type_keyring; - -This can be used with a function such as request_key() to find a specific -keyring in a process's keyrings. A keyring thus found can then be searched -with keyring_search(). Note that it is not possible to use request_key() to -search a specific keyring, so using keyrings in this way is of limited utility. - - -=================================== -NOTES ON ACCESSING PAYLOAD CONTENTS -=================================== - -The simplest payload is just data stored in key->payload directly. In this -case, there's no need to indulge in RCU or locking when accessing the payload. - -More complex payload contents must be allocated and pointers to them set in the -key->payload.data[] array. One of the following ways must be selected to -access the data: - - (1) Unmodifiable key type. - - If the key type does not have a modify method, then the key's payload can - be accessed without any form of locking, provided that it's known to be - instantiated (uninstantiated keys cannot be "found"). - - (2) The key's semaphore. - - The semaphore could be used to govern access to the payload and to control - the payload pointer. It must be write-locked for modifications and would - have to be read-locked for general access. The disadvantage of doing this - is that the accessor may be required to sleep. - - (3) RCU. - - RCU must be used when the semaphore isn't already held; if the semaphore - is held then the contents can't change under you unexpectedly as the - semaphore must still be used to serialise modifications to the key. The - key management code takes care of this for the key type. - - However, this means using: - - rcu_read_lock() ... rcu_dereference() ... rcu_read_unlock() - - to read the pointer, and: - - rcu_dereference() ... rcu_assign_pointer() ... call_rcu() - - to set the pointer and dispose of the old contents after a grace period. - Note that only the key type should ever modify a key's payload. - - Furthermore, an RCU controlled payload must hold a struct rcu_head for the - use of call_rcu() and, if the payload is of variable size, the length of - the payload. key->datalen cannot be relied upon to be consistent with the - payload just dereferenced if the key's semaphore is not held. - - Note that key->payload.data[0] has a shadow that is marked for __rcu - usage. This is called key->payload.rcu_data0. The following accessors - wrap the RCU calls to this element: - - (a) Set or change the first payload pointer: - - rcu_assign_keypointer(struct key *key, void *data); - - (b) Read the first payload pointer with the key semaphore held: - - [const] void *dereference_key_locked([const] struct key *key); - - Note that the return value will inherit its constness from the key - parameter. Static analysis will give an error if it things the lock - isn't held. - - (c) Read the first payload pointer with the RCU read lock held: - - const void *dereference_key_rcu(const struct key *key); - - -=================== -DEFINING A KEY TYPE -=================== - -A kernel service may want to define its own key type. For instance, an AFS -filesystem might want to define a Kerberos 5 ticket key type. To do this, it -author fills in a key_type struct and registers it with the system. - -Source files that implement key types should include the following header file: - - - -The structure has a number of fields, some of which are mandatory: - - (*) const char *name - - The name of the key type. This is used to translate a key type name - supplied by userspace into a pointer to the structure. - - - (*) size_t def_datalen - - This is optional - it supplies the default payload data length as - contributed to the quota. If the key type's payload is always or almost - always the same size, then this is a more efficient way to do things. - - The data length (and quota) on a particular key can always be changed - during instantiation or update by calling: - - int key_payload_reserve(struct key *key, size_t datalen); - - With the revised data length. Error EDQUOT will be returned if this is not - viable. - - - (*) int (*vet_description)(const char *description); - - This optional method is called to vet a key description. If the key type - doesn't approve of the key description, it may return an error, otherwise - it should return 0. - - - (*) int (*preparse)(struct key_preparsed_payload *prep); - - This optional method permits the key type to attempt to parse payload - before a key is created (add key) or the key semaphore is taken (update or - instantiate key). The structure pointed to by prep looks like: - - struct key_preparsed_payload { - char *description; - union key_payload payload; - const void *data; - size_t datalen; - size_t quotalen; - time_t expiry; - }; - - Before calling the method, the caller will fill in data and datalen with - the payload blob parameters; quotalen will be filled in with the default - quota size from the key type; expiry will be set to TIME_T_MAX and the - rest will be cleared. - - If a description can be proposed from the payload contents, that should be - attached as a string to the description field. This will be used for the - key description if the caller of add_key() passes NULL or "". - - The method can attach anything it likes to payload. This is merely passed - along to the instantiate() or update() operations. If set, the expiry - time will be applied to the key if it is instantiated from this data. - - The method should return 0 if successful or a negative error code - otherwise. - - - (*) void (*free_preparse)(struct key_preparsed_payload *prep); - - This method is only required if the preparse() method is provided, - otherwise it is unused. It cleans up anything attached to the description - and payload fields of the key_preparsed_payload struct as filled in by the - preparse() method. It will always be called after preparse() returns - successfully, even if instantiate() or update() succeed. - - - (*) int (*instantiate)(struct key *key, struct key_preparsed_payload *prep); - - This method is called to attach a payload to a key during construction. - The payload attached need not bear any relation to the data passed to this - function. - - The prep->data and prep->datalen fields will define the original payload - blob. If preparse() was supplied then other fields may be filled in also. - - If the amount of data attached to the key differs from the size in - keytype->def_datalen, then key_payload_reserve() should be called. - - This method does not have to lock the key in order to attach a payload. - The fact that KEY_FLAG_INSTANTIATED is not set in key->flags prevents - anything else from gaining access to the key. - - It is safe to sleep in this method. - - generic_key_instantiate() is provided to simply copy the data from - prep->payload.data[] to key->payload.data[], with RCU-safe assignment on - the first element. It will then clear prep->payload.data[] so that the - free_preparse method doesn't release the data. - - - (*) int (*update)(struct key *key, const void *data, size_t datalen); - - If this type of key can be updated, then this method should be provided. - It is called to update a key's payload from the blob of data provided. - - The prep->data and prep->datalen fields will define the original payload - blob. If preparse() was supplied then other fields may be filled in also. - - key_payload_reserve() should be called if the data length might change - before any changes are actually made. Note that if this succeeds, the type - is committed to changing the key because it's already been altered, so all - memory allocation must be done first. - - The key will have its semaphore write-locked before this method is called, - but this only deters other writers; any changes to the key's payload must - be made under RCU conditions, and call_rcu() must be used to dispose of - the old payload. - - key_payload_reserve() should be called before the changes are made, but - after all allocations and other potentially failing function calls are - made. - - It is safe to sleep in this method. - - - (*) int (*match_preparse)(struct key_match_data *match_data); - - This method is optional. It is called when a key search is about to be - performed. It is given the following structure: - - struct key_match_data { - bool (*cmp)(const struct key *key, - const struct key_match_data *match_data); - const void *raw_data; - void *preparsed; - unsigned lookup_type; - }; - - On entry, raw_data will be pointing to the criteria to be used in matching - a key by the caller and should not be modified. (*cmp)() will be pointing - to the default matcher function (which does an exact description match - against raw_data) and lookup_type will be set to indicate a direct lookup. - - The following lookup_type values are available: - - [*] KEYRING_SEARCH_LOOKUP_DIRECT - A direct lookup hashes the type and - description to narrow down the search to a small number of keys. - - [*] KEYRING_SEARCH_LOOKUP_ITERATE - An iterative lookup walks all the - keys in the keyring until one is matched. This must be used for any - search that's not doing a simple direct match on the key description. - - The method may set cmp to point to a function of its choice that does some - other form of match, may set lookup_type to KEYRING_SEARCH_LOOKUP_ITERATE - and may attach something to the preparsed pointer for use by (*cmp)(). - (*cmp)() should return true if a key matches and false otherwise. - - If preparsed is set, it may be necessary to use the match_free() method to - clean it up. - - The method should return 0 if successful or a negative error code - otherwise. - - It is permitted to sleep in this method, but (*cmp)() may not sleep as - locks will be held over it. - - If match_preparse() is not provided, keys of this type will be matched - exactly by their description. - - - (*) void (*match_free)(struct key_match_data *match_data); - - This method is optional. If given, it called to clean up - match_data->preparsed after a successful call to match_preparse(). - - - (*) void (*revoke)(struct key *key); - - This method is optional. It is called to discard part of the payload - data upon a key being revoked. The caller will have the key semaphore - write-locked. - - It is safe to sleep in this method, though care should be taken to avoid - a deadlock against the key semaphore. - - - (*) void (*destroy)(struct key *key); - - This method is optional. It is called to discard the payload data on a key - when it is being destroyed. - - This method does not need to lock the key to access the payload; it can - consider the key as being inaccessible at this time. Note that the key's - type may have been changed before this function is called. - - It is not safe to sleep in this method; the caller may hold spinlocks. - - - (*) void (*describe)(const struct key *key, struct seq_file *p); - - This method is optional. It is called during /proc/keys reading to - summarise a key's description and payload in text form. - - This method will be called with the RCU read lock held. rcu_dereference() - should be used to read the payload pointer if the payload is to be - accessed. key->datalen cannot be trusted to stay consistent with the - contents of the payload. - - The description will not change, though the key's state may. - - It is not safe to sleep in this method; the RCU read lock is held by the - caller. - - - (*) long (*read)(const struct key *key, char __user *buffer, size_t buflen); - - This method is optional. It is called by KEYCTL_READ to translate the - key's payload into something a blob of data for userspace to deal with. - Ideally, the blob should be in the same format as that passed in to the - instantiate and update methods. - - If successful, the blob size that could be produced should be returned - rather than the size copied. - - This method will be called with the key's semaphore read-locked. This will - prevent the key's payload changing. It is not necessary to use RCU locking - when accessing the key's payload. It is safe to sleep in this method, such - as might happen when the userspace buffer is accessed. - - - (*) int (*request_key)(struct key_construction *cons, const char *op, - void *aux); - - This method is optional. If provided, request_key() and friends will - invoke this function rather than upcalling to /sbin/request-key to operate - upon a key of this type. - - The aux parameter is as passed to request_key_async_with_auxdata() and - similar or is NULL otherwise. Also passed are the construction record for - the key to be operated upon and the operation type (currently only - "create"). - - This method is permitted to return before the upcall is complete, but the - following function must be called under all circumstances to complete the - instantiation process, whether or not it succeeds, whether or not there's - an error: - - void complete_request_key(struct key_construction *cons, int error); - - The error parameter should be 0 on success, -ve on error. The - construction record is destroyed by this action and the authorisation key - will be revoked. If an error is indicated, the key under construction - will be negatively instantiated if it wasn't already instantiated. - - If this method returns an error, that error will be returned to the - caller of request_key*(). complete_request_key() must be called prior to - returning. - - The key under construction and the authorisation key can be found in the - key_construction struct pointed to by cons: - - (*) struct key *key; - - The key under construction. - - (*) struct key *authkey; - - The authorisation key. - - - (*) struct key_restriction *(*lookup_restriction)(const char *params); - - This optional method is used to enable userspace configuration of keyring - restrictions. The restriction parameter string (not including the key type - name) is passed in, and this method returns a pointer to a key_restriction - structure containing the relevant functions and data to evaluate each - attempted key link operation. If there is no match, -EINVAL is returned. - - -============================ -REQUEST-KEY CALLBACK SERVICE -============================ - -To create a new key, the kernel will attempt to execute the following command -line: - - /sbin/request-key create \ - - - is the key being constructed, and the three keyrings are the process -keyrings from the process that caused the search to be issued. These are -included for two reasons: - - (1) There may be an authentication token in one of the keyrings that is - required to obtain the key, eg: a Kerberos Ticket-Granting Ticket. - - (2) The new key should probably be cached in one of these rings. - -This program should set it UID and GID to those specified before attempting to -access any more keys. It may then look around for a user specific process to -hand the request off to (perhaps a path held in placed in another key by, for -example, the KDE desktop manager). - -The program (or whatever it calls) should finish construction of the key by -calling KEYCTL_INSTANTIATE or KEYCTL_INSTANTIATE_IOV, which also permits it to -cache the key in one of the keyrings (probably the session ring) before -returning. Alternatively, the key can be marked as negative with KEYCTL_NEGATE -or KEYCTL_REJECT; this also permits the key to be cached in one of the -keyrings. - -If it returns with the key remaining in the unconstructed state, the key will -be marked as being negative, it will be added to the session keyring, and an -error will be returned to the key requestor. - -Supplementary information may be provided from whoever or whatever invoked this -service. This will be passed as the parameter. If no such -information was made available, then "-" will be passed as this parameter -instead. - - -Similarly, the kernel may attempt to update an expired or a soon to expire key -by executing: - - /sbin/request-key update \ - - -In this case, the program isn't required to actually attach the key to a ring; -the rings are provided for reference. - - -================== -GARBAGE COLLECTION -================== - -Dead keys (for which the type has been removed) will be automatically unlinked -from those keyrings that point to them and deleted as soon as possible by a -background garbage collector. - -Similarly, revoked and expired keys will be garbage collected, but only after a -certain amount of time has passed. This time is set as a number of seconds in: - - /proc/sys/kernel/keys/gc_delay diff --git a/Documentation/security/keys/core.rst b/Documentation/security/keys/core.rst new file mode 100644 index 000000000000..0d831a7afe4f --- /dev/null +++ b/Documentation/security/keys/core.rst @@ -0,0 +1,1550 @@ +============================ +Kernel Key Retention Service +============================ + +This service allows cryptographic keys, authentication tokens, cross-domain +user mappings, and similar to be cached in the kernel for the use of +filesystems and other kernel services. + +Keyrings are permitted; these are a special type of key that can hold links to +other keys. Processes each have three standard keyring subscriptions that a +kernel service can search for relevant keys. + +The key service can be configured on by enabling: + + "Security options"/"Enable access key retention support" (CONFIG_KEYS) + +This document has the following sections: + + - Key overview + - Key service overview + - Key access permissions + - SELinux support + - New procfs files + - Userspace system call interface + - Kernel services + - Notes on accessing payload contents + - Defining a key type + - Request-key callback service + - Garbage collection + + +Key Overview +============ + +In this context, keys represent units of cryptographic data, authentication +tokens, keyrings, etc.. These are represented in the kernel by struct key. + +Each key has a number of attributes: + + - A serial number. + - A type. + - A description (for matching a key in a search). + - Access control information. + - An expiry time. + - A payload. + - State. + + + * Each key is issued a serial number of type key_serial_t that is unique for + the lifetime of that key. All serial numbers are positive non-zero 32-bit + integers. + + Userspace programs can use a key's serial numbers as a way to gain access + to it, subject to permission checking. + + * Each key is of a defined "type". Types must be registered inside the + kernel by a kernel service (such as a filesystem) before keys of that type + can be added or used. Userspace programs cannot define new types directly. + + Key types are represented in the kernel by struct key_type. This defines a + number of operations that can be performed on a key of that type. + + Should a type be removed from the system, all the keys of that type will + be invalidated. + + * Each key has a description. This should be a printable string. The key + type provides an operation to perform a match between the description on a + key and a criterion string. + + * Each key has an owner user ID, a group ID and a permissions mask. These + are used to control what a process may do to a key from userspace, and + whether a kernel service will be able to find the key. + + * Each key can be set to expire at a specific time by the key type's + instantiation function. Keys can also be immortal. + + * Each key can have a payload. This is a quantity of data that represent the + actual "key". In the case of a keyring, this is a list of keys to which + the keyring links; in the case of a user-defined key, it's an arbitrary + blob of data. + + Having a payload is not required; and the payload can, in fact, just be a + value stored in the struct key itself. + + When a key is instantiated, the key type's instantiation function is + called with a blob of data, and that then creates the key's payload in + some way. + + Similarly, when userspace wants to read back the contents of the key, if + permitted, another key type operation will be called to convert the key's + attached payload back into a blob of data. + + * Each key can be in one of a number of basic states: + + * Uninstantiated. The key exists, but does not have any data attached. + Keys being requested from userspace will be in this state. + + * Instantiated. This is the normal state. The key is fully formed, and + has data attached. + + * Negative. This is a relatively short-lived state. The key acts as a + note saying that a previous call out to userspace failed, and acts as + a throttle on key lookups. A negative key can be updated to a normal + state. + + * Expired. Keys can have lifetimes set. If their lifetime is exceeded, + they traverse to this state. An expired key can be updated back to a + normal state. + + * Revoked. A key is put in this state by userspace action. It can't be + found or operated upon (apart from by unlinking it). + + * Dead. The key's type was unregistered, and so the key is now useless. + +Keys in the last three states are subject to garbage collection. See the +section on "Garbage collection". + + +Key Service Overview +==================== + +The key service provides a number of features besides keys: + + * The key service defines three special key types: + + (+) "keyring" + + Keyrings are special keys that contain a list of other keys. Keyring + lists can be modified using various system calls. Keyrings should not + be given a payload when created. + + (+) "user" + + A key of this type has a description and a payload that are arbitrary + blobs of data. These can be created, updated and read by userspace, + and aren't intended for use by kernel services. + + (+) "logon" + + Like a "user" key, a "logon" key has a payload that is an arbitrary + blob of data. It is intended as a place to store secrets which are + accessible to the kernel but not to userspace programs. + + The description can be arbitrary, but must be prefixed with a non-zero + length string that describes the key "subclass". The subclass is + separated from the rest of the description by a ':'. "logon" keys can + be created and updated from userspace, but the payload is only + readable from kernel space. + + * Each process subscribes to three keyrings: a thread-specific keyring, a + process-specific keyring, and a session-specific keyring. + + The thread-specific keyring is discarded from the child when any sort of + clone, fork, vfork or execve occurs. A new keyring is created only when + required. + + The process-specific keyring is replaced with an empty one in the child on + clone, fork, vfork unless CLONE_THREAD is supplied, in which case it is + shared. execve also discards the process's process keyring and creates a + new one. + + The session-specific keyring is persistent across clone, fork, vfork and + execve, even when the latter executes a set-UID or set-GID binary. A + process can, however, replace its current session keyring with a new one + by using PR_JOIN_SESSION_KEYRING. It is permitted to request an anonymous + new one, or to attempt to create or join one of a specific name. + + The ownership of the thread keyring changes when the real UID and GID of + the thread changes. + + * Each user ID resident in the system holds two special keyrings: a user + specific keyring and a default user session keyring. The default session + keyring is initialised with a link to the user-specific keyring. + + When a process changes its real UID, if it used to have no session key, it + will be subscribed to the default session key for the new UID. + + If a process attempts to access its session key when it doesn't have one, + it will be subscribed to the default for its current UID. + + * Each user has two quotas against which the keys they own are tracked. One + limits the total number of keys and keyrings, the other limits the total + amount of description and payload space that can be consumed. + + The user can view information on this and other statistics through procfs + files. The root user may also alter the quota limits through sysctl files + (see the section "New procfs files"). + + Process-specific and thread-specific keyrings are not counted towards a + user's quota. + + If a system call that modifies a key or keyring in some way would put the + user over quota, the operation is refused and error EDQUOT is returned. + + * There's a system call interface by which userspace programs can create and + manipulate keys and keyrings. + + * There's a kernel interface by which services can register types and search + for keys. + + * There's a way for the a search done from the kernel to call back to + userspace to request a key that can't be found in a process's keyrings. + + * An optional filesystem is available through which the key database can be + viewed and manipulated. + + +Key Access Permissions +====================== + +Keys have an owner user ID, a group access ID, and a permissions mask. The mask +has up to eight bits each for possessor, user, group and other access. Only +six of each set of eight bits are defined. These permissions granted are: + + * View + + This permits a key or keyring's attributes to be viewed - including key + type and description. + + * Read + + This permits a key's payload to be viewed or a keyring's list of linked + keys. + + * Write + + This permits a key's payload to be instantiated or updated, or it allows a + link to be added to or removed from a keyring. + + * Search + + This permits keyrings to be searched and keys to be found. Searches can + only recurse into nested keyrings that have search permission set. + + * Link + + This permits a key or keyring to be linked to. To create a link from a + keyring to a key, a process must have Write permission on the keyring and + Link permission on the key. + + * Set Attribute + + This permits a key's UID, GID and permissions mask to be changed. + +For changing the ownership, group ID or permissions mask, being the owner of +the key or having the sysadmin capability is sufficient. + + +SELinux Support +=============== + +The security class "key" has been added to SELinux so that mandatory access +controls can be applied to keys created within various contexts. This support +is preliminary, and is likely to change quite significantly in the near future. +Currently, all of the basic permissions explained above are provided in SELinux +as well; SELinux is simply invoked after all basic permission checks have been +performed. + +The value of the file /proc/self/attr/keycreate influences the labeling of +newly-created keys. If the contents of that file correspond to an SELinux +security context, then the key will be assigned that context. Otherwise, the +key will be assigned the current context of the task that invoked the key +creation request. Tasks must be granted explicit permission to assign a +particular context to newly-created keys, using the "create" permission in the +key security class. + +The default keyrings associated with users will be labeled with the default +context of the user if and only if the login programs have been instrumented to +properly initialize keycreate during the login process. Otherwise, they will +be labeled with the context of the login program itself. + +Note, however, that the default keyrings associated with the root user are +labeled with the default kernel context, since they are created early in the +boot process, before root has a chance to log in. + +The keyrings associated with new threads are each labeled with the context of +their associated thread, and both session and process keyrings are handled +similarly. + + +New ProcFS Files +================ + +Two files have been added to procfs by which an administrator can find out +about the status of the key service: + + * /proc/keys + + This lists the keys that are currently viewable by the task reading the + file, giving information about their type, description and permissions. + It is not possible to view the payload of the key this way, though some + information about it may be given. + + The only keys included in the list are those that grant View permission to + the reading process whether or not it possesses them. Note that LSM + security checks are still performed, and may further filter out keys that + the current process is not authorised to view. + + The contents of the file look like this:: + + SERIAL FLAGS USAGE EXPY PERM UID GID TYPE DESCRIPTION: SUMMARY + 00000001 I----- 39 perm 1f3f0000 0 0 keyring _uid_ses.0: 1/4 + 00000002 I----- 2 perm 1f3f0000 0 0 keyring _uid.0: empty + 00000007 I----- 1 perm 1f3f0000 0 0 keyring _pid.1: empty + 0000018d I----- 1 perm 1f3f0000 0 0 keyring _pid.412: empty + 000004d2 I--Q-- 1 perm 1f3f0000 32 -1 keyring _uid.32: 1/4 + 000004d3 I--Q-- 3 perm 1f3f0000 32 -1 keyring _uid_ses.32: empty + 00000892 I--QU- 1 perm 1f000000 0 0 user metal:copper: 0 + 00000893 I--Q-N 1 35s 1f3f0000 0 0 user metal:silver: 0 + 00000894 I--Q-- 1 10h 003f0000 0 0 user metal:gold: 0 + + The flags are:: + + I Instantiated + R Revoked + D Dead + Q Contributes to user's quota + U Under construction by callback to userspace + N Negative key + + + * /proc/key-users + + This file lists the tracking data for each user that has at least one key + on the system. Such data includes quota information and statistics:: + + [root@andromeda root]# cat /proc/key-users + 0: 46 45/45 1/100 13/10000 + 29: 2 2/2 2/100 40/10000 + 32: 2 2/2 2/100 40/10000 + 38: 2 2/2 2/100 40/10000 + + The format of each line is:: + + : User ID to which this applies + Structure refcount + / Total number of keys and number instantiated + / Key count quota + / Key size quota + + +Four new sysctl files have been added also for the purpose of controlling the +quota limits on keys: + + * /proc/sys/kernel/keys/root_maxkeys + /proc/sys/kernel/keys/root_maxbytes + + These files hold the maximum number of keys that root may have and the + maximum total number of bytes of data that root may have stored in those + keys. + + * /proc/sys/kernel/keys/maxkeys + /proc/sys/kernel/keys/maxbytes + + These files hold the maximum number of keys that each non-root user may + have and the maximum total number of bytes of data that each of those + users may have stored in their keys. + +Root may alter these by writing each new limit as a decimal number string to +the appropriate file. + + +Userspace System Call Interface +=============================== + +Userspace can manipulate keys directly through three new syscalls: add_key, +request_key and keyctl. The latter provides a number of functions for +manipulating keys. + +When referring to a key directly, userspace programs should use the key's +serial number (a positive 32-bit integer). However, there are some special +values available for referring to special keys and keyrings that relate to the +process making the call:: + + CONSTANT VALUE KEY REFERENCED + ============================== ====== =========================== + KEY_SPEC_THREAD_KEYRING -1 thread-specific keyring + KEY_SPEC_PROCESS_KEYRING -2 process-specific keyring + KEY_SPEC_SESSION_KEYRING -3 session-specific keyring + KEY_SPEC_USER_KEYRING -4 UID-specific keyring + KEY_SPEC_USER_SESSION_KEYRING -5 UID-session keyring + KEY_SPEC_GROUP_KEYRING -6 GID-specific keyring + KEY_SPEC_REQKEY_AUTH_KEY -7 assumed request_key() + authorisation key + + +The main syscalls are: + + * Create a new key of given type, description and payload and add it to the + nominated keyring:: + + key_serial_t add_key(const char *type, const char *desc, + const void *payload, size_t plen, + key_serial_t keyring); + + If a key of the same type and description as that proposed already exists + in the keyring, this will try to update it with the given payload, or it + will return error EEXIST if that function is not supported by the key + type. The process must also have permission to write to the key to be able + to update it. The new key will have all user permissions granted and no + group or third party permissions. + + Otherwise, this will attempt to create a new key of the specified type and + description, and to instantiate it with the supplied payload and attach it + to the keyring. In this case, an error will be generated if the process + does not have permission to write to the keyring. + + If the key type supports it, if the description is NULL or an empty + string, the key type will try and generate a description from the content + of the payload. + + The payload is optional, and the pointer can be NULL if not required by + the type. The payload is plen in size, and plen can be zero for an empty + payload. + + A new keyring can be generated by setting type "keyring", the keyring name + as the description (or NULL) and setting the payload to NULL. + + User defined keys can be created by specifying type "user". It is + recommended that a user defined key's description by prefixed with a type + ID and a colon, such as "krb5tgt:" for a Kerberos 5 ticket granting + ticket. + + Any other type must have been registered with the kernel in advance by a + kernel service such as a filesystem. + + The ID of the new or updated key is returned if successful. + + + * Search the process's keyrings for a key, potentially calling out to + userspace to create it:: + + key_serial_t request_key(const char *type, const char *description, + const char *callout_info, + key_serial_t dest_keyring); + + This function searches all the process's keyrings in the order thread, + process, session for a matching key. This works very much like + KEYCTL_SEARCH, including the optional attachment of the discovered key to + a keyring. + + If a key cannot be found, and if callout_info is not NULL, then + /sbin/request-key will be invoked in an attempt to obtain a key. The + callout_info string will be passed as an argument to the program. + + See also Documentation/security/keys-request-key.txt. + + +The keyctl syscall functions are: + + * Map a special key ID to a real key ID for this process:: + + key_serial_t keyctl(KEYCTL_GET_KEYRING_ID, key_serial_t id, + int create); + + The special key specified by "id" is looked up (with the key being created + if necessary) and the ID of the key or keyring thus found is returned if + it exists. + + If the key does not yet exist, the key will be created if "create" is + non-zero; and the error ENOKEY will be returned if "create" is zero. + + + * Replace the session keyring this process subscribes to with a new one:: + + key_serial_t keyctl(KEYCTL_JOIN_SESSION_KEYRING, const char *name); + + If name is NULL, an anonymous keyring is created attached to the process + as its session keyring, displacing the old session keyring. + + If name is not NULL, if a keyring of that name exists, the process + attempts to attach it as the session keyring, returning an error if that + is not permitted; otherwise a new keyring of that name is created and + attached as the session keyring. + + To attach to a named keyring, the keyring must have search permission for + the process's ownership. + + The ID of the new session keyring is returned if successful. + + + * Update the specified key:: + + long keyctl(KEYCTL_UPDATE, key_serial_t key, const void *payload, + size_t plen); + + This will try to update the specified key with the given payload, or it + will return error EOPNOTSUPP if that function is not supported by the key + type. The process must also have permission to write to the key to be able + to update it. + + The payload is of length plen, and may be absent or empty as for + add_key(). + + + * Revoke a key:: + + long keyctl(KEYCTL_REVOKE, key_serial_t key); + + This makes a key unavailable for further operations. Further attempts to + use the key will be met with error EKEYREVOKED, and the key will no longer + be findable. + + + * Change the ownership of a key:: + + long keyctl(KEYCTL_CHOWN, key_serial_t key, uid_t uid, gid_t gid); + + This function permits a key's owner and group ID to be changed. Either one + of uid or gid can be set to -1 to suppress that change. + + Only the superuser can change a key's owner to something other than the + key's current owner. Similarly, only the superuser can change a key's + group ID to something other than the calling process's group ID or one of + its group list members. + + + * Change the permissions mask on a key:: + + long keyctl(KEYCTL_SETPERM, key_serial_t key, key_perm_t perm); + + This function permits the owner of a key or the superuser to change the + permissions mask on a key. + + Only bits the available bits are permitted; if any other bits are set, + error EINVAL will be returned. + + + * Describe a key:: + + long keyctl(KEYCTL_DESCRIBE, key_serial_t key, char *buffer, + size_t buflen); + + This function returns a summary of the key's attributes (but not its + payload data) as a string in the buffer provided. + + Unless there's an error, it always returns the amount of data it could + produce, even if that's too big for the buffer, but it won't copy more + than requested to userspace. If the buffer pointer is NULL then no copy + will take place. + + A process must have view permission on the key for this function to be + successful. + + If successful, a string is placed in the buffer in the following format:: + + ;;;; + + Where type and description are strings, uid and gid are decimal, and perm + is hexadecimal. A NUL character is included at the end of the string if + the buffer is sufficiently big. + + This can be parsed with:: + + sscanf(buffer, "%[^;];%d;%d;%o;%s", type, &uid, &gid, &mode, desc); + + + * Clear out a keyring:: + + long keyctl(KEYCTL_CLEAR, key_serial_t keyring); + + This function clears the list of keys attached to a keyring. The calling + process must have write permission on the keyring, and it must be a + keyring (or else error ENOTDIR will result). + + This function can also be used to clear special kernel keyrings if they + are appropriately marked if the user has CAP_SYS_ADMIN capability. The + DNS resolver cache keyring is an example of this. + + + * Link a key into a keyring:: + + long keyctl(KEYCTL_LINK, key_serial_t keyring, key_serial_t key); + + This function creates a link from the keyring to the key. The process must + have write permission on the keyring and must have link permission on the + key. + + Should the keyring not be a keyring, error ENOTDIR will result; and if the + keyring is full, error ENFILE will result. + + The link procedure checks the nesting of the keyrings, returning ELOOP if + it appears too deep or EDEADLK if the link would introduce a cycle. + + Any links within the keyring to keys that match the new key in terms of + type and description will be discarded from the keyring as the new one is + added. + + + * Unlink a key or keyring from another keyring:: + + long keyctl(KEYCTL_UNLINK, key_serial_t keyring, key_serial_t key); + + This function looks through the keyring for the first link to the + specified key, and removes it if found. Subsequent links to that key are + ignored. The process must have write permission on the keyring. + + If the keyring is not a keyring, error ENOTDIR will result; and if the key + is not present, error ENOENT will be the result. + + + * Search a keyring tree for a key:: + + key_serial_t keyctl(KEYCTL_SEARCH, key_serial_t keyring, + const char *type, const char *description, + key_serial_t dest_keyring); + + This searches the keyring tree headed by the specified keyring until a key + is found that matches the type and description criteria. Each keyring is + checked for keys before recursion into its children occurs. + + The process must have search permission on the top level keyring, or else + error EACCES will result. Only keyrings that the process has search + permission on will be recursed into, and only keys and keyrings for which + a process has search permission can be matched. If the specified keyring + is not a keyring, ENOTDIR will result. + + If the search succeeds, the function will attempt to link the found key + into the destination keyring if one is supplied (non-zero ID). All the + constraints applicable to KEYCTL_LINK apply in this case too. + + Error ENOKEY, EKEYREVOKED or EKEYEXPIRED will be returned if the search + fails. On success, the resulting key ID will be returned. + + + * Read the payload data from a key:: + + long keyctl(KEYCTL_READ, key_serial_t keyring, char *buffer, + size_t buflen); + + This function attempts to read the payload data from the specified key + into the buffer. The process must have read permission on the key to + succeed. + + The returned data will be processed for presentation by the key type. For + instance, a keyring will return an array of key_serial_t entries + representing the IDs of all the keys to which it is subscribed. The user + defined key type will return its data as is. If a key type does not + implement this function, error EOPNOTSUPP will result. + + As much of the data as can be fitted into the buffer will be copied to + userspace if the buffer pointer is not NULL. + + On a successful return, the function will always return the amount of data + available rather than the amount copied. + + + * Instantiate a partially constructed key:: + + long keyctl(KEYCTL_INSTANTIATE, key_serial_t key, + const void *payload, size_t plen, + key_serial_t keyring); + long keyctl(KEYCTL_INSTANTIATE_IOV, key_serial_t key, + const struct iovec *payload_iov, unsigned ioc, + key_serial_t keyring); + + If the kernel calls back to userspace to complete the instantiation of a + key, userspace should use this call to supply data for the key before the + invoked process returns, or else the key will be marked negative + automatically. + + The process must have write access on the key to be able to instantiate + it, and the key must be uninstantiated. + + If a keyring is specified (non-zero), the key will also be linked into + that keyring, however all the constraints applying in KEYCTL_LINK apply in + this case too. + + The payload and plen arguments describe the payload data as for add_key(). + + The payload_iov and ioc arguments describe the payload data in an iovec + array instead of a single buffer. + + + * Negatively instantiate a partially constructed key:: + + long keyctl(KEYCTL_NEGATE, key_serial_t key, + unsigned timeout, key_serial_t keyring); + long keyctl(KEYCTL_REJECT, key_serial_t key, + unsigned timeout, unsigned error, key_serial_t keyring); + + If the kernel calls back to userspace to complete the instantiation of a + key, userspace should use this call mark the key as negative before the + invoked process returns if it is unable to fulfill the request. + + The process must have write access on the key to be able to instantiate + it, and the key must be uninstantiated. + + If a keyring is specified (non-zero), the key will also be linked into + that keyring, however all the constraints applying in KEYCTL_LINK apply in + this case too. + + If the key is rejected, future searches for it will return the specified + error code until the rejected key expires. Negating the key is the same + as rejecting the key with ENOKEY as the error code. + + + * Set the default request-key destination keyring:: + + long keyctl(KEYCTL_SET_REQKEY_KEYRING, int reqkey_defl); + + This sets the default keyring to which implicitly requested keys will be + attached for this thread. reqkey_defl should be one of these constants:: + + CONSTANT VALUE NEW DEFAULT KEYRING + ====================================== ====== ======================= + KEY_REQKEY_DEFL_NO_CHANGE -1 No change + KEY_REQKEY_DEFL_DEFAULT 0 Default[1] + KEY_REQKEY_DEFL_THREAD_KEYRING 1 Thread keyring + KEY_REQKEY_DEFL_PROCESS_KEYRING 2 Process keyring + KEY_REQKEY_DEFL_SESSION_KEYRING 3 Session keyring + KEY_REQKEY_DEFL_USER_KEYRING 4 User keyring + KEY_REQKEY_DEFL_USER_SESSION_KEYRING 5 User session keyring + KEY_REQKEY_DEFL_GROUP_KEYRING 6 Group keyring + + The old default will be returned if successful and error EINVAL will be + returned if reqkey_defl is not one of the above values. + + The default keyring can be overridden by the keyring indicated to the + request_key() system call. + + Note that this setting is inherited across fork/exec. + + [1] The default is: the thread keyring if there is one, otherwise + the process keyring if there is one, otherwise the session keyring if + there is one, otherwise the user default session keyring. + + + * Set the timeout on a key:: + + long keyctl(KEYCTL_SET_TIMEOUT, key_serial_t key, unsigned timeout); + + This sets or clears the timeout on a key. The timeout can be 0 to clear + the timeout or a number of seconds to set the expiry time that far into + the future. + + The process must have attribute modification access on a key to set its + timeout. Timeouts may not be set with this function on negative, revoked + or expired keys. + + + * Assume the authority granted to instantiate a key:: + + long keyctl(KEYCTL_ASSUME_AUTHORITY, key_serial_t key); + + This assumes or divests the authority required to instantiate the + specified key. Authority can only be assumed if the thread has the + authorisation key associated with the specified key in its keyrings + somewhere. + + Once authority is assumed, searches for keys will also search the + requester's keyrings using the requester's security label, UID, GID and + groups. + + If the requested authority is unavailable, error EPERM will be returned, + likewise if the authority has been revoked because the target key is + already instantiated. + + If the specified key is 0, then any assumed authority will be divested. + + The assumed authoritative key is inherited across fork and exec. + + + * Get the LSM security context attached to a key:: + + long keyctl(KEYCTL_GET_SECURITY, key_serial_t key, char *buffer, + size_t buflen) + + This function returns a string that represents the LSM security context + attached to a key in the buffer provided. + + Unless there's an error, it always returns the amount of data it could + produce, even if that's too big for the buffer, but it won't copy more + than requested to userspace. If the buffer pointer is NULL then no copy + will take place. + + A NUL character is included at the end of the string if the buffer is + sufficiently big. This is included in the returned count. If no LSM is + in force then an empty string will be returned. + + A process must have view permission on the key for this function to be + successful. + + + * Install the calling process's session keyring on its parent:: + + long keyctl(KEYCTL_SESSION_TO_PARENT); + + This functions attempts to install the calling process's session keyring + on to the calling process's parent, replacing the parent's current session + keyring. + + The calling process must have the same ownership as its parent, the + keyring must have the same ownership as the calling process, the calling + process must have LINK permission on the keyring and the active LSM module + mustn't deny permission, otherwise error EPERM will be returned. + + Error ENOMEM will be returned if there was insufficient memory to complete + the operation, otherwise 0 will be returned to indicate success. + + The keyring will be replaced next time the parent process leaves the + kernel and resumes executing userspace. + + + * Invalidate a key:: + + long keyctl(KEYCTL_INVALIDATE, key_serial_t key); + + This function marks a key as being invalidated and then wakes up the + garbage collector. The garbage collector immediately removes invalidated + keys from all keyrings and deletes the key when its reference count + reaches zero. + + Keys that are marked invalidated become invisible to normal key operations + immediately, though they are still visible in /proc/keys until deleted + (they're marked with an 'i' flag). + + A process must have search permission on the key for this function to be + successful. + + * Compute a Diffie-Hellman shared secret or public key:: + + long keyctl(KEYCTL_DH_COMPUTE, struct keyctl_dh_params *params, + char *buffer, size_t buflen, struct keyctl_kdf_params *kdf); + + The params struct contains serial numbers for three keys:: + + - The prime, p, known to both parties + - The local private key + - The base integer, which is either a shared generator or the + remote public key + + The value computed is:: + + result = base ^ private (mod prime) + + If the base is the shared generator, the result is the local + public key. If the base is the remote public key, the result is + the shared secret. + + If the parameter kdf is NULL, the following applies: + + - The buffer length must be at least the length of the prime, or zero. + + - If the buffer length is nonzero, the length of the result is + returned when it is successfully calculated and copied in to the + buffer. When the buffer length is zero, the minimum required + buffer length is returned. + + The kdf parameter allows the caller to apply a key derivation function + (KDF) on the Diffie-Hellman computation where only the result + of the KDF is returned to the caller. The KDF is characterized with + struct keyctl_kdf_params as follows: + + - ``char *hashname`` specifies the NUL terminated string identifying + the hash used from the kernel crypto API and applied for the KDF + operation. The KDF implemenation complies with SP800-56A as well + as with SP800-108 (the counter KDF). + + - ``char *otherinfo`` specifies the OtherInfo data as documented in + SP800-56A section 5.8.1.2. The length of the buffer is given with + otherinfolen. The format of OtherInfo is defined by the caller. + The otherinfo pointer may be NULL if no OtherInfo shall be used. + + This function will return error EOPNOTSUPP if the key type is not + supported, error ENOKEY if the key could not be found, or error + EACCES if the key is not readable by the caller. In addition, the + function will return EMSGSIZE when the parameter kdf is non-NULL + and either the buffer length or the OtherInfo length exceeds the + allowed length. + + * Restrict keyring linkage:: + + long keyctl(KEYCTL_RESTRICT_KEYRING, key_serial_t keyring, + const char *type, const char *restriction); + + An existing keyring can restrict linkage of additional keys by evaluating + the contents of the key according to a restriction scheme. + + "keyring" is the key ID for an existing keyring to apply a restriction + to. It may be empty or may already have keys linked. Existing linked keys + will remain in the keyring even if the new restriction would reject them. + + "type" is a registered key type. + + "restriction" is a string describing how key linkage is to be restricted. + The format varies depending on the key type, and the string is passed to + the lookup_restriction() function for the requested type. It may specify + a method and relevant data for the restriction such as signature + verification or constraints on key payload. If the requested key type is + later unregistered, no keys may be added to the keyring after the key type + is removed. + + To apply a keyring restriction the process must have Set Attribute + permission and the keyring must not be previously restricted. + +Kernel Services +=============== + +The kernel services for key management are fairly simple to deal with. They can +be broken down into two areas: keys and key types. + +Dealing with keys is fairly straightforward. Firstly, the kernel service +registers its type, then it searches for a key of that type. It should retain +the key as long as it has need of it, and then it should release it. For a +filesystem or device file, a search would probably be performed during the open +call, and the key released upon close. How to deal with conflicting keys due to +two different users opening the same file is left to the filesystem author to +solve. + +To access the key manager, the following header must be #included:: + + + +Specific key types should have a header file under include/keys/ that should be +used to access that type. For keys of type "user", for example, that would be:: + + + +Note that there are two different types of pointers to keys that may be +encountered: + + * struct key * + + This simply points to the key structure itself. Key structures will be at + least four-byte aligned. + + * key_ref_t + + This is equivalent to a ``struct key *``, but the least significant bit is set + if the caller "possesses" the key. By "possession" it is meant that the + calling processes has a searchable link to the key from one of its + keyrings. There are three functions for dealing with these:: + + key_ref_t make_key_ref(const struct key *key, bool possession); + + struct key *key_ref_to_ptr(const key_ref_t key_ref); + + bool is_key_possessed(const key_ref_t key_ref); + + The first function constructs a key reference from a key pointer and + possession information (which must be true or false). + + The second function retrieves the key pointer from a reference and the + third retrieves the possession flag. + +When accessing a key's payload contents, certain precautions must be taken to +prevent access vs modification races. See the section "Notes on accessing +payload contents" for more information. + + * To search for a key, call:: + + struct key *request_key(const struct key_type *type, + const char *description, + const char *callout_info); + + This is used to request a key or keyring with a description that matches + the description specified according to the key type's match_preparse() + method. This permits approximate matching to occur. If callout_string is + not NULL, then /sbin/request-key will be invoked in an attempt to obtain + the key from userspace. In that case, callout_string will be passed as an + argument to the program. + + Should the function fail error ENOKEY, EKEYEXPIRED or EKEYREVOKED will be + returned. + + If successful, the key will have been attached to the default keyring for + implicitly obtained request-key keys, as set by KEYCTL_SET_REQKEY_KEYRING. + + See also Documentation/security/keys-request-key.txt. + + + * To search for a key, passing auxiliary data to the upcaller, call:: + + struct key *request_key_with_auxdata(const struct key_type *type, + const char *description, + const void *callout_info, + size_t callout_len, + void *aux); + + This is identical to request_key(), except that the auxiliary data is + passed to the key_type->request_key() op if it exists, and the callout_info + is a blob of length callout_len, if given (the length may be 0). + + + * A key can be requested asynchronously by calling one of:: + + struct key *request_key_async(const struct key_type *type, + const char *description, + const void *callout_info, + size_t callout_len); + + or:: + + struct key *request_key_async_with_auxdata(const struct key_type *type, + const char *description, + const char *callout_info, + size_t callout_len, + void *aux); + + which are asynchronous equivalents of request_key() and + request_key_with_auxdata() respectively. + + These two functions return with the key potentially still under + construction. To wait for construction completion, the following should be + called:: + + int wait_for_key_construction(struct key *key, bool intr); + + The function will wait for the key to finish being constructed and then + invokes key_validate() to return an appropriate value to indicate the state + of the key (0 indicates the key is usable). + + If intr is true, then the wait can be interrupted by a signal, in which + case error ERESTARTSYS will be returned. + + + * When it is no longer required, the key should be released using:: + + void key_put(struct key *key); + + Or:: + + void key_ref_put(key_ref_t key_ref); + + These can be called from interrupt context. If CONFIG_KEYS is not set then + the argument will not be parsed. + + + * Extra references can be made to a key by calling one of the following + functions:: + + struct key *__key_get(struct key *key); + struct key *key_get(struct key *key); + + Keys so references will need to be disposed of by calling key_put() when + they've been finished with. The key pointer passed in will be returned. + + In the case of key_get(), if the pointer is NULL or CONFIG_KEYS is not set + then the key will not be dereferenced and no increment will take place. + + + * A key's serial number can be obtained by calling:: + + key_serial_t key_serial(struct key *key); + + If key is NULL or if CONFIG_KEYS is not set then 0 will be returned (in the + latter case without parsing the argument). + + + * If a keyring was found in the search, this can be further searched by:: + + key_ref_t keyring_search(key_ref_t keyring_ref, + const struct key_type *type, + const char *description) + + This searches the keyring tree specified for a matching key. Error ENOKEY + is returned upon failure (use IS_ERR/PTR_ERR to determine). If successful, + the returned key will need to be released. + + The possession attribute from the keyring reference is used to control + access through the permissions mask and is propagated to the returned key + reference pointer if successful. + + + * A keyring can be created by:: + + struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid, + const struct cred *cred, + key_perm_t perm, + struct key_restriction *restrict_link, + unsigned long flags, + struct key *dest); + + This creates a keyring with the given attributes and returns it. If dest + is not NULL, the new keyring will be linked into the keyring to which it + points. No permission checks are made upon the destination keyring. + + Error EDQUOT can be returned if the keyring would overload the quota (pass + KEY_ALLOC_NOT_IN_QUOTA in flags if the keyring shouldn't be accounted + towards the user's quota). Error ENOMEM can also be returned. + + If restrict_link is not NULL, it should point to a structure that contains + the function that will be called each time an attempt is made to link a + key into the new keyring. The structure may also contain a key pointer + and an associated key type. The function is called to check whether a key + may be added into the keyring or not. The key type is used by the garbage + collector to clean up function or data pointers in this structure if the + given key type is unregistered. Callers of key_create_or_update() within + the kernel can pass KEY_ALLOC_BYPASS_RESTRICTION to suppress the check. + An example of using this is to manage rings of cryptographic keys that are + set up when the kernel boots where userspace is also permitted to add keys + - provided they can be verified by a key the kernel already has. + + When called, the restriction function will be passed the keyring being + added to, the key type, the payload of the key being added, and data to be + used in the restriction check. Note that when a new key is being created, + this is called between payload preparsing and actual key creation. The + function should return 0 to allow the link or an error to reject it. + + A convenience function, restrict_link_reject, exists to always return + -EPERM to in this case. + + + * To check the validity of a key, this function can be called:: + + int validate_key(struct key *key); + + This checks that the key in question hasn't expired or and hasn't been + revoked. Should the key be invalid, error EKEYEXPIRED or EKEYREVOKED will + be returned. If the key is NULL or if CONFIG_KEYS is not set then 0 will be + returned (in the latter case without parsing the argument). + + + * To register a key type, the following function should be called:: + + int register_key_type(struct key_type *type); + + This will return error EEXIST if a type of the same name is already + present. + + + * To unregister a key type, call:: + + void unregister_key_type(struct key_type *type); + + +Under some circumstances, it may be desirable to deal with a bundle of keys. +The facility provides access to the keyring type for managing such a bundle:: + + struct key_type key_type_keyring; + +This can be used with a function such as request_key() to find a specific +keyring in a process's keyrings. A keyring thus found can then be searched +with keyring_search(). Note that it is not possible to use request_key() to +search a specific keyring, so using keyrings in this way is of limited utility. + + +Notes On Accessing Payload Contents +=================================== + +The simplest payload is just data stored in key->payload directly. In this +case, there's no need to indulge in RCU or locking when accessing the payload. + +More complex payload contents must be allocated and pointers to them set in the +key->payload.data[] array. One of the following ways must be selected to +access the data: + + 1) Unmodifiable key type. + + If the key type does not have a modify method, then the key's payload can + be accessed without any form of locking, provided that it's known to be + instantiated (uninstantiated keys cannot be "found"). + + 2) The key's semaphore. + + The semaphore could be used to govern access to the payload and to control + the payload pointer. It must be write-locked for modifications and would + have to be read-locked for general access. The disadvantage of doing this + is that the accessor may be required to sleep. + + 3) RCU. + + RCU must be used when the semaphore isn't already held; if the semaphore + is held then the contents can't change under you unexpectedly as the + semaphore must still be used to serialise modifications to the key. The + key management code takes care of this for the key type. + + However, this means using:: + + rcu_read_lock() ... rcu_dereference() ... rcu_read_unlock() + + to read the pointer, and:: + + rcu_dereference() ... rcu_assign_pointer() ... call_rcu() + + to set the pointer and dispose of the old contents after a grace period. + Note that only the key type should ever modify a key's payload. + + Furthermore, an RCU controlled payload must hold a struct rcu_head for the + use of call_rcu() and, if the payload is of variable size, the length of + the payload. key->datalen cannot be relied upon to be consistent with the + payload just dereferenced if the key's semaphore is not held. + + Note that key->payload.data[0] has a shadow that is marked for __rcu + usage. This is called key->payload.rcu_data0. The following accessors + wrap the RCU calls to this element: + + a) Set or change the first payload pointer:: + + rcu_assign_keypointer(struct key *key, void *data); + + b) Read the first payload pointer with the key semaphore held:: + + [const] void *dereference_key_locked([const] struct key *key); + + Note that the return value will inherit its constness from the key + parameter. Static analysis will give an error if it things the lock + isn't held. + + c) Read the first payload pointer with the RCU read lock held:: + + const void *dereference_key_rcu(const struct key *key); + + +Defining a Key Type +=================== + +A kernel service may want to define its own key type. For instance, an AFS +filesystem might want to define a Kerberos 5 ticket key type. To do this, it +author fills in a key_type struct and registers it with the system. + +Source files that implement key types should include the following header file:: + + + +The structure has a number of fields, some of which are mandatory: + + * ``const char *name`` + + The name of the key type. This is used to translate a key type name + supplied by userspace into a pointer to the structure. + + + * ``size_t def_datalen`` + + This is optional - it supplies the default payload data length as + contributed to the quota. If the key type's payload is always or almost + always the same size, then this is a more efficient way to do things. + + The data length (and quota) on a particular key can always be changed + during instantiation or update by calling:: + + int key_payload_reserve(struct key *key, size_t datalen); + + With the revised data length. Error EDQUOT will be returned if this is not + viable. + + + * ``int (*vet_description)(const char *description);`` + + This optional method is called to vet a key description. If the key type + doesn't approve of the key description, it may return an error, otherwise + it should return 0. + + + * ``int (*preparse)(struct key_preparsed_payload *prep);`` + + This optional method permits the key type to attempt to parse payload + before a key is created (add key) or the key semaphore is taken (update or + instantiate key). The structure pointed to by prep looks like:: + + struct key_preparsed_payload { + char *description; + union key_payload payload; + const void *data; + size_t datalen; + size_t quotalen; + time_t expiry; + }; + + Before calling the method, the caller will fill in data and datalen with + the payload blob parameters; quotalen will be filled in with the default + quota size from the key type; expiry will be set to TIME_T_MAX and the + rest will be cleared. + + If a description can be proposed from the payload contents, that should be + attached as a string to the description field. This will be used for the + key description if the caller of add_key() passes NULL or "". + + The method can attach anything it likes to payload. This is merely passed + along to the instantiate() or update() operations. If set, the expiry + time will be applied to the key if it is instantiated from this data. + + The method should return 0 if successful or a negative error code + otherwise. + + + * ``void (*free_preparse)(struct key_preparsed_payload *prep);`` + + This method is only required if the preparse() method is provided, + otherwise it is unused. It cleans up anything attached to the description + and payload fields of the key_preparsed_payload struct as filled in by the + preparse() method. It will always be called after preparse() returns + successfully, even if instantiate() or update() succeed. + + + * ``int (*instantiate)(struct key *key, struct key_preparsed_payload *prep);`` + + This method is called to attach a payload to a key during construction. + The payload attached need not bear any relation to the data passed to this + function. + + The prep->data and prep->datalen fields will define the original payload + blob. If preparse() was supplied then other fields may be filled in also. + + If the amount of data attached to the key differs from the size in + keytype->def_datalen, then key_payload_reserve() should be called. + + This method does not have to lock the key in order to attach a payload. + The fact that KEY_FLAG_INSTANTIATED is not set in key->flags prevents + anything else from gaining access to the key. + + It is safe to sleep in this method. + + generic_key_instantiate() is provided to simply copy the data from + prep->payload.data[] to key->payload.data[], with RCU-safe assignment on + the first element. It will then clear prep->payload.data[] so that the + free_preparse method doesn't release the data. + + + * ``int (*update)(struct key *key, const void *data, size_t datalen);`` + + If this type of key can be updated, then this method should be provided. + It is called to update a key's payload from the blob of data provided. + + The prep->data and prep->datalen fields will define the original payload + blob. If preparse() was supplied then other fields may be filled in also. + + key_payload_reserve() should be called if the data length might change + before any changes are actually made. Note that if this succeeds, the type + is committed to changing the key because it's already been altered, so all + memory allocation must be done first. + + The key will have its semaphore write-locked before this method is called, + but this only deters other writers; any changes to the key's payload must + be made under RCU conditions, and call_rcu() must be used to dispose of + the old payload. + + key_payload_reserve() should be called before the changes are made, but + after all allocations and other potentially failing function calls are + made. + + It is safe to sleep in this method. + + + * ``int (*match_preparse)(struct key_match_data *match_data);`` + + This method is optional. It is called when a key search is about to be + performed. It is given the following structure:: + + struct key_match_data { + bool (*cmp)(const struct key *key, + const struct key_match_data *match_data); + const void *raw_data; + void *preparsed; + unsigned lookup_type; + }; + + On entry, raw_data will be pointing to the criteria to be used in matching + a key by the caller and should not be modified. ``(*cmp)()`` will be pointing + to the default matcher function (which does an exact description match + against raw_data) and lookup_type will be set to indicate a direct lookup. + + The following lookup_type values are available: + + * KEYRING_SEARCH_LOOKUP_DIRECT - A direct lookup hashes the type and + description to narrow down the search to a small number of keys. + + * KEYRING_SEARCH_LOOKUP_ITERATE - An iterative lookup walks all the + keys in the keyring until one is matched. This must be used for any + search that's not doing a simple direct match on the key description. + + The method may set cmp to point to a function of its choice that does some + other form of match, may set lookup_type to KEYRING_SEARCH_LOOKUP_ITERATE + and may attach something to the preparsed pointer for use by ``(*cmp)()``. + ``(*cmp)()`` should return true if a key matches and false otherwise. + + If preparsed is set, it may be necessary to use the match_free() method to + clean it up. + + The method should return 0 if successful or a negative error code + otherwise. + + It is permitted to sleep in this method, but ``(*cmp)()`` may not sleep as + locks will be held over it. + + If match_preparse() is not provided, keys of this type will be matched + exactly by their description. + + + * ``void (*match_free)(struct key_match_data *match_data);`` + + This method is optional. If given, it called to clean up + match_data->preparsed after a successful call to match_preparse(). + + + * ``void (*revoke)(struct key *key);`` + + This method is optional. It is called to discard part of the payload + data upon a key being revoked. The caller will have the key semaphore + write-locked. + + It is safe to sleep in this method, though care should be taken to avoid + a deadlock against the key semaphore. + + + * ``void (*destroy)(struct key *key);`` + + This method is optional. It is called to discard the payload data on a key + when it is being destroyed. + + This method does not need to lock the key to access the payload; it can + consider the key as being inaccessible at this time. Note that the key's + type may have been changed before this function is called. + + It is not safe to sleep in this method; the caller may hold spinlocks. + + + * ``void (*describe)(const struct key *key, struct seq_file *p);`` + + This method is optional. It is called during /proc/keys reading to + summarise a key's description and payload in text form. + + This method will be called with the RCU read lock held. rcu_dereference() + should be used to read the payload pointer if the payload is to be + accessed. key->datalen cannot be trusted to stay consistent with the + contents of the payload. + + The description will not change, though the key's state may. + + It is not safe to sleep in this method; the RCU read lock is held by the + caller. + + + * ``long (*read)(const struct key *key, char __user *buffer, size_t buflen);`` + + This method is optional. It is called by KEYCTL_READ to translate the + key's payload into something a blob of data for userspace to deal with. + Ideally, the blob should be in the same format as that passed in to the + instantiate and update methods. + + If successful, the blob size that could be produced should be returned + rather than the size copied. + + This method will be called with the key's semaphore read-locked. This will + prevent the key's payload changing. It is not necessary to use RCU locking + when accessing the key's payload. It is safe to sleep in this method, such + as might happen when the userspace buffer is accessed. + + + * ``int (*request_key)(struct key_construction *cons, const char *op, void *aux);`` + + This method is optional. If provided, request_key() and friends will + invoke this function rather than upcalling to /sbin/request-key to operate + upon a key of this type. + + The aux parameter is as passed to request_key_async_with_auxdata() and + similar or is NULL otherwise. Also passed are the construction record for + the key to be operated upon and the operation type (currently only + "create"). + + This method is permitted to return before the upcall is complete, but the + following function must be called under all circumstances to complete the + instantiation process, whether or not it succeeds, whether or not there's + an error:: + + void complete_request_key(struct key_construction *cons, int error); + + The error parameter should be 0 on success, -ve on error. The + construction record is destroyed by this action and the authorisation key + will be revoked. If an error is indicated, the key under construction + will be negatively instantiated if it wasn't already instantiated. + + If this method returns an error, that error will be returned to the + caller of request_key*(). complete_request_key() must be called prior to + returning. + + The key under construction and the authorisation key can be found in the + key_construction struct pointed to by cons: + + * ``struct key *key;`` + + The key under construction. + + * ``struct key *authkey;`` + + The authorisation key. + + + * ``struct key_restriction *(*lookup_restriction)(const char *params);`` + + This optional method is used to enable userspace configuration of keyring + restrictions. The restriction parameter string (not including the key type + name) is passed in, and this method returns a pointer to a key_restriction + structure containing the relevant functions and data to evaluate each + attempted key link operation. If there is no match, -EINVAL is returned. + + +Request-Key Callback Service +============================ + +To create a new key, the kernel will attempt to execute the following command +line:: + + /sbin/request-key create \ + + + is the key being constructed, and the three keyrings are the process +keyrings from the process that caused the search to be issued. These are +included for two reasons: + + 1 There may be an authentication token in one of the keyrings that is + required to obtain the key, eg: a Kerberos Ticket-Granting Ticket. + + 2 The new key should probably be cached in one of these rings. + +This program should set it UID and GID to those specified before attempting to +access any more keys. It may then look around for a user specific process to +hand the request off to (perhaps a path held in placed in another key by, for +example, the KDE desktop manager). + +The program (or whatever it calls) should finish construction of the key by +calling KEYCTL_INSTANTIATE or KEYCTL_INSTANTIATE_IOV, which also permits it to +cache the key in one of the keyrings (probably the session ring) before +returning. Alternatively, the key can be marked as negative with KEYCTL_NEGATE +or KEYCTL_REJECT; this also permits the key to be cached in one of the +keyrings. + +If it returns with the key remaining in the unconstructed state, the key will +be marked as being negative, it will be added to the session keyring, and an +error will be returned to the key requestor. + +Supplementary information may be provided from whoever or whatever invoked this +service. This will be passed as the parameter. If no such +information was made available, then "-" will be passed as this parameter +instead. + + +Similarly, the kernel may attempt to update an expired or a soon to expire key +by executing:: + + /sbin/request-key update \ + + +In this case, the program isn't required to actually attach the key to a ring; +the rings are provided for reference. + + +Garbage Collection +================== + +Dead keys (for which the type has been removed) will be automatically unlinked +from those keyrings that point to them and deleted as soon as possible by a +background garbage collector. + +Similarly, revoked and expired keys will be garbage collected, but only after a +certain amount of time has passed. This time is set as a number of seconds in:: + + /proc/sys/kernel/keys/gc_delay diff --git a/Documentation/security/keys/index.rst b/Documentation/security/keys/index.rst new file mode 100644 index 000000000000..ddfe7e4726e6 --- /dev/null +++ b/Documentation/security/keys/index.rst @@ -0,0 +1,8 @@ +=========== +Kernel Keys +=========== + +.. toctree:: + :maxdepth: 1 + + core diff --git a/MAINTAINERS b/MAINTAINERS index ce6744ee83e2..9f3b8b0cae5a 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7342,7 +7342,7 @@ KEYS/KEYRINGS: M: David Howells L: keyrings@vger.kernel.org S: Maintained -F: Documentation/security/keys.txt +F: Documentation/security/keys/core.rst F: include/linux/key.h F: include/linux/key-type.h F: include/linux/keyctl.h diff --git a/include/linux/key.h b/include/linux/key.h index 0c9b93b0d1f7..24dfe6c1f8cb 100644 --- a/include/linux/key.h +++ b/include/linux/key.h @@ -9,7 +9,7 @@ * 2 of the License, or (at your option) any later version. * * - * See Documentation/security/keys.txt for information on keys/keyrings. + * See Documentation/security/keys/core.rst for information on keys/keyrings. */ #ifndef _LINUX_KEY_H -- cgit v1.2.3-59-g8ed1b From 5395d312dff00d9e94702d28fe1e08dacd1cbe31 Mon Sep 17 00:00:00 2001 From: Kees Cook Date: Sat, 13 May 2017 04:51:53 -0700 Subject: doc: ReSTify keys-trusted-encrypted.txt Adjusts for ReST markup and moves under keys security devel index. Cc: David Howells Cc: Mimi Zohar Signed-off-by: Kees Cook Signed-off-by: Jonathan Corbet --- Documentation/security/00-INDEX | 4 - Documentation/security/conf.py | 8 - Documentation/security/keys-trusted-encrypted.txt | 167 --------------------- Documentation/security/keys/index.rst | 1 + Documentation/security/keys/trusted-encrypted.rst | 175 ++++++++++++++++++++++ MAINTAINERS | 4 +- security/keys/encrypted-keys/encrypted.c | 2 +- security/keys/encrypted-keys/masterkey_trusted.c | 2 +- security/keys/trusted.c | 2 +- 9 files changed, 181 insertions(+), 184 deletions(-) delete mode 100644 Documentation/security/00-INDEX delete mode 100644 Documentation/security/conf.py delete mode 100644 Documentation/security/keys-trusted-encrypted.txt create mode 100644 Documentation/security/keys/trusted-encrypted.rst (limited to 'MAINTAINERS') diff --git a/Documentation/security/00-INDEX b/Documentation/security/00-INDEX deleted file mode 100644 index c8dbbc227326..000000000000 --- a/Documentation/security/00-INDEX +++ /dev/null @@ -1,4 +0,0 @@ -00-INDEX - - this file. -keys-trusted-encrypted.txt - - info on the Trusted and Encrypted keys in the kernel key ring service. diff --git a/Documentation/security/conf.py b/Documentation/security/conf.py deleted file mode 100644 index 472fc9a8eb67..000000000000 --- a/Documentation/security/conf.py +++ /dev/null @@ -1,8 +0,0 @@ -project = "The kernel security subsystem manual" - -tags.add("subproject") - -latex_documents = [ - ('index', 'security.tex', project, - 'The kernel development community', 'manual'), -] diff --git a/Documentation/security/keys-trusted-encrypted.txt b/Documentation/security/keys-trusted-encrypted.txt deleted file mode 100644 index b20a993a32af..000000000000 --- a/Documentation/security/keys-trusted-encrypted.txt +++ /dev/null @@ -1,167 +0,0 @@ - Trusted and Encrypted Keys - -Trusted and Encrypted Keys are two new key types added to the existing kernel -key ring service. Both of these new types are variable length symmetric keys, -and in both cases all keys are created in the kernel, and user space sees, -stores, and loads only encrypted blobs. Trusted Keys require the availability -of a Trusted Platform Module (TPM) chip for greater security, while Encrypted -Keys can be used on any system. All user level blobs, are displayed and loaded -in hex ascii for convenience, and are integrity verified. - -Trusted Keys use a TPM both to generate and to seal the keys. Keys are sealed -under a 2048 bit RSA key in the TPM, and optionally sealed to specified PCR -(integrity measurement) values, and only unsealed by the TPM, if PCRs and blob -integrity verifications match. A loaded Trusted Key can be updated with new -(future) PCR values, so keys are easily migrated to new pcr values, such as -when the kernel and initramfs are updated. The same key can have many saved -blobs under different PCR values, so multiple boots are easily supported. - -By default, trusted keys are sealed under the SRK, which has the default -authorization value (20 zeros). This can be set at takeownership time with the -trouser's utility: "tpm_takeownership -u -z". - -Usage: - keyctl add trusted name "new keylen [options]" ring - keyctl add trusted name "load hex_blob [pcrlock=pcrnum]" ring - keyctl update key "update [options]" - keyctl print keyid - - options: - keyhandle= ascii hex value of sealing key default 0x40000000 (SRK) - keyauth= ascii hex auth for sealing key default 0x00...i - (40 ascii zeros) - blobauth= ascii hex auth for sealed data default 0x00... - (40 ascii zeros) - pcrinfo= ascii hex of PCR_INFO or PCR_INFO_LONG (no default) - pcrlock= pcr number to be extended to "lock" blob - migratable= 0|1 indicating permission to reseal to new PCR values, - default 1 (resealing allowed) - hash= hash algorithm name as a string. For TPM 1.x the only - allowed value is sha1. For TPM 2.x the allowed values - are sha1, sha256, sha384, sha512 and sm3-256. - policydigest= digest for the authorization policy. must be calculated - with the same hash algorithm as specified by the 'hash=' - option. - policyhandle= handle to an authorization policy session that defines the - same policy and with the same hash algorithm as was used to - seal the key. - -"keyctl print" returns an ascii hex copy of the sealed key, which is in standard -TPM_STORED_DATA format. The key length for new keys are always in bytes. -Trusted Keys can be 32 - 128 bytes (256 - 1024 bits), the upper limit is to fit -within the 2048 bit SRK (RSA) keylength, with all necessary structure/padding. - -Encrypted keys do not depend on a TPM, and are faster, as they use AES for -encryption/decryption. New keys are created from kernel generated random -numbers, and are encrypted/decrypted using a specified 'master' key. The -'master' key can either be a trusted-key or user-key type. The main -disadvantage of encrypted keys is that if they are not rooted in a trusted key, -they are only as secure as the user key encrypting them. The master user key -should therefore be loaded in as secure a way as possible, preferably early in -boot. - -The decrypted portion of encrypted keys can contain either a simple symmetric -key or a more complex structure. The format of the more complex structure is -application specific, which is identified by 'format'. - -Usage: - keyctl add encrypted name "new [format] key-type:master-key-name keylen" - ring - keyctl add encrypted name "load hex_blob" ring - keyctl update keyid "update key-type:master-key-name" - -format:= 'default | ecryptfs' -key-type:= 'trusted' | 'user' - - -Examples of trusted and encrypted key usage: - -Create and save a trusted key named "kmk" of length 32 bytes: - - $ keyctl add trusted kmk "new 32" @u - 440502848 - - $ keyctl show - Session Keyring - -3 --alswrv 500 500 keyring: _ses - 97833714 --alswrv 500 -1 \_ keyring: _uid.500 - 440502848 --alswrv 500 500 \_ trusted: kmk - - $ keyctl print 440502848 - 0101000000000000000001005d01b7e3f4a6be5709930f3b70a743cbb42e0cc95e18e915 - 3f60da455bbf1144ad12e4f92b452f966929f6105fd29ca28e4d4d5a031d068478bacb0b - 27351119f822911b0a11ba3d3498ba6a32e50dac7f32894dd890eb9ad578e4e292c83722 - a52e56a097e6a68b3f56f7a52ece0cdccba1eb62cad7d817f6dc58898b3ac15f36026fec - d568bd4a706cb60bb37be6d8f1240661199d640b66fb0fe3b079f97f450b9ef9c22c6d5d - dd379f0facd1cd020281dfa3c70ba21a3fa6fc2471dc6d13ecf8298b946f65345faa5ef0 - f1f8fff03ad0acb083725535636addb08d73dedb9832da198081e5deae84bfaf0409c22b - e4a8aea2b607ec96931e6f4d4fe563ba - - $ keyctl pipe 440502848 > kmk.blob - -Load a trusted key from the saved blob: - - $ keyctl add trusted kmk "load `cat kmk.blob`" @u - 268728824 - - $ keyctl print 268728824 - 0101000000000000000001005d01b7e3f4a6be5709930f3b70a743cbb42e0cc95e18e915 - 3f60da455bbf1144ad12e4f92b452f966929f6105fd29ca28e4d4d5a031d068478bacb0b - 27351119f822911b0a11ba3d3498ba6a32e50dac7f32894dd890eb9ad578e4e292c83722 - a52e56a097e6a68b3f56f7a52ece0cdccba1eb62cad7d817f6dc58898b3ac15f36026fec - d568bd4a706cb60bb37be6d8f1240661199d640b66fb0fe3b079f97f450b9ef9c22c6d5d - dd379f0facd1cd020281dfa3c70ba21a3fa6fc2471dc6d13ecf8298b946f65345faa5ef0 - f1f8fff03ad0acb083725535636addb08d73dedb9832da198081e5deae84bfaf0409c22b - e4a8aea2b607ec96931e6f4d4fe563ba - -Reseal a trusted key under new pcr values: - - $ keyctl update 268728824 "update pcrinfo=`cat pcr.blob`" - $ keyctl print 268728824 - 010100000000002c0002800093c35a09b70fff26e7a98ae786c641e678ec6ffb6b46d805 - 77c8a6377aed9d3219c6dfec4b23ffe3000001005d37d472ac8a44023fbb3d18583a4f73 - d3a076c0858f6f1dcaa39ea0f119911ff03f5406df4f7f27f41da8d7194f45c9f4e00f2e - df449f266253aa3f52e55c53de147773e00f0f9aca86c64d94c95382265968c354c5eab4 - 9638c5ae99c89de1e0997242edfb0b501744e11ff9762dfd951cffd93227cc513384e7e6 - e782c29435c7ec2edafaa2f4c1fe6e7a781b59549ff5296371b42133777dcc5b8b971610 - 94bc67ede19e43ddb9dc2baacad374a36feaf0314d700af0a65c164b7082401740e489c9 - 7ef6a24defe4846104209bf0c3eced7fa1a672ed5b125fc9d8cd88b476a658a4434644ef - df8ae9a178e9f83ba9f08d10fa47e4226b98b0702f06b3b8 - -The initial consumer of trusted keys is EVM, which at boot time needs a high -quality symmetric key for HMAC protection of file metadata. The use of a -trusted key provides strong guarantees that the EVM key has not been -compromised by a user level problem, and when sealed to specific boot PCR -values, protects against boot and offline attacks. Create and save an -encrypted key "evm" using the above trusted key "kmk": - -option 1: omitting 'format' - $ keyctl add encrypted evm "new trusted:kmk 32" @u - 159771175 - -option 2: explicitly defining 'format' as 'default' - $ keyctl add encrypted evm "new default trusted:kmk 32" @u - 159771175 - - $ keyctl print 159771175 - default trusted:kmk 32 2375725ad57798846a9bbd240de8906f006e66c03af53b1b3 - 82dbbc55be2a44616e4959430436dc4f2a7a9659aa60bb4652aeb2120f149ed197c564e0 - 24717c64 5972dcb82ab2dde83376d82b2e3c09ffc - - $ keyctl pipe 159771175 > evm.blob - -Load an encrypted key "evm" from saved blob: - - $ keyctl add encrypted evm "load `cat evm.blob`" @u - 831684262 - - $ keyctl print 831684262 - default trusted:kmk 32 2375725ad57798846a9bbd240de8906f006e66c03af53b1b3 - 82dbbc55be2a44616e4959430436dc4f2a7a9659aa60bb4652aeb2120f149ed197c564e0 - 24717c64 5972dcb82ab2dde83376d82b2e3c09ffc - -Other uses for trusted and encrypted keys, such as for disk and file encryption -are anticipated. In particular the new format 'ecryptfs' has been defined in -in order to use encrypted keys to mount an eCryptfs filesystem. More details -about the usage can be found in the file -'Documentation/security/keys-ecryptfs.txt'. diff --git a/Documentation/security/keys/index.rst b/Documentation/security/keys/index.rst index d7ddbc1c2502..647d58f2588e 100644 --- a/Documentation/security/keys/index.rst +++ b/Documentation/security/keys/index.rst @@ -8,3 +8,4 @@ Kernel Keys core ecryptfs request-key + trusted-encrypted diff --git a/Documentation/security/keys/trusted-encrypted.rst b/Documentation/security/keys/trusted-encrypted.rst new file mode 100644 index 000000000000..7b503831bdea --- /dev/null +++ b/Documentation/security/keys/trusted-encrypted.rst @@ -0,0 +1,175 @@ +========================== +Trusted and Encrypted Keys +========================== + +Trusted and Encrypted Keys are two new key types added to the existing kernel +key ring service. Both of these new types are variable length symmetric keys, +and in both cases all keys are created in the kernel, and user space sees, +stores, and loads only encrypted blobs. Trusted Keys require the availability +of a Trusted Platform Module (TPM) chip for greater security, while Encrypted +Keys can be used on any system. All user level blobs, are displayed and loaded +in hex ascii for convenience, and are integrity verified. + +Trusted Keys use a TPM both to generate and to seal the keys. Keys are sealed +under a 2048 bit RSA key in the TPM, and optionally sealed to specified PCR +(integrity measurement) values, and only unsealed by the TPM, if PCRs and blob +integrity verifications match. A loaded Trusted Key can be updated with new +(future) PCR values, so keys are easily migrated to new pcr values, such as +when the kernel and initramfs are updated. The same key can have many saved +blobs under different PCR values, so multiple boots are easily supported. + +By default, trusted keys are sealed under the SRK, which has the default +authorization value (20 zeros). This can be set at takeownership time with the +trouser's utility: "tpm_takeownership -u -z". + +Usage:: + + keyctl add trusted name "new keylen [options]" ring + keyctl add trusted name "load hex_blob [pcrlock=pcrnum]" ring + keyctl update key "update [options]" + keyctl print keyid + + options: + keyhandle= ascii hex value of sealing key default 0x40000000 (SRK) + keyauth= ascii hex auth for sealing key default 0x00...i + (40 ascii zeros) + blobauth= ascii hex auth for sealed data default 0x00... + (40 ascii zeros) + pcrinfo= ascii hex of PCR_INFO or PCR_INFO_LONG (no default) + pcrlock= pcr number to be extended to "lock" blob + migratable= 0|1 indicating permission to reseal to new PCR values, + default 1 (resealing allowed) + hash= hash algorithm name as a string. For TPM 1.x the only + allowed value is sha1. For TPM 2.x the allowed values + are sha1, sha256, sha384, sha512 and sm3-256. + policydigest= digest for the authorization policy. must be calculated + with the same hash algorithm as specified by the 'hash=' + option. + policyhandle= handle to an authorization policy session that defines the + same policy and with the same hash algorithm as was used to + seal the key. + +"keyctl print" returns an ascii hex copy of the sealed key, which is in standard +TPM_STORED_DATA format. The key length for new keys are always in bytes. +Trusted Keys can be 32 - 128 bytes (256 - 1024 bits), the upper limit is to fit +within the 2048 bit SRK (RSA) keylength, with all necessary structure/padding. + +Encrypted keys do not depend on a TPM, and are faster, as they use AES for +encryption/decryption. New keys are created from kernel generated random +numbers, and are encrypted/decrypted using a specified 'master' key. The +'master' key can either be a trusted-key or user-key type. The main +disadvantage of encrypted keys is that if they are not rooted in a trusted key, +they are only as secure as the user key encrypting them. The master user key +should therefore be loaded in as secure a way as possible, preferably early in +boot. + +The decrypted portion of encrypted keys can contain either a simple symmetric +key or a more complex structure. The format of the more complex structure is +application specific, which is identified by 'format'. + +Usage:: + + keyctl add encrypted name "new [format] key-type:master-key-name keylen" + ring + keyctl add encrypted name "load hex_blob" ring + keyctl update keyid "update key-type:master-key-name" + +Where:: + + format:= 'default | ecryptfs' + key-type:= 'trusted' | 'user' + + +Examples of trusted and encrypted key usage: + +Create and save a trusted key named "kmk" of length 32 bytes:: + + $ keyctl add trusted kmk "new 32" @u + 440502848 + + $ keyctl show + Session Keyring + -3 --alswrv 500 500 keyring: _ses + 97833714 --alswrv 500 -1 \_ keyring: _uid.500 + 440502848 --alswrv 500 500 \_ trusted: kmk + + $ keyctl print 440502848 + 0101000000000000000001005d01b7e3f4a6be5709930f3b70a743cbb42e0cc95e18e915 + 3f60da455bbf1144ad12e4f92b452f966929f6105fd29ca28e4d4d5a031d068478bacb0b + 27351119f822911b0a11ba3d3498ba6a32e50dac7f32894dd890eb9ad578e4e292c83722 + a52e56a097e6a68b3f56f7a52ece0cdccba1eb62cad7d817f6dc58898b3ac15f36026fec + d568bd4a706cb60bb37be6d8f1240661199d640b66fb0fe3b079f97f450b9ef9c22c6d5d + dd379f0facd1cd020281dfa3c70ba21a3fa6fc2471dc6d13ecf8298b946f65345faa5ef0 + f1f8fff03ad0acb083725535636addb08d73dedb9832da198081e5deae84bfaf0409c22b + e4a8aea2b607ec96931e6f4d4fe563ba + + $ keyctl pipe 440502848 > kmk.blob + +Load a trusted key from the saved blob:: + + $ keyctl add trusted kmk "load `cat kmk.blob`" @u + 268728824 + + $ keyctl print 268728824 + 0101000000000000000001005d01b7e3f4a6be5709930f3b70a743cbb42e0cc95e18e915 + 3f60da455bbf1144ad12e4f92b452f966929f6105fd29ca28e4d4d5a031d068478bacb0b + 27351119f822911b0a11ba3d3498ba6a32e50dac7f32894dd890eb9ad578e4e292c83722 + a52e56a097e6a68b3f56f7a52ece0cdccba1eb62cad7d817f6dc58898b3ac15f36026fec + d568bd4a706cb60bb37be6d8f1240661199d640b66fb0fe3b079f97f450b9ef9c22c6d5d + dd379f0facd1cd020281dfa3c70ba21a3fa6fc2471dc6d13ecf8298b946f65345faa5ef0 + f1f8fff03ad0acb083725535636addb08d73dedb9832da198081e5deae84bfaf0409c22b + e4a8aea2b607ec96931e6f4d4fe563ba + +Reseal a trusted key under new pcr values:: + + $ keyctl update 268728824 "update pcrinfo=`cat pcr.blob`" + $ keyctl print 268728824 + 010100000000002c0002800093c35a09b70fff26e7a98ae786c641e678ec6ffb6b46d805 + 77c8a6377aed9d3219c6dfec4b23ffe3000001005d37d472ac8a44023fbb3d18583a4f73 + d3a076c0858f6f1dcaa39ea0f119911ff03f5406df4f7f27f41da8d7194f45c9f4e00f2e + df449f266253aa3f52e55c53de147773e00f0f9aca86c64d94c95382265968c354c5eab4 + 9638c5ae99c89de1e0997242edfb0b501744e11ff9762dfd951cffd93227cc513384e7e6 + e782c29435c7ec2edafaa2f4c1fe6e7a781b59549ff5296371b42133777dcc5b8b971610 + 94bc67ede19e43ddb9dc2baacad374a36feaf0314d700af0a65c164b7082401740e489c9 + 7ef6a24defe4846104209bf0c3eced7fa1a672ed5b125fc9d8cd88b476a658a4434644ef + df8ae9a178e9f83ba9f08d10fa47e4226b98b0702f06b3b8 + +The initial consumer of trusted keys is EVM, which at boot time needs a high +quality symmetric key for HMAC protection of file metadata. The use of a +trusted key provides strong guarantees that the EVM key has not been +compromised by a user level problem, and when sealed to specific boot PCR +values, protects against boot and offline attacks. Create and save an +encrypted key "evm" using the above trusted key "kmk": + +option 1: omitting 'format':: + + $ keyctl add encrypted evm "new trusted:kmk 32" @u + 159771175 + +option 2: explicitly defining 'format' as 'default':: + + $ keyctl add encrypted evm "new default trusted:kmk 32" @u + 159771175 + + $ keyctl print 159771175 + default trusted:kmk 32 2375725ad57798846a9bbd240de8906f006e66c03af53b1b3 + 82dbbc55be2a44616e4959430436dc4f2a7a9659aa60bb4652aeb2120f149ed197c564e0 + 24717c64 5972dcb82ab2dde83376d82b2e3c09ffc + + $ keyctl pipe 159771175 > evm.blob + +Load an encrypted key "evm" from saved blob:: + + $ keyctl add encrypted evm "load `cat evm.blob`" @u + 831684262 + + $ keyctl print 831684262 + default trusted:kmk 32 2375725ad57798846a9bbd240de8906f006e66c03af53b1b3 + 82dbbc55be2a44616e4959430436dc4f2a7a9659aa60bb4652aeb2120f149ed197c564e0 + 24717c64 5972dcb82ab2dde83376d82b2e3c09ffc + +Other uses for trusted and encrypted keys, such as for disk and file encryption +are anticipated. In particular the new format 'ecryptfs' has been defined in +in order to use encrypted keys to mount an eCryptfs filesystem. More details +about the usage can be found in the file +``Documentation/security/keys-ecryptfs.txt``. diff --git a/MAINTAINERS b/MAINTAINERS index 9f3b8b0cae5a..20f25e3b0667 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7356,7 +7356,7 @@ M: Mimi Zohar L: linux-security-module@vger.kernel.org L: keyrings@vger.kernel.org S: Supported -F: Documentation/security/keys-trusted-encrypted.txt +F: Documentation/security/keys/trusted-encrypted.rst F: include/keys/trusted-type.h F: security/keys/trusted.c F: security/keys/trusted.h @@ -7367,7 +7367,7 @@ M: David Safford L: linux-security-module@vger.kernel.org L: keyrings@vger.kernel.org S: Supported -F: Documentation/security/keys-trusted-encrypted.txt +F: Documentation/security/keys/trusted-encrypted.rst F: include/keys/encrypted-type.h F: security/keys/encrypted-keys/ diff --git a/security/keys/encrypted-keys/encrypted.c b/security/keys/encrypted-keys/encrypted.c index 0010955d7876..72ecbd0d1e37 100644 --- a/security/keys/encrypted-keys/encrypted.c +++ b/security/keys/encrypted-keys/encrypted.c @@ -11,7 +11,7 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2 of the License. * - * See Documentation/security/keys-trusted-encrypted.txt + * See Documentation/security/keys/trusted-encrypted.rst */ #include diff --git a/security/keys/encrypted-keys/masterkey_trusted.c b/security/keys/encrypted-keys/masterkey_trusted.c index b5b4812dbc87..cbf0bc127a73 100644 --- a/security/keys/encrypted-keys/masterkey_trusted.c +++ b/security/keys/encrypted-keys/masterkey_trusted.c @@ -11,7 +11,7 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2 of the License. * - * See Documentation/security/keys-trusted-encrypted.txt + * See Documentation/security/keys/trusted-encrypted.rst */ #include diff --git a/security/keys/trusted.c b/security/keys/trusted.c index 2ae31c5a87de..3811e75d280f 100644 --- a/security/keys/trusted.c +++ b/security/keys/trusted.c @@ -8,7 +8,7 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2 of the License. * - * See Documentation/security/keys-trusted-encrypted.txt + * See Documentation/security/keys/trusted-encrypted.rst */ #include -- cgit v1.2.3-59-g8ed1b From 52b3f239bb692d9b3a68461798fb15c011e4108e Mon Sep 17 00:00:00 2001 From: Jonathan Corbet Date: Fri, 23 Jun 2017 14:17:38 -0600 Subject: Docs: clean up some DocBook loose ends There were a few bits and pieces left over from the now-disused DocBook toolchain; git rid of them. Reported-by: Markus Heiser Signed-off-by: Jonathan Corbet --- Documentation/dontdiff | 1 - Documentation/sphinx/convert_template.sed | 18 - Documentation/sphinx/post_convert.sed | 23 - MAINTAINERS | 3 +- Makefile | 1 - scripts/.gitignore | 1 - scripts/Makefile | 7 +- scripts/docproc.c | 681 ------------------------------ scripts/kernel-doc-xml-ref | 198 --------- 9 files changed, 3 insertions(+), 930 deletions(-) delete mode 100644 Documentation/sphinx/convert_template.sed delete mode 100644 Documentation/sphinx/post_convert.sed delete mode 100644 scripts/docproc.c delete mode 100755 scripts/kernel-doc-xml-ref (limited to 'MAINTAINERS') diff --git a/Documentation/dontdiff b/Documentation/dontdiff index 77b92221f951..f64a63b233c3 100644 --- a/Documentation/dontdiff +++ b/Documentation/dontdiff @@ -118,7 +118,6 @@ defkeymap.c devlist.h* devicetable-offsets.h dnotify_test -docproc dslm dtc elf2ecoff diff --git a/Documentation/sphinx/convert_template.sed b/Documentation/sphinx/convert_template.sed deleted file mode 100644 index c1503fcca4ec..000000000000 --- a/Documentation/sphinx/convert_template.sed +++ /dev/null @@ -1,18 +0,0 @@ -# -# Pandoc doesn't grok or , so convert them -# ahead of time. -# -# Use the following escapes to pass through pandoc: -# $bq = "`" -# $lt = "<" -# $gt = ">" -# -s%\([^<(]\+\)()%:c:func:$bq\1()$bq%g -s%\([^<(]\+\)%:c:func:$bq\1()$bq%g -s%struct *\([^<]\+\)%:c:type:$bqstruct \1 $lt\1$gt$bq%g -s%struct \([^<]\+\)%:c:type:$bqstruct \1 $lt\1$gt$bq%g -s%\([^<]\+\)%:c:type:$bqstruct \1 $lt\1$gt$bq%g -# -# Wrap docproc directives in para and code blocks. -# -s%^\(!.*\)$%DOCPROC: \1% diff --git a/Documentation/sphinx/post_convert.sed b/Documentation/sphinx/post_convert.sed deleted file mode 100644 index 392770bac53b..000000000000 --- a/Documentation/sphinx/post_convert.sed +++ /dev/null @@ -1,23 +0,0 @@ -# -# Unescape. -# -s/$bq/`/g -s/$lt//g -# -# pandoc thinks that both "_" needs to be escaped. Remove the extra -# backslashes. -# -s/\\_/_/g -# -# Unwrap docproc directives. -# -s/^``DOCPROC: !E\(.*\)``$/.. kernel-doc:: \1\n :export:/ -s/^``DOCPROC: !I\(.*\)``$/.. kernel-doc:: \1\n :internal:/ -s/^``DOCPROC: !F\([^ ]*\) \(.*\)``$/.. kernel-doc:: \1\n :functions: \2/ -s/^``DOCPROC: !P\([^ ]*\) \(.*\)``$/.. kernel-doc:: \1\n :doc: \2/ -s/^``DOCPROC: \(!.*\)``$/.. WARNING: DOCPROC directive not supported: \1/ -# -# Trim trailing whitespace. -# -s/[[:space:]]*$// diff --git a/MAINTAINERS b/MAINTAINERS index 5df61e9757dc..12110616b2d2 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4135,8 +4135,7 @@ M: Jonathan Corbet L: linux-doc@vger.kernel.org S: Maintained F: Documentation/ -F: scripts/docproc.c -F: scripts/kernel-doc* +F: scripts/kernel-doc X: Documentation/ABI/ X: Documentation/devicetree/ X: Documentation/acpi diff --git a/Makefile b/Makefile index 855a48c41d61..dd1eb8d6c232 100644 --- a/Makefile +++ b/Makefile @@ -1467,7 +1467,6 @@ $(help-board-dirs): help-%: DOC_TARGETS := xmldocs sgmldocs psdocs latexdocs pdfdocs htmldocs mandocs installmandocs epubdocs cleandocs linkcheckdocs PHONY += $(DOC_TARGETS) $(DOC_TARGETS): scripts_basic FORCE - $(Q)$(MAKE) $(build)=scripts build_docproc $(Q)$(MAKE) $(build)=Documentation $@ else # KBUILD_EXTMOD diff --git a/scripts/.gitignore b/scripts/.gitignore index e063daa3ec4a..0442c06eefcb 100644 --- a/scripts/.gitignore +++ b/scripts/.gitignore @@ -7,7 +7,6 @@ pnmtologo unifdef ihex2fw recordmcount -docproc check-lc_ctype sortextable asn1_compiler diff --git a/scripts/Makefile b/scripts/Makefile index 55550e4141c4..c06f4997d700 100644 --- a/scripts/Makefile +++ b/scripts/Makefile @@ -6,7 +6,6 @@ # pnmttologo: Convert pnm files to logo files # conmakehash: Create chartable # conmakehash: Create arrays for initializing the kernel console tables -# docproc: Used in Documentation/ HOST_EXTRACFLAGS += -I$(srctree)/tools/include @@ -28,14 +27,12 @@ HOSTLOADLIBES_extract-cert = -lcrypto always := $(hostprogs-y) $(hostprogs-m) # The following hostprogs-y programs are only build on demand -hostprogs-y += unifdef docproc +hostprogs-y += unifdef # These targets are used internally to avoid "is up to date" messages -PHONY += build_unifdef build_docproc +PHONY += build_unifdef build_unifdef: $(obj)/unifdef @: -build_docproc: $(obj)/docproc - @: subdir-$(CONFIG_MODVERSIONS) += genksyms subdir-y += mod diff --git a/scripts/docproc.c b/scripts/docproc.c deleted file mode 100644 index 0a12593b9041..000000000000 --- a/scripts/docproc.c +++ /dev/null @@ -1,681 +0,0 @@ -/* - * docproc is a simple preprocessor for the template files - * used as placeholders for the kernel internal documentation. - * docproc is used for documentation-frontend and - * dependency-generator. - * The two usages have in common that they require - * some knowledge of the .tmpl syntax, therefore they - * are kept together. - * - * documentation-frontend - * Scans the template file and call kernel-doc for - * all occurrences of ![EIF]file - * Beforehand each referenced file is scanned for - * any symbols that are exported via these macros: - * EXPORT_SYMBOL(), EXPORT_SYMBOL_GPL(), & - * EXPORT_SYMBOL_GPL_FUTURE() - * This is used to create proper -function and - * -nofunction arguments in calls to kernel-doc. - * Usage: docproc doc file.tmpl - * - * dependency-generator: - * Scans the template file and list all files - * referenced in a format recognized by make. - * Usage: docproc depend file.tmpl - * Writes dependency information to stdout - * in the following format: - * file.tmpl src.c src2.c - * The filenames are obtained from the following constructs: - * !Efilename - * !Ifilename - * !Dfilename - * !Ffilename - * !Pfilename - * - */ - -#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* exitstatus is used to keep track of any failing calls to kernel-doc, - * but execution continues. */ -int exitstatus = 0; - -typedef void DFL(char *); -DFL *defaultline; - -typedef void FILEONLY(char * file); -FILEONLY *internalfunctions; -FILEONLY *externalfunctions; -FILEONLY *symbolsonly; -FILEONLY *findall; - -typedef void FILELINE(char * file, char * line); -FILELINE * singlefunctions; -FILELINE * entity_system; -FILELINE * docsection; - -#define MAXLINESZ 2048 -#define MAXFILES 250 -#define KERNELDOCPATH "scripts/" -#define KERNELDOC "kernel-doc" -#define DOCBOOK "-docbook" -#define RST "-rst" -#define LIST "-list" -#define FUNCTION "-function" -#define NOFUNCTION "-nofunction" -#define NODOCSECTIONS "-no-doc-sections" -#define SHOWNOTFOUND "-show-not-found" - -enum file_format { - FORMAT_AUTO, - FORMAT_DOCBOOK, - FORMAT_RST, -}; - -static enum file_format file_format = FORMAT_AUTO; - -#define KERNELDOC_FORMAT (file_format == FORMAT_RST ? RST : DOCBOOK) - -static char *srctree, *kernsrctree; - -static char **all_list = NULL; -static int all_list_len = 0; - -static void consume_symbol(const char *sym) -{ - int i; - - for (i = 0; i < all_list_len; i++) { - if (!all_list[i]) - continue; - if (strcmp(sym, all_list[i])) - continue; - all_list[i] = NULL; - break; - } -} - -static void usage (void) -{ - fprintf(stderr, "Usage: docproc [{--docbook|--rst}] {doc|depend} file\n"); - fprintf(stderr, "Input is read from file.tmpl. Output is sent to stdout\n"); - fprintf(stderr, "doc: frontend when generating kernel documentation\n"); - fprintf(stderr, "depend: generate list of files referenced within file\n"); - fprintf(stderr, "Environment variable SRCTREE: absolute path to sources.\n"); - fprintf(stderr, " KBUILD_SRC: absolute path to kernel source tree.\n"); -} - -/* - * Execute kernel-doc with parameters given in svec - */ -static void exec_kernel_doc(char **svec) -{ - pid_t pid; - int ret; - char real_filename[PATH_MAX + 1]; - /* Make sure output generated so far are flushed */ - fflush(stdout); - switch (pid=fork()) { - case -1: - perror("fork"); - exit(1); - case 0: - memset(real_filename, 0, sizeof(real_filename)); - strncat(real_filename, kernsrctree, PATH_MAX); - strncat(real_filename, "/" KERNELDOCPATH KERNELDOC, - PATH_MAX - strlen(real_filename)); - execvp(real_filename, svec); - fprintf(stderr, "exec "); - perror(real_filename); - exit(1); - default: - waitpid(pid, &ret ,0); - } - if (WIFEXITED(ret)) - exitstatus |= WEXITSTATUS(ret); - else - exitstatus = 0xff; -} - -/* Types used to create list of all exported symbols in a number of files */ -struct symbols -{ - char *name; -}; - -struct symfile -{ - char *filename; - struct symbols *symbollist; - int symbolcnt; -}; - -struct symfile symfilelist[MAXFILES]; -int symfilecnt = 0; - -static void add_new_symbol(struct symfile *sym, char * symname) -{ - sym->symbollist = - realloc(sym->symbollist, (sym->symbolcnt + 1) * sizeof(char *)); - sym->symbollist[sym->symbolcnt++].name = strdup(symname); -} - -/* Add a filename to the list */ -static struct symfile * add_new_file(char * filename) -{ - symfilelist[symfilecnt++].filename = strdup(filename); - return &symfilelist[symfilecnt - 1]; -} - -/* Check if file already are present in the list */ -static struct symfile * filename_exist(char * filename) -{ - int i; - for (i=0; i < symfilecnt; i++) - if (strcmp(symfilelist[i].filename, filename) == 0) - return &symfilelist[i]; - return NULL; -} - -/* - * List all files referenced within the template file. - * Files are separated by tabs. - */ -static void adddep(char * file) { printf("\t%s", file); } -static void adddep2(char * file, char * line) { line = line; adddep(file); } -static void noaction(char * line) { line = line; } -static void noaction2(char * file, char * line) { file = file; line = line; } - -/* Echo the line without further action */ -static void printline(char * line) { printf("%s", line); } - -/* - * Find all symbols in filename that are exported with EXPORT_SYMBOL & - * EXPORT_SYMBOL_GPL (& EXPORT_SYMBOL_GPL_FUTURE implicitly). - * All symbols located are stored in symfilelist. - */ -static void find_export_symbols(char * filename) -{ - FILE * fp; - struct symfile *sym; - char line[MAXLINESZ]; - if (filename_exist(filename) == NULL) { - char real_filename[PATH_MAX + 1]; - memset(real_filename, 0, sizeof(real_filename)); - strncat(real_filename, srctree, PATH_MAX); - strncat(real_filename, "/", PATH_MAX - strlen(real_filename)); - strncat(real_filename, filename, - PATH_MAX - strlen(real_filename)); - sym = add_new_file(filename); - fp = fopen(real_filename, "r"); - if (fp == NULL) { - fprintf(stderr, "docproc: "); - perror(real_filename); - exit(1); - } - while (fgets(line, MAXLINESZ, fp)) { - char *p; - char *e; - if (((p = strstr(line, "EXPORT_SYMBOL_GPL")) != NULL) || - ((p = strstr(line, "EXPORT_SYMBOL")) != NULL)) { - /* Skip EXPORT_SYMBOL{_GPL} */ - while (isalnum(*p) || *p == '_') - p++; - /* Remove parentheses & additional whitespace */ - while (isspace(*p)) - p++; - if (*p != '(') - continue; /* Syntax error? */ - else - p++; - while (isspace(*p)) - p++; - e = p; - while (isalnum(*e) || *e == '_') - e++; - *e = '\0'; - add_new_symbol(sym, p); - } - } - fclose(fp); - } -} - -/* - * Document all external or internal functions in a file. - * Call kernel-doc with following parameters: - * kernel-doc [-docbook|-rst] -nofunction function_name1 filename - * Function names are obtained from all the src files - * by find_export_symbols. - * intfunc uses -nofunction - * extfunc uses -function - */ -static void docfunctions(char * filename, char * type) -{ - int i,j; - int symcnt = 0; - int idx = 0; - char **vec; - - for (i=0; i <= symfilecnt; i++) - symcnt += symfilelist[i].symbolcnt; - vec = malloc((2 + 2 * symcnt + 3) * sizeof(char *)); - if (vec == NULL) { - perror("docproc: "); - exit(1); - } - vec[idx++] = KERNELDOC; - vec[idx++] = KERNELDOC_FORMAT; - vec[idx++] = NODOCSECTIONS; - for (i=0; i < symfilecnt; i++) { - struct symfile * sym = &symfilelist[i]; - for (j=0; j < sym->symbolcnt; j++) { - vec[idx++] = type; - consume_symbol(sym->symbollist[j].name); - vec[idx++] = sym->symbollist[j].name; - } - } - vec[idx++] = filename; - vec[idx] = NULL; - if (file_format == FORMAT_RST) - printf(".. %s\n", filename); - else - printf("\n", filename); - exec_kernel_doc(vec); - fflush(stdout); - free(vec); -} -static void intfunc(char * filename) { docfunctions(filename, NOFUNCTION); } -static void extfunc(char * filename) { docfunctions(filename, FUNCTION); } - -/* - * Document specific function(s) in a file. - * Call kernel-doc with the following parameters: - * kernel-doc -docbook -function function1 [-function function2] - */ -static void singfunc(char * filename, char * line) -{ - char *vec[200]; /* Enough for specific functions */ - int i, idx = 0; - int startofsym = 1; - vec[idx++] = KERNELDOC; - vec[idx++] = KERNELDOC_FORMAT; - vec[idx++] = SHOWNOTFOUND; - - /* Split line up in individual parameters preceded by FUNCTION */ - for (i=0; line[i]; i++) { - if (isspace(line[i])) { - line[i] = '\0'; - startofsym = 1; - continue; - } - if (startofsym) { - startofsym = 0; - vec[idx++] = FUNCTION; - vec[idx++] = &line[i]; - } - } - for (i = 0; i < idx; i++) { - if (strcmp(vec[i], FUNCTION)) - continue; - consume_symbol(vec[i + 1]); - } - vec[idx++] = filename; - vec[idx] = NULL; - exec_kernel_doc(vec); -} - -/* - * Insert specific documentation section from a file. - * Call kernel-doc with the following parameters: - * kernel-doc -docbook -function "doc section" filename - */ -static void docsect(char *filename, char *line) -{ - /* kerneldoc -docbook -show-not-found -function "section" file NULL */ - char *vec[7]; - char *s; - - for (s = line; *s; s++) - if (*s == '\n') - *s = '\0'; - - if (asprintf(&s, "DOC: %s", line) < 0) { - perror("asprintf"); - exit(1); - } - consume_symbol(s); - free(s); - - vec[0] = KERNELDOC; - vec[1] = KERNELDOC_FORMAT; - vec[2] = SHOWNOTFOUND; - vec[3] = FUNCTION; - vec[4] = line; - vec[5] = filename; - vec[6] = NULL; - exec_kernel_doc(vec); -} - -static void find_all_symbols(char *filename) -{ - char *vec[4]; /* kerneldoc -list file NULL */ - pid_t pid; - int ret, i, count, start; - char real_filename[PATH_MAX + 1]; - int pipefd[2]; - char *data, *str; - size_t data_len = 0; - - vec[0] = KERNELDOC; - vec[1] = LIST; - vec[2] = filename; - vec[3] = NULL; - - if (pipe(pipefd)) { - perror("pipe"); - exit(1); - } - - switch (pid=fork()) { - case -1: - perror("fork"); - exit(1); - case 0: - close(pipefd[0]); - dup2(pipefd[1], 1); - memset(real_filename, 0, sizeof(real_filename)); - strncat(real_filename, kernsrctree, PATH_MAX); - strncat(real_filename, "/" KERNELDOCPATH KERNELDOC, - PATH_MAX - strlen(real_filename)); - execvp(real_filename, vec); - fprintf(stderr, "exec "); - perror(real_filename); - exit(1); - default: - close(pipefd[1]); - data = malloc(4096); - do { - while ((ret = read(pipefd[0], - data + data_len, - 4096)) > 0) { - data_len += ret; - data = realloc(data, data_len + 4096); - } - } while (ret == -EAGAIN); - if (ret != 0) { - perror("read"); - exit(1); - } - waitpid(pid, &ret ,0); - } - if (WIFEXITED(ret)) - exitstatus |= WEXITSTATUS(ret); - else - exitstatus = 0xff; - - count = 0; - /* poor man's strtok, but with counting */ - for (i = 0; i < data_len; i++) { - if (data[i] == '\n') { - count++; - data[i] = '\0'; - } - } - start = all_list_len; - all_list_len += count; - all_list = realloc(all_list, sizeof(char *) * all_list_len); - str = data; - for (i = 0; i < data_len && start != all_list_len; i++) { - if (data[i] == '\0') { - all_list[start] = str; - str = data + i + 1; - start++; - } - } -} - -/* - * Terminate s at first space, if any. If there was a space, return pointer to - * the character after that. Otherwise, return pointer to the terminating NUL. - */ -static char *chomp(char *s) -{ - while (*s && !isspace(*s)) - s++; - - if (*s) - *s++ = '\0'; - - return s; -} - -/* Return pointer to directive content, or NULL if not a directive. */ -static char *is_directive(char *line) -{ - if (file_format == FORMAT_DOCBOOK && line[0] == '!') - return line + 1; - else if (file_format == FORMAT_RST && !strncmp(line, ".. !", 4)) - return line + 4; - - return NULL; -} - -/* - * Parse file, calling action specific functions for: - * 1) Lines containing !E - * 2) Lines containing !I - * 3) Lines containing !D - * 4) Lines containing !F - * 5) Lines containing !P - * 6) Lines containing !C - * 7) Default lines - lines not matching the above - */ -static void parse_file(FILE *infile) -{ - char line[MAXLINESZ]; - char *p, *s; - while (fgets(line, MAXLINESZ, infile)) { - p = is_directive(line); - if (!p) { - defaultline(line); - continue; - } - - switch (*p++) { - case 'E': - chomp(p); - externalfunctions(p); - break; - case 'I': - chomp(p); - internalfunctions(p); - break; - case 'D': - chomp(p); - symbolsonly(p); - break; - case 'F': - /* filename */ - s = chomp(p); - /* function names */ - while (isspace(*s)) - s++; - singlefunctions(p, s); - break; - case 'P': - /* filename */ - s = chomp(p); - /* DOC: section name */ - while (isspace(*s)) - s++; - docsection(p, s); - break; - case 'C': - chomp(p); - if (findall) - findall(p); - break; - default: - defaultline(line); - } - } - fflush(stdout); -} - -/* - * Is this a RestructuredText template? Answer the question by seeing if its - * name ends in ".rst". - */ -static int is_rst(const char *file) -{ - char *dot = strrchr(file, '.'); - - return dot && !strcmp(dot + 1, "rst"); -} - -enum opts { - OPT_DOCBOOK, - OPT_RST, - OPT_HELP, -}; - -int main(int argc, char *argv[]) -{ - const char *subcommand, *filename; - FILE * infile; - int i; - - srctree = getenv("SRCTREE"); - if (!srctree) - srctree = getcwd(NULL, 0); - kernsrctree = getenv("KBUILD_SRC"); - if (!kernsrctree || !*kernsrctree) - kernsrctree = srctree; - - for (;;) { - int c; - struct option opts[] = { - { "docbook", no_argument, NULL, OPT_DOCBOOK }, - { "rst", no_argument, NULL, OPT_RST }, - { "help", no_argument, NULL, OPT_HELP }, - {} - }; - - c = getopt_long_only(argc, argv, "", opts, NULL); - if (c == -1) - break; - - switch (c) { - case OPT_DOCBOOK: - file_format = FORMAT_DOCBOOK; - break; - case OPT_RST: - file_format = FORMAT_RST; - break; - case OPT_HELP: - usage(); - return 0; - default: - case '?': - usage(); - return 1; - } - } - - argc -= optind; - argv += optind; - - if (argc != 2) { - usage(); - exit(1); - } - - subcommand = argv[0]; - filename = argv[1]; - - if (file_format == FORMAT_AUTO) - file_format = is_rst(filename) ? FORMAT_RST : FORMAT_DOCBOOK; - - /* Open file, exit on error */ - infile = fopen(filename, "r"); - if (infile == NULL) { - fprintf(stderr, "docproc: "); - perror(filename); - exit(2); - } - - if (strcmp("doc", subcommand) == 0) { - if (file_format == FORMAT_RST) { - time_t t = time(NULL); - printf(".. generated from %s by docproc %s\n", - filename, ctime(&t)); - } - - /* Need to do this in two passes. - * First pass is used to collect all symbols exported - * in the various files; - * Second pass generate the documentation. - * This is required because some functions are declared - * and exported in different files :-(( - */ - /* Collect symbols */ - defaultline = noaction; - internalfunctions = find_export_symbols; - externalfunctions = find_export_symbols; - symbolsonly = find_export_symbols; - singlefunctions = noaction2; - docsection = noaction2; - findall = find_all_symbols; - parse_file(infile); - - /* Rewind to start from beginning of file again */ - fseek(infile, 0, SEEK_SET); - defaultline = printline; - internalfunctions = intfunc; - externalfunctions = extfunc; - symbolsonly = printline; - singlefunctions = singfunc; - docsection = docsect; - findall = NULL; - - parse_file(infile); - - for (i = 0; i < all_list_len; i++) { - if (!all_list[i]) - continue; - fprintf(stderr, "Warning: didn't use docs for %s\n", - all_list[i]); - } - } else if (strcmp("depend", subcommand) == 0) { - /* Create first part of dependency chain - * file.tmpl */ - printf("%s\t", filename); - defaultline = noaction; - internalfunctions = adddep; - externalfunctions = adddep; - symbolsonly = adddep; - singlefunctions = adddep2; - docsection = adddep2; - findall = adddep; - parse_file(infile); - printf("\n"); - } else { - fprintf(stderr, "Unknown option: %s\n", subcommand); - exit(1); - } - fclose(infile); - fflush(stdout); - return exitstatus; -} diff --git a/scripts/kernel-doc-xml-ref b/scripts/kernel-doc-xml-ref deleted file mode 100755 index 104a5a5ba2c8..000000000000 --- a/scripts/kernel-doc-xml-ref +++ /dev/null @@ -1,198 +0,0 @@ -#!/usr/bin/perl -w - -use strict; - -## Copyright (C) 2015 Intel Corporation ## -# ## -## This software falls under the GNU General Public License. ## -## Please read the COPYING file for more information ## -# -# -# This software reads a XML file and a list of valid interal -# references to replace Docbook tags with links. -# -# The list of "valid internal references" must be one-per-line in the following format: -# API-struct-foo -# API-enum-bar -# API-my-function -# -# The software walks over the XML file looking for xml tags representing possible references -# to the Document. Each reference will be cross checked against the "Valid Internal Reference" list. If -# the referece is found it replaces its content by a tag. -# -# usage: -# kernel-doc-xml-ref -db filename -# xml filename > outputfile - -# read arguments -if ($#ARGV != 2) { - usage(); -} - -#Holds the database filename -my $databasefile; -my @database; - -#holds the inputfile -my $inputfile; -my $errors = 0; - -my %highlights = ( - "(.*?)", - "\"\" . convert_function(\$1, \$line) . \"\"", - "(.*?)", - "\"\" . convert_struct(\$1) . \"\"", - "(.*?)(.*?)", - "\"\" . convert_param(\$1) . \"\$2\"", - "(.*?)(.*?)", - "\"\" . convert_param(\$1) . \"\$2\""); - -while($ARGV[0] =~ m/^-(.*)/) { - my $cmd = shift @ARGV; - if ($cmd eq "-db") { - $databasefile = shift @ARGV - } else { - usage(); - } -} -$inputfile = shift @ARGV; - -sub open_database { - open (my $handle, '<', $databasefile) or die "Cannot open $databasefile"; - chomp(my @lines = <$handle>); - close $handle; - - @database = @lines; -} - -sub process_file { - open_database(); - - my $dohighlight; - foreach my $pattern (keys %highlights) { - $dohighlight .= "\$line =~ s:$pattern:$highlights{$pattern}:eg;\n"; - } - - open(FILE, $inputfile) or die("Could not open $inputfile") or die ("Cannot open $inputfile"); - foreach my $line () { - eval $dohighlight; - print $line; - } -} - -sub trim($_) -{ - my $str = $_[0]; - $str =~ s/^\s+|\s+$//g; - return $str -} - -sub has_key_defined($_) -{ - if ( grep( /^$_[0]$/, @database)) { - return 1; - } - return 0; -} - -# Gets a content and add it a hyperlink if possible. -sub convert_function($_) -{ - my $arg = $_[0]; - my $key = $_[0]; - - my $line = $_[1]; - - $key = trim($key); - - $key =~ s/[^A-Za-z0-9]/-/g; - $key = "API-" . $key; - - # We shouldn't add links to prototype - if (!has_key_defined($key) || $line =~ m/\s+$head$tail"; -} - -# Converting a struct text to link -sub convert_struct($_) -{ - my $arg = $_[0]; - my $key = $_[0]; - $key =~ s/(struct )?(\w)/$2/g; - $key =~ s/[^A-Za-z0-9]/-/g; - $key = "API-struct-" . $key; - - if (!has_key_defined($key)) { - return $arg; - } - - my ($head, $tail) = split_pointer($arg); - return "$head$tail"; -} - -# Identify "object *" elements -sub split_pointer($_) -{ - my $arg = $_[0]; - if ($arg =~ /(.*?)( ?\* ?)/) { - return ($1, $2); - } - return ($arg, ""); -} - -sub convert_param($_) -{ - my $type = $_[0]; - my $keyname = convert_key_name($type); - - if (!has_key_defined($keyname)) { - return $type; - } - - my ($head, $tail) = split_pointer($type); - return "$head$tail"; - -} - -# DocBook links are in the API-- format -# This method gets an element and returns a valid DocBook reference for it. -sub convert_key_name($_) -{ - #Pattern $2 is optional and might be uninitialized - no warnings 'uninitialized'; - - my $str = $_[0]; - $str =~ s/(const|static)? ?(struct)? ?([a-zA-Z0-9_]+) ?(\*|&)?/$2 $3/g ; - - # trim - $str =~ s/^\s+|\s+$//g; - - # spaces and _ to - - $str =~ s/[^A-Za-z0-9]/-/g; - - return "API-" . $str; -} - -sub usage { - print "Usage: $0 -db database filename\n"; - print " xml source file(s) > outputfile\n"; - exit 1; -} - -# starting point -process_file(); - -if ($errors) { - print STDERR "$errors errors\n"; -} - -exit($errors); -- cgit v1.2.3-59-g8ed1b