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

Use GSSAPI for IntegratedSecurity on Unix #77

Merged
merged 7 commits into from
Aug 29, 2020
Merged
Show file tree
Hide file tree
Changes from 4 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: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ async-trait = "0.1"
[target.'cfg(windows)'.dependencies]
winauth = "0.0.4"

[target.'cfg(unix)'.dependencies]
libgssapi = { version = "0.4", optional = true }

[dependencies.tokio]
version = "0.2"
optional = true
Expand Down Expand Up @@ -110,11 +113,12 @@ anyhow = "1"
env_logger = "0.7"

[package.metadata.docs.rs]
features = ["tls", "chrono", "tds73", "sql-browser-async-std", "sql-browser-tokio"]
features = ["tls", "chrono", "tds73", "sql-browser-async-std", "sql-browser-tokio", "integrated-auth-gssapi"]

[features]
default = ["tls", "tds73"]
tls = ["async-native-tls"]
tds73 = []
sql-browser-async-std = ["async-std"]
sql-browser-tokio = ["tokio", "tokio-util"]
integrated-auth-gssapi = ["libgssapi"]
4 changes: 4 additions & 0 deletions src/client/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ pub enum AuthMethod {
/// Authenticate as the currently logged in user. Only available on Windows
/// platforms.
WindowsIntegrated,
#[cfg(any(feature = "integrated-auth-gssapi", doc))]
/// Authenticate as the currently logged in (Kerberos) user. (Enable feature
/// `integrated-auth-gssapi`) to enable.
Integrated,
#[doc(hidden)]
None,
}
Expand Down
4 changes: 3 additions & 1 deletion src/client/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl Config {
/// |Parameter|Allowed values|Description|
/// |--------|--------|--------|
/// |`server`|`<string>`|The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name. The correct form of this parameter is either `tcp:host,port` or `tcp:host\\instance`|
/// |`IntegratedSecurity`|`true`,`false`,`yes`,`no`|Toggle between Windows authentication and SQL authentication.|
/// |`IntegratedSecurity`|`true`,`false`,`yes`,`no`|Toggle between Windows/Kerberos authentication and SQL authentication.|
/// |`uid`,`username`,`user`,`user id`|`<string>`|The SQL Server login account.|
/// |`password`,`pwd`|`<string>`|The password for the SQL Server account logging on.|
/// |`database`|`<string>`|The name of the database.|
Expand Down Expand Up @@ -281,6 +281,8 @@ impl AdoNetString {
(None, None) => Ok(AuthMethod::WindowsIntegrated),
_ => Ok(AuthMethod::windows(user.unwrap_or(""), pw.unwrap_or(""))),
},
#[cfg(feature = "integrated-auth-gssapi")]
Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => Ok(AuthMethod::Integrated),
_ => Ok(AuthMethod::sql_server(user.unwrap_or(""), pw.unwrap_or(""))),
}
}
Expand Down
61 changes: 55 additions & 6 deletions src/client/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
EncryptionLevel, SqlReadBytes,
};
use bytes::BytesMut;
#[cfg(windows)]
#[cfg(any(windows, feature = "integrated-auth-gssapi"))]
use codec::TokenSSPI;
use futures::{ready, AsyncRead, AsyncWrite, SinkExt, Stream, TryStream, TryStreamExt};
use futures_codec::Framed;
Expand All @@ -23,6 +23,15 @@ use task::Poll;
use tracing::{event, Level};
#[cfg(windows)]
use winauth::{windows::NtlmSspiBuilder, NextBytes};
#[cfg(feature = "integrated-auth-gssapi")]
use libgssapi::{
name::Name,
credential::{Cred, CredUsage},
context::{CtxFlags, ClientCtx},
oid::{OidSet, GSS_NT_KRB5_PRINCIPAL, GSS_MECH_KRB5}
};
#[cfg(feature = "integrated-auth-gssapi")]
use std::ops::Deref;

/// A `Connection` is an abstraction between the [`Client`] and the server. It
/// can be used as a `Stream` to fetch [`Packet`]s from and to `send` packets
Expand Down Expand Up @@ -55,16 +64,12 @@ impl<S: AsyncRead + AsyncWrite + Unpin + Send> Connection<S> {
/// Creates a new connection
pub(crate) async fn connect(config: Config, tcp_stream: S) -> crate::Result<Connection<S>>
where {
#[cfg(windows)]
let context = {
let mut context = Context::new();
context.set_spn(config.get_host(), config.get_port());
context
};

#[cfg(not(windows))]
let context = { Context::new() };

let transport = Framed::new(MaybeTlsStream::Raw(tcp_stream), PacketCodec);

let mut connection = Self {
Expand Down Expand Up @@ -95,7 +100,7 @@ where {
TokenStream::new(self).flush_done().await
}

#[cfg(windows)]
#[cfg(any(windows, feature = "integrated-auth-gssapi"))]
/// 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 @@ -262,6 +267,50 @@ where {
None => unreachable!(),
}
}
#[cfg(feature = "integrated-auth-gssapi")]
AuthMethod::Integrated => {
let mut s = OidSet::new()?;
s.add(&GSS_MECH_KRB5)?;

let client_cred = Cred::acquire(
None, None, CredUsage::Initiate, Some(&s)
)?;

let ctx = ClientCtx::new(
client_cred,
Name::new(self.context.spn().as_bytes(), Some(&GSS_NT_KRB5_PRINCIPAL))?,
CtxFlags::GSS_C_MUTUAL_FLAG | CtxFlags::GSS_C_SEQUENCE_FLAG,
None,
);

let init_token = ctx.step(None)?;

msg.integrated_security = Some(Vec::from(init_token.unwrap().deref()));

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

self = self.post_login_encryption(encryption);

let auth_bytes = self.flush_sspi().await?;

let next_token = match ctx.step(Some(auth_bytes.as_ref()))? {
Some(response) => {
event!(Level::TRACE, response_len = response.len());
TokenSSPI::new(Vec::from(response.deref()))
esheppa marked this conversation as resolved.
Show resolved Hide resolved
},
None => {
event!(Level::TRACE, response_len = 0);
TokenSSPI::new(Vec::new())
esheppa marked this conversation as resolved.
Show resolved Hide resolved
}
};

let id = self.context.next_packet_id();
let header = PacketHeader::login(id);

self.send(header, next_token).await?;

},
#[cfg(windows)]
AuthMethod::Windows(auth) => {
let spn = self.context.spn().to_string();
Expand Down
11 changes: 11 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ pub enum Error {
#[error("Error forming TLS connection: {}", _0)]
/// An error in the TLS handshake.
Tls(String),
#[cfg(any(feature = "integrated-auth-gssapi", doc))]
/// An error from the GSSAPI library.
#[error("GSSAPI Error: {}", _0)]
Gssapi(String)
}

impl From<uuid::Error> for Error {
Expand Down Expand Up @@ -93,3 +97,10 @@ impl From<std::string::FromUtf16Error> for Error {
Error::Utf16
}
}

#[cfg(feature = "integrated-auth-gssapi")]
impl From<libgssapi::error::Error> for Error {
fn from(err: libgssapi::error::Error) -> Error {
Error::Gssapi(format!("{}", err))
}
}
7 changes: 4 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,11 @@
//! Tiberius supports different [ways of authentication] to the SQL Server:
//!
//! - SQL Server authentication uses the facilities of the database to
//! authenticate the user. This is also the only cross-platform method that
//! works outside of Windows platforms.
//! authenticate the user.
//! - Authentication with Windows credentials
//! - Authentication with currently logged in Windows user
//! - Authentication with currently logged in Windows user / Kerberos credentials
//! - Authentication with currently logged in Kerberos credentials via GSSAPI (feature =
//! `integrated-auth-gssapi`)
//!
//! # TLS
//!
Expand Down
2 changes: 0 additions & 2 deletions src/tds/codec/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ mod token_login_ack;
mod token_order;
mod token_return_value;
mod token_row;
#[cfg(windows)]
mod token_sspi;
mod token_type;

Expand All @@ -20,6 +19,5 @@ pub use token_login_ack::*;
pub use token_order::*;
pub use token_return_value::*;
pub use token_row::*;
#[cfg(windows)]
pub use token_sspi::*;
pub use token_type::*;
1 change: 1 addition & 0 deletions src/tds/codec/token/token_sspi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ impl AsRef<[u8]> for TokenSSPI {
}

impl TokenSSPI {
#[cfg(any(windows, feature = "integrated-auth-gssapi"))]
pub fn new(bytes: Vec<u8>) -> Self {
Self(bytes)
}
Expand Down
5 changes: 1 addition & 4 deletions src/tds/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ pub(crate) struct Context {
packet_id: u8,
transaction_id: u64,
last_meta: Option<Arc<TokenColMetaData>>,
#[cfg(windows)]
spn: Option<String>,
}

Expand All @@ -21,7 +20,6 @@ impl Context {
packet_id: 0,
transaction_id: 0,
last_meta: None,
#[cfg(windows)]
spn: None,
}
}
Expand Down Expand Up @@ -60,12 +58,11 @@ impl Context {
self.version
}

#[cfg(windows)]
pub fn set_spn(&mut self, host: impl AsRef<str>, port: u16) {
self.spn = Some(format!("MSSQLSvc/{}:{}", host.as_ref(), port));
}

#[cfg(windows)]
#[cfg(any(windows, feature = "integrated-auth-gssapi"))]
pub fn spn(&self) -> &str {
self.spn.as_ref().map(|s| s.as_str()).unwrap_or("")
}
Expand Down
6 changes: 1 addition & 5 deletions src/tds/stream/token.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#[cfg(windows)]
use crate::tds::codec::TokenSSPI;
use crate::{
client::Connection,
Expand All @@ -25,7 +24,6 @@ pub enum ReceivedToken {
EnvChange(TokenEnvChange),
Info(TokenInfo),
LoginAck(TokenLoginAck),
#[cfg(windows)]
SSPI(TokenSSPI),
}

Expand Down Expand Up @@ -53,7 +51,7 @@ where
}
}

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

Expand Down Expand Up @@ -163,7 +161,6 @@ where
Ok(ReceivedToken::LoginAck(ack))
}

#[cfg(windows)]
async fn get_sspi(&mut self) -> crate::Result<ReceivedToken> {
let sspi = TokenSSPI::decode_async(self.conn).await?;
event!(Level::TRACE, "SSPI response");
Expand Down Expand Up @@ -195,7 +192,6 @@ where
TokenType::EnvChange => this.get_env_change().await?,
TokenType::Info => this.get_info().await?,
TokenType::LoginAck => this.get_login_ack().await?,
#[cfg(windows)]
TokenType::SSPI => this.get_sspi().await?,
_ => panic!("Token {:?} unimplemented!", ty),
};
Expand Down