initial work towards server-side support

This commit is contained in:
lumi 2017-03-16 20:04:22 +01:00
commit 4b9f2376af
10 changed files with 759 additions and 260 deletions

View file

@ -1,12 +1,15 @@
#![deny(missing_docs)]
//#![deny(missing_docs)]
//! This crate provides a framework for SASL authentication and a few authentication mechanisms.
//!
//! # Examples
//!
//! ## Simple client-sided usage
//!
//! ```rust
//! use sasl::{Credentials, Mechanism, Error};
//! use sasl::mechanisms::Plain;
//! use sasl::client::Mechanism;
//! use sasl::common::Credentials;
//! use sasl::client::mechanisms::Plain;
//!
//! let creds = Credentials::default()
//! .with_username("user")
@ -19,7 +22,98 @@
//! assert_eq!(initial_data, b"\0user\0pencil");
//! ```
//!
//! You may look at the tests of `mechanisms/scram.rs` for examples of more advanced usage.
//! ## More complex usage
//!
//! ```rust
//! use sasl::server::{Validator, Mechanism as ServerMechanism, Response};
//! use sasl::server::mechanisms::{Plain as ServerPlain, Scram as ServerScram};
//! use sasl::client::Mechanism as ClientMechanism;
//! use sasl::client::mechanisms::{Plain as ClientPlain, Scram as ClientScram};
//! use sasl::common::{Identity, Credentials, Secret, Password, ChannelBinding};
//! use sasl::common::scram::{ScramProvider, Sha1, Sha256};
//!
//! const USERNAME: &'static str = "user";
//! const PASSWORD: &'static str = "pencil";
//! const SALT: [u8; 8] = [35, 71, 92, 105, 212, 219, 114, 93];
//! const ITERATIONS: usize = 4096;
//!
//! struct MyValidator;
//!
//! impl Validator for MyValidator {
//! fn validate_credentials(&self, creds: &Credentials) -> Result<Identity, String> {
//! if creds.identity != Identity::Username(USERNAME.to_owned()) {
//! Err("authentication failure".to_owned())
//! }
//! else if creds.secret != Secret::password_plain(PASSWORD) {
//! Err("authentication failure".to_owned())
//! }
//! else {
//! Ok(creds.identity.clone())
//! }
//! }
//!
//! fn request_pbkdf2<S: ScramProvider>(&self) -> Result<(Vec<u8>, usize, Vec<u8>), String> {
//! Ok( ( SALT.to_vec()
//! , ITERATIONS
//! , S::derive(&Password::Plain(PASSWORD.to_owned()), &SALT, ITERATIONS)? ) )
//! }
//! }
//!
//! let mut mech = ServerPlain::new(MyValidator);
//! let expected_response = Response::Success(Identity::Username("user".to_owned()), Vec::new());
//! assert_eq!(mech.respond(b"\0user\0pencil"), Ok(expected_response));
//!
//! let mut mech = ServerPlain::new(MyValidator);
//! assert_eq!(mech.respond(b"\0user\0marker"), Err("authentication failure".to_owned()));
//!
//! let creds = Credentials::default()
//! .with_username(USERNAME)
//! .with_password(PASSWORD);
//!
//! fn finish<CM, SM, V>(cm: &mut CM, sm: &mut SM) -> Result<Identity, String>
//! where CM: ClientMechanism,
//! SM: ServerMechanism<V>,
//! V: Validator {
//! let init = cm.initial()?;
//! println!("C: {}", String::from_utf8_lossy(&init));
//! let mut resp = sm.respond(&init)?;
//! loop {
//! let msg;
//! match resp {
//! Response::Proceed(ref data) => {
//! println!("S: {}", String::from_utf8_lossy(&data));
//! msg = cm.response(data)?;
//! println!("C: {}", String::from_utf8_lossy(&msg));
//! },
//! _ => break,
//! }
//! resp = sm.respond(&msg)?;
//! }
//! if let Response::Success(ret, fin) = resp {
//! println!("S: {}", String::from_utf8_lossy(&fin));
//! cm.success(&fin)?;
//! Ok(ret)
//! }
//! else {
//! unreachable!();
//! }
//! }
//!
//! let mut client_mech = ClientPlain::from_credentials(creds.clone()).unwrap();
//! let mut server_mech = ServerPlain::new(MyValidator);
//!
//! assert_eq!(finish(&mut client_mech, &mut server_mech), Ok(Identity::Username(USERNAME.to_owned())));
//!
//! let mut client_mech = ClientScram::<Sha1>::from_credentials(creds.clone()).unwrap();
//! let mut server_mech = ServerScram::<Sha1, _>::new(MyValidator, ChannelBinding::Unsupported);
//!
//! assert_eq!(finish(&mut client_mech, &mut server_mech), Ok(Identity::Username(USERNAME.to_owned())));
//!
//! let mut client_mech = ClientScram::<Sha256>::from_credentials(creds.clone()).unwrap();
//! let mut server_mech = ServerScram::<Sha256, _>::new(MyValidator, ChannelBinding::Unsupported);
//!
//! assert_eq!(finish(&mut client_mech, &mut server_mech), Ok(Identity::Username(USERNAME.to_owned())));
//! ```
//!
//! # Usage
//!
@ -34,113 +128,8 @@ extern crate openssl;
mod error;
pub mod client;
pub mod common;
pub mod server;
pub use error::Error;
/// A struct containing SASL credentials.
#[derive(Clone, Debug)]
pub struct Credentials {
/// The requested username.
pub username: Option<String>,
/// The secret used to authenticate.
pub secret: Secret,
/// Channel binding data, for *-PLUS mechanisms.
pub channel_binding: ChannelBinding,
}
impl Default for Credentials {
fn default() -> Credentials {
Credentials {
username: None,
secret: Secret::None,
channel_binding: ChannelBinding::None,
}
}
}
impl Credentials {
/// Creates a new Credentials with the specified username.
pub fn with_username<N: Into<String>>(mut self, username: N) -> Credentials {
self.username = Some(username.into());
self
}
/// Creates a new Credentials with the specified password.
pub fn with_password<P: Into<String>>(mut self, password: P) -> Credentials {
self.secret = Secret::Password(password.into());
self
}
/// Creates a new Credentials with the specified chanel binding.
pub fn with_channel_binding(mut self, channel_binding: ChannelBinding) -> Credentials {
self.channel_binding = channel_binding;
self
}
}
/// Channel binding configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChannelBinding {
/// No channel binding data.
None,
/// Advertise that the client does not think the server supports channel binding.
Unsupported,
/// p=tls-unique channel binding data.
TlsUnique(Vec<u8>),
}
impl ChannelBinding {
/// Return the gs2 header for this channel binding mechanism.
pub fn header(&self) -> &[u8] {
match *self {
ChannelBinding::None => b"n,,",
ChannelBinding::Unsupported => b"y,,",
ChannelBinding::TlsUnique(_) => b"p=tls-unique,,",
}
}
/// Return the channel binding data for this channel binding mechanism.
pub fn data(&self) -> &[u8] {
match *self {
ChannelBinding::None => &[],
ChannelBinding::Unsupported => &[],
ChannelBinding::TlsUnique(ref data) => data,
}
}
}
/// Represents a SASL secret, like a password.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Secret {
/// No extra data needed.
None,
/// Password required.
Password(String),
}
/// A trait which defines SASL mechanisms.
pub trait Mechanism {
/// The name of the mechanism.
fn name(&self) -> &str;
/// Creates this mechanism from `Credentials`.
fn from_credentials(credentials: Credentials) -> Result<Self, String>
where
Self: Sized;
/// Provides initial payload of the SASL mechanism.
fn initial(&mut self) -> Result<Vec<u8>, String> {
Ok(Vec::new())
}
/// Creates a response to the SASL challenge.
fn response(&mut self, _challenge: &[u8]) -> Result<Vec<u8>, String> {
Ok(Vec::new())
}
/// Verifies the server success response, if there is one.
fn success(&mut self, _data: &[u8]) -> Result<(), String> {
Ok(())
}
}
pub mod mechanisms;