Skip to main content

countersign_native/
lib.rs

1//! Electron-main-only native operations. Provider entry points are private to this crate.
2use base64::{
3    Engine,
4    engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
5};
6use countersign_protocol::{Origin, wire::*};
7use napi_derive::napi;
8use serde_json::{Value, json};
9use sha2::{Digest, Sha256};
10use std::collections::HashMap;
11use std::sync::{Arc, LazyLock, Mutex};
12use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
13use tokio::sync::Semaphore;
14use x509_parser::{prelude::*, public_key::PublicKey};
15
16#[cfg(target_os = "linux")]
17mod linux;
18#[cfg(target_os = "linux")]
19use linux as platform;
20#[cfg(target_os = "windows")]
21mod windows;
22#[cfg(target_os = "windows")]
23use windows as platform;
24#[cfg(target_os = "macos")]
25mod macos;
26#[cfg(target_os = "macos")]
27use macos as platform;
28
29type NativeResult<T> = std::result::Result<T, String>;
30
31fn clock_ms() -> NativeResult<u64> {
32    Ok(SystemTime::now()
33        .duration_since(UNIX_EPOCH)
34        .map_err(|_| "system clock unavailable")?
35        .as_millis() as u64)
36}
37fn random_id() -> NativeResult<String> {
38    let mut bytes = [0u8; 16];
39    getrandom::fill(&mut bytes).map_err(|_| "random generator unavailable")?;
40    Ok(hex::encode(bytes))
41}
42fn new_locator(origin: &Origin) -> NativeResult<String> {
43    Ok(format!(
44        "cs1-{}-{}",
45        hex::encode(Sha256::digest(origin.to_string().as_bytes())),
46        random_id()?
47    ))
48}
49fn valid_locator(s: &str) -> bool {
50    let mut p = s.split('-');
51    p.next() == Some("cs1")
52        && [64, 32].iter().all(|len| {
53            p.next()
54                .is_some_and(|s| s.len() == *len && s.bytes().all(|b| b.is_ascii_hexdigit()))
55        })
56        && p.next().is_none()
57}
58
59// A blocked provider dialog retains the execution permit after its caller cancels.
60static PROVIDER: Semaphore = Semaphore::const_new(1);
61static CAPACITY: Semaphore = Semaphore::const_new(17);
62
63async fn native<F, T>(f: F) -> napi::Result<T>
64where
65    F: FnOnce() -> NativeResult<T> + Send + 'static,
66    T: Send + 'static,
67{
68    let slot = CAPACITY
69        .try_acquire()
70        .map_err(|_| napi::Error::from_reason("native queue full"))?;
71    let permit = PROVIDER
72        .acquire()
73        .await
74        .map_err(|_| napi::Error::from_reason("native provider unavailable"))?;
75    tokio::task::spawn_blocking(move || {
76        let _held = (permit, slot);
77        f()
78    })
79    .await
80    .map_err(|_| napi::Error::from_reason("native provider failed"))?
81    .map_err(napi::Error::from_reason)
82}
83
84#[napi]
85pub fn validate_broker_frame(text: String) -> napi::Result<String> {
86    let frame = Frame::<BrokerToCompanion>::decode(text.as_bytes())
87        .map_err(|e| napi::Error::from_reason(e.to_string()))?;
88    let bytes = frame
89        .encode()
90        .map_err(|e| napi::Error::from_reason(e.to_string()))?;
91    String::from_utf8(bytes).map_err(|_| napi::Error::from_reason("invalid frame encoding"))
92}
93
94#[napi]
95pub async fn create_pairing_key(integrator_origin: String) -> napi::Result<Value> {
96    native(move || {
97        let origin = Origin::parse(&integrator_origin).map_err(|e| e.to_string())?;
98        let locator = new_locator(&origin)?;
99        let public = platform::create_pairing(&locator)?;
100        Ok(json!({"locator":locator,"publicSec1":STANDARD.encode(public)}))
101    })
102    .await
103}
104
105#[napi]
106pub async fn pairing_public_key(locator: String) -> napi::Result<String> {
107    native(move || {
108        if !valid_locator(&locator) {
109            return Err("invalid pairing locator".into());
110        }
111        Ok(STANDARD.encode(platform::pairing_public(&locator)?))
112    })
113    .await
114}
115
116#[napi]
117pub async fn prove_pairing(
118    locator: String,
119    challenge_json: String,
120    integrator_origin: String,
121) -> napi::Result<String> {
122    native(move || {
123        if challenge_json.len() > 16_384 || !valid_locator(&locator) {
124            return Err("invalid device proof request".into());
125        }
126        let c: Challenge =
127            serde_json::from_str(&challenge_json).map_err(|_| "invalid challenge")?;
128        let origin = Origin::parse(&integrator_origin).map_err(|e| e.to_string())?;
129        let prefix = format!(
130            "cs1-{}-",
131            hex::encode(Sha256::digest(origin.to_string().as_bytes()))
132        );
133        let now = clock_ms()?;
134        if origin != c.integrator_origin
135            || origin != c.broker_origin
136            || !locator.starts_with(&prefix)
137            || now < c.issued_at_ms
138            || now >= c.expires_at_ms
139            || c.expires_at_ms.saturating_sub(c.issued_at_ms) > 60_000
140        {
141            return Err("challenge authority or deadline mismatch".into());
142        }
143        let public = platform::pairing_public(&locator)?;
144        if URL_SAFE_NO_PAD.encode(Sha256::digest(public)) != c.key.as_str() {
145            return Err("challenge key mismatch".into());
146        }
147        let header =
148            URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256","typ":"countersign-device-proof+jws"}"#);
149        let claims =
150            serde_json::to_vec(&json!({"version":1,"challenge":c})).map_err(|_| "encode proof")?;
151        let signed = format!("{header}.{}", URL_SAFE_NO_PAD.encode(claims));
152        let raw = platform::pairing_sign(&locator, signed.as_bytes())?;
153        let sig =
154            p256::ecdsa::Signature::from_slice(&raw).map_err(|_| "invalid device signature")?;
155        Ok(format!(
156            "{signed}.{}",
157            URL_SAFE_NO_PAD.encode(sig.to_bytes())
158        ))
159    })
160    .await
161}
162
163#[napi]
164pub async fn retire_pairing_key(locator: String) -> napi::Result<()> {
165    native(move || {
166        if !valid_locator(&locator) {
167            return Err("invalid pairing locator".into());
168        }
169        platform::retire_pairing(&locator)
170    })
171    .await
172}
173
174pub(crate) struct Identity {
175    chain: Vec<Vec<u8>>,
176    // Provider-private locator for this identity. Never sent to JS or the Broker.
177    key: Vec<u8>,
178}
179
180struct Selection {
181    identity: Identity,
182    fingerprint: Fingerprint,
183    expires: Instant,
184}
185struct Active {
186    binding: GrantBinding,
187    selected: Arc<Selection>,
188    expires_at_ms: u64,
189    expires: Instant,
190    used: HashMap<String, u64>,
191}
192type GrantKey = (Id, Id);
193fn grant_key(binding: &GrantBinding) -> GrantKey {
194    (binding.device.key.clone(), binding.grant.clone())
195}
196type OperationKey = (GrantKey, Id);
197fn operation_key(op: &Operation) -> OperationKey {
198    (grant_key(&op.grant), op.operation.clone())
199}
200
201#[derive(Default)]
202struct State {
203    selections: HashMap<String, Arc<Selection>>,
204    active: HashMap<GrantKey, Active>,
205    pending: HashMap<OperationKey, (Operation, bool)>,
206}
207static STATE: LazyLock<Mutex<State>> = LazyLock::new(|| Mutex::new(State::default()));
208
209fn eligible(der: &[u8]) -> NativeResult<(String, String, i64)> {
210    let (remaining, c) = X509Certificate::from_der(der).map_err(|_| "unreadable certificate")?;
211    if !remaining.is_empty()
212        || !c.validity().is_valid()
213        || c.is_ca()
214        || c.key_usage()
215            .map_err(|_| "invalid KU")?
216            .is_some_and(|u| !u.value.digital_signature())
217        || c.extended_key_usage()
218            .map_err(|_| "invalid EKU")?
219            .is_some_and(|u| !u.value.client_auth && !u.value.any)
220    {
221        return Err("ineligible certificate".into());
222    }
223    if supported_schemes(&c)?.is_empty() {
224        return Err("ineligible key".into());
225    }
226    Ok((
227        c.subject().to_string(),
228        c.issuer().to_string(),
229        c.validity().not_after.timestamp() * 1000,
230    ))
231}
232
233fn supported_schemes(leaf: &X509Certificate<'_>) -> NativeResult<&'static [SignatureScheme]> {
234    use SignatureScheme::*;
235    match leaf.public_key().parsed().map_err(|_| "ineligible key")? {
236        PublicKey::RSA(key) if (2048..=8192).contains(&key.key_size()) => Ok(&[
237            RsaPssSha256,
238            RsaPssSha384,
239            RsaPssSha512,
240            RsaPkcs1Sha256,
241            RsaPkcs1Sha384,
242            RsaPkcs1Sha512,
243        ]),
244        PublicKey::EC(_) => {
245            let curve = leaf
246                .public_key()
247                .algorithm
248                .parameters
249                .as_ref()
250                .and_then(|param| param.as_oid().ok())
251                .map(|oid| oid.to_id_string());
252            Ok(match curve.as_deref() {
253                Some("1.2.840.10045.3.1.7") => &[EcdsaNistp256Sha256],
254                Some("1.3.132.0.34") => &[EcdsaNistp384Sha384],
255                _ => &[],
256            })
257        }
258        _ => Ok(&[]),
259    }
260}
261
262fn matches_hints(hints: &IdentityHints, chain: &[Vec<u8>], fingerprint: &Fingerprint) -> bool {
263    if hints
264        .cert_fingerprints
265        .as_ref()
266        .is_some_and(|allowed| !allowed.contains(fingerprint))
267    {
268        return false;
269    }
270    if !hints.signature_schemes.is_empty() {
271        let Some((_, leaf)) = chain
272            .first()
273            .and_then(|der| X509Certificate::from_der(der).ok())
274        else {
275            return false;
276        };
277        if !supported_schemes(&leaf)
278            .is_ok_and(|schemes| schemes.iter().any(|s| hints.signature_schemes.contains(s)))
279        {
280            return false;
281        }
282    }
283    hints.issuer_names.is_empty()
284        || chain.iter().any(|der| {
285            X509Certificate::from_der(der).is_ok_and(|(_, cert)| {
286                hints
287                    .issuer_names
288                    .iter()
289                    .any(|name| name.as_slice() == cert.issuer().as_raw())
290            })
291        })
292}
293
294#[napi]
295pub async fn list_identities(hints_json: Option<String>) -> napi::Result<Vec<Value>> {
296    native(move || {
297        let hints: IdentityHints = match hints_json {
298            None => IdentityHints::default(),
299            Some(json) if json.len() <= MAX_FRAME_BYTES => {
300                serde_json::from_str(&json).map_err(|_| "invalid identity constraints")?
301            }
302            _ => return Err("oversized identity constraints".into()),
303        };
304        let identities = platform::identities()?;
305        let mut choices = Vec::new();
306        let mut st = STATE.lock().map_err(|_| "state unavailable")?;
307        st.selections.retain(|_, s| s.expires > Instant::now());
308        for identity in identities {
309            let Some(leaf) = identity.chain.first() else {
310                continue;
311            };
312            let Ok((subject, issuer, expires_at_ms)) = eligible(leaf) else {
313                continue;
314            };
315            let cert_sha256 = Fingerprint::new(Sha256::digest(leaf).into());
316            if !matches_hints(&hints, &identity.chain, &cert_sha256) {
317                continue;
318            }
319            let Ok(chain) = PublicChain::new(identity.chain.clone()) else {
320                continue;
321            };
322            if st.selections.len() >= 4096 {
323                return Err("identity selection limit reached".into());
324            }
325            let selection = random_id()?;
326            choices.push(json!({
327                "selection": selection, "subject": subject, "issuer": issuer,
328                "expiresAtMs": expires_at_ms, "certSha256": cert_sha256, "chain": chain,
329            }));
330            st.selections.insert(
331                selection,
332                Arc::new(Selection {
333                    identity,
334                    fingerprint: cert_sha256,
335                    expires: Instant::now() + Duration::from_secs(600),
336                }),
337            );
338        }
339        Ok(choices)
340    })
341    .await
342}
343
344#[napi]
345pub fn activate_scope(activation_json: String, selection: String) -> napi::Result<()> {
346    if activation_json.len() > MAX_FRAME_BYTES {
347        return Err(napi::Error::from_reason("invalid scope"));
348    }
349    let activation: Activate = serde_json::from_str(&activation_json)
350        .map_err(|_| napi::Error::from_reason("invalid scope"))?;
351    let mut st = STATE
352        .lock()
353        .map_err(|_| napi::Error::from_reason("state unavailable"))?;
354    let selected = st
355        .selections
356        .remove(&selection)
357        .ok_or_else(|| napi::Error::from_reason("selection expired"))?;
358    let now = clock_ms().map_err(napi::Error::from_reason)?;
359    let (_, _, expires) =
360        eligible(&selected.identity.chain[0]).map_err(napi::Error::from_reason)?;
361    if selected.expires <= Instant::now()
362        || activation.expires_at_ms <= now
363        || activation.expires_at_ms > expires as u64
364        || activation.grant.cert_sha256 != selected.fingerprint
365    {
366        return Err(napi::Error::from_reason("selection or grant mismatch"));
367    }
368    let started = Instant::now();
369    let expires = started
370        .checked_add(Duration::from_millis(activation.expires_at_ms - now))
371        .ok_or_else(|| napi::Error::from_reason("invalid grant lifetime"))?;
372    st.active
373        .retain(|_, a| a.expires_at_ms > now && a.expires > started);
374    if st.active.contains_key(&grant_key(&activation.grant)) || st.active.len() >= 256 {
375        return Err(napi::Error::from_reason("grant slot unavailable"));
376    }
377    st.active.insert(
378        grant_key(&activation.grant),
379        Active {
380            binding: activation.grant,
381            selected,
382            expires_at_ms: activation.expires_at_ms,
383            expires,
384            used: HashMap::new(),
385        },
386    );
387    Ok(())
388}
389
390#[napi]
391pub fn retire_scope(binding_json: String) -> napi::Result<()> {
392    if binding_json.len() > MAX_FRAME_BYTES {
393        return Err(napi::Error::from_reason("invalid retirement"));
394    }
395    let binding: GrantBinding = serde_json::from_str(&binding_json)
396        .map_err(|_| napi::Error::from_reason("invalid retirement"))?;
397    let key = grant_key(&binding);
398    let mut st = STATE
399        .lock()
400        .map_err(|_| napi::Error::from_reason("state unavailable"))?;
401    if st.active.get(&key).is_some_and(|a| a.binding == binding) {
402        st.active.remove(&key);
403    }
404    for (grant, cancelled) in st.pending.values_mut() {
405        if grant.grant == binding {
406            *cancelled = true
407        }
408    }
409    Ok(())
410}
411#[napi]
412pub fn cancel_operation(operation_json: String) -> napi::Result<()> {
413    if operation_json.len() > MAX_FRAME_BYTES {
414        return Err(napi::Error::from_reason("invalid cancellation"));
415    }
416    let op: Operation = serde_json::from_str(&operation_json)
417        .map_err(|_| napi::Error::from_reason("invalid cancellation"))?;
418    if let Some((binding, cancelled)) = STATE
419        .lock()
420        .map_err(|_| napi::Error::from_reason("state unavailable"))?
421        .pending
422        .get_mut(&operation_key(&op))
423        && *binding == op
424    {
425        *cancelled = true
426    }
427    Ok(())
428}
429
430#[napi]
431pub async fn sign_tls(sign_json: String) -> napi::Result<String> {
432    if sign_json.len() > MAX_FRAME_BYTES {
433        return Err(napi::Error::from_reason("oversized signing operation"));
434    }
435    let request: Sign = serde_json::from_str(&sign_json)
436        .map_err(|_| napi::Error::from_reason("invalid signing operation"))?;
437    let operation = operation_key(&request.binding);
438    let grant = grant_key(&request.binding.grant);
439    let now = clock_ms().map_err(napi::Error::from_reason)?;
440    let selection = {
441        let mut st = STATE
442            .lock()
443            .map_err(|_| napi::Error::from_reason("state unavailable"))?;
444        if st.pending.contains_key(&operation)
445            || st.pending.keys().filter(|(g, _)| g == &grant).count() >= 4
446        {
447            return Err(napi::Error::from_reason("operation busy"));
448        }
449        let active = st
450            .active
451            .get_mut(&grant)
452            .ok_or_else(|| napi::Error::from_reason("inactive grant"))?;
453        if active.expires <= Instant::now()
454            || request.binding.grant != active.binding
455            || !active
456                .binding
457                .scope
458                .pattern()
459                .matches(&request.binding.host)
460            || request.deadline_ms <= now
461            || request.deadline_ms > active.expires_at_ms
462            || request.deadline_ms - now > 120_000
463        {
464            return Err(napi::Error::from_reason("operation outside active grant"));
465        }
466        active.used.retain(|_, expiry| *expiry > now);
467        if active.used.len() >= 4096 || active.used.contains_key(operation.1.as_str()) {
468            return Err(napi::Error::from_reason("reused or full operation slot"));
469        }
470        active
471            .used
472            .insert(operation.1.as_str().to_string(), request.deadline_ms);
473        let selection = active.selected.clone();
474        st.pending
475            .insert(operation.clone(), (request.binding.clone(), false));
476        selection
477    };
478    let key = operation.clone();
479    let result = native(move || {
480        ensure_current(&key, request.deadline_ms)?;
481        let cert = &selection.identity.chain[0];
482        eligible(cert)?;
483        let (_, leaf) = X509Certificate::from_der(cert).map_err(|_| "invalid selected leaf")?;
484        if !supported_schemes(&leaf)?.contains(&request.scheme) {
485            return Err("scheme incompatible with selected key".into());
486        }
487        check_transcript(&request, cert)?;
488        let signature = platform::sign_identity(
489            &selection.identity,
490            request.scheme,
491            request.certificate_verify.as_slice(),
492        )?;
493        ensure_current(&key, request.deadline_ms)?;
494        Ok(STANDARD.encode(signature))
495    })
496    .await;
497    STATE
498        .lock()
499        .map_err(|_| napi::Error::from_reason("state unavailable"))?
500        .pending
501        .remove(&operation);
502    result
503}
504fn ensure_current(op: &OperationKey, deadline: u64) -> NativeResult<()> {
505    let state = STATE.lock().map_err(|_| "state unavailable")?;
506    if !state
507        .pending
508        .get(op)
509        .is_some_and(|(_, cancelled)| !*cancelled)
510        || !state
511            .active
512            .get(&op.0)
513            .is_some_and(|grant| grant.expires > Instant::now())
514        || clock_ms()? >= deadline
515    {
516        return Err("operation cancelled or expired".into());
517    }
518    Ok(())
519}
520/// Read a TLS vector with a 1- or 2-byte length prefix.
521fn vector<'a>(input: &mut &'a [u8], width: usize) -> Option<&'a [u8]> {
522    let n = match width {
523        1 => *input.first()? as usize,
524        2 => u16::from_be_bytes(input.get(..2)?.try_into().ok()?) as usize,
525        _ => return None,
526    };
527    let value = input.get(width..width + n)?;
528    *input = &input[width + n..];
529    Some(value)
530}
531
532fn tls12_sni(hello: &[u8]) -> Option<&[u8]> {
533    // legacy_version, random, session_id, cipher_suites, compression_methods.
534    let mut bytes = hello.get(34..)?;
535    vector(&mut bytes, 1)?;
536    vector(&mut bytes, 2)?;
537    vector(&mut bytes, 1)?;
538    let mut extensions = vector(&mut bytes, 2)?;
539    if !bytes.is_empty() {
540        return None;
541    }
542    let mut sni = None;
543    while !extensions.is_empty() {
544        let typ = extensions.get(..2)?;
545        extensions = &extensions[2..];
546        let mut data = vector(&mut extensions, 2)?;
547        if typ != [0, 0] {
548            continue;
549        }
550        let mut names = vector(&mut data, 2)?;
551        if !data.is_empty() || sni.is_some() || names.first()? != &0 {
552            return None;
553        }
554        names = &names[1..];
555        sni = Some(vector(&mut names, 2)?);
556        if !names.is_empty() {
557            return None;
558        }
559    }
560    sni
561}
562
563fn check_transcript(req: &Sign, leaf: &[u8]) -> NativeResult<()> {
564    let bytes = req.certificate_verify.as_slice();
565    match req.tls {
566        TlsVersion::Tls13 => {
567            let prefix = [&[0x20u8; 64][..], b"TLS 1.3, client CertificateVerify\0"].concat();
568            if !bytes
569                .strip_prefix(&prefix[..])
570                .is_some_and(|hash| matches!(hash.len(), 32 | 48))
571                || matches!(
572                    req.scheme,
573                    SignatureScheme::RsaPkcs1Sha256
574                        | SignatureScheme::RsaPkcs1Sha384
575                        | SignatureScheme::RsaPkcs1Sha512
576                )
577            {
578                return Err("invalid TLS 1.3 CertificateVerify input".into());
579            }
580        }
581        TlsVersion::Tls12 => {
582            let mut rest = bytes;
583            let mut types = Vec::new();
584            while !rest.is_empty() {
585                let header = rest.get(..4).ok_or("invalid TLS transcript")?;
586                let n = u32::from_be_bytes([0, header[1], header[2], header[3]]) as usize;
587                let body = rest.get(4..4 + n).ok_or("truncated TLS transcript")?;
588                if types.len() == 9 {
589                    return Err("excess TLS transcript messages".into());
590                }
591                if header[0] == 1 && tls12_sni(body) != Some(req.binding.host.host().as_bytes()) {
592                    return Err("TLS ClientHello has a different origin".into());
593                }
594                if header[0] == 11 && types.contains(&14) {
595                    // TLS 1.2 Certificate after ServerHelloDone is the client chain.
596                    let list = body.get(..3).ok_or("missing client chain")?;
597                    let length = u32::from_be_bytes([0, list[0], list[1], list[2]]) as usize;
598                    let first = body.get(3..6).ok_or("missing selected leaf")?;
599                    let leaf_length =
600                        u32::from_be_bytes([0, first[0], first[1], first[2]]) as usize;
601                    if body.len() != 3 + length || body.get(6..6 + leaf_length) != Some(leaf) {
602                        return Err("TLS transcript has a different client identity".into());
603                    }
604                }
605                types.push(header[0]);
606                rest = &rest[4 + n..];
607            }
608            if types.as_slice() != [1, 2, 11, 12, 13, 14, 11, 16]
609                && types.as_slice() != [1, 2, 11, 22, 12, 13, 14, 11, 16]
610            {
611                return Err("unsupported TLS 1.2 client authentication transcript".into());
612            }
613        }
614    }
615    Ok(())
616}