code:
==========================
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 Trust Source 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.

Trust Source
============

A trust source provides the source of security for Trusted Keys.  This
section lists currently supported trust sources, along with their security
considerations.  Whether or not a trust source is sufficiently safe depends
on the strength and correctness of its implementation, as well as the threat
environment for a specific use case.  Since the kernel doesn't know what the
environment is, and there is no metric of trust, it is dependent on the
consumer of the Trusted Keys to determine if the trust source is sufficiently
safe.

  *  Root of trust for storage

     (1) TPM (Trusted Platform Module: hardware device)

         Rooted to Storage Root Key (SRK) which never leaves the TPM that
         provides crypto operation to establish root of trust for storage.

     (2) TEE (Trusted Execution Environment: OP-TEE based on Arm TrustZone)

         Rooted to Hardware Unique Key (HUK) which is generally burnt in on-chip
         fuses and is accessible to TEE only.

     (3) CAAM (Cryptographic Acceleration and Assurance Module: IP on NXP SoCs)

         When High Assurance Boot (HAB) is enabled and the CAAM is in secure
         mode, trust is rooted to the OTPMK, a never-disclosed 256-bit key
         randomly generated and fused into each SoC at manufacturing time.
         Otherwise, a common fixed test key is used instead.

  *  Execution isolation

     (1) TPM

         Fixed set of operations running in isolated execution environment.

     (2) TEE

         Customizable set of operations running in isolated execution
         environment verified via Secure/Trusted boot process.

     (3) CAAM

         Fixed set of operations running in isolated execution environment.

  * Optional binding to platform integrity state

     (1) TPM

         Keys can be 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.

     (2) TEE

         Relies on Secure/Trusted boot process for platform integrity. It can
         be extended with TEE based measured boot process.

     (3) CAAM

         Relies on the High Assurance Boot (HAB) mechanism of NXP SoCs
         for platform integrity.

  *  Interfaces and APIs

     (1) TPM

         TPMs have well-documented, standardized interfaces and APIs.

     (2) TEE

         TEEs have well-documented, standardized client interface and APIs. For
         more details refer to ``Documentation/staging/tee.rst``.

     (3) CAAM

         Interface is specific to silicon vendor.

  *  Threat model

     The strength and appropriateness of a particular trust source for a given
     purpose must be assessed when using them to protect security-relevant data.

Key Generation
==============

Trusted Keys
------------

New keys are created from random numbers. They are encrypted/decrypted using
a child key in the storage key hierarchy. Encryption and decryption of the
child key must be protected by a strong access control policy within the
trust source. The random number generator in use differs according to the
selected trust source:

  *  TPM: hardware device based RNG

     Keys are generated within the TPM. Strength of random numbers may vary
     from one device manufacturer to another.

  *  TEE: OP-TEE based on Arm TrustZone based RNG

     RNG is customizable as per platform needs. It can either be direct output
     from platform specific hardware RNG or a software based Fortuna CSPRNG
     which can be seeded via multiple entropy sources.

  *  CAAM: Kernel RNG

     The normal kernel random number generator is used. To seed it from the
     CAAM HWRNG, enable CRYPTO_DEV_FSL_CAAM_RNG_API and ensure the device
     is probed.

Users may override this by specifying ``trusted.rng=kernel`` on the kernel
command-line to override the used RNG with the kernel's random number pool.

Encrypted Keys
--------------

Encrypted keys do not depend on a trust source, and are faster, as they use AES
for encryption/decryption. New keys are created either from kernel-generated
random numbers or user-provided decrypted data, 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.

Usage
=====

Trusted Keys usage: TPM
-----------------------

TPM 1.2: By default, trusted keys are sealed under the SRK, which has the
default authorization value (20 bytes of 0s).  This can be set at takeownership
time with the TrouSerS utility: "tpm_takeownership -u -z".

TPM 2.0: The user must first create a storage key and make it persistent, so the
key is available after reboot. This can be done using the following commands.

With the IBM TSS 2 stack::

  #> tsscreateprimary -hi o -st
  Handle 80000000
  #> tssevictcontrol -hi o -ho 80000000 -hp 81000001

Or with the Intel TSS 2 stack::

  #> tpm2_createprimary --hierarchy o -G rsa2048 -c key.ctxt
  [...]
  #> tpm2_evictcontrol -c key.ctxt 0x81000001
  persistentHandle: 0x81000001

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
                       TPM 1.2: default 0x40000000 (SRK)
                       TPM 2.0: no default; must be passed every time
       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.

Trusted Keys usage: TEE
-----------------------

Usage::

    keyctl add trusted name "new keylen" ring
    keyctl add trusted name "load hex_blob" ring
    keyctl print keyid

"keyctl print" returns an ASCII hex copy of the sealed key, which is in format
specific to TEE device implementation.  The key length for new keys is always
in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).

Trusted Keys usage: CAAM
------------------------

Usage::

    keyctl add trusted name "new keylen" ring
    keyctl add trusted name "load hex_blob" ring
    keyctl print keyid

"keyctl print" returns an ASCII hex copy of the sealed key, which is in a
CAAM-specific format.  The key length for new keys is always in bytes.
Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).

Encrypted Keys usage
--------------------

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 "new [format] key-type:master-key-name keylen
        decrypted-data" ring
    keyctl add encrypted name "load hex_blob" ring
    keyctl update keyid "update key-type:master-key-name"

Where::

	format:= 'default | ecryptfs | enc32'
	key-type:= 'trusted' | 'user'

Examples of trusted and encrypted key usage
-------------------------------------------

Create and save a trusted key named "kmk" of length 32 bytes.

Note: When using a TPM 2.0 with a persistent key with handle 0x81000001,
append 'keyhandle=0x81000001' to statements between quotes, such as
"new 32 keyhandle=0x81000001".

::

    $ 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 (TPM specific) 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 a platform integrity
state, 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

Instantiate an encrypted key "evm" using user-provided decrypted data::

    $ evmkey=$(dd if=/dev/urandom bs=1 count=32 | xxd -c32 -p)
    $ keyctl add encrypted evm "new default user:kmk 32 $evmkey" @u
    794890253

    $ keyctl print 794890253
    default user:kmk 32 2375725ad57798846a9bbd240de8906f006e66c03af53b1b382d
    bbc55be2a44616e4959430436dc4f2a7a9659aa60bb4652aeb2120f149ed197c564e0247
    17c64 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 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.rst``.

Another new format 'enc32' has been defined in order to support encrypted keys
with payload size of 32 bytes. This will initially be used for nvdimm security
but may expand to other usages that require 32 bytes payload.

TPM 2.0 ASN.1 Key Format
------------------------

The TPM 2.0 ASN.1 key format is designed to be easily recognisable,
even in binary form (fixing a problem we had with the TPM 1.2 ASN.1
format) and to be extensible for additions like importable keys and
policy::

    TPMKey ::= SEQUENCE {
        type		OBJECT IDENTIFIER
        emptyAuth	[0] EXPLICIT BOOLEAN OPTIONAL
        parent		INTEGER
        pubkey		OCTET STRING
        privkey		OCTET STRING
    }

type is what distinguishes the key even in binary form since the OID
is provided by the TCG to be unique and thus forms a recognizable
binary pattern at offset 3 in the key.  The OIDs currently made
available are::

    2.23.133.10.1.3 TPM Loadable key.  This is an asymmetric key (Usually
                    RSA2048 or Elliptic Curve) which can be imported by a
                    TPM2_Load() operation.

    2.23.133.10.1.4 TPM Importable Key.  This is an asymmetric key (Usually
                    RSA2048 or Elliptic Curve) which can be imported by a
                    TPM2_Import() operation.

    2.23.133.10.1.5 TPM Sealed Data.  This is a set of data (up to 128
                    bytes) which is sealed by the TPM.  It usually
                    represents a symmetric key and must be unsealed before
                    use.

The trusted key code only uses the TPM Sealed Data OID.

emptyAuth is true if the key has well known authorization "".  If it
is false or not present, the key requires an explicit authorization
phrase.  This is used by most user space consumers to decide whether
to prompt for a password.

parent represents the parent key handle, either in the 0x81 MSO space,
like 0x81000001 for the RSA primary storage key.  Userspace programmes
also support specifying the primary handle in the 0x40 MSO space.  If
this happens the Elliptic Curve variant of the primary key using the
TCG defined template will be generated on the fly into a volatile
object and used as the parent.  The current kernel code only supports
the 0x81 MSO form.

pubkey is the binary representation of TPM2B_PRIVATE excluding the
initial TPM2B header, which can be reconstructed from the ASN.1 octet
string length.

privkey is the binary representation of TPM2B_PUBLIC excluding the
initial TPM2B header which can be reconstructed from the ASN.1 octed
string length.


code:
.. SPDX-License-Identifier: GPL-2.0
.. Copyright © 2017-2020 Mickaël Salaün <mic@digikod.net>
.. Copyright © 2019-2020 ANSSI

==================================
Landlock LSM: kernel documentation
==================================

:Author: Mickaël Salaün
:Date: September 2022

Landlock's goal is to create scoped access-control (i.e. sandboxing).  To
harden a whole system, this feature should be available to any process,
including unprivileged ones.  Because such process may be compromised or
backdoored (i.e. untrusted), Landlock's features must be safe to use from the
kernel and other processes point of view.  Landlock's interface must therefore
expose a minimal attack surface.

Landlock is designed to be usable by unprivileged processes while following the
system security policy enforced by other access control mechanisms (e.g. DAC,
LSM).  Indeed, a Landlock rule shall not interfere with other access-controls
enforced on the system, only add more restrictions.

Any user can enforce Landlock rulesets on their processes.  They are merged and
evaluated according to the inherited ones in a way that ensures that only more
constraints can be added.

User space documentation can be found here:
Documentation/userspace-api/landlock.rst.

Guiding principles for safe access controls
===========================================

* A Landlock rule shall be focused on access control on kernel objects instead
  of syscall filtering (i.e. syscall arguments), which is the purpose of
  seccomp-bpf.
* To avoid multiple kinds of side-channel attacks (e.g. leak of security
  policies, CPU-based attacks), Landlock rules shall not be able to
  programmatically communicate with user space.
* Kernel access check shall not slow down access request from unsandboxed
  processes.
* Computation related to Landlock operations (e.g. enforcing a ruleset) shall
  only impact the processes requesting them.

Design choices
==============

Filesystem access rights
------------------------

All access rights are tied to an inode and what can be accessed through it.
Reading the content of a directory does not imply to be allowed to read the
content of a listed inode.  Indeed, a file name is local to its parent
directory, and an inode can be referenced by multiple file names thanks to
(hard) links.  Being able to unlink a file only has a direct impact on the
directory, not the unlinked inode.  This is the reason why
``LANDLOCK_ACCESS_FS_REMOVE_FILE`` or ``LANDLOCK_ACCESS_FS_REFER`` are not
allowed to be tied to files but only to directories.

Tests
=====

Userspace tests for backward compatibility, ptrace restrictions and filesystem
support can be found here: `tools/testing/selftests/landlock/`_.

Kernel structures
=================

Object
------

.. kernel-doc:: security/landlock/object.h
    :identifiers:

Filesystem
----------

.. kernel-doc:: security/landlock/fs.h
    :identifiers:

Ruleset and domain
------------------

A domain is a read-only ruleset tied to a set of subjects (i.e. tasks'
credentials).  Each time a ruleset is enforced on a task, the current domain is
duplicated and the ruleset is imported as a new layer of rules in the new
domain.  Indeed, once in a domain, each rule is tied to a layer level.  To
grant access to an object, at least one rule of each layer must allow the
requested action on the object.  A task can then only transit to a new domain
that is the intersection of the constraints from the current domain and those
of a ruleset provided by the task.

The definition of a subject is implicit for a task sandboxing itself, which
makes the reasoning much easier and helps avoid pitfalls.

.. kernel-doc:: security/landlock/ruleset.h
    :identifiers:

.. Links
.. _tools/testing/selftests/landlock/:
   https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/landlock/

repo_name: angery/linux


code:
=================================
Linux Security Module Development
=================================

Based on https://lore.kernel.org/r/20071026073721.618b4778@laptopd505.fenrus.org,
a new LSM is accepted into the kernel when its intent (a description of
what it tries to protect against and in what cases one would expect to
use it) has been appropriately documented in ``Documentation/admin-guide/LSM/``.
This allows an LSM's code to be easily compared to its goals, and so
that end users and distros can make a more informed decision about which
LSMs suit their requirements.

For extensive documentation on the available LSM hook interfaces, please
see ``include/linux/lsm_hooks.h`` and associated structures:

.. kernel-doc:: include/linux/lsm_hooks.h
   :internal:


code:
========================================================
Linux Security Modules: General Security Hooks for Linux
========================================================

:Author: Stephen Smalley
:Author: Timothy Fraser
:Author: Chris Vance

.. note::

   The APIs described in this book are outdated.

Introduction
============

In March 2001, the National Security Agency (NSA) gave a presentation
about Security-Enhanced Linux (SELinux) at the 2.5 Linux Kernel Summit.
SELinux is an implementation of flexible and fine-grained
nondiscretionary access controls in the Linux kernel, originally
implemented as its own particular kernel patch. Several other security
projects (e.g. RSBAC, Medusa) have also developed flexible access
control architectures for the Linux kernel, and various projects have
developed particular access control models for Linux (e.g. LIDS, DTE,
SubDomain). Each project has developed and maintained its own kernel
patch to support its security needs.

In response to the NSA presentation, Linus Torvalds made a set of
remarks that described a security framework he would be willing to
consider for inclusion in the mainstream Linux kernel. He described a
general framework that would provide a set of security hooks to control
operations on kernel objects and a set of opaque security fields in
kernel data structures for maintaining security attributes. This
framework could then be used by loadable kernel modules to implement any
desired model of security. Linus also suggested the possibility of
migrating the Linux capabilities code into such a module.

The Linux Security Modules (LSM) project was started by WireX to develop
such a framework. LSM was a joint development effort by several security
projects, including Immunix, SELinux, SGI and Janus, and several
individuals, including Greg Kroah-Hartman and James Morris, to develop a
Linux kernel patch that implements this framework. The work was
incorporated in the mainstream in December of 2003. This technical
report provides an overview of the framework and the capabilities
security module.

LSM Framework
=============

The LSM framework provides a general kernel framework to support
security modules. In particular, the LSM framework is primarily focused
on supporting access control modules, although future development is
likely to address other security needs such as sandboxing. By itself, the
framework does not provide any additional security; it merely provides
the infrastructure to support security modules. The LSM framework is
optional, requiring `CONFIG_SECURITY` to be enabled. The capabilities
logic is implemented as a security module.
This capabilities module is discussed further in
`LSM Capabilities Module`_.

The LSM framework includes security fields in kernel data structures and
calls to hook functions at critical points in the kernel code to
manage the security fields and to perform access control.
It also adds functions for registering security modules.
An interface `/sys/kernel/security/lsm` reports a comma separated list
of security modules that are active on the system.

The LSM security fields are simply ``void*`` pointers.
The data is referred to as a blob, which may be managed by
the framework or by the individual security modules that use it.
Security blobs that are used by more than one security module are
typically managed by the framework.
For process and
program execution security information, security fields are included in
:c:type:`struct task_struct <task_struct>` and
:c:type:`struct cred <cred>`.
For filesystem
security information, a security field is included in :c:type:`struct
super_block <super_block>`. For pipe, file, and socket security
information, security fields are included in :c:type:`struct inode
<inode>` and :c:type:`struct file <file>`.
For System V IPC security information,
security fields were added to :c:type:`struct kern_ipc_perm
<kern_ipc_perm>` and :c:type:`struct msg_msg
<msg_msg>`; additionally, the definitions for :c:type:`struct
msg_msg <msg_msg>`, struct msg_queue, and struct shmid_kernel
were moved to header files (``include/linux/msg.h`` and
``include/linux/shm.h`` as appropriate) to allow the security modules to
use these definitions.

For packet and
network device security information, security fields were added to
:c:type:`struct sk_buff <sk_buff>` and
:c:type:`struct scm_cookie <scm_cookie>`.
Unlike the other security module data, the data used here is a
32-bit integer. The security modules are required to map or otherwise
associate these values with real security attributes.

LSM hooks are maintained in lists. A list is maintained for each
hook, and the hooks are called in the order specified by CONFIG_LSM.
Detailed documentation for each hook is
included in the `include/linux/lsm_hooks.h` header file.

The LSM framework provides for a close approximation of
general security module stacking. It defines
security_add_hooks() to which each security module passes a
:c:type:`struct security_hooks_list <security_hooks_list>`,
which are added to the lists.
The LSM framework does not provide a mechanism for removing hooks that
have been registered. The SELinux security module has implemented
a way to remove itself, however the feature has been deprecated.

The hooks can be viewed as falling into two major
categories: hooks that are used to manage the security fields and hooks
that are used to perform access control. Examples of the first category
of hooks include the security_inode_alloc() and security_inode_free()
These hooks are used to allocate
and free security structures for inode objects.
An example of the second category of hooks
is the security_inode_permission() hook.
This hook checks permission when accessing an inode.

LSM Capabilities Module
=======================

The POSIX.1e capabilities logic is maintained as a security module
stored in the file ``security/commoncap.c``. The capabilities
module uses the order field of the :c:type:`lsm_info` description
to identify it as the first security module to be registered.
The capabilities security module does not use the general security
blobs, unlike other modules. The reasons are historical and are
based on overhead, complexity and performance concerns.


code:
=========================================
Linux Secure Attention Key (SAK) handling
=========================================

:Date: 18 March 2001
:Author: Andrew Morton

An operating system's Secure Attention Key is a security tool which is
provided as protection against trojan password capturing programs.  It
is an undefeatable way of killing all programs which could be
masquerading as login applications.  Users need to be taught to enter
this key sequence before they log in to the system.

From the PC keyboard, Linux has two similar but different ways of
providing SAK.  One is the ALT-SYSRQ-K sequence.  You shouldn't use
this sequence.  It is only available if the kernel was compiled with
sysrq support.

The proper way of generating a SAK is to define the key sequence using
``loadkeys``.  This will work whether or not sysrq support is compiled
into the kernel.

SAK works correctly when the keyboard is in raw mode.  This means that
once defined, SAK will kill a running X server.  If the system is in
run level 5, the X server will restart.  This is what you want to
happen.

What key sequence should you use? Well, CTRL-ALT-DEL is used to reboot
the machine.  CTRL-ALT-BACKSPACE is magical to the X server.  We'll
choose CTRL-ALT-PAUSE.

In your rc.sysinit (or rc.local) file, add the command::

	echo "control alt keycode 101 = SAK" | /bin/loadkeys

And that's it!  Only the superuser may reprogram the SAK key.

.. note::

  1. Linux SAK is said to be not a "true SAK" as is required by
     systems which implement C2 level security.  This author does not
     know why.

  2. On the PC keyboard, SAK kills all applications which have
     /dev/console opened.

     Unfortunately this includes a number of things which you don't
     actually want killed.  This is because these applications are
     incorrectly holding /dev/console open.  Be sure to complain to your
     Linux distributor about this!

     You can identify processes which will be killed by SAK with the
     command::

	# ls -l /proc/[0-9]*/fd/* | grep console
	l-wx------    1 root     root           64 Mar 18 00:46 /proc/579/fd/0 -> /dev/console

     Then::

	# ps aux|grep 579
	root       579  0.0  0.1  1088  436 ?        S    00:43   0:00 gpm -t ps/2

     So ``gpm`` will be killed by SAK.  This is a bug in gpm.  It should
     be closing standard input.  You can work around this by finding the
     initscript which launches gpm and changing it thusly:

     Old::

	daemon gpm

     New::

	daemon gpm < /dev/null

     Vixie cron also seems to have this problem, and needs the same treatment.

     Also, one prominent Linux distribution has the following three
     lines in its rc.sysinit and rc scripts::

	exec 3<&0
	exec 4>&1
	exec 5>&2

     These commands cause **all** daemons which are launched by the
     initscripts to have file descriptors 3, 4 and 5 attached to
     /dev/console.  So SAK kills them all.  A workaround is to simply
     delete these lines, but this may cause system management
     applications to malfunction - test everything well.


code:
.. SPDX-License-Identifier: GPL-2.0

==============================
Confidential Computing secrets
==============================

This document describes how Confidential Computing secret injection is handled
from the firmware to the operating system, in the EFI driver and the efi_secret
kernel module.

Introduction
============

Confidential Computing (coco) hardware such as AMD SEV (Secure Encrypted
Virtualization) allows guest owners to inject secrets into the VMs
memory without the host/hypervisor being able to read them.  In SEV,
secret injection is performed early in the VM launch process, before the
guest starts running.

The efi_secret kernel module allows userspace applications to access these
secrets via securityfs.

Secret data flow
================

The guest firmware may reserve a designated memory area for secret injection,
and publish its location (base GPA and length) in the EFI configuration table
under a ``LINUX_EFI_COCO_SECRET_AREA_GUID`` entry
(``adf956ad-e98c-484c-ae11-b51c7d336447``).  This memory area should be marked
by the firmware as ``EFI_RESERVED_TYPE``, and therefore the kernel should not
be use it for its own purposes.

During the VM's launch, the virtual machine manager may inject a secret to that
area.  In AMD SEV and SEV-ES this is performed using the
``KVM_SEV_LAUNCH_SECRET`` command (see [sev]_).  The strucutre of the injected
Guest Owner secret data should be a GUIDed table of secret values; the binary
format is described in ``drivers/virt/coco/efi_secret/efi_secret.c`` under
"Structure of the EFI secret area".

On kernel start, the kernel's EFI driver saves the location of the secret area
(taken from the EFI configuration table) in the ``efi.coco_secret`` field.
Later it checks if the secret area is populated: it maps the area and checks
whether its content begins with ``EFI_SECRET_TABLE_HEADER_GUID``
(``1e74f542-71dd-4d66-963e-ef4287ff173b``).  If the secret area is populated,
the EFI driver will autoload the efi_secret kernel module, which exposes the
secrets to userspace applications via securityfs.  The details of the
efi_secret filesystem interface are in [secrets-coco-abi]_.

Application usage example
=========================

Consider a guest performing computations on encrypted files.  The Guest Owner
provides the decryption key (= secret) using the secret injection mechanism.
The guest application reads the secret from the efi_secret filesystem and
proceeds to decrypt the files into memory and then performs the needed
computations on the content.

In this example, the host can't read the files from the disk image
because they are encrypted.  Host can't read the decryption key because
it is passed using the secret injection mechanism (= secure channel).
Host can't read the decrypted content from memory because it's a
confidential (memory-encrypted) guest.

Here is a simple example for usage of the efi_secret module in a guest
to which an EFI secret area with 4 secrets was injected during launch::

	# ls -la /sys/kernel/security/secrets/coco
	total 0
	drwxr-xr-x 2 root root 0 Jun 28 11:54 .
	drwxr-xr-x 3 root root 0 Jun 28 11:54 ..
	-r--r----- 1 root root 0 Jun 28 11:54 736870e5-84f0-4973-92ec-06879ce3da0b
	-r--r----- 1 root root 0 Jun 28 11:54 83c83f7f-1356-4975-8b7e-d3a0b54312c6
	-r--r----- 1 root root 0 Jun 28 11:54 9553f55d-3da2-43ee-ab5d-ff17f78864d2
	-r--r----- 1 root root 0 Jun 28 11:54 e6f5a162-d67f-4750-a67c-5d065f2a9910

	# hd /sys/kernel/security/secrets/coco/e6f5a162-d67f-4750-a67c-5d065f2a9910
	00000000  74 68 65 73 65 2d 61 72  65 2d 74 68 65 2d 6b 61  |these-are-the-ka|
	00000010  74 61 2d 73 65 63 72 65  74 73 00 01 02 03 04 05  |ta-secrets......|
	00000020  06 07                                             |..|
	00000022

	# rm /sys/kernel/security/secrets/coco/e6f5a162-d67f-4750-a67c-5d065f2a9910

	# ls -la /sys/kernel/security/secrets/coco
	total 0
	drwxr-xr-x 2 root root 0 Jun 28 11:55 .
	drwxr-xr-x 3 root root 0 Jun 28 11:54 ..
	-r--r----- 1 root root 0 Jun 28 11:54 736870e5-84f0-4973-92ec-06879ce3da0b
	-r--r----- 1 root root 0 Jun 28 11:54 83c83f7f-1356-4975-8b7e-d3a0b54312c6
	-r--r----- 1 root root 0 Jun 28 11:54 9553f55d-3da2-43ee-ab5d-ff17f78864d2

References
==========

See [sev-api-spec]_ for more info regarding SEV ``LAUNCH_SECRET`` operation.

.. [sev] Documentation/virt/kvm/x86/amd-memory-encryption.rst
.. [secrets-coco-abi] Documentation/ABI/testing/securityfs-secrets-coco
.. [sev-api-spec] https://www.amd.com/system/files/TechDocs/55766_SEV-KM_API_Specification.pdf


code:
.. SPDX-License-Identifier: GPL-2.0

=====================
Secrets documentation
=====================

.. toctree::

   coco


code:
======================
Kernel Self-Protection
======================

Kernel self-protection is the design and implementation of systems and
structures within the Linux kernel to protect against security flaws in
the kernel itself. This covers a wide range of issues, including removing
entire classes of bugs, blocking security flaw exploitation methods,
and actively detecting attack attempts. Not all topics are explored in
this document, but it should serve as a reasonable starting point and
answer any frequently asked questions. (Patches welcome, of course!)

In the worst-case scenario, we assume an unprivileged local attacker
has arbitrary read and write access to the kernel's memory. In many
cases, bugs being exploited will not provide this level of access,
but with systems in place that defend against the worst case we'll
cover the more limited cases as well. A higher bar, and one that should
still be kept in mind, is protecting the kernel against a _privileged_
local attacker, since the root user has access to a vastly increased
attack surface. (Especially when they have the ability to load arbitrary
kernel modules.)

The goals for successful self-protection systems would be that they
are effective, on by default, require no opt-in by developers, have no
performance impact, do not impede kernel debugging, and have tests. It
is uncommon that all these goals can be met, but it is worth explicitly
mentioning them, since these aspects need to be explored, dealt with,
and/or accepted.

Attack Surface Reduction
========================

The most fundamental defense against security exploits is to reduce the
areas of the kernel that can be used to redirect execution. This ranges
from limiting the exposed APIs available to userspace, making in-kernel
APIs hard to use incorrectly, minimizing the areas of writable kernel
memory, etc.

Strict kernel memory permissions
--------------------------------

When all of kernel memory is writable, it becomes trivial for attacks
to redirect execution flow. To reduce the availability of these targets
the kernel needs to protect its memory with a tight set of permissions.

Executable code and read-only data must not be writable
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Any areas of the kernel with executable memory must not be writable.
While this obviously includes the kernel text itself, we must consider
all additional places too: kernel modules, JIT memory, etc. (There are
temporary exceptions to this rule to support things like instruction
alternatives, breakpoints, kprobes, etc. If these must exist in a
kernel, they are implemented in a way where the memory is temporarily
made writable during the update, and then returned to the original
permissions.)

In support of this are ``CONFIG_STRICT_KERNEL_RWX`` and
``CONFIG_STRICT_MODULE_RWX``, which seek to make sure that code is not
writable, data is not executable, and read-only data is neither writable
nor executable.

Most architectures have these options on by default and not user selectable.
For some architectures like arm that wish to have these be selectable,
the architecture Kconfig can select ARCH_OPTIONAL_KERNEL_RWX to enable
a Kconfig prompt. ``CONFIG_ARCH_OPTIONAL_KERNEL_RWX_DEFAULT`` determines
the default setting when ARCH_OPTIONAL_KERNEL_RWX is enabled.

Function pointers and sensitive variables must not be writable
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Vast areas of kernel memory contain function pointers that are looked
up by the kernel and used to continue execution (e.g. descriptor/vector
tables, file/network/etc operation structures, etc). The number of these
variables must be reduced to an absolute minimum.

Many such variables can be made read-only by setting them "const"
so that they live in the .rodata section instead of the .data section
of the kernel, gaining the protection of the kernel's strict memory
permissions as described above.

For variables that are initialized once at ``__init`` time, these can
be marked with the ``__ro_after_init`` attribute.

What remains are variables that are updated rarely (e.g. GDT). These
will need another infrastructure (similar to the temporary exceptions
made to kernel code mentioned above) that allow them to spend the rest
of their lifetime read-only. (For example, when being updated, only the
CPU thread performing the update would be given uninterruptible write
access to the memory.)

Segregation of kernel memory from userspace memory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The kernel must never execute userspace memory. The kernel must also never
access userspace memory without explicit expectation to do so. These
rules can be enforced either by support of hardware-based restrictions
(x86's SMEP/SMAP, ARM's PXN/PAN) or via emulation (ARM's Memory Domains).
By blocking userspace memory in this way, execution and data parsing
cannot be passed to trivially-controlled userspace memory, forcing
attacks to operate entirely in kernel memory.

Reduced access to syscalls
--------------------------

One trivial way to eliminate many syscalls for 64-bit systems is building
without ``CONFIG_COMPAT``. However, this is rarely a feasible scenario.

The "seccomp" system provides an opt-in feature made available to
userspace, which provides a way to reduce the number of kernel entry
points available to a running process. This limits the breadth of kernel
code that can be reached, possibly reducing the availability of a given
bug to an attack.

An area of improvement would be creating viable ways to keep access to
things like compat, user namespaces, BPF creation, and perf limited only
to trusted processes. This would keep the scope of kernel entry points
restricted to the more regular set of normally available to unprivileged
userspace.

Restricting access to kernel modules
------------------------------------

The kernel should never allow an unprivileged user the ability to
load specific kernel modules, since that would provide a facility to
unexpectedly extend the available attack surface. (The on-demand loading
of modules via their predefined subsystems, e.g. MODULE_ALIAS_*, is
considered "expected" here, though additional consideration should be
given even to these.) For example, loading a filesystem module via an
unprivileged socket API is nonsense: only the root or physically local
user should trigger filesystem module loading. (And even this can be up
for debate in some scenarios.)

To protect against even privileged users, systems may need to either
disable module loading entirely (e.g. monolithic kernel builds or
modules_disabled sysctl), or provide signed modules (e.g.
``CONFIG_MODULE_SIG_FORCE``, or dm-crypt with LoadPin), to keep from having
root load arbitrary kernel code via the module loader interface.

Memory integrity
================

There are many memory structures in the kernel that are regularly abused
to gain execution control during an attack, By far the most commonly
understood is that of the stack buffer overflow in which the return
address stored on the stack is overwritten. Many other examples of this
kind of attack exist, and protections exist to defend against them.

Stack buffer overflow
---------------------

The classic stack buffer overflow involves writing past the expected end
of a variable stored on the stack, ultimately writing a controlled value
to the stack frame's stored return address. The most widely used defense
is the presence of a stack canary between the stack variables and the
return address (``CONFIG_STACKPROTECTOR``), which is verified just before
the function returns. Other defenses include things like shadow stacks.

Stack depth overflow
--------------------

A less well understood attack is using a bug that triggers the
kernel to consume stack memory with deep function calls or large stack
allocations. With this attack it is possible to write beyond the end of
the kernel's preallocated stack space and into sensitive structures. Two
important changes need to be made for better protections: moving the
sensitive thread_info structure elsewhere, and adding a faulting memory
hole at the bottom of the stack to catch these overflows.

Heap memory integrity
---------------------

The structures used to track heap free lists can be sanity-checked during
allocation and freeing to make sure they aren't being used to manipulate
other memory areas.

Counter integrity
-----------------

Many places in the kernel use atomic counters to track object references
or perform similar lifetime management. When these counters can be made
to wrap (over or under) this traditionally exposes a use-after-free
flaw. By trapping atomic wrapping, this class of bug vanishes.

Size calculation overflow detection
-----------------------------------

Similar to counter overflow, integer overflows (usually size calculations)
need to be detected at runtime to kill this class of bug, which
traditionally leads to being able to write past the end of kernel buffers.

Probabilistic defenses
======================

While many protections can be considered deterministic (e.g. read-only
memory cannot be written to), some protections provide only statistical
defense, in that an attack must gather enough information about a
running system to overcome the defense. While not perfect, these do
provide meaningful defenses.

Canaries, blinding, and other secrets
-------------------------------------

It should be noted that things like the stack canary discussed earlier
are technically statistical defenses, since they rely on a secret value,
and such values may become discoverable through an information exposure
flaw.

Blinding literal values for things like JITs, where the executable
contents may be partially under the control of userspace, need a similar
secret value.

It is critical that the secret values used must be separate (e.g.
different canary per stack) and high entropy (e.g. is the RNG actually
working?) in order to maximize their success.

Kernel Address Space Layout Randomization (KASLR)
-------------------------------------------------

Since the location of kernel memory is almost always instrumental in
mounting a successful attack, making the location non-deterministic
raises the difficulty of an exploit. (Note that this in turn makes
the value of information exposures higher, since they may be used to
discover desired memory locations.)

Text and module base
~~~~~~~~~~~~~~~~~~~~

By relocating the physical and virtual base address of the kernel at
boot-time (``CONFIG_RANDOMIZE_BASE``), attacks needing kernel code will be
frustrated. Additionally, offsetting the module loading base address
means that even systems that load the same set of modules in the same
order every boot will not share a common base address with the rest of
the kernel text.

Stack base
~~~~~~~~~~

If the base address of the kernel stack is not the same between processes,
or even not the same between syscalls, targets on or beyond the stack
become more difficult to locate.

Dynamic memory base
~~~~~~~~~~~~~~~~~~~

Much of the kernel's dynamic memory (e.g. kmalloc, vmalloc, etc) ends up
being relatively deterministic in layout due to the order of early-boot
initializations. If the base address of these areas is not the same
between boots, targeting them is frustrated, requiring an information
exposure specific to the region.

Structure layout
~~~~~~~~~~~~~~~~

By performing a per-build randomization of the layout of sensitive
structures, attacks must either be tuned to known kernel builds or expose
enough kernel memory to determine structure layouts before manipulating
them.

Preventing Information Exposures
================================

Since the locations of sensitive structures are the primary target for
attacks, it is important to defend against exposure of both kernel memory
addresses and kernel memory contents (since they may contain kernel
addresses or other sensitive things like canary values).

Kernel addresses
----------------

Printing kernel addresses to userspace leaks sensitive information about
the kernel memory layout. Care should be exercised when using any printk
specifier that prints the raw address, currently %px, %p[ad], (and %p[sSb]
in certain circumstances [*]).  Any file written to using one of these
specifiers should be readable only by privileged processes.

Kernels 4.14 and older printed the raw address using %p. As of 4.15-rc1
addresses printed with the specifier %p are hashed before printing.

[*] If KALLSYMS is enabled and symbol lookup fails, the raw address is
printed. If KALLSYMS is not enabled the raw address is printed.

Unique identifiers
------------------

Kernel memory addresses must never be used as identifiers exposed to
userspace. Instead, use an atomic counter, an idr, or similar unique
identifier.

Memory initialization
---------------------

Memory copied to userspace must always be fully initialized. If not
explicitly memset(), this will require changes to the compiler to make
sure structure holes are cleared.

Memory poisoning
----------------

When releasing memory, it is best to poison the contents, to avoid reuse
attacks that rely on the old contents of memory. E.g., clear stack on a
syscall return (``CONFIG_GCC_PLUGIN_STACKLEAK``), wipe heap memory on a
free. This frustrates many uninitialized variable attacks, stack content
exposures, heap content exposures, and use-after-free attacks.

Destination tracking
--------------------

To help kill classes of bugs that result in kernel addresses being
written to userspace, the destination of writes needs to be tracked. If
the buffer is destined for userspace (e.g. seq_file backed ``/proc`` files),
it should automatically censor sensitive values.


code:
===========================
SipHash - a short input PRF
===========================

:Author: Written by Jason A. Donenfeld <jason@zx2c4.com>

SipHash is a cryptographically secure PRF -- a keyed hash function -- that
performs very well for short inputs, hence the name. It was designed by
cryptographers Daniel J. Bernstein and Jean-Philippe Aumasson. It is intended
as a replacement for some uses of: `jhash`, `md5_transform`, `sha1_transform`,
and so forth.

SipHash takes a secret key filled with randomly generated numbers and either
an input buffer or several input integers. It spits out an integer that is
indistinguishable from random. You may then use that integer as part of secure
sequence numbers, secure cookies, or mask it off for use in a hash table.

Generating a key
================

Keys should always be generated from a cryptographically secure source of
random numbers, either using get_random_bytes or get_random_once::

	siphash_key_t key;
	get_random_bytes(&key, sizeof(key));

If you're not deriving your key from here, you're doing it wrong.

Using the functions
===================

There are two variants of the function, one that takes a list of integers, and
one that takes a buffer::

	u64 siphash(const void *data, size_t len, const siphash_key_t *key);

And::

	u64 siphash_1u64(u64, const siphash_key_t *key);
	u64 siphash_2u64(u64, u64, const siphash_key_t *key);
	u64 siphash_3u64(u64, u64, u64, const siphash_key_t *key);
	u64 siphash_4u64(u64, u64, u64, u64, const siphash_key_t *key);
	u64 siphash_1u32(u32, const siphash_key_t *key);
	u64 siphash_2u32(u32, u32, const siphash_key_t *key);
	u64 siphash_3u32(u32, u32, u32, const siphash_key_t *key);
	u64 siphash_4u32(u32, u32, u32, u32, const siphash_key_t *key);

If you pass the generic siphash function something of a constant length, it
will constant fold at compile-time and automatically choose one of the
optimized functions.

Hashtable key function usage::

	struct some_hashtable {
		DECLARE_HASHTABLE(hashtable, 8);
		siphash_key_t key;
	};

	void init_hashtable(struct some_hashtable *table)
	{
		get_random_bytes(&table->key, sizeof(table->key));
	}

	static inline hlist_head *some_hashtable_bucket(struct some_hashtable *table, struct interesting_input *input)
	{
		return &table->hashtable[siphash(input, sizeof(*input), &table->key) & (HASH_SIZE(table->hashtable) - 1)];
	}

You may then iterate like usual over the returned hash bucket.

Security
========

SipHash has a very high security margin, with its 128-bit key. So long as the
key is kept secret, it is impossible for an attacker to guess the outputs of
the function, even if being able to observe many outputs, since 2^128 outputs
is significant.

Linux implements the "2-4" variant of SipHash.

Struct-passing Pitfalls
=======================

Often times the XuY functions will not be large enough, and instead you'll
want to pass a pre-filled struct to siphash. When doing this, it's important
to always ensure the struct has no padding holes. The easiest way to do this
is to simply arrange the members of the struct in descending order of size,
and to use offsetofend() instead of sizeof() for getting the size. For
performance reasons, if possible, it's probably a good thing to align the
struct to the right boundary. Here's an example::

	const struct {
		struct in6_addr saddr;
		u32 counter;
		u16 dport;
	} __aligned(SIPHASH_ALIGNMENT) combined = {
		.saddr = *(struct in6_addr *)saddr,
		.counter = counter,
		.dport = dport
	};
	u64 h = siphash(&combined, offsetofend(typeof(combined), dport), &secret);

Resources
=========

Read the SipHash paper if you're interested in learning more:
https://131002.net/siphash/siphash.pdf

-------------------------------------------------------------------------------

===============================================
HalfSipHash - SipHash's insecure younger cousin
===============================================

:Author: Written by Jason A. Donenfeld <jason@zx2c4.com>

On the off-chance that SipHash is not fast enough for your needs, you might be
able to justify using HalfSipHash, a terrifying but potentially useful
possibility. HalfSipHash cuts SipHash's rounds down from "2-4" to "1-3" and,
even scarier, uses an easily brute-forcable 64-bit key (with a 32-bit output)
instead of SipHash's 128-bit key. However, this may appeal to some
high-performance `jhash` users.

HalfSipHash support is provided through the "hsiphash" family of functions.

.. warning::
   Do not ever use the hsiphash functions except for as a hashtable key
   function, and only then when you can be absolutely certain that the outputs
   will never be transmitted out of the kernel. This is only remotely useful
   over `jhash` as a means of mitigating hashtable flooding denial of service
   attacks.

On 64-bit kernels, the hsiphash functions actually implement SipHash-1-3, a
reduced-round variant of SipHash, instead of HalfSipHash-1-3. This is because in
64-bit code, SipHash-1-3 is no slower than HalfSipHash-1-3, and can be faster.
Note, this does *not* mean that in 64-bit kernels the hsiphash functions are the
same as the siphash ones, or that they are secure; the hsiphash functions still
use a less secure reduced-round algorithm and truncate their outputs to 32
bits.

Generating a hsiphash key
=========================

Keys should always be generated from a cryptographically secure source of
random numbers, either using get_random_bytes or get_random_once::

	hsiphash_key_t key;
	get_random_bytes(&key, sizeof(key));

If you're not deriving your key from here, you're doing it wrong.

Using the hsiphash functions
============================

There are two variants of the function, one that takes a list of integers, and
one that takes a buffer::

	u32 hsiphash(const void *data, size_t len, const hsiphash_key_t *key);

And::

	u32 hsiphash_1u32(u32, const hsiphash_key_t *key);
	u32 hsiphash_2u32(u32, u32, const hsiphash_key_t *key);
	u32 hsiphash_3u32(u32, u32, u32, const hsiphash_key_t *key);
	u32 hsiphash_4u32(u32, u32, u32, u32, const hsiphash_key_t *key);

If you pass the generic hsiphash function something of a constant length, it
will constant fold at compile-time and automatically choose one of the
optimized functions.

Hashtable key function usage
============================

::

	struct some_hashtable {
		DECLARE_HASHTABLE(hashtable, 8);
		hsiphash_key_t key;
	};

	void init_hashtable(struct some_hashtable *table)
	{
		get_random_bytes(&table->key, sizeof(table->key));
	}

	static inline hlist_head *some_hashtable_bucket(struct some_hashtable *table, struct interesting_input *input)
	{
		return &table->hashtable[hsiphash(input, sizeof(*input), &table->key) & (HASH_SIZE(table->hashtable) - 1)];
	}

You may then iterate like usual over the returned hash bucket.

Performance
===========

hsiphash() is roughly 3 times slower than jhash(). For many replacements, this
will not be a problem, as the hashtable lookup isn't the bottleneck. And in
general, this is probably a good sacrifice to make for the security and DoS
resistance of hsiphash().


code:
=====================================
Trusted Platform Module documentation
=====================================

.. toctree::

   tpm_event_log
   tpm_vtpm_proxy
   xen-tpmfront
   tpm_ftpm_tee


code:
.. SPDX-License-Identifier: GPL-2.0

=============
TPM Event Log
=============

This document briefly describes what TPM log is and how it is handed
over from the preboot firmware to the operating system.

Introduction
============

The preboot firmware maintains an event log that gets new entries every
time something gets hashed by it to any of the PCR registers. The events
are segregated by their type and contain the value of the hashed PCR
register. Typically, the preboot firmware will hash the components to
who execution is to be handed over or actions relevant to the boot
process.

The main application for this is remote attestation and the reason why
it is useful is nicely put in the very first section of [1]:

"Attestation is used to provide information about the platform’s state
to a challenger. However, PCR contents are difficult to interpret;
therefore, attestation is typically more useful when the PCR contents
are accompanied by a measurement log. While not trusted on their own,
the measurement log contains a richer set of information than do the PCR
contents. The PCR contents are used to provide the validation of the
measurement log."

UEFI event log
==============

UEFI provided event log has a few somewhat weird quirks.

Before calling ExitBootServices() Linux EFI stub copies the event log to
a custom configuration table defined by the stub itself. Unfortunately,
the events generated by ExitBootServices() don't end up in the table.

The firmware provides so called final events configuration table to sort
out this issue. Events gets mirrored to this table after the first time
EFI_TCG2_PROTOCOL.GetEventLog() gets called.

This introduces another problem: nothing guarantees that it is not called
before the Linux EFI stub gets to run. Thus, it needs to calculate and save the
final events table size while the stub is still running to the custom
configuration table so that the TPM driver can later on skip these events when
concatenating two halves of the event log from the custom configuration table
and the final events table.

References
==========

- [1] https://trustedcomputinggroup.org/resource/pc-client-specific-platform-firmware-profile-specification/
- [2] The final concatenation is done in drivers/char/tpm/eventlog/efi.c


code:
=============================================
Firmware TPM Driver
=============================================

This document describes the firmware Trusted Platform Module (fTPM)
device driver.

Introduction
============

This driver is a shim for firmware implemented in ARM's TrustZone
environment. The driver allows programs to interact with the TPM in the same
way they would interact with a hardware TPM.

Design
======

The driver acts as a thin layer that passes commands to and from a TPM
implemented in firmware. The driver itself doesn't contain much logic and is
used more like a dumb pipe between firmware and kernel/userspace.

The firmware itself is based on the following paper:
https://www.microsoft.com/en-us/research/wp-content/uploads/2017/06/ftpm1.pdf

When the driver is loaded it will expose ``/dev/tpmX`` character devices to
userspace which will enable userspace to communicate with the firmware TPM
through this device.


code:
=============================================
Virtual TPM Proxy Driver for Linux Containers
=============================================

| Authors:
| Stefan Berger <stefanb@linux.vnet.ibm.com>

This document describes the virtual Trusted Platform Module (vTPM)
proxy device driver for Linux containers.

Introduction
============

The goal of this work is to provide TPM functionality to each Linux
container. This allows programs to interact with a TPM in a container
the same way they interact with a TPM on the physical system. Each
container gets its own unique, emulated, software TPM.

Design
======

To make an emulated software TPM available to each container, the container
management stack needs to create a device pair consisting of a client TPM
character device ``/dev/tpmX`` (with X=0,1,2...) and a 'server side' file
descriptor. The former is moved into the container by creating a character
device with the appropriate major and minor numbers while the file descriptor
is passed to the TPM emulator. Software inside the container can then send
TPM commands using the character device and the emulator will receive the
commands via the file descriptor and use it for sending back responses.

To support this, the virtual TPM proxy driver provides a device ``/dev/vtpmx``
that is used to create device pairs using an ioctl. The ioctl takes as
an input flags for configuring the device. The flags  for example indicate
whether TPM 1.2 or TPM 2 functionality is supported by the TPM emulator.
The result of the ioctl are the file descriptor for the 'server side'
as well as the major and minor numbers of the character device that was created.
Besides that the number of the TPM character device is returned. If for
example ``/dev/tpm10`` was created, the number (``dev_num``) 10 is returned.

Once the device has been created, the driver will immediately try to talk
to the TPM. All commands from the driver can be read from the file descriptor
returned by the ioctl. The commands should be responded to immediately.

UAPI
====

.. kernel-doc:: include/uapi/linux/vtpm_proxy.h

.. kernel-doc:: drivers/char/tpm/tpm_vtpm_proxy.c
   :functions: vtpmx_ioc_new_dev


code:
=============================
Virtual TPM interface for Xen
=============================

Authors: Matthew Fioravante (JHUAPL), Daniel De Graaf (NSA)

This document describes the virtual Trusted Platform Module (vTPM) subsystem for
Xen. The reader is assumed to have familiarity with building and installing Xen,
Linux, and a basic understanding of the TPM and vTPM concepts.

Introduction
------------

The goal of this work is to provide a TPM functionality to a virtual guest
operating system (in Xen terms, a DomU).  This allows programs to interact with
a TPM in a virtual system the same way they interact with a TPM on the physical
system.  Each guest gets its own unique, emulated, software TPM.  However, each
of the vTPM's secrets (Keys, NVRAM, etc) are managed by a vTPM Manager domain,
which seals the secrets to the Physical TPM.  If the process of creating each of
these domains (manager, vTPM, and guest) is trusted, the vTPM subsystem extends
the chain of trust rooted in the hardware TPM to virtual machines in Xen. Each
major component of vTPM is implemented as a separate domain, providing secure
separation guaranteed by the hypervisor. The vTPM domains are implemented in
mini-os to reduce memory and processor overhead.

This mini-os vTPM subsystem was built on top of the previous vTPM work done by
IBM and Intel corporation.

Design Overview
---------------

The architecture of vTPM is described below::

  +------------------+
  |    Linux DomU    | ...
  |       |  ^       |
  |       v  |       |
  |   xen-tpmfront   |
  +------------------+
          |  ^
          v  |
  +------------------+
  | mini-os/tpmback  |
  |       |  ^       |
  |       v  |       |
  |  vtpm-stubdom    | ...
  |       |  ^       |
  |       v  |       |
  | mini-os/tpmfront |
  +------------------+
          |  ^
          v  |
  +------------------+
  | mini-os/tpmback  |
  |       |  ^       |
  |       v  |       |
  | vtpmmgr-stubdom  |
  |       |  ^       |
  |       v  |       |
  | mini-os/tpm_tis  |
  +------------------+
          |  ^
          v  |
  +------------------+
  |   Hardware TPM   |
  +------------------+

* Linux DomU:
	       The Linux based guest that wants to use a vTPM. There may be
	       more than one of these.

* xen-tpmfront.ko:
		    Linux kernel virtual TPM frontend driver. This driver
                    provides vTPM access to a Linux-based DomU.

* mini-os/tpmback:
		    Mini-os TPM backend driver. The Linux frontend driver
		    connects to this backend driver to facilitate communications
		    between the Linux DomU and its vTPM. This driver is also
		    used by vtpmmgr-stubdom to communicate with vtpm-stubdom.

* vtpm-stubdom:
		 A mini-os stub domain that implements a vTPM. There is a
		 one to one mapping between running vtpm-stubdom instances and
                 logical vtpms on the system. The vTPM Platform Configuration
                 Registers (PCRs) are normally all initialized to zero.

* mini-os/tpmfront:
		     Mini-os TPM frontend driver. The vTPM mini-os domain
		     vtpm-stubdom uses this driver to communicate with
		     vtpmmgr-stubdom. This driver is also used in mini-os
		     domains such as pv-grub that talk to the vTPM domain.

* vtpmmgr-stubdom:
		    A mini-os domain that implements the vTPM manager. There is
		    only one vTPM manager and it should be running during the
		    entire lifetime of the machine.  This domain regulates
		    access to the physical TPM on the system and secures the
		    persistent state of each vTPM.

* mini-os/tpm_tis:
		    Mini-os TPM version 1.2 TPM Interface Specification (TIS)
                    driver. This driver used by vtpmmgr-stubdom to talk directly to
                    the hardware TPM. Communication is facilitated by mapping
                    hardware memory pages into vtpmmgr-stubdom.

* Hardware TPM:
		The physical TPM that is soldered onto the motherboard.

Integration With Xen
--------------------

Support for the vTPM driver was added in Xen using the libxl toolstack in Xen
4.3.  See the Xen documentation (docs/misc/vtpm.txt) for details on setting up
the vTPM and vTPM Manager stub domains.  Once the stub domains are running, a
vTPM device is set up in the same manner as a disk or network device in the
domain's configuration file.

In order to use features such as IMA that require a TPM to be loaded prior to
the initrd, the xen-tpmfront driver must be compiled in to the kernel.  If not
using such features, the driver can be compiled as a module and will be loaded
as usual.


code:
.. SPDX-License-Identifier: GPL-2.0

DeviceTree Booting
------------------

  Device-tree compatible SH bootloaders are expected to provide the physical
  address of the device tree blob in r4. Since legacy bootloaders did not
  guarantee any particular initial register state, kernels built to
  inter-operate with old bootloaders must either use a builtin DTB or
  select a legacy board option (something other than CONFIG_SH_DEVICE_TREE)
  that does not use device tree. Support for the latter is being phased out
  in favor of device tree.


code:
.. SPDX-License-Identifier: GPL-2.0

.. kernel-feat:: $srctree/Documentation/features sh


code:
=======================
SuperH Interfaces Guide
=======================

:Author: Paul Mundt

.. toctree::
    :maxdepth: 1

    booting
    new-machine
    register-banks

    features

Memory Management
=================

SH-4
----

Store Queue API
~~~~~~~~~~~~~~~

.. kernel-doc:: arch/sh/kernel/cpu/sh4/sq.c
   :export:

Machine Specific Interfaces
===========================

mach-dreamcast
--------------

.. kernel-doc:: arch/sh/boards/mach-dreamcast/rtc.c
   :internal:

mach-x3proto
------------

.. kernel-doc:: arch/sh/boards/mach-x3proto/ilsel.c
   :export:

Busses
======

SuperHyway
----------

.. kernel-doc:: drivers/sh/superhyway/superhyway.c
   :export:

Maple
-----

.. kernel-doc:: drivers/sh/maple/maple.c
   :export:


code:
.. SPDX-License-Identifier: GPL-2.0

=============================
Adding a new board to LinuxSH
=============================

               Paul Mundt <lethal@linux-sh.org>

This document attempts to outline what steps are necessary to add support
for new boards to the LinuxSH port under the new 2.5 and 2.6 kernels. This
also attempts to outline some of the noticeable changes between the 2.4
and the 2.5/2.6 SH backend.

1. New Directory Structure
==========================

The first thing to note is the new directory structure. Under 2.4, most
of the board-specific code (with the exception of stboards) ended up
in arch/sh/kernel/ directly, with board-specific headers ending up in
include/asm-sh/. For the new kernel, things are broken out by board type,
companion chip type, and CPU type. Looking at a tree view of this directory
hierarchy looks like the following:

Board-specific code::

    .
    |-- arch
    |   `-- sh
    |       `-- boards
    |           |-- adx
    |           |   `-- board-specific files
    |           |-- bigsur
    |           |   `-- board-specific files
    |           |
    |           ... more boards here ...
    |
    `-- include
	`-- asm-sh
	    |-- adx
	    |   `-- board-specific headers
	    |-- bigsur
	    |   `-- board-specific headers
	    |
	    .. more boards here ...

Next, for companion chips::

    .
    `-- arch
	`-- sh
	    `-- cchips
		`-- hd6446x
		    `-- hd64461
			`-- cchip-specific files

... and so on. Headers for the companion chips are treated the same way as
board-specific headers. Thus, include/asm-sh/hd64461 is home to all of the
hd64461-specific headers.

Finally, CPU family support is also abstracted::

    .
    |-- arch
    |   `-- sh
    |       |-- kernel
    |       |   `-- cpu
    |       |       |-- sh2
    |       |       |   `-- SH-2 generic files
    |       |       |-- sh3
    |       |       |   `-- SH-3 generic files
    |       |       `-- sh4
    |       |           `-- SH-4 generic files
    |       `-- mm
    |           `-- This is also broken out per CPU family, so each family can
    |               have their own set of cache/tlb functions.
    |
    `-- include
	`-- asm-sh
	    |-- cpu-sh2
	    |   `-- SH-2 specific headers
	    |-- cpu-sh3
	    |   `-- SH-3 specific headers
	    `-- cpu-sh4
		`-- SH-4 specific headers

It should be noted that CPU subtypes are _not_ abstracted. Thus, these still
need to be dealt with by the CPU family specific code.

2. Adding a New Board
=====================

The first thing to determine is whether the board you are adding will be
isolated, or whether it will be part of a family of boards that can mostly
share the same board-specific code with minor differences.

In the first case, this is just a matter of making a directory for your
board in arch/sh/boards/ and adding rules to hook your board in with the
build system (more on this in the next section). However, for board families
it makes more sense to have a common top-level arch/sh/boards/ directory
and then populate that with sub-directories for each member of the family.
Both the Solution Engine and the hp6xx boards are an example of this.

After you have setup your new arch/sh/boards/ directory, remember that you
should also add a directory in include/asm-sh for headers localized to this
board (if there are going to be more than one). In order to interoperate
seamlessly with the build system, it's best to have this directory the same
as the arch/sh/boards/ directory name, though if your board is again part of
a family, the build system has ways of dealing with this (via incdir-y
overloading), and you can feel free to name the directory after the family
member itself.

There are a few things that each board is required to have, both in the
arch/sh/boards and the include/asm-sh/ hierarchy. In order to better
explain this, we use some examples for adding an imaginary board. For
setup code, we're required at the very least to provide definitions for
get_system_type() and platform_setup(). For our imaginary board, this
might look something like::

    /*
    * arch/sh/boards/vapor/setup.c - Setup code for imaginary board
    */
    #include <linux/init.h>

    const char *get_system_type(void)
    {
	    return "FooTech Vaporboard";
    }

    int __init platform_setup(void)
    {
	    /*
	    * If our hardware actually existed, we would do real
	    * setup here. Though it's also sane to leave this empty
	    * if there's no real init work that has to be done for
	    * this board.
	    */

	    /* Start-up imaginary PCI ... */

	    /* And whatever else ... */

	    return 0;
    }

Our new imaginary board will also have to tie into the machvec in order for it
to be of any use.

machvec functions fall into a number of categories:

 - I/O functions to IO memory (inb etc) and PCI/main memory (readb etc).
 - I/O mapping functions (ioport_map, ioport_unmap, etc).
 - a 'heartbeat' function.
 - PCI and IRQ initialization routines.
 - Consistent allocators (for boards that need special allocators,
   particularly for allocating out of some board-specific SRAM for DMA
   handles).

There are machvec functions added and removed over time, so always be sure to
consult include/asm-sh/machvec.h for the current state of the machvec.

The kernel will automatically wrap in generic routines for undefined function
pointers in the machvec at boot time, as machvec functions are referenced
unconditionally throughout most of the tree. Some boards have incredibly
sparse machvecs (such as the dreamcast and sh03), whereas others must define
virtually everything (rts7751r2d).

Adding a new machine is relatively trivial (using vapor as an example):

If the board-specific definitions are quite minimalistic, as is the case for
the vast majority of boards, simply having a single board-specific header is
sufficient.

 - add a new file include/asm-sh/vapor.h which contains prototypes for
   any machine specific IO functions prefixed with the machine name, for
   example vapor_inb. These will be needed when filling out the machine
   vector.

   Note that these prototypes are generated automatically by setting
   __IO_PREFIX to something sensible. A typical example would be::

	#define __IO_PREFIX vapor
	#include <asm/io_generic.h>

   somewhere in the board-specific header. Any boards being ported that still
   have a legacy io.h should remove it entirely and switch to the new model.

 - Add machine vector definitions to the board's setup.c. At a bare minimum,
   this must be defined as something like::

	struct sh_machine_vector mv_vapor __initmv = {
		.mv_name = "vapor",
	};
	ALIAS_MV(vapor)

 - finally add a file arch/sh/boards/vapor/io.c, which contains definitions of
   the machine specific io functions (if there are enough to warrant it).

3. Hooking into the Build System
================================

Now that we have the corresponding directories setup, and all of the
board-specific code is in place, it's time to look at how to get the
whole mess to fit into the build system.

Large portions of the build system are now entirely dynamic, and merely
require the proper entry here and there in order to get things done.

The first thing to do is to add an entry to arch/sh/Kconfig, under the
"System type" menu::

    config SH_VAPOR
	    bool "Vapor"
	    help
	    select Vapor if configuring for a FooTech Vaporboard.

next, this has to be added into arch/sh/Makefile. All boards require a
machdir-y entry in order to be built. This entry needs to be the name of
the board directory as it appears in arch/sh/boards, even if it is in a
sub-directory (in which case, all parent directories below arch/sh/boards/
need to be listed). For our new board, this entry can look like::

    machdir-$(CONFIG_SH_VAPOR)	+= vapor

provided that we've placed everything in the arch/sh/boards/vapor/ directory.

Next, the build system assumes that your include/asm-sh directory will also
be named the same. If this is not the case (as is the case with multiple
boards belonging to a common family), then the directory name needs to be
implicitly appended to incdir-y. The existing code manages this for the
Solution Engine and hp6xx boards, so see these for an example.

Once that is taken care of, it's time to add an entry for the mach type.
This is done by adding an entry to the end of the arch/sh/tools/mach-types
list. The method for doing this is self explanatory, and so we won't waste
space restating it here. After this is done, you will be able to use
implicit checks for your board if you need this somewhere throughout the
common code, such as::

	/* Make sure we're on the FooTech Vaporboard */
	if (!mach_is_vapor())
		return -ENODEV;

also note that the mach_is_boardname() check will be implicitly forced to
lowercase, regardless of the fact that the mach-types entries are all
uppercase. You can read the script if you really care, but it's pretty ugly,
so you probably don't want to do that.

Now all that's left to do is providing a defconfig for your new board. This
way, other people who end up with this board can simply use this config
for reference instead of trying to guess what settings are supposed to be
used on it.

Also, as soon as you have copied over a sample .config for your new board
(assume arch/sh/configs/vapor_defconfig), you can also use this directly as a
build target, and it will be implicitly listed as such in the help text.

Looking at the 'make help' output, you should now see something like:

Architecture specific targets (sh):

  =======================   =============================================
  zImage                    Compressed kernel image (arch/sh/boot/zImage)
  adx_defconfig             Build for adx
  cqreek_defconfig          Build for cqreek
  dreamcast_defconfig       Build for dreamcast
  ...
  vapor_defconfig           Build for vapor
  =======================   =============================================

which then allows you to do::

    $ make ARCH=sh CROSS_COMPILE=sh4-linux- vapor_defconfig vmlinux

which will in turn copy the defconfig for this board, run it through
oldconfig (prompting you for any new options since the time of creation),
and start you on your way to having a functional kernel for your new
board.


code:
.. SPDX-License-Identifier: GPL-2.0

==========================================
Notes on register bank usage in the kernel
==========================================

Introduction
------------

The SH-3 and SH-4 CPU families traditionally include a single partial register
bank (selected by SR.RB, only r0 ... r7 are banked), whereas other families
may have more full-featured banking or simply no such capabilities at all.

SR.RB banking
-------------

In the case of this type of banking, banked registers are mapped directly to
r0 ... r7 if SR.RB is set to the bank we are interested in, otherwise ldc/stc
can still be used to reference the banked registers (as r0_bank ... r7_bank)
when in the context of another bank. The developer must keep the SR.RB value
in mind when writing code that utilizes these banked registers, for obvious
reasons. Userspace is also not able to poke at the bank1 values, so these can
be used rather effectively as scratch registers by the kernel.

Presently the kernel uses several of these registers.

	- r0_bank, r1_bank (referenced as k0 and k1, used for scratch
	  registers when doing exception handling).

	- r2_bank (used to track the EXPEVT/INTEVT code)

		- Used by do_IRQ() and friends for doing irq mapping based off
		  of the interrupt exception vector jump table offset

	- r6_bank (global interrupt mask)

		- The SR.IMASK interrupt handler makes use of this to set the
		  interrupt priority level (used by local_irq_enable())

	- r7_bank (current)