async-native-tls-0.5.0/.cargo_vcs_info.json0000644000000001360000000000100142370ustar { "git": { "sha1": "9d09830cc792a060af1c1916151a60d68959005b" }, "path_in_vcs": "" }async-native-tls-0.5.0/.github/workflows/ci.yml000064400000000000000000000025441046102023000175470ustar 00000000000000name: CI on: workflow_dispatch: pull_request: push: branches: - master schedule: - cron: "11 7 * * 1,4" env: RUSTFLAGS: -Dwarnings jobs: build_and_test: name: Build and test runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macOS-latest] rust: [nightly, beta, stable] steps: - uses: actions/checkout@v3 - name: Install ${{ matrix.rust }} uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} override: true - name: check uses: actions-rs/cargo@v1 with: command: check args: --all --bins --examples --tests - name: check bench uses: actions-rs/cargo@v1 if: matrix.rust == 'nightly' with: command: check args: --benches - name: tests run: cargo test --all --features vendored check_fmt_and_docs: name: Checking fmt, clippy and docs runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true components: rustfmt - name: fmt run: cargo fmt --all -- --check - name: clippy run: cargo clippy --all - name: Docs run: cargo doc async-native-tls-0.5.0/.gitignore000064400000000000000000000000361046102023000150160ustar 00000000000000/target **/*.rs.bk Cargo.lock async-native-tls-0.5.0/Cargo.toml0000644000000036520000000000100122430ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "async-native-tls" version = "0.5.0" authors = ["dignifiedquire "] description = """ Native TLS using futures """ homepage = "https://docs.rs/crate/async-native-tls/" documentation = "https://docs.rs/crate/async-native-tls/" readme = "README.md" categories = [ "asynchronous", "cryptography", "network-programming", ] license = "MIT/Apache-2.0" repository = "https://github.com/async-email/async-native-tls" [[test]] name = "google" required-features = ["runtime-async-std"] [[test]] name = "google-tokio" required-features = ["runtime-tokio"] [[test]] name = "bad" required-features = ["runtime-async-std"] [[test]] name = "smoke" required-features = ["runtime-async-std"] [dependencies.futures-util] version = "0.3.1" features = ["io"] optional = true [dependencies.native-tls] version = "0.2.8" features = ["alpn"] [dependencies.thiserror] version = "1.0.9" [dependencies.tokio] version = "1.0" features = ["io-util"] optional = true default-features = false [dependencies.url] version = "2.1.1" [dev-dependencies.async-std] version = "1.6.0" features = ["attributes"] [dev-dependencies.cfg-if] version = "1.0.0" [dev-dependencies.env_logger] version = "0.9.0" [dev-dependencies.futures] version = "0.3.1" [dev-dependencies.tokio] version = "1.0" features = ["full"] [features] default = ["runtime-async-std"] runtime-async-std = ["futures-util"] runtime-tokio = ["tokio"] vendored = ["native-tls/vendored"] async-native-tls-0.5.0/Cargo.toml.orig000064400000000000000000000025131046102023000157170ustar 00000000000000[package] name = "async-native-tls" version = "0.5.0" authors = ["dignifiedquire "] edition = "2018" license = "MIT/Apache-2.0" repository = "https://github.com/async-email/async-native-tls" homepage = "https://docs.rs/crate/async-native-tls/" documentation = "https://docs.rs/crate/async-native-tls/" description = """ Native TLS using futures """ readme = "README.md" categories = ["asynchronous", "cryptography", "network-programming"] [dependencies] native-tls = { version = "0.2.8", features = ["alpn"] } thiserror = "1.0.9" futures-util = { version = "0.3.1", features = ["io"], optional = true } tokio = { version = "1.0", default-features = false, features = ["io-util"], optional = true } url = "2.1.1" [features] default = ["runtime-async-std"] vendored = ["native-tls/vendored"] # Runtime runtime-async-std = ["futures-util"] runtime-tokio = ["tokio"] [dev-dependencies] env_logger = "0.9.0" async-std = { version = "1.6.0", features = ["attributes"] } tokio = { version = "1.0", features = ["full"] } cfg-if = "1.0.0" futures = "0.3.1" [[test]] name = "google" required-features = [ "runtime-async-std" ] [[test]] name = "google-tokio" required-features = [ "runtime-tokio" ] [[test]] name = "bad" required-features = [ "runtime-async-std" ] [[test]] name = "smoke" required-features = [ "runtime-async-std" ] async-native-tls-0.5.0/LICENSE-APACHE000064400000000000000000000251271046102023000147620ustar 00000000000000 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 2019 Friedel Ziegelmayer 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. async-native-tls-0.5.0/LICENSE-MIT000064400000000000000000000017771046102023000144770ustar 00000000000000Permission 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. async-native-tls-0.5.0/README.md000064400000000000000000000070521046102023000143120ustar 00000000000000

async-native-tls

Asynchronous Native TLS

Crates.io version Download docs.rs docs

API Docs | Releases


> [Native TLS](https://crates.io/crates/native-tls) for [async-std](https://crates.io/crates/async-std) or [tokio](https://crates.io/crates/tokio). This crate uses SChannel on Windows (via [schannel](https://crates.io/crates/schannel)), Secure Transport on OSX (via [security-framework](https://crates.io/crates/security-framework)), and OpenSSL (via [openssl](https://crates.io/crates/openssl)) on all other platforms. ## Installation ```sh $ cargo add async-native-tls ``` #### Cargo Feature Flags * `runtime-async-std` (on by default): Use the `async-std` runtime. * `runtime-tokio`: Use the `tokio` runtime. This is mutually exclusive with `runtime-async-std`. ## Example #### async-std > Requires `runtime-async-std` feature (on by default). ```toml # Cargo.toml [dependencies] async-native-tls = "0.4" ``` ```rust use async_std::prelude::*; use async_std::net::TcpStream; let stream = TcpStream::connect("google.com:443").await?; let mut stream = async_native_tls::connect("google.com", stream).await?; stream.write_all(b"GET / HTTP/1.0\r\n\r\n").await?; let mut res = Vec::new(); stream.read_to_end(&mut res).await?; println!("{}", String::from_utf8_lossy(&res)); ``` #### tokio > Requires `runtime-tokio` feature. ```toml # Cargo.toml [dependencies] async-native-tls = { version = "0.4", default-features = false, features = [ "runtime-tokio" ] } ``` ```rust use tokio::prelude::*; use tokio::net::TcpStream; let stream = TcpStream::connect("google.com:443").await?; let mut stream = async_native_tls::connect("google.com", stream).await?; stream.write_all(b"GET / HTTP/1.0\r\n\r\n").await?; let mut res = Vec::new(); stream.read_to_end(&mut res).await?; println!("{}", String::from_utf8_lossy(&res)); ``` ## Contributing Want to join us? Check out our ["Contributing" guide][contributing] and take a look at some of these issues: - [Issues labeled "good first issue"][good-first-issue] - [Issues labeled "help wanted"][help-wanted] [contributing]: https://github.com/dignifiedquire/semver2/blob/master.github/CONTRIBUTING.md [good-first-issue]: https://github.com/dignifiedquire/semver2/labels/good%20first%20issue [help-wanted]: https://github.com/dignifiedquire/semver2/labels/help%20wanted ## License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. async-native-tls-0.5.0/src/acceptor.rs000064400000000000000000000107101046102023000157630ustar 00000000000000use std::fmt; use std::marker::Unpin; use crate::handshake::handshake; use crate::runtime::{AsyncRead, AsyncReadExt, AsyncWrite}; use crate::TlsStream; /// A wrapper around a `native_tls::TlsAcceptor`, providing an async `accept` /// method. /// /// # Example /// /// ```no_run /// # #[cfg(feature = "runtime-async-std")] /// # fn main() -> Result<(), Box> { async_std::task::block_on(async { /// # /// use async_std::prelude::*; /// use async_std::net::TcpListener; /// use async_std::fs::File; /// use async_native_tls::TlsAcceptor; /// /// let key = File::open("tests/identity.pfx").await?; /// let acceptor = TlsAcceptor::new(key, "hello").await?; /// let listener = TcpListener::bind("127.0.0.1:8443").await?; /// let mut incoming = listener.incoming(); /// /// while let Some(stream) = incoming.next().await { /// let acceptor = acceptor.clone(); /// let stream = stream?; /// async_std::task::spawn(async move { /// let stream = acceptor.accept(stream).await.unwrap(); /// // handle stream here /// }); /// } /// # /// # Ok(()) }) } /// # #[cfg(feature = "runtime-tokio")] /// # fn main() {} /// ``` #[derive(Clone)] pub struct TlsAcceptor(native_tls::TlsAcceptor); /// An error returned from creating an acceptor. #[derive(thiserror::Error, Debug)] pub enum Error { /// NativeTls error. #[error("NativeTls({})", 0)] NativeTls(#[from] native_tls::Error), /// Io error. #[error("Io({})", 0)] Io(#[from] std::io::Error), } impl TlsAcceptor { /// Create a new TlsAcceptor based on an identity file and matching password. pub async fn new(mut file: R, password: S) -> Result where R: AsyncRead + Unpin, S: AsRef, { let mut identity = vec![]; file.read_to_end(&mut identity).await?; let identity = native_tls::Identity::from_pkcs12(&identity, password.as_ref())?; Ok(TlsAcceptor(native_tls::TlsAcceptor::new(identity)?)) } /// Accepts a new client connection with the provided stream. /// /// This function will internally call `TlsAcceptor::accept` to connect /// the stream and returns a future representing the resolution of the /// connection operation. The returned future will resolve to either /// `TlsStream` or `Error` depending if it's successful or not. /// /// This is typically used after a new socket has been accepted from a /// `TcpListener`. That socket is then passed to this function to perform /// the server half of accepting a client connection. pub async fn accept(&self, stream: S) -> Result, native_tls::Error> where S: AsyncRead + AsyncWrite + Unpin, { let stream = handshake(move |s| self.0.accept(s), stream).await?; Ok(stream) } } impl fmt::Debug for TlsAcceptor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TlsAcceptor").finish() } } impl From for TlsAcceptor { fn from(inner: native_tls::TlsAcceptor) -> TlsAcceptor { TlsAcceptor(inner) } } #[cfg(all(test, feature = "runtime-async-std"))] mod tests { use super::*; use crate::runtime::AsyncWriteExt; use crate::TlsConnector; use async_std::fs::File; use async_std::net::{TcpListener, TcpStream}; use async_std::stream::StreamExt; #[async_std::test] async fn test_acceptor() { let key = File::open("tests/identity.pfx").await.unwrap(); let acceptor = TlsAcceptor::new(key, "hello").await.unwrap(); let listener = TcpListener::bind("127.0.0.1:8443").await.unwrap(); async_std::task::spawn(async move { let mut incoming = listener.incoming(); while let Some(stream) = incoming.next().await { let acceptor = acceptor.clone(); let stream = stream.unwrap(); async_std::task::spawn(async move { let mut stream = acceptor.accept(stream).await.unwrap(); stream.write_all(b"hello").await.unwrap(); }); } }); let stream = TcpStream::connect("127.0.01:8443").await.unwrap(); let connector = TlsConnector::new().danger_accept_invalid_certs(true); let mut stream = connector.connect("127.0.0.1", stream).await.unwrap(); let mut res = Vec::new(); stream.read_to_end(&mut res).await.unwrap(); assert_eq!(res, b"hello"); } } async-native-tls-0.5.0/src/connector.rs000064400000000000000000000017271046102023000161650ustar 00000000000000use std::fmt; use std::marker::Unpin; use native_tls::Error; use crate::handshake::handshake; use crate::runtime::{AsyncRead, AsyncWrite}; use crate::TlsStream; /// A wrapper around a `native_tls::TlsConnector`, providing an async `connect` /// method. #[derive(Clone)] pub(crate) struct TlsConnector(native_tls::TlsConnector); impl TlsConnector { /// Connects the provided stream with this connector, assuming the provided domain. pub(crate) async fn connect(&self, domain: &str, stream: S) -> Result, Error> where S: AsyncRead + AsyncWrite + Unpin, { handshake(move |s| self.0.connect(domain, s), stream).await } } impl fmt::Debug for TlsConnector { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TlsConnector").finish() } } impl From for TlsConnector { fn from(inner: native_tls::TlsConnector) -> TlsConnector { TlsConnector(inner) } } async-native-tls-0.5.0/src/handshake.rs000064400000000000000000000057671046102023000161310ustar 00000000000000use std::future::Future; use std::io::{Read, Write}; use std::marker::Unpin; use std::pin::Pin; use std::ptr::null_mut; use std::task::{Context, Poll}; use native_tls::{Error, HandshakeError, MidHandshakeTlsStream}; use crate::runtime::{AsyncRead, AsyncWrite}; use crate::std_adapter::StdAdapter; use crate::TlsStream; pub(crate) async fn handshake(f: F, stream: S) -> Result, Error> where F: FnOnce( StdAdapter, ) -> Result>, HandshakeError>> + Unpin, S: AsyncRead + AsyncWrite + Unpin, { let start = StartedHandshakeFuture(Some(StartedHandshakeFutureInner { f, stream })); match start.await { Err(e) => Err(e), Ok(StartedHandshake::Done(s)) => Ok(s), Ok(StartedHandshake::Mid(s)) => MidHandshake(Some(s)).await, } } struct MidHandshake(Option>>); enum StartedHandshake { Done(TlsStream), Mid(MidHandshakeTlsStream>), } struct StartedHandshakeFuture(Option>); struct StartedHandshakeFutureInner { f: F, stream: S, } impl Future for StartedHandshakeFuture where F: FnOnce( StdAdapter, ) -> Result>, HandshakeError>> + Unpin, S: Unpin, StdAdapter: Read + Write, { type Output = Result, Error>; fn poll( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll, Error>> { let inner = self.0.take().expect("future polled after completion"); let stream = StdAdapter { inner: inner.stream, context: ctx as *mut _ as *mut (), }; match (inner.f)(stream) { Ok(mut s) => { s.get_mut().context = null_mut(); Poll::Ready(Ok(StartedHandshake::Done(TlsStream::new(s)))) } Err(HandshakeError::WouldBlock(mut s)) => { s.get_mut().context = null_mut(); Poll::Ready(Ok(StartedHandshake::Mid(s))) } Err(HandshakeError::Failure(e)) => Poll::Ready(Err(e)), } } } impl Future for MidHandshake { type Output = Result, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let mut_self = self.get_mut(); let mut s = mut_self.0.take().expect("future polled after completion"); s.get_mut().context = cx as *mut _ as *mut (); match s.handshake() { Ok(stream) => Poll::Ready(Ok(TlsStream::new(stream))), Err(HandshakeError::Failure(e)) => Poll::Ready(Err(e)), Err(HandshakeError::WouldBlock(mut s)) => { s.get_mut().context = null_mut(); mut_self.0 = Some(s); Poll::Pending } } } } async-native-tls-0.5.0/src/lib.rs000064400000000000000000000274221046102023000147410ustar 00000000000000#![warn( missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub )] //! Async TLS streams //! //! # Examples //! //! To connect as a client to a remote server: //! //! ```rust //! # #[cfg(feature = "runtime-async-std")] //! # fn main() -> Result<(), Box> { async_std::task::block_on(async { //! # //! use async_std::prelude::*; //! use async_std::net::TcpStream; //! //! let stream = TcpStream::connect("google.com:443").await?; //! let mut stream = async_native_tls::connect("google.com", stream).await?; //! stream.write_all(b"GET / HTTP/1.0\r\n\r\n").await?; //! //! let mut res = Vec::new(); //! stream.read_to_end(&mut res).await?; //! println!("{}", String::from_utf8_lossy(&res)); //! # //! # Ok(()) }) } //! # #[cfg(feature = "runtime-tokio")] //! # fn main() {} //! ``` #[cfg(not(any(feature = "runtime-tokio", feature = "runtime-async-std")))] compile_error!("one of 'runtime-async-std' or 'runtime-tokio' features must be enabled"); #[cfg(all(feature = "runtime-tokio", feature = "runtime-async-std"))] compile_error!("only one of 'runtime-async-std' or 'runtime-tokio' features must be enabled"); mod acceptor; mod connector; mod handshake; mod runtime; mod std_adapter; mod tls_stream; pub use accept::accept; pub use acceptor::{Error as AcceptError, TlsAcceptor}; pub use connect::{connect, TlsConnector}; pub use host::Host; pub use tls_stream::TlsStream; #[doc(inline)] pub use native_tls::{Certificate, Error, Identity, Protocol, Result}; mod accept { use crate::runtime::{AsyncRead, AsyncWrite}; use crate::TlsStream; /// One of accept of an incoming connection. /// /// # Example /// /// ```no_run /// # #[cfg(feature = "runtime-async-std")] /// # fn main() -> Result<(), Box> { async_std::task::block_on(async { /// # /// use async_std::prelude::*; /// use async_std::net::TcpListener; /// use async_std::fs::File; /// /// let listener = TcpListener::bind("0.0.0.0:8443").await?; /// let (stream, _addr) = listener.accept().await?; /// /// let key = File::open("identity.pfx").await?; /// let stream = async_native_tls::accept(key, "", stream).await?; /// // handle stream here /// # /// # Ok(()) }) } /// # #[cfg(feature = "runtime-tokio")] /// # fn main() {} /// ``` pub async fn accept( file: R, password: S, stream: T, ) -> Result, crate::AcceptError> where R: AsyncRead + Unpin, S: AsRef, T: AsyncRead + AsyncWrite + Unpin, { let acceptor = crate::TlsAcceptor::new(file, password).await?; let stream = acceptor.accept(stream).await?; Ok(stream) } } mod host { use url::Url; /// The host part of a domain (without scheme, port and path). /// /// This is the argument to the [`connect`](crate::connect::connect) function. Strings and string slices are /// converted into Hosts automatically, as is [Url](url::Url) with the `host-from-url` feature (enabled by default). #[derive(Debug)] pub struct Host(String); impl Host { /// The host as string. Consumes self. #[allow(clippy::wrong_self_convention)] pub fn as_string(self) -> String { self.0 } } impl From<&str> for Host { fn from(host: &str) -> Self { Self(host.into()) } } impl From for Host { fn from(host: String) -> Self { Self(host) } } impl From<&String> for Host { fn from(host: &String) -> Self { Self(host.into()) } } impl From for Host { fn from(url: Url) -> Self { Self( url.host_str() .expect("URL has to include a host part.") .into(), ) } } impl From<&Url> for Host { fn from(url: &Url) -> Self { Self( url.host_str() .expect("URL has to include a host part.") .into(), ) } } } mod connect { use std::fmt::{self, Debug}; use crate::host::Host; use crate::runtime::{AsyncRead, AsyncWrite}; use crate::TlsStream; use crate::{Certificate, Identity, Protocol}; /// Connect a client to a remote server. /// /// # Examples /// /// ``` /// # #[cfg(feature = "runtime-async-std")] /// # fn main() -> Result<(), Box> { async_std::task::block_on(async { /// # /// use async_std::prelude::*; /// use async_std::net::TcpStream; /// /// let stream = TcpStream::connect("google.com:443").await?; /// let mut stream = async_native_tls::connect("google.com", stream).await?; /// stream.write_all(b"GET / HTTP/1.0\r\n\r\n").await?; /// /// let mut res = Vec::new(); /// stream.read_to_end(&mut res).await?; /// println!("{}", String::from_utf8_lossy(&res)); /// # /// # Ok(()) }) } /// # #[cfg(feature = "runtime-tokio")] /// # fn main() {} /// ``` pub async fn connect(host: impl Into, stream: S) -> native_tls::Result> where S: AsyncRead + AsyncWrite + Unpin, { let stream = TlsConnector::new().connect(host, stream).await?; Ok(stream) } /// Connect a client to a remote server. /// /// # Examples /// /// ``` /// # #[cfg(feature = "runtime-async-std")] /// # fn main() -> Result<(), Box> { async_std::task::block_on(async { /// # /// use async_std::prelude::*; /// use async_std::net::TcpStream; /// use async_native_tls::TlsConnector; /// /// let stream = TcpStream::connect("google.com:443").await?; /// let mut stream = TlsConnector::new() /// .use_sni(true) /// .connect("google.com", stream) /// .await?; /// stream.write_all(b"GET / HTTP/1.0\r\n\r\n").await?; /// /// let mut res = Vec::new(); /// stream.read_to_end(&mut res).await?; /// println!("{}", String::from_utf8_lossy(&res)); /// # /// # Ok(()) }) } /// # #[cfg(feature = "runtime-tokio")] /// # fn main() {} /// ``` pub struct TlsConnector { builder: native_tls::TlsConnectorBuilder, } impl Default for TlsConnector { fn default() -> Self { TlsConnector::new() } } impl TlsConnector { /// Create a new instance. pub fn new() -> Self { Self { builder: native_tls::TlsConnector::builder(), } } /// Sets the identity to be used for client certificate authentication. pub fn identity(mut self, identity: Identity) -> Self { self.builder.identity(identity); self } /// Sets the minimum supported protocol version. /// /// A value of `None` enables support for the oldest protocols supported by the /// implementation. Defaults to `Some(Protocol::Tlsv10)`. pub fn min_protocol_version(mut self, protocol: Option) -> Self { self.builder.min_protocol_version(protocol); self } /// Sets the maximum supported protocol version. /// /// A value of `None` enables support for the newest protocols supported by the /// implementation. Defaults to `None`. pub fn max_protocol_version(mut self, protocol: Option) -> Self { self.builder.max_protocol_version(protocol); self } /// Adds a certificate to the set of roots that the connector will trust. /// /// The connector will use the system's trust root by default. This method can be used to /// add to that set when communicating with servers not trusted by the system. Defaults to /// an empty set. pub fn add_root_certificate(mut self, cert: Certificate) -> Self { self.builder.add_root_certificate(cert); self } /// Request specific protocols through ALPN (Application-Layer Protocol Negotiation). /// /// Defaults to none pub fn request_alpns(mut self, protocols: &[&str]) -> Self { self.builder.request_alpns(protocols); self } /// Controls the use of certificate validation. /// /// Defaults to false. /// /// # Warning /// /// You should think very carefully before using this method. If invalid certificates are /// trusted, any certificate for any site will be trusted for use. This includes expired /// certificates. This introduces significant vulnerabilities, and should only be used as a /// last resort. pub fn danger_accept_invalid_certs(mut self, accept_invalid_certs: bool) -> Self { self.builder .danger_accept_invalid_certs(accept_invalid_certs); self } /// Controls the use of Server Name Indication (SNI). /// /// Defaults to `true`. pub fn use_sni(mut self, use_sni: bool) -> Self { self.builder.use_sni(use_sni); self } /// Controls the use of hostname verification. /// /// Defaults to `false`. /// /// # Warning /// /// You should think very carefully before using this method. If invalid hostnames are /// trusted, any valid certificate for any site will be trusted for use. This introduces /// significant vulnerabilities, and should only be used as a last resort. pub fn danger_accept_invalid_hostnames(mut self, accept_invalid_hostnames: bool) -> Self { self.builder .danger_accept_invalid_hostnames(accept_invalid_hostnames); self } /// Connect to a remote server. /// /// # Examples /// /// ``` /// # #[cfg(feature = "runtime-async-std")] /// # fn main() -> Result<(), Box> { async_std::task::block_on(async { /// # /// use async_std::prelude::*; /// use async_std::net::TcpStream; /// use async_native_tls::TlsConnector; /// /// let stream = TcpStream::connect("google.com:443").await?; /// let mut stream = TlsConnector::new() /// .use_sni(true) /// .connect("google.com", stream) /// .await?; /// stream.write_all(b"GET / HTTP/1.0\r\n\r\n").await?; /// /// let mut res = Vec::new(); /// stream.read_to_end(&mut res).await?; /// println!("{}", String::from_utf8_lossy(&res)); /// # /// # Ok(()) }) } /// # #[cfg(feature = "runtime-tokio")] /// # fn main() {} /// ``` pub async fn connect( &self, host: impl Into, stream: S, ) -> native_tls::Result> where S: AsyncRead + AsyncWrite + Unpin, { let host: Host = host.into(); let domain = host.as_string(); let connector = self.builder.build()?; let connector = crate::connector::TlsConnector::from(connector); let stream = connector.connect(&domain, stream).await?; Ok(stream) } } impl Debug for TlsConnector { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TlsConnector").finish() } } impl From for TlsConnector { fn from(builder: native_tls::TlsConnectorBuilder) -> Self { Self { builder } } } } async-native-tls-0.5.0/src/runtime.rs000064400000000000000000000005041046102023000156460ustar 00000000000000#[cfg(feature = "runtime-async-std")] pub(crate) use futures_util::io::{AsyncRead, AsyncWrite}; #[cfg(feature = "runtime-async-std")] #[allow(unused_imports)] pub(crate) use futures_util::io::{AsyncReadExt, AsyncWriteExt}; #[cfg(feature = "runtime-tokio")] pub(crate) use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite}; async-native-tls-0.5.0/src/std_adapter.rs000064400000000000000000000041661046102023000164650ustar 00000000000000use std::io::{self, Read, Write}; use std::marker::Unpin; use std::pin::Pin; use std::task::{Context, Poll}; use crate::runtime::{AsyncRead, AsyncWrite}; #[derive(Debug)] pub(crate) struct StdAdapter { pub(crate) inner: S, pub(crate) context: *mut (), } // *mut () context is neither Send nor Sync unsafe impl Send for StdAdapter {} unsafe impl Sync for StdAdapter {} impl StdAdapter where S: Unpin, { pub(crate) fn with_context(&mut self, f: F) -> R where F: FnOnce(&mut Context<'_>, Pin<&mut S>) -> R, { unsafe { assert!(!self.context.is_null()); let waker = &mut *(self.context as *mut _); f(waker, Pin::new(&mut self.inner)) } } } #[cfg(feature = "runtime-async-std")] impl Read for StdAdapter where S: AsyncRead + Unpin, { fn read(&mut self, buf: &mut [u8]) -> io::Result { match self.with_context(|ctx, stream| stream.poll_read(ctx, buf)) { Poll::Ready(r) => r, Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), } } } #[cfg(feature = "runtime-tokio")] impl Read for StdAdapter where S: AsyncRead + Unpin, { fn read(&mut self, buf: &mut [u8]) -> io::Result { let mut buf = tokio::io::ReadBuf::new(buf); match self.with_context(|ctx, stream| stream.poll_read(ctx, &mut buf)) { Poll::Ready(r) => r.map(|_| buf.filled().len()), Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), } } } impl Write for StdAdapter 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)), } } } async-native-tls-0.5.0/src/tls_stream.rs000064400000000000000000000115141046102023000163430ustar 00000000000000use std::io::{self, Read, Write}; use std::marker::Unpin; use std::pin::Pin; use std::ptr::null_mut; use std::task::{Context, Poll}; use crate::runtime::{AsyncRead, AsyncWrite}; use crate::std_adapter::StdAdapter; /// A stream managing a TLS session. /// /// A wrapper around an underlying raw stream which implements the TLS or SSL /// protocol. /// /// A `TlsStream` 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 `TlsStream` are decrypted from `S` and bytes written /// to a `TlsStream` are encrypted when passing through to `S`. #[derive(Debug)] pub struct TlsStream(native_tls::TlsStream>); impl TlsStream { pub(crate) fn new(stream: native_tls::TlsStream>) -> Self { Self(stream) } fn with_context(&mut self, ctx: &mut Context<'_>, f: F) -> R where F: FnOnce(&mut native_tls::TlsStream>) -> R, StdAdapter: Read + Write, { self.0.get_mut().context = ctx as *mut _ as *mut (); let g = Guard(self); f(&mut (g.0).0) } /// Returns a shared reference to the inner stream. pub fn get_ref(&self) -> &S where S: AsyncRead + AsyncWrite + Unpin, { &self.0.get_ref().inner } /// Returns a mutable reference to the inner stream. pub fn get_mut(&mut self) -> &mut S where S: AsyncRead + AsyncWrite + Unpin, { &mut self.0.get_mut().inner } /// Returns the number of bytes that can be read without resulting in any network calls. pub fn buffered_read_size(&self) -> crate::Result where S: AsyncRead + AsyncWrite + Unpin, { self.0.buffered_read_size() } /// Returns the peer's leaf certificate, if available. pub fn peer_certificate(&self) -> crate::Result> where S: AsyncRead + AsyncWrite + Unpin, { self.0.peer_certificate() } /// Returns the tls-server-end-point channel binding data as defined in [RFC 5929](https://tools.ietf.org/html/rfc5929). pub fn tls_server_end_point(&self) -> crate::Result>> where S: AsyncRead + AsyncWrite + Unpin, { self.0.tls_server_end_point() } } #[cfg(feature = "runtime-async-std")] impl AsyncRead for TlsStream where S: AsyncRead + AsyncWrite + Unpin, { fn poll_read( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &mut [u8], ) -> Poll> { self.with_context(ctx, |s| cvt(s.read(buf))) } } #[cfg(feature = "runtime-tokio")] impl AsyncRead for TlsStream where S: AsyncRead + AsyncWrite + Unpin, { fn poll_read( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> Poll> { match self.with_context(ctx, |s| cvt(s.read(buf.initialize_unfilled()))) { Poll::Ready(Ok(len)) => { buf.advance(len); Poll::Ready(Ok(())) } Poll::Ready(Err(err)) => Poll::Ready(Err(err)), Poll::Pending => Poll::Pending, } } } impl AsyncWrite for TlsStream 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())) } #[cfg(feature = "runtime-async-std")] fn poll_close(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll> { match self.with_context(ctx, |s| s.shutdown()) { Ok(()) => Poll::Ready(Ok(())), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, Err(e) => Poll::Ready(Err(e)), } } #[cfg(feature = "runtime-tokio")] fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll> { match self.with_context(ctx, |s| s.shutdown()) { Ok(()) => Poll::Ready(Ok(())), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, Err(e) => Poll::Ready(Err(e)), } } } struct Guard<'a, S>(&'a mut TlsStream) where StdAdapter: Read + Write; impl Drop for Guard<'_, S> where StdAdapter: Read + Write, { fn drop(&mut self) { (self.0).0.get_mut().context = null_mut(); } } 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)), } } async-native-tls-0.5.0/tests/bad.rs000064400000000000000000000054711046102023000152740ustar 00000000000000// #![warn(rust_2018_idioms)] use std::io::{self, Error}; use std::net::ToSocketAddrs; use async_native_tls::TlsConnector; use async_std::net::TcpStream; use cfg_if::cfg_if; use env_logger; macro_rules! t { ($e:expr) => { match $e { Ok(e) => e, Err(e) => panic!("{} failed with {:?}", stringify!($e), e), } }; } cfg_if! { if #[cfg(any(feature = "force-openssl", all(not(target_os = "macos"), not(target_os = "windows"), not(target_os = "ios"))))] { fn verify_failed(err: &Error) { assert!(format!("{}", err).contains("certificate verify failed")) } use verify_failed as assert_expired_error; use verify_failed as assert_wrong_host; use verify_failed as assert_self_signed; use verify_failed as assert_untrusted_root; } else if #[cfg(any(target_os = "macos", target_os = "ios"))] { fn assert_invalid_cert_chain(err: &Error) { assert!(format!("{}", err).contains("was not trusted.")) } use crate::assert_invalid_cert_chain as assert_expired_error; use crate::assert_invalid_cert_chain as assert_wrong_host; use crate::assert_invalid_cert_chain as assert_self_signed; use crate::assert_invalid_cert_chain as assert_untrusted_root; } else { fn assert_expired_error(err: &Error) { let s = err.to_string(); assert!(s.contains("system clock"), "error = {:?}", s); } fn assert_wrong_host(err: &Error) { let s = err.to_string(); assert!(s.contains("CN name"), "error = {:?}", s); } fn assert_self_signed(err: &Error) { let s = err.to_string(); assert!(s.contains("root certificate which is not trusted"), "error = {:?}", s); } use assert_self_signed as assert_untrusted_root; } } async fn get_host(host: &'static str) -> Error { drop(env_logger::try_init()); let addr = format!("{}:443", host); let addr = t!(addr.to_socket_addrs()).next().unwrap(); let socket = t!(TcpStream::connect(&addr).await); let cx = TlsConnector::new(); let res = cx .connect(host, socket) .await .map_err(|e| Error::new(io::ErrorKind::Other, e)); assert!(res.is_err()); res.err().unwrap() } #[async_std::test] async fn expired() { assert_expired_error(&get_host("expired.badssl.com").await) } #[async_std::test] async fn wrong_host() { assert_wrong_host(&get_host("wrong.host.badssl.com").await) } #[async_std::test] async fn self_signed() { assert_self_signed(&get_host("self-signed.badssl.com").await) } #[async_std::test] async fn untrusted_root() { assert_untrusted_root(&get_host("untrusted-root.badssl.com").await) } async-native-tls-0.5.0/tests/google-tokio.rs000064400000000000000000000044651046102023000171470ustar 00000000000000#![warn(rust_2018_idioms)] use std::io; use std::net::ToSocketAddrs; use async_native_tls; use cfg_if::cfg_if; use env_logger; use native_tls; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; macro_rules! t { ($e:expr) => { match $e { Ok(e) => e, Err(e) => panic!("{} failed with {:?}", stringify!($e), e), } }; } cfg_if! { if #[cfg(any(feature = "force-openssl", all(not(target_os = "macos"), not(target_os = "windows"), not(target_os = "ios"))))] { fn assert_bad_hostname_error(err: &io::Error) { let err = err.get_ref().unwrap(); let err = err.downcast_ref::().unwrap(); assert!(format!("{}", err).contains("certificate verify failed")); } } else if #[cfg(any(target_os = "macos", target_os = "ios"))] { fn assert_bad_hostname_error(err: &io::Error) { let err = err.get_ref().unwrap(); let err = err.downcast_ref::().unwrap(); assert!(format!("{}", err).contains("was not trusted.")); } } else { fn assert_bad_hostname_error(err: &io::Error) { let err = err.get_ref().unwrap(); let err = err.downcast_ref::().unwrap(); assert!(format!("{}", err).contains("CN name")); } } } #[tokio::test] async fn fetch_google() { drop(env_logger::try_init()); // First up, resolve google.com let addr = t!("google.com:443".to_socket_addrs()).next().unwrap(); let socket = TcpStream::connect(&addr).await.unwrap(); // Send off the request by first negotiating an SSL handshake, then writing // of our request, then flushing, then finally read off the response. let connector = async_native_tls::TlsConnector::new(); let mut socket = t!(connector.connect("google.com", socket).await); t!(socket.write_all(b"GET / HTTP/1.0\r\n\r\n").await); let mut data = Vec::new(); t!(socket.read_to_end(&mut data).await); // any response code is fine assert!(data.starts_with(b"HTTP/1.0 ")); let data = String::from_utf8_lossy(&data); let data = data.trim_end(); assert!(data.ends_with("") || data.ends_with("")); } async-native-tls-0.5.0/tests/google.rs000064400000000000000000000023771046102023000160240ustar 00000000000000#![warn(rust_2018_idioms)] use std::net::ToSocketAddrs; use async_native_tls; use async_std::net::TcpStream; use async_std::prelude::*; use env_logger; macro_rules! t { ($e:expr) => { match $e { Ok(e) => e, Err(e) => panic!("{} failed with {:?}", stringify!($e), e), } }; } #[async_std::test] async fn fetch_google() { drop(env_logger::try_init()); // First up, resolve google.com let addr = t!("google.com:443".to_socket_addrs()).next().unwrap(); let socket = TcpStream::connect(&addr).await.unwrap(); // Send off the request by first negotiating an SSL handshake, then writing // of our request, then flushing, then finally read off the response. let connector = async_native_tls::TlsConnector::new(); let url = url::Url::parse("https://google.com/").unwrap(); let mut socket = t!(connector.connect(&url, socket).await); t!(socket.write_all(b"GET / HTTP/1.0\r\n\r\n").await); let mut data = Vec::new(); t!(socket.read_to_end(&mut data).await); // any response code is fine assert!(data.starts_with(b"HTTP/1.0 ")); let data = String::from_utf8_lossy(&data); let data = data.trim_end(); assert!(data.ends_with("") || data.ends_with("")); } async-native-tls-0.5.0/tests/identity.pfx000064400000000000000000000046551046102023000165530ustar 000000000000000 0 o *H  ` \0 X0 *H 00 *H 0 *H  0_CȲB^(w)8sv0Vp)Ta{{\0epۀo0J` 妄AboH݃KSm[V#|ȁFT*oVI6(B}HpדnGI6Lר3h+h>W=7|x5 'G2eP366 hY( \e|=nc/NBq5q;KK'k3 go(QV@*TZeҋRy[xudO >D(Aՙlr~E9 @p PvXYEv3Y'n-l`Sf}KnY+0~eҩ@8;R`_P\ 7d$ttNy7x*UMHoᘬEþ3{zYH-y{0D$5#~F.ZhR2W!rm͹Y69/ ;$ Gk:'[ShDQ7,Y0BGiC^T6[͍]^~8'6TbND tR2W}+V~yIM;vDx Q/' $„s9^x`~wr˟hʉ 2b98w\R0A *H 2.0*0& *H  00 *H  0?;h}81~$ɜCU)e,|5: it(hѡd΁Aq@믍YܴN5 0$9_kA,k(zPlv|=Q4ԯ~0ݰvW7i"safqmhݵ382IѦeq8/caaUҰLV_V `Z'X`4S mO,y/TŸoa Nxr$-`z/Y'h] 3)(XC(;k$Ief5X3]oDήCq2F sZzIU2MЉa1TX׾2Vd1c8nJЊ  C7?3 \$piݶ@ǝ @D;+܆ {1jnB|tTj=\早fsw3/o ߪZ1 1Z )xE$@,r?< eХ'G{FXhD7s,oKig9p߄.GBw/ۂO/qP6`ƴ]grb# RųڇP_0eM`z.tnVXF5@W^y.iet91V=kg~T)O!e5E=L.IOg^\e}!ZX6螏'{[ 3 MXBKB.'ȷE}V}EmgQ׽>m RgP*91'I1RYM4Q1D3Ŷ& do~R$Nד-KK*|z_&`7INeAzBϾ͘&s^:{ڔ)0]HğZk5&1BEڙ} FS2؀ōJ$~2 sFC&B&B*G1NXzۏT;!) i=4cu(ZYoA9E:nv\iR]~ku`*-i|rFOBDs^Uz3N>WRA%i dd%Y'(00 g:Px'+$͒h%(ȑ3 OlWpJC9,&2PZ`&xI؈ 61%0# *H  1VċLb4d&010!0 +ER~( ec8&4async-native-tls-0.5.0/tests/private.pem000064400000000000000000000032171046102023000163510ustar 00000000000000-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAt12jPQlDWLtJS+WQNxqhWrZJDjvR2zma2xc7E6oD9h8DrZ8J L2D6hS6+v/K3BsQW89wJIU10WFAaZmuJ/8QJ3Rwf9Yzqjy0PPAwDY8Nt/kbcXb77 odFXxt3wHoe2g3x4kXRMSGfb++GVkjpXus9mY1pU0LWgH/HWjy1bPbxM4tPykQ+J iHJ0xxRHjHdmO+NnR2ZRsW0/+eT1RbegLXiMYoJ5iiZ5niXRL1pqs0ixTvKQ1Rqr iZxdorbAN+27EP69XMwBdC9LzEUR8d07oCBDKIBJJ/N5DH1dZqJkviNzg4umkbML BYpSIvCod8GvzEKGdCXZuUmh4Ud60elQa4xjIQIDAQABAoIBAHP0vxoGFZSzOzLH xV9Tc95Nj/10Ts13rDoIgs94oHCwRD8zZzeS+Fnoqa/w6VVaA7nK1+s7c+u1HDzQ nMAlVKeC9aLurhZExHGQl0Qrfg9i+FBAShiWrg+QohxsbjrQJ96z0Nmo9DBhA5kp U/lK1tDVevVRJiWNZcW9RQnRXj3B/+2doHpaBTWfvzbsIYX3CZDWokOZUbCE0YD7 dK8MxsiXlbRTtCzCM1zBzRJFILH8bjepAP8UVoGkYZR1poJ4ouogUsMeUZad8lkj rltnd1N7Zfhrgf1i9h1qekqOlpMq5S8DLWtt24QjzTP+HZvHB5q016m5tC5/ig8I ySra89ECgYEA546CxyIkXmS384JkbWMa6CWOG8NG+ENsKpBRplS+fPGfCHcrMYxc taRY2B1x8K9D8uQGb2G32VkgUE6kzhgDYGgo3pC3diCislPI4uWvMfkf3HTptJfE 435NtbmgU85sYUEazzTBAdffRBeLTB8yfVkQPSHKR/0ht4LUP394FTMCgYEAyrjW DiFBXZH96ebeg55xrOq+kbtHO5HdHmIzUG7LXowzbqDrqbZ5hbH2qkFS5FtoJfvO oN2DYTCXCPKaw9uPVLxIbXX66AwlkTZRYOmMc5Q30gDiUYiH1EM0C9CLtxuHJCUU 4g9Tr2gnTMGXTyHHi8ahLDp86wARvvgXqMFbvlsCgYEA4i3a4kYgPi+lWu8/x3Vp n96nG8k39mJtMno7tvvKAWNGE0/L2h8fo7F/ssG4PQAFoChJfNx3Z49eN/NJmaHt EmtLmHLFMVaZdRTQAYmXAno0O/PbIDKq+Ae0QlCqIZJdXPXqCQGfkXxaMjnJL7a9 a6DmcsAhxQWlvInHZqrNEe8CgYEAqxsf8YU4OtZCzu5C2i0eHal1eGPuV+ViEYcp cLZTiVYlAzdoMjMGl0YCwOmqIXzVh1nmqfjOL3ZnxPGgl7f2XrsdFucCBGJcQxjp zzbRiayNAQAmBlOK8ipW/7Hie4cMpgF2gugU5nSu1yZ/pBcK6nuZBk/HqELCt8GH lrS9zwkCgYBum7PSlGWuyb7+8VEl8hSt16p6X/j/cb0NT1aZ9zXxtlSI8HF+2bYX LpIrWdhyeyhRUavw4qfI4HIYdFV7A+kPT2AMXOb+SsnXbVTNIFV6QBM1acS+jY6E Nd4OlK5N1HjC1+3Ls9sZhY6ITwyXwWZL1v+l+Ux4l2T2+FDlIYafBQ== -----END RSA PRIVATE KEY----- async-native-tls-0.5.0/tests/public.pem000064400000000000000000000023351046102023000161550ustar 00000000000000-----BEGIN CERTIFICATE----- MIIDazCCAlOgAwIBAgIUUmZABc91z+oEFScf1UAj0z7J/yUwDQYJKoZIhvcNAQEL BQAwRTELMAkGA1UEBhMCREUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0xOTEyMjAyMzM5MzVaFw0yMDAx MTkyMzM5MzVaMEUxCzAJBgNVBAYTAkRFMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB AQUAA4IBDwAwggEKAoIBAQC3XaM9CUNYu0lL5ZA3GqFatkkOO9HbOZrbFzsTqgP2 HwOtnwkvYPqFLr6/8rcGxBbz3AkhTXRYUBpma4n/xAndHB/1jOqPLQ88DANjw23+ Rtxdvvuh0VfG3fAeh7aDfHiRdExIZ9v74ZWSOle6z2ZjWlTQtaAf8daPLVs9vEzi 0/KRD4mIcnTHFEeMd2Y742dHZlGxbT/55PVFt6AteIxignmKJnmeJdEvWmqzSLFO 8pDVGquJnF2itsA37bsQ/r1czAF0L0vMRRHx3TugIEMogEkn83kMfV1momS+I3OD i6aRswsFilIi8Kh3wa/MQoZ0Jdm5SaHhR3rR6VBrjGMhAgMBAAGjUzBRMB0GA1Ud DgQWBBRV/2ir5TPL0YLbsuk+6FY60YaRFzAfBgNVHSMEGDAWgBRV/2ir5TPL0YLb suk+6FY60YaRFzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBi tpb5GGSoEYz0oToyrXCKmkixVwVwM1KCvaXZb75rStyka39JK7eDfZyIK7QmGUV8 87XLqAe74gH50WxMh1bGpGp8RCzkF9ogs6XUk2pnankM5tQb6UmccBWoW7vp4DJr W/eC3QGGwulWvpqnp+/wcBR/g/6It0HkPbWblD+DsFYlyk0f1a7eF6JziJaqBx8D 9KM2Nlxt70d56drhAw72JlvKXHTbUXO25o/4NZoVcB4UUJpLqrfHj3E2o/DRRnaK SvvBJ8QSYupF/WLt0iUUhGCoQ9F3fsSCwcBNYpWlDj3YsOERkO4PvXwhWaPhE8hq FonvBHqxCuTKOmU4uEyL -----END CERTIFICATE----- async-native-tls-0.5.0/tests/smoke.rs000064400000000000000000000455531046102023000156710ustar 00000000000000#![warn(rust_2018_idioms)] use std::io::Write; use std::marker::Unpin; use std::process::Command; use std::ptr; use async_std::io; use async_std::net::{TcpListener, TcpStream}; use async_std::prelude::*; use cfg_if::cfg_if; use env_logger; use futures::join; use futures::stream::StreamExt; use futures::AsyncWrite; use native_tls; use native_tls::{Identity, TlsAcceptor}; macro_rules! t { ($e:expr) => { match $e { Ok(e) => e, Err(e) => panic!("{} failed with {:?}", stringify!($e), e), } }; } #[allow(dead_code)] struct Keys { cert_der: Vec, pkey_der: Vec, pkcs12_der: Vec, } #[allow(dead_code)] fn openssl_keys() -> &'static Keys { static INIT: Once = Once::new(); static mut KEYS: *mut Keys = ptr::null_mut(); INIT.call_once(|| { let path = t!(env::current_exe()); let path = path.parent().unwrap(); let keyfile = path.join("test.key"); let certfile = path.join("test.crt"); let config = path.join("openssl.config"); File::create(&config) .unwrap() .write_all( b"\ [req]\n\ distinguished_name=dn\n\ [ dn ]\n\ CN=localhost\n\ [ ext ]\n\ basicConstraints=CA:FALSE,pathlen:0\n\ subjectAltName = @alt_names extendedKeyUsage=serverAuth,clientAuth [alt_names] DNS.1 = localhost ", ) .unwrap(); let subj = "/C=US/ST=Denial/L=Sprintfield/O=Dis/CN=localhost"; let output = t!(Command::new("openssl") .arg("req") .arg("-nodes") .arg("-x509") .arg("-newkey") .arg("rsa:2048") .arg("-config") .arg(&config) .arg("-extensions") .arg("ext") .arg("-subj") .arg(subj) .arg("-keyout") .arg(&keyfile) .arg("-out") .arg(&certfile) .arg("-days") .arg("1") .output()); assert!(output.status.success()); let crtout = t!(Command::new("openssl") .arg("x509") .arg("-outform") .arg("der") .arg("-in") .arg(&certfile) .output()); assert!(crtout.status.success()); let keyout = t!(Command::new("openssl") .arg("rsa") .arg("-outform") .arg("der") .arg("-in") .arg(&keyfile) .output()); assert!(keyout.status.success()); let pkcs12out = t!(Command::new("openssl") .arg("pkcs12") .arg("-export") .arg("-nodes") .arg("-inkey") .arg(&keyfile) .arg("-in") .arg(&certfile) .arg("-password") .arg("pass:foobar") .output()); assert!(pkcs12out.status.success()); let keys = Box::new(Keys { cert_der: crtout.stdout, pkey_der: keyout.stdout, pkcs12_der: pkcs12out.stdout, }); unsafe { KEYS = Box::into_raw(keys); } }); unsafe { &*KEYS } } cfg_if! { if #[cfg(any(feature = "force-openssl", all(not(target_os = "macos"), not(target_os = "windows"), not(target_os = "ios"))))] { use std::fs::File; use std::env; use std::sync::Once; use async_native_tls::TlsConnector; fn contexts() -> (async_native_tls::TlsAcceptor, async_native_tls::TlsConnector) { let keys = openssl_keys(); let pkcs12 = t!(Identity::from_pkcs12(&keys.pkcs12_der, "foobar")); let srv = TlsAcceptor::builder(pkcs12); let cert = t!(native_tls::Certificate::from_der(&keys.cert_der)); let client = TlsConnector::new(); let client = client.add_root_certificate(cert); (t!(srv.build()).into(), client.into()) } } else if #[cfg(any(target_os = "macos", target_os = "ios"))] { use std::env; use std::fs::File; use std::sync::Once; fn contexts() -> (async_native_tls::TlsAcceptor, async_native_tls::TlsConnector) { let keys = openssl_keys(); let pkcs12 = t!(Identity::from_pkcs12(&keys.pkcs12_der, "foobar")); let srv = TlsAcceptor::builder(pkcs12); let cert = native_tls::Certificate::from_der(&keys.cert_der).unwrap(); let client = async_native_tls::TlsConnector::new().add_root_certificate(cert); (t!(srv.build()).into(), client.into()) } } else { use schannel; use winapi; use std::env; use std::fs::File; use std::io; use std::mem; use std::sync::Once; use schannel::cert_context::CertContext; use schannel::cert_store::{CertStore, CertAdd, Memory}; use winapi::shared::basetsd::*; use winapi::shared::lmcons::*; use winapi::shared::minwindef::*; use winapi::shared::ntdef::WCHAR; use winapi::um::minwinbase::*; use winapi::um::sysinfoapi::*; use winapi::um::timezoneapi::*; use winapi::um::wincrypt::*; const FRIENDLY_NAME: &'static str = "async-native-tls localhost testing cert"; fn contexts() -> (async_native_tls::TlsAcceptor, async_native_tls::TlsConnector) { let cert = localhost_cert(); let mut store = t!(Memory::new()).into_store(); t!(store.add_cert(&cert, CertAdd::Always)); let pkcs12_der = t!(store.export_pkcs12("foobar")); let pkcs12 = t!(Identity::from_pkcs12(&pkcs12_der, "foobar")); let srv = TlsAcceptor::builder(pkcs12); let client = TlsConnector::builder(); (t!(srv.build()).into(), t!(client.build()).into()) } // ==================================================================== // Magic! // // Lots of magic is happening here to wrangle certificates for running // these tests on Windows. For more information see the test suite // in the schannel-rs crate as this is just coyping that. // // The general gist of this though is that the only way to add custom // trusted certificates is to add it to the system store of trust. To // do that we go through the whole rigamarole here to generate a new // self-signed certificate and then insert that into the system store. // // This generates some dialogs, so we print what we're doing sometimes, // and otherwise we just manage the ephemeral certificates. Because // they're in the system store we always ensure that they're only valid // for a small period of time (e.g. 1 day). fn localhost_cert() -> CertContext { static INIT: Once = Once::new(); INIT.call_once(|| { for cert in local_root_store().certs() { let name = match cert.friendly_name() { Ok(name) => name, Err(_) => continue, }; if name != FRIENDLY_NAME { continue } if !cert.is_time_valid().unwrap() { io::stdout().write_all(br#" The async-native-tls test suite is about to delete an old copy of one of its certificates from your root trust store. This certificate was only valid for one day and it is no longer needed. The host should be "localhost" and the description should mention "async-native-tls". "#).unwrap(); cert.delete().unwrap(); } else { return } } install_certificate().unwrap(); }); for cert in local_root_store().certs() { let name = match cert.friendly_name() { Ok(name) => name, Err(_) => continue, }; if name == FRIENDLY_NAME { return cert } } panic!("couldn't find a cert"); } fn local_root_store() -> CertStore { if env::var("CI").is_ok() { CertStore::open_local_machine("Root").unwrap() } else { CertStore::open_current_user("Root").unwrap() } } fn install_certificate() -> io::Result { unsafe { let mut provider = 0; let mut hkey = 0; let mut buffer = "async-native-tls test suite".encode_utf16() .chain(Some(0)) .collect::>(); let res = CryptAcquireContextW(&mut provider, buffer.as_ptr(), ptr::null_mut(), PROV_RSA_FULL, CRYPT_MACHINE_KEYSET); if res != TRUE { // create a new key container (since it does not exist) let res = CryptAcquireContextW(&mut provider, buffer.as_ptr(), ptr::null_mut(), PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET); if res != TRUE { return Err(Error::last_os_error()) } } // create a new keypair (RSA-2048) let res = CryptGenKey(provider, AT_SIGNATURE, 0x0800<<16 | CRYPT_EXPORTABLE, &mut hkey); if res != TRUE { return Err(Error::last_os_error()); } // start creating the certificate let name = "CN=localhost,O=async-native-tls,OU=async-native-tls,\ G=async-native_tls".encode_utf16() .chain(Some(0)) .collect::>(); let mut cname_buffer: [WCHAR; UNLEN as usize + 1] = mem::zeroed(); let mut cname_len = cname_buffer.len() as DWORD; let res = CertStrToNameW(X509_ASN_ENCODING, name.as_ptr(), CERT_X500_NAME_STR, ptr::null_mut(), cname_buffer.as_mut_ptr() as *mut u8, &mut cname_len, ptr::null_mut()); if res != TRUE { return Err(Error::last_os_error()); } let mut subject_issuer = CERT_NAME_BLOB { cbData: cname_len, pbData: cname_buffer.as_ptr() as *mut u8, }; let mut key_provider = CRYPT_KEY_PROV_INFO { pwszContainerName: buffer.as_mut_ptr(), pwszProvName: ptr::null_mut(), dwProvType: PROV_RSA_FULL, dwFlags: CRYPT_MACHINE_KEYSET, cProvParam: 0, rgProvParam: ptr::null_mut(), dwKeySpec: AT_SIGNATURE, }; let mut sig_algorithm = CRYPT_ALGORITHM_IDENTIFIER { pszObjId: szOID_RSA_SHA256RSA.as_ptr() as *mut _, Parameters: mem::zeroed(), }; let mut expiration_date: SYSTEMTIME = mem::zeroed(); GetSystemTime(&mut expiration_date); let mut file_time: FILETIME = mem::zeroed(); let res = SystemTimeToFileTime(&mut expiration_date, &mut file_time); if res != TRUE { return Err(Error::last_os_error()); } let mut timestamp: u64 = file_time.dwLowDateTime as u64 | (file_time.dwHighDateTime as u64) << 32; // one day, timestamp unit is in 100 nanosecond intervals timestamp += (1E9 as u64) / 100 * (60 * 60 * 24); file_time.dwLowDateTime = timestamp as u32; file_time.dwHighDateTime = (timestamp >> 32) as u32; let res = FileTimeToSystemTime(&file_time, &mut expiration_date); if res != TRUE { return Err(Error::last_os_error()); } // create a self signed certificate let cert_context = CertCreateSelfSignCertificate( 0 as ULONG_PTR, &mut subject_issuer, 0, &mut key_provider, &mut sig_algorithm, ptr::null_mut(), &mut expiration_date, ptr::null_mut()); if cert_context.is_null() { return Err(Error::last_os_error()); } // TODO: this is.. a terrible hack. Right now `schannel` // doesn't provide a public method to go from a raw // cert context pointer to the `CertContext` structure it // has, so we just fake it here with a transmute. This'll // probably break at some point, but hopefully by then // it'll have a method to do this! struct MyCertContext(T); impl Drop for MyCertContext { fn drop(&mut self) {} } let cert_context = MyCertContext(cert_context); let cert_context: CertContext = mem::transmute(cert_context); cert_context.set_friendly_name(FRIENDLY_NAME)?; // install the certificate to the machine's local store io::stdout().write_all(br#" The async-native-tls test suite is about to add a certificate to your set of root and trusted certificates. This certificate should be for the domain "localhost" with the description related to "async-native-tls". This certificate is only valid for one day and will be automatically deleted if you re-run the async-native-tls test suite later. "#).unwrap(); local_root_store().add_cert(&cert_context, CertAdd::ReplaceExisting)?; Ok(cert_context) } } } } const AMT: usize = 128 * 1024; async fn copy_data(mut w: W) -> Result { let mut data = vec![9; AMT as usize]; let mut amt = 0; while !data.is_empty() { let written = w.write(&data).await?; if written <= data.len() { amt += written; data.resize(data.len() - written, 0); } else { w.write_all(&data).await?; amt += data.len(); break; } println!("remaining: {}", data.len()); } Ok(amt) } #[async_std::test] async fn client_to_server() { drop(env_logger::try_init()); // Create a server listening on a port, then figure out what that port is let srv = t!(TcpListener::bind("127.0.0.1:0").await); let addr = t!(srv.local_addr()); let (server_cx, client_cx) = contexts(); // Create a future to accept one socket, connect the ssl stream, and then // read all the data from it. let server = async move { let mut incoming = srv.incoming(); let socket = t!(incoming.next().await.unwrap()); let mut socket = t!(server_cx.accept(socket).await); let mut data = Vec::new(); t!(socket.read_to_end(&mut data).await); data }; // Create a future to connect to our server, connect the ssl stream, and // then write a bunch of data to it. let client = async move { let socket = t!(TcpStream::connect(&addr).await); let socket = t!(client_cx.connect("localhost", socket).await); copy_data(socket).await }; // Finally, run everything! let (data, _) = join!(server, client); // assert_eq!(amt, AMT); assert!(data == vec![9; AMT]); } #[async_std::test] async fn server_to_client() { drop(env_logger::try_init()); // Create a server listening on a port, then figure out what that port is let srv = t!(TcpListener::bind("127.0.0.1:0").await); let addr = t!(srv.local_addr()); let (server_cx, client_cx) = contexts(); let server = async move { let mut incoming = srv.incoming(); let socket = t!(incoming.next().await.unwrap()); let socket = t!(server_cx.accept(socket).await); copy_data(socket).await }; let client = async move { let socket = t!(TcpStream::connect(&addr).await); let mut socket = t!(client_cx.connect("localhost", socket).await); let mut data = Vec::new(); t!(socket.read_to_end(&mut data).await); data }; // Finally, run everything! let (_, data) = join!(server, client); // assert_eq!(amt, AMT); assert!(data == vec![9; AMT]); } #[async_std::test] async fn one_byte_at_a_time() { const AMT: usize = 1024; drop(env_logger::try_init()); let srv = t!(TcpListener::bind("127.0.0.1:0").await); let addr = t!(srv.local_addr()); let (server_cx, client_cx) = contexts(); let server = async move { let mut incoming = srv.incoming(); let socket = t!(incoming.next().await.unwrap()); let mut socket = t!(server_cx.accept(socket).await); let mut amt = 0; for b in std::iter::repeat(9).take(AMT) { let data = [b as u8]; t!(socket.write_all(&data).await); amt += 1; } amt }; let client = async move { let socket = t!(TcpStream::connect(&addr).await); let mut socket = t!(client_cx.connect("localhost", socket).await); let mut data = Vec::new(); loop { let mut buf = [0; 1]; match socket.read_exact(&mut buf).await { Ok(_) => data.extend_from_slice(&buf), Err(ref err) if err.kind() == std::io::ErrorKind::UnexpectedEof => break, Err(err) => panic!("{}", err), } } data }; let (amt, data) = join!(server, client); assert_eq!(amt, AMT); assert!(data == vec![9; AMT as usize]); }