Skip to content
pi-c Documentation
Login

Documentation

/* Remote control's cryptography against test/pic/remote-vectors.json (docs/design/remote-protocol.md,
 * section 8): the file's hash, the derivations, both handshakes in both roles, the transport, VAPID
 * and Web Push; and the refusals: a flipped bit anywhere in a message 1, the wrong psk, a key off
 * the curve, the wrong channel, a replayed or reordered counter. Usage: test_noise VECTORS.JSON */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "bearssl.h"
#include "noise.h"
#include "sqlite3.h"

#define VECTORS_SHA256 "fa895483624944e6f7e36b690bc3344a19e6755c270d49d10c4a876869e0e4ab"

static sqlite3 *mem;
static char *doc;

/* The vectors' string at PATH (static until the next call). */
static const char *v(const char *path) {
    static char out[65536];
    sqlite3_stmt *q = NULL;
    assert(sqlite3_prepare_v2(mem, "SELECT json_extract(?1, ?2)", -1, &q, NULL) == SQLITE_OK);
    sqlite3_bind_text(q, 1, doc, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
    assert(sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0));
    (void)snprintf(out, sizeof out, "%s", (const char *)sqlite3_column_text(q, 0));
    sqlite3_finalize(q);
    return out;
}

static size_t unhex(const char *s, unsigned char *out) {
    size_t n = 0;
    for (; s[0] && s[1]; s += 2) {
        unsigned x;
        assert(sscanf(s, "%2x", &x) == 1);
        out[n++] = (unsigned char)x;
    }
    return n;
}

static void hexs(const unsigned char *b, size_t n, char *out) {
    for (size_t i = 0; i < n; i++) {
        (void)snprintf(out + 2 * i, 3, "%02x", b[i]);
    }
    out[2 * n] = '\0';
}

static void same_hex(const char *what, const unsigned char *b, size_t n, const char *path) {
    char got[2 * PIC_NOISE_RECORD_CAP + 1];
    hexs(b, n, got);
    if (strcmp(got, v(path)) != 0) {
        fprintf(stderr, "%s: got %s\n    want %s\n", what, got, v(path));
        exit(1);
    }
}

static void seqkey(unsigned char *b, int first) {
    for (int i = 0; i < 32; i++) {
        b[i] = (unsigned char)(first + i);
    }
}

static void test_file_hash(const char *text, size_t n) {
    unsigned char d[32];
    char h[65];
    pic_noise_sha256(d, text, n, NULL, 0);
    hexs(d, 32, h);
    if (strcmp(h, VECTORS_SHA256) != 0) {
        fprintf(stderr, "remote-vectors.json changed: sha256 %s, the tests expect %s\n", h, VECTORS_SHA256);
        exit(1);
    }
    puts("ok vectors file hash");
}

static void test_derive(void) {
    unsigned char owner[32], dev[32], ps[32], psk[32], tok[32], ch[16], mb[16], dc[16], offer[PIC_NOISE_OFFER], back[16];
    unsigned char pub[65], ps2[32];
    pic_noise_keypair pic;
    uint64_t exp = 0;
    char url[512], b64[200];
    seqkey(owner, 0x10);
    seqkey(dev, 0x30);
    seqkey(ps, 0xc1);
    pic_noise_id(mb, "pic-rc/1 mailbox", owner);
    same_hex("mailbox", mb, 16, "$.derive.mailbox");
    pic_noise_pair_derive(ps, psk, tok, ch);
    same_hex("psk", psk, 32, "$.derive.psk");
    same_hex("pair token", tok, 32, "$.derive.pair_token");
    same_hex("pair channel", ch, 16, "$.derive.pair_channel");
    pic_noise_id(dc, "pic-rc/1 channel", dev);
    same_hex("device channel", dc, 16, "$.derive.device_channel");
    {
        unsigned char k[32];
        seqkey(k, 0x01);
        assert(pic_noise_keypair_make(&pic, k) == 0);
    }
    same_hex("pic static public", pic.pub, 65, "$.keys.pic_static_public");
    pic_noise_offer(mb, pic.pub, ps, 1800000000u, offer);
    same_hex("offer", offer, sizeof offer, "$.offer.bytes");
    pic_b64u_enc(offer, sizeof offer, b64);
    (void)snprintf(url, sizeof url, "https://relay.example/#p1.%s", b64);
    assert(strcmp(url, v("$.offer.url")) == 0);
    assert(pic_noise_offer_read(offer, sizeof offer, back, pub, ps2, &exp) == 0);
    assert(memcmp(back, mb, 16) == 0 && memcmp(pub, pic.pub, 65) == 0 && memcmp(ps2, ps, 32) == 0 && exp == 1800000000u);
    offer[0] = 2;
    assert(pic_noise_offer_read(offer, sizeof offer, back, pub, ps2, &exp) == -1);
    puts("ok derivations and the offer");
}

/* One handshake of the vectors, at PFX ("$.pairing" or "$.session"): both roles reproduce both
 * records, the hash and the keys, and each reads the vector's record of the other. */
static void handshake(const char *pfx, int psk_mode, pic_noise_transport *up_t, pic_noise_transport *down_t) {
    unsigned char picp[32], php[32], ie[32], re[32], prologue[64], psk[32], sid[8], m[2048], rec[2048], pl[512];
    unsigned char up[32], down[32], up2[32], down2[32];
    pic_noise_keypair pic, phone;
    pic_noise_hs I, R;
    size_t pn, mn, rn, n;
    char path[96], p1[512], p2[512];
    seqkey(picp, 0x01);
    seqkey(php, 0x21);
    assert(pic_noise_keypair_make(&pic, picp) == 0 && pic_noise_keypair_make(&phone, php) == 0);
#define P(x) ((void)snprintf(path, sizeof path, "%s.%s", pfx, x), path)
    pn = unhex(v(P("prologue")), prologue);
    unhex(v(P("phone_ephemeral_private")), ie);
    unhex(v(P("pic_ephemeral_private")), re);
    unhex(v(P("sid")), sid);
    unhex(v("$.derive.psk"), psk);
    (void)snprintf(p1, sizeof p1, "%s", v(P("payload1")));
    (void)snprintf(p2, sizeof p2, "%s", v(P("payload2")));
    pic_noise_hs_init(&I, 1, &phone, pic.pub, psk_mode ? psk : NULL, prologue, pn);
    pic_noise_hs_init(&R, 0, &pic, NULL, psk_mode ? psk : NULL, prologue, pn);
    assert(pic_noise_hs_ephemeral(&I, ie) == 0 && pic_noise_hs_ephemeral(&R, re) == 0);
    assert(pic_noise_write1(&I, p1, strlen(p1), m, sizeof m, &mn) == 0);
    rn = pic_noise_head(PIC_NOISE_REC_M1, sid, m, mn, rec);
    same_hex("record1", rec, rn, P("record1"));
    /* the responder reads the vector's record, not ours */
    rn = unhex(v(P("record1")), rec);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == 0);
    assert(n == strlen(p1) && memcmp(pl, p1, n) == 0 && memcmp(R.rs, phone.pub, 65) == 0);
    assert(pic_noise_write2(&R, p2, strlen(p2), m, sizeof m, &mn) == 0);
    rn = pic_noise_head(PIC_NOISE_REC_M2, sid, m, mn, rec);
    same_hex("record2", rec, rn, P("record2"));
    rn = unhex(v(P("record2")), rec);
    assert(pic_noise_read2(&I, rec + 9, rn - 9, pl, sizeof pl, &n) == 0);
    assert(n == strlen(p2) && memcmp(pl, p2, n) == 0);
    same_hex("handshake hash", I.h, 32, P("handshake_hash"));
    assert(memcmp(I.h, R.h, 32) == 0);
    pic_noise_split(&I, up, down);
    pic_noise_split(&R, up2, down2);
    assert(memcmp(up, up2, 32) == 0 && memcmp(down, down2, 32) == 0);
    same_hex("key up", up, 32, P("key_up"));
    same_hex("key down", down, 32, P("key_down"));
    if (psk_mode) {
        char sas[7];
        pic_noise_sas(I.h, sas);
        assert(strcmp(sas, v("$.pairing.sas")) == 0);
    }
    pic_noise_transport_init(up_t, 1, sid, up, down);   /* the phone's */
    pic_noise_transport_init(down_t, 0, sid, up, down); /* pic's */
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
#undef P
}

static void transport_pair(const char *pfx, const char *name, pic_noise_transport *sender, pic_noise_transport *reader) {
    unsigned char rec[PIC_NOISE_RECORD_CAP], out[PIC_NOISE_CHUNK];
    char path[96], plain[512];
    size_t rn, n;
    int flag, gap;
    (void)snprintf(path, sizeof path, "%s.%s_plain", pfx, name);
    (void)snprintf(plain, sizeof plain, "%s", v(path));
    rn = pic_noise_record(sender, 1, plain, strlen(plain), rec);
    (void)snprintf(path, sizeof path, "%s.%s", pfx, name);
    same_hex(path, rec, rn, path);
    rn = unhex(v(path), rec);
    assert(pic_noise_open_record(reader, rec, rn, &flag, out, &n, &gap) == 0);
    assert(flag == 1 && n == strlen(plain) && memcmp(out, plain, n) == 0);
    /* the same record again is a replay, dropped */
    assert(pic_noise_open_record(reader, rec, rn, &flag, out, &n, &gap) == -1);
}

static void test_pairing(void) {
    pic_noise_transport phone, pic;
    handshake("$.pairing", 1, &phone, &pic);
    transport_pair("$.pairing", "up0", &phone, &pic);
    transport_pair("$.pairing", "down0", &pic, &phone);
    puts("ok pairing handshake, code and first transport records");
}

static void test_session(void) {
    pic_noise_transport phone, pic;
    unsigned char rec[PIC_NOISE_RECORD_CAP], out[PIC_NOISE_CHUNK], d[32], sid[8], big[20000];
    size_t rn, n;
    int flag, gap;
    handshake("$.session", 0, &phone, &pic);
    transport_pair("$.session", "up0", &phone, &pic);
    transport_pair("$.session", "down0", &pic, &phone);
    /* n 7 down: the phone sees a gap */
    pic.send_n = 7;
    transport_pair("$.session", "down7", &pic, &phone);
    /* a 20000-byte message as two records, n 1 and 2 up */
    memset(big, 0x61, sizeof big);
    rn = pic_noise_record(&phone, 0, big, PIC_NOISE_CHUNK, rec);
    pic_noise_sha256(d, rec, rn, NULL, 0);
    same_hex("fragment 1", d, 32, "$.session.fragmented.sha256_of_records[0]");
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == 0 && flag == 0 && n == PIC_NOISE_CHUNK && !gap);
    {
        unsigned char rec2[PIC_NOISE_RECORD_CAP];
        size_t rn2 = pic_noise_record(&phone, 1, big + PIC_NOISE_CHUNK, sizeof big - PIC_NOISE_CHUNK, rec2);
        pic_noise_sha256(d, rec2, rn2, NULL, 0);
        same_hex("fragment 2", d, 32, "$.session.fragmented.sha256_of_records[1]");
        assert(pic_noise_open_record(&pic, rec2, rn2, &flag, out, &n, &gap) == 0 && flag == 1 &&
               n == sizeof big - PIC_NOISE_CHUNK && !gap);
        /* reordered: the older record after the newer is dropped */
        assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == -1);
    }
    /* a gap: n 4 after 2 */
    phone.send_n = 4;
    rn = pic_noise_record(&phone, 1, "{}", 2, rec);
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == 0 && gap == 1);
    /* one bit changed anywhere in a transport record: dropped, nothing changed */
    rn = pic_noise_record(&phone, 1, "{\"type\":\"ping\"}", 15, rec);
    for (size_t i = 0; i < rn; i++) {
        for (int b = 0; b < 8; b++) {
            int64_t was = pic.last;
            rec[i] ^= (unsigned char)(1u << b);
            assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == -1);
            assert(pic.last == was);
            rec[i] ^= (unsigned char)(1u << b);
        }
    }
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == 0);
    /* counters stop at 2^32, as the page's do: 2^32 - 1 is taken, 2^32 is dropped */
    phone.send_n = (1ull << 32) - 1;
    rn = pic_noise_record(&phone, 1, "{}", 2, rec);
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == 0);
    rn = pic_noise_record(&phone, 1, "{}", 2, rec);
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == -1);
    unhex(v("$.session.sid"), sid);
    rn = pic_noise_head(PIC_NOISE_REC_RESET, sid, NULL, 0, rec);
    same_hex("reset", rec, rn, "$.session.reset");
    puts("ok session handshake, transport counters, fragments, gaps and reset");
}

/* The refusals of section 8 for message 1: each leaves a fresh responder unable to read it. */
static void test_refusals(void) {
    unsigned char picp[32], prologue[64], psk[32], rec[2048], pl[512], bad[32];
    pic_noise_keypair pic;
    pic_noise_hs R;
    size_t pn, rn, n;
    seqkey(picp, 0x01);
    assert(pic_noise_keypair_make(&pic, picp) == 0);
    pn = unhex(v("$.pairing.prologue"), prologue);
    unhex(v("$.derive.psk"), psk);
    rn = unhex(v("$.pairing.record1"), rec);
    /* one bit changed anywhere in the Noise message */
    for (size_t i = 9; i < rn; i++) {
        rec[i] ^= 0x10;
        pic_noise_hs_init(&R, 0, &pic, NULL, psk, prologue, pn);
        assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
        rec[i] ^= 0x10;
    }
    /* the wrong psk */
    memcpy(bad, psk, 32);
    bad[31] ^= 1;
    pic_noise_hs_init(&R, 0, &pic, NULL, bad, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
    /* the wrong channel: another prologue */
    prologue[pn - 1] ^= 1;
    pic_noise_hs_init(&R, 0, &pic, NULL, psk, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
    prologue[pn - 1] ^= 1;
    /* an ephemeral key not on the curve */
    rec[9 + 64] ^= 1;
    {
        unsigned char k[65];
        memcpy(k, rec + 9, 65);
        assert(!pic_noise_pub_valid(k));
    }
    pic_noise_hs_init(&R, 0, &pic, NULL, psk, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
    rec[9 + 64] ^= 1;
    /* a session message 1 (no psk) is not a pairing message 1 */
    pic_noise_hs_init(&R, 0, &pic, NULL, NULL, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
    /* and the untouched record still reads */
    pic_noise_hs_init(&R, 0, &pic, NULL, psk, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == 0);
    /* an initiator whose static key is off the curve cannot even be written to */
    {
        unsigned char off[65];
        memcpy(off, pic.pub, 65);
        off[64] ^= 1;
        assert(!pic_noise_pub_valid(off));
    }
    puts("ok refusals: flipped bits, wrong psk, wrong channel, off-curve key, wrong protocol");
}

static void test_vapid(void) {
    unsigned char vp[32], sig[64];
    pic_noise_keypair k;
    char input[512], jwt[700], b64[100], pubs[100];
    seqkey(vp, 0x51);
    assert(pic_noise_keypair_make(&k, vp) == 0);
    pic_b64u_enc(k.pub, 65, pubs);
    assert(strcmp(pubs, v("$.vapid.public")) == 0);
    {
        char h[100], c[300];
        const char *head = v("$.vapid.header");
        pic_b64u_enc((const unsigned char *)head, strlen(head), h);
        (void)snprintf(input, sizeof input, "%s.", h);
        {
            const char *claims = v("$.vapid.claims");
            pic_b64u_enc((const unsigned char *)claims, strlen(claims), c);
        }
        (void)snprintf(input + strlen(input), sizeof input - strlen(input), "%s", c);
    }
    assert(pic_noise_es256(vp, input, sig) == 0);
    pic_b64u_enc(sig, 64, b64);
    (void)snprintf(jwt, sizeof jwt, "%s.%s", input, b64);
    assert(strcmp(jwt, v("$.vapid.jwt")) == 0);
    puts("ok VAPID token");
}

static void b64(const char *s, unsigned char *out, size_t want) {
    long n = pic_b64u_dec(s, strlen(s), out, 4096);
    assert(n == (long)want);
}

static void test_push(void) {
    unsigned char ua[32], as[32], salt[16], auth[16], body[4096], t[32];
    pic_noise_keypair uak, ask;
    char enc[8192], topic[64];
    const char *pt;
    size_t n;
    seqkey(ua, 0x71);
    seqkey(as, 0x91);
    unhex(v("$.push.salt"), salt);
    b64(v("$.push.auth"), auth, 16);
    assert(pic_noise_keypair_make(&uak, ua) == 0 && pic_noise_keypair_make(&ask, as) == 0);
    pt = v("$.push.plaintext");
    {
        char copy[512];
        (void)snprintf(copy, sizeof copy, "%s", pt);
        n = pic_noise_webpush(&ask, salt, uak.pub, auth, copy, strlen(copy), body);
    }
    assert(n > 0);
    pic_b64u_enc(body, n, enc);
    assert(strcmp(enc, v("$.push.body")) == 0);
    {
        static const char label[] = "pic-rc/1 topic";
        unsigned char in[64];
        memcpy(in, label, sizeof label); /* with its NUL: the 0x00 */
        memcpy(in + sizeof label, "w1/c1", 5);
        pic_noise_hmac(t, auth, 16, in, sizeof label + 5, NULL, 0);
        pic_b64u_enc(t, 16, topic);
        assert(strcmp(topic, v("$.push.topic")) == 0);
    }
    /* RFC 8291 appendix A */
    {
        unsigned char uap[32], asp[32], rsalt[16], rauth[16];
        const char *msg = "When I grow up, I want to be a watermelon";
        b64("q1dXpw3UpT5VOmu_cf_v6ih07Aems3njxI-JWgLcM94", uap, 32);
        b64("yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw", asp, 32);
        b64("DGv6ra1nlYgDCS1FRnbzlw", rsalt, 16);
        b64("BTBZMqHH6r4Tts7J_aSIgg", rauth, 16);
        assert(pic_noise_keypair_make(&uak, uap) == 0 && pic_noise_keypair_make(&ask, asp) == 0);
        n = pic_noise_webpush(&ask, rsalt, uak.pub, rauth, msg, strlen(msg), body);
        pic_b64u_enc(body, n, enc);
        assert(strcmp(enc, v("$.rfc8291_appendix_a.body")) == 0);
    }
    puts("ok Web Push body, topic and RFC 8291 appendix A");
}

static void test_b64u(void) {
    unsigned char out[8];
    assert(pic_b64u_dec("AQ", 2, out, sizeof out) == 1 && out[0] == 1);
    assert(pic_b64u_dec("AR", 2, out, sizeof out) == -1); /* nonzero leftover bits */
    assert(pic_b64u_dec("A", 1, out, sizeof out) == -1);
    assert(pic_b64u_dec("A+", 2, out, sizeof out) == -1);
    assert(pic_b64u_dec("AAAAAAAAAAAA", 12, out, sizeof out) == -1); /* 9 bytes in 8 */
    puts("ok base64url");
}

int main(int argc, char **argv) {
    FILE *f;
    long n;
    assert(argc == 2);
    assert((f = fopen(argv[1], "rb")) != NULL);
    assert(fseek(f, 0, SEEK_END) == 0 && (n = ftell(f)) > 0 && fseek(f, 0, SEEK_SET) == 0);
    assert((doc = malloc((size_t)n + 1)) != NULL && fread(doc, 1, (size_t)n, f) == (size_t)n);
    doc[n] = '\0';
    fclose(f);
    assert(sqlite3_open(":memory:", &mem) == SQLITE_OK);
    test_file_hash(doc, (size_t)n);
    test_b64u();
    test_derive();
    test_pairing();
    test_session();
    test_refusals();
    test_vapid();
    test_push();
    sqlite3_close(mem);
    free(doc);
    puts("ok all remote vectors");
    return 0;
}