Artifact e05410694de1713b0c7f0aed12de5699bebcf86dd86e47aa5bd97114501ddf4c:
- File
src/cred.c
— part of check-in
[9dabe49948]
at
2026-11-21 19:00:33
on branch amalgam
— Amalgamation: pic as one pic.c beside the vendored sources, built by one cc line
make amalgamation writes pic-amalgamation-VERSION/ and its tarball; make test-amal builds it from the README's own line and runs crash, print and tools against that binary, and is part of make test-pic. About 60 file-local names that collided in one translation unit take their file's prefix; test/pic/amalgam.sh fails on a new collision. (user: dmestas, size: 19375) [annotate] [blame] [check-ins using] [more...]
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/resource.h> #include <unistd.h> #include "bearssl.h" #include "cred.h" #include "platform.h" #include "userdb.h" /* PBKDF2-HMAC-SHA256 for a passphrase: OWASP's 2023 floor for this KDF. * Nothing memory-hard is vendored; the count is stored per store, so it can * rise later without breaking an old one. */ #define KDF_NAME "pbkdf2-sha256" #define KDF_ITERATIONS 600000u #define SALT_BYTES 16 #define VERIFIER_TEXT "pic credential store" /* AADs: the verifier's and a provider key's live in separate namespaces * (a provider is bound as "key:NAME"), so no provider name can make one * pass for the other. */ #define VERIFIER_AAD "verifier:picu_credential_key" #define KEY_AAD "key:" #define SECRET_CAP 512 static unsigned char master[PIC_CRED_KEY]; static int unlocked; static unsigned char handed[PIC_CRED_KEY]; /* a key a parent handed over, not yet checked */ static int have_handed; static int wipe_registered; void pic_cred_wipe(void *p, size_t n) { volatile unsigned char *v = p; while (n--) { *v++ = 0; } } static void wipe_all(void) { pic_cred_wipe(master, sizeof master); pic_cred_wipe(handed, sizeof handed); unlocked = have_handed = 0; } void pic_cred_lock(void) { wipe_all(); } /* Host only: once a master key or a plaintext key is in memory, no core * dump may carry it. */ static void no_core(void) { struct rlimit rl = {0, 0}; (void)setrlimit(RLIMIT_CORE, &rl); } /* The AAD a provider's key is sealed under. */ static void key_aad(const char *provider, char *out, size_t cap) { (void)snprintf(out, cap, KEY_AAD "%s", provider); } static void remember(const unsigned char key[PIC_CRED_KEY]) { no_core(); memcpy(master, key, PIC_CRED_KEY); unlocked = 1; if (!wipe_registered) { wipe_registered = 1; (void)atexit(wipe_all); } } /* ---- primitives ---------------------------------------------------------- */ /* The one source of nonces and salts: the platform's entropy (the OS RNG on * a host), at most 256 bytes a call. */ static int random_bytes(void *buf, size_t n) { return pic_platform_get()->entropy(buf, n); } int pic_cred_seal(const unsigned char key[PIC_CRED_KEY], const char *aad, const void *pt, size_t n, unsigned char *out) { unsigned char *nonce = out, *body = out + PIC_CRED_NONCE, *tag = out + PIC_CRED_NONCE + n; if (random_bytes(nonce, PIC_CRED_NONCE) != 0) { return -1; } memcpy(body, pt, n); br_poly1305_ctmul_run(key, nonce, body, n, aad, strlen(aad), tag, br_chacha20_ct_run, 1); return 0; } int pic_cred_open(const unsigned char key[PIC_CRED_KEY], const char *aad, const unsigned char *in, size_t n, void *pt) { unsigned char tag[PIC_CRED_TAG], diff = 0; size_t len; if (n < PIC_CRED_OVERHEAD) { return -1; } len = n - PIC_CRED_OVERHEAD; memcpy(pt, in + PIC_CRED_NONCE, len); br_poly1305_ctmul_run(key, in, pt, len, aad, strlen(aad), tag, br_chacha20_ct_run, 0); for (size_t i = 0; i < PIC_CRED_TAG; i++) { diff |= (unsigned char)(tag[i] ^ in[PIC_CRED_NONCE + len + i]); } if (diff != 0) { pic_cred_wipe(pt, len); return -1; } return 0; } void pic_cred_kdf(const void *pass, size_t n, const unsigned char *salt, size_t saltn, uint32_t iterations, unsigned char out[PIC_CRED_KEY]) { br_hmac_key_context kc; br_hmac_context hc; unsigned char u[PIC_CRED_KEY], one[4] = {0, 0, 0, 1}; br_hmac_key_init(&kc, &br_sha256_vtable, pass, n); br_hmac_init(&hc, &kc, 0); br_hmac_update(&hc, salt, saltn); br_hmac_update(&hc, one, 4); br_hmac_out(&hc, u); memcpy(out, u, PIC_CRED_KEY); for (uint32_t i = 1; i < iterations; i++) { br_hmac_init(&hc, &kc, 0); br_hmac_update(&hc, u, sizeof u); br_hmac_out(&hc, u); for (size_t k = 0; k < PIC_CRED_KEY; k++) { out[k] ^= u[k]; } } pic_cred_wipe(u, sizeof u); pic_cred_wipe(&kc, sizeof kc); pic_cred_wipe(&hc, sizeof hc); } /* ---- the master key ------------------------------------------------------ */ static long long cred_now_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); } /* The secret from the platform's source, as a 32-byte key: stretched when it * is a passphrase. 0, or -1 with err. */ static int source_key(int fresh, const unsigned char *salt, size_t saltn, uint32_t iterations, unsigned char key[PIC_CRED_KEY], char *err, size_t errcap) { const pic_platform *p = pic_platform_get(); unsigned char secret[SECRET_CAP]; size_t len = 0; int stretch = 1, rc = -1; char why[200] = ""; if (!p->secret_key) { (void)snprintf(err, errcap, "this build has no source for the credential store's key"); return -1; } if (p->secret_key(fresh, secret, sizeof secret, &len, &stretch, why, sizeof why) != 0) { (void)snprintf(err, errcap, "cannot unlock the credential store: %s", why[0] ? why : "no key"); } else if (stretch) { pic_cred_kdf(secret, len, salt, saltn, iterations, key); rc = 0; } else if (len == PIC_CRED_KEY) { memcpy(key, secret, PIC_CRED_KEY); rc = 0; } else { (void)snprintf(err, errcap, "the credential store's key source gave a key of the wrong size"); } pic_cred_wipe(secret, sizeof secret); return rc; } /* Makes the store's master key: a salt, the key from the source (asked * twice), and the verifier. 0, or -1 with err. */ static int create(sqlite3 *db, char *err, size_t errcap) { unsigned char salt[SALT_BYTES], key[PIC_CRED_KEY], verifier[sizeof VERIFIER_TEXT - 1 + PIC_CRED_OVERHEAD]; sqlite3_stmt *q = NULL; int rc = -1; if (random_bytes(salt, sizeof salt) != 0) { (void)snprintf(err, errcap, "no entropy for the credential store's salt"); return -1; } if (source_key(1, salt, sizeof salt, KDF_ITERATIONS, key, err, errcap) != 0) { return -1; } if (pic_cred_seal(key, VERIFIER_AAD, VERIFIER_TEXT, sizeof VERIFIER_TEXT - 1, verifier) != 0) { (void)snprintf(err, errcap, "no entropy for a nonce"); } else if (sqlite3_prepare_v2(db, "INSERT INTO picu_credential_key(id, source, kdf, iterations, salt, verifier, created_ms)" " VALUES(1, 'passphrase', ?1, ?2, ?3, ?4, ?5)", -1, &q, NULL) != SQLITE_OK) { (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db)); } else { sqlite3_bind_text(q, 1, KDF_NAME, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 2, KDF_ITERATIONS); sqlite3_bind_blob(q, 3, salt, sizeof salt, SQLITE_STATIC); sqlite3_bind_blob(q, 4, verifier, sizeof verifier, SQLITE_STATIC); sqlite3_bind_int64(q, 5, cred_now_ms()); if (sqlite3_step(q) == SQLITE_DONE) { remember(key); rc = 0; } else { (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db)); } } sqlite3_finalize(q); pic_cred_wipe(key, sizeof key); return rc; } /* Unlocks the store: 0; 1 when it has no master key yet (CREATE 0); -1 with * err. */ static int unlock(int create_if_new, char *err, size_t errcap) { sqlite3 *db = pic_userdb(err, errcap); sqlite3_stmt *q = NULL; unsigned char key[PIC_CRED_KEY], check[sizeof VERIFIER_TEXT - 1]; int rc = -1, step; if (unlocked) { return 0; } if (!db) { return -1; } if (sqlite3_prepare_v2(db, "SELECT kdf, iterations, salt, verifier FROM picu_credential_key WHERE id = 1", -1, &q, NULL) != SQLITE_OK) { (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db)); return -1; } step = sqlite3_step(q); if (step == SQLITE_DONE) { sqlite3_finalize(q); if (create_if_new) { return create(db, err, errcap); } (void)snprintf(err, errcap, "the credential store has no master key record (picu_credential_key)"); return 1; } if (step != SQLITE_ROW) { (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db)); } else if (strcmp((const char *)sqlite3_column_text(q, 0), KDF_NAME) != 0 || sqlite3_column_int64(q, 1) < 1 || sqlite3_column_int64(q, 1) > 100000000) { (void)snprintf(err, errcap, "the credential store uses a key derivation this pic does not know"); } else if ((size_t)sqlite3_column_bytes(q, 3) != sizeof check + PIC_CRED_OVERHEAD) { (void)snprintf(err, errcap, "the credential store's verifier is damaged"); } else { const unsigned char *salt = sqlite3_column_blob(q, 2), *verifier = sqlite3_column_blob(q, 3); int got, from_parent = have_handed; if (have_handed) { memcpy(key, handed, sizeof key); pic_cred_wipe(handed, sizeof handed); have_handed = 0; got = 0; } else { got = source_key(0, salt, (size_t)sqlite3_column_bytes(q, 2), (uint32_t)sqlite3_column_int64(q, 1), key, err, errcap); } if (got == 0) { if (pic_cred_open(key, VERIFIER_AAD, verifier, sizeof check + PIC_CRED_OVERHEAD, check) == 0) { remember(key); rc = 0; } else { (void)snprintf(err, errcap, from_parent ? "the key handed over by the parent pic does not open the credential store" : "wrong passphrase for the credential store"); } } } sqlite3_finalize(q); pic_cred_wipe(key, sizeof key); pic_cred_wipe(check, sizeof check); return rc; } int pic_cred_unlock(char *err, size_t errcap) { int rc = unlock(0, err, errcap); if (rc == 1) { (void)snprintf(err, errcap, "no key is stored yet: run `pic login PROVIDER`"); return -1; } return rc; } /* ---- rows ---------------------------------------------------------------- */ int pic_cred_check(const char *what, const char *key, char *err, size_t errcap) { size_t n = strlen(key); if (n == 0) { (void)snprintf(err, errcap, "%s is empty", what); return -1; } if (n >= PIC_CRED_KEY_CAP) { (void)snprintf(err, errcap, "%s is longer than %d bytes", what, PIC_CRED_KEY_CAP - 1); return -1; } for (size_t i = 0; i < n; i++) { if ((unsigned char)key[i] < 0x21 || (unsigned char)key[i] > 0x7e) { (void)snprintf(err, errcap, "%s has a character that cannot go in a header", what); return -1; } } return 0; } int pic_cred_stored(const char *provider) { sqlite3 *db = pic_userdb(NULL, 0); sqlite3_stmt *q = NULL; int found = 0; if (db && sqlite3_prepare_v2(db, "SELECT 1 FROM picu_credential WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC); found = sqlite3_step(q) == SQLITE_ROW; } sqlite3_finalize(q); return found; } int pic_cred_login(const char *provider, const char *key, char *err, size_t errcap) { sqlite3 *db; sqlite3_stmt *q = NULL; char aad[sizeof KEY_AAD + 128]; unsigned char *box; size_t n = strlen(key); int rc = -1; if (!provider || !*provider) { (void)snprintf(err, errcap, "no provider named"); return -1; } if (pic_cred_check("the key", key, err, errcap) != 0 || unlock(1, err, errcap) != 0 || !(db = pic_userdb(err, errcap))) { return -1; } if (!(box = malloc(n + PIC_CRED_OVERHEAD))) { (void)snprintf(err, errcap, "out of memory"); return -1; } no_core(); key_aad(provider, aad, sizeof aad); if (pic_cred_seal(master, aad, key, n, box) != 0) { (void)snprintf(err, errcap, "no entropy for a nonce"); } else if (sqlite3_prepare_v2(db, "INSERT INTO picu_credential(name, kind, sealed, created_ms) VALUES(?1, 'api_key', ?2, ?3)" " ON CONFLICT(name) DO UPDATE SET kind = excluded.kind, sealed = excluded.sealed," " created_ms = excluded.created_ms, used_ms = NULL", -1, &q, NULL) != SQLITE_OK) { (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db)); } else { sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC); sqlite3_bind_blob(q, 2, box, (int)(n + PIC_CRED_OVERHEAD), SQLITE_STATIC); sqlite3_bind_int64(q, 3, cred_now_ms()); if (sqlite3_step(q) == SQLITE_DONE) { rc = 0; } else { (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db)); } } sqlite3_finalize(q); free(box); return rc; } int pic_cred_logout(const char *provider) { sqlite3 *db = pic_userdb(NULL, 0); sqlite3_stmt *q = NULL; int rc = -1; if (db && sqlite3_prepare_v2(db, "DELETE FROM picu_credential WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC); rc = sqlite3_step(q) == SQLITE_DONE ? sqlite3_changes(db) > 0 : -1; } sqlite3_finalize(q); return rc; } int pic_cred_each(int (*fn)(void *ctx, const char *name, long long created_ms, long long used_ms), void *ctx) { sqlite3 *db = pic_userdb(NULL, 0); sqlite3_stmt *q = NULL; if (!db || sqlite3_prepare_v2(db, "SELECT name, created_ms, coalesce(used_ms, 0) FROM picu_credential" " ORDER BY created_ms, name", -1, &q, NULL) != SQLITE_OK) { return -1; } while (sqlite3_step(q) == SQLITE_ROW && !fn(ctx, (const char *)sqlite3_column_text(q, 0), sqlite3_column_int64(q, 1), sqlite3_column_int64(q, 2))) { } sqlite3_finalize(q); return 0; } /* PROVIDER's stored key into buf: 0; 1 none stored; -1 with err. */ static int stored_key(const char *provider, char *buf, size_t cap, char *err, size_t errcap) { sqlite3 *db; sqlite3_stmt *q = NULL; char aad[sizeof KEY_AAD + 128]; int rc = -1, locked; if (!pic_cred_stored(provider)) { return 1; } if ((locked = unlock(0, err, errcap)) != 0 || !(db = pic_userdb(err, errcap))) { if (locked == 1) { /* rows, but nothing to open them with */ (void)snprintf(err, errcap, "the credential store has a key for %s but no master key record (picu_credential_key), so it" " cannot be opened: run `pic logout %s`, then `pic login %s`", provider, provider, provider); } return -1; } if (sqlite3_prepare_v2(db, "SELECT sealed FROM picu_credential WHERE name = ?1", -1, &q, NULL) != SQLITE_OK) { (void)snprintf(err, errcap, "the credential store: %s", sqlite3_errmsg(db)); return -1; } sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC); if (sqlite3_step(q) != SQLITE_ROW) { rc = 1; } else { size_t n = (size_t)sqlite3_column_bytes(q, 0); if (n < PIC_CRED_OVERHEAD || n - PIC_CRED_OVERHEAD >= cap) { (void)snprintf(err, errcap, "the stored key for %s is damaged: run `pic login %s` again", provider, provider); } else if ((key_aad(provider, aad, sizeof aad), no_core(), pic_cred_open(master, aad, sqlite3_column_blob(q, 0), n, buf)) != 0) { (void)snprintf(err, errcap, "the stored key for %s does not open: run `pic login %s` again", provider, provider); } else { buf[n - PIC_CRED_OVERHEAD] = '\0'; rc = pic_cred_check("the stored key", buf, err, errcap) == 0 ? 0 : -1; if (rc != 0) { pic_cred_wipe(buf, cap); } } } sqlite3_finalize(q); if (rc == 0 && sqlite3_prepare_v2(db, "UPDATE picu_credential SET used_ms = ?2 WHERE name = ?1", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, provider, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 2, cred_now_ms()); (void)sqlite3_step(q); sqlite3_finalize(q); } return rc; } int pic_cred_get(const char *provider, const char *env, const char *literal, char *buf, size_t cap, char *err, size_t errcap) { const char *value = literal && *literal ? literal : NULL; const char *what = value ? "the models file's apiKey" : env; size_t n; if (!value && env && *env) { value = getenv(env); value = value && *value ? value : NULL; } if (!value) { char why[256] = ""; int got = provider && *provider ? stored_key(provider, buf, cap, why, sizeof why) : 1; if (got == 0) { return 0; } if (got < 0) { (void)snprintf(err, errcap, "%s", why); return -1; } if (!env || !*env) { return 1; /* nothing configured and nothing stored: a server that needs no key */ } (void)snprintf(err, errcap, "%s is not set and no key is stored for %s: run `pic login %s`", env, provider && *provider ? provider : "this provider", provider && *provider ? provider : "PROVIDER"); return -1; } n = strlen(value); if (n >= cap) { (void)snprintf(err, errcap, "%s is longer than %zu bytes", what, cap - 1); return -1; } if (pic_cred_check(what, value, err, errcap) != 0) { return -1; } memcpy(buf, value, n + 1); return 0; } int pic_cred_needs_unlock(const char *provider, const char *env, const char *literal) { const char *v = env && *env ? getenv(env) : NULL; if (unlocked || (literal && *literal) || (v && *v) || !provider || !*provider) { return 0; } return pic_cred_stored(provider); } /* ---- handing the key to a child ------------------------------------------ */ int pic_cred_handoff(void) { int fds[2]; ssize_t w; if (!unlocked || pipe(fds) != 0) { return -1; } do { w = write(fds[1], master, sizeof master); } while (w < 0 && errno == EINTR); close(fds[1]); if (w != (ssize_t)sizeof master) { close(fds[0]); return -1; } (void)fcntl(fds[0], F_SETFD, FD_CLOEXEC); return fds[0]; } void pic_cred_adopt(void) { const char *v = getenv("PIC_KEY_FD"); char *end; long fd; size_t got = 0; if (!v) { return; } fd = strtol(v, &end, 10); if (*end || fd < 3 || fd > 65535) { fd = -1; } (void)unsetenv("PIC_KEY_FD"); /* frees v */ if (fd < 0) { return; } while (got < sizeof handed) { ssize_t r = read((int)fd, handed + got, sizeof handed - got); if (r < 0 && errno == EINTR) { continue; } if (r <= 0) { break; } got += (size_t)r; } close((int)fd); have_handed = got == sizeof handed; if (!have_handed) { pic_cred_wipe(handed, sizeof handed); } }