pub trait SessionJoinString<'de>: CborDecode<'de, ()> + CborEncode<()> {
    fn scheme() -> &'static str;

    fn to_bytes(&self) -> Result<Vec<u8>, RemoteSignError> { ... }
}
Expand description

Common behaviors for a session join string.

Implementations must also implement Encode, which will emit the CBOR encoding of the instance to an encoder.

Required Methods§

The scheme / name for this SJS implementation.

This is advertised as the first component in the encoded SJS.

Provided Methods§

Obtain the raw bytes constituting the session join string.

Examples found in repository?
src/remote_signing/session_negotiation.rs (line 448)
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
    fn session_join_string_bytes(&self) -> Result<Vec<u8>> {
        self.sjs.to_bytes()
    }

    fn negotiate_session(self: Box<Self>, peer_context: Option<Vec<u8>>) -> Result<PeerKeys> {
        let public_key = peer_context.ok_or_else(|| {
            RemoteSignError::Crypto(
                "missing peer public key context in session join message".into(),
            )
        })?;

        let public_key = UnparsedPublicKey::new(&X25519, public_key);

        let (sealing, opening) = agree_ephemeral(
            self.agreement_private,
            &public_key,
            RemoteSignError::Crypto("error deriving agreement key".into()),
            |agreement_key| {
                derive_aead_keys(
                    Role::A,
                    agreement_key.to_vec(),
                    &self.session_id,
                    &self.extra_identifier,
                )
            },
        )
        .map_err(|_| {
            RemoteSignError::Crypto("error deriving AEAD keys from agreement key".into())
        })?;

        Ok(PeerKeys { sealing, opening })
    }
}

impl PublicKeyInitiator {
    /// Create a new initiator using public key agreement.
    pub fn new(peer_public_key: impl AsRef<[u8]>, server_url: Option<String>) -> Result<Self> {
        let spki = SubjectPublicKeyInfo::from_der(peer_public_key.as_ref())
            .map_err(|e| RemoteSignError::Crypto(format!("when parsing SPKI data: {e}")))?;

        let session_id = uuid::Uuid::new_v4().to_string();

        let rng = SystemRandom::new();

        let mut challenge = [0u8; 32];
        rng.fill(&mut challenge)
            .map_err(|_| RemoteSignError::Crypto("failed to generate random data".into()))?;

        let mut aes_key_data = [0u8; 16];
        rng.fill(&mut aes_key_data)
            .map_err(|_| RemoteSignError::Crypto("failed to generate random data".into()))?;

        let agreement_private = EphemeralPrivateKey::generate(&X25519, &rng).map_err(|_| {
            RemoteSignError::Crypto("failed to generate ephemeral agreement key".into())
        })?;

        let agreement_public = agreement_private.compute_public_key().map_err(|_| {
            RemoteSignError::Crypto(
                "failed to derive public key from ephemeral agreement key".into(),
            )
        })?;

        let peer_message = PublicKeySecretMessage {
            server_url,
            session_id: session_id.clone(),
            challenge: challenge.as_ref().to_vec(),
            agreement_public: agreement_public.as_ref().to_vec(),
        };

        // The unique AES key is used to encrypt the main CBOR message.
        let mut message_ciphertext = minicbor::to_vec(peer_message)
            .map_err(|e| RemoteSignError::Crypto(format!("CBOR encode error: {e}")))?;
        let aes_key = UnboundKey::new(&AES_128_GCM, &aes_key_data).map_err(|_| {
            RemoteSignError::Crypto("failed to load AES encryption key into ring".into())
        })?;
        let mut sealing_key = SealingKey::new(aes_key, ConstantNonceSequence::default());
        sealing_key
            .seal_in_place_append_tag(Aad::empty(), &mut message_ciphertext)
            .map_err(|_| RemoteSignError::Crypto("failed to AES encrypt message to peer".into()))?;

        // The AES encrypting key is encrypted using asymmetric encryption.

        let aes_ciphertext = match spki.algorithm.oid.as_ref() {
            x if x == OID_PKCS1_RSAENCRYPTION.as_bytes() => {
                let public_key =
                    RsaPublicKeyAsn1::from_der(spki.subject_public_key).map_err(|e| {
                        RemoteSignError::Crypto(format!("when parsing RSA public key: {e}"))
                    })?;

                let n = BigUint::from_bytes_be(public_key.modulus.as_bytes());
                let e = BigUint::from_bytes_be(public_key.public_exponent.as_bytes());

                let rsa_public = RsaPublicKey::new(n, e).map_err(|e| {
                    RemoteSignError::Crypto(format!("when constructing RSA public key: {e}"))
                })?;

                let padding = PaddingScheme::new_oaep::<sha2::Sha256>();

                rsa_public
                    .encrypt(&mut rand::thread_rng(), padding, &aes_key_data)
                    .map_err(|e| {
                        RemoteSignError::Crypto(format!("RSA public key encryption error: {e}"))
                    })?
            }
            _ => {
                return Err(RemoteSignError::Crypto(format!(
                    "do not know how to encrypt for algorithm {}",
                    spki.algorithm.oid
                )));
            }
        };

        let public_key = spki
            .to_vec()
            .map_err(|e| RemoteSignError::Crypto(format!("when encoding SPKI to DER: {e}")))?;

        let sjs = PublicKeySessionJoinString {
            aes_ciphertext,
            public_key,
            message_ciphertext,
        };

        Ok(Self {
            session_id,
            extra_identifier: challenge.as_ref().to_vec(),
            sjs,
            agreement_private,
        })
    }
}

/// Describes a type that is capable of decrypting messages used during public key negotiation.
pub trait PublicKeyPeerDecrypt {
    /// Decrypt an encrypted message.
    fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>>;
}

/// A joining peer using public key encryption.
struct PublicKeyPeerPreJoined {
    sjs: PublicKeySessionJoinString,

    decrypter: Option<Box<dyn PublicKeyPeerDecrypt>>,
}

impl SessionJoinPeerPreJoin for PublicKeyPeerPreJoined {
    fn register_state(&mut self, state: SessionJoinState) -> Result<()> {
        match state {
            SessionJoinState::PublicKeyDecrypt(decrypt) => {
                self.decrypter = Some(decrypt);
                Ok(())
            }
            SessionJoinState::SharedSecret(_) => Ok(()),
        }
    }

    fn join_context(self: Box<Self>) -> Result<SessionJoinContext> {
        let decrypter = self
            .decrypter
            .ok_or_else(|| RemoteSignError::Crypto("decryption key not registered".into()))?;

        let aes_key = decrypter.decrypt(&self.sjs.aes_ciphertext)?;
        let aes_key = UnboundKey::new(&AES_128_GCM, &aes_key).map_err(|_| {
            RemoteSignError::Crypto("failed to construct AES key from key data".into())
        })?;
        let mut opening_key = OpeningKey::new(aes_key, ConstantNonceSequence::default());

        let mut cbor_message = self.sjs.message_ciphertext.clone();
        let cbor_plaintext = opening_key
            .open_in_place(Aad::empty(), &mut cbor_message)
            .map_err(|_| {
                RemoteSignError::Crypto("failed to decrypt using shared AES key".into())
            })?;

        // The plaintext is a CBOR encoded message.
        let message = minicbor::decode::<PublicKeySecretMessage>(cbor_plaintext)
            .map_err(|e| RemoteSignError::Crypto(format!("CBOR decode error: {e}")))?;

        let agreement_private = EphemeralPrivateKey::generate(&X25519, &SystemRandom::new())
            .map_err(|_| {
                RemoteSignError::Crypto("failed to generate ephemeral agreement key".into())
            })?;
        let agreement_public = agreement_private.compute_public_key().map_err(|_| {
            RemoteSignError::Crypto(
                "failed to derive public key from ephemeral agreement key".into(),
            )
        })?;

        let peer_handshake = Box::new(PublicKeyHandshakePeer {
            session_id: message.session_id.clone(),
            extra_identifier: message.challenge,
            agreement_private,
            agreement_public: message.agreement_public,
        });

        Ok(SessionJoinContext {
            server_url: message.server_url,
            session_id: message.session_id,
            peer_context: Some(agreement_public.as_ref().to_vec()),
            peer_handshake,
        })
    }
}

impl PublicKeyPeerPreJoined {
    fn new(sjs: PublicKeySessionJoinString) -> Result<Self> {
        Ok(Self {
            sjs,
            decrypter: None,
        })
    }
}

pub struct PublicKeyHandshakePeer {
    session_id: String,
    extra_identifier: Vec<u8>,
    agreement_private: EphemeralPrivateKey,
    agreement_public: Vec<u8>,
}

impl SessionJoinPeerHandshake for PublicKeyHandshakePeer {
    fn negotiate_session(self: Box<Self>) -> Result<PeerKeys> {
        let peer_public_key = UnparsedPublicKey::new(&X25519, &self.agreement_public);

        let (sealing, opening) = agree_ephemeral(
            self.agreement_private,
            &peer_public_key,
            RemoteSignError::Crypto("error deriving agreement key".into()),
            |agreement_key| {
                derive_aead_keys(
                    Role::B,
                    agreement_key.to_vec(),
                    &self.session_id,
                    &self.extra_identifier,
                )
            },
        )
        .map_err(|_| {
            RemoteSignError::Crypto("error deriving AEAD keys from agreement key".into())
        })?;

        Ok(PeerKeys { sealing, opening })
    }
}

fn spake_identity(role: Role, session_id: &str, extra_identifier: &[u8]) -> Identity {
    Identity::new(&derive_hkdf_info(role, session_id, extra_identifier))
}

pub struct SharedSecretInitiator {
    sjs: SharedSecretSessionJoinString,
    spake: Spake2<Ed25519Group>,
}

impl SessionInitiatePeer for SharedSecretInitiator {
    fn session_id(&self) -> &str {
        &self.sjs.session_id
    }

    fn session_create_context(&self) -> Option<Vec<u8>> {
        None
    }

    fn session_join_string_bytes(&self) -> Result<Vec<u8>> {
        self.sjs.to_bytes()
    }

Implementors§