---
name: "crypto"
section: "9freebsd"
platform: "linux"
package: "freebsd-manpages"
version: "12.2-2"
release: "Debian 13 (Trixie)"
platforms: ["linux"]
url: "https://new.carta.tech/crypto/9freebsd"
---

# crypto(9freebsd)

API for cryptographic services in the kernel

## NAME

**crypto** – API for cryptographic services in the kernel

## SYNOPSIS

**#include \<opencrypto/cryptodev.h\>**

*int32\_t*\

**crypto\_get\_driverid**(*device\_t dev*, *size\_t session\_size*, *int flags*);

*int*\

**crypto\_register**(*uint32\_t driverid*, *int alg*, *uint16\_t maxoplen*, *uint32\_t flags*);

*int*\

**crypto\_kregister**(*uint32\_t driverid*, *int kalg*, *uint32\_t flags*);

*int*\

**crypto\_unregister**(*uint32\_t driverid*, *int alg*);

*int*\

**crypto\_unregister\_all**(*uint32\_t driverid*);

*void*\

**crypto\_done**(*struct cryptop \*crp*);

*void*\

**crypto\_kdone**(*struct cryptkop \*krp*);

*int*\

**crypto\_find\_driver**(*const char \*match*);

*int*\

**crypto\_newsession**(*crypto\_session\_t \*cses*, *struct cryptoini \*cri*, *int crid*);

*int*\

**crypto\_freesession**(*crypto\_session\_t cses*);

*int*\

**crypto\_dispatch**(*struct cryptop \*crp*);

*int*\

**crypto\_kdispatch**(*struct cryptkop \*krp*);

*int*\

**crypto\_unblock**(*uint32\_t driverid*, *int what*);

*struct cryptop \**\

**crypto\_getreq**(*int num*);

*void*\

**crypto\_freereq**(*struct cryptop \*crp*);

```
#define	CRYPTO_SYMQ	0x1
#define	CRYPTO_ASYMQ	0x2
#define EALG_MAX_BLOCK_LEN      16
struct cryptoini {
	int                cri_alg;
	int                cri_klen;
	int                cri_mlen;
	caddr_t            cri_key;
	uint8_t            cri_iv[EALG_MAX_BLOCK_LEN];
	struct cryptoini  *cri_next;
};
struct cryptodesc {
	int                crd_skip;
	int                crd_len;
	int                crd_inject;
	int                crd_flags;
	struct cryptoini   CRD_INI;
#define crd_iv          CRD_INI.cri_iv
#define crd_key         CRD_INI.cri_key
#define crd_alg         CRD_INI.cri_alg
#define crd_klen        CRD_INI.cri_klen
	struct cryptodesc *crd_next;
};
struct cryptop {
	TAILQ_ENTRY(cryptop) crp_next;
	crypto_session_t   crp_session;
	int                crp_ilen;
	int                crp_olen;
	int                crp_etype;
	int                crp_flags;
	caddr_t            crp_buf;
	caddr_t            crp_opaque;
	struct cryptodesc *crp_desc;
	int              (*crp_callback) (struct cryptop *);
	caddr_t            crp_mac;
};
struct crparam {
        caddr_t         crp_p;
        u_int           crp_nbits;
};
#define CRK_MAXPARAM    8
struct cryptkop {
        TAILQ_ENTRY(cryptkop) krp_next;
        u_int              krp_op;         /* ie. CRK_MOD_EXP or other */
        u_int              krp_status;     /* return status */
        u_short            krp_iparams;    /* # of input parameters */
        u_short            krp_oparams;    /* # of output parameters */
        uint32_t           krp_hid;
        struct crparam     krp_param[CRK_MAXPARAM];
        int               (*krp_callback)(struct cryptkop *);
};
```

## DESCRIPTION

**crypto** is a framework for drivers of cryptographic hardware to register with the kernel so “consumers” (other kernel subsystems, and users through the */dev/crypto* device) are able to make use of it. Drivers register with the framework the algorithms they support, and provide entry points (functions) the framework may call to establish, use, and tear down sessions. Sessions are used to cache cryptographic information in a particular driver (or associated hardware), so initialization is not needed with every request. Consumers of cryptographic services pass a set of descriptors that instruct the framework (and the drivers registered with it) of the operations that should be applied on the data (more than one cryptographic operation can be requested).

Keying operations are supported as well. Unlike the symmetric operators described above, these sessionless commands perform mathematical operations using input and output parameters.

Since the consumers may not be associated with a process, drivers may not [sleep(9)](/sleep/9.md). The same holds for the framework. Thus, a callback mechanism is used to notify a consumer that a request has been completed (the callback is specified by the consumer on a per-request basis). The callback is invoked by the framework whether the request was successfully completed or not. An error indication is provided in the latter case. A specific error code, EAGAIN, is used to indicate that a session handle has changed and that the request may be re-submitted immediately with the new session. Errors are only returned to the invoking function if not enough information to call the callback is available (meaning, there was a fatal error in verifying the arguments). For session initialization and teardown no callback mechanism is used.

The **crypto\_find\_driver**() returns the driver id of the device whose name matches *match*. *match* can either be the exact name of a device including the unit or the driver name without a unit. In the latter case, the id of the first device with the matching driver name is returned. If no matching device is found, the value -1 is returned.

The **crypto\_newsession**() routine is called by consumers of cryptographic services (such as the [ipsec(4)](/ipsec/4.md) stack) that wish to establish a new session with the framework. The *cri* argument points to a *cryptoini* structure containing all the necessary information for the driver to establish the session. The *crid* argument is either a specific driver id or a bitmask of flags. The flags are CRYPTOCAP\_F\_HARDWARE, to select hardware devices, or CRYPTOCAP\_F\_SOFTWARE, to select software devices. If both are specified, hardware devices are preferred over software devices. On success, the opaque session handle of the new session will be stored in *\*cses*. The *cryptoini* structure pointed to by *cri* contains these fields:

- *cri\_alg*

  An algorithm identifier. Currently supported algorithms are:

  - CRYPTO\_AES\_128\_NIST\_GMAC

    - CRYPTO\_AES\_192\_NIST\_GMAC

    - CRYPTO\_AES\_256\_NIST\_GMAC

    - CRYPTO\_AES\_CBC

    - CRYPTO\_AES\_CCM\_16

    - CRYPTO\_AES\_CCM\_CBC\_MAC

    - CRYPTO\_AES\_ICM

    - CRYPTO\_AES\_NIST\_GCM\_16

    - CRYPTO\_AES\_NIST\_GMAC

    - CRYPTO\_AES\_XTS

    - CRYPTO\_ARC4

    - CRYPTO\_BLAKE2B

    - CRYPTO\_BLAKE2S

    - CRYPTO\_BLF\_CBC

    - CRYPTO\_CAMELLIA\_CBC

    - CRYPTO\_CAST\_CBC

    - CRYPTO\_CHACHA20

    - CRYPTO\_DEFLATE\_COMP

    - CRYPTO\_DES\_CBC

    - CRYPTO\_3DES\_CBC

    - CRYPTO\_MD5

    - CRYPTO\_MD5\_HMAC

    - CRYPTO\_MD5\_KPDK

    - CRYPTO\_NULL\_HMAC

    - CRYPTO\_NULL\_CBC

    - CRYPTO\_POLY1305

    - CRYPTO\_RIPEMD160

    - CRYPTO\_RIPEMD160\_HMAC

    - CRYPTO\_SHA1

    - CRYPTO\_SHA1\_HMAC

    - CRYPTO\_SHA1\_KPDK

    - CRYPTO\_SHA2\_224

    - CRYPTO\_SHA2\_224\_HMAC

    - CRYPTO\_SHA2\_256

    - CRYPTO\_SHA2\_256\_HMAC

    - CRYPTO\_SHA2\_384

    - CRYPTO\_SHA2\_384\_HMAC

    - CRYPTO\_SHA2\_512

    - CRYPTO\_SHA2\_512\_HMAC

    - CRYPTO\_SKIPJACK\_CBC

    - *cri\_klen*

  For variable-size key algorithms, the length of the key in bits.

- *cri\_mlen*

  If non-zero, truncate the calculated hash to this many bytes.

- *cri\_key*

  The key to be used.

- *cri\_iv*

  An explicit initialization vector if it does not prefix the data. This field is ignored during initialization (**crypto\_newsession**). If no IV is explicitly passed (see below on details), a random IV is used by the device driver processing the request.

- *cri\_next*

  Pointer to another *cryptoini* structure. This is used to establish dual-algorithm sessions, such as combining a cipher with a MAC.

The *cryptoini* structure and its contents will not be modified or referenced by the framework or any cryptographic drivers. The memory associated with *cri* can be released once **crypto\_newsession**() returns.

**crypto\_freesession**() is called with the session handle returned by **crypto\_newsession**() to free the session.

**crypto\_dispatch**() is called to process a request. The various fields in the *cryptop* structure are:

- *crp\_session*

  The session handle.

- *crp\_ilen*

  The total length in bytes of the buffer to be processed.

- *crp\_olen*

  On return, contains the total length of the result. For symmetric crypto operations, this will be the same as the input length. This will be used if the framework needs to allocate a new buffer for the result (or for re-formatting the input).

- *crp\_callback*

  Callback routine invoked when a request is completed via **crypto\_done**(). The callback routine should inspect the *crp\_etype* to determine if the request was successfully completed.

- *crp\_etype*

  The error type, if any errors were encountered, or zero if the request was successfully processed. If the EAGAIN error code is returned, the session handle has changed (and has been recorded in the *crp\_session* field). The consumer should record the new session handle and use it in all subsequent requests. In this case, the request may be re-submitted immediately. This mechanism is used by the framework to perform session migration (move a session from one driver to another, because of availability, performance, or other considerations).

  This field is only valid in the context of the callback routine specified by *crp\_callback*. Errors are returned to the invoker of **crypto\_process**() only when enough information is not present to call the callback routine (i.e., if the pointer passed is NULL or if no callback routine was specified).

- *crp\_flags*

  A bitmask of flags associated with this request. Currently defined flags are:

  - CRYPTO\_F\_IMBUF

    The buffer is an mbuf chain pointed to by *crp\_mbuf*.

  - CRYPTO\_F\_IOV

    The buffer is a *uio* structure pointed to by *crp\_uio*.

  - CRYPTO\_F\_BATCH

    Batch operation if possible.

  - CRYPTO\_F\_CBIMM

    Do callback immediately instead of doing it from a dedicated kernel thread.

  - CRYPTO\_F\_DONE

    Operation completed.

  - CRYPTO\_F\_CBIFSYNC

    Do callback immediately if operation is synchronous (that the driver specified the CRYPTOCAP\_F\_SYNC flag).

  - CRYPTO\_F\_ASYNC

    Try to do the crypto operation in a pool of workers if the operation is synchronous (that is, if the driver specified the CRYPTOCAP\_F\_SYNC flag). It aims to speed up processing by dispatching crypto operations on different processors.

  - CRYPTO\_F\_ASYNC\_KEEPORDER

    Dispatch callbacks in the same order they are posted. Only relevant if the CRYPTO\_F\_ASYNC flag is set and if the operation is synchronous.

- *crp\_buf*

  Data buffer unless CRYPTO\_F\_IMBUF or CRYPTO\_F\_IOV is set in *crp\_flags*. The length in bytes is set in *crp\_ilen*.

- *crp\_mbuf*

  Data buffer mbuf chain when CRYPTO\_F\_IMBUF is set in *crp\_flags*.

- *crp\_uio*

  *struct* *uio* data buffer when CRYPTO\_F\_IOV is set in *crp\_flags*.

- *crp\_opaque*

  Cookie passed through the crypto framework untouched. It is intended for the invoking application's use.

- *crp\_desc*

  A linked list of descriptors. Each descriptor provides information about what type of cryptographic operation should be done on the input buffer. The various fields are:

  - *crd\_iv*

    When the flag CRD\_F\_IV\_EXPLICIT is set, this field contains the IV.

  - *crd\_key*

    When the CRD\_F\_KEY\_EXPLICIT flag is set, the *crd\_key* points to a buffer with encryption or authentication key.

  - *crd\_alg*

    An algorithm to use. Must be the same as the one given at newsession time.

  - *crd\_klen*

    The *crd\_key* key length.

  - *crd\_skip*

    The offset in the input buffer where processing should start.

  - *crd\_len*

    How many bytes, after *crd\_skip*, should be processed.

  - *crd\_inject*

    The *crd\_inject* field specifies an offset in bytes from the beginning of the buffer. For encryption algorithms, this may be where the IV will be inserted when encrypting or where the IV may be found for decryption (subject to *crd\_flags*). For MAC algorithms, this is where the result of the keyed hash will be inserted.

  - *crd\_flags*

    The following flags are defined:

    - CRD\_F\_ENCRYPT

      For encryption algorithms, this bit is set when encryption is required (when not set, decryption is performed).

    - CRD\_F\_IV\_PRESENT

      For encryption, if this bit is not set the IV used to encrypt the packet will be written at the location pointed to by *crd\_inject*. The IV length is assumed to be equal to the blocksize of the encryption algorithm. For encryption, if this bit is set, nothing is done. For decryption, this flag has no meaning. Applications that do special “IV cooking”, such as the half-IV mode in [ipsec(4)](/ipsec/4.md), can use this flag to indicate that the IV should not be written on the packet. This flag is typically used in conjunction with the CRD\_F\_IV\_EXPLICIT flag.

    - CRD\_F\_IV\_EXPLICIT

      This bit is set when the IV is explicitly provided by the consumer in the *crd\_iv* field. Otherwise, for encryption operations the IV is provided for by the driver used to perform the operation, whereas for decryption operations the offset of the IV is provided by the *crd\_inject* field. This flag is typically used when the IV is calculated “on the fly” by the consumer, and does not precede the data.

    - CRD\_F\_KEY\_EXPLICIT

      For encryption and authentication (MAC) algorithms, this bit is set when the key is explicitly provided by the consumer in the *crd\_key* field for the given operation. Otherwise, the key is taken at newsession time from the *cri\_key* field. As calculating the key schedule may take a while, it is recommended that often used keys are given their own session.

    - CRD\_F\_COMP

      For compression algorithms, this bit is set when compression is required (when not set, decompression is performed).

  - *CRD\_INI*

    This *cryptoini* structure will not be modified by the framework or the device drivers. Since this information accompanies every cryptographic operation request, drivers may re-initialize state on-demand (typically an expensive operation). Furthermore, the cryptographic framework may re-route requests as a result of full queues or hardware failure, as described above.

  - *crd\_next*

    Point to the next descriptor. Linked operations are useful in protocols such as [ipsec(4)](/ipsec/4.md), where multiple cryptographic transforms may be applied on the same block of data.

**crypto\_getreq**() allocates a *cryptop* structure with a linked list of *num* *cryptodesc* structures.

**crypto\_freereq**() deallocates a structure *cryptop* and any *cryptodesc* structures linked to it. Note that it is the responsibility of the callback routine to do the necessary cleanups associated with the opaque field in the *cryptop* structure.

**crypto\_kdispatch**() is called to perform a keying operation. The various fields in the *cryptkop* structure are:

- *krp\_op*

  Operation code, such as CRK\_MOD\_EXP.

- *krp\_status*

  Return code. This *errno*-style variable indicates whether lower level reasons for operation failure.

- *krp\_iparams*

  Number of input parameters to the specified operation. Note that each operation has a (typically hardwired) number of such parameters.

- *krp\_oparams*

  Number of output parameters from the specified operation. Note that each operation has a (typically hardwired) number of such parameters.

- *krp\_kvp*

  An array of kernel memory blocks containing the parameters.

- *krp\_hid*

  Identifier specifying which low-level driver is being used.

- *krp\_callback*

  Callback called on completion of a keying operation.

## DRIVER-SIDE API

The **crypto\_get\_driverid**(), **crypto\_get\_driver\_session**(), **crypto\_register**(), **crypto\_kregister**(), **crypto\_unregister**(), **crypto\_unblock**(), and **crypto\_done**() routines are used by drivers that provide support for cryptographic primitives to register and unregister with the kernel crypto services framework.

Drivers must first use the **crypto\_get\_driverid**() function to acquire a driver identifier, specifying the *flags* as an argument. One of CRYPTOCAP\_F\_SOFTWARE or CRYPTOCAP\_F\_HARDWARE must be specified. The CRYPTOCAP\_F\_SYNC may also be specified, and should be specified if the driver does all of it's operations synchronously. Drivers must pass the size of their session structure as the second argument. An appropriately sized memory will be allocated by the framework, zeroed, and passed to the driver's **newsession**() method.

For each algorithm the driver supports, it must then call **crypto\_register**(). The first two arguments are the driver and algorithm identifiers. The next two arguments specify the largest possible operator length (in bits, important for public key operations) and flags for this algorithm.

**crypto\_unregister**() is called by drivers that wish to withdraw support for an algorithm. The two arguments are the driver and algorithm identifiers, respectively. Typically, drivers for PCMCIA crypto cards that are being ejected will invoke this routine for all algorithms supported by the card. **crypto\_unregister\_all**() will unregister all algorithms registered by a driver and the driver will be disabled (no new sessions will be allocated on that driver, and any existing sessions will be migrated to other drivers). The same will be done if all algorithms associated with a driver are unregistered one by one. After a call to **crypto\_unregister\_all**() there will be no threads in either the newsession or freesession function of the driver.

The calling convention for the driver-supplied routines are:

-

  *int* **\*newsession**(*device\_t*, *crypto\_session\_t*, *struct cryptoini \**);

-

  *void* **\*freesession**(*device\_t*, *crypto\_session\_t*);

-

  *int* **\*process**(*device\_t*, *struct cryptop \**, *int*);

-

  *int* **\*kprocess**(*device\_t*, *struct cryptkop \**, *int*);

On invocation, the first argument to all routines is the *device\_t* that was provided to **crypto\_get\_driverid**(). The second argument to **newsession**() is the opaque session handle for the new session. The third argument is identical to that of **crypto\_newsession**().

Drivers obtain a pointer to their session memory by invoking **crypto\_get\_driver\_session**() on the opaque *crypto\_session\_t* handle.

The **freesession**() routine takes as arguments the opaque data value and the session handle. It should clear any context associated with the session (clear hardware registers, memory, etc.). If no resources need to be released other than the contents of session memory, the method is optional. The **crypto** framework will zero and release the allocated session memory (after running the **freesession**() method, if one exists).

The **process**() routine is invoked with a request to perform crypto processing. This routine must not block or sleep, but should queue the request and return immediately or process the request to completion. In case of an unrecoverable error, the error indication must be placed in the *crp\_etype* field of the *cryptop* structure. When the request is completed, or an error is detected, the **process**() routine must invoke **crypto\_done**(). Session migration may be performed, as mentioned previously.

In case of a temporary resource exhaustion, the **process**() routine may return ERESTART in which case the crypto services will requeue the request, mark the driver as “blocked”, and stop submitting requests for processing. The driver is then responsible for notifying the crypto services when it is again able to process requests through the **crypto\_unblock**() routine. This simple flow control mechanism should only be used for short-lived resource exhaustion as it causes operations to be queued in the crypto layer. Doing so is preferable to returning an error in such cases as it can cause network protocols to degrade performance by treating the failure much like a lost packet.

The **kprocess**() routine is invoked with a request to perform crypto key processing. This routine must not block, but should queue the request and return immediately. Upon processing the request, the callback routine should be invoked. In case of an unrecoverable error, the error indication must be placed in the *krp\_status* field of the *cryptkop* structure. When the request is completed, or an error is detected, the **kprocess**() routine should invoked **crypto\_kdone**().

## RETURN VALUES

**crypto\_register**(), **crypto\_kregister**(), **crypto\_unregister**(), **crypto\_newsession**(), **crypto\_freesession**(), and **crypto\_unblock**() return 0 on success, or an error code on failure. **crypto\_get\_driverid**() returns a non-negative value on error, and -1 on failure. **crypto\_getreq**() returns a pointer to a *cryptop* structure and NULL on failure. **crypto\_dispatch**() returns EINVAL if its argument or the callback function was NULL, and 0 otherwise. The callback is provided with an error code in case of failure, in the *crp\_etype* field.

## FILES

- *sys/opencrypto/crypto.c*

  most of the framework code

## SEE ALSO

[crypto(4)](/crypto/4.md), [ipsec(4)](/ipsec/4.md), [crypto(7)](/crypto/7.md), [malloc(9)](/malloc/9.md), [sleep(9)](/sleep/9.md)

## HISTORY

The cryptographic framework first appeared in OpenBSD 2.7 and was written by Angelos D. Keromytis ⟨*angelos@openbsd.org*⟩.

## BUGS

The framework currently assumes that all the algorithms in a **crypto\_newsession**() operation must be available by the same driver. If that is not the case, session initialization will fail.

The framework also needs a mechanism for determining which driver is best for a specific set of algorithms associated with a session. Some type of benchmarking is in order here.

Multiple instances of the same algorithm in the same session are not supported.
