Skip to content

About

TDS 7.2+ (Microsoft SQL Server) driver for Rust

Resources

Stars

1 star

Watchers

0 watching

Forks

 
 

Repository files navigation

Tiberius

crates.io docs.rs Cargo tests Chat

A native Microsoft SQL Server (TDS) client for Rust.

Goals

  • A perfect implementation of the TDS protocol.
  • Asynchronous network IO.
  • Independent of the network protocol.
  • Support for latest versions of Linux, Windows and macOS.

Non-goals

  • Connection pooling (use bb8, mobc, deadpool or any of the other asynchronous connection pools)
  • Query building
  • Object-relational mapping

Supported SQL Server versions

Version Support level Notes
2022 Tested on CI
2019 Tested on CI
2017 Tested on CI
2016 Should work
2014 Should work
2012 Should work
2008 Should work
2005 Should work With feature flag tds73 disabled.

Feature flags

Flag Description Default
tds73 Support for new date and time types in TDS version 7.3. Disable if using version 7.2. enabled
native-tls Use operating system's TLS libraries for traffic encryption. enabled
rustls Use the builtin TLS implementation from rustls instead of linking to the operating system implementation for traffic encryption. disabled
vendored-openssl Statically link against OpenSSL instead of dynamically linking to the operating system implementation for traffic encryption. disabled
chrono Read and write date and time values using chrono's types. (for greenfield, using time instead of chrono is recommended) disabled
time Read and write date and time values using time crate types. disabled
rust_decimal Read and write numeric/decimal values using rust_decimal's Decimal. disabled
bigdecimal Read and write numeric/decimal values using bigdecimal's BigDecimal. 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
sql-browser-smol SQL Browser implementation for the TcpStream of smol. disabled
integrated-auth-gssapi Support for using Integrated Auth via GSSAPI disabled

Supported protocols

Tiberius does not rely on any protocol when connecting to an SQL Server instance. Instead the Client takes a socket that implements the AsyncRead and AsyncWrite traits from the futures-rs crate.

Currently there are good async implementations for TCP in the async-std, Tokio and Smol projects.

To be able to use them together with Tiberius on Windows platforms with SQL Server, you should make sure that the TCP protocol is enabled, as depending on the edition, this may not be the case. Standard and Enterprise editions will have the setting enabled by default, whereas Developer, Express editions and the Windows Internal Database feature of the Windows Server OS don't. To enable the TCP/IP protocol you may want to use the server settings the command line. In the official Docker image TCP is is enabled by default.

Named pipes should work by using the NamedPipeClient from the latest Tokio versions.

The shared memory protocol is not documented and seems there are no Rust crates implementing it.

Encryption (TLS/SSL)

Tiberius can be set to use two different implementations of TLS connection encryption. By default it uses native-tls, linking to the TLS library provided by the operating system. This is a good practice and in case of security vulnerabilities, upgrading the system libraries fixes the vulnerability in Tiberius without a recompilation. On Linux we link against OpenSSL, on Windows against schannel and on macOS against Security Framework.

Alternatively one can use the rustls feature flag to use the Rust native TLS implementation. This way there are no dynamic dependencies to the system. This might be useful in certain installations, but requires a rebuild to update to a new TLS version. For some reasons the Security Framework on macOS does not work with SQL Server TLS settings, and on Apple platforms if needing TLS it is recommended to use rustls instead of native-tls. The other option is to use the vendored-openssl feature flag, that statically links against the latest OpenSSL implementation.

The crate can also be compiled without TLS support, but not with both features enabled at the same time.

Encryption level Description
Required Require full-session TLS; reject a server that declines. Default for Config::new() with TLS enabled.
On Require full-session TLS, like Required.
Off Optional. Uses login-only TLS when the server returns ENCRYPT_OFF and full-session TLS when the server selects it. Returns Error::Tls before sending the login if the server returns ENCRYPT_NOT_SUP.
NotSupported Allows an unencrypted login and session when the server agrees. Rejects a server that requests TLS.

Native TLS additionally supports Config::strict_encryption(true): TLS-first TDS 8.0 (SQL Server 2022+), TLS 1.2 or later, with no TDS 7 fallback. Set EncryptionLevel::Required with Strict. Non-Strict native TLS uses TLS up to 1.2 for TDS 7 compatibility.

Certificate identity is validated against OS trust and the connection hostname by default:

  • trust_cert_ca(path) adds one PEM or DER CA certificate to OS trust. rustls and vendored OpenSSL keep their existing CA file handling.
  • certificate_hostname(name) overrides the verification hostname/SNI without changing the TCP destination.
  • server_certificate(path) pins the exact DER leaf certificate from one PEM or DER file instead of chain/hostname validation. Pinning does not check expiry or hostname; update the pin when the certificate changes.
  • trust_cert() explicitly bypasses certificate/hostname checks. It is forbidden in Strict and conflicts with other identity controls.

Pinning requires full-session encryption and conflicts with CA/hostname overrides. With native TLS, unreadable, malformed, bundled, or trailing-data certificate files fail without fallback. Certificate files are read when the TLS handshake starts, which in TDS 7 mode is after the PRELOGIN exchange but before the login is sent. Unsupported backend/option combinations and conflicting settings return errors before protocol I/O; hostname/pin/Strict controls require the native TLS backend. Client::is_encrypted() reports actual post-login TLS, including Optional's negotiated outcome. These APIs apply to programmatic configuration; RSSQL parses its own connection-string controls.

Integrated Authentication (TrustedConnection) on *nix

With the integrated-auth-gssapi feature enabled, the crate requires the GSSAPI/Kerberos libraries/headers installed:

  • CentOS
  • Arch
  • Debian (you need the -dev packages to build)
  • Ubuntu
  • NixOS: Run nix-shell shell.nix on the repository root.
  • Mac: as of version 0.4.2 the libgssapi crate used for this feature now uses Apple's GSS Framework which ships with MacOS 10.14+.

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.

Redirects

With certain Azure firewall settings, a login might return Error::Routing { host, port }. This means the user must create a new TcpStream to the given address, and connect again.

A simple connection procedure would then be:

use tiberius::{Client, Config, AuthMethod, error::Error};
use tokio_util::compat::TokioAsyncWriteCompatExt;
use tokio::net::TcpStream;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = Config::new();

    config.host("0.0.0.0");
    config.port(1433);
    config.authentication(AuthMethod::sql_server("SA", "<Mys3cureP4ssW0rD>"));

    let tcp = TcpStream::connect(config.get_addr()).await?;
    tcp.set_nodelay(true)?;

    let client = match Client::connect(config, tcp.compat_write()).await {
        // Connection successful.
        Ok(client) => client,
        // The server wants us to redirect to a different address
        Err(Error::Routing { host, port }) => {
            let mut config = Config::new();

            config.host(&host);
            config.port(port);
            config.authentication(AuthMethod::sql_server("SA", "<Mys3cureP4ssW0rD>"));

            let tcp = TcpStream::connect(config.get_addr()).await?;
            tcp.set_nodelay(true)?;

            // we should not have more than one redirect, so we'll short-circuit here.
            Client::connect(config, tcp.compat_write()).await?
        }
        Err(e) => Err(e)?,
    };

    Ok(())
}

Running the tests

The integration tests need a SQL Server. scripts/docker-test.sh builds one from docker/, the images CI uses, and runs cargo test against it, including the live tests in tests/rpc_helpers_live.rs that are otherwise ignored:

scripts/docker-test.sh run                                       # SQL Server 2022, default features
TIBERIUS_TEST_SERVER=2025 scripts/docker-test.sh run --no-default-features --features=rustls
scripts/docker-test.sh up                                        # keep a server between runs
scripts/docker-test.sh test --test query
scripts/docker-test.sh down

The container listens on 127.0.0.1:1434 (set TIBERIUS_TEST_PORT to change it), so it can run next to another SQL Server on 1433. The TLS backends exclude each other, so rustls and vendored-openssl need --no-default-features. To use a server of your own instead, set TIBERIUS_TEST_CONNECTION_STRING and run cargo test --tests -- --include-ignored, then cargo test --doc; --include-ignored would also try to compile the doc examples marked ignore, which are not meant to build. tests/custom-cert.rs passes only against the docker/ images, whose certificate is signed by docker/certs/customCA.crt. That certificate lasts 200 days; once it expires, the script stops and prints the command that reissues it.

Security

If you have a security issue to report, please contact us at security@prisma.io

About

TDS 7.2+ (Microsoft SQL Server) driver for Rust

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages