Skip to content
Merged
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
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ winauth = { version = "0.0.4", optional = true }

[target.'cfg(unix)'.dependencies]
libgssapi = { version = "0.8.1", optional = true, default-features = false }
sspi = { version = "0.18", optional = true }
libc = "0.2"

[dependencies.async-native-tls]
Expand Down Expand Up @@ -220,6 +221,7 @@ all = [
"bigdecimal",
"native-tls",
"serde",
"sspi-rs",
]
default = ["tds80", "winauth", "native-tls"]
tds73 = []
Expand All @@ -234,6 +236,10 @@ bigdecimal = ["bigdecimal_"]
rustls = ["tokio-rustls", "tokio-util", "rustls-native-certs"]
native-tls = ["async-native-tls"]
vendored-openssl = ["opentls"]
# Enables Windows-style SSPI/NTLM authentication (`AuthMethod::Windows`) on Unix
# platforms without requiring Kerberos, via the pure-Rust `sspi` crate. On
# Windows the same authentication is provided by the `winauth` feature.
sspi-rs = ["sspi"]
# Optional serde Serialize/Deserialize impls for query result types
# (Row, Column, ColumnData, Numeric, ColumnType and time/xml types).
serde = ["dep:serde", "uuid/serde"]
32 changes: 23 additions & 9 deletions src/client/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,22 @@ impl Debug for SqlServerAuth {
}

#[derive(Clone, PartialEq, Eq)]
#[cfg(any(all(windows, feature = "winauth"), doc))]
#[cfg_attr(docsrs, doc(all(windows, feature = "winauth")))]
#[cfg(any(all(windows, feature = "winauth"), all(unix, feature = "sspi-rs"), doc))]
#[cfg_attr(
docsrs,
doc(cfg(any(all(windows, feature = "winauth"), all(unix, feature = "sspi-rs"))))
)]
pub struct WindowsAuth {
pub(crate) user: String,
pub(crate) password: String,
pub(crate) domain: Option<String>,
}

#[cfg(any(all(windows, feature = "winauth"), doc))]
#[cfg_attr(docsrs, doc(all(windows, feature = "winauth")))]
#[cfg(any(all(windows, feature = "winauth"), all(unix, feature = "sspi-rs"), doc))]
#[cfg_attr(
docsrs,
doc(cfg(any(all(windows, feature = "winauth"), all(unix, feature = "sspi-rs"))))
)]
impl Debug for WindowsAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WindowsAuth")
Expand All @@ -48,9 +54,14 @@ impl Debug for WindowsAuth {
pub enum AuthMethod {
/// Authenticate directly with SQL Server.
SqlServer(SqlServerAuth),
/// Authenticate with Windows credentials.
#[cfg(any(all(windows, feature = "winauth"), doc))]
#[cfg_attr(docsrs, doc(cfg(all(windows, feature = "winauth"))))]
/// Authenticate with Windows credentials. On Windows this uses SSPI via the
/// `winauth` feature; on Unix it uses NTLM (no Kerberos) via the `sspi-rs`
/// feature.
#[cfg(any(all(windows, feature = "winauth"), all(unix, feature = "sspi-rs"), doc))]
#[cfg_attr(
docsrs,
doc(cfg(any(all(windows, feature = "winauth"), all(unix, feature = "sspi-rs"))))
)]
Windows(WindowsAuth),
/// Authenticate as the currently logged in user. On Windows uses SSPI and
/// Kerberos on Unix platforms.
Expand Down Expand Up @@ -81,8 +92,11 @@ impl AuthMethod {
}

/// Construct a new Windows authentication configuration.
#[cfg(any(all(windows, feature = "winauth"), doc))]
#[cfg_attr(docsrs, doc(cfg(all(windows, feature = "winauth"))))]
#[cfg(any(all(windows, feature = "winauth"), all(unix, feature = "sspi-rs"), doc))]
#[cfg_attr(
docsrs,
doc(cfg(any(all(windows, feature = "winauth"), all(unix, feature = "sspi-rs"))))
)]
pub fn windows(user: impl AsRef<str>, password: impl ToString) -> Self {
let (domain, user) = match user.as_ref().find('\\') {
Some(idx) => (Some(&user.as_ref()[..idx]), &user.as_ref()[idx + 1..]),
Expand Down
35 changes: 34 additions & 1 deletion src/client/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,23 @@ pub(crate) trait ConfigString {
(None, None) => Ok(AuthMethod::Integrated),
_ => Ok(AuthMethod::windows(user.unwrap_or(""), pw.unwrap_or(""))),
},
#[cfg(feature = "integrated-auth-gssapi")]
// On Unix with `sspi-rs`, `IntegratedSecurity=SSPI` (or a truthy
// value) uses NTLM when a username/password is supplied, and falls
// back to Kerberos (`Integrated`) only if `integrated-auth-gssapi`
// is also enabled and no credentials are given.
#[cfg(all(unix, feature = "sspi-rs"))]
Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => {
match (user, pw) {
(Some(user), Some(pw)) => Ok(AuthMethod::windows(user, pw)),
#[cfg(feature = "integrated-auth-gssapi")]
(None, None) => Ok(AuthMethod::Integrated),
_ => Ok(AuthMethod::windows(user.unwrap_or(""), pw.unwrap_or(""))),
}
}
#[cfg(all(
feature = "integrated-auth-gssapi",
not(all(unix, feature = "sspi-rs"))
))]
Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => {
Ok(AuthMethod::Integrated)
}
Expand Down Expand Up @@ -695,4 +711,21 @@ mod tests {
assert_eq!("localhost:1433", config.get_addr());
assert_eq!(Some("master"), config.database.as_deref());
}

#[cfg(all(unix, feature = "sspi-rs"))]
#[test]
fn ado_integrated_security_sspi_with_credentials_uses_windows_ntlm() {
let config = Config::from_ado_string(
"server=tcp:localhost,1433;IntegratedSecurity=SSPI;uid=DOMAIN\\user;pwd=secret",
)
.unwrap();

match config.auth {
AuthMethod::Windows(auth) => {
assert_eq!("user", auth.user);
assert_eq!(Some("DOMAIN"), auth.domain.as_deref());
}
other => panic!("expected Windows NTLM auth, got {other:?}"),
}
}
}
87 changes: 85 additions & 2 deletions src/client/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::{
};
use asynchronous_codec::Framed;
use bytes::BytesMut;
#[cfg(any(windows, feature = "integrated-auth-gssapi"))]
#[cfg(any(windows, feature = "integrated-auth-gssapi", feature = "sspi-rs"))]
use codec::TokenSspi;
use futures_util::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
use futures_util::ready;
Expand All @@ -32,6 +32,11 @@ use libgssapi::{
oid::{OidSet, GSS_MECH_KRB5, GSS_NT_KRB5_PRINCIPAL},
};
use pretty_hex::*;
#[cfg(all(unix, feature = "sspi-rs"))]
use sspi::{
AuthIdentity, BufferType, ClientRequestFlags, CredentialUse, DataRepresentation, Ntlm,
SecurityBuffer, Sspi, SspiImpl, Username,
};
#[cfg(all(unix, feature = "integrated-auth-gssapi"))]
use std::ops::Deref;
use std::{cmp, fmt::Debug, io, pin::Pin, task};
Expand Down Expand Up @@ -155,7 +160,7 @@ impl<S: AsyncRead + AsyncWrite + Unpin + Send> Connection<S> {
TokenStream::new(self).flush_done().await
}

#[cfg(any(windows, feature = "integrated-auth-gssapi"))]
#[cfg(any(windows, feature = "integrated-auth-gssapi", feature = "sspi-rs"))]
/// Flush the incoming token stream until receiving `SSPI` token.
async fn flush_sspi(&mut self) -> crate::Result<TokenSspi> {
TokenStream::new(self).flush_sspi().await
Expand Down Expand Up @@ -488,6 +493,84 @@ impl<S: AsyncRead + AsyncWrite + Unpin + Send> Connection<S> {

self.send(header, next_token).await?;
}
#[cfg(all(unix, feature = "sspi-rs"))]
AuthMethod::Windows(auth) => {
let mut ntlm = Ntlm::new();

let username =
Username::new(&auth.user, auth.domain.as_deref()).map_err(sspi::Error::from)?;

let identity = AuthIdentity {
username,
password: auth.password.clone().into(),
};

let mut creds = ntlm
.acquire_credentials_handle()
.with_credential_use(CredentialUse::Outbound)
.with_auth_data(&identity)
.execute(&mut ntlm)?;

let spn = self.context.spn().to_string();

// First leg of the NTLM handshake: produce the NEGOTIATE token
// and ship it in the login packet as integrated security data.
let mut input = vec![SecurityBuffer::new(Vec::new(), BufferType::Token)];
let mut output = vec![SecurityBuffer::new(Vec::new(), BufferType::Token)];

let mut builder = ntlm
.initialize_security_context()
.with_credentials_handle(&mut creds.credentials_handle)
.with_context_requirements(
ClientRequestFlags::CONFIDENTIALITY | ClientRequestFlags::ALLOCATE_MEMORY,
)
.with_target_data_representation(DataRepresentation::Native)
.with_target_name(&spn)
.with_input(&mut input)
.with_output(&mut output);

ntlm.initialize_security_context_impl(&mut builder)?
.resolve_to_result()?;

login_message.integrated_security(Some(output[0].buffer.clone()));

let id = self.context.next_packet_id();
self.send(PacketHeader::login(id), login_message).await?;
self = self.post_login_encryption(encryption);

// Second leg: consume the server's CHALLENGE token and reply
// with the AUTHENTICATE token.
let sspi_bytes = self.flush_sspi().await?;

let mut input = vec![SecurityBuffer::new(
sspi_bytes.as_ref().to_vec(),
BufferType::Token,
)];
let mut output = vec![SecurityBuffer::new(Vec::new(), BufferType::Token)];

let mut builder = ntlm
.initialize_security_context()
.with_credentials_handle(&mut creds.credentials_handle)
.with_context_requirements(
ClientRequestFlags::CONFIDENTIALITY | ClientRequestFlags::ALLOCATE_MEMORY,
)
.with_target_data_representation(DataRepresentation::Native)
.with_target_name(&spn)
.with_input(&mut input)
.with_output(&mut output);

ntlm.initialize_security_context_impl(&mut builder)?
.resolve_to_result()?;

event!(Level::TRACE, authenticate_len = output[0].buffer.len());

let id = self.context.next_packet_id();
self.send(
PacketHeader::login(id),
TokenSspi::new(output[0].buffer.clone()),
)
.await?;
}
#[cfg(all(windows, feature = "winauth"))]
AuthMethod::Windows(auth) => {
let spn = self.context.spn().to_string();
Expand Down
15 changes: 14 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ pub enum Error {
/// An error from the GSSAPI library.
#[error("GSSAPI Error: {}", _0)]
Gssapi(String),
#[cfg(any(all(unix, feature = "sspi-rs"), doc))]
#[cfg_attr(docsrs, doc(cfg(all(unix, feature = "sspi-rs"))))]
/// An error from the `sspi` (sspi-rs) library.
#[error("sspi-rs Error: {}", _0)]
SspiRs(String),
#[error(
"Server requested a connection to an alternative address: `{}:{}`",
host,
Expand Down Expand Up @@ -80,7 +85,7 @@ impl Error {

impl From<uuid::Error> for Error {
fn from(e: uuid::Error) -> Self {
Self::Conversion(format!("Error convertiong a Guid value {}", e).into())
Self::Conversion(format!("Error converting a Guid value {}", e).into())
}
}

Expand Down Expand Up @@ -152,6 +157,14 @@ impl From<libgssapi::error::Error> for Error {
}
}

#[cfg(all(unix, feature = "sspi-rs"))]
#[cfg_attr(docsrs, doc(cfg(all(unix, feature = "sspi-rs"))))]
impl From<sspi::Error> for Error {
fn from(err: sspi::Error) -> Error {
Error::SspiRs(format!("{}", err))
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
5 changes: 4 additions & 1 deletion src/tds/codec/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,10 @@ impl<'a> LoginMessage<'a> {
get_computer_name().map(Cow::Owned).unwrap_or_default()
}

#[cfg(any(all(unix, feature = "integrated-auth-gssapi"), windows))]
#[cfg(any(
all(unix, any(feature = "integrated-auth-gssapi", feature = "sspi-rs")),
windows
))]
pub fn integrated_security(&mut self, bytes: Option<Vec<u8>>) {
if bytes.is_some() {
self.option_flags_2.insert(OptionFlag2::IntegratedSecurity);
Expand Down
5 changes: 4 additions & 1 deletion src/tds/codec/token/token_sspi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ impl AsRef<[u8]> for TokenSspi {
}

impl TokenSspi {
#[cfg(any(windows, all(unix, feature = "integrated-auth-gssapi")))]
#[cfg(any(
windows,
all(unix, any(feature = "integrated-auth-gssapi", feature = "sspi-rs"))
))]
pub fn new(bytes: Vec<u8>) -> Self {
Self(bytes)
}
Expand Down
5 changes: 4 additions & 1 deletion src/tds/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ impl Context {
self.spn = Some(format!("MSSQLSvc/{}:{}", host.as_ref(), port));
}

#[cfg(any(windows, all(unix, feature = "integrated-auth-gssapi")))]
#[cfg(any(
windows,
all(unix, any(feature = "integrated-auth-gssapi", feature = "sspi-rs"))
))]
pub fn spn(&self) -> &str {
self.spn.as_deref().unwrap_or("")
}
Expand Down
2 changes: 1 addition & 1 deletion src/tds/stream/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ where
}
}

#[cfg(any(windows, feature = "integrated-auth-gssapi"))]
#[cfg(any(windows, feature = "integrated-auth-gssapi", feature = "sspi-rs"))]
pub(crate) async fn flush_sspi(self) -> crate::Result<TokenSspi> {
let mut stream = self.try_unfold();
let mut last_error = None;
Expand Down