Skip to content

Commit

Permalink
Use GSSAPI for IntegratedSecurity on Unix (#77)
Browse files Browse the repository at this point in the history
* Use GSSAPI for IntegratedSecurity on Unix

* Handle ADO.NET Connection Strings & Document

* Address PR Feedback

* Add integrated-auth feature
* Add trace!s where indicated

* Move gssapi under feature integrated-auth-gssapi

* Add additional color about integrated-auth-gssapi

* Fixes for GSSAPI

- Do not enable `integrated-auth-gssapi` for docs.rs (they probably miss
the krb headers).
- Combine `AuthMethod::Integrated` and `AuthMethod::WindowsIntegrated`
to `AuthMethod::Integrated` variant for clarity.
- Make the docs a bit more clear (hopefully)

Co-authored-by: Julius de Bruijn <julius+github@nauk.io>
  • Loading branch information
dwink and Julius de Bruijn authored Aug 29, 2020
1 parent 1a8f682 commit 8e5f44f
Show file tree
Hide file tree
Showing 11 changed files with 111 additions and 29 deletions.
4 changes: 4 additions & 0 deletions 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 @@ -118,3 +121,4 @@ tls = ["async-native-tls"]
tds73 = []
sql-browser-async-std = ["async-std"]
sql-browser-tokio = ["tokio", "tokio-util"]
integrated-auth-gssapi = ["libgssapi"]
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ things:
| `rust_decimal` | Read and write `numeric`/`decimal` values using `rust_decimal`'s `Decimal`. | `disabled` |
| `sql-browser-async-std` | SQL Browser implementation for the `TcpStream` of async-std. | `disabled` |
| `sql-browser-tokio` | SQL Browser implementation for the `TcpStream` of Tokio. | `disabled` |
| `integrated-auth-gssapi` | Support for using Integrated Auth via GSSAPI | `disabled` |

### Supported protocols

Expand Down Expand Up @@ -77,6 +78,17 @@ tiberius = { version = "0.X", default-features=false, features=["chrono"] }

**This will disable encryption for your ENTIRE crate**

### Integrated Authentication (TrustedConnection) on \*nix

With the `integrated-auth-gssapi` feature enabled, the crate requires the GSSAPI/Kerberos libraries/headers installed:
* [CentOS](https://pkgs.org/download/krb5-devel)
* [Arch](https://www.archlinux.org/packages/core/x86_64/krb5/)
* [Debian](https://tracker.debian.org/pkg/krb5) (you need the -dev packages to build)
* [Ubuntu](https://packages.ubuntu.com/bionic-updates/libkrb5-dev)
* [Mac - Homebrew](https://formulae.brew.sh/formula/krb5)

Additionally, your runtime system will need to be trusted by and configured for the Active Directory domain your SQL Server is part of. In particular, you'll need to be able to get a valid TGT for your identity, via `kinit` or a keytab. This setup varies by environment and OS, but your friendly network/system administrator should be able to help figure out the specifics.

## Security

If you have a security issue to report, please contact us at [security@prisma.io](mailto:security@prisma.io?subject=[GitHub]%20Prisma%202%20Security%20Report%20Tiberius)
9 changes: 5 additions & 4 deletions src/client/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,11 @@ pub enum AuthMethod {
/// Authenticate with Windows credentials. Only available on Windows
/// platforms.
Windows(WindowsAuth),
#[cfg(any(windows, doc))]
/// Authenticate as the currently logged in user. Only available on Windows
/// platforms.
WindowsIntegrated,
#[cfg(any(windows, all(unix, feature = "integrated-auth-gssapi"), doc))]
/// Authenticate as the currently logged in user. On Windows uses SSPI and
/// Kerberos on Unix platforms. On Unix platforms the
/// `integrated-auth-gssapi` feature needs to be enabled.
Integrated,
#[doc(hidden)]
None,
}
Expand Down
21 changes: 18 additions & 3 deletions 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 @@ -278,9 +278,13 @@ impl AdoNetString {
#[cfg(windows)]
Some(val) if val.to_lowercase() == "sspi" || Self::parse_bool(val)? => match (user, pw)
{
(None, None) => Ok(AuthMethod::WindowsIntegrated),
(None, None) => Ok(AuthMethod::Integrated),
_ => 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 Expand Up @@ -480,7 +484,18 @@ mod tests {
let test_str = "IntegratedSecurity=SSPI";
let ado = AdoNetString::parse(test_str)?;

assert_eq!(AuthMethod::WindowsIntegrated, ado.authentication()?);
assert_eq!(AuthMethod::Integrated, ado.authentication()?);

Ok(())
}

#[test]
#[cfg(all(feature = "integrated-auth-gssapi", unix))]
fn parsing_sspi_authentication() -> crate::Result<()> {
let test_str = "IntegratedSecurity=true";
let ado = AdoNetString::parse(test_str)?;

assert_eq!(AuthMethod::Integrated, ado.authentication()?);

Ok(())
}
Expand Down
60 changes: 53 additions & 7 deletions src/client/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,20 @@ 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;
#[cfg(feature = "integrated-auth-gssapi")]
use libgssapi::{
context::{ClientCtx, CtxFlags},
credential::{Cred, CredUsage},
name::Name,
oid::{OidSet, GSS_MECH_KRB5, GSS_NT_KRB5_PRINCIPAL},
};
use pretty_hex::*;
#[cfg(feature = "integrated-auth-gssapi")]
use std::ops::Deref;
use std::{cmp, fmt::Debug, io, pin::Pin, task};
use task::Poll;
use tracing::{event, Level};
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 @@ -235,7 +240,7 @@ where {

match auth {
#[cfg(windows)]
AuthMethod::WindowsIntegrated => {
AuthMethod::Integrated => {
let mut client = NtlmSspiBuilder::new()
.target_spn(self.context.spn())
.build()?;
Expand All @@ -262,6 +267,47 @@ where {
None => unreachable!(),
}
}
#[cfg(all(unix, 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()))
}
None => {
event!(Level::TRACE, response_len = 0);
TokenSSPI::new(Vec::new())
}
};

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))
}
}
9 changes: 5 additions & 4 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.
//! - Authentication with Windows credentials
//! - Authentication with currently logged in Windows user
//! authenticate the user.
//! - On Windows, you can authenticate using the currently logged in user or
//! specified Windows credentials.
//! - If enabling the `integrated-auth-gssapi` feature, it is possible to login
//! with the currently active Kerberos credentials.
//!
//! # 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

0 comments on commit 8e5f44f

Please sign in to comment.