# Introduction

Libec is a small PKI library leveraging the crypto routines available in [libsodium](http://www.libsodium.org/).

## Support

For development support, questions etc. please use the [mailing list](https://groups.google.com/a/erayd.net/forum/#!forum/libec).

This documentation may also be downloaded as an ebook or PDF [here](http://manual.libec.erayd.net/).

## Licence

Libec is available under the [ISC Licence](http://en.wikipedia.org/wiki/ISC_license). Please see the LICENCE file in the root of the project for more information.


# Usage

```c
#include <ec.h>

int main(void) {
    if(ec_init() != 0) {
        //init failed
    }
    ...
}
```

`ec.h` is the only header required, and declares all user-accessible functionality. `-lec` will link to it.

`ec_init()` should be called before any other function in the library.

All functions other than `ec_init()` are thread-safe, but data structures should not be shared by multiple threads without appropriate protection.


# Build & Install

## Installation

Libec requires the following runtime dependencies:

| Dependency                            | Version |
| ------------------------------------- | ------- |
| [libsodium](http://www.libsodium.org) | >=1.0.0 |
| [talloc](https://talloc.samba.org)    | >=2.0.0 |

To install, run the following commands:

```bash
$ git clone https://github.com/erayd/libec.git
$ cd libec
$ ./autogen.sh
$ ./configure
$ make check
# make install
```

### System Requirements

Libec is intended for use on little-endian POSIX systems (e.g. Linux, OSX etc.)

***Libec is not targeted at or tested on big-endian systems.*** While it's possible that libec may build on some big-endian systems, it will probably not function as intended, and at a minimum will be incompatible with certificate or other data generated on a little-endian system.

## Build requirements

### Linux

Any recent Linux system with autotools installed should be able to build libec out of the box, provided libsodium and talloc are installed.

The reference system for development is 64bit Gentoo Linux.

### OSX

In order to build libec on OSX, the following additional built-time dependencies are required:

* XCode
* autoconf
* automake
* libtool
* pkg-config

autoconf, automake, libtool, pkg-config, libsodium, and talloc are all available via homebrew (`brew install <package>`). If you don't have homebrew installed, please see [brew.sh](http://brew.sh).

If `make` is unable to find header files (particularly on OSX 10.10 Yosemite), it's likely that /usr/include is missing or empty. Run `xcode-select --install` and install the Command Line Developer Tools to resolve this issue.

### Windows

Libec is not currently available on Windows, but may be in the future. Code contributions for a Windows build are welcome.


# Certificates

Certificates are represented by the `ec_cert_t` type, and are created by `ec_cert_create()`. All certificates must be freed once they are no longer required using `ec_cert_destroy()`.

If a certificate has been saved using `ec_ctx_save()`, then it will be destroyed automatically once it is removed, overwritten, or the context it was saved to is destroyed.

## API

* [ec\_cert\_create()](/certificates#ec-cert-create)
* [ec\_cert\_copy()](/certificates#ec-cert-copy)
* [ec\_cert\_destroy()](/certificates#ec-cert-destroy)
* [ec\_cert\_strip()](/certificates#ec-cert-strip)
* [ec\_cert\_sign()](/certificates#ec-cert-sign)
* [ec\_cert\_check()](/certificates#ec-cert-check)
* [ec\_cert\_id()](/certificates#ec-cert-id)
* [ec\_cert\_records()](/certificates#ec-cert-records)
* [ec\_cert\_lock()](/certificates#ec-cert-lock)
* [ec\_cert\_unlock()](/certificates#ec-cert-unlock)

### ec\_cert\_create()

`ec_cert_t *ec_cert_create(time_t valid_from, time_t valid_until);`

Create a new certificate, and return a pointer to it. Returns NULL on failure. `valid_from` and `valid_until` define the certificate's validity period - if the validity period does not fall entirely within the valitity period of its signer, then the timestamp which violates this constraint will be adjusted to match that of the signer.

Timestamps are handled as seconds since 1970-01-01 00:00:00. The current time can be obtained using `time()` (see `time.h`).

Certificates created using this function must be destroyed using `ec_cert_destroy()` when they are no longer required.

```c
#include <ec.h>
#include <time.h>
...
time_t from = time(NULL);
time_t until = from + (86400 * 365); //one year
ec_cert_t *c = ec_cert_create(from, until);
...
```

### ec\_cert\_copy()

`ec_cert_t *ec_cert_copy(ec_cert_t *c);`

Copy a certificate. Returns a new copy of `c`, or NULL on failure.

```c
#include <ec.h>
...
ec_cert_t *c2 = ec_cert_copy(c1);
if(c == NULL) {
    //failed to copy certificate
}
...
```

### ec\_cert\_destroy()

`void ec_cert_destroy(ec_cert_t *c);`

Destroy a certificate previously created with `ec_cert_create()`.

```c
#include <ec.h>
...
ec_cert_destroy(c);
...
```

### ec\_cert\_strip()

`void ec_cert_strip(ec_cert_t *c, int what);`

Strip unwanted data from a certificate, specified by `when`. Possible flags are listed below:

| Flag              | Removed Data                            |
| ----------------- | --------------------------------------- |
| EC\_STRIP\_SECRET | Secret key                              |
| EC\_STRIP\_RECORD | All records with EC\_RECORD\_NOSIGN set |
| EC\_STRIP\_SIGN   | Signer ID & signature                   |

```c
#include <ec.h>
...
ec_cert_strip(c, EC_STRIP_SECRET | EC_STRIP_RECORD);
...
```

### ec\_cert\_sign()

`ec_err_t ec_cert_sign(ec_cert_t *c, ec_cert_t *signer);`

Sign a certificate using another certificate. Returns a nonzero error code on failure.

The signer must have a valid secret key available, and both certificates must pass the following checks prior to signing:

```c
ec_cert_check(NULL, c, EC_CHECK_CERT);
ec_cert_check(NULL, signer, EC_CHECK_CERT | EC_CHECK_SECRET);
```

If the certificate's validity falls outside that of the signer, the appropriate timestamp on the certificate will be adjusted to match that of the signer.

```c
#include <ec.h>
...
if(ec_cert_sign(c, signer) != 0) {
    //signing succeeded
}
...
```

### ec\_cert\_check()

`ec_err_t ec_cert_check(ec_ctx_t *ctx, ec_cert_t *c, int flags);`

Ensure that a certificate passes a given set of tests. Returns a nonzero error code on failure.

All tests which require a valid trust chain to be present must also provide a context where the trust chain may be found. Tests which apply only to the certificate may pass `NULL` instead.

The `flags` parameter is used to set which tests are run, according to the following table. Checks are run in the order that they are listed here.

| Flag               | Implies          | Context Required? | Tests                                                                                                                                                                                                                                                                             |
| ------------------ | ---------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| EC\_CHECK\_CERT    |                  | No                | Certificate is the correct version, a valid public key is present, the current time falls within the certificate's validity period, any records present are of a valid length, any section records have a NULL-terminated string key.                                             |
| EC\_CHECK\_SECRET  |                  | No                | A secret key is present                                                                                                                                                                                                                                                           |
| EC\_CHECK\_SIGN    |                  | Yes1              | Signer ID is present, signature is present, signer is available, validity period falls within signer validity period, signature passes cryptographic validation.                                                                                                                  |
| EC\_CHECK\_CHAIN2  | EC\_CHECK\_SIGN  | Yes               | Certificate is not self-signed, signer also passes every check that certificate is required to pass, except for EC\_CHECK\_SECRET.                                                                                                                                                |
| EC\_CHECK\_ROLE    | EC\_CHECK\_CHAIN | Yes               | Grant records have a valid string key, grant records match or are a subset of the signer's grant records unless EC\_CERT\_TRUSTED is set, role records have a valid string key, role records match or are a subset of the signer's grant records unless EC\_CERT\_TRUSTED is set. |
| EC\_CHECK\_REQUIRE |                  | Yes               | A validator function has been set, all records with EC\_RECORD\_REQUIRE are considered acceptable by the validator.                                                                                                                                                               |
| EC\_CHECK\_ALL     |                  | Yes               | Every check listed above except for EC\_CHECK\_SECRET.                                                                                                                                                                                                                            |

1 Context is not required if the certificate is self-signed.\
2 `EC_CHECK_CHAIN` always passes if `EC_CERT_TRUSTED` is set on the certificate.

```c
#include <ec.h>
...
if(ec_cert_check(ctx, c, EC_CHECK_CERT | EC_CHECK_ROLE) != 0) {
    //certificate passes the defined checks
}
...
```

### ec\_cert\_id()

`ec_id_t ec_cert_id(ec_cert_t *c);`

Get a unique ID for a certificate. This ID is based on the certificate's public key, and will not change if the certificate is modified by e.g. signing, adding records etc.

This ID is used for things like retrieving a certificate from a context store, identifying a signer, etc.

```c
#include <ec.h>
...
ec_id_t id = ec_cert_id(c);
...
```

### ec\_cert\_records()

`ec_record_t *ec_cert_records(ec_cert_t *c);`

Get the records list for a certificate. Returns NULL if there are no records present.

```c
#include <ec.h>
...
ec_record_t *list = ec_cert_records(c);
if(list == NULL) {
    //no records present
}
...
```

### ec\_cert\_lock()

`ec_err_t ec_cert_lock(ec_cert_t *c, char *password);`

Encrypt a certificate's secret key using a password. Returns zero on success, or a nonzero error code otherwise.

If the secret key is encrypted successfully, EC\_CERT\_CRYPTSK will be set.

```c
#include <ec.h>
...
if(ec_cert_lock(c, "mySuperSecretPassword") != 0) {
    //unable to encrypt secret key
}
...
```

### ec\_cert\_unlock()

`ec_err_t ec_cert_unlock(ec_cert_t *c, char *password);`

Decrypt a certificate's secret key using a password. Returns zero on success, or a nonzero error code otherwise. If the secret key is not encrypted, then this function will take no action and return zero anyway.

If the secret key is decrypted successfully, then EC\_CERT\_CRYPTSK will be cleared.

Note that using an incorrect password is not considered an error, but the resulting secret key will be unusable, and any attempts to sign something with it will fail.

```c
#include <ec.h>
...
if(ec_cert_unlock(c, "mySuperSecretPassword") != 0) {
    //unable to decrypt secret key
}
...
```


# Records

Records are the fundamental unit used to store additional data attached to a certificate (e.g. roles, grants, user data, etc.) Records are key / value pairs. The key and value are both optional, and may contain either string or binary data.

Records are organised by section. Each section begins with a 'section header' record, which must use a NULL-terminated string containing the name of the section as its key.

Section names beginning with an underscore are reserved for internal use by the library.

If a section name is prefixed by '$', then all records in that section (including the section header) *must* be signed. Certificates containing a NOSIGN record in such a section will not validate.

## API

* [ec\_record\_create()](/records#ec-record-create)
* [ec\_record\_bin()](/records#ec-record-bin)
* [ec\_record\_str()](/records#ec-record-str)
* [ec\_record\_destroy()](/records#ec-record-destroy)
* [ec\_record\_add()](/records#ec-record-add)
* [ec\_record\_remove()](/records#ec-record-remove)
* [ec\_record\_remove\_section()](/records#ec-record-remove-section)
* [ec\_record\_match()](/records#ec-record-match)
* [ec\_record\_match\_bin()](/records#ec-record-match-bin)
* [ec\_record\_match\_str()](/records#ec-record-match-str)
* [ec\_record\_next()](/records#ec-record-next)
* [ec\_record\_set()](/records#ec-record-set)
* [ec\_record\_get()](/records#ec-record-get)
* [ec\_record\_section()](/records#ec-record-section)
* [ec\_record\_section\_flags()](/records#ec-record-section-flags)
* [ec\_record\_data()](/records#ec-record-data)
* [ec\_record\_buf()](/records#ec-record-buf)

### ec\_record\_create()

`ec_record_t *ec_record_create(uint16_t flags, char *key, unsigned char *data, uint16_t data_len);`

Create a new record. Returns a pointer to the new record, or NULL on failure. `key` must be a NULL-terminated string.

Records created with `ec_record_create()` must be freed using `ec_record_destroy()` once they are no longer required, unless they are attached to a certificate. All records attached to a certificate are automatically freed when the certificate is destroyed.

`flags` is used to set additional metadata on the record, according to the following table:

| Flag                | Meaning                                                                                                                                                                                                                                                                             |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| EC\_RECORD\_SECTION | Record is a section header.                                                                                                                                                                                                                                                         |
| EC\_RECORD\_REQUIRE | Client *must* understand this record. If it does not, the certificate must be treated as invalid.                                                                                                                                                                                   |
| EC\_RECORD\_INHERIT | If this record is a section header, then all records added to this section will inherit the same flags by default. Otherwise, this record will inherit its flags from the section header. Inheritance is defined as a bitwise OR with the section header for all inheritable flags. |
| EC\_RECORD\_NOSIGN  | This record will not be signed, and should be treated as untrustworthy. Intended for adding comments, internal metadata etc. to an already-signed certificate.                                                                                                                      |
| EC\_RECORD\_KFREE   | The key for this record will be automatically freed when the record is destroyed.                                                                                                                                                                                                   |
| EC\_RECORD\_KCOPY   | The key for this record will be copied, rather than added by reference. Implies EC\_RECORD\_KFREE.                                                                                                                                                                                  |
| EC\_RECORD\_DFREE   | The data for this record will be automatically freed when the record is destroyed.                                                                                                                                                                                                  |
| EC\_RECORD\_DCOPY   | The data for this record will be copied, rather than added by reference. Implies EC\_RECORD\_DFREE.                                                                                                                                                                                 |
| EC\_RECORD\_KALLOC  | Allocate and initialise to zero a new buffer for the key. The value of `key` is ignored.                                                                                                                                                                                            |
| EC\_RECORD\_DALLOC  | Allocate and initialise to zero a new buffer for the data. The value of `data` is ignored.                                                                                                                                                                                          |
| EC\_RECORD\_SIGNED  | Used only as a match filter. If this flag is set, records with NOSIGN will not match.                                                                                                                                                                                               |

```c
#include <ec.h>
...
ec_record_t *r = ec_record_create(EC_RECORD_NOSIGN | EC_RECORD_DCOPY, "my_key", my_data,
    my_data_length);
if(r == NULL) {
    //failed to create record
}
...
```

### ec\_record\_bin()

`ec_record_t *ec_record_bin(uint16_t flags, unsigned char *key, uint8_t key_len, unsigned char *data, uint16_t data_len);`

Identical to `ec_record_create()`, except using a binary key.

### ec\_record\_str()

`ec_record_t *ec_record_str(uint16_t flags, char *key, char *data);`

Identical to `ec_record_create()`, except data is a NULL-terminated string.

### ec\_record\_destroy()

`void ec_record_destroy(ec_record_t *r);`

Destroy a record. If EC\_RECORD\_KFREE / EC\_RECORD\_DFREE are set, then also free the record's key / data respectively.

```c
#include <ec.h>
...
ec_record_destroy(r);
...
```

### ec\_record\_add()

`ec_record_t *ec_record_add(ec_cert_t *c, char *section, ec_record_t *r);`

Add a record to a certificate. Returns `r` on success, NULL otherwise.

The record will be added to the section referred to by `section`, and the section will be created if it does not already exist. If `EC_RECORD_SECTION` is set, then `section` will be ignored and the record will be treated as a section header.

```c
#include <ec.h>
...
if(ec_record_add(c, "my_section", my_record) == NULL) {
    //failed to add record
}
...
```

### ec\_record\_remove()

`ec_record_t *ec_record_remove(ec_cert_t *c, ec_record_t *r);`

Remove a record from a certificate, if present. Always returns `r`.

```c
#include <ec.h>
...
ec_record_remove(c, r);
...
```

### ec\_record\_remove\_section()

`void ec_record_remove_section(ec_cert_t *c, char *section, ec_freefn_t freefn);`

Remove an entire section and all its child records from a certificate, if present.

If `freefn` is provided, it will be run once for each removed record, after that record is removed. If `freefn` is NULL, then nothing will be run on the removed records, and you should destroy them manually if they are no longer required.

```c
#include <ec.h>
...
ec_record_remove_section(c, "mySection", (ec_freefn_t)ec_record_destroy);
...
```

### ec\_record\_match()

`ec_record_t *ec_record_match(ec_record_t *start, char *section, uint16_t flags, char *key,`\
`unsigned char *data, uint16_t data_len);`

Find the first matching record in a record list. `key` must be a NULL-terminated string. All provided flags must be present in a record for it to match. `section` must be defined unless searching for a section header, in which case it should be NULL.

```c
#include <ec.h>
...
ec_record_t *list = ec_cert_records(c);
ec_record_t *r = ec_record_match(list, "my_section", EC_RECORD_NOSIGN,
    "my_record", NULL, 0);
if(r != NULL) {
    //found a matching record
}
...
```

### ec\_record\_match\_bin()

`ec_record_t *ec_record_match_bin(ec_record_t *start, char *section, uint16_t flags,`\
`unsigned char *key, uint8_t key_len, unsigned char *data, uint16_t data_len);`

Identical to `ec_record_match()`, except using a binary key.

### ec\_record\_match\_str()

`ec_record_t *ec_record_match_str(ec_record_t *start, char *section, uint16_t flags,`\
`char *key, char *data);`

Identical to `ec_record_match()`, except data is a NULL-terminated string.

### ec\_record\_next()

`ec_record_t *ec_record_next(ec_record_t *start, int filter);`

Get the next matching record in the same section. The next record that matches `start` is returned, or NULL if no matching record is found.

`filter` specifies which aspects of a record must match, according to the following table:

| Filter               | Description            |
| -------------------- | ---------------------- |
| EC\_MATCH\_FLAGS     | Flags must match       |
| EC\_MATCH\_KEY       | Key must match         |
| EC\_MATCH\_KEY\_LEN  | Key length must match  |
| EC\_MATCH\_DATA      | Data must match        |
| EC\_MATCH\_DATA\_LEN | Data length must match |

```c
#include <ec.h>
...
ec_record_t *next = ec_record_next(r, EC_MATCH_FLAGS | EC_MATCH_KEY);
if(next !== NULL) {
    //found a matching record
}
...
```

### ec\_record\_set()

`ec_record_t *ec_record_set(ec_cert_t *c, char *section, uint16_t flags, char *key, char *data);`

Identical to `ec_record_add(c, section, ec_record_str(flags, key, data));`

### ec\_record\_get()

`char *ec_record_get(ec_record_t *start, char *section, uint16_t flags, char *key);`

Get the NULL-terminated data field from a matching record. Returns NULL if not found, or if the data field is not NULL-terminated.

```c
#include <ec.h>
...
ec_record_t *list = ec_cert_records(c);
char *s = ec_record_get(list, "my_section", EC_RECORD_NOSIGN, "my_record");
if(s != NULL) {
    //found a valid matching string
}
...
```

### ec\_record\_section()

`char *ec_record_section(ec_record_t *r);`

Get the name for the section to which the record belongs. Returns the section name if present, or NULL if the record is not associated with a section, or is a section header.

```c
#include <ec.h>
...
char *section_name = ec_record_section(r);
if(section_name != NULL) {
    //record has a valid section name
}
...
```

### ec\_record\_section\_flags()

`void ec_record_section_flags(ec_cert_t *c, char *section, uint16_t flags);`

Bulk-set additional flags for an entire section, if the section exists.

```c
#include <ec.h>
...
ec_record_section_flags(c, "mySection", EC_CERT_NOSIGN);
...
```

### ec\_record\_data()

`unsigned char *ec_record_data(ec_record_t *r);`

Get a pointer to a record's data buffer. Returns NULL if `r` is NULL.

```c
#include <ec.h>
...
unsigned char *buf = ec_record_data(r);
...
```

### ec\_record\_buf()

`unsigned char *ec_record_buf(ec_cert_t *c, char *section, char *key, size_t length,`\
`uint16_t flags);`

Quickly get or create a record-backed buffer of at least `length` bytes. Returns NULL on error.

If the record already exists, but the buffer is smaller than `length`, or some of the `flags` are unset, this is considered an error. Otherwise, the existing record is used as-is without alteration, and the data buffer is returned.

If the record does not exist, then a new record is created with a zero-initialised buffer of the desired length, and `flags` will be added to the default.

```c
#include <ec.h>
...
unsigned char *buf = ec_record_buf(c, "mySection", "myRecord", 500, EC_RECORD_NOSIGN);
if(buf != NULL) {
    //successfully created a 500-byte buffer
}
...
```


# Contexts

Contexts are used to manage groups of certificates together. They contain a centralised configuration, and a pool of stored certificates.

Contexts are automatically used when checking a certificate's signer, trust chain, or grants & roles. In most cases, every certificate you create should be assigned to a context.

When a context is destroyed, all associated certificates are also destroyed at the same time.

## API

* [ec\_ctx\_create()](/contexts#ec-ctx-create)
* [ec\_ctx\_destroy()](/contexts#ec-ctx-destroy)
* [ec\_ctx\_autoload()](/contexts#ec-ctx-autoload)
* [ec\_ctx\_validator()](/contexts#ec-ctx-validator)
* [ec\_ctx\_next()](/contexts#ec-ctx-next)
* [ec\_ctx\_save()](/contexts#ec-ctx-save)
* [ec\_ctx\_remove()](/contexts#ec-ctx-remove)
* [ec\_ctx\_cert()](https://github.com/erayd/libec-doc/tree/f47c3e9a304777f09654e80a52051e695de22716/chapters/ec-ctx-cert/README.md)
* [ec\_ctx\_anchor()](/contexts#ec-ctx-anchor)

### ec\_ctx\_create()

`ec_ctx_t *ec_ctx_create(void);`

Creates a new context. Returns `NULL` on failure.

Contexts created using this function must be destroyed using `ec_ctx_destroy()` once they are no longer required.

```c
#include <ec.h>
...
ec_ctx_t *ctx = ec_ctx_create();
if(ctx != NULL) {
    //context created OK
}
...
```

### ec\_ctx\_destroy()

`void ec_ctx_destroy(ec_ctx_t *ctx);`

Destroys a context previously created with `ec_ctx_create()`.

```c
#include <ec.h>
...
ec_ctx_destroy(ctx);
...
```

### ec\_ctx\_autoload()

`typedef ec_cert_t *(*ec_autoload_t)(ec_id_t id);`\
`void ec_ctx_autoload(ec_ctx_t *ctx, ec_autoload_t autoload);`

Sets the autoload function that the context will use when trying to locate certificates it doesn't have available in its internal store.

This can be used to e.g. load certificates from disk, via a network connection etc.

```c
#include <ec.h>
...
ec_cert_t *my_autoloader(ec_id_t id) {
    ec_cert_t *c = //load cert from somewhere
    return c;
}
...
ec_ctx_autoload(ctx, my_autoloader);
...
```

### ec\_ctx\_validator()

`void ec_ctx_validator(ec_ctx_t *ctx, ec_record_validator_t validator);`

Sets the validator function used to check whether records with `EC_RECORD_REQUIRE` are acceptable. The validator function should return zero for acceptable, nonzero otherwise.

A validator function *must* be set in order to use `EC_CHECK_REQUIRE`. The validator must reject as failed any records it does not understand.

All arguments to the validator are guaranteed to be present and correct, and the certificate will have passed at least `EC_CHECK_CERT` before the validator is run.

```c
#include <ec.h>
...
int my_validator(ec_ctx_t *ctx, ec_cert_t *c, ec_record_t *r) {
    if(record_relates_to_goldfish(r))
        return 0;
    else
        return 1;
}
...
ec_ctx_validator(ctx, my_validator);
...
```

### ec\_ctx\_next()

`ec_ctx_t *ec_ctx_next(ec_ctx_t *ctx, ec_ctx_t *next);`

Sets the next context to search when attempting to load a certificate from the context's internal store. Always returns `next`.

This is used when trying to locate a certificate using `ec_ctx_cert()` which is not available in the context's internal store of via autoload.

```c
#include <ec.h>
...
ec_ctx_next(ctx, my_other_ctx);
...
```

### ec\_ctx\_save()

`ec_cert_t *ec_ctx_save(ec_ctx_t *ctx, ec_cert_t *c);`

Saves a certificate in the context's internal store, and returns a pointer to the certificate. Returns NULL on failure.

Saving a certificate transfers its ownership to the context, and it will be automatically freed when it is overwritten or when the context is destroyed. The user should ***not*** manually destroy certificates which have been saved in a context.

```c
#include <ec.h>
...
if(ec_ctx_save(ctx, c) == NULL) {
    //failed to save certificate
}
...
```

### ec\_ctx\_remove()

`ec_cert_t *ec_ctx_remove(ec_ctx_t *ctx, ec_id_t id);`

Remove a certificate from the context store. Returns the certificate if present, NULL otherwise.

Once a certificate has been removed from its context, the user is now responsible for destroying it with `ec_cert_destroy()` once it is no longer required.

```c
#include <ec.h>
...
ec_cert_t *c = ec_ctx_remove(ctx, my_cert_id);
if(c != NULL) {
    //certificate was present
}
...
```

### ec\_ctx\_cert()

`ec_cert_t *ec_ctx_cert(ec_ctx_t *ctx, ec_id_t id);`

Loads a certificate from the context's internal store. Returns NULL on failure (e.g. if a certificate is not found).

If an autoloader is defined, an attempt will be made to autoload the certificate if it is not already present in the store.

If an additional search context has been defined using `ec_ctx_next()`, that context will also be searched (*after* attempting to autoload).

```c
#include <ec.h>
...
ec_cert_t *c = ec_ctx_cert(c, my_cert_id);
if(c != NULL) {
    //certificate loaded OK
}
...
```

### ec\_ctx\_anchor()

`ec_cert_t *ec_ctx_anchor(ec_ctx_t *ctx, ec_cert_t *c);`

Get the trust anchor for a certificate. Returns NULL on failure.

If `c` does not pass EC\_CHECK\_CHAIN, this is considered an error. The same search method as `ec_ctx_cert()` is used to find the CA certificate.

```c
#include <ec.h>
...
ec_cert_t *ca = ec_ctx_anchor(ctx, c);
if(ca == NULL) {
    //unable to get CA
}
...
```


# Roles & Grants

Libec uses roles to implement a hierachal set of granular permissions attached to a certificate. This is intended to allow issuing certificates with various embedded permissions, which can be verified up to a trust root without needing to query any third party.

Roles are defined as a set of period-delimited strings, where each string is considered to be a child of the string to its left. The rightmost string may optionally be '\*' - this is a wildcard match.

As an example, the role of `com.example.myPond.goFishing` might allow the user to go fishing in the pond, but not feed the fish, or stir the water. In contrast, the role `com.example.myPond.*` would allow the user to do anything to the pond, or anything subordinate to it (i.e. the user is also considered to have `com.example.myPond.lilyPad.locateFrog`).

In order for a role to be considered valid, the certificate's signer must have either the same role, or a parent / wildcard role which matches it, defined as a grant. In order for a grant to be considered valid, the certificate's signer must have the same grant, or a parent / wildcard grant which matches it, defined as a grant.

This means that a certificate may also delegate granting authority for any role it is capable of granting.

A certificate with the flag `EC_CERT_TRUSTED` may define any role or grant, with no higher authority required to validate it. Such roles and grants must be explicitly defined in the certificate; by default a certificate defines nothing at all.

## API

* [ec\_role\_add()](/roles_and_grants#ec-role-add)
* [ec\_role\_grant()](/roles_and_grants#ec-role-grant)
* [ec\_role\_has()](/roles_and_grants#ec-role-has)
* [ec\_role\_has\_grant()](/roles_and_grants#ec-role-has-grant)

### ec\_role\_add()

`ec_record_t *ec_role_add(ec_cert_t *c, char *role);`

Add a role to a certificate. Returns the new role record on success, NULL otherwise. The created record will be automatically freed when the certificate is destroyed.

```c
#include <ec.h>
...
ec_record_t *r = ec_role_add(c, "com.example.myPond.goFishing");
if(r == NULL) {
    //failed to add role
}
...
```

### ec\_role\_grant()

`ec_record_t *ec_role_grant(ec_cert_t *c, char *role);`

Allow a certificate to grant a role. Returns the new grant record on success, NULL otherwise. The created record will be automatically freed when the certificate is destroyed.

```c
#include <ec.h>
...
ec_record_t *g = ec_role_grant(c, "com.example.myPond.*");
if(g == NULL) {
    //failed to add grant for role
}
...
```

### ec\_role\_has()

`ec_err_t ec_role_has(ec_cert_t *c, char *role);`

Check whether a certificate holds the given role. Returns EC\_OK on success, or a nonzero error code otherwise.

If the certificate holds a matching wildcard role, this is considered sufficient (e.g. if a certificate holds `com.example.*`, it is also considered to hold `com.example.myPond.goFishing`).

```c
#include <ec.h>
...
if(ec_role_has(c, "com.example.myPond") == EC_OK) {
    //certificate holds the com.example.myPond permission
}
...
```

### ec\_role\_has\_grant()

`ec_err_t ec_role_has_grant(ec_cert_t *c, char *role);`

Check whether a certificate is allowed to grant the given role. This does ***not*** imply that the certificate also holds this role; grants and roles may be held independantly.

If the certificate holds a matching wildcard grant, this is considered sufficient (e.g. if a certificate defines a grant for `com.example.*`, it may also grant `com.example.myPond.goFishing`).

```c
#include <ec.h>
...
if(ec_role_has_grant(c, "com.example.myPond.goFishing") == EC_OK) {
    //certificate may grant com.example.myPond.goFishing
}
...
```


# Export & Import

Certificates may be exported / imported in either binary or base64-encoded form. Binary is more efficient and should be used by default in most cases - base64 is intended for scenarios where a user may need to interact with the certificate directly (for example, pasting into a web form).

A certificate's secret key will ***not*** be exported unless EC\_EXPORT\_SECRET is set, but will always be imported if available.

## API

* [ec\_export\_len()](/export_and_import#ec-export-len)
* [ec\_export\_len\_64()](/export_and_import#ec-export-len-64)
* [ec\_export()](/export_and_import#ec-export)
* [ec\_export\_64()](/export_and_import#ec-export-64)
* [ec\_import()](/export_and_import#ec-import)
* [ec\_import\_64()](/export_and_import#ec-import-64)

### ec\_export\_len()

`uint16_t ec_export_len(ec_cert_t *c, uint8_t export_flags);`

Get the buffer length required to export a certificate with the given flags.

```c
#include <ec.h>
...
unsigned char buf[ec_export_len(c, EC_EXPORT_SECRET)];
...
```

### ec\_export\_len\_64

`size_t ec_export_len_64(ec_cert_t *c, uint8_t export_flags);`

Identical to `ec_export_len()`, except returns the buffer length required to export to base64.

### ec\_export()

`size_t ec_export(unsigned char *dest, ec_cert_t *c, uint8_t export_flags);`

Export a certificate to the given buffer. Returns the number of bytes written to the buffer, or zero on failure.

```c
#include <ec.h>
...
size_t bytes_written = ec_export(buf, c, EC_EXPORT_SECRET);
if(bytes_written == 0) {
    //failed to export certificate
}
...
```

### ec\_export\_64()

`char *ec_export_64(char *dest, ec_cert_t *c, uint8_t export_flags);`

Identical to `ec_export()`, except that the certificate is base64-encoded and armoured before writing to `dest`. Returns `dest` on success, or NULL on failure.

### ec\_import()

`ec_cert_t *ec_import(unsigned char *src, size_t length, size_t *consumed);`

Import a certificate from a buffer. Returns a certificate on success, or NULL otherwise.

If `consumed` is not NULL, then the number of bytes consumed from `src` will be stored there. On error, this value is considered undefined.

The certificate is tested with `EC_CHECK_CERT` before returning - if it does not pass, the import is considered to have failed and NULL is returned.

```c
#include <ec.h>
...
ec_cert_t *c = ec_import(buf, buf_size);
if(c != NULL) {
    //imported successfully
}
...
```

### ec\_import\_64()

`ec_cert_t *ec_import_64(char *src, size_t length, size_t *consumed);`

Identical to `ec_import()`, except interprets the buffer as armoured and base64-encoded. The certificate may be present at any offset in the buffer, provided that the envelope is intact.


# Channels

Libec uses channels to implement secure communication between two entities. Data is encrypted and protected with a MAC.

## API

* [ec\_channel\_clean()](/channels#ec-channel-clean)
* [ec\_channel\_init()](/channels#ec-channel-init)
* [ec\_channel\_start()](/channels#ec-channel-start)
* [ec\_channel\_encrypt()](/channels#ec-channel-encrypt)
* [ec\_channel\_decrypt()](/channels#ec-channel-decrypt)
* [ec\_channel\_remote()](/channels#ec-channel-remote)

### ec\_channel\_clean()

\`void ec\_channel\_clean(ec\_channel\_t \*ch);

Clean a previously used channel for reuse or free. Unlocks locked memory and zeros entire structure. Should be run once a channel is no longer required, before disposing of the channel.

```c
#include <ec.h>
...
ec_channel_clean(ch);
...
```

### ec\_channel\_init()

`ec_err_t ec_channel_init(ec_channel_t *ch, ec_cert_t *c, ec_ctx_t *ctx, unsigned char *dh);`

Initialise a channel and generate a signed Diffie-Hellman packet to pass to the remote endpoint. Returns zero on success, a nonzero error code otherwise. Once the channel is no longer required, it should be scrubbed using `ec_channel_clean()`.

`ctx` should point to a context where the remote certificate can be found, and will be used for validation purposes - if trust chain checks are performed, then those certificates will also need to be available.

`c` is the certificate used as the local endpoint. This certificate does *not* need to be available in `ctx`.

Data to be passed to the remote endpoint (the negotiation packet) will be stored in `dh`, which should be a buffer of at least `EC_CHANNEL_DH_BYTES` bytes. The contents of this buffer should be provided to `ec_channel_start()` on the remote end.

```c
#include <ec.h>
...
ec_channel_t *ch;
unsigned char dh[EC_CHANNEL_DH_BYTES];
if(ec_channel_init(ch, c, ctx, dh) != 0) {
    //init failed
}
...
```

### ec\_channel\_start()

`ec_err_t ec_channel_start(ec_channel_t *ch, unsigned char *dh, int checks);`

Finish Diffie-Hellman negotiation and finalise channel setup. Returns zero on success, a nonzero error code otherwise.

`dh` should contain the negotiation packet generated by `ec_channel_init()` on the remote end.

`checks` is a bitfield determining which checks should be run on the remote certificate. All checks must pass for channel setup to complete successfully. `EC_CHECK_CERT` and `EC_CHECK_SIGN` will always be tested, whether or not they are set.

```c
#include <ec.h>
...
if(ec_channel_start(ch, dh, EC_CHECK_ALL) != 0) {
    //negotiation failed
}
...
```

### ec\_channel\_encrypt()

`ec_err_t ec_channel_encrypt(ec_channel_t *ch, unsigned char *buf, size_t len,`\
`unsigned char *mac, uint64_t *ctr);`

Encrypt a buffer, for later decryption by the other end of a channel. Returns zero on success, a nonzero error code otherwise.

A MAC (`EC_CHANNEL_MAC_BYTES` bytes) for the message will be stored in `*mac`, and the message sequence number will be stored in `*ctr` if `ctr` is not NULL.

```c
#include <ec.h>
...
unsigned char mac[EC_CHANNEL_MAC_BYTES];
uint64_t ctr;
if(ec_channel_encrypt(ch, buf, buf_length, mac, &ctr) != 0) {
    //encryption failed
}
...
```

### ec\_channel\_decrypt()

`ec_err_t ec_channel_decrypt(ec_channel_t *ch, unsigned char *buf, size_t len,`\
`unsigned char *mac, uint64_t ctr);`

Decrypt a buffer previously encrypted by the other end of the channel. Returns zero on success, a nonzero error code otherwise.

`mac` should be the MAC generated by the other end of the channel using `ec_channel_encrypt()`.

If messages are not decrypted in linear order, then `ctr` should be set to the sequence number of the message being decrypted. Otherwise, this can be left at zero, and it will be set automatically.

```c
#include <ec.h>
...
if(ec_cert_decrypt(ch, buf, buf_length, mac, 0) != 0) {
    //decryption failed
}
...
```

### ec\_channel\_remote()

`ec_cert_t *ec_channel_remote(ec_channel_t *ch);`

Get the certificate for the remote channel endpoint. Returns NULL on failure.

```c
#include <ec.h>
...
ec_cert_t *c = ec_channel_remote(ch);
if(c == NULL) {
    //unable to get remote certificate
}
...
```


# Misc

Various functions which don't fit into any other category.

## API

* [ec\_init()](/misc#ec-init)
* [ec\_version()](/misc#ec-version)
* [ec\_errstr()](/misc#ec-errstr)

### ec\_init()

`ec_err_t ec_init(void);`

Initialises libec and its dependencies. Returns a nonzero error code on failure. `ec_init()` must be called before any other function in the library.

This function may be called more than once, but is not thread-safe.

```c
#include <ec/h>
...
if(ec_init() == 0) {
    //initialised OK
}
...
```

### ec\_version()

`char *ec_version(void);`

Returns the version of libec in use. This function is guaranteed to return a valid string.

```c
#include <ec.h>
...
printf("Libec version: %s\n", ec_version());
...
```

### ec\_errstr()

`char *ec_errstr(ec_err_t error);`

Get a string description for a libec error code.

```c
#include <ec.h>
...
printf("Error: %s\n", ec_errstr(error));
...
```


