lair_keystore_api 0.1.0

secret lair private keystore API library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use super::*;

pub(crate) fn priv_req_hello<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    req: LairApiReqHello,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        // DON'T check connection 'unlocked' here,
        // we want to be able to verify the server,
        // before we unlock the individual connection.

        let (id_pk, server_name, server_version) = {
            let lock = inner.read();
            (
                lock.id_pk.clone(),
                lock.server_name.clone(),
                lock.server_version.clone(),
            )
        };

        let server_pub_key = (*id_pk.read_lock_sized()).into();

        // send our hello response
        send.send(
            LairApiResHello {
                msg_id: req.msg_id,
                name: server_name,
                version: server_version,
                server_pub_key,
            }
            .into_api_enum(),
        )
        .await?;

        Ok(())
    }
}

pub(crate) fn priv_req_unlock<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    dec_ctx_key: &'a sodoken::BufReadSized<32>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqUnlock,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        let passphrase = req.passphrase.decrypt(dec_ctx_key.clone()).await?;

        let (config, id_pk) = {
            let lock = inner.read();
            (lock.config.clone(), lock.id_pk.clone())
        };

        // read salt from config
        let salt = sodoken::BufReadSized::from(
            config.runtime_secrets_salt.cloned_inner(),
        );

        // read limits from config
        let ops_limit = config.runtime_secrets_ops_limit;
        let mem_limit = config.runtime_secrets_mem_limit;

        // calculate pre_secret from argon2id passphrase hash
        let pre_secret = <sodoken::BufWriteSized<32>>::new_mem_locked()?;
        sodoken::hash::argon2id::hash(
            pre_secret.clone(),
            passphrase,
            salt,
            ops_limit,
            mem_limit,
        )
        .await?;

        // derive signature decryption secret
        let id_secret = <sodoken::BufWriteSized<32>>::new_mem_locked()?;
        sodoken::kdf::derive_from_key(
            id_secret.clone(),
            142,
            *b"IdnSecKy",
            pre_secret,
        )?;

        // decrypt the signature seed
        let id_seed = config
            .runtime_secrets_id_seed
            .decrypt(id_secret.to_read_sized())
            .await?;

        // derive the signature keypair from the signature seed
        let d_id_pk = <sodoken::BufWriteSized<32>>::new_no_lock();
        let d_id_sk = <sodoken::BufWriteSized<32>>::new_mem_locked()?;
        use sodoken::crypto_box::curve25519xchacha20poly1305::*;
        seed_keypair(d_id_pk.clone(), d_id_sk, id_seed).await?;

        if *id_pk.read_lock() != *d_id_pk.read_lock() {
            return Err("InvalidPassphrase".into());
        }

        // if that was successfull, we can also set the connection level
        // unlock state to unlocked
        unlocked.store(true, atomic::Ordering::Relaxed);

        // return the success
        send.send(LairApiResUnlock { msg_id: req.msg_id }.into_api_enum())
            .await?;

        Ok(())
    }
}

pub(crate) fn priv_req_get_entry<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqGetEntry,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        if !unlocked.load(atomic::Ordering::Relaxed) {
            return Err("KeystoreLocked".into());
        }

        // get the entry
        let (full_entry, _) =
            priv_get_full_entry_by_tag(inner, req.tag).await?;

        // convert the entry to LairEntryInfo
        let entry_info = match &*full_entry.entry {
            LairEntryInner::Seed { tag, seed_info, .. } => {
                LairEntryInfo::Seed {
                    tag: tag.clone(),
                    seed_info: seed_info.clone(),
                }
            }
            LairEntryInner::DeepLockedSeed { tag, seed_info, .. } => {
                LairEntryInfo::DeepLockedSeed {
                    tag: tag.clone(),
                    seed_info: seed_info.clone(),
                }
            }
            LairEntryInner::WkaTlsCert { tag, cert_info, .. } => {
                LairEntryInfo::WkaTlsCert {
                    tag: tag.clone(),
                    cert_info: cert_info.clone(),
                }
            }
        };

        // send the response
        send.send(
            LairApiResGetEntry {
                msg_id: req.msg_id,
                entry_info,
            }
            .into_api_enum(),
        )
        .await?;

        Ok(())
    }
}

pub(crate) fn priv_req_list_entries<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqListEntries,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        let store = priv_get_store(inner, unlocked)?;

        // list entries
        let entry_list = store.list_entries().await?;

        // send the response
        send.send(
            LairApiResListEntries {
                msg_id: req.msg_id,
                entry_list,
            }
            .into_api_enum(),
        )
        .await?;

        Ok(())
    }
}

pub(crate) fn priv_req_new_seed<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    dec_ctx_key: &'a sodoken::BufReadSized<32>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqNewSeed,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        let store = priv_get_store(inner, unlocked)?;

        let seed_info = match req.deep_lock_passphrase {
            Some(secret) => {
                // if deep locked, decrypt the deep lock passphrase
                let deep_lock_passphrase =
                    secret.passphrase.decrypt(dec_ctx_key.clone()).await?;

                // create a new deep locked seed
                store
                    .new_deep_locked_seed(
                        req.tag.clone(),
                        secret.ops_limit,
                        secret.mem_limit,
                        deep_lock_passphrase,
                    )
                    .await?
            }
            // create a new seed
            None => store.new_seed(req.tag.clone()).await?,
        };

        // send the response
        send.send(
            LairApiResNewSeed {
                msg_id: req.msg_id,
                tag: req.tag.clone(),
                seed_info,
            }
            .into_api_enum(),
        )
        .await?;

        Ok(())
    }
}

pub(crate) fn priv_req_sign_by_pub_key<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqSignByPubKey,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        if !unlocked.load(atomic::Ordering::Relaxed) {
            return Err("KeystoreLocked".into());
        }

        // get cached full entry
        let res =
            match priv_get_full_entry_by_ed_pub_key(inner, req.pub_key.clone())
                .await
            {
                Ok((full_entry, _)) => {
                    // sign the data
                    let signature = if let Some(ed_sk) = full_entry.ed_sk {
                        let signature = sodoken::BufWriteSized::new_no_lock();
                        sodoken::sign::detached(
                            signature.clone(),
                            req.data,
                            ed_sk,
                        )
                        .await?;
                        signature.try_unwrap_sized().unwrap().into()
                    } else {
                        return Err(
                            "deep_seed signing not yet implemented".into()
                        );
                    };

                    LairApiResSignByPubKey {
                        msg_id: req.msg_id,
                        signature,
                    }
                }
                Err(e) => {
                    // we don't have this key, let's see if we should invoke
                    // a signature fallback command
                    let fallback_cmd = inner.read().fallback_cmd.clone();
                    if let Some(fallback_cmd) = fallback_cmd {
                        fallback_cmd.sign_by_pub_key(req).await?
                    } else {
                        return Err(e);
                    }
                }
            };

        // send the response
        send.send(res.into_api_enum()).await?;

        Ok(())
    }
}

pub(crate) fn priv_req_crypto_box_xsalsa_by_pub_key<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqCryptoBoxXSalsaByPubKey,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        if !unlocked.load(atomic::Ordering::Relaxed) {
            return Err("KeystoreLocked".into());
        }

        // get cached full entry
        let (full_entry, _) =
            priv_get_full_entry_by_x_pub_key(inner, req.sender_pub_key.clone())
                .await?;

        let nonce = sodoken::BufWriteSized::new_no_lock();
        sodoken::random::bytes_buf(nonce.clone()).await?;

        use sodoken::crypto_box::curve25519xsalsa20poly1305::*;
        let cipher = if let Some(x_sk) = full_entry.x_sk {
            easy(
                nonce.clone(),
                req.data,
                req.recipient_pub_key.cloned_inner(),
                x_sk,
            )
            .await?
        } else {
            return Err("deep_seed crypto_box not yet implemented".into());
        };

        send.send(
            LairApiResCryptoBoxXSalsaByPubKey {
                msg_id: req.msg_id,
                nonce: nonce.try_unwrap_sized().unwrap(),
                cipher: cipher.try_unwrap().unwrap().into(),
            }
            .into_api_enum(),
        )
        .await?;

        Ok(())
    }
}

pub(crate) fn priv_req_crypto_box_xsalsa_open_by_pub_key<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqCryptoBoxXSalsaOpenByPubKey,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        if !unlocked.load(atomic::Ordering::Relaxed) {
            return Err("KeystoreLocked".into());
        }

        // get cached full entry
        let (full_entry, _) = priv_get_full_entry_by_x_pub_key(
            inner,
            req.recipient_pub_key.clone(),
        )
        .await?;

        use sodoken::crypto_box::curve25519xsalsa20poly1305::*;

        let message =
            sodoken::BufWrite::new_no_lock(open_easy_msg_len(req.cipher.len()));

        if let Some(x_sk) = full_entry.x_sk {
            open_easy(
                req.nonce,
                message.clone(),
                req.cipher,
                req.sender_pub_key.cloned_inner(),
                x_sk,
            )
            .await?;
        } else {
            return Err("deep_seed crypto_box not yet implemented".into());
        }

        send.send(
            LairApiResCryptoBoxXSalsaOpenByPubKey {
                msg_id: req.msg_id,
                message: message.try_unwrap().unwrap().into(),
            }
            .into_api_enum(),
        )
        .await?;

        Ok(())
    }
}

pub(crate) fn priv_req_new_wka_tls_cert<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqNewWkaTlsCert,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        let store = priv_get_store(inner, unlocked)?;

        // create a e new
        let cert_info = store.new_wka_tls_cert(req.tag.clone()).await?;

        send.send(
            LairApiResNewWkaTlsCert {
                msg_id: req.msg_id,
                tag: req.tag.clone(),
                cert_info,
            }
            .into_api_enum(),
        )
        .await?;

        Ok(())
    }
}

pub(crate) fn priv_gen_and_register_entry<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    store: &'a LairStore,
    entry: LairEntry,
) -> impl Future<Output = LairResult<FullLairEntry>> + 'a + Send {
    async move {
        let (ed_pk, ed_sk, x_pk, x_sk) = match &*entry {
            // only cache non-deep-locked seeds
            LairEntryInner::Seed { seed, .. } => {
                // read the seed
                let seed = seed.decrypt(store.get_bidi_ctx_key()).await?;

                // get the signature keypair
                let ed_pk = sodoken::BufWriteSized::new_no_lock();
                let ed_sk = sodoken::BufWriteSized::new_mem_locked()?;
                sodoken::sign::seed_keypair(
                    ed_pk.clone(),
                    ed_sk.clone(),
                    seed.clone(),
                )
                .await?;

                // get the encryption keypair
                let x_pk = sodoken::BufWriteSized::new_no_lock();
                let x_sk = sodoken::BufWriteSized::new_mem_locked()?;
                sodoken::crypto_box::curve25519xchacha20poly1305::seed_keypair(
                    x_pk.clone(),
                    x_sk.clone(),
                    seed,
                )
                .await?;

                (
                    Some(ed_pk.try_unwrap_sized().unwrap().into()),
                    Some(ed_sk.to_read_sized()),
                    Some(x_pk.try_unwrap_sized().unwrap().into()),
                    Some(x_sk.to_read_sized()),
                )
            }
            _ => (None, None, None, None),
        };

        let full_entry = FullLairEntry { entry, ed_sk, x_sk };

        let mut lock = inner.write();

        // add full entry to our LRU caches
        lock.entries_by_tag
            .put(full_entry.entry.tag(), full_entry.clone());
        if let Some(ed_pk) = ed_pk {
            lock.entries_by_ed.put(ed_pk, full_entry.clone());
        }
        if let Some(x_pk) = x_pk {
            lock.entries_by_x.put(x_pk, full_entry.clone());
        }

        Ok(full_entry)
    }
}

#[allow(clippy::needless_lifetimes)] // this helps me define the future bounds
pub(crate) fn priv_get_full_entry_by_tag<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    tag: Arc<str>,
) -> impl Future<Output = LairResult<(FullLairEntry, LairStore)>> + 'a + Send {
    async move {
        let store = {
            let mut lock = inner.write();
            let store = lock.store.clone();
            if let Some(full_entry) = lock.entries_by_tag.get(&tag) {
                return Ok((full_entry.clone(), store));
            }
            store
        };

        // get the entry
        let entry = store.get_entry_by_tag(tag).await?;

        let full_entry =
            priv_gen_and_register_entry(inner, &store, entry).await?;

        Ok((full_entry, store))
    }
}

#[allow(clippy::needless_lifetimes)] // this helps me define the future bounds
pub(crate) fn priv_get_full_entry_by_ed_pub_key<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    ed_pub_key: Ed25519PubKey,
) -> impl Future<Output = LairResult<(FullLairEntry, LairStore)>> + 'a + Send {
    async move {
        let store = {
            let mut lock = inner.write();
            let store = lock.store.clone();
            if let Some(full_entry) = lock.entries_by_ed.get(&ed_pub_key) {
                return Ok((full_entry.clone(), store));
            }
            store
        };

        // get the entry
        let entry = store.get_entry_by_ed25519_pub_key(ed_pub_key).await?;

        let full_entry =
            priv_gen_and_register_entry(inner, &store, entry).await?;

        Ok((full_entry, store))
    }
}

#[allow(clippy::needless_lifetimes)] // this helps me define the future bounds
pub(crate) fn priv_get_full_entry_by_x_pub_key<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    x_pub_key: X25519PubKey,
) -> impl Future<Output = LairResult<(FullLairEntry, LairStore)>> + 'a + Send {
    async move {
        let store = {
            let mut lock = inner.write();
            let store = lock.store.clone();
            if let Some(full_entry) = lock.entries_by_x.get(&x_pub_key) {
                return Ok((full_entry.clone(), store));
            }
            store
        };

        // get the entry
        let entry = store.get_entry_by_x25519_pub_key(x_pub_key).await?;

        let full_entry =
            priv_gen_and_register_entry(inner, &store, entry).await?;

        Ok((full_entry, store))
    }
}

pub(crate) fn priv_req_get_wka_tls_cert_priv_key<'a>(
    inner: &'a Arc<RwLock<SrvInner>>,
    send: &'a crate::sodium_secretstream::S3Sender<LairApiEnum>,
    enc_ctx_key: &'a sodoken::BufReadSized<32>,
    unlocked: &'a Arc<atomic::AtomicBool>,
    req: LairApiReqGetWkaTlsCertPrivKey,
) -> impl Future<Output = LairResult<()>> + 'a + Send {
    async move {
        if !unlocked.load(atomic::Ordering::Relaxed) {
            return Err("KeystoreLocked".into());
        }

        // get the entry
        let (full_entry, store) =
            priv_get_full_entry_by_tag(inner, req.tag).await?;

        // make sure the entry is the correct type
        let priv_key = match &*full_entry.entry {
            LairEntryInner::WkaTlsCert { priv_key, .. } => priv_key.clone(),
            _ => return Err("invalid entry type".into()),
        };

        // decrypt the priv_key using our DB CONTEXT KEY
        let priv_key = priv_key.decrypt(store.get_bidi_ctx_key()).await?;

        // encrypt the priv_key using our CONNECTION CONTEXT KEY
        let priv_key =
            SecretData::encrypt(enc_ctx_key.clone(), priv_key).await?;

        send.send(
            LairApiResGetWkaTlsCertPrivKey {
                msg_id: req.msg_id,
                priv_key,
            }
            .into_api_enum(),
        )
        .await?;

        Ok(())
    }
}