├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── high_level.rs ├── high_level_hyper.rs ├── high_level_tokio.rs ├── high_level_warp.rs ├── low_level.rs ├── low_level_axum.rs ├── low_level_axum_http01.rs └── low_level_tokio.rs ├── rustfmt.toml └── src ├── acceptor.rs ├── acme.rs ├── axum.rs ├── cache.rs ├── caches ├── boxed.rs ├── composite.rs ├── dir.rs ├── mod.rs ├── no.rs └── test.rs ├── config.rs ├── helpers.rs ├── https_helper.rs ├── incoming.rs ├── jose.rs ├── lib.rs ├── resolver.rs ├── state.rs ├── tokio.rs └── tower.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Cargo Build & Test 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build_and_test: 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | toolchain: ["stable", "beta", "nightly"] 18 | crypto: ["ring", "aws-lc-rs", "ring,aws-lc-rs"] 19 | tokio: ["tokio", "axum", "tower", ""] 20 | steps: 21 | - uses: actions/checkout@v3 22 | - run: rustup update ${{ matrix.toolchain }} && rustup default ${{ matrix.toolchain }} 23 | - run: rustup component add clippy 24 | - run: rustup component add rustfmt 25 | - run: cargo fmt --check 26 | - run: cargo build --verbose --no-default-features --features ${{ matrix.crypto }},${{ matrix.tokio }} 27 | - run: cargo test --verbose --no-default-features --features ${{ matrix.crypto }},${{ matrix.tokio }} 28 | - run: cargo clippy --tests --no-default-features --features ${{ matrix.crypto }},${{ matrix.tokio }} 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /Cargo.lock 2 | /target 3 | /.idea 4 | /cache 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustls-acme" 3 | version = "0.13.0" 4 | authors = ["Florian Uekermann "] 5 | edition = "2018" 6 | description = "TLS certificate management and serving using rustls" 7 | license = "Apache-2.0 OR MIT" 8 | repository = "https://github.com/FlorianUekermann/rustls-acme" 9 | documentation = "https://docs.rs/rustls-acme" 10 | keywords = ["acme", "rustls", "tls", "letsencrypt"] 11 | categories = ["asynchronous", "cryptography", "network-programming"] 12 | 13 | [dependencies] 14 | futures-rustls = { version = "0.26", default-features = false } 15 | futures = "0.3.21" 16 | rcgen = { version = "0.13", default-features = false, features = ["pem"] } 17 | serde_json = "1.0.81" 18 | serde = { version = "1.0.137", features=["derive"] } 19 | ring = { version = "0.17.7", features = ["std"], optional = true } 20 | aws-lc-rs = { version = "1.5.2", optional = true, default-features = false, features = ["aws-lc-sys"] } 21 | base64 = "0.22" 22 | log = "0.4.17" 23 | webpki-roots = "0.26" 24 | pem = "3.0.3" 25 | thiserror = "2" 26 | x509-parser = "0.16" 27 | chrono = { version = "0.4.24", default-features = false, features = ["clock"] } 28 | async-trait = "0.1.53" 29 | async-io = "2.3.0" 30 | tokio = { version= "1.20.1", optional= true } 31 | tokio-util = { version="0.7.3", features = ["compat"], optional=true } 32 | axum-server = { version = "0.7", features = ["tls-rustls-no-provider"], optional=true } 33 | async-web-client = { version = "0.6.2", default-features = false } 34 | http = "1" 35 | blocking = "1.4.1" 36 | tower-service = { version = "0.3.3", optional=true } 37 | 38 | [dev-dependencies] 39 | simple_logger = "4.3.3" 40 | clap = { version = "3.1.18", features = ["derive"] } 41 | axum = "0.8" 42 | tokio = { version="1.35.1", features = ["full"] } 43 | tokio-stream = { version="0.1.14", features = ["net"] } 44 | tokio-util = { version="0.7.10", features = ["compat"] } 45 | warp = "0.3.7" 46 | smol = "2.0.0" 47 | tokio-rustls = { version = "0.26", default-features = false } 48 | smol-macros = "0.1.0" 49 | macro_rules_attribute = "0.2.0" 50 | hyper = "1.3.1" 51 | http-body-util = "0.1.1" 52 | bytes = "1.6.0" 53 | hyper-util = "0.1.3" 54 | 55 | [package.metadata.docs.rs] 56 | all-features = true 57 | rustdoc-args = ["--cfg", "doc_auto_cfg"] 58 | 59 | [features] 60 | default = ["aws-lc-rs", "tls12"] 61 | ring = ["dep:ring", "async-web-client/ring", "rcgen/ring"] 62 | aws-lc-rs = ["dep:aws-lc-rs", "async-web-client/aws-lc-rs", "rcgen/aws_lc_rs"] 63 | axum = ["dep:axum-server", "tower"] 64 | tower = ["dep:tower-service", "tokio"] 65 | tokio = ["dep:tokio", "dep:tokio-util"] 66 | tls12 = ["async-web-client/tls12"] 67 | 68 | [[example]] 69 | name = "low_level_axum" 70 | required-features = ["axum"] 71 | 72 | [[example]] 73 | name = "low_level_axum_http01" 74 | required-features = ["axum", "tower"] 75 | 76 | [[example]] 77 | name="high_level_warp" 78 | required-features=["tokio"] 79 | 80 | [[example]] 81 | name="high_level_tokio" 82 | required-features=["tokio"] 83 | 84 | [[example]] 85 | name="high_level_hyper" 86 | required-features=["tokio"] 87 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Documentation](https://docs.rs/rustls-acme/badge.svg)](https://docs.rs/rustls-acme/) 2 | 3 | TLS certificate management and serving using rustls 4 | 5 | ## License 6 | 7 | Licensed under either of 8 | 9 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 10 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 11 | 12 | at your option. 13 | 14 | #### Contribution 15 | 16 | Unless you explicitly state otherwise, any contribution intentionally submitted 17 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 18 | dual licensed as above, without any additional terms or conditions. 19 | -------------------------------------------------------------------------------- /examples/high_level.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use futures::AsyncWriteExt; 3 | use futures::StreamExt; 4 | use rustls_acme::caches::DirCache; 5 | use rustls_acme::AcmeConfig; 6 | use smol::net::TcpListener; 7 | use smol::spawn; 8 | use std::net::Ipv6Addr; 9 | use std::path::PathBuf; 10 | 11 | #[derive(Parser, Debug)] 12 | struct Args { 13 | /// Domains 14 | #[clap(short, required = true)] 15 | domains: Vec, 16 | 17 | /// Contact info 18 | #[clap(short)] 19 | email: Vec, 20 | 21 | /// Cache directory 22 | #[clap(short, parse(from_os_str))] 23 | cache: Option, 24 | 25 | /// Use Let's Encrypt production environment 26 | /// (see https://letsencrypt.org/docs/staging-environment/) 27 | #[clap(long)] 28 | prod: bool, 29 | 30 | #[clap(short, long, default_value = "443")] 31 | port: u16, 32 | } 33 | 34 | #[macro_rules_attribute::apply(smol_macros::main!)] 35 | async fn main() { 36 | simple_logger::init_with_level(log::Level::Info).unwrap(); 37 | let args = Args::parse(); 38 | 39 | let tcp_listener = TcpListener::bind((Ipv6Addr::UNSPECIFIED, args.port)).await.unwrap(); 40 | 41 | let mut tls_incoming = AcmeConfig::new(args.domains) 42 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 43 | .cache_option(args.cache.clone().map(DirCache::new)) 44 | .directory_lets_encrypt(args.prod) 45 | .incoming(tcp_listener.incoming(), Vec::new()); 46 | 47 | while let Some(tls) = tls_incoming.next().await { 48 | let mut tls = tls.unwrap(); 49 | spawn(async move { 50 | tls.write_all(HELLO).await.unwrap(); 51 | tls.close().await.unwrap(); 52 | }) 53 | .detach() 54 | } 55 | unreachable!() 56 | } 57 | 58 | const HELLO: &'static [u8] = br#"HTTP/1.1 200 OK 59 | Content-Length: 10 60 | Content-Type: text/plain; charset=utf-8 61 | 62 | Hello Tls!"#; 63 | -------------------------------------------------------------------------------- /examples/high_level_hyper.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use rustls_acme::caches::DirCache; 3 | use rustls_acme::AcmeConfig; 4 | use std::net::Ipv6Addr; 5 | use std::path::PathBuf; 6 | use tokio_stream::wrappers::TcpListenerStream; 7 | use tokio_stream::StreamExt; 8 | 9 | #[derive(Parser, Debug)] 10 | struct Args { 11 | /// Domains 12 | #[clap(short, required = true)] 13 | domains: Vec, 14 | 15 | /// Contact info 16 | #[clap(short)] 17 | email: Vec, 18 | 19 | /// Cache directory 20 | #[clap(short, parse(from_os_str))] 21 | cache: Option, 22 | 23 | /// Use Let's Encrypt production environment 24 | /// (see https://letsencrypt.org/docs/staging-environment/) 25 | #[clap(long)] 26 | prod: bool, 27 | 28 | #[clap(short, long, default_value = "443")] 29 | port: u16, 30 | } 31 | 32 | #[tokio::main] 33 | async fn main() { 34 | simple_logger::init_with_level(log::Level::Info).unwrap(); 35 | let args = Args::parse(); 36 | 37 | let tcp_listener = tokio::net::TcpListener::bind((Ipv6Addr::UNSPECIFIED, args.port)).await.unwrap(); 38 | let tcp_incoming = TcpListenerStream::new(tcp_listener); 39 | 40 | let mut tls_incoming = AcmeConfig::new(args.domains) 41 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 42 | .cache_option(args.cache.clone().map(DirCache::new)) 43 | .directory_lets_encrypt(args.prod) 44 | .tokio_incoming(tcp_incoming, Vec::new()); 45 | 46 | while let Some(tls) = tls_incoming.next().await { 47 | let tls = tls.unwrap(); 48 | tokio::spawn(async move { 49 | use hyper::{server::conn::http1, service::service_fn}; 50 | use hyper_util::rt::TokioIo; 51 | let tls = TokioIo::new(tls); 52 | if let Err(err) = http1::Builder::new().serve_connection(tls, service_fn(hello)).await { 53 | eprintln!("Error serving connection: {:?}", err); 54 | } 55 | }); 56 | } 57 | unreachable!() 58 | } 59 | 60 | use bytes::Bytes; 61 | use http_body_util::Full; 62 | use hyper::{Request, Response}; 63 | use std::convert::Infallible; 64 | 65 | async fn hello(_: Request) -> Result>, Infallible> { 66 | Ok(Response::new(Full::new(Bytes::from("Hello Tls!")))) 67 | } 68 | -------------------------------------------------------------------------------- /examples/high_level_tokio.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use rustls_acme::caches::DirCache; 3 | use rustls_acme::AcmeConfig; 4 | use std::net::Ipv6Addr; 5 | use std::path::PathBuf; 6 | use tokio::io::AsyncWriteExt; 7 | use tokio_stream::wrappers::TcpListenerStream; 8 | use tokio_stream::StreamExt; 9 | 10 | #[derive(Parser, Debug)] 11 | struct Args { 12 | /// Domains 13 | #[clap(short, required = true)] 14 | domains: Vec, 15 | 16 | /// Contact info 17 | #[clap(short)] 18 | email: Vec, 19 | 20 | /// Cache directory 21 | #[clap(short, parse(from_os_str))] 22 | cache: Option, 23 | 24 | /// Use Let's Encrypt production environment 25 | /// (see https://letsencrypt.org/docs/staging-environment/) 26 | #[clap(long)] 27 | prod: bool, 28 | 29 | #[clap(short, long, default_value = "443")] 30 | port: u16, 31 | } 32 | 33 | #[tokio::main] 34 | async fn main() { 35 | simple_logger::init_with_level(log::Level::Info).unwrap(); 36 | let args = Args::parse(); 37 | 38 | let tcp_listener = tokio::net::TcpListener::bind((Ipv6Addr::UNSPECIFIED, args.port)).await.unwrap(); 39 | let tcp_incoming = TcpListenerStream::new(tcp_listener); 40 | 41 | let mut tls_incoming = AcmeConfig::new(args.domains) 42 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 43 | .cache_option(args.cache.clone().map(DirCache::new)) 44 | .directory_lets_encrypt(args.prod) 45 | .tokio_incoming(tcp_incoming, Vec::new()); 46 | 47 | while let Some(tls) = tls_incoming.next().await { 48 | let mut tls = tls.unwrap(); 49 | tokio::spawn(async move { 50 | tls.write_all(HELLO).await.unwrap(); 51 | tls.shutdown().await.unwrap(); 52 | }); 53 | } 54 | unreachable!() 55 | } 56 | 57 | const HELLO: &'static [u8] = br#"HTTP/1.1 200 OK 58 | Content-Length: 10 59 | Content-Type: text/plain; charset=utf-8 60 | 61 | Hello Tls!"#; 62 | -------------------------------------------------------------------------------- /examples/high_level_warp.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use rustls_acme::caches::DirCache; 3 | use rustls_acme::AcmeConfig; 4 | use std::net::Ipv6Addr; 5 | use std::path::PathBuf; 6 | use tokio_stream::wrappers::TcpListenerStream; 7 | use warp::Filter; 8 | 9 | #[derive(Parser, Debug)] 10 | struct Args { 11 | /// Domains 12 | #[clap(short, required = true)] 13 | domains: Vec, 14 | 15 | /// Contact info 16 | #[clap(short)] 17 | email: Vec, 18 | 19 | /// Cache directory 20 | #[clap(short, parse(from_os_str))] 21 | cache: Option, 22 | 23 | /// Use Let's Encrypt production environment 24 | /// (see https://letsencrypt.org/docs/staging-environment/) 25 | #[clap(long)] 26 | prod: bool, 27 | 28 | #[clap(short, long, default_value = "443")] 29 | port: u16, 30 | } 31 | 32 | #[tokio::main] 33 | async fn main() { 34 | simple_logger::init_with_level(log::Level::Info).unwrap(); 35 | let args = Args::parse(); 36 | 37 | let tcp_listener = tokio::net::TcpListener::bind((Ipv6Addr::UNSPECIFIED, args.port)).await.unwrap(); 38 | let tcp_incoming = TcpListenerStream::new(tcp_listener); 39 | 40 | let tls_incoming = AcmeConfig::new(args.domains) 41 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 42 | .cache_option(args.cache.clone().map(DirCache::new)) 43 | .directory_lets_encrypt(args.prod) 44 | .tokio_incoming(tcp_incoming, Vec::new()); 45 | 46 | let route = warp::any().map(|| "Hello Tls!"); 47 | warp::serve(route).run_incoming(tls_incoming).await; 48 | 49 | unreachable!() 50 | } 51 | -------------------------------------------------------------------------------- /examples/low_level.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use futures::AsyncWriteExt; 3 | use futures::StreamExt; 4 | use rustls_acme::caches::DirCache; 5 | use rustls_acme::futures_rustls::LazyConfigAcceptor; 6 | use rustls_acme::is_tls_alpn_challenge; 7 | use rustls_acme::AcmeConfig; 8 | use smol::net::TcpListener; 9 | use smol::spawn; 10 | use std::net::Ipv6Addr; 11 | use std::path::PathBuf; 12 | 13 | #[derive(Parser, Debug)] 14 | struct Args { 15 | /// Domains 16 | #[clap(short, required = true)] 17 | domains: Vec, 18 | 19 | /// Contact info 20 | #[clap(short)] 21 | email: Vec, 22 | 23 | /// Cache directory 24 | #[clap(short, parse(from_os_str))] 25 | cache: Option, 26 | 27 | /// Use Let's Encrypt production environment 28 | /// (see https://letsencrypt.org/docs/staging-environment/) 29 | #[clap(long)] 30 | prod: bool, 31 | 32 | #[clap(short, long, default_value = "443")] 33 | port: u16, 34 | } 35 | 36 | #[macro_rules_attribute::apply(smol_macros::main!)] 37 | async fn main() { 38 | simple_logger::init_with_level(log::Level::Info).unwrap(); 39 | let args = Args::parse(); 40 | 41 | let mut state = AcmeConfig::new(args.domains) 42 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 43 | .cache_option(args.cache.clone().map(DirCache::new)) 44 | .directory_lets_encrypt(args.prod) 45 | .state(); 46 | let challenge_rustls_config = state.challenge_rustls_config(); 47 | let default_rustls_config = state.default_rustls_config(); 48 | 49 | spawn(async move { 50 | loop { 51 | match state.next().await.unwrap() { 52 | Ok(ok) => log::info!("event: {:?}", ok), 53 | Err(err) => log::error!("error: {:?}", err), 54 | } 55 | } 56 | }) 57 | .detach(); 58 | 59 | let listener = TcpListener::bind((Ipv6Addr::UNSPECIFIED, args.port)).await.unwrap(); 60 | while let Some(tcp) = listener.incoming().next().await { 61 | let challenge_rustls_config = challenge_rustls_config.clone(); 62 | let default_rustls_config = default_rustls_config.clone(); 63 | 64 | spawn(async move { 65 | let start_handshake = LazyConfigAcceptor::new(Default::default(), tcp.unwrap()).await.unwrap(); 66 | 67 | if is_tls_alpn_challenge(&start_handshake.client_hello()) { 68 | log::info!("received TLS-ALPN-01 validation request"); 69 | let mut tls = start_handshake.into_stream(challenge_rustls_config).await.unwrap(); 70 | tls.close().await.unwrap(); 71 | } else { 72 | let mut tls = start_handshake.into_stream(default_rustls_config).await.unwrap(); 73 | tls.write_all(HELLO).await.unwrap(); 74 | tls.close().await.unwrap(); 75 | } 76 | }) 77 | .detach(); 78 | } 79 | } 80 | 81 | const HELLO: &'static [u8] = br#"HTTP/1.1 200 OK 82 | Content-Length: 10 83 | Content-Type: text/plain; charset=utf-8 84 | 85 | Hello Tls!"#; 86 | -------------------------------------------------------------------------------- /examples/low_level_axum.rs: -------------------------------------------------------------------------------- 1 | use axum::{routing::get, Router}; 2 | use clap::Parser; 3 | use rustls_acme::caches::DirCache; 4 | use rustls_acme::AcmeConfig; 5 | use std::net::{Ipv6Addr, SocketAddr}; 6 | use std::path::PathBuf; 7 | use tokio_stream::StreamExt; 8 | 9 | #[derive(Parser, Debug)] 10 | struct Args { 11 | /// Domains 12 | #[clap(short, required = true)] 13 | domains: Vec, 14 | 15 | /// Contact info 16 | #[clap(short)] 17 | email: Vec, 18 | 19 | /// Cache directory 20 | #[clap(short, parse(from_os_str))] 21 | cache: Option, 22 | 23 | /// Use Let's Encrypt production environment 24 | /// (see https://letsencrypt.org/docs/staging-environment/) 25 | #[clap(long)] 26 | prod: bool, 27 | 28 | #[clap(short, long, default_value = "443")] 29 | port: u16, 30 | } 31 | 32 | #[tokio::main] 33 | async fn main() { 34 | simple_logger::init_with_level(log::Level::Info).unwrap(); 35 | let args = Args::parse(); 36 | 37 | let mut state = AcmeConfig::new(args.domains) 38 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 39 | .cache_option(args.cache.clone().map(DirCache::new)) 40 | .directory_lets_encrypt(args.prod) 41 | .state(); 42 | let acceptor = state.axum_acceptor(state.default_rustls_config()); 43 | 44 | tokio::spawn(async move { 45 | loop { 46 | match state.next().await.unwrap() { 47 | Ok(ok) => log::info!("event: {:?}", ok), 48 | Err(err) => log::error!("error: {:?}", err), 49 | } 50 | } 51 | }); 52 | 53 | let app = Router::new().route("/", get(|| async { "Hello Tls!" })); 54 | 55 | let addr = SocketAddr::from((Ipv6Addr::UNSPECIFIED, args.port)); 56 | axum_server::bind(addr).acceptor(acceptor).serve(app.into_make_service()).await.unwrap(); 57 | } 58 | -------------------------------------------------------------------------------- /examples/low_level_axum_http01.rs: -------------------------------------------------------------------------------- 1 | use axum::extract::State; 2 | use axum::{routing::get, Router}; 3 | use axum_server::bind; 4 | use clap::Parser; 5 | use rustls_acme::caches::DirCache; 6 | use rustls_acme::tower::TowerHttp01ChallengeService; 7 | use rustls_acme::AcmeConfig; 8 | use rustls_acme::UseChallenge::Http01; 9 | use std::net::{Ipv6Addr, SocketAddr}; 10 | use std::path::PathBuf; 11 | use tokio::try_join; 12 | use tokio_stream::StreamExt; 13 | 14 | #[derive(Parser, Debug)] 15 | struct Args { 16 | /// Domains 17 | #[clap(short, required = true)] 18 | domains: Vec, 19 | 20 | /// Contact info 21 | #[clap(short)] 22 | email: Vec, 23 | 24 | /// Cache directory 25 | #[clap(short, parse(from_os_str))] 26 | cache: Option, 27 | 28 | /// Use Let's Encrypt production environment 29 | /// (see https://letsencrypt.org/docs/staging-environment/) 30 | #[clap(long)] 31 | prod: bool, 32 | 33 | #[clap(long, default_value = "443")] 34 | https_port: u16, 35 | 36 | #[clap(long, default_value = "80")] 37 | http_port: u16, 38 | } 39 | 40 | #[tokio::main] 41 | async fn main() { 42 | simple_logger::init_with_level(log::Level::Info).unwrap(); 43 | let args = Args::parse(); 44 | 45 | let mut state = AcmeConfig::new(args.domains) 46 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 47 | .cache_option(args.cache.clone().map(DirCache::new)) 48 | .directory_lets_encrypt(args.prod) 49 | .challenge_type(Http01) 50 | .state(); 51 | let acceptor = state.axum_acceptor(state.default_rustls_config()); 52 | let acme_challenge_tower_service: TowerHttp01ChallengeService = state.http01_challenge_tower_service(); 53 | 54 | tokio::spawn(async move { 55 | loop { 56 | match state.next().await.unwrap() { 57 | Ok(ok) => log::info!("event: {:?}", ok), 58 | Err(err) => log::error!("error: {:?}", err), 59 | } 60 | } 61 | }); 62 | 63 | let http_addr = SocketAddr::from((Ipv6Addr::UNSPECIFIED, args.http_port)); 64 | let https_addr = SocketAddr::from((Ipv6Addr::UNSPECIFIED, args.https_port)); 65 | 66 | let app = Router::new() 67 | .route("/", get(move |State(t): State<&'static str>| async move { format!("Hello {t}!") })) 68 | .route_service("/.well-known/acme-challenge/{challenge_token}", acme_challenge_tower_service); 69 | 70 | let http_future = bind(http_addr).serve(app.clone().with_state("Tcp").into_make_service()); 71 | let https_future = bind(https_addr).acceptor(acceptor).serve(app.with_state("Tls").into_make_service()); 72 | try_join!(https_future, http_future).unwrap(); 73 | } 74 | -------------------------------------------------------------------------------- /examples/low_level_tokio.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use rustls_acme::caches::DirCache; 3 | use rustls_acme::{is_tls_alpn_challenge, AcmeConfig}; 4 | use std::net::Ipv6Addr; 5 | use std::path::PathBuf; 6 | use tokio::io::AsyncWriteExt; 7 | use tokio_rustls::LazyConfigAcceptor; 8 | use tokio_stream::StreamExt; 9 | 10 | #[derive(Parser, Debug)] 11 | struct Args { 12 | /// Domains 13 | #[clap(short, required = true)] 14 | domains: Vec, 15 | 16 | /// Contact info 17 | #[clap(short)] 18 | email: Vec, 19 | 20 | /// Cache directory 21 | #[clap(short, parse(from_os_str))] 22 | cache: Option, 23 | 24 | /// Use Let's Encrypt production environment 25 | /// (see https://letsencrypt.org/docs/staging-environment/) 26 | #[clap(long)] 27 | prod: bool, 28 | 29 | #[clap(short, long, default_value = "443")] 30 | port: u16, 31 | } 32 | 33 | #[tokio::main] 34 | async fn main() { 35 | simple_logger::init_with_level(log::Level::Info).unwrap(); 36 | let args = Args::parse(); 37 | 38 | let mut state = AcmeConfig::new(args.domains) 39 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 40 | .cache_option(args.cache.clone().map(DirCache::new)) 41 | .directory_lets_encrypt(args.prod) 42 | .state(); 43 | let challenge_rustls_config = state.challenge_rustls_config(); 44 | let default_rustls_config = state.default_rustls_config(); 45 | 46 | tokio::spawn(async move { 47 | loop { 48 | match state.next().await.unwrap() { 49 | Ok(ok) => log::info!("event: {:?}", ok), 50 | Err(err) => log::error!("error: {:?}", err), 51 | } 52 | } 53 | }); 54 | 55 | let listener = tokio::net::TcpListener::bind((Ipv6Addr::UNSPECIFIED, args.port)).await.unwrap(); 56 | loop { 57 | let (tcp, _) = listener.accept().await.unwrap(); 58 | let challenge_rustls_config = challenge_rustls_config.clone(); 59 | let default_rustls_config = default_rustls_config.clone(); 60 | 61 | tokio::spawn(async move { 62 | let start_handshake = LazyConfigAcceptor::new(Default::default(), tcp).await.unwrap(); 63 | 64 | if is_tls_alpn_challenge(&start_handshake.client_hello()) { 65 | log::info!("received TLS-ALPN-01 validation request"); 66 | let mut tls = start_handshake.into_stream(challenge_rustls_config).await.unwrap(); 67 | tls.shutdown().await.unwrap(); 68 | } else { 69 | let mut tls = start_handshake.into_stream(default_rustls_config).await.unwrap(); 70 | tls.write_all(HELLO).await.unwrap(); 71 | tls.shutdown().await.unwrap(); 72 | } 73 | }); 74 | } 75 | } 76 | 77 | const HELLO: &'static [u8] = br#"HTTP/1.1 200 OK 78 | Content-Length: 10 79 | Content-Type: text/plain; charset=utf-8 80 | 81 | Hello Tls!"#; 82 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 150 2 | -------------------------------------------------------------------------------- /src/acceptor.rs: -------------------------------------------------------------------------------- 1 | use crate::acme::ACME_TLS_ALPN_NAME; 2 | use crate::{crypto_provider, is_tls_alpn_challenge, ResolvesServerCertAcme}; 3 | use core::fmt; 4 | use futures::prelude::*; 5 | use futures_rustls::rustls::server::Acceptor; 6 | use futures_rustls::rustls::ServerConfig; 7 | use futures_rustls::{Accept, LazyConfigAcceptor, StartHandshake}; 8 | use std::io; 9 | use std::pin::Pin; 10 | use std::sync::Arc; 11 | use std::task::{Context, Poll}; 12 | 13 | #[derive(Clone)] 14 | pub struct AcmeAcceptor { 15 | config: Arc, 16 | } 17 | 18 | impl AcmeAcceptor { 19 | #[cfg(any(feature = "ring", feature = "aws-lc-rs"))] 20 | #[deprecated(note = "please use high-level API via `AcmeState::incoming()` instead or refer to updated low-level API examples")] 21 | pub(crate) fn new(resolver: Arc) -> Self { 22 | let mut config = ServerConfig::builder_with_provider(crypto_provider().into()) 23 | .with_safe_default_protocol_versions() 24 | .unwrap() 25 | .with_no_client_auth() 26 | .with_cert_resolver(resolver.clone()); 27 | config.alpn_protocols.push(ACME_TLS_ALPN_NAME.to_vec()); 28 | Self { config: Arc::new(config) } 29 | } 30 | pub fn accept(&self, io: IO) -> AcmeAccept { 31 | AcmeAccept::new(io, self.config.clone()) 32 | } 33 | } 34 | 35 | impl fmt::Debug for AcmeAcceptor { 36 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 37 | f.debug_struct("AcmeAcceptor").finish_non_exhaustive() 38 | } 39 | } 40 | 41 | pub struct AcmeAccept { 42 | acceptor: LazyConfigAcceptor, 43 | config: Arc, 44 | validation_accept: Option>, 45 | } 46 | 47 | impl AcmeAccept { 48 | pub(crate) fn new(io: IO, config: Arc) -> Self { 49 | Self { 50 | acceptor: LazyConfigAcceptor::new(Acceptor::default(), io), 51 | config, 52 | validation_accept: None, 53 | } 54 | } 55 | } 56 | 57 | impl Future for AcmeAccept { 58 | type Output = io::Result>>; 59 | 60 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 61 | loop { 62 | if let Some(validation_accept) = &mut self.validation_accept { 63 | return match Pin::new(validation_accept).poll(cx) { 64 | Poll::Ready(Ok(_)) => Poll::Ready(Ok(None)), 65 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 66 | Poll::Pending => Poll::Pending, 67 | }; 68 | } 69 | 70 | return match Pin::new(&mut self.acceptor).poll(cx) { 71 | Poll::Ready(Ok(handshake)) => { 72 | if is_tls_alpn_challenge(&handshake.client_hello()) { 73 | self.validation_accept = Some(handshake.into_stream(self.config.clone())); 74 | continue; 75 | } 76 | Poll::Ready(Ok(Some(handshake))) 77 | } 78 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 79 | Poll::Pending => Poll::Pending, 80 | }; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/acme.rs: -------------------------------------------------------------------------------- 1 | use crate::any_ecdsa_type; 2 | use crate::crypto::error::{KeyRejected, Unspecified}; 3 | use crate::crypto::rand::SystemRandom; 4 | use crate::crypto::signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, ECDSA_P256_SHA256_FIXED_SIGNING}; 5 | use crate::https_helper::{https, HttpsRequestError}; 6 | use crate::jose::{key_authorization, key_authorization_sha256, sign, JoseError}; 7 | use base64::prelude::*; 8 | use futures_rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; 9 | use futures_rustls::rustls::{sign::CertifiedKey, ClientConfig}; 10 | use http::header::ToStrError; 11 | use http::{Method, Response}; 12 | use rcgen::{CustomExtension, KeyPair, PKCS_ECDSA_P256_SHA256}; 13 | use serde::{Deserialize, Serialize}; 14 | use serde_json::json; 15 | use std::sync::Arc; 16 | use thiserror::Error; 17 | 18 | pub const LETS_ENCRYPT_STAGING_DIRECTORY: &str = "https://acme-staging-v02.api.letsencrypt.org/directory"; 19 | pub const LETS_ENCRYPT_PRODUCTION_DIRECTORY: &str = "https://acme-v02.api.letsencrypt.org/directory"; 20 | pub const ACME_TLS_ALPN_NAME: &[u8] = b"acme-tls/1"; 21 | 22 | #[derive(Debug)] 23 | pub struct Account { 24 | pub key_pair: EcdsaKeyPair, 25 | pub directory: Directory, 26 | pub kid: String, 27 | } 28 | 29 | static ALG: &EcdsaSigningAlgorithm = &ECDSA_P256_SHA256_FIXED_SIGNING; 30 | 31 | impl Account { 32 | pub fn generate_key_pair() -> Vec { 33 | let rng = SystemRandom::new(); 34 | let pkcs8 = EcdsaKeyPair::generate_pkcs8(ALG, &rng).unwrap(); 35 | pkcs8.as_ref().to_vec() 36 | } 37 | pub async fn create<'a, S, I>(client_config: &Arc, directory: Directory, contact: I) -> Result 38 | where 39 | S: AsRef + 'a, 40 | I: IntoIterator, 41 | { 42 | let key_pair = Self::generate_key_pair(); 43 | Self::create_with_keypair(client_config, directory, contact, &key_pair).await 44 | } 45 | pub async fn create_with_keypair<'a, S, I>( 46 | client_config: &Arc, 47 | directory: Directory, 48 | contact: I, 49 | key_pair: &[u8], 50 | ) -> Result 51 | where 52 | S: AsRef + 'a, 53 | I: IntoIterator, 54 | { 55 | let key_pair = EcdsaKeyPair::from_pkcs8( 56 | ALG, 57 | key_pair, 58 | // ring 0.17 has a third argument here; aws-lc-rs doesn't. 59 | #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] 60 | &SystemRandom::new(), 61 | )?; 62 | let contact: Vec<&'a str> = contact.into_iter().map(AsRef::::as_ref).collect(); 63 | let payload = json!({ 64 | "termsOfServiceAgreed": true, 65 | "contact": contact, 66 | }) 67 | .to_string(); 68 | let body = sign(&key_pair, None, directory.nonce(client_config).await?, &directory.new_account, &payload)?; 69 | let response = https(client_config, &directory.new_account, Method::POST, Some(body)).await?; 70 | let kid = get_header(&response, "Location")?; 71 | Ok(Account { key_pair, kid, directory }) 72 | } 73 | async fn request(&self, client_config: &Arc, url: impl AsRef, payload: &str) -> Result<(Option, String), AcmeError> { 74 | let body = sign( 75 | &self.key_pair, 76 | Some(&self.kid), 77 | self.directory.nonce(client_config).await?, 78 | url.as_ref(), 79 | payload, 80 | )?; 81 | let response = https(client_config, url.as_ref(), Method::POST, Some(body)).await?; 82 | let location = get_header(&response, "Location").ok(); 83 | let body = response.into_body(); 84 | log::debug!("response: {:?}", body); 85 | Ok((location, body)) 86 | } 87 | pub async fn new_order(&self, client_config: &Arc, domains: Vec) -> Result<(String, Order), AcmeError> { 88 | let domains: Vec = domains.into_iter().map(Identifier::Dns).collect(); 89 | let payload = format!("{{\"identifiers\":{}}}", serde_json::to_string(&domains)?); 90 | let response = self.request(client_config, &self.directory.new_order, &payload).await?; 91 | let url = response.0.ok_or(AcmeError::MissingHeader("Location"))?; 92 | let order = serde_json::from_str(&response.1)?; 93 | Ok((url, order)) 94 | } 95 | pub async fn auth(&self, client_config: &Arc, url: impl AsRef) -> Result { 96 | let payload = "".to_string(); 97 | let response = self.request(client_config, url, &payload).await?; 98 | Ok(serde_json::from_str(&response.1)?) 99 | } 100 | pub async fn challenge(&self, client_config: &Arc, url: impl AsRef) -> Result<(), AcmeError> { 101 | self.request(client_config, &url, "{}").await?; 102 | Ok(()) 103 | } 104 | pub async fn order(&self, client_config: &Arc, url: impl AsRef) -> Result { 105 | let response = self.request(client_config, &url, "").await?; 106 | Ok(serde_json::from_str(&response.1)?) 107 | } 108 | pub async fn finalize(&self, client_config: &Arc, url: impl AsRef, csr: &[u8]) -> Result { 109 | let payload = format!("{{\"csr\":\"{}\"}}", BASE64_URL_SAFE_NO_PAD.encode(csr)); 110 | let response = self.request(client_config, &url, &payload).await?; 111 | Ok(serde_json::from_str(&response.1)?) 112 | } 113 | pub async fn certificate(&self, client_config: &Arc, url: impl AsRef) -> Result { 114 | Ok(self.request(client_config, &url, "").await?.1) 115 | } 116 | pub fn tls_alpn_01<'a>(&self, challenges: &'a [Challenge], domain: String) -> Result<(&'a Challenge, CertifiedKey), AcmeError> { 117 | let challenge = challenges.iter().find(|c| c.typ == ChallengeType::TlsAlpn01); 118 | let challenge = match challenge { 119 | Some(challenge) => challenge, 120 | None => return Err(AcmeError::NoTlsAlpn01Challenge), 121 | }; 122 | let mut params = rcgen::CertificateParams::new(vec![domain])?; 123 | let key_auth = key_authorization_sha256(&self.key_pair, &challenge.token)?; 124 | params.custom_extensions = vec![CustomExtension::new_acme_identifier(key_auth.as_ref())]; 125 | let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; 126 | let cert = params.self_signed(&key_pair)?; 127 | 128 | let sk = any_ecdsa_type(&PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der()))).unwrap(); 129 | let certified_key = CertifiedKey::new(vec![cert.der().clone()], sk); 130 | Ok((challenge, certified_key)) 131 | } 132 | pub fn http_01<'a>(&self, challenges: &'a [Challenge]) -> Result<(&'a Challenge, String), AcmeError> { 133 | let challenge = challenges.iter().find(|c| c.typ == ChallengeType::Http01); 134 | let challenge = match challenge { 135 | Some(challenge) => challenge, 136 | None => return Err(AcmeError::NoHttp01Challenge), 137 | }; 138 | let key_auth = key_authorization(&self.key_pair, &challenge.token)?; 139 | Ok((challenge, key_auth)) 140 | } 141 | } 142 | 143 | #[derive(Debug, Clone, Deserialize)] 144 | #[serde(rename_all = "camelCase")] 145 | pub struct Directory { 146 | pub new_nonce: String, 147 | pub new_account: String, 148 | pub new_order: String, 149 | } 150 | 151 | impl Directory { 152 | pub async fn discover(client_config: &Arc, url: impl AsRef) -> Result { 153 | let body = https(client_config, url, Method::GET, None).await?.into_body(); 154 | Ok(serde_json::from_str(&body)?) 155 | } 156 | pub async fn nonce(&self, client_config: &Arc) -> Result { 157 | let response = &https(client_config, &self.new_nonce.as_str(), Method::HEAD, None).await?; 158 | get_header(response, "replay-nonce") 159 | } 160 | } 161 | 162 | #[derive(Debug, Deserialize, Eq, PartialEq)] 163 | pub enum ChallengeType { 164 | #[serde(rename = "http-01")] 165 | Http01, 166 | #[serde(rename = "dns-01")] 167 | Dns01, 168 | #[serde(rename = "tls-alpn-01")] 169 | TlsAlpn01, 170 | } 171 | 172 | #[derive(Debug, Deserialize)] 173 | #[serde(rename_all = "camelCase")] 174 | pub struct Order { 175 | #[serde(flatten)] 176 | pub status: OrderStatus, 177 | pub authorizations: Vec, 178 | pub finalize: String, 179 | pub error: Option, 180 | } 181 | 182 | #[derive(Debug, Deserialize, Clone, PartialEq, Eq)] 183 | #[serde(tag = "status", rename_all = "camelCase")] 184 | pub enum OrderStatus { 185 | Pending, 186 | Ready, 187 | Valid { certificate: String }, 188 | Invalid, 189 | Processing, 190 | } 191 | 192 | #[derive(Debug, Deserialize)] 193 | #[serde(rename_all = "camelCase")] 194 | pub struct Auth { 195 | pub status: AuthStatus, 196 | pub identifier: Identifier, 197 | pub challenges: Vec, 198 | } 199 | 200 | #[derive(Debug, Deserialize)] 201 | #[serde(rename_all = "camelCase")] 202 | pub enum AuthStatus { 203 | Pending, 204 | Valid, 205 | Invalid, 206 | Revoked, 207 | Expired, 208 | Deactivated, 209 | } 210 | 211 | #[derive(Clone, Debug, Serialize, Deserialize)] 212 | #[serde(tag = "type", content = "value", rename_all = "camelCase")] 213 | pub enum Identifier { 214 | Dns(String), 215 | } 216 | 217 | #[derive(Debug, Deserialize)] 218 | pub struct Challenge { 219 | #[serde(rename = "type")] 220 | pub typ: ChallengeType, 221 | pub url: String, 222 | pub token: String, 223 | pub error: Option, 224 | } 225 | 226 | #[derive(Clone, Debug, Serialize, Deserialize)] 227 | #[serde(rename_all = "camelCase")] 228 | pub struct Problem { 229 | #[serde(rename = "type")] 230 | pub typ: Option, 231 | pub detail: Option, 232 | } 233 | 234 | #[derive(Error, Debug)] 235 | pub enum AcmeError { 236 | #[error("io error: {0}")] 237 | Io(#[from] std::io::Error), 238 | #[error("certificate generation error: {0}")] 239 | Rcgen(#[from] rcgen::Error), 240 | #[error("JOSE error: {0}")] 241 | Jose(#[from] JoseError), 242 | #[error("JSON error: {0}")] 243 | Json(#[from] serde_json::Error), 244 | #[error("http request error: {0}")] 245 | HttpRequest(#[from] HttpsRequestError), 246 | #[error("non-string http response header: {0}")] 247 | HttpResponseNonStringHeader(#[from] ToStrError), 248 | #[error("invalid key pair: {0}")] 249 | KeyRejected(#[from] KeyRejected), 250 | #[error("crypto error: {0}")] 251 | Crypto(#[from] Unspecified), 252 | #[error("acme service response is missing {0} header")] 253 | MissingHeader(&'static str), 254 | #[error("no TLS-ALPN-01 challenge found")] 255 | NoTlsAlpn01Challenge, 256 | #[error("no HTTP-01 challenge found")] 257 | NoHttp01Challenge, 258 | } 259 | 260 | impl From for AcmeError { 261 | fn from(e: http::Error) -> Self { 262 | Self::HttpRequest(HttpsRequestError::from(e)) 263 | } 264 | } 265 | 266 | fn get_header(response: &Response, header: &'static str) -> Result { 267 | match response.headers().get_all(header).iter().last() { 268 | None => Err(AcmeError::MissingHeader(header)), 269 | Some(value) => Ok(value.to_str()?.to_string()), 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /src/axum.rs: -------------------------------------------------------------------------------- 1 | use crate::futures_rustls::rustls::ServerConfig; 2 | use crate::{AcmeAccept, AcmeAcceptor}; 3 | use futures::prelude::*; 4 | use futures_rustls::Accept; 5 | use std::io; 6 | use std::io::ErrorKind; 7 | use std::pin::Pin; 8 | use std::sync::Arc; 9 | use std::task::{Context, Poll}; 10 | use tokio::io::{AsyncRead, AsyncWrite}; 11 | use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt}; 12 | 13 | #[derive(Clone)] 14 | pub struct AxumAcceptor { 15 | acme_acceptor: AcmeAcceptor, 16 | config: Arc, 17 | } 18 | 19 | impl AxumAcceptor { 20 | pub fn new(acme_acceptor: AcmeAcceptor, config: Arc) -> Self { 21 | Self { acme_acceptor, config } 22 | } 23 | } 24 | 25 | impl axum_server::accept::Accept for AxumAcceptor { 26 | type Stream = Compat>>; 27 | type Service = S; 28 | type Future = AxumAccept; 29 | 30 | fn accept(&self, stream: I, service: S) -> Self::Future { 31 | let acme_accept = self.acme_acceptor.accept(stream.compat()); 32 | Self::Future { 33 | config: self.config.clone(), 34 | acme_accept, 35 | tls_accept: None, 36 | service: Some(service), 37 | } 38 | } 39 | } 40 | 41 | pub struct AxumAccept { 42 | config: Arc, 43 | acme_accept: AcmeAccept>, 44 | tls_accept: Option>>, 45 | service: Option, 46 | } 47 | 48 | impl Unpin for AxumAccept {} 49 | 50 | impl Future for AxumAccept { 51 | type Output = io::Result<(Compat>>, S)>; 52 | 53 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 54 | loop { 55 | if let Some(tls_accept) = &mut self.tls_accept { 56 | return match Pin::new(&mut *tls_accept).poll(cx) { 57 | Poll::Ready(Ok(tls)) => Poll::Ready(Ok((tls.compat(), self.service.take().unwrap()))), 58 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 59 | Poll::Pending => Poll::Pending, 60 | }; 61 | } 62 | return match Pin::new(&mut self.acme_accept).poll(cx) { 63 | Poll::Ready(Ok(Some(start_handshake))) => { 64 | let config = self.config.clone(); 65 | self.tls_accept = Some(start_handshake.into_stream(config)); 66 | continue; 67 | } 68 | Poll::Ready(Ok(None)) => Poll::Ready(Err(io::Error::new(ErrorKind::Other, "TLS-ALPN-01 validation request"))), 69 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 70 | Poll::Pending => Poll::Pending, 71 | }; 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/cache.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Debug; 2 | 3 | use async_trait::async_trait; 4 | 5 | pub trait Cache: CertCache + AccountCache {} 6 | 7 | impl Cache for T where T: CertCache + AccountCache {} 8 | 9 | #[async_trait] 10 | pub trait CertCache: Send + Sync { 11 | type EC: Debug; 12 | async fn load_cert(&self, domains: &[String], directory_url: &str) -> Result>, Self::EC>; 13 | async fn store_cert(&self, domains: &[String], directory_url: &str, cert: &[u8]) -> Result<(), Self::EC>; 14 | } 15 | 16 | #[async_trait] 17 | pub trait AccountCache: Send + Sync { 18 | type EA: Debug; 19 | async fn load_account(&self, contact: &[String], directory_url: &str) -> Result>, Self::EA>; 20 | async fn store_account(&self, contact: &[String], directory_url: &str, account: &[u8]) -> Result<(), Self::EA>; 21 | } 22 | -------------------------------------------------------------------------------- /src/caches/boxed.rs: -------------------------------------------------------------------------------- 1 | use crate::{AccountCache, CertCache}; 2 | use async_trait::async_trait; 3 | use std::fmt::Debug; 4 | 5 | pub struct BoxedErrCache { 6 | inner: T, 7 | } 8 | 9 | impl BoxedErrCache { 10 | pub fn new(inner: T) -> Self { 11 | Self { inner } 12 | } 13 | pub fn into_inner(self) -> T { 14 | self.inner 15 | } 16 | } 17 | 18 | fn box_err(e: impl Debug + 'static) -> Box { 19 | Box::new(e) 20 | } 21 | 22 | #[async_trait] 23 | impl CertCache for BoxedErrCache 24 | where 25 | ::EC: 'static, 26 | { 27 | type EC = Box; 28 | async fn load_cert(&self, domains: &[String], directory_url: &str) -> Result>, Self::EC> { 29 | self.inner.load_cert(domains, directory_url).await.map_err(box_err) 30 | } 31 | 32 | async fn store_cert(&self, domains: &[String], directory_url: &str, cert: &[u8]) -> Result<(), Self::EC> { 33 | self.inner.store_cert(domains, directory_url, cert).await.map_err(box_err) 34 | } 35 | } 36 | 37 | #[async_trait] 38 | impl AccountCache for BoxedErrCache 39 | where 40 | ::EA: 'static, 41 | { 42 | type EA = Box; 43 | async fn load_account(&self, contact: &[String], directory_url: &str) -> Result>, Self::EA> { 44 | self.inner.load_account(contact, directory_url).await.map_err(box_err) 45 | } 46 | 47 | async fn store_account(&self, contact: &[String], directory_url: &str, account: &[u8]) -> Result<(), Self::EA> { 48 | self.inner.store_account(contact, directory_url, account).await.map_err(box_err) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/caches/composite.rs: -------------------------------------------------------------------------------- 1 | use crate::{AccountCache, CertCache}; 2 | use async_trait::async_trait; 3 | 4 | pub struct CompositeCache { 5 | pub cert_cache: C, 6 | pub account_cache: A, 7 | } 8 | 9 | impl CompositeCache { 10 | pub fn new(cert_cache: C, account_cache: A) -> Self { 11 | Self { cert_cache, account_cache } 12 | } 13 | pub fn into_inner(self) -> (C, A) { 14 | (self.cert_cache, self.account_cache) 15 | } 16 | } 17 | 18 | #[async_trait] 19 | impl CertCache for CompositeCache { 20 | type EC = C::EC; 21 | async fn load_cert(&self, domains: &[String], directory_url: &str) -> Result>, Self::EC> { 22 | self.cert_cache.load_cert(domains, directory_url).await 23 | } 24 | 25 | async fn store_cert(&self, domains: &[String], directory_url: &str, cert: &[u8]) -> Result<(), Self::EC> { 26 | self.cert_cache.store_cert(domains, directory_url, cert).await 27 | } 28 | } 29 | 30 | #[async_trait] 31 | impl AccountCache for CompositeCache { 32 | type EA = A::EA; 33 | async fn load_account(&self, contact: &[String], directory_url: &str) -> Result>, Self::EA> { 34 | self.account_cache.load_account(contact, directory_url).await 35 | } 36 | 37 | async fn store_account(&self, contact: &[String], directory_url: &str, account: &[u8]) -> Result<(), Self::EA> { 38 | self.account_cache.store_account(contact, directory_url, account).await 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/caches/dir.rs: -------------------------------------------------------------------------------- 1 | use crate::crypto::digest::{Context, SHA256}; 2 | use crate::{AccountCache, CertCache}; 3 | use async_trait::async_trait; 4 | use base64::prelude::*; 5 | use blocking::unblock; 6 | use std::io::ErrorKind; 7 | use std::path::Path; 8 | 9 | pub struct DirCache + Send + Sync> { 10 | inner: P, 11 | } 12 | 13 | impl + Send + Sync> DirCache

{ 14 | pub fn new(dir: P) -> Self { 15 | Self { inner: dir } 16 | } 17 | async fn read_if_exist(&self, file: impl AsRef) -> Result>, std::io::Error> { 18 | let path = self.inner.as_ref().join(file); 19 | match unblock(move || std::fs::read(&path)).await { 20 | Ok(content) => Ok(Some(content)), 21 | Err(err) => match err.kind() { 22 | ErrorKind::NotFound => Ok(None), 23 | _ => Err(err), 24 | }, 25 | } 26 | } 27 | async fn write(&self, file: impl AsRef, contents: impl AsRef<[u8]>) -> Result<(), std::io::Error> { 28 | let path = self.inner.as_ref().to_owned(); 29 | unblock(move || std::fs::create_dir_all(&path)).await?; 30 | let path = self.inner.as_ref().join(file); 31 | let contents = contents.as_ref().to_owned(); 32 | unblock(move || std::fs::write(path, contents)).await 33 | } 34 | fn cached_account_file_name(contact: &[String], directory_url: impl AsRef) -> String { 35 | let mut ctx = Context::new(&SHA256); 36 | for el in contact { 37 | ctx.update(el.as_ref()); 38 | ctx.update(&[0]) 39 | } 40 | ctx.update(directory_url.as_ref().as_bytes()); 41 | let hash = BASE64_URL_SAFE_NO_PAD.encode(ctx.finish()); 42 | format!("cached_account_{}", hash) 43 | } 44 | fn cached_cert_file_name(domains: &[String], directory_url: impl AsRef) -> String { 45 | let mut ctx = Context::new(&SHA256); 46 | for domain in domains { 47 | ctx.update(domain.as_ref()); 48 | ctx.update(&[0]) 49 | } 50 | ctx.update(directory_url.as_ref().as_bytes()); 51 | let hash = BASE64_URL_SAFE_NO_PAD.encode(ctx.finish()); 52 | format!("cached_cert_{}", hash) 53 | } 54 | } 55 | 56 | #[async_trait] 57 | impl + Send + Sync> CertCache for DirCache

{ 58 | type EC = std::io::Error; 59 | async fn load_cert(&self, domains: &[String], directory_url: &str) -> Result>, Self::EC> { 60 | let file_name = Self::cached_cert_file_name(domains, directory_url); 61 | self.read_if_exist(file_name).await 62 | } 63 | async fn store_cert(&self, domains: &[String], directory_url: &str, cert: &[u8]) -> Result<(), Self::EC> { 64 | let file_name = Self::cached_cert_file_name(domains, directory_url); 65 | self.write(file_name, cert).await 66 | } 67 | } 68 | 69 | #[async_trait] 70 | impl + Send + Sync> AccountCache for DirCache

{ 71 | type EA = std::io::Error; 72 | async fn load_account(&self, contact: &[String], directory_url: &str) -> Result>, Self::EA> { 73 | let file_name = Self::cached_account_file_name(contact, directory_url); 74 | self.read_if_exist(file_name).await 75 | } 76 | 77 | async fn store_account(&self, contact: &[String], directory_url: &str, account: &[u8]) -> Result<(), Self::EA> { 78 | let file_name = Self::cached_account_file_name(contact, directory_url); 79 | self.write(file_name, account).await 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/caches/mod.rs: -------------------------------------------------------------------------------- 1 | mod boxed; 2 | mod composite; 3 | mod dir; 4 | mod no; 5 | mod test; 6 | 7 | pub use boxed::*; 8 | pub use composite::*; 9 | pub use dir::*; 10 | pub use no::*; 11 | pub use test::*; 12 | -------------------------------------------------------------------------------- /src/caches/no.rs: -------------------------------------------------------------------------------- 1 | use crate::{AccountCache, CertCache}; 2 | use async_trait::async_trait; 3 | use std::convert::Infallible; 4 | use std::fmt::Debug; 5 | use std::marker::PhantomData; 6 | use std::sync::atomic::AtomicPtr; 7 | 8 | /// No-op cache, which does nothing. 9 | /// ```rust 10 | /// # use rustls_acme::caches::NoCache; 11 | /// # type EC = std::io::Error; 12 | /// # type EA = EC; 13 | /// let no_cache = NoCache::::default(); 14 | /// ``` 15 | #[derive(Copy, Clone)] 16 | pub struct NoCache { 17 | _cert_error: PhantomData>>, 18 | _account_error: PhantomData>>, 19 | } 20 | 21 | impl Default for NoCache { 22 | fn default() -> Self { 23 | Self { 24 | _cert_error: Default::default(), 25 | _account_error: Default::default(), 26 | } 27 | } 28 | } 29 | 30 | #[async_trait] 31 | impl CertCache for NoCache { 32 | type EC = EC; 33 | async fn load_cert(&self, _domains: &[String], _directory_url: &str) -> Result>, Self::EC> { 34 | log::info!("no cert cache configured, could not load certificate"); 35 | Ok(None) 36 | } 37 | async fn store_cert(&self, _domains: &[String], _directory_url: &str, _cert: &[u8]) -> Result<(), Self::EC> { 38 | log::info!("no cert cache configured, could not store certificate"); 39 | Ok(()) 40 | } 41 | } 42 | 43 | #[async_trait] 44 | impl AccountCache for NoCache { 45 | type EA = EA; 46 | async fn load_account(&self, _contact: &[String], _directory_url: &str) -> Result>, Self::EA> { 47 | log::info!("no account cache configured, could not load account"); 48 | Ok(None) 49 | } 50 | async fn store_account(&self, _contact: &[String], _directory_url: &str, _account: &[u8]) -> Result<(), Self::EA> { 51 | log::info!("no account cache configured, could not store account"); 52 | Ok(()) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/caches/test.rs: -------------------------------------------------------------------------------- 1 | use crate::{AccountCache, CertCache}; 2 | use async_trait::async_trait; 3 | use rcgen::{date_time_ymd, BasicConstraints, CertificateParams, DistinguishedName, DnType, IsCa, KeyPair, KeyUsagePurpose, PKCS_ECDSA_P256_SHA256}; 4 | use std::fmt::Debug; 5 | use std::marker::PhantomData; 6 | use std::sync::atomic::AtomicPtr; 7 | use std::sync::Arc; 8 | 9 | /// Test cache, which generates certificates for ACME incompatible test environments. 10 | /// ```rust 11 | /// # use rustls_acme::{AcmeConfig}; 12 | /// # use rustls_acme::caches::{DirCache, TestCache}; 13 | /// # let test_environment = true; 14 | /// let mut config = AcmeConfig::new(["example.com"]) 15 | /// .cache(DirCache::new("./cache")); 16 | /// if test_environment { 17 | /// config = config.cache(TestCache::default()); 18 | /// } 19 | /// ``` 20 | #[derive(Clone)] 21 | pub struct TestCache { 22 | ca_key: Arc, 23 | ca_cert: Arc, 24 | ca_pem: Arc, 25 | _cert_error: PhantomData>>, 26 | _account_error: PhantomData>>, 27 | } 28 | 29 | impl Default for TestCache { 30 | fn default() -> Self { 31 | let mut params = CertificateParams::default(); 32 | let mut distinguished_name = DistinguishedName::new(); 33 | distinguished_name.push(DnType::CountryName, "US"); 34 | distinguished_name.push(DnType::OrganizationName, "Test CA"); 35 | distinguished_name.push(DnType::CommonName, "Test CA"); 36 | params.distinguished_name = distinguished_name; 37 | params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); 38 | params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; 39 | params.not_before = date_time_ymd(2000, 1, 1); 40 | params.not_after = date_time_ymd(3000, 1, 1); 41 | let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); 42 | let ca_cert = params.self_signed(&key_pair).unwrap(); 43 | let ca_pem = ca_cert.pem(); 44 | Self { 45 | ca_key: key_pair.into(), 46 | ca_cert: ca_cert.into(), 47 | ca_pem: ca_pem.into(), 48 | _cert_error: Default::default(), 49 | _account_error: Default::default(), 50 | } 51 | } 52 | } 53 | 54 | impl TestCache { 55 | pub fn ca_pem(&self) -> &str { 56 | &self.ca_pem 57 | } 58 | } 59 | 60 | #[async_trait] 61 | impl CertCache for TestCache { 62 | type EC = EC; 63 | async fn load_cert(&self, domains: &[String], _directory_url: &str) -> Result>, Self::EC> { 64 | let mut params = CertificateParams::new(domains).unwrap(); 65 | let mut distinguished_name = DistinguishedName::new(); 66 | distinguished_name.push(DnType::CommonName, "Test Cert"); 67 | params.distinguished_name = distinguished_name; 68 | params.not_before = date_time_ymd(2000, 1, 1); 69 | params.not_after = date_time_ymd(3000, 1, 1); 70 | let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); 71 | let cert = params.signed_by(&key_pair, &self.ca_cert, &self.ca_key).unwrap(); 72 | let private_key_pem = key_pair.serialize_pem(); 73 | let signed_cert_pem = cert.pem(); 74 | Ok(Some([&private_key_pem, "\n", &signed_cert_pem, "\n", &self.ca_pem].concat().into_bytes())) 75 | } 76 | async fn store_cert(&self, _domains: &[String], _directory_url: &str, _cert: &[u8]) -> Result<(), Self::EC> { 77 | log::info!("test cache configured, could not store certificate"); 78 | Ok(()) 79 | } 80 | } 81 | 82 | #[async_trait] 83 | impl AccountCache for TestCache { 84 | type EA = EA; 85 | async fn load_account(&self, _contact: &[String], _directory_url: &str) -> Result>, Self::EA> { 86 | log::info!("test cache configured, could not load account"); 87 | Ok(None) 88 | } 89 | async fn store_account(&self, _contact: &[String], _directory_url: &str, _account: &[u8]) -> Result<(), Self::EA> { 90 | log::info!("test cache configured, could not store account"); 91 | Ok(()) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | use crate::acme::{LETS_ENCRYPT_PRODUCTION_DIRECTORY, LETS_ENCRYPT_STAGING_DIRECTORY}; 2 | use crate::caches::{BoxedErrCache, CompositeCache, NoCache}; 3 | use crate::UseChallenge::TlsAlpn01; 4 | use crate::{crypto_provider, AccountCache, Cache, CertCache}; 5 | use crate::{AcmeState, Incoming}; 6 | use core::fmt; 7 | use futures::{AsyncRead, AsyncWrite, Stream}; 8 | use futures_rustls::pki_types::TrustAnchor; 9 | use futures_rustls::rustls::crypto::CryptoProvider; 10 | use futures_rustls::rustls::{ClientConfig, RootCertStore}; 11 | use std::convert::Infallible; 12 | use std::fmt::Debug; 13 | use std::sync::Arc; 14 | use webpki_roots::TLS_SERVER_ROOTS; 15 | 16 | /// Configuration for an ACME resolver. 17 | /// 18 | /// The type parameters represent the error types for the certificate cache and account cache. 19 | pub struct AcmeConfig { 20 | pub(crate) client_config: Arc, 21 | pub(crate) directory_url: String, 22 | pub(crate) domains: Vec, 23 | pub(crate) contact: Vec, 24 | pub(crate) cache: Box>, 25 | pub(crate) challenge_type: UseChallenge, 26 | } 27 | 28 | pub enum UseChallenge { 29 | Http01, 30 | TlsAlpn01, 31 | } 32 | 33 | impl AcmeConfig { 34 | /// Creates a new [AcmeConfig] instance. 35 | /// 36 | /// The new [AcmeConfig] instance will initially have no cache, and its type parameters for 37 | /// error types will be `Infallible` since the cache cannot return an error. The methods to set 38 | /// a cache will change the error types to match those returned by the supplied cache. 39 | /// 40 | /// ```rust 41 | /// # use rustls_acme::AcmeConfig; 42 | /// use rustls_acme::caches::DirCache; 43 | /// let config = AcmeConfig::new(["example.com"]).cache(DirCache::new("./rustls_acme_cache")); 44 | /// ``` 45 | /// 46 | /// Due to limited support for type parameter inference in Rust (see 47 | /// [RFC213](https://github.com/rust-lang/rfcs/blob/master/text/0213-defaulted-type-params.md)), 48 | /// [AcmeConfig::new] is not (yet) generic over the [AcmeConfig]'s type parameters. 49 | /// An uncached instance of [AcmeConfig] with particular type parameters can be created using 50 | /// [NoCache]. 51 | /// 52 | /// ```rust 53 | /// # use rustls_acme::AcmeConfig; 54 | /// use rustls_acme::caches::NoCache; 55 | /// # type EC = std::io::Error; 56 | /// # type EA = EC; 57 | /// let config: AcmeConfig = AcmeConfig::new(["example.com"]).cache(NoCache::default()); 58 | /// ``` 59 | #[cfg(any(feature = "ring", feature = "aws-lc-rs"))] 60 | pub fn new(domains: impl IntoIterator>) -> Self { 61 | Self::new_with_provider(domains, crypto_provider().into()) 62 | } 63 | 64 | /// Same as [AcmeConfig::new], with a specific [CryptoProvider]. 65 | pub fn new_with_provider(domains: impl IntoIterator>, provider: Arc) -> Self { 66 | let mut root_store = RootCertStore::empty(); 67 | root_store.extend(TLS_SERVER_ROOTS.iter().map(|ta| { 68 | let ta = ta.to_owned(); 69 | TrustAnchor { 70 | subject: ta.subject, 71 | subject_public_key_info: ta.subject_public_key_info, 72 | name_constraints: ta.name_constraints, 73 | } 74 | })); 75 | let client_config = Arc::new( 76 | ClientConfig::builder_with_provider(provider) 77 | .with_safe_default_protocol_versions() 78 | .unwrap() 79 | .with_root_certificates(root_store) 80 | .with_no_client_auth(), 81 | ); 82 | AcmeConfig { 83 | client_config, 84 | directory_url: LETS_ENCRYPT_STAGING_DIRECTORY.into(), 85 | domains: domains.into_iter().map(|s| s.as_ref().into()).collect(), 86 | contact: vec![], 87 | cache: Box::new(NoCache::default()), 88 | challenge_type: TlsAlpn01, 89 | } 90 | } 91 | } 92 | 93 | impl AcmeConfig { 94 | /// Set custom `rustls::ClientConfig` for ACME API calls. 95 | pub fn client_tls_config(mut self, client_config: Arc) -> Self { 96 | self.client_config = client_config; 97 | self 98 | } 99 | pub fn directory(mut self, directory_url: impl AsRef) -> Self { 100 | self.directory_url = directory_url.as_ref().into(); 101 | self 102 | } 103 | pub fn directory_lets_encrypt(mut self, production: bool) -> Self { 104 | self.directory_url = match production { 105 | true => LETS_ENCRYPT_PRODUCTION_DIRECTORY, 106 | false => LETS_ENCRYPT_STAGING_DIRECTORY, 107 | } 108 | .into(); 109 | self 110 | } 111 | pub fn domains(mut self, contact: impl IntoIterator>) -> Self { 112 | self.domains = contact.into_iter().map(|s| s.as_ref().into()).collect(); 113 | self 114 | } 115 | pub fn domains_push(mut self, contact: impl AsRef) -> Self { 116 | self.domains.push(contact.as_ref().into()); 117 | self 118 | } 119 | 120 | /// Provide a list of contacts for the account. 121 | /// 122 | /// Note that email addresses must include a `mailto:` prefix. 123 | pub fn contact(mut self, contact: impl IntoIterator>) -> Self { 124 | self.contact = contact.into_iter().map(|s| s.as_ref().into()).collect(); 125 | self 126 | } 127 | 128 | /// Provide a contact for the account. 129 | /// 130 | /// Note that an email address must include a `mailto:` prefix. 131 | pub fn contact_push(mut self, contact: impl AsRef) -> Self { 132 | self.contact.push(contact.as_ref().into()); 133 | self 134 | } 135 | 136 | pub fn cache(self, cache: C) -> AcmeConfig { 137 | AcmeConfig { 138 | client_config: self.client_config, 139 | directory_url: self.directory_url, 140 | domains: self.domains, 141 | contact: self.contact, 142 | cache: Box::new(cache), 143 | challenge_type: self.challenge_type, 144 | } 145 | } 146 | pub fn cache_compose(self, cert_cache: CC, account_cache: CA) -> AcmeConfig { 147 | self.cache(CompositeCache::new(cert_cache, account_cache)) 148 | } 149 | pub fn cache_with_boxed_err(self, cache: C) -> AcmeConfig> { 150 | self.cache(BoxedErrCache::new(cache)) 151 | } 152 | pub fn cache_option(self, cache: Option) -> AcmeConfig { 153 | match cache { 154 | Some(cache) => self.cache(cache), 155 | None => self.cache(NoCache::::default()), 156 | } 157 | } 158 | pub fn challenge_type(mut self, challenge_type: UseChallenge) -> Self { 159 | self.challenge_type = challenge_type; 160 | self 161 | } 162 | pub fn state(self) -> AcmeState { 163 | AcmeState::new(self) 164 | } 165 | /// Turn a stream of TCP connections into a stream of TLS connections. 166 | /// 167 | /// Specify supported protocol names in `alpn_protocols`, most preferred first. If empty (`Vec::new()`), we don't do ALPN. 168 | pub fn incoming> + Unpin>( 169 | self, 170 | tcp_incoming: ITCP, 171 | alpn_protocols: Vec>, 172 | ) -> Incoming { 173 | self.state().incoming(tcp_incoming, alpn_protocols) 174 | } 175 | #[cfg(feature = "tokio")] 176 | /// Tokio compatible wrapper for [Self::incoming]. 177 | pub fn tokio_incoming< 178 | TokioTCP: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, 179 | ETCP, 180 | TokioITCP: Stream> + Unpin, 181 | >( 182 | self, 183 | tcp_incoming: TokioITCP, 184 | alpn_protocols: Vec>, 185 | ) -> crate::tokio::TokioIncoming< 186 | tokio_util::compat::Compat, 187 | ETCP, 188 | crate::tokio::TokioIncomingTcpWrapper, 189 | EC, 190 | EA, 191 | > { 192 | self.state().tokio_incoming(tcp_incoming, alpn_protocols) 193 | } 194 | } 195 | 196 | impl fmt::Debug for AcmeConfig { 197 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 198 | f.debug_struct("AcmeConfig") 199 | .field("directory", &self.directory_url) 200 | .field("domains", &self.domains) 201 | .field("contact", &self.contact) 202 | .finish_non_exhaustive() 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /src/helpers.rs: -------------------------------------------------------------------------------- 1 | use futures_rustls::rustls::server::ClientHello; 2 | 3 | use crate::acme::ACME_TLS_ALPN_NAME; 4 | 5 | /// Returns `true` if the client_hello indicates a TLS-ALPN-01 challenge connection. 6 | pub fn is_tls_alpn_challenge(client_hello: &ClientHello) -> bool { 7 | client_hello.alpn().into_iter().flatten().eq([ACME_TLS_ALPN_NAME]) 8 | } 9 | -------------------------------------------------------------------------------- /src/https_helper.rs: -------------------------------------------------------------------------------- 1 | use async_web_client::prelude::*; 2 | use futures::AsyncReadExt; 3 | use futures_rustls::pki_types::InvalidDnsNameError; 4 | use futures_rustls::rustls::ClientConfig; 5 | use http::header::CONTENT_TYPE; 6 | use http::{Method, Request, Response}; 7 | use std::io; 8 | use std::sync::Arc; 9 | use thiserror::Error; 10 | 11 | pub(crate) async fn https( 12 | client_config: &Arc, 13 | url: impl AsRef, 14 | method: Method, 15 | body: Option, 16 | ) -> Result, HttpsRequestError> { 17 | let request = Request::builder().method(method).uri(url.as_ref()); 18 | let request = if let Some(body) = body { 19 | request.header(CONTENT_TYPE, "application/jose+json").body(body) 20 | } else { 21 | request.body("".to_string()) 22 | }; 23 | let request = request?; 24 | let mut response = request.send_with_client_config(client_config.clone()).await?; 25 | let mut body = String::new(); 26 | response.body_mut().read_to_string(&mut body).await?; 27 | let response = response.map(|_| body); 28 | let status = response.status(); 29 | if !status.is_success() { 30 | return Err(HttpsRequestError::Non2xxStatus { 31 | status_code: status.into(), 32 | body: response.into_body(), 33 | }); 34 | } 35 | Ok(response) 36 | } 37 | 38 | #[derive(Error, Debug)] 39 | pub enum HttpsRequestError { 40 | #[error("io error: {0:?}")] 41 | Io(#[from] io::Error), 42 | #[error("invalid dns name: {0:?}")] 43 | InvalidDnsName(#[from] InvalidDnsNameError), 44 | #[error("http error: {0:?}")] 45 | Http(Box), 46 | #[error("non 2xx http status: {status_code} {body:?}")] 47 | Non2xxStatus { status_code: u16, body: String }, 48 | #[error("could not determine host from url")] 49 | UndefinedHost, 50 | } 51 | 52 | impl From for HttpsRequestError { 53 | fn from(e: async_web_client::HttpError) -> Self { 54 | Self::Http(e.into()) 55 | } 56 | } 57 | 58 | impl From for HttpsRequestError { 59 | fn from(e: http::Error) -> Self { 60 | Self::Http(e.into()) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/incoming.rs: -------------------------------------------------------------------------------- 1 | use crate::acceptor::{AcmeAccept, AcmeAcceptor}; 2 | use crate::{crypto_provider, AcmeState}; 3 | use core::fmt; 4 | use futures::stream::{FusedStream, FuturesUnordered}; 5 | use futures::{AsyncRead, AsyncWrite, Stream}; 6 | use futures_rustls::rustls::crypto::CryptoProvider; 7 | use futures_rustls::rustls::ServerConfig; 8 | use futures_rustls::server::TlsStream; 9 | use futures_rustls::Accept; 10 | use std::fmt::Debug; 11 | use std::pin::Pin; 12 | use std::sync::Arc; 13 | use std::task::{Context, Poll}; 14 | 15 | pub struct Incoming< 16 | TCP: AsyncRead + AsyncWrite + Unpin, 17 | ETCP, 18 | ITCP: Stream> + Unpin, 19 | EC: Debug + 'static, 20 | EA: Debug + 'static, 21 | > { 22 | state: AcmeState, 23 | acceptor: AcmeAcceptor, 24 | rustls_config: Arc, 25 | tcp_incoming: Option, 26 | acme_accepting: FuturesUnordered>, 27 | tls_accepting: FuturesUnordered>, 28 | } 29 | 30 | impl> + Unpin, EC: Debug + 'static, EA: Debug + 'static> fmt::Debug 31 | for Incoming 32 | { 33 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 34 | f.debug_struct("Incoming") 35 | .field("state", &self.state) 36 | .field("acceptor", &self.acceptor) 37 | .field("in_progress", &(self.acme_accepting.len() + self.tls_accepting.len())) 38 | .field("terminated", &self.is_terminated()) 39 | .finish_non_exhaustive() 40 | } 41 | } 42 | 43 | impl> + Unpin, EC: Debug + 'static, EA: Debug + 'static> Unpin 44 | for Incoming 45 | { 46 | } 47 | 48 | impl> + Unpin, EC: Debug + 'static, EA: Debug + 'static> 49 | Incoming 50 | { 51 | #[cfg(any(feature = "ring", feature = "aws-lc-rs"))] 52 | pub fn new(tcp_incoming: ITCP, state: AcmeState, acceptor: AcmeAcceptor, alpn_protocols: Vec>) -> Self { 53 | Self::new_with_provider(tcp_incoming, state, acceptor, alpn_protocols, crypto_provider().into()) 54 | } 55 | 56 | /// Same as [Incoming::new], with a specific [CryptoProvider]. 57 | pub fn new_with_provider( 58 | tcp_incoming: ITCP, 59 | state: AcmeState, 60 | acceptor: AcmeAcceptor, 61 | alpn_protocols: Vec>, 62 | provider: Arc, 63 | ) -> Self { 64 | let mut config = ServerConfig::builder_with_provider(provider) 65 | .with_safe_default_protocol_versions() 66 | .unwrap() 67 | .with_no_client_auth() 68 | .with_cert_resolver(state.resolver()); 69 | config.alpn_protocols = alpn_protocols; 70 | Self { 71 | state, 72 | acceptor, 73 | rustls_config: Arc::new(config), 74 | tcp_incoming: Some(tcp_incoming), 75 | acme_accepting: FuturesUnordered::new(), 76 | tls_accepting: FuturesUnordered::new(), 77 | } 78 | } 79 | } 80 | 81 | impl> + Unpin, EC: Debug + 'static, EA: Debug + 'static> Stream 82 | for Incoming 83 | { 84 | type Item = Result, ETCP>; 85 | 86 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 87 | loop { 88 | match Pin::new(&mut self.state).poll_next(cx) { 89 | Poll::Ready(Some(event)) => { 90 | match event { 91 | Ok(ok) => log::info!("event: {:?}", ok), 92 | Err(err) => log::error!("event: {:?}", err), 93 | } 94 | continue; 95 | } 96 | Poll::Ready(None) => unreachable!(), 97 | Poll::Pending => {} 98 | } 99 | match Pin::new(&mut self.acme_accepting).poll_next(cx) { 100 | Poll::Ready(Some(Ok(Some(tls)))) => self.tls_accepting.push(tls.into_stream(self.rustls_config.clone())), 101 | Poll::Ready(Some(Ok(None))) => { 102 | log::info!("received TLS-ALPN-01 validation request"); 103 | continue; 104 | } 105 | Poll::Ready(Some(Err(err))) => { 106 | log::error!("tls accept failed, {:?}", err); 107 | continue; 108 | } 109 | Poll::Ready(None) | Poll::Pending => {} 110 | } 111 | match Pin::new(&mut self.tls_accepting).poll_next(cx) { 112 | Poll::Ready(Some(Ok(tls))) => return Poll::Ready(Some(Ok(tls))), 113 | Poll::Ready(Some(Err(err))) => { 114 | log::error!("tls accept failed, {:?}", err); 115 | continue; 116 | } 117 | Poll::Ready(None) | Poll::Pending => {} 118 | } 119 | let tcp_incoming = match &mut self.tcp_incoming { 120 | Some(tcp_incoming) => tcp_incoming, 121 | None => match self.is_terminated() { 122 | true => return Poll::Ready(None), 123 | false => return Poll::Pending, 124 | }, 125 | }; 126 | match Pin::new(tcp_incoming).poll_next(cx) { 127 | Poll::Ready(Some(Ok(tcp))) => self.acme_accepting.push(self.acceptor.accept(tcp)), 128 | Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err))), 129 | Poll::Ready(None) => drop(self.tcp_incoming.as_mut().take()), 130 | Poll::Pending => return Poll::Pending, 131 | } 132 | } 133 | } 134 | } 135 | 136 | impl> + Unpin, EC: Debug + 'static, EA: Debug + 'static> FusedStream 137 | for Incoming 138 | { 139 | fn is_terminated(&self) -> bool { 140 | self.tcp_incoming.is_none() && self.acme_accepting.is_terminated() && self.tls_accepting.is_terminated() 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/jose.rs: -------------------------------------------------------------------------------- 1 | use crate::crypto::digest::{digest, Digest, SHA256}; 2 | use crate::crypto::rand::SystemRandom; 3 | use crate::crypto::signature::{EcdsaKeyPair, KeyPair}; 4 | use base64::prelude::*; 5 | use serde::Serialize; 6 | use thiserror::Error; 7 | 8 | pub(crate) fn sign(key: &EcdsaKeyPair, kid: Option<&str>, nonce: String, url: &str, payload: &str) -> Result { 9 | let jwk = match kid { 10 | None => Some(Jwk::new(key)), 11 | Some(_) => None, 12 | }; 13 | let protected = Protected::base64(jwk, kid, nonce, url)?; 14 | let payload = BASE64_URL_SAFE_NO_PAD.encode(payload); 15 | let combined = format!("{}.{}", &protected, &payload); 16 | let signature = key.sign(&SystemRandom::new(), combined.as_bytes())?; 17 | let signature = BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref()); 18 | let body = Body { 19 | protected, 20 | payload, 21 | signature, 22 | }; 23 | Ok(serde_json::to_string(&body)?) 24 | } 25 | 26 | pub(crate) fn key_authorization(key: &EcdsaKeyPair, token: &str) -> Result { 27 | let jwk = Jwk::new(key); 28 | Ok(format!("{}.{}", token, jwk.thumb_sha256_base64()?)) 29 | } 30 | 31 | pub(crate) fn key_authorization_sha256(key: &EcdsaKeyPair, token: &str) -> Result { 32 | let key_authorization = key_authorization(key, token)?; 33 | Ok(digest(&SHA256, key_authorization.as_bytes())) 34 | } 35 | 36 | #[derive(Serialize)] 37 | struct Body { 38 | protected: String, 39 | payload: String, 40 | signature: String, 41 | } 42 | 43 | #[derive(Serialize)] 44 | struct Protected<'a> { 45 | alg: &'static str, 46 | #[serde(skip_serializing_if = "Option::is_none")] 47 | jwk: Option, 48 | #[serde(skip_serializing_if = "Option::is_none")] 49 | kid: Option<&'a str>, 50 | nonce: String, 51 | url: &'a str, 52 | } 53 | 54 | impl<'a> Protected<'a> { 55 | fn base64(jwk: Option, kid: Option<&'a str>, nonce: String, url: &'a str) -> Result { 56 | let protected = Self { 57 | alg: "ES256", 58 | jwk, 59 | kid, 60 | nonce, 61 | url, 62 | }; 63 | let protected = serde_json::to_vec(&protected)?; 64 | Ok(BASE64_URL_SAFE_NO_PAD.encode(protected)) 65 | } 66 | } 67 | 68 | #[derive(Serialize)] 69 | struct Jwk { 70 | alg: &'static str, 71 | crv: &'static str, 72 | kty: &'static str, 73 | #[serde(rename = "use")] 74 | u: &'static str, 75 | x: String, 76 | y: String, 77 | } 78 | 79 | impl Jwk { 80 | pub(crate) fn new(key: &EcdsaKeyPair) -> Self { 81 | let (x, y) = key.public_key().as_ref()[1..].split_at(32); 82 | Self { 83 | alg: "ES256", 84 | crv: "P-256", 85 | kty: "EC", 86 | u: "sig", 87 | x: BASE64_URL_SAFE_NO_PAD.encode(x), 88 | y: BASE64_URL_SAFE_NO_PAD.encode(y), 89 | } 90 | } 91 | pub(crate) fn thumb_sha256_base64(&self) -> Result { 92 | let jwk_thumb = JwkThumb { 93 | crv: self.crv, 94 | kty: self.kty, 95 | x: &self.x, 96 | y: &self.y, 97 | }; 98 | let json = serde_json::to_vec(&jwk_thumb)?; 99 | let hash = digest(&SHA256, &json); 100 | Ok(BASE64_URL_SAFE_NO_PAD.encode(hash)) 101 | } 102 | } 103 | 104 | #[derive(Serialize)] 105 | struct JwkThumb<'a> { 106 | crv: &'a str, 107 | kty: &'a str, 108 | x: &'a str, 109 | y: &'a str, 110 | } 111 | 112 | #[derive(Error, Debug)] 113 | pub enum JoseError { 114 | #[error("json serialization failed: {0}")] 115 | Json(#[from] serde_json::Error), 116 | #[error("crypto error: {0}")] 117 | Crypto(#[from] crate::crypto::error::Unspecified), 118 | } 119 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! rustls-acme is an easy-to-use, async compatible ACME client library for rustls. 2 | //! The validation mechanism used is TLS-ALPN-01 OR HTTP-01, which allow serving acme challenge responses and 3 | //! regular TLS traffic on the same port. 4 | //! 5 | //! rustls-acme is designed to be runtime agnostic and as runtime independent as Rust allows at the 6 | //! moment. 7 | //! No persistent tasks are spawned under the hood and the certificate acquisition/renewal process 8 | //! is folded into the streams and futures being polled by the library user. 9 | //! 10 | //! The goal is to provide a [Let's Encrypt](https://letsencrypt.org/) compatible TLS serving and 11 | //! certificate management using a simple and flexible stream based API. 12 | //! 13 | //! To use rustls-acme add the following lines to your `Cargo.toml`: 14 | //! 15 | //! ```toml 16 | //! [dependencies] 17 | //! rustls-acme = "*" 18 | //! ``` 19 | //! 20 | //! ## Validation mechanims 21 | //! 22 | //! Using TLS-ALPN-01 is used by default and recommended. 23 | //! However, if the DNS entry points to an HTTP proxy, which terminates TLS, but you still need a certificate, 24 | //! you may be able to use HTTP-01 instead (see `examples/low_level_axum_http01.rs`). 25 | //! 26 | //! ## High-level API 27 | //! 28 | //! The high-level API consists of a single stream [Incoming] of incoming TLS connection. 29 | //! Polling the next future of the stream takes care of acquisition and renewal of certificates, as 30 | //! well as accepting TLS connections, which are handed over to the caller on success. 31 | //! 32 | //! ```rust,no_run 33 | //! use futures::prelude::*; 34 | //! use rustls_acme::{AcmeConfig, caches::DirCache}; 35 | //! 36 | //! #[macro_rules_attribute::apply(smol_macros::main!)] 37 | //! async fn main() { 38 | //! simple_logger::init_with_level(log::Level::Info).unwrap(); 39 | //! 40 | //! let tcp_listener = smol::net::TcpListener::bind("[::]:443").await.unwrap(); 41 | //! 42 | //! let mut tls_incoming = AcmeConfig::new(["example.com"]) 43 | //! .contact_push("mailto:admin@example.com") 44 | //! .cache(DirCache::new("./rustls_acme_cache")) 45 | //! .incoming(tcp_listener.incoming(), Vec::new()); 46 | //! 47 | //! while let Some(tls) = tls_incoming.next().await { 48 | //! let mut tls = tls.unwrap(); 49 | //! smol::spawn(async move { 50 | //! tls.write_all(HELLO).await.unwrap(); 51 | //! tls.close().await.unwrap(); 52 | //! }).detach(); 53 | //! } 54 | //! } 55 | //! 56 | //! const HELLO: &'static [u8] = br#"HTTP/1.1 200 OK 57 | //! Content-Length: 11 58 | //! Content-Type: text/plain; charset=utf-8 59 | //! 60 | //! Hello Tls!"#; 61 | //! ``` 62 | //! 63 | //! `examples/high_level.rs` implements a "Hello Tls!" server similar to the one above, which accepts 64 | //! domain, port and cache directory parameters. 65 | //! 66 | //! Note that all examples use the let's encrypt staging directory by default. 67 | //! The production directory imposes strict rate limits, which are easily exhausted accidentally 68 | //! during testing and development. 69 | //! For testing with the staging directory you may open `https://:` in a browser 70 | //! that allows TLS connections to servers signed by an untrusted CA (in Firefox click "Advanced..." 71 | //! -> "Accept the Risk and Continue"). 72 | //! 73 | //! ## Low-level Rustls API 74 | //! 75 | //! For users who may want to interact with [rustls] or [futures_rustls] 76 | //! directly, the library exposes the underlying certificate management [AcmeState] as well as a 77 | //! matching resolver [ResolvesServerCertAcme] which implements the [rustls::server::ResolvesServerCert] trait. 78 | //! See the server_low_level example on how to use the low-level API directly with [futures_rustls]. 79 | //! 80 | //! ## Account and certificate caching 81 | //! 82 | //! A production server using the let's encrypt production directory must implement both account and 83 | //! certificate caching to avoid exhausting the let's encrypt API rate limits. 84 | //! A file based cache using a cache directory is provided by [caches::DirCache]. 85 | //! Caches backed by other persistence layers may be implemented using the [Cache] trait, 86 | //! or the underlying [CertCache], [AccountCache] traits (contributions welcome). 87 | //! [caches::CompositeCache] provides a wrapper to combine two implementors of [CertCache] and 88 | //! [AccountCache] into a single [Cache]. 89 | //! 90 | //! Note, that the error type parameters of the cache carries over to some other types in this 91 | //! crate via the [AcmeConfig] they are added to. 92 | //! If you want to avoid different specializations based on cache type use the 93 | //! [AcmeConfig::cache_with_boxed_err] method to construct an [AcmeConfig] object. 94 | //! 95 | //! 96 | //! ## The acme module 97 | //! 98 | //! The underlying implementation of an async acme client may be useful to others and is exposed as 99 | //! a module. It is incomplete (contributions welcome) and not covered by any stability 100 | //! promises. 101 | //! 102 | //! ## Special thanks 103 | //! 104 | //! This crate was inspired by the [autocert](https://golang.org/x/crypto/acme/autocert/) 105 | //! package for [Go](https://golang.org). 106 | //! 107 | //! This crate builds on the excellent work of the authors of 108 | //! [rustls](https://github.com/ctz/rustls), 109 | //! [futures-rustls](https://github.com/quininer/futures-rustls), 110 | //! and many others. 111 | //! 112 | //! Thanks to: 113 | //! - [Josh Triplett](https://github.com/joshtriplett) for many contributions and feedback. 114 | //! - [Jack Klamer](https://github.com/jklamer) for contributing HTTP-01 challenge support. 115 | 116 | #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] 117 | 118 | mod acceptor; 119 | pub mod acme; 120 | #[cfg(feature = "axum")] 121 | pub mod axum; 122 | mod cache; 123 | pub mod caches; 124 | mod config; 125 | mod helpers; 126 | mod https_helper; 127 | mod incoming; 128 | mod jose; 129 | mod resolver; 130 | mod state; 131 | #[cfg(feature = "tokio")] 132 | pub mod tokio; 133 | #[cfg(feature = "tower")] 134 | pub mod tower; 135 | 136 | pub use futures_rustls; 137 | 138 | pub use acceptor::*; 139 | pub use cache::*; 140 | pub use config::*; 141 | pub use helpers::*; 142 | pub use incoming::*; 143 | pub use resolver::*; 144 | pub use state::*; 145 | 146 | #[cfg(feature = "aws-lc-rs")] 147 | use ::aws_lc_rs as crypto; 148 | #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] 149 | use ::ring as crypto; 150 | 151 | // TODO: Can we use something like CryptoProvider for rustls, but for ring to drop this requirement? 152 | #[cfg(not(any(feature = "ring", feature = "aws-lc-rs")))] 153 | compile_error!("rustls-acme requires either the ring or aws-lc-rs feature enabled"); 154 | 155 | #[cfg(any(feature = "ring", feature = "aws-lc-rs"))] 156 | pub(crate) fn any_ecdsa_type( 157 | der: &futures_rustls::pki_types::PrivateKeyDer, 158 | ) -> Result, futures_rustls::rustls::Error> { 159 | #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] 160 | return futures_rustls::rustls::crypto::ring::sign::any_ecdsa_type(der); 161 | #[cfg(feature = "aws-lc-rs")] 162 | return futures_rustls::rustls::crypto::aws_lc_rs::sign::any_ecdsa_type(der); 163 | } 164 | 165 | #[cfg(any(feature = "ring", feature = "aws-lc-rs"))] 166 | pub(crate) fn crypto_provider() -> futures_rustls::rustls::crypto::CryptoProvider { 167 | #[cfg(all(feature = "ring", not(feature = "aws-lc-rs")))] 168 | return futures_rustls::rustls::crypto::ring::default_provider(); 169 | #[cfg(feature = "aws-lc-rs")] 170 | return futures_rustls::rustls::crypto::aws_lc_rs::default_provider(); 171 | } 172 | -------------------------------------------------------------------------------- /src/resolver.rs: -------------------------------------------------------------------------------- 1 | use crate::is_tls_alpn_challenge; 2 | use futures_rustls::rustls::{ 3 | server::{ClientHello, ResolvesServerCert}, 4 | sign::CertifiedKey, 5 | }; 6 | use std::fmt::Debug; 7 | use std::sync::Arc; 8 | use std::sync::Mutex; 9 | 10 | #[derive(Debug)] 11 | pub struct ResolvesServerCertAcme { 12 | inner: Mutex, 13 | } 14 | 15 | #[derive(Debug)] 16 | struct Inner { 17 | cert: Option>, 18 | challenge_data: Option, 19 | } 20 | 21 | #[derive(Debug)] 22 | enum ChallengeData { 23 | TlsAlpn01 { sni: String, cert: Arc }, 24 | Http01 { token: String, key_auth: String }, 25 | } 26 | 27 | impl ResolvesServerCertAcme { 28 | pub(crate) fn new() -> Arc { 29 | Arc::new(Self { 30 | inner: Mutex::new(Inner { 31 | cert: None, 32 | challenge_data: None, 33 | }), 34 | }) 35 | } 36 | pub(crate) fn set_cert(&self, cert: Arc) { 37 | self.inner.lock().unwrap().cert = Some(cert); 38 | } 39 | pub(crate) fn set_tls_alpn_01_challenge_data(&self, domain: String, cert: Arc) { 40 | self.inner.lock().unwrap().challenge_data = Some(ChallengeData::TlsAlpn01 { sni: domain, cert }); 41 | } 42 | pub(crate) fn set_http_01_challenge_data(&self, token: String, key_auth: String) { 43 | self.inner.lock().unwrap().challenge_data = Some(ChallengeData::Http01 { token, key_auth }) 44 | } 45 | pub(crate) fn clear_challenge_data(&self) { 46 | self.inner.lock().unwrap().challenge_data = None; 47 | } 48 | pub fn get_http_01_key_auth(&self, challenge_token: &str) -> Option { 49 | match &self.inner.lock().unwrap().challenge_data { 50 | Some(ChallengeData::Http01 { token, key_auth }) => { 51 | if token == challenge_token { 52 | Some(key_auth.clone()) 53 | } else { 54 | None 55 | } 56 | } 57 | _ => None, 58 | } 59 | } 60 | } 61 | 62 | impl ResolvesServerCert for ResolvesServerCertAcme { 63 | fn resolve(&self, client_hello: ClientHello) -> Option> { 64 | let is_acme_challenge = is_tls_alpn_challenge(&client_hello); 65 | if is_acme_challenge { 66 | match client_hello.server_name() { 67 | None => { 68 | log::debug!("client did not supply SNI"); 69 | None 70 | } 71 | Some(domain) => match &self.inner.lock().unwrap().challenge_data { 72 | Some(ChallengeData::TlsAlpn01 { sni, cert }) => { 73 | if sni == domain { 74 | Some(cert.clone()) 75 | } else { 76 | None 77 | } 78 | } 79 | _ => None, 80 | }, 81 | } 82 | } else { 83 | self.inner.lock().unwrap().cert.clone() 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/state.rs: -------------------------------------------------------------------------------- 1 | use crate::acceptor::AcmeAcceptor; 2 | use crate::acme::{Account, AcmeError, Auth, AuthStatus, Directory, Identifier, Order, OrderStatus, ACME_TLS_ALPN_NAME}; 3 | use crate::{any_ecdsa_type, crypto_provider, AcmeConfig, Incoming, ResolvesServerCertAcme, UseChallenge}; 4 | use async_io::Timer; 5 | use chrono::{DateTime, TimeZone, Utc}; 6 | use core::fmt; 7 | use futures::prelude::*; 8 | use futures::ready; 9 | use futures_rustls::pki_types::{CertificateDer as RustlsCertificate, PrivateKeyDer, PrivatePkcs8KeyDer}; 10 | use futures_rustls::rustls::crypto::CryptoProvider; 11 | use futures_rustls::rustls::sign::CertifiedKey; 12 | use futures_rustls::rustls::ServerConfig; 13 | use rcgen::{CertificateParams, DistinguishedName, KeyPair, PKCS_ECDSA_P256_SHA256}; 14 | use std::convert::Infallible; 15 | use std::fmt::Debug; 16 | use std::future::Future; 17 | use std::pin::Pin; 18 | use std::sync::Arc; 19 | use std::task::{Context, Poll}; 20 | use std::time::Duration; 21 | use thiserror::Error; 22 | use x509_parser::parse_x509_certificate; 23 | 24 | #[allow(clippy::type_complexity)] 25 | pub struct AcmeState { 26 | config: Arc>, 27 | resolver: Arc, 28 | account_key: Option>, 29 | 30 | early_action: Option> + Send>>>, 31 | load_cert: Option>, EC>> + Send>>>, 32 | load_account: Option>, EA>> + Send>>>, 33 | order: Option, OrderError>> + Send>>>, 34 | backoff_cnt: usize, 35 | wait: Option, 36 | } 37 | 38 | impl fmt::Debug for AcmeState { 39 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 40 | f.debug_struct("AcmeState").field("config", &self.config).finish_non_exhaustive() 41 | } 42 | } 43 | 44 | pub type Event = Result>; 45 | 46 | #[derive(Debug)] 47 | pub enum EventOk { 48 | DeployedCachedCert, 49 | DeployedNewCert, 50 | CertCacheStore, 51 | AccountCacheStore, 52 | } 53 | 54 | #[derive(Error, Debug)] 55 | pub enum EventError { 56 | #[error("cert cache load: {0}")] 57 | CertCacheLoad(EC), 58 | #[error("account cache load: {0}")] 59 | AccountCacheLoad(EA), 60 | #[error("cert cache store: {0}")] 61 | CertCacheStore(EC), 62 | #[error("account cache store: {0}")] 63 | AccountCacheStore(EA), 64 | #[error("cached cert parse: {0}")] 65 | CachedCertParse(CertParseError), 66 | #[error("order: {0}")] 67 | Order(OrderError), 68 | #[error("new cert parse: {0}")] 69 | NewCertParse(CertParseError), 70 | } 71 | 72 | #[derive(Error, Debug)] 73 | pub enum OrderError { 74 | #[error("acme error: {0}")] 75 | Acme(#[from] AcmeError), 76 | #[error("certificate generation error: {0}")] 77 | Rcgen(#[from] rcgen::Error), 78 | #[error("bad order object: {0:?}")] 79 | BadOrder(Order), 80 | #[error("bad auth object: {0:?}")] 81 | BadAuth(Auth), 82 | #[error("authorization for {0} failed too many times")] 83 | TooManyAttemptsAuth(String), 84 | #[error("order status stayed on processing too long")] 85 | ProcessingTimeout(Order), 86 | } 87 | 88 | #[derive(Error, Debug)] 89 | pub enum CertParseError { 90 | #[error("X509 parsing error: {0}")] 91 | X509(#[from] x509_parser::nom::Err), 92 | #[error("expected 2 or more pem, got: {0}")] 93 | Pem(#[from] pem::PemError), 94 | #[error("expected 2 or more pem, got: {0}")] 95 | TooFewPem(usize), 96 | #[error("unsupported private key type")] 97 | InvalidPrivateKey, 98 | } 99 | 100 | impl AcmeState { 101 | pub fn incoming> + Unpin>( 102 | self, 103 | tcp_incoming: ITCP, 104 | alpn_protocols: Vec>, 105 | ) -> Incoming { 106 | #[allow(deprecated)] 107 | let acceptor = self.acceptor(); 108 | Incoming::new(tcp_incoming, self, acceptor, alpn_protocols) 109 | } 110 | #[deprecated(note = "please use high-level API via `AcmeState::incoming()` instead or refer to updated low-level API examples")] 111 | #[allow(deprecated)] 112 | pub fn acceptor(&self) -> AcmeAcceptor { 113 | AcmeAcceptor::new(self.resolver()) 114 | } 115 | #[cfg(feature = "tokio")] 116 | pub fn tokio_incoming< 117 | TokioTCP: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, 118 | ETCP, 119 | TokioITCP: Stream> + Unpin, 120 | >( 121 | self, 122 | tcp_incoming: TokioITCP, 123 | alpn_protocols: Vec>, 124 | ) -> crate::tokio::TokioIncoming< 125 | tokio_util::compat::Compat, 126 | ETCP, 127 | crate::tokio::TokioIncomingTcpWrapper, 128 | EC, 129 | EA, 130 | > { 131 | let tcp_incoming = crate::tokio::TokioIncomingTcpWrapper::from(tcp_incoming); 132 | crate::tokio::TokioIncoming::from(self.incoming(tcp_incoming, alpn_protocols)) 133 | } 134 | #[cfg(feature = "axum")] 135 | pub fn axum_acceptor(&self, rustls_config: Arc) -> crate::axum::AxumAcceptor { 136 | #[allow(deprecated)] 137 | crate::axum::AxumAcceptor::new(self.acceptor(), rustls_config) 138 | } 139 | 140 | #[cfg(feature = "tower")] 141 | pub fn http01_challenge_tower_service(&self) -> crate::tower::TowerHttp01ChallengeService { 142 | crate::tower::TowerHttp01ChallengeService(self.resolver.clone()) 143 | } 144 | 145 | pub fn resolver(&self) -> Arc { 146 | self.resolver.clone() 147 | } 148 | /// Creates a [rustls::ServerConfig] for TLS-ALPN-01 challenge connections. Use this if [crate::is_tls_alpn_challenge] returns `true`. 149 | #[cfg(any(feature = "ring", feature = "aws-lc-rs"))] 150 | pub fn challenge_rustls_config(&self) -> Arc { 151 | self.challenge_rustls_config_with_provider(crypto_provider().into()) 152 | } 153 | /// Same as [AcmeState::challenge_rustls_config], with a specific [CryptoProvider]. 154 | pub fn challenge_rustls_config_with_provider(&self, provider: Arc) -> Arc { 155 | let mut rustls_config = ServerConfig::builder_with_provider(provider) 156 | .with_safe_default_protocol_versions() 157 | .unwrap() 158 | .with_no_client_auth() 159 | .with_cert_resolver(self.resolver()); 160 | rustls_config.alpn_protocols.push(ACME_TLS_ALPN_NAME.to_vec()); 161 | Arc::new(rustls_config) 162 | } 163 | /// Creates a default [rustls::ServerConfig] for accepting regular tls connections. Use this if [crate::is_tls_alpn_challenge] returns `false`. 164 | /// If you need a [rustls::ServerConfig], which uses the certificates acquired by this [AcmeState], 165 | /// you may build your own using the output of [AcmeState::resolver]. 166 | #[cfg(any(feature = "ring", feature = "aws-lc-rs"))] 167 | pub fn default_rustls_config(&self) -> Arc { 168 | self.default_rustls_config_with_provider(crypto_provider().into()) 169 | } 170 | /// Same as [AcmeState::default_rustls_config], with a specific [CryptoProvider]. 171 | pub fn default_rustls_config_with_provider(&self, provider: Arc) -> Arc { 172 | let rustls_config = ServerConfig::builder_with_provider(provider) 173 | .with_safe_default_protocol_versions() 174 | .unwrap() 175 | .with_no_client_auth() 176 | .with_cert_resolver(self.resolver()); 177 | Arc::new(rustls_config) 178 | } 179 | pub fn new(config: AcmeConfig) -> Self { 180 | let config = Arc::new(config); 181 | Self { 182 | config: config.clone(), 183 | resolver: ResolvesServerCertAcme::new(), 184 | account_key: None, 185 | early_action: None, 186 | load_cert: Some(Box::pin({ 187 | let config = config.clone(); 188 | async move { config.cache.load_cert(&config.domains, &config.directory_url).await } 189 | })), 190 | load_account: Some(Box::pin({ 191 | let config = config.clone(); 192 | async move { config.cache.load_account(&config.contact, &config.directory_url).await } 193 | })), 194 | order: None, 195 | backoff_cnt: 0, 196 | wait: None, 197 | } 198 | } 199 | fn parse_cert(pem: &[u8]) -> Result<(CertifiedKey, [DateTime; 2]), CertParseError> { 200 | let mut pems = pem::parse_many(pem)?; 201 | if pems.len() < 2 { 202 | return Err(CertParseError::TooFewPem(pems.len())); 203 | } 204 | let pk = match any_ecdsa_type(&PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(pems.remove(0).contents()))) { 205 | Ok(pk) => pk, 206 | Err(_) => return Err(CertParseError::InvalidPrivateKey), 207 | }; 208 | let cert_chain: Vec = pems.into_iter().map(|p| RustlsCertificate::from(p.into_contents())).collect(); 209 | let validity = match parse_x509_certificate(&cert_chain[0]) { 210 | Ok((_, cert)) => { 211 | let validity = cert.validity(); 212 | [validity.not_before, validity.not_after].map(|t| Utc.timestamp_opt(t.timestamp(), 0).earliest().unwrap()) 213 | } 214 | Err(err) => return Err(CertParseError::X509(err)), 215 | }; 216 | let cert = CertifiedKey::new(cert_chain, pk); 217 | Ok((cert, validity)) 218 | } 219 | 220 | #[allow(clippy::result_large_err)] 221 | fn process_cert(&mut self, pem: Vec, cached: bool) -> Event { 222 | let (cert, validity) = match (Self::parse_cert(&pem), cached) { 223 | (Ok(r), _) => r, 224 | (Err(err), cached) => { 225 | return match cached { 226 | true => Err(EventError::CachedCertParse(err)), 227 | false => Err(EventError::NewCertParse(err)), 228 | } 229 | } 230 | }; 231 | self.resolver.set_cert(Arc::new(cert)); 232 | let wait_duration = (validity[1] - (validity[1] - validity[0]) / 3 - Utc::now()) 233 | .max(chrono::Duration::zero()) 234 | .to_std() 235 | .unwrap_or_default(); 236 | self.wait = Some(Timer::after(wait_duration)); 237 | if cached { 238 | return Ok(EventOk::DeployedCachedCert); 239 | } 240 | let config = self.config.clone(); 241 | self.early_action = Some(Box::pin(async move { 242 | match config.cache.store_cert(&config.domains, &config.directory_url, &pem).await { 243 | Ok(()) => Ok(EventOk::CertCacheStore), 244 | Err(err) => Err(EventError::CertCacheStore(err)), 245 | } 246 | })); 247 | Event::Ok(EventOk::DeployedNewCert) 248 | } 249 | async fn order(config: Arc>, resolver: Arc, key_pair: Vec) -> Result, OrderError> { 250 | let directory = Directory::discover(&config.client_config, &config.directory_url).await?; 251 | let account = Account::create_with_keypair(&config.client_config, directory, &config.contact, &key_pair).await?; 252 | 253 | let mut params = CertificateParams::new(config.domains.clone())?; 254 | params.distinguished_name = DistinguishedName::new(); 255 | let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; 256 | let csr = params.serialize_request(&key_pair)?; 257 | 258 | let (order_url, mut order) = account.new_order(&config.client_config, config.domains.clone()).await?; 259 | loop { 260 | match order.status { 261 | OrderStatus::Pending => { 262 | // Force in order authorizations to allow single global challenge data state 263 | for url in order.authorizations.iter() { 264 | Self::authorize(&config, &resolver, &account, url).await? 265 | } 266 | log::info!("completed all authorizations"); 267 | order = account.order(&config.client_config, &order_url).await?; 268 | } 269 | OrderStatus::Processing => { 270 | for i in 0u64..10 { 271 | log::info!("order processing"); 272 | Timer::after(Duration::from_secs(1u64 << i)).await; 273 | order = account.order(&config.client_config, &order_url).await?; 274 | if order.status != OrderStatus::Processing { 275 | break; 276 | } 277 | } 278 | if order.status == OrderStatus::Processing { 279 | return Err(OrderError::ProcessingTimeout(order)); 280 | } 281 | } 282 | OrderStatus::Ready => { 283 | log::info!("sending csr"); 284 | order = account.finalize(&config.client_config, order.finalize, csr.der()).await? 285 | } 286 | OrderStatus::Valid { certificate } => { 287 | log::info!("download certificate"); 288 | let pem = [ 289 | &key_pair.serialize_pem(), 290 | "\n", 291 | &account.certificate(&config.client_config, certificate).await?, 292 | ] 293 | .concat(); 294 | return Ok(pem.into_bytes()); 295 | } 296 | OrderStatus::Invalid => return Err(OrderError::BadOrder(order)), 297 | } 298 | } 299 | } 300 | async fn authorize(config: &AcmeConfig, resolver: &ResolvesServerCertAcme, account: &Account, url: &String) -> Result<(), OrderError> { 301 | let auth = account.auth(&config.client_config, url).await?; 302 | let (domain, challenge_url) = match auth.status { 303 | AuthStatus::Pending => { 304 | let Identifier::Dns(domain) = auth.identifier; 305 | log::info!("trigger challenge for {}", &domain); 306 | let challenge = match config.challenge_type { 307 | UseChallenge::Http01 => { 308 | let (challenge, key_auth) = account.http_01(&auth.challenges)?; 309 | resolver.set_http_01_challenge_data(challenge.token.clone(), key_auth); 310 | challenge 311 | } 312 | UseChallenge::TlsAlpn01 => { 313 | let (challenge, auth_key) = account.tls_alpn_01(&auth.challenges, domain.clone())?; 314 | resolver.set_tls_alpn_01_challenge_data(domain.clone(), Arc::new(auth_key)); 315 | challenge 316 | } 317 | }; 318 | account.challenge(&config.client_config, &challenge.url).await?; 319 | (domain, challenge.url.clone()) 320 | } 321 | AuthStatus::Valid => { 322 | // clear challenge data when auth validated 323 | resolver.clear_challenge_data(); 324 | return Ok(()); 325 | } 326 | _ => { 327 | // clear challenge data when auth invalidated 328 | resolver.clear_challenge_data(); 329 | return Err(OrderError::BadAuth(auth)); 330 | } 331 | }; 332 | for i in 0u64..5 { 333 | Timer::after(Duration::from_secs(1u64 << i)).await; 334 | let auth = account.auth(&config.client_config, url).await?; 335 | match auth.status { 336 | AuthStatus::Pending => { 337 | log::info!("authorization for {} still pending", &domain); 338 | account.challenge(&config.client_config, &challenge_url).await? 339 | } 340 | AuthStatus::Valid => { 341 | // clear challenge data when auth validated 342 | resolver.clear_challenge_data(); 343 | return Ok(()); 344 | } 345 | _ => { 346 | // clear challenge data when auth invalidated 347 | resolver.clear_challenge_data(); 348 | return Err(OrderError::BadAuth(auth)); 349 | } 350 | } 351 | } 352 | Err(OrderError::TooManyAttemptsAuth(domain)) 353 | } 354 | fn poll_next_infinite(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 355 | loop { 356 | // queued early action 357 | if let Some(early_action) = &mut self.early_action { 358 | let result = ready!(early_action.poll_unpin(cx)); 359 | self.early_action.take(); 360 | return Poll::Ready(result); 361 | } 362 | 363 | // sleep 364 | if let Some(timer) = &mut self.wait { 365 | ready!(timer.poll_unpin(cx)); 366 | self.wait.take(); 367 | } 368 | 369 | // load from cert cache 370 | if let Some(load_cert) = &mut self.load_cert { 371 | let result = ready!(load_cert.poll_unpin(cx)); 372 | self.load_cert.take(); 373 | match result { 374 | Ok(Some(pem)) => { 375 | return Poll::Ready(Self::process_cert(self.get_mut(), pem, true)); 376 | } 377 | Ok(None) => {} 378 | Err(err) => return Poll::Ready(Err(EventError::CertCacheLoad(err))), 379 | } 380 | } 381 | 382 | // load from account cache 383 | if let Some(load_account) = &mut self.load_account { 384 | let result = ready!(load_account.poll_unpin(cx)); 385 | self.load_account.take(); 386 | match result { 387 | Ok(Some(key_pair)) => self.account_key = Some(key_pair), 388 | Ok(None) => {} 389 | Err(err) => return Poll::Ready(Err(EventError::AccountCacheLoad(err))), 390 | } 391 | } 392 | 393 | // execute order 394 | if let Some(order) = &mut self.order { 395 | let result = ready!(order.poll_unpin(cx)); 396 | self.order.take(); 397 | match result { 398 | Ok(pem) => { 399 | self.backoff_cnt = 0; 400 | return Poll::Ready(Self::process_cert(self.get_mut(), pem, false)); 401 | } 402 | Err(err) => { 403 | // TODO: replace key on some errors or high backoff_cnt? 404 | self.wait = Some(Timer::after(Duration::from_secs(1 << self.backoff_cnt))); 405 | self.backoff_cnt = (self.backoff_cnt + 1).min(16); 406 | return Poll::Ready(Err(EventError::Order(err))); 407 | } 408 | } 409 | } 410 | 411 | // schedule order 412 | let account_key = match &self.account_key { 413 | None => { 414 | let account_key = Account::generate_key_pair(); 415 | self.account_key = Some(account_key.clone()); 416 | let config = self.config.clone(); 417 | let account_key_clone = account_key.clone(); 418 | self.early_action = Some(Box::pin(async move { 419 | match config 420 | .cache 421 | .store_account(&config.contact, &config.directory_url, &account_key_clone) 422 | .await 423 | { 424 | Ok(()) => Ok(EventOk::AccountCacheStore), 425 | Err(err) => Err(EventError::AccountCacheStore(err)), 426 | } 427 | })); 428 | account_key 429 | } 430 | Some(account_key) => account_key.clone(), 431 | }; 432 | let config = self.config.clone(); 433 | let resolver = self.resolver.clone(); 434 | self.order = Some(Box::pin(Self::order(config.clone(), resolver.clone(), account_key))); 435 | } 436 | } 437 | } 438 | 439 | impl Stream for AcmeState { 440 | type Item = Event; 441 | 442 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 443 | Poll::Ready(Some(ready!(self.poll_next_infinite(cx)))) 444 | } 445 | } 446 | -------------------------------------------------------------------------------- /src/tokio.rs: -------------------------------------------------------------------------------- 1 | use crate::Incoming; 2 | use futures::{AsyncRead, AsyncWrite, Stream}; 3 | use futures_rustls::server::TlsStream; 4 | use std::fmt::Debug; 5 | use std::pin::Pin; 6 | use std::task::{Context, Poll}; 7 | use tokio_util::compat::FuturesAsyncReadCompatExt; 8 | use tokio_util::compat::TokioAsyncReadCompatExt; 9 | 10 | pub struct TokioIncomingTcpWrapper< 11 | TokioTCP: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, 12 | ETCP, 13 | TokioITCP: Stream> + Unpin, 14 | > { 15 | incoming_tcp: TokioITCP, 16 | } 17 | 18 | impl> + Unpin> 19 | TokioIncomingTcpWrapper 20 | { 21 | pub fn into_inner(self) -> TokioITCP { 22 | self.incoming_tcp 23 | } 24 | } 25 | 26 | impl> + Unpin> Stream 27 | for TokioIncomingTcpWrapper 28 | { 29 | type Item = Result, ETCP>; 30 | 31 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 32 | match Pin::new(&mut self.incoming_tcp).poll_next(cx) { 33 | Poll::Ready(Some(Ok(tcp))) => Poll::Ready(Some(Ok(tcp.compat()))), 34 | Poll::Ready(Some(Err(err))) => Poll::Ready(Some(Err(err))), 35 | Poll::Ready(None) => Poll::Ready(None), 36 | Poll::Pending => Poll::Pending, 37 | } 38 | } 39 | } 40 | 41 | impl> + Unpin> From 42 | for TokioIncomingTcpWrapper 43 | { 44 | fn from(incoming_tcp: TokioITCP) -> Self { 45 | Self { incoming_tcp } 46 | } 47 | } 48 | 49 | pub struct TokioIncoming< 50 | TCP: AsyncRead + AsyncWrite + Unpin, 51 | ETCP, 52 | ITCP: Stream> + Unpin, 53 | EC: Debug + 'static, 54 | EA: Debug + 'static, 55 | > { 56 | incoming: Incoming, 57 | } 58 | 59 | impl> + Unpin, EC: Debug + 'static, EA: Debug + 'static> Stream 60 | for TokioIncoming 61 | { 62 | type Item = Result>, ETCP>; 63 | 64 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 65 | match Pin::new(&mut self.incoming).poll_next(cx) { 66 | Poll::Ready(Some(Ok(tls))) => Poll::Ready(Some(Ok(tls.compat()))), 67 | Poll::Ready(Some(Err(err))) => Poll::Ready(Some(Err(err))), 68 | Poll::Ready(None) => Poll::Ready(None), 69 | Poll::Pending => Poll::Pending, 70 | } 71 | } 72 | } 73 | 74 | impl> + Unpin, EC: Debug + 'static, EA: Debug + 'static> 75 | From> for TokioIncoming 76 | { 77 | fn from(incoming: Incoming) -> Self { 78 | Self { incoming } 79 | } 80 | } 81 | 82 | impl> + Unpin, EC: Debug + 'static, EA: Debug + 'static> 83 | From> for Incoming 84 | { 85 | fn from(tokio_incoming: TokioIncoming) -> Self { 86 | tokio_incoming.incoming 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/tower.rs: -------------------------------------------------------------------------------- 1 | use crate::ResolvesServerCertAcme; 2 | use http::{header, HeaderValue, Request, StatusCode}; 3 | use std::sync::Arc; 4 | 5 | #[derive(Clone)] 6 | pub struct TowerHttp01ChallengeService(pub(crate) Arc); 7 | 8 | impl tower_service::Service> for TowerHttp01ChallengeService { 9 | type Response = http::Response; 10 | type Error = std::convert::Infallible; 11 | type Future = std::future::Ready>; 12 | 13 | fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> std::task::Poll> { 14 | std::task::Poll::Ready(Ok(())) 15 | } 16 | 17 | fn call(&mut self, req: Request) -> Self::Future { 18 | let mut response = http::Response::new(String::new()); 19 | *response.status_mut() = StatusCode::NOT_FOUND; 20 | let Some((_, token)) = req.uri().path().rsplit_once('/') else { 21 | return std::future::ready(Ok(response)); 22 | }; 23 | let Some(body) = self.0.get_http_01_key_auth(token) else { 24 | return std::future::ready(Ok(response)); 25 | }; 26 | *response.status_mut() = StatusCode::OK; 27 | *response.body_mut() = body; 28 | response 29 | .headers_mut() 30 | .append(header::CONTENT_TYPE, HeaderValue::from_static("application/octet-stream")); 31 | std::future::ready(Ok(response)) 32 | } 33 | } 34 | --------------------------------------------------------------------------------