Skip to content
pi-c Artifact [f9cf90143d]
Login

Artifact [f9cf90143d]

Artifact f9cf90143d503100b9f533a6eebf3007dcbd82b5b22a77f9fd9e89cf92d38c7f:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "bearssl.h"
#include "http.h"
#include "platform.h"
#include "webpush.h"

typedef unsigned char u8;

#define WEBPUSH_HEAD 86 /* salt (16), record size (4), key length (1), key (65) */
#define WEBPUSH_CLAIM_MAX 512

static void webpush_wipe(void *p, size_t n) {
    volatile u8 *v = p;
    while (n--) {
        *v++ = 0;
    }
}

static const char webpush_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

/* base64url without padding into OUT (4 * ceil(N / 3) + 1 bytes); its length. */
static size_t webpush_b64(const u8 *in, size_t n, char *out) {
    size_t o = 0;
    unsigned acc = 0;
    int bits = 0;
    for (size_t i = 0; i < n; i++) {
        acc = ((acc << 8) | in[i]) & 0xffffu;
        bits += 8;
        while (bits >= 6) {
            bits -= 6;
            out[o++] = webpush_alphabet[(acc >> bits) & 63];
        }
    }
    if (bits > 0) {
        out[o++] = webpush_alphabet[(acc << (6 - bits)) & 63];
    }
    out[o] = '\0';
    return o;
}

static void webpush_hmac(u8 out[32], const u8 *key, size_t kn, const void *a, size_t an, const void *b, size_t bn) {
    br_hmac_key_context kc;
    br_hmac_context c;
    br_hmac_key_init(&kc, &br_sha256_vtable, key, kn);
    br_hmac_init(&c, &kc, 0);
    br_hmac_update(&c, a, an);
    br_hmac_update(&c, b, bn);
    br_hmac_out(&c, out);
    webpush_wipe(&kc, sizeof kc);
    webpush_wipe(&c, sizeof c);
}

/* Whether PRIV is a P-256 scalar in [1, n - 1], in time that does not depend on its value. */
static int webpush_scalar_ok(const u8 priv[PIC_WEBPUSH_PRIV]) {
    static const u8 order[32] = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff,
                                 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17,
                                 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51};
    unsigned borrow = 0, any = 0;
    for (int i = 31; i >= 0; i--) {
        unsigned d = (unsigned)priv[i] - (unsigned)order[i] - borrow;
        borrow = (d >> 8) & 1u;
        any |= priv[i];
    }
    return (int)(borrow & (unsigned)(any != 0));
}

int pic_webpush_public(const unsigned char priv[PIC_WEBPUSH_PRIV], unsigned char pub[PIC_WEBPUSH_PUB]) {
    if (!webpush_scalar_ok(priv)) {
        return -1;
    }
    return br_ec_p256_m31.mulgen(pub, priv, PIC_WEBPUSH_PRIV, BR_EC_secp256r1) == PIC_WEBPUSH_PUB ? 0 : -1;
}

/* Splits an http or https URL: 0 with its parts (HOST lowercased), or -1. *EXPLICIT is 1 when a
 * port was written. */
static int webpush_url(const char *url, int *tls, char *host, size_t hostcap, int *port, int *explicit_port) {
    const char *p, *end;
    size_t n;
    if (strncmp(url, "https://", 8) == 0) {
        *tls = 1;
        p = url + 8;
    } else if (strncmp(url, "http://", 7) == 0) {
        *tls = 0;
        p = url + 7;
    } else {
        return -1;
    }
    end = p + strcspn(p, "/?#");
    if (memchr(p, '@', (size_t)(end - p))) {
        return -1;
    }
    *port = *tls ? 443 : 80;
    *explicit_port = 0;
    {
        const char *colon = NULL;
        const char *hend = end;
        if (*p == '[') {
            const char *rb = memchr(p, ']', (size_t)(end - p));
            if (!rb) {
                return -1;
            }
            hend = rb + 1;
            if (hend < end && *hend == ':') {
                colon = hend;
            } else if (hend != end) {
                return -1;
            }
        } else {
            colon = memchr(p, ':', (size_t)(end - p));
            if (colon) {
                hend = colon;
            }
        }
        if (colon) {
            long v = 0;
            const char *d = colon + 1;
            if (d == end || end - d > 5) {
                return -1;
            }
            for (; d < end; d++) {
                if (*d < '0' || *d > '9') {
                    return -1;
                }
                v = v * 10 + (*d - '0');
            }
            if (v < 1 || v > 65535) {
                return -1;
            }
            *port = (int)v;
            *explicit_port = 1;
        }
        n = (size_t)(hend - p);
    }
    if (n == 0 || n >= hostcap) {
        return -1;
    }
    for (size_t i = 0; i < n; i++) {
        char c = p[i];
        host[i] = c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
    }
    host[n] = '\0';
    return 0;
}

int pic_webpush_origin(const char *url, char *out, size_t cap) {
    char host[256];
    int tls, port, explicit_port, n;
    if (webpush_url(url, &tls, host, sizeof host, &port, &explicit_port) != 0) {
        return -1;
    }
    n = port == (tls ? 443 : 80) ? snprintf(out, cap, "%s://%s", tls ? "https" : "http", host)
                                 : snprintf(out, cap, "%s://%s:%d", tls ? "https" : "http", host, port);
    return n < 0 || (size_t)n >= cap ? -1 : n;
}

int pic_webpush_endpoint_ok(const char *endpoint) {
    char host[256];
    int tls, port, explicit_port, digits_only = 1;
    size_t label = 0;
    for (const char *c = endpoint; *c; c++) {
        if ((unsigned char)*c <= 0x20 || (unsigned char)*c >= 0x7f) {
            return 0;
        }
    }
    if (webpush_url(endpoint, &tls, host, sizeof host, &port, &explicit_port) != 0 || !tls || port != 443) {
        return 0;
    }
    /* A host name: dot-separated labels of letters, digits and hyphens, the last not all digits
     * (which leaves out IPv4 addresses; IPv6 ones fail at their bracket). */
    for (const char *c = host;; c++) {
        if (*c == '.' || *c == '\0') {
            if (label == 0 || label > 63) {
                return 0;
            }
            if (*c == '\0') {
                break;
            }
            label = 0;
            digits_only = 1;
            continue;
        }
        if (!((*c >= 'a' && *c <= 'z') || (*c >= '0' && *c <= '9') || *c == '-')) {
            return 0;
        }
        digits_only = digits_only && *c >= '0' && *c <= '9';
        label++;
    }
    return !digits_only;
}

static int webpush_claim_ok(const char *s) {
    size_t n = strlen(s);
    if (n == 0 || n > WEBPUSH_CLAIM_MAX) {
        return 0;
    }
    for (size_t i = 0; i < n; i++) {
        unsigned char c = (unsigned char)s[i];
        if (c < 0x20 || c == 0x7f || c == '"' || c == '\\') {
            return 0;
        }
    }
    return 1;
}

int pic_webpush_authorization(const unsigned char priv[PIC_WEBPUSH_PRIV], const char *aud, int64_t exp,
                              const char *subject, char *out, size_t cap) {
    static const char header[] = "{\"typ\":\"JWT\",\"alg\":\"ES256\"}";
    char claims[2 * WEBPUSH_CLAIM_MAX + 64];
    char *token;
    u8 pub[PIC_WEBPUSH_PUB], hash[32], sig[64], key[PIC_WEBPUSH_PRIV];
    br_ec_private_key sk = {BR_EC_secp256r1, key, sizeof key};
    br_sha256_context sc;
    size_t tn, need;
    int cn, rc = -1;
    if (!webpush_claim_ok(aud) || !webpush_claim_ok(subject) || pic_webpush_public(priv, pub) != 0) {
        return -1;
    }
    cn = snprintf(claims, sizeof claims, "{\"aud\":\"%s\",\"exp\":%lld,\"sub\":\"%s\"}", aud, (long long)exp, subject);
    if (cn < 0 || (size_t)cn >= sizeof claims) {
        return -1;
    }
    /* "vapid t=" header "." claims "." sig ", k=" pub */
    need = 8 + 4 * ((sizeof header - 1 + 2) / 3) + 1 + 4 * (((size_t)cn + 2) / 3) + 1 + 86 + 4 + 87 + 1;
    token = malloc(need);
    if (!token) {
        return -1;
    }
    memcpy(token, "vapid t=", 8);
    tn = 8;
    tn += webpush_b64((const u8 *)header, sizeof header - 1, token + tn);
    token[tn++] = '.';
    tn += webpush_b64((const u8 *)claims, (size_t)cn, token + tn);
    br_sha256_init(&sc);
    br_sha256_update(&sc, token + 8, tn - 8);
    br_sha256_out(&sc, hash);
    memcpy(key, priv, sizeof key);
    if (br_ecdsa_i31_sign_raw(&br_ec_p256_m31, &br_sha256_vtable, hash, &sk, sig) == sizeof sig) {
        token[tn++] = '.';
        tn += webpush_b64(sig, sizeof sig, token + tn);
        memcpy(token + tn, ", k=", 4);
        tn += 4;
        tn += webpush_b64(pub, sizeof pub, token + tn);
        if (tn < cap) {
            memcpy(out, token, tn + 1);
            rc = (int)tn;
        }
    }
    webpush_wipe(key, sizeof key);
    webpush_wipe(&sc, sizeof sc);
    free(token);
    return rc;
}

size_t pic_webpush_encrypt(const unsigned char as_priv[PIC_WEBPUSH_PRIV], const unsigned char salt[PIC_WEBPUSH_SALT],
                           const unsigned char ua_pub[PIC_WEBPUSH_PUB], const unsigned char auth[PIC_WEBPUSH_AUTH],
                           const void *pt, size_t len, unsigned char *out) {
    u8 as_pub[PIC_WEBPUSH_PUB], shared[PIC_WEBPUSH_PUB], prk_key[32], ikm[32], prk[32], cek[32], nonce[32];
    u8 info[14 + 2 * PIC_WEBPUSH_PUB + 1];
    br_aes_ct_ctr_keys aes;
    br_gcm_context gcm;
    size_t n = 0;
    if (len > PIC_WEBPUSH_MAX || ua_pub[0] != 0x04 || pic_webpush_public(as_priv, as_pub) != 0) {
        return 0;
    }
    memcpy(shared, ua_pub, sizeof shared);
    /* mul validates that the point is on the curve; the scalar was checked above. */
    if (!br_ec_p256_m31.mul(shared, sizeof shared, as_priv, PIC_WEBPUSH_PRIV, BR_EC_secp256r1)) {
        webpush_wipe(shared, sizeof shared);
        return 0;
    }
    webpush_hmac(prk_key, auth, PIC_WEBPUSH_AUTH, shared + 1, 32, NULL, 0);
    memcpy(info, "WebPush: info", 14); /* with its 0x00 */
    memcpy(info + 14, ua_pub, PIC_WEBPUSH_PUB);
    memcpy(info + 14 + PIC_WEBPUSH_PUB, as_pub, PIC_WEBPUSH_PUB);
    info[sizeof info - 1] = 0x01;
    webpush_hmac(ikm, prk_key, sizeof prk_key, info, sizeof info, NULL, 0);
    webpush_hmac(prk, salt, PIC_WEBPUSH_SALT, ikm, sizeof ikm, NULL, 0);
    webpush_hmac(cek, prk, sizeof prk, "Content-Encoding: aes128gcm\0\1", 29, NULL, 0);
    webpush_hmac(nonce, prk, sizeof prk, "Content-Encoding: nonce\0\1", 25, NULL, 0);

    memcpy(out, salt, PIC_WEBPUSH_SALT);
    memcpy(out + 16, "\x00\x00\x10\x00", 4); /* record size 4096 */
    out[20] = PIC_WEBPUSH_PUB;
    memcpy(out + 21, as_pub, PIC_WEBPUSH_PUB);
    if (len > 0) {
        memcpy(out + WEBPUSH_HEAD, pt, len);
    }
    out[WEBPUSH_HEAD + len] = 0x02; /* the last record's delimiter */
    br_aes_ct_ctr_init(&aes, cek, 16);
    br_gcm_init(&gcm, &aes.vtable, br_ghash_ctmul32);
    br_gcm_reset(&gcm, nonce, 12);
    br_gcm_flip(&gcm);
    br_gcm_run(&gcm, 1, out + WEBPUSH_HEAD, len + 1);
    br_gcm_get_tag(&gcm, out + WEBPUSH_HEAD + len + 1);
    n = len + PIC_WEBPUSH_OVERHEAD;

    webpush_wipe(shared, sizeof shared);
    webpush_wipe(prk_key, sizeof prk_key);
    webpush_wipe(ikm, sizeof ikm);
    webpush_wipe(prk, sizeof prk);
    webpush_wipe(cek, sizeof cek);
    webpush_wipe(nonce, sizeof nonce);
    webpush_wipe(&aes, sizeof aes);
    webpush_wipe(&gcm, sizeof gcm);
    return n;
}

void pic_webpush_topic(const unsigned char auth[PIC_WEBPUSH_AUTH], const char *session, char out[PIC_WEBPUSH_TOPIC]) {
    u8 mac[32];
    webpush_hmac(mac, auth, PIC_WEBPUSH_AUTH, "pic-rc/1 topic", 15, session, strlen(session));
    (void)webpush_b64(mac, 16, out);
    webpush_wipe(mac, sizeof mac);
}

static int webpush_topic_ok(const char *topic) {
    size_t n = strlen(topic);
    if (n == 0 || n > 32) {
        return 0;
    }
    for (size_t i = 0; i < n; i++) {
        if (!strchr(webpush_alphabet, topic[i])) {
            return 0;
        }
    }
    return 1;
}

/* Seconds from a Retry-After that is a number of them, else -1 (an HTTP date is not read). */
static long webpush_retry_after(const char *v) {
    long s = 0;
    size_t n = strlen(v);
    if (n == 0 || n > 9) {
        return -1;
    }
    for (size_t i = 0; i < n; i++) {
        if (v[i] < '0' || v[i] > '9') {
            return -1;
        }
        s = s * 10 + (v[i] - '0');
    }
    return s;
}

static int webpush_done(pic_webpush_result *res, pic_webpush_outcome outcome, int status, const char *err) {
    res->outcome = outcome;
    res->status = status;
    if (err) {
        (void)snprintf(res->err, sizeof res->err, "%s", err);
    }
    return outcome == PIC_WEBPUSH_SENT ? 0 : -1;
}

int pic_webpush_send(pic_net *net, const pic_webpush_sub *sub, const pic_webpush_vapid *vapid, const char *topic,
                     const void *payload, size_t len, int ttl, pic_webpush_result *res) {
    const pic_platform *plat = pic_platform_get();
    char aud[300], auth_h[16 + 2400], ttl_h[32], topic_h[48], err[160];
    const char *headers[6];
    size_t nh = 0, body_n;
    u8 as_priv[PIC_WEBPUSH_PRIV], salt[PIC_WEBPUSH_SALT], *body;
    pic_http_resp r;
    int64_t now_ns;
    int rc, tries = 0;
    memset(res, 0, sizeof *res);
    res->retry_after = -1;
    if (len > PIC_WEBPUSH_MAX) {
        return webpush_done(res, PIC_WEBPUSH_TOO_LARGE, 0, "the payload is too large for one push");
    }
    if (topic && !webpush_topic_ok(topic)) {
        return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "the topic is not 1 to 32 base64url characters");
    }
    if (pic_webpush_origin(sub->endpoint, aud, sizeof aud) < 0) {
        return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "the endpoint is not an http or https address");
    }
    if ((now_ns = plat->wall_ns()) < 0) {
        return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "the date is unknown");
    }
    memcpy(auth_h, "Authorization: ", 15);
    if (pic_webpush_authorization(vapid->priv, aud, now_ns / 1000000000 + PIC_WEBPUSH_EXPIRY, vapid->subject,
                                  auth_h + 15, sizeof auth_h - 15) < 0) {
        return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "cannot make the VAPID token");
    }
    /* A new key pair and salt for every push. */
    do {
        if (plat->entropy(as_priv, sizeof as_priv) != 0 || plat->entropy(salt, sizeof salt) != 0) {
            webpush_wipe(as_priv, sizeof as_priv);
            return webpush_done(res, PIC_WEBPUSH_FAILED, 0, "cannot get random bytes");
        }
    } while (!webpush_scalar_ok(as_priv) && ++tries < 8);
    body = malloc(len + PIC_WEBPUSH_OVERHEAD);
    body_n = body ? pic_webpush_encrypt(as_priv, salt, sub->p256dh, sub->auth, payload, len, body) : 0;
    webpush_wipe(as_priv, sizeof as_priv);
    webpush_wipe(salt, sizeof salt);
    if (body_n == 0) {
        free(body);
        return webpush_done(res, PIC_WEBPUSH_FAILED, 0,
                            body ? "the subscription's key is not a P-256 public key" : "out of memory");
    }
    (void)snprintf(ttl_h, sizeof ttl_h, "TTL: %d", ttl < 0 ? 0 : ttl);
    headers[nh++] = ttl_h;
    headers[nh++] = "Urgency: normal";
    if (topic) {
        (void)snprintf(topic_h, sizeof topic_h, "Topic: %s", topic);
        headers[nh++] = topic_h;
    }
    headers[nh++] = "Content-Encoding: aes128gcm";
    headers[nh++] = "Content-Type: application/octet-stream";
    headers[nh++] = auth_h;
    pic_http_resp_init(&r, NULL, NULL);
    err[0] = '\0';
    rc = pic_http_post(net, sub->endpoint, headers, nh, (const char *)body, body_n, &r, 15, 30, err, sizeof err);
    webpush_wipe(body, body_n);
    free(body);
    webpush_wipe(auth_h, sizeof auth_h);
    if (rc != 0) {
        return webpush_done(res, PIC_WEBPUSH_FAILED, 0, err[0] ? err : "the push service did not answer");
    }
    (void)snprintf(err, sizeof err, "the push service answered %d", r.status);
    switch (r.status) {
    case 201:
        return webpush_done(res, PIC_WEBPUSH_SENT, r.status, NULL);
    case 404:
    case 410:
        return webpush_done(res, PIC_WEBPUSH_GONE, r.status, err);
    case 413:
        return webpush_done(res, PIC_WEBPUSH_TOO_LARGE, r.status, err);
    case 429:
        res->retry_after = webpush_retry_after(r.retry_after);
        return webpush_done(res, PIC_WEBPUSH_RETRY, r.status, err);
    default:
        return webpush_done(res, PIC_WEBPUSH_FAILED, r.status, err);
    }
}