From 548771adb130ebe19486a5c6528f4238ebc1b997 Mon Sep 17 00:00:00 2001 From: Ivan Nikulin Date: Wed, 11 Nov 2020 19:26:21 +0000 Subject: [PATCH] Add tokio-boring --- .rusty-hook.toml | 2 + Cargo.toml | 3 +- README.md | 6 +- boring/Cargo.toml | 1 + tokio-boring/Cargo.toml | 21 ++ tokio-boring/LICENSE-APACHE | 201 +++++++++++++++++++ tokio-boring/LICENSE-MIT | 25 +++ tokio-boring/README.md | 48 +++++ tokio-boring/src/lib.rs | 360 +++++++++++++++++++++++++++++++++++ tokio-boring/tests/cert.pem | 21 ++ tokio-boring/tests/google.rs | 81 ++++++++ tokio-boring/tests/key.pem | 28 +++ 12 files changed, 794 insertions(+), 3 deletions(-) create mode 100644 .rusty-hook.toml create mode 100644 tokio-boring/Cargo.toml create mode 100644 tokio-boring/LICENSE-APACHE create mode 100644 tokio-boring/LICENSE-MIT create mode 100644 tokio-boring/README.md create mode 100644 tokio-boring/src/lib.rs create mode 100644 tokio-boring/tests/cert.pem create mode 100644 tokio-boring/tests/google.rs create mode 100644 tokio-boring/tests/key.pem diff --git a/.rusty-hook.toml b/.rusty-hook.toml new file mode 100644 index 00000000..971966b6 --- /dev/null +++ b/.rusty-hook.toml @@ -0,0 +1,2 @@ +[hooks] +pre-commit = "cargo fmt --all -- --check" \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 33cf3f95..d48b3865 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,5 +2,6 @@ members = [ "boring", "boring-sys", - "systest" + "systest", + "tokio-boring" ] diff --git a/README.md b/README.md index 0e936110..b3341534 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,8 @@ [![crates.io](https://img.shields.io/crates/v/openssl.svg)](https://crates.io/crates/boring) -BoringSSL bindings for the Rust programming language. +BoringSSL bindings for the Rust programming language and TLS adapters for [tokio](https://github.com/tokio-rs/tokio) +and [hyper](https://github.com/hyperium/hyper) built on top of it. [Documentation](https://docs.rs/boring). @@ -18,4 +19,5 @@ license, shall be dual licensed under the terms of both the Apache License, Version 2.0 and the MIT license without any additional terms or conditions. ## Accolades -The project is based on a fork of [rust-openssl](https://github.com/sfackler/rust-openssl). \ No newline at end of file + +The project is based on a fork of [rust-openssl](https://github.com/sfackler/rust-openssl). diff --git a/boring/Cargo.toml b/boring/Cargo.toml index d4f7c0f6..4d578eb5 100644 --- a/boring/Cargo.toml +++ b/boring/Cargo.toml @@ -19,3 +19,4 @@ boring-sys = { version = "1.0.0", path = "../boring-sys" } [dev-dependencies] tempdir = "0.3" hex = "0.3" +rusty-hook = "^0.10.1" \ No newline at end of file diff --git a/tokio-boring/Cargo.toml b/tokio-boring/Cargo.toml new file mode 100644 index 00000000..d3d1b146 --- /dev/null +++ b/tokio-boring/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "tokio-boring" +version = "1.0.0" +authors = ["Alex Crichton ", "Ivan Nikulin "] +license = "MIT/Apache-2.0" +edition = "2018" +repository = "https://github.com/inikulin/boring" +homepage = "https://github.com/inikulin/boring" +documentation = "https://docs.rs/tokio-boring" +description = """ +An implementation of SSL streams for Tokio backed by BoringSSL +""" + +[dependencies] +boring = { version = "1.0.0", path = "../boring" } +boring-sys = { version = "1.0.0", path = "../boring-sys" } +tokio = "0.3" + +[dev-dependencies] +futures = "0.3" +tokio = { version = "0.3", features = ["full"] } diff --git a/tokio-boring/LICENSE-APACHE b/tokio-boring/LICENSE-APACHE new file mode 100644 index 00000000..2a6afc56 --- /dev/null +++ b/tokio-boring/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2016 Tokio contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/tokio-boring/LICENSE-MIT b/tokio-boring/LICENSE-MIT new file mode 100644 index 00000000..d5a3b639 --- /dev/null +++ b/tokio-boring/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 Tokio contributors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/tokio-boring/README.md b/tokio-boring/README.md new file mode 100644 index 00000000..62455bf4 --- /dev/null +++ b/tokio-boring/README.md @@ -0,0 +1,48 @@ +# tokio-boring + +An implementation of SSL streams for Tokio built on top of the BoringSSL. + +[Documentation](https://docs.rs/tokio-boring) + +## Usage + +First, add this to your `Cargo.toml`: + +```toml +[dependencies] +tokio-boring = "1.0.0" +``` + +Next, add this to your crate: + +```rust +use tokio_boring::{SslConnectorExt, SslAcceptorExt}; +``` + +This crate provides two extension traits, `SslConnectorExt` and +`SslAcceptorExt`, which augment the functionality provided by the [`boring` crate](https://github.com/inikulin/boring). +These extension traits provide the ability to connect a stream +asynchronously and accept a socket asynchronously. Configuration of BoringSSL +parameters is still done through the support in the [`boring` crate](https://github.com/inikulin/boring). + + +# License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +## Accolades + +The project is based on a fork of [tokio-openssl](https://github.com/sfackler/tokio-openssl). \ No newline at end of file diff --git a/tokio-boring/src/lib.rs b/tokio-boring/src/lib.rs new file mode 100644 index 00000000..b7cb10d0 --- /dev/null +++ b/tokio-boring/src/lib.rs @@ -0,0 +1,360 @@ +//! Async TLS streams backed by BoringSSL +//! +//! This library is an implementation of TLS streams using BoringSSL for +//! negotiating the connection. Each TLS stream implements the `Read` and +//! `Write` traits to interact and interoperate with the rest of the futures I/O +//! ecosystem. Client connections initiated from this crate verify hostnames +//! automatically and by default. +//! +//! This crate primarily exports this ability through two extension traits, +//! `SslConnectorExt` and `SslAcceptorExt`. These traits augment the +//! functionality provided by the [`boring` crate](https://github.com/inikulin/boring) crate, +//! on which this crate is built. Configuration of TLS parameters is still primarily done through +//! the [`boring` crate](https://github.com/inikulin/boring) +#![warn(missing_docs)] + +use boring::ssl::{ + self, ConnectConfiguration, ErrorCode, MidHandshakeSslStream, ShutdownResult, SslAcceptor, + SslRef, +}; +use boring_sys as ffi; +use std::error::Error; +use std::fmt; +use std::future::Future; +use std::io::{self, Read, Write}; +use std::pin::Pin; +use std::task::{Context, Poll}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; + +/// Asynchronously performs a client-side TLS handshake over the provided stream. +pub async fn connect( + config: ConnectConfiguration, + domain: &str, + stream: S, +) -> Result, HandshakeError> +where + S: AsyncRead + AsyncWrite + Unpin, +{ + handshake(|s| config.connect(domain, s), stream).await +} + +/// Asynchronously performs a server-side TLS handshake over the provided stream. +pub async fn accept(acceptor: &SslAcceptor, stream: S) -> Result, HandshakeError> +where + S: AsyncRead + AsyncWrite + Unpin, +{ + handshake(|s| acceptor.accept(s), stream).await +} + +async fn handshake(f: F, stream: S) -> Result, HandshakeError> +where + F: FnOnce( + StreamWrapper, + ) + -> Result>, ssl::HandshakeError>> + + Unpin, + S: AsyncRead + AsyncWrite + Unpin, +{ + let start = StartHandshakeFuture(Some(StartHandshakeFutureInner { f, stream })); + + match start.await? { + StartedHandshake::Done(s) => Ok(s), + StartedHandshake::Mid(s) => HandshakeFuture(Some(s)).await, + } +} + +struct StreamWrapper { + stream: S, + context: usize, +} + +impl fmt::Debug for StreamWrapper +where + S: fmt::Debug, +{ + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.stream, fmt) + } +} + +impl StreamWrapper +where + S: Unpin, +{ + fn with_context(&mut self, f: F) -> R + where + F: FnOnce(&mut Context<'_>, Pin<&mut S>) -> R, + { + unsafe { + assert_ne!(self.context, 0); + let waker = &mut *(self.context as *mut _); + f(waker, Pin::new(&mut self.stream)) + } + } +} + +impl Read for StreamWrapper +where + S: AsyncRead + Unpin, +{ + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.with_context(|ctx, stream| { + let mut buf = ReadBuf::new(buf); + match stream.poll_read(ctx, &mut buf)? { + Poll::Ready(()) => Ok(buf.filled().len()), + Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), + } + }) + } +} + +impl Write for StreamWrapper +where + S: AsyncWrite + Unpin, +{ + fn write(&mut self, buf: &[u8]) -> io::Result { + match self.with_context(|ctx, stream| stream.poll_write(ctx, buf)) { + Poll::Ready(r) => r, + Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), + } + } + + fn flush(&mut self) -> io::Result<()> { + match self.with_context(|ctx, stream| stream.poll_flush(ctx)) { + Poll::Ready(r) => r, + Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), + } + } +} + +fn cvt(r: io::Result) -> Poll> { + match r { + Ok(v) => Poll::Ready(Ok(v)), + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, + Err(e) => Poll::Ready(Err(e)), + } +} + +/// A wrapper around an underlying raw stream which implements the SSL +/// protocol. +/// +/// A `SslStream` represents a handshake that has been completed successfully +/// and both the server and the client are ready for receiving and sending +/// data. Bytes read from a `SslStream` are decrypted from `S` and bytes written +/// to a `SslStream` are encrypted when passing through to `S`. +#[derive(Debug)] +pub struct SslStream(ssl::SslStream>); + +impl SslStream { + /// Returns a shared reference to the `Ssl` object associated with this stream. + pub fn ssl(&self) -> &SslRef { + self.0.ssl() + } + + /// Returns a shared reference to the underlying stream. + pub fn get_ref(&self) -> &S { + &self.0.get_ref().stream + } + + /// Returns a mutable reference to the underlying stream. + pub fn get_mut(&mut self) -> &mut S { + &mut self.0.get_mut().stream + } + + fn with_context(&mut self, ctx: &mut Context<'_>, f: F) -> R + where + F: FnOnce(&mut ssl::SslStream>) -> R, + { + self.0.get_mut().context = ctx as *mut _ as usize; + let r = f(&mut self.0); + self.0.get_mut().context = 0; + r + } +} + +impl SslStream +where + S: AsyncRead + AsyncWrite + Unpin, +{ + /// Constructs an `SslStream` from a pointer to the underlying BoringSSL `SSL` struct. + /// + /// This is useful if the handshake has already been completed elsewhere. + /// + /// # Safety + /// + /// The caller must ensure the pointer is valid. + pub unsafe fn from_raw_parts(ssl: *mut ffi::SSL, stream: S) -> Self { + let stream = StreamWrapper { stream, context: 0 }; + SslStream(ssl::SslStream::from_raw_parts(ssl, stream)) + } +} + +impl AsyncRead for SslStream +where + S: AsyncRead + AsyncWrite + Unpin, +{ + fn poll_read( + mut self: Pin<&mut Self>, + ctx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + self.with_context(ctx, |s| match cvt(s.read(buf.initialize_unfilled()))? { + Poll::Ready(nread) => { + buf.advance(nread); + Poll::Ready(Ok(())) + } + Poll::Pending => Poll::Pending, + }) + } +} + +impl AsyncWrite for SslStream +where + S: AsyncRead + AsyncWrite + Unpin, +{ + fn poll_write( + mut self: Pin<&mut Self>, + ctx: &mut Context, + buf: &[u8], + ) -> Poll> { + self.with_context(ctx, |s| cvt(s.write(buf))) + } + + fn poll_flush(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll> { + self.with_context(ctx, |s| cvt(s.flush())) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll> { + match self.with_context(ctx, |s| s.shutdown()) { + Ok(ShutdownResult::Sent) | Ok(ShutdownResult::Received) => {} + Err(ref e) if e.code() == ErrorCode::ZERO_RETURN => {} + Err(ref e) if e.code() == ErrorCode::WANT_READ || e.code() == ErrorCode::WANT_WRITE => { + return Poll::Pending; + } + Err(e) => { + return Poll::Ready(Err(e + .into_io_error() + .unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e)))); + } + } + + Pin::new(&mut self.0.get_mut().stream).poll_shutdown(ctx) + } +} + +/// The error type returned after a failed handshake. +pub struct HandshakeError(ssl::HandshakeError>); + +impl HandshakeError { + /// Returns a shared reference to the `Ssl` object associated with this error. + pub fn ssl(&self) -> Option<&SslRef> { + match &self.0 { + ssl::HandshakeError::Failure(s) => Some(s.ssl()), + _ => None, + } + } +} + +impl fmt::Debug for HandshakeError +where + S: fmt::Debug, +{ + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, fmt) + } +} + +impl fmt::Display for HandshakeError +where + S: fmt::Debug, +{ + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.0, fmt) + } +} + +impl Error for HandshakeError +where + S: fmt::Debug, +{ + fn source(&self) -> Option<&(dyn Error + 'static)> { + self.0.source() + } +} + +enum StartedHandshake { + Done(SslStream), + Mid(MidHandshakeSslStream>), +} + +struct StartHandshakeFuture(Option>); + +struct StartHandshakeFutureInner { + f: F, + stream: S, +} + +impl Future for StartHandshakeFuture +where + F: FnOnce( + StreamWrapper, + ) + -> Result>, ssl::HandshakeError>> + + Unpin, + S: Unpin, +{ + type Output = Result, HandshakeError>; + + fn poll( + mut self: Pin<&mut Self>, + ctx: &mut Context<'_>, + ) -> Poll, HandshakeError>> { + let inner = self.0.take().expect("future polled after completion"); + + let stream = StreamWrapper { + stream: inner.stream, + context: ctx as *mut _ as usize, + }; + match (inner.f)(stream) { + Ok(mut s) => { + s.get_mut().context = 0; + Poll::Ready(Ok(StartedHandshake::Done(SslStream(s)))) + } + Err(ssl::HandshakeError::WouldBlock(mut s)) => { + s.get_mut().context = 0; + Poll::Ready(Ok(StartedHandshake::Mid(s))) + } + Err(e) => Poll::Ready(Err(HandshakeError(e))), + } + } +} + +struct HandshakeFuture(Option>>); + +impl Future for HandshakeFuture +where + S: AsyncRead + AsyncWrite + Unpin, +{ + type Output = Result, HandshakeError>; + + fn poll( + mut self: Pin<&mut Self>, + ctx: &mut Context<'_>, + ) -> Poll, HandshakeError>> { + let mut s = self.0.take().expect("future polled after completion"); + + s.get_mut().context = ctx as *mut _ as usize; + match s.handshake() { + Ok(mut s) => { + s.get_mut().context = 0; + Poll::Ready(Ok(SslStream(s))) + } + Err(ssl::HandshakeError::WouldBlock(mut s)) => { + s.get_mut().context = 0; + self.0 = Some(s); + Poll::Pending + } + Err(e) => Poll::Ready(Err(HandshakeError(e))), + } + } +} diff --git a/tokio-boring/tests/cert.pem b/tokio-boring/tests/cert.pem new file mode 100644 index 00000000..2d08323d --- /dev/null +++ b/tokio-boring/tests/cert.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDhTCCAm2gAwIBAgIJALClJS+cq+ykMA0GCSqGSIb3DQEBCwUAMFkxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQxEjAQBgNV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--git a/tokio-boring/tests/google.rs b/tokio-boring/tests/google.rs new file mode 100644 index 00000000..b3cd6525 --- /dev/null +++ b/tokio-boring/tests/google.rs @@ -0,0 +1,81 @@ +use boring::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod}; +use futures::future; +use std::net::ToSocketAddrs; +use std::pin::Pin; +use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +#[tokio::test] +async fn google() { + let addr = "google.com:443".to_socket_addrs().unwrap().next().unwrap(); + let stream = TcpStream::connect(&addr).await.unwrap(); + + let config = SslConnector::builder(SslMethod::tls()) + .unwrap() + .build() + .configure() + .unwrap(); + let mut stream = tokio_boring::connect(config, "google.com", stream) + .await + .unwrap(); + + stream.write_all(b"GET / HTTP/1.0\r\n\r\n").await.unwrap(); + + let mut buf = vec![]; + stream.read_to_end(&mut buf).await.unwrap(); + let response = String::from_utf8_lossy(&buf); + let response = response.trim_end(); + + // any response code is fine + assert!(response.starts_with("HTTP/1.0 ")); + assert!(response.ends_with("") || response.ends_with("")); +} + +#[tokio::test] +async fn server() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + + let server = async move { + let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); + acceptor + .set_private_key_file("tests/key.pem", SslFiletype::PEM) + .unwrap(); + acceptor + .set_certificate_chain_file("tests/cert.pem") + .unwrap(); + let acceptor = acceptor.build(); + + let stream = listener.accept().await.unwrap().0; + let mut stream = tokio_boring::accept(&acceptor, stream).await.unwrap(); + + let mut buf = [0; 4]; + stream.read_exact(&mut buf).await.unwrap(); + assert_eq!(&buf, b"asdf"); + + stream.write_all(b"jkl;").await.unwrap(); + + future::poll_fn(|ctx| Pin::new(&mut stream).poll_shutdown(ctx)) + .await + .unwrap() + }; + + let client = async { + let mut connector = SslConnector::builder(SslMethod::tls()).unwrap(); + connector.set_ca_file("tests/cert.pem").unwrap(); + let config = connector.build().configure().unwrap(); + + let stream = TcpStream::connect(&addr).await.unwrap(); + let mut stream = tokio_boring::connect(config, "localhost", stream) + .await + .unwrap(); + + stream.write_all(b"asdf").await.unwrap(); + + let mut buf = vec![]; + stream.read_to_end(&mut buf).await.unwrap(); + assert_eq!(buf, b"jkl;"); + }; + + future::join(server, client).await; +} diff --git a/tokio-boring/tests/key.pem b/tokio-boring/tests/key.pem new file mode 100644 index 00000000..58f1020a --- /dev/null +++ b/tokio-boring/tests/key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC+JANJoIVdezD4 +tN97SodSCuKTOs6cxxa4ItrJlPezv5Mb0mzZw6GRxHaqtwLUXIxC4B3ik3dNo8gB +8RqEUwFTkSKdKeCwgr5UexJxx+/Ht7yKt5ZC3ubqsro58djSSSKyF6+WPmd0LjFE +gIsehq3gG9fSnE2RvNooL4eHTkD/6ZpakLMqz6YqC8udDtjbgalOUMcnrxUR7Fn3 +tzO2ssyQVcDKQycYN7GjhE14MzM3yra49j8NJn3B0DLbD7+8/OboNMsnfYl8MC2M +dkamenqQobFrmNs4+2X3IrNw827K1vPye+fCjZI2VVkvWiZgxrE90cUZVQ5yHqMP +0louarahAgMBAAECggEAd08brQCHjs/1O6orLS7n2IgyAhZ9fQzD6ckdJi5Oe8Cz +K1sPqFlEMbZoi9iIcv6bmH8O4ZSM4O/rWaSTcgKvq2M/qASWE8wGZ/ZN7Y16nQRi +z1xBcjZyCUUa668g0VrI5Z1NNWZ0/gbaLVTHduEli6GM/H/NgKxS67JfRXzJ9onl +d6vrK+xmeHyA7QSOieEDettaNCvm+HjU8mmOb4F1pCNZktDrch5rI8EzQlmFQuq4 +y50YLRZGSlK1QLjzMnT//oaP7mHjN/inzZTHBvTzhU2OjcjzEW7l4ry224Sdu/eH +lhEnNk2eq+mH/yESkn3sJcmH4uYIXh8Dyvcy/uVkPQKBgQDzSC89q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