Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-tls

Source of release 0.7.1

0.7.1 / src / chain.lucb

## Server certificate path validation for TLS (RFC 5280 ยง6 as profiled by the
## CA/Browser Forum): the leaf from a TLS 1.3 Certificate message is checked
## for the host name, validity and usage, and a path is built from it to any
## trust anchor through the other presented certificates, in any order. Each
## issuer must be a valid CA (basicConstraints, keyUsage, EKU, pathLen) whose
## signature verifies (ECDSA P-256/P-384, RSA PKCS#1 v1.5 or PSS). Extra,
## duplicate or unparsable certificates that no path needs are ignored.
## No revocation checking and no policy processing.
from luce_crypto import native as crypto
import anchors
import certificate
import signature
from tls import hostname_matches

pub let invalid = crypto.invalid
pub let max_certificates: usize = 10
pub let max_chain_bytes: usize = 65536
let max_depth: usize = 6

## ISRG Root X2, SHA-256 certificate fingerprint
## 69:72:9B:8E:15:A8:6E:FC:17:7A:57:AF:B7:17:1D:FC:
## 64:AD:D2:8C:2F:CA:8C:F1:50:7E:34:45:3C:CB:14:70.
## Source: https://letsencrypt.org/certs/isrg-root-x2.pem
pub let isrg_root_x2_x = b"\xcd\x9b\xd5\x9f\x80\x83\x0a\xec\x09\x4a\xf3\x16\x4a\x3e\x5c\xcf\x77\xac\xde\x67\x05\x0d\x1d\x07\xb6\xdc\x16\xfb\x5a\x8b\x14\xdb\xe2\x71\x60\xc4\xba\x45\x95\x11\x89\x8e\xea\x06\xdf\xf7\x2a\x16"
pub let isrg_root_x2_y = b"\x1c\xa4\xb9\xc5\xc5\x32\xe0\x03\xe0\x1e\x82\x18\x38\x8b\xd7\x45\xd8\x0a\x6a\x6e\xe6\x00\x77\xfb\x02\x51\x7d\x22\xd8\x0a\x6e\x9a\x5b\x77\xdf\xf0\xfa\x41\xec\x39\xdc\x75\xca\x68\x07\x0c\x1f\xea"

## The presented certificates and the state of one path search.
struct Search:
    var message: const u8[]
    var start: usize[10]
    var end: usize[10]
    var count: usize
    var now: i64
    var reason: str

    func der(i: usize) -> const u8[]:
        return self.message[self.start[i]..<self.end[i]]

## Validate a complete TLS 1.3 Certificate handshake message for `host` at
## Unix time `now` against `trusted`, and return the authenticated leaf key.
## CertificateEntry extensions must be empty, as the client requests none.
pub func verify_server_chain(message: const u8[], host: str, now: i64, trusted: const anchors.Anchors*) -> signature.PublicKey!:
    if host.length == 0:
        error(invalid, "a server certificate needs a host name to match")
    return try verify(message, host, now, trusted)

## The same validation without the host-name check, for path-validation test
## suites that have no server name. TLS clients use `verify_server_chain`.
pub func verify_chain_without_name(message: const u8[], now: i64, trusted: const anchors.Anchors*) -> signature.PublicKey!:
    return try verify(message, "", now, trusted)

func verify(message: const u8[], host: str, now: i64, trusted: const anchors.Anchors*) -> signature.PublicKey!:
    var search = Search(message = message, now = now, reason = "no trusted root issued the certificate chain")
    try split(message, &search)
    let leaf_der = search.der(0)
    let leaf = try certificate.parse(leaf_der)
    try validate_leaf(leaf_der, &leaf, host, now)
    if not (try extend(&search, trusted, &leaf, 0, 1, 0, 0)):
        error(invalid, search.reason)
    return try leaf.public_key(leaf_der)

func u24(data: const u8[], at: usize) -> usize:
    return ((usize)data[at] << 16) | ((usize)data[at + 1] << 8) | (usize)data[at + 2]

## Locate each certificate in the message.
func split(message: const u8[], search: Search*) -> !:
    if message.length < 12 or message[0] != 11 or u24(message, 1) != message.length - 4:
        error(invalid, "invalid TLS Certificate handshake message")
    if message[4] != 0:
        error(invalid, "unexpected TLS certificate request context")
    let list = u24(message, 5)
    if list == 0 or list > max_chain_bytes or list != message.length - 8:
        error(invalid, "invalid TLS certificate_list length")
    var pos: usize = 8
    while pos < message.length:
        if search.count >= max_certificates or message.length - pos < 5:
            error(invalid, "too many or truncated TLS certificates")
        let size = u24(message, pos)
        pos += 3
        if size == 0 or size > certificate.max_certificate_bytes or size > message.length - pos:
            error(invalid, "invalid TLS certificate length")
        search.start[search.count] = pos
        search.end[search.count] = pos + size
        search.count += 1
        pos += size
        if message.length - pos < 2:
            error(invalid, "truncated TLS CertificateEntry extensions")
        if message[pos] != 0 or message[pos + 1] != 0:
            error(invalid, "unexpected TLS CertificateEntry extensions")
        pos += 2

func validate_leaf(bytes: const u8[], leaf: const certificate.Certificate*, host: str, now: i64) -> !:
    if not leaf.valid_at(now):
        error(invalid, "the server certificate is expired or not yet valid")
    if leaf.basic_present and leaf.is_ca:
        error(invalid, "the server certificate is a CA certificate")
    if leaf.key_usage_present and not leaf.digital_signature:
        error(invalid, "the server certificate keyUsage excludes digitalSignature")
    if leaf.eku_present and not leaf.server_auth:
        error(invalid, "the server certificate extendedKeyUsage excludes TLS servers")
    if leaf.algorithm == 0:
        error(invalid, "the server certificate uses an unsupported signature algorithm")
    if host.length != 0 and not matches_dns_name(bytes, leaf, host):
        error(invalid, "the server certificate does not match the host name")

## Whether a subjectAltName dNSName matches `host` (no common-name fallback).
pub func matches_dns_name(bytes: const u8[], cert: const certificate.Certificate*, host: str) -> bool:
    var pos = cert.san_start
    while pos + 2 <= cert.san_end:
        let tag = bytes[pos]
        var length = (usize)bytes[pos + 1]
        var header: usize = 2
        if length >= 0x80:
            let count = length & 0x7f
            if count == 0 or count > 2 or pos + 2 + count > cert.san_end:
                return false
            length = 0
            for i in 0..<count:
                length = (length << 8) | (usize)bytes[pos + 2 + i]
            header += count
        if pos + header + length > cert.san_end:
            return false
        if tag == 0x82 and hostname_matches((str)bytes[pos + header..<pos + header + length], host):
            return true
        pos += header + length
    return false

## Whether `issuer` may issue under the CA rules, with `ca_below` non-self-
## issued intermediates already between it and the leaf.
func acceptable_ca(issuer: const certificate.Certificate*, ca_below: usize, now: i64, search: Search*) -> bool:
    if not issuer.valid_at(now):
        search.reason = "an intermediate certificate is expired or not yet valid"
        return false
    if not issuer.basic_present or not issuer.is_ca:
        search.reason = "an issuing certificate is not a CA"
        return false
    if issuer.key_usage_present and not issuer.key_cert_sign:
        search.reason = "an issuing certificate cannot sign certificates"
        return false
    if issuer.eku_present and not issuer.server_auth:
        search.reason = "an issuing certificate excludes TLS server authentication"
        return false
    if issuer.path_len_present and ca_below > issuer.path_len:
        search.reason = "a pathLenConstraint was exceeded"
        return false
    return true

## Try to finish a path above `child` (certificate `child_index`): first by a
## trust anchor, then through each unused presented CA certificate.
func extend(search: Search*, trusted: const anchors.Anchors*, child: const certificate.Certificate*, child_index: usize,
    used: u32, depth: usize, ca_below: usize) -> bool!:
    let child_der = search.der(child_index)
    let issuer_name = child.issuer(child_der)
    for i in 0..<trusted.count():
        let subject = trusted.subject(i)
        if subject.length == 0 or crypto.equal(subject, issuer_name):
            let key = try trusted.key_at(i)
            if try child.signed_by(child_der, &key):
                return true
            search.reason = "a certificate signature does not verify under its trusted root"
    if depth + 1 >= max_depth:
        search.reason = "the certificate chain is too long"
        return false
    for i in 1..<search.count:
        if (used & ((u32)1 << (u32)i)) != 0:
            continue
        let issuer_der = search.der(i)
        let issuer = certificate.parse(issuer_der) catch: continue
        if not crypto.equal(issuer.subject(issuer_der), issuer_name):
            continue
        if not acceptable_ca(&issuer, ca_below, search.now, search):
            continue
        let key = try issuer.public_key(issuer_der)
        if not (try child.signed_by(child_der, &key)):
            search.reason = "a certificate signature does not verify under its issuer"
            continue
        let below = ca_below if issuer.self_issued(issuer_der) else ca_below + 1
        if try extend(search, trusted, &issuer, i, used | ((u32)1 << (u32)i), depth + 1, below):
            return true
    return false