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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
use std::{
    collections::{
        HashMap,
    },
    ffi::{
        CStr,
    },
    sync::atomic,
};
use libc::{
    c_char,
    c_int,
    c_void,
    size_t,
};

#[macro_use]
extern crate lazy_static;

use sequoia_openpgp as openpgp;
use openpgp::{
    Fingerprint,
    KeyID,
    cert::{
        Cert,
    },
    crypto::{
        Password,
        mem::Protected,
    },
    packet::{
        Key,
        key::{SecretParts, UnspecifiedRole},
        UserID,
    },
    policy::{
        StandardPolicy,
    },
    serialize::Serialize,
};

/// Controls tracing.
const TRACE: bool = cfg!(debug_assertions);

#[allow(unused_macros)]
macro_rules! stub {
    ($s: ident) => {
        #[no_mangle] pub extern "C"
        fn $s() -> RnpResult {
            log!("\nSTUB: {}\n", stringify!($s));
            RNP_ERROR_NOT_IMPLEMENTED
        }
    };
}

#[allow(dead_code)]
#[macro_use]
mod error;
use error::*;

// XXX: This is a copy of sequoia/ipc/src/keygrip.rs.
mod keygrip;
use keygrip::*;

mod keystore;
use keystore::Keystore;

mod buffer;
use buffer::*;

#[allow(dead_code)]
mod flags;
use flags::*;
#[allow(dead_code)]
mod io;
use io::*;
#[allow(dead_code)]
mod utils;
use utils::*;
#[allow(dead_code)]
mod conversions;
use conversions::*;

mod version;
#[allow(dead_code)]
mod op_verify;
#[allow(dead_code)]
mod op_encrypt;
#[allow(dead_code)]
mod op_sign;
mod recombine;
#[allow(dead_code)]
mod op_generate;
#[allow(dead_code)]
mod signature;
use signature::RnpSignature;
#[allow(dead_code)]
mod key;
use key::RnpKey;
#[allow(dead_code)]
mod iter;
#[allow(dead_code)]
mod userid;
use userid::RnpUserID;
#[allow(dead_code)]
mod import;
mod keyring;
// The gpg module is copied from OpenPGP CA.  We don't want to modify
// it.
#[allow(dead_code)]
mod gpg;

mod tbprofile;
mod wot;
#[cfg(feature="net")]
mod parcimonie;
#[cfg(not(feature="net"))]
mod parcimonie_stub;
#[cfg(not(feature="net"))]
use parcimonie_stub as parcimonie;

pub const P: &StandardPolicy = &StandardPolicy::new();

#[allow(dead_code)]
fn cert_dump(cert: &Cert) {
    use openpgp::packet::key::SecretKeyMaterial;

    eprintln!("Cert: {}, {}", cert.fingerprint(),
              cert.with_policy(&StandardPolicy::new(), None)
              .map(|cert| {
                  cert.primary_userid()
                      .map(|ua| {
                          String::from_utf8_lossy(ua.userid().value())
                              .into_owned()
                      })
                      .unwrap_or("<No UserID>"[..].into())
              })
              .unwrap_or("<Invalid>".into()));

    for (i, k) in cert.keys().enumerate() {
        eprint!("  {}. {}", i, k.fingerprint());
        match k.optional_secret() {
            Some(SecretKeyMaterial::Unencrypted(_)) => {
                eprint!(" has unencrypted secret key material");
            }
            Some(SecretKeyMaterial::Encrypted(m)) => {
                eprint!(" has encrypted secret key material: {:?}",
                        m.ciphertext());
            }
            None => {
                eprint!(" has NO secret key material");
            }
        }
        eprintln!("");
    }
}

#[derive(Default)]
pub struct RnpContext {
    certs: Keystore,
    unlocked_keys: HashMap<Fingerprint, Key<SecretParts, UnspecifiedRole>>,
    password_cb: Option<(RnpPasswordCb, *mut c_void)>,
    plaintext_cache: recombine::PlaintextCache,
}

type RnpPasswordCb = unsafe extern fn(*mut RnpContext,
                                      *mut c_void,
                                      *const Cert,
                                      *const c_char,
                                      *mut c_char,
                                      size_t) -> bool;

#[no_mangle] pub unsafe extern "C"
fn rnp_ffi_create(ctx: *mut *mut RnpContext,
                  pub_fmt: *const c_char,
                  sec_fmt: *const c_char)
                  -> RnpResult
{
    assert_ptr!(ctx);
    assert_ptr!(pub_fmt);
    assert_ptr!(sec_fmt);
    if CStr::from_ptr(pub_fmt).to_bytes() != b"GPG"
        || CStr::from_ptr(sec_fmt).to_bytes() != b"GPG"
    {
        return RNP_ERROR_BAD_FORMAT;
    }

    *ctx = Box::into_raw(Box::new(RnpContext::default()));
    RNP_SUCCESS
}

#[no_mangle] pub unsafe extern "C"
fn rnp_ffi_destroy(ctx: *mut RnpContext) -> RnpResult {
    if ! ctx.is_null() {
        drop(Box::from_raw(ctx));
    }
    RNP_SUCCESS
}

#[no_mangle] pub unsafe extern "C"
fn rnp_ffi_set_log_fd(ctx: *mut RnpContext, _fd: c_int) -> RnpResult {
    assert_ptr!(ctx);
    RNP_SUCCESS
}

#[no_mangle] pub unsafe extern "C"
fn rnp_ffi_set_pass_provider(ctx: *mut RnpContext,
                             cb: RnpPasswordCb,
                             cookie: *mut c_void)
                             -> RnpResult {
    assert_ptr!(ctx);
    (*ctx).password_cb = Some((cb, cookie));
    RNP_SUCCESS
}

impl RnpContext {
    /// Inserts a cert into the keystore.
    ///
    /// This strips any secret key material.
    ///
    /// # Locking
    ///
    /// This acquires a write lock on the keystore and, if the
    /// certificate is already present, a write lock on the
    /// certificate's cell.
    pub fn insert_cert(&mut self, cert: Cert) {
        self.certs.write().insert(cert.strip_secret_key_material());
    }

    /// Inserts a cert from an external source into the keystore.
    ///
    /// This strips any secret key material.
    ///
    /// certs from external sources won't be serialized.
    ///
    /// # Locking
    ///
    /// This acquires a write lock on the keystore and, if the
    /// certificate is already present, a write lock on the
    /// certificate's cell.
    pub fn insert_cert_external(&mut self, cert: Cert) {
        self.certs.write().insert_external(cert.strip_secret_key_material());
    }

    /// Inserts a key into the keystore.
    ///
    /// Secret key material is preserved.
    ///
    /// # Locking
    ///
    /// This acquires a write lock on the keystore and, if the
    /// certificate is already present, a write lock on the
    /// certificate's cell.
    pub fn insert_key(&mut self, cert: Cert) {
        self.certs.write().insert(cert);
    }

    /// Retrieves a certificate from the keystore by userid.
    ///
    /// RNP searches both the certring and the keyring, and the
    /// keyhandle can thus refer to two certificates, potentially
    /// different versions of the same, or even different
    /// certificates!  Since we merge the key keyrings, this is not a
    /// problem for us.
    ///
    /// # Locking
    ///
    /// This acquires a read lock on the keystore and one or more
    /// certificates' cells.  See the corresponding search methods for
    /// details.
    pub fn cert(&self, by: &RnpIdentifier) -> Option<Cert> {
        rnp_function!(RnpContext::cert, TRACE);

        use RnpIdentifier::*;
        let cert = match by {
            UserID(id) => self.cert_by_userid(id),
            KeyID(id) => self.cert_by_subkey_id(id),
            Fingerprint(fp) => self.cert_by_subkey_fp(fp),
            Keygrip(grip) => self.cert_by_subkey_grip(grip),
        };

        t!("Lookup by {:?} returned cert {:?}",
           by,
           cert.as_ref().map(|c| c.fingerprint()));

        cert
    }

    /// Retrieves a certificate by userid.
    ///
    /// XXX: This is super dodgy.  rnp.h says "Note: only valid
    /// userids are checked while searching by userid." but it is not
    /// clear what that means.
    ///
    /// XXX: I think it would be better to fail these lookups.  Are
    /// they used by TB?
    ///
    /// # Locking
    ///
    /// This acquires a read lock on the keystore.  Currently, this
    /// function performs a linear scan of all keys.  As such, it
    /// potentially acquires (in turn) a read lock on all of the
    /// certificates' cells.
    pub fn cert_by_userid(&self, uid: &UserID) -> Option<Cert> {
        let mut r_cert = None;

        // XXX O(n)
        for cert in self.certs.read().iter() {
            if cert.userids().any(|u| u.userid() == uid) {
                r_cert = Some(cert.clone());
                break;
            }
        }

        r_cert
    }

    /// Retrieves a certificate from the keystore by (sub)key
    /// fingerprint.
    ///
    /// # Locking
    ///
    /// This acquires a read lock on the keystore and, if a matching
    /// certificate is present, a read lock on the certificate's cell.
    pub fn cert_by_subkey_fp(&self, fp: &Fingerprint) -> Option<Cert> {
        self.certs.read().by_fp(fp).nth(0).map(|c| c.clone())
    }

    /// Retrieves a certificate from the keystore by (sub)key
    /// keyid.
    ///
    /// # Locking
    ///
    /// This acquires a read lock on the keystore and, if a matching
    /// certificate is present, a read lock on the certificate's cell.
    pub fn cert_by_subkey_id(&self, id: &KeyID) -> Option<Cert> {
        let ks = self.certs.read();

         let r = ks.by_primary_id(id).nth(0)
            .or_else(|| ks.by_subkey_id(id).nth(0))
            .map(|c| c.clone());
        r
    }

    /// Retrieves a certificate from the keystore by (sub)key
    /// keygrip.
    ///
    /// # Locking
    ///
    /// This acquires a read lock on the keystore and, if a matching
    /// certificate is present, a read lock on the certificate's cell.
    pub fn cert_by_subkey_grip(&self, grip: &Keygrip) -> Option<Cert> {
        let ks = self.certs.read();

        let r = ks.by_primary_grip(grip).nth(0)
            .or_else(|| ks.by_subkey_grip(grip).nth(0))
            .map(|c| c.clone());
        r
    }
}

#[derive(Debug)]
pub enum RnpPasswordFor {
    AddSubkey,
    AddUserID,
    Sign,
    Decrypt,
    Unlock,
    Protect,
    Unprotect,
    DecryptSymmetric,
    EncryptSymmetric,
}

impl RnpPasswordFor {
    fn pgp_context(&self) -> *const c_char {
        use RnpPasswordFor::*;
        (match self {
            AddSubkey => b"add subkey\x00".as_ptr(),
            AddUserID => b"add userid\x00".as_ptr(),
            Sign => b"sign\x00".as_ptr(),
            Decrypt => b"decrypt\x00".as_ptr(),
            Unlock => b"unlock\x00".as_ptr(),
            Protect => b"protect\x00".as_ptr(),
            Unprotect => b"unprotect\x00".as_ptr(),
            DecryptSymmetric => b"decrypt (symmetric)\x00".as_ptr(),
            EncryptSymmetric => b"encrypt (symmetric)\x00".as_ptr(),
        }) as *const c_char
    }
}

impl RnpContext {
    pub fn request_password(&mut self,
                            cert: Option<&Cert>,
                            reason: RnpPasswordFor) -> Option<Password> {
        rnp_function!(RnpContext::request_password, TRACE);
        t!("cert = {:?}, reason = {:?}", cert.map(|c| c.fingerprint()), reason);

        if let Some((f, cookie)) = self.password_cb {
            let mut buf: Protected = vec![0; 128].into();
            let len = buf.len();
            let ok = unsafe {
                f(self,
                  cookie,
                  cert.map(|c| c as *const _).unwrap_or(std::ptr::null()),
                  reason.pgp_context(),
                  buf.as_mut().as_mut_ptr() as *mut c_char,
                  len)
            };

            if ! ok {
                t!("password_cb returned failure");
                return None;
            }

            if let Some(got) = buf.iter().position(|b| *b == 0) {
                t!("password_cb returned {:?}",
                   String::from_utf8_lossy(&buf[..got]));
                Some(Password::from(&buf[..got]))
            } else {
                eprintln!("sequoia-octopus: given password exceeded buffer");
                None
            }
        } else {
            t!("No password_cb set");
            None
        }
    }

    /// Decrypts the given key, if necessary.
    pub fn decrypt_key_for(&mut self,
                           cert: Option<&Cert>,
                           mut key: Key<SecretParts, UnspecifiedRole>,
                           reason: RnpPasswordFor)
                           -> openpgp::Result<Key<SecretParts, UnspecifiedRole>>
    {
        rnp_function!(RnpContext::decrypt_key_for, TRACE);
        t!("cert = {:?}, key = {}, reason = {:?}",
           cert.map(|c| c.fingerprint()),
           key.fingerprint(),
           reason);

        if ! key.has_unencrypted_secret() {
            if let Some(k) = self.unlocked_keys.get(&key.fingerprint()) {
                // Use the unlocked key instead of prompting for a
                // password.
                t!("Found unlocked key in cache");
                return Ok(k.clone());
            }

            let pk_algo = key.pk_algo();
            if let Some(pw) = self.request_password(cert, reason) {
                key.secret_mut().decrypt_in_place(pk_algo, &pw)
                    .map_err(|_| Error::BadPassword)?;
                t!("Key decrypted successfully")
            } else {
                return Err(anyhow::anyhow!("no password given"));
            }
        } else {
            t!("Key is not encrypted, nothing to do");
        }
        Ok(key)
    }

    /// Returns false iff the key has not been unlocked.
    pub fn key_is_locked(&mut self, key: &Key<SecretParts, UnspecifiedRole>)
                         -> bool {
        ! self.unlocked_keys.contains_key(&key.fingerprint())
    }

    /// Locks the key.
    pub fn key_lock(&mut self, key: &Key<SecretParts, UnspecifiedRole>) {
        self.unlocked_keys.remove(&key.fingerprint());
    }

    /// Unlocks the key.
    ///
    /// If `password` is None, this function will ask for a password
    /// using the callback.
    pub fn key_unlock(&mut self,
                      mut key: Key<SecretParts, UnspecifiedRole>,
                      password: Option<Password>)
                      -> openpgp::Result<()>
    {
        rnp_function!(RnpContext::key_unlock, crate::TRACE);
        t!("key: {}; password: {:?}", key.fingerprint(), password);

        if ! key.has_unencrypted_secret() {
            let pk_algo = key.pk_algo();
            if let Some(pw) = password
                .or_else(|| self.request_password(
                    None, RnpPasswordFor::Unlock))
            {
                key.secret_mut().decrypt_in_place(pk_algo, &pw)
                    .map_err(|_| Error::BadPassword)?;
            } else {
                return Err(anyhow::anyhow!("no password given"));
            }
        }

        assert!(key.has_unencrypted_secret());
        self.unlocked_keys.insert(key.fingerprint(), key);
        Ok(())
    }
}

#[no_mangle] pub unsafe extern "C"
fn rnp_load_keys(ctx: *mut RnpContext,
                 format: *const c_char,
                 input: *mut RnpInput,
                 flags: RnpLoadSaveFlags)
                 -> RnpResult {
    rnp_function!(rnp_load_keys, TRACE);

    assert_ptr!(ctx);
    assert_ptr!(format);
    assert_ptr!(input);

    lazy_static! {
        static ref BANNER_SHOWN: atomic::AtomicBool
            = atomic::AtomicBool::new(false);
    };
    if ! BANNER_SHOWN.load(atomic::Ordering::Relaxed) {
        warn!("Your Thunderbird is using Sequoia's Octopus, version {}\n\
               (sequoia-opnepgp: {}).  For details, and to report issues please\n\
               see https://gitlab.com/sequoia-pgp/sequoia-octopus-librnp .",
              env!("CARGO_PKG_VERSION"), sequoia_openpgp::VERSION);
        if let Some(path) = crate::tbprofile::TBProfile::path() {
            warn!("Your Thunderbird profile appears to be: {:?}", path);
        } else {
            warn!("Failed to detect your Thunderbird profile.  Please report\n\
                   open an issue at https://gitlab.com/sequoia-pgp/sequoia-octopus-librnp .");
        }
        BANNER_SHOWN.store(true, atomic::Ordering::Relaxed);
    }


    if CStr::from_ptr(format).to_bytes() != b"GPG" {
        return RNP_ERROR_BAD_FORMAT;
    }

    let input = &mut *input;
    let input_size = input.size();

    match flags {
        RNP_LOAD_SAVE_PUBLIC_KEYS => {
            if let Ok(input_size) = input_size {
                if let Some(profile) = tbprofile::TBProfile::path() {
                    let pubring = profile.join("pubring.gpg");
                    if let Ok(pubring) = std::fs::metadata(pubring) {
                        let file_size = pubring.len();
                        t!("input is {} bytes, pubring.gpg is {} bytes.",
                           input_size, file_size);
                        if input_size == file_size {
                            t!("Looks like a match.  Periodically flushing \
                                the keystore to disk.");
                            (*ctx).certs.set_directory(profile);
                        } else {
                            t!("pubring.gpg does not match input.  \
                                Conservatively disabling flushing the \
                                keystore to disk.");
                        }
                    }
                }
            }

            // Also load GPG's public key database.
            if let Err(err) = (*ctx).certs.load_gpg_keyring() {
                warn!("Import gpg's keyring: {}", err);
            }

            // And load the WoT data.
            if let Err(err) = wot::WoT::monitor() {
                t!("Instantiating WoT updater: {}", err);
            }

            (*ctx).certs.start_parcimonie();
        }
        RNP_LOAD_SAVE_SECRET_KEYS => (),
        f => {
            eprintln!("sequoia-octopus: unexpected flags to rnp_load_keys: \
                       {:x}", f);
            return RNP_ERROR_BAD_PARAMETERS;
        },
    }

    use std::io::Read;
    let mut data = Vec::new();
    if let Err(err) = input.read_to_end(&mut data)
    {
        warn!("sequoia-octopus: Error reading input: {}", err);
        return RNP_ERROR_GENERIC;
    }

    if let Err(err) = (*ctx).certs.load_keyring_in_background(
        data, flags == RNP_LOAD_SAVE_SECRET_KEYS)
    {
        warn!("sequoia-octopus: Error reading certs: {}", err);
        return RNP_ERROR_GENERIC;
    }

    RNP_SUCCESS
}

#[no_mangle] pub unsafe extern "C"
fn rnp_save_keys(ctx: *mut RnpContext,
                 format: *const c_char,
                 output: *mut RnpOutput,
                 flags: RnpLoadSaveFlags)
                 -> RnpResult {
    rnp_function!(rnp_save_keys, TRACE);
    assert_ptr!(ctx);
    assert_ptr!(format);
    assert_ptr!(output);
    if CStr::from_ptr(format).to_bytes() != b"GPG" {
        return RNP_ERROR_BAD_FORMAT;
    }

    let output = &mut *output;
    let mut r = Ok(());
    match flags {
        RNP_LOAD_SAVE_PUBLIC_KEYS => {
            let _ = (*ctx).certs.block_on_load();
            for cert in (*ctx).certs.read().to_save().filter(|cert| ! cert.is_tsk()) {
                if let Err(err) = cert.serialize(output) {
                    r = Err(err);
                    break;
                }
            }
        },
        RNP_LOAD_SAVE_SECRET_KEYS => {
            let _ = (*ctx).certs.block_on_load();
            for cert in (*ctx).certs.read().to_save().filter(|cert| cert.is_tsk()) {
                if let Err(err) = cert.as_tsk().serialize(output) {
                    r = Err(err);
                    break;
                }
            }
        }
        f => {
            warn!("unexpected flags to rnp_load_keys: {:x}", f);
            return RNP_ERROR_BAD_PARAMETERS;
        },
    };

    if let Err(err) = r {
        warn!("failed saving keys: {}", err);
        RNP_ERROR_GENERIC
    } else {
        RNP_SUCCESS
    }
}

#[no_mangle] pub unsafe extern "C"
fn rnp_get_public_key_count(ctx: *mut RnpContext,
                            count: *mut size_t)
                            -> RnpResult {
    assert_ptr!(ctx);
    *count = (*ctx).certs.read().iter().filter(|cert| ! cert.is_tsk()).count();
    RNP_SUCCESS
}

#[no_mangle] pub unsafe extern "C"
fn rnp_get_secret_key_count(ctx: *mut RnpContext,
                            count: *mut size_t)
                            -> RnpResult {
    assert_ptr!(ctx);
    *count = (*ctx).certs.read().iter().filter(|cert| cert.is_tsk()).count();
    RNP_SUCCESS
}

// These are bound in RNPlib.jsm but not actually used.
macro_rules! unused {
    ($s: ident) => {
        #[no_mangle] pub extern "C"
        fn $s() -> RnpResult {
            warn!("previously unused function is used: {}", stringify!($s));
            RNP_ERROR_NOT_IMPLEMENTED
        }
    };
}

unused!(rnp_guess_contents);
unused!(rnp_decrypt);
unused!(rnp_symenc_get_aead_alg);
unused!(rnp_symenc_get_cipher);
unused!(rnp_symenc_get_hash_alg);
unused!(rnp_symenc_get_s2k_iterations);
unused!(rnp_symenc_get_s2k_type);