Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support encrypted assertions #47

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Changelog

### Unreleased
- add `EncryptedAssertion` and ability to decrypt it

### 0.0.15

- Updates dependencies
Expand Down
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ Current Features:
- IDP-initiated SSO
- SP-initiated SSO Redirect-POST binding
- Helpers for validating SAML assertions
- Encrypted assertions aren't supported yet
- Encrypted assertions only support:
- **key info:**
- `http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p`
- **value info:**
- `http://www.w3.org/2001/04/xmlenc#aes128-cbc`
- `http://www.w3.org/2009/xmlenc11#aes128-gcm`
- Verify SAMLRequest (AuthnRequest) message signatures
- Create signed SAMLResponse (Response) messages

Expand Down
46 changes: 44 additions & 2 deletions src/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use base64::{engine::general_purpose, Engine as _};
use std::collections::HashMap;
use std::convert::TryInto;
use std::ffi::CString;
use std::str::FromStr;
use thiserror::Error;

#[cfg(feature = "xmlsec")]
use crate::xmlsec::{self, XmlSecKey, XmlSecKeyFormat, XmlSecSignatureContext};
#[cfg(feature = "xmlsec")]
use libxml::parser::Parser as XmlParser;
#[cfg(feature = "xmlsec")]
use std::ffi::CString;
#[cfg(feature = "xmlsec")]
use openssl::symm::{Cipher, Crypter, Mode};

#[cfg(feature = "xmlsec")]
const XMLNS_XML_DSIG: &str = "http://www.w3.org/2000/09/xmldsig#";
Expand Down Expand Up @@ -671,6 +673,46 @@ impl UrlVerifier {
}
}

#[cfg(feature = "xmlsec")]
pub(crate) fn decrypt(
t: Cipher,
key: &[u8],
iv: Option<&[u8]>,
data: &[u8],
) -> Result<Vec<u8>, Error> {
let mut decrypter = Crypter::new(t, Mode::Decrypt, key, iv)?;
decrypter.pad(false);
let mut out = vec![0; data.len() + t.block_size()];

let count = decrypter.update(data, &mut out)?;
let rest = decrypter.finalize(&mut out[count..])?;

out.truncate(count + rest);
Ok(out)
}

#[cfg(feature = "xmlsec")]
pub(crate) fn decrypt_aead(
t: Cipher,
key: &[u8],
iv: Option<&[u8]>,
aad: &[u8],
data: &[u8],
tag: &[u8],
) -> Result<Vec<u8>, Error> {
let mut decrypter = Crypter::new(t, Mode::Decrypt, key, iv)?;
decrypter.pad(false);
let mut out = vec![0; data.len() + t.block_size()];

decrypter.aad_update(aad)?;
let count = decrypter.update(data, &mut out)?;
decrypter.set_tag(tag)?;
let rest = decrypter.finalize(&mut out[count..])?;

out.truncate(count + rest);
Ok(out)
}

#[cfg(test)]
mod test {
use super::UrlVerifier;
Expand Down
8 changes: 4 additions & 4 deletions src/idp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,8 @@ fn test_do_not_accept_unsigned_response() {

let err = resp.err().unwrap();
assert_eq!(
err,
crate::service_provider::Error::FailedToParseSamlResponse
err.to_string(),
crate::service_provider::Error::FailedToParseSamlResponse.to_string()
);
}

Expand All @@ -248,8 +248,8 @@ fn test_do_not_accept_signed_with_wrong_key() {
let err = resp.err().unwrap();

assert_eq!(
err,
crate::service_provider::Error::FailedToValidateSignature
err.to_string(),
crate::service_provider::Error::FailedToValidateSignature.to_string()
);
}

Expand Down
46 changes: 46 additions & 0 deletions src/key_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ use quick_xml::Writer;
use serde::Deserialize;
use std::io::Cursor;

use crate::schema::EncryptedKey;

const NAME: &str = "ds:KeyInfo";
const SCHEMA: &str = "xmlns:ds";

#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct KeyInfo {
Expand Down Expand Up @@ -83,3 +86,46 @@ impl TryFrom<&X509Data> for Event<'_> {
)?)))
}
}

#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct EncryptedKeyInfo {
#[serde(rename = "@Id")]
pub id: Option<String>,
#[serde(rename = "@xmlns:ds")]
pub ds: String,
#[serde(rename = "EncryptedKey")]
pub encrypted_key: Option<EncryptedKey>,
}

impl TryFrom<EncryptedKeyInfo> for Event<'_> {
type Error = Box<dyn std::error::Error>;

fn try_from(value: EncryptedKeyInfo) -> Result<Self, Self::Error> {
(&value).try_into()
}
}

impl TryFrom<&EncryptedKeyInfo> for Event<'_> {
type Error = Box<dyn std::error::Error>;

fn try_from(value: &EncryptedKeyInfo) -> Result<Self, Self::Error> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root = BytesStart::new(NAME);
if let Some(id) = &value.id {
root.push_attribute(("Id", id.as_ref()));
}
root.push_attribute((SCHEMA, value.ds.as_ref()));

writer.write_event(Event::Start(root))?;
if let Some(encrypted_key) = &value.encrypted_key {
let event: Event<'_> = encrypted_key.try_into()?;
writer.write_event(event)?;
}

writer.write_event(Event::End(BytesEnd::new(NAME)))?;
Ok(Event::Text(BytesText::from_escaped(String::from_utf8(
write_buf,
)?)))
}
}
Loading