├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── high_level.rs ├── high_level_warp.rs ├── low_level.rs └── low_level_axum.rs └── src ├── acceptor.rs ├── acme.rs ├── axum.rs ├── cache.rs ├── caches ├── boxed.rs ├── composite.rs ├── dir.rs ├── mod.rs ├── no.rs └── test.rs ├── config.rs ├── https_helper.rs ├── incoming.rs ├── jose.rs ├── lib.rs ├── resolver.rs └── state.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | pull_request: 5 | 6 | 7 | concurrency: 8 | group: tests-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 9 | cancel-in-progress: true 10 | 11 | env: 12 | MSRV: "1.63" 13 | RUST_BACKTRACE: 1 14 | RUSTFLAGS: -Dwarnings 15 | SCCACHE_GHA_ENABLED: "on" 16 | 17 | jobs: 18 | lint: 19 | runs-on: ubuntu-latest 20 | env: 21 | RUSTC_WRAPPER: "sccache" 22 | steps: 23 | - uses: actions/checkout@v4 24 | - uses: dtolnay/rust-toolchain@stable 25 | - uses: mozilla-actions/sccache-action@v0.0.9 26 | - name: cargo fmt 27 | run: cargo fmt --all -- --check 28 | - name: cargo clippy 29 | run: cargo clippy --workspace --all-targets --all-features 30 | 31 | test: 32 | runs-on: ${{ matrix.target.os }} 33 | strategy: 34 | fail-fast: false 35 | matrix: 36 | target: 37 | - os: "ubuntu-latest" 38 | toolchain: "x86_64-unknown-linux-gnu" 39 | name: "Linux GNU" 40 | - os: "macOS-latest" 41 | toolchain: "x86_64-apple-darwin" 42 | name: "macOS" 43 | - os: "windows-latest" 44 | toolchain: "x86_64-pc-windows-msvc" 45 | name: "Windows MSVC" 46 | - os: "windows-latest" 47 | toolchain: "x86_64-pc-windows-gnu" 48 | name: "Windows GNU" 49 | channel: 50 | - "stable" 51 | env: 52 | RUSTC_WRAPPER: "sccache" 53 | steps: 54 | - uses: actions/checkout@v4 55 | - uses: dtolnay/rust-toolchain@master 56 | with: 57 | toolchain: ${{ matrix.channel }} 58 | targets: ${{ matrix.target.toolchain }} 59 | - uses: mozilla-actions/sccache-action@v0.0.9 60 | - name: cargo test 61 | run: cargo test --workspace --all-features --bins --tests --examples 62 | 63 | # Checks correct runtime deps and features are requested by not including dev-dependencies. 64 | check-deps: 65 | runs-on: ubuntu-latest 66 | env: 67 | RUSTC_WRAPPER: "sccache" 68 | steps: 69 | - uses: actions/checkout@v4 70 | - uses: dtolnay/rust-toolchain@stable 71 | - uses: mozilla-actions/sccache-action@v0.0.9 72 | - name: cargo check 73 | run: cargo check --workspace --all-features --lib --bins 74 | 75 | minimal-crates: 76 | runs-on: ubuntu-latest 77 | env: 78 | RUSTC_WRAPPER: "sccache" 79 | steps: 80 | - uses: actions/checkout@v4 81 | - uses: dtolnay/rust-toolchain@nightly 82 | - uses: mozilla-actions/sccache-action@v0.0.9 83 | - name: cargo check 84 | run: | 85 | rm -f Cargo.lock 86 | cargo +nightly check -Z minimal-versions --workspace --all-features --lib --bins 87 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /Cargo.lock 2 | /target 3 | /.idea 4 | /cache 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tokio-rustls-acme" 3 | version = "0.7.1" 4 | authors = [ 5 | "dignifiedquire ", 6 | "Florian Uekermann ", 7 | ] 8 | edition = "2018" 9 | description = "Automatic TLS certificate management using rustls" 10 | license = "Apache-2.0 OR MIT" 11 | repository = "https://github.com/n0-computer/tokio-rustls-acme" 12 | documentation = "https://docs.rs/tokio-rustls-acme" 13 | keywords = ["acme", "rustls", "tls", "letsencrypt"] 14 | categories = ["asynchronous", "cryptography", "network-programming"] 15 | 16 | [dependencies] 17 | futures = "0.3.21" 18 | rcgen = "0.13" 19 | serde_json = "1.0.81" 20 | serde = { version = "1.0.137", features = ["derive"] } 21 | ring = { version = "0.17.0", features = ["std"] } 22 | base64 = "0.22" 23 | log = "0.4.17" 24 | webpki-roots = "0.26" 25 | pem = "3.0" 26 | thiserror = "2.0" 27 | x509-parser = "0.16" 28 | chrono = { version = "0.4.24", default-features = false, features = ["clock"] } 29 | async-trait = "0.1.53" 30 | rustls = { version = "0.23", default-features = false, features = ["ring"] } 31 | time = "0.3.36" # force the transitive dependency to a more recent minimal version. The build fails with 0.3.20 32 | 33 | tokio = { version = "1.20.1", default-features = false } 34 | tokio-rustls = { version = "0.26", default-features = false, features = [ 35 | "tls12", 36 | ] } 37 | reqwest = { version = "0.12", default-features = false, features = [ 38 | "rustls-tls", 39 | ] } 40 | 41 | # Axum 42 | axum-server = { version = "0.7", features = ["tokio-rustls"], optional = true } 43 | 44 | [dependencies.proc-macro2] 45 | # This is a transitive dependency, we specify it to make sure we have 46 | # a recent-enough version so that -Z minimal-versions crate resolution 47 | # works. 48 | version = "1.0.78" 49 | 50 | [dependencies.num-bigint] 51 | # This is a transitive dependency, we specify it to make sure we have 52 | # a recent-enough version so that -Z minimal-versions crate resolution 53 | # works. 54 | version = "0.4.4" 55 | 56 | [dev-dependencies] 57 | simple_logger = "5.0" 58 | structopt = "0.3.26" 59 | clap = { version = "4", features = ["derive"] } 60 | axum = "0.8" 61 | tokio = { version = "1.19.2", features = ["full"] } 62 | tokio-stream = { version = "0.1.9", features = ["net"] } 63 | tokio-util = { version = "0.7.3", features = ["compat"] } 64 | warp = "0.3" 65 | 66 | [package.metadata.docs.rs] 67 | all-features = true 68 | rustdoc-args = ["--cfg", "doc_auto_cfg"] 69 | 70 | [features] 71 | default = [] 72 | axum = ["dep:axum-server"] 73 | 74 | [[example]] 75 | name = "low_level_axum" 76 | required-features = ["axum"] 77 | 78 | [[example]] 79 | name = "high_level_warp" 80 | 81 | [[example]] 82 | name = "high_level" 83 | 84 | [[example]] 85 | name = "low_level" 86 | -------------------------------------------------------------------------------- /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 |

tokio-rustls-acme

2 |
3 | 4 | Automatic TLS certificate management using rustls with ring. 5 | 6 |
7 | 8 |
9 | 10 |
11 | 12 | 13 | Crates.io version 15 | 16 | 17 | 18 | Download 20 | 21 | 22 | 23 | docs.rs docs 25 | 26 |
27 | 28 |
29 |

30 | 31 | API Docs 32 | 33 |

34 |
35 |
36 | 37 | > Original implementation based on https://github.com/FlorianUekermann/rustls-acme. 38 | 39 | An easy-to-use, async compatible [ACME] client library using [rustls] with [ring]. 40 | The validation mechanism used is tls-alpn-01, which allows serving acme challenge responses and 41 | regular TLS traffic on the same port. 42 | 43 | Is designed to use the tokio runtime, if you need support for other runtimes take a look 44 | at the original implementation [rustls-acme](https://github.com/FlorianUekermann/rustls-acme). 45 | 46 | No persistent tasks are spawned under the hood and the certificate acquisition/renewal process 47 | is folded into the streams and futures being polled by the library user. 48 | 49 | The goal is to provide a [Let's Encrypt](https://letsencrypt.org/) compatible TLS serving and 50 | certificate management using a simple and flexible stream based API. 51 | 52 | This crate uses [ring] as [rustls]'s backend, instead of [aws-lc-rs]. This generally makes it 53 | much easier to compile. If you'd like to use [aws-lc-rs] as [rustls]'s backend, we're open to 54 | contributions with the necessary `Cargo.toml` changes and feature-flags to enable you to do so. 55 | 56 | To use tokio-rustls-acme add the following lines to your `Cargo.toml`: 57 | 58 | ```toml 59 | [dependencies] 60 | tokio-rustls-acme = "*" 61 | ``` 62 | 63 | ## High-level API 64 | 65 | The high-level API consists of a single stream `Incoming` of incoming TLS connection. 66 | Polling the next future of the stream takes care of acquisition and renewal of certificates, as 67 | well as accepting TLS connections, which are handed over to the caller on success. 68 | 69 | ```rust 70 | use tokio::io::AsyncWriteExt; 71 | use futures::StreamExt; 72 | use tokio_rustls_acme::{AcmeConfig, caches::DirCache}; 73 | use tokio_stream::wrappers::TcpListenerStream; 74 | 75 | #[tokio::main] 76 | async fn main() { 77 | simple_logger::init_with_level(log::Level::Info).unwrap(); 78 | 79 | let tcp_listener = tokio::net::TcpListener::bind("[::]:443").await.unwrap(); 80 | let tcp_incoming = TcpListenerStream::new(tcp_listener); 81 | 82 | let mut tls_incoming = AcmeConfig::new(["example.com"]) 83 | .contact_push("mailto:admin@example.com") 84 | .cache(DirCache::new("./rustls_acme_cache")) 85 | .incoming(tcp_incoming, Vec::new()); 86 | 87 | while let Some(tls) = tls_incoming.next().await { 88 | let mut tls = tls.unwrap(); 89 | tokio::spawn(async move { 90 | tls.write_all(HELLO).await.unwrap(); 91 | tls.shutdown().await.unwrap(); 92 | }); 93 | } 94 | } 95 | 96 | const HELLO: &'static [u8] = br#"HTTP/1.1 200 OK 97 | Content-Length: 11 98 | Content-Type: text/plain; charset=utf-8 99 | 100 | Hello Tls!"#; 101 | ``` 102 | 103 | `examples/high_level.rs` implements a "Hello Tls!" server similar to the one above, which accepts 104 | domain, port and cache directory parameters. 105 | 106 | Note that all examples use the let's encrypt staging directory by default. 107 | The production directory imposes strict rate limits, which are easily exhausted accidentally 108 | during testing and development. 109 | For testing with the staging directory you may open `https://:` in a browser 110 | that allows TLS connections to servers signed by an untrusted CA (in Firefox click "Advanced..." 111 | -> "Accept the Risk and Continue"). 112 | 113 | ## Low-level Rustls API 114 | 115 | For users who may want to interact with [`rustls`] or [`tokio-rustls`] 116 | directly, the library exposes the underlying certificate management `AcmeState` as well as a 117 | matching resolver `ResolvesServerCertAcme` which implements the `rustls::server::ResolvesServerCert` trait. 118 | See the `server_low_level` example on how to use the low-level API directly with [`tokio-rustls`]. 119 | 120 | ## Account and certificate caching 121 | 122 | A production server using the let's encrypt production directory must implement both account and 123 | certificate caching to avoid exhausting the let's encrypt API rate limits. 124 | A file based cache using a cache directory is provided by `caches::DirCache`. 125 | Caches backed by other persistence layers may be implemented using the `Cache` trait, 126 | or the underlying `CertCache`, `AccountCache` traits (contributions welcome). 127 | `caches::CompositeCache` provides a wrapper to combine two implementors of `CertCache` and 128 | `AccountCache` into a single `Cache`. 129 | 130 | Note, that the error type parameters of the cache carries over to some other types in this 131 | crate via the `AcmeConfig` they are added to. 132 | If you want to avoid different specializations based on cache type use the 133 | `AcmeConfig::cache_with_boxed_err` method to construct the an `AcmeConfig` object. 134 | 135 | 136 | ## The acme module 137 | 138 | The underlying implementation of an async acme client may be useful to others and is exposed as 139 | a module. It is incomplete (contributions welcome) and not covered by any stability 140 | promises. 141 | 142 | ## Special thanks 143 | 144 | This crate was inspired by the [autocert](https://golang.org/x/crypto/acme/autocert/) 145 | package for [Go](https://golang.org). 146 | 147 | The original implementation of this crate can be found at [FlorianUekermann/rustls-acme](https://github.com/FlorianUekermann/rustls-acme/commits/main), this is just a version focused on supporting only tokio. 148 | 149 | This crate also builds on the excellent work of the authors of 150 | [`rustls`](https://github.com/ctz/rustls), 151 | [`tokio-rustls`](https://github.com/tokio-rs/tls/tree/master/tokio-rustls) and many others. 152 | 153 | 154 | # License 155 | 156 | This project is licensed under either of 157 | 158 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or 159 | http://www.apache.org/licenses/LICENSE-2.0) 160 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or 161 | http://opensource.org/licenses/MIT) 162 | 163 | at your option. 164 | 165 | ### Contribution 166 | 167 | Unless you explicitly state otherwise, any contribution intentionally submitted 168 | for inclusion in this project by you, as defined in the Apache-2.0 license, 169 | shall be dual licensed as above, without any additional terms or conditions. 170 | 171 | 172 | [ACME]: https://en.wikipedia.org/wiki/Automatic_Certificate_Management_Environment 173 | [ring]: https://github.com/briansmith/ring 174 | [rustls]: https://github.com/ctz/rustls 175 | [aws-lc-rs]: https://github.com/aws/aws-lc-rs 176 | -------------------------------------------------------------------------------- /examples/high_level.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use std::net::Ipv6Addr; 3 | use std::path::PathBuf; 4 | use tokio::io::AsyncWriteExt; 5 | use tokio_rustls_acme::caches::DirCache; 6 | use tokio_rustls_acme::AcmeConfig; 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)] 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)) 39 | .await 40 | .unwrap(); 41 | let tcp_incoming = TcpListenerStream::new(tcp_listener); 42 | 43 | let mut tls_incoming = AcmeConfig::new(args.domains) 44 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 45 | .cache_option(args.cache.clone().map(DirCache::new)) 46 | .directory_lets_encrypt(args.prod) 47 | .incoming(tcp_incoming, Vec::new()); 48 | 49 | while let Some(tls) = tls_incoming.next().await { 50 | let mut tls = tls.unwrap(); 51 | tokio::spawn(async move { 52 | tls.write_all(HELLO).await.unwrap(); 53 | tls.shutdown().await.unwrap(); 54 | }); 55 | } 56 | unreachable!() 57 | } 58 | 59 | const HELLO: &[u8] = br#"HTTP/1.1 200 OK 60 | Content-Length: 10 61 | Content-Type: text/plain; charset=utf-8 62 | 63 | Hello Tls!"#; 64 | -------------------------------------------------------------------------------- /examples/high_level_warp.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use std::net::Ipv6Addr; 3 | use std::path::PathBuf; 4 | use tokio_rustls_acme::caches::DirCache; 5 | use tokio_rustls_acme::AcmeConfig; 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)] 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)) 38 | .await 39 | .unwrap(); 40 | let tcp_incoming = TcpListenerStream::new(tcp_listener); 41 | 42 | let tls_incoming = AcmeConfig::new(args.domains) 43 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 44 | .cache_option(args.cache.clone().map(DirCache::new)) 45 | .directory_lets_encrypt(args.prod) 46 | .incoming(tcp_incoming, Vec::new()); 47 | 48 | let route = warp::any().map(|| "Hello Tls!"); 49 | warp::serve(route).run_incoming(tls_incoming).await; 50 | 51 | unreachable!() 52 | } 53 | -------------------------------------------------------------------------------- /examples/low_level.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use rustls::ServerConfig; 3 | use std::net::Ipv6Addr; 4 | use std::path::PathBuf; 5 | use std::sync::Arc; 6 | use tokio::io::AsyncWriteExt; 7 | use tokio_rustls_acme::caches::DirCache; 8 | use tokio_rustls_acme::{AcmeAcceptor, AcmeConfig}; 9 | use tokio_stream::StreamExt; 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)] 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 | #[tokio::main] 35 | async fn main() { 36 | simple_logger::init_with_level(log::Level::Info).unwrap(); 37 | let args = Args::parse(); 38 | 39 | let mut state = AcmeConfig::new(args.domains) 40 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 41 | .cache_option(args.cache.clone().map(DirCache::new)) 42 | .directory_lets_encrypt(args.prod) 43 | .state(); 44 | let rustls_config = ServerConfig::builder() 45 | .with_no_client_auth() 46 | .with_cert_resolver(state.resolver()); 47 | let acceptor = state.acceptor(); 48 | 49 | tokio::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 | 58 | serve(acceptor, Arc::new(rustls_config), args.port).await; 59 | } 60 | 61 | async fn serve(acceptor: AcmeAcceptor, rustls_config: Arc, port: u16) { 62 | let listener = tokio::net::TcpListener::bind((Ipv6Addr::UNSPECIFIED, port)) 63 | .await 64 | .unwrap(); 65 | loop { 66 | let tcp = listener.accept().await.unwrap().0; 67 | let rustls_config = rustls_config.clone(); 68 | let accept_future = acceptor.accept(tcp); 69 | 70 | tokio::spawn(async move { 71 | match accept_future.await.unwrap() { 72 | None => log::info!("received TLS-ALPN-01 validation request"), 73 | Some(start_handshake) => { 74 | let mut tls = start_handshake.into_stream(rustls_config).await.unwrap(); 75 | tls.write_all(HELLO).await.unwrap(); 76 | tls.shutdown().await.unwrap(); 77 | } 78 | } 79 | }); 80 | } 81 | } 82 | 83 | const HELLO: &[u8] = br#"HTTP/1.1 200 OK 84 | Content-Length: 10 85 | Content-Type: text/plain; charset=utf-8 86 | 87 | Hello Tls!"#; 88 | -------------------------------------------------------------------------------- /examples/low_level_axum.rs: -------------------------------------------------------------------------------- 1 | use axum::{routing::get, Router}; 2 | use clap::Parser; 3 | use rustls::ServerConfig; 4 | use std::net::{Ipv6Addr, SocketAddr}; 5 | use std::path::PathBuf; 6 | use std::sync::Arc; 7 | use tokio_rustls_acme::caches::DirCache; 8 | use tokio_rustls_acme::AcmeConfig; 9 | use tokio_stream::StreamExt; 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)] 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 | #[tokio::main] 35 | async fn main() { 36 | simple_logger::init_with_level(log::Level::Info).unwrap(); 37 | let args = Args::parse(); 38 | 39 | let mut state = AcmeConfig::new(args.domains) 40 | .contact(args.email.iter().map(|e| format!("mailto:{}", e))) 41 | .cache_option(args.cache.clone().map(DirCache::new)) 42 | .directory_lets_encrypt(args.prod) 43 | .state(); 44 | let rustls_config = ServerConfig::builder() 45 | .with_no_client_auth() 46 | .with_cert_resolver(state.resolver()); 47 | let acceptor = state.axum_acceptor(Arc::new(rustls_config)); 48 | 49 | tokio::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 | 58 | let app = Router::new().route("/", get(|| async { "Hello Tls!" })); 59 | 60 | let addr = SocketAddr::from((Ipv6Addr::UNSPECIFIED, args.port)); 61 | axum_server::bind(addr) 62 | .acceptor(acceptor) 63 | .serve(app.into_make_service()) 64 | .await 65 | .unwrap(); 66 | } 67 | -------------------------------------------------------------------------------- /src/acceptor.rs: -------------------------------------------------------------------------------- 1 | use crate::acme::ACME_TLS_ALPN_NAME; 2 | use crate::ResolvesServerCertAcme; 3 | use rustls::server::Acceptor; 4 | use rustls::ServerConfig; 5 | use std::future::Future; 6 | use std::io; 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_rustls::{Accept, LazyConfigAcceptor, StartHandshake}; 12 | 13 | #[derive(Clone)] 14 | pub struct AcmeAcceptor { 15 | config: Arc, 16 | } 17 | 18 | impl AcmeAcceptor { 19 | pub(crate) fn new(resolver: Arc) -> Self { 20 | let mut config = ServerConfig::builder() 21 | .with_no_client_auth() 22 | .with_cert_resolver(resolver); 23 | config.alpn_protocols.push(ACME_TLS_ALPN_NAME.to_vec()); 24 | Self { 25 | config: Arc::new(config), 26 | } 27 | } 28 | pub fn accept(&self, io: IO) -> AcmeAccept { 29 | AcmeAccept::new(io, self.config.clone()) 30 | } 31 | } 32 | 33 | pub struct AcmeAccept { 34 | acceptor: LazyConfigAcceptor, 35 | config: Arc, 36 | validation_accept: Option>, 37 | } 38 | 39 | impl AcmeAccept { 40 | pub(crate) fn new(io: IO, config: Arc) -> Self { 41 | Self { 42 | acceptor: LazyConfigAcceptor::new(Acceptor::default(), io), 43 | config, 44 | validation_accept: None, 45 | } 46 | } 47 | } 48 | 49 | impl Future for AcmeAccept { 50 | type Output = io::Result>>; 51 | 52 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 53 | loop { 54 | if let Some(validation_accept) = &mut self.validation_accept { 55 | return match Pin::new(validation_accept).poll(cx) { 56 | Poll::Ready(Ok(_)) => Poll::Ready(Ok(None)), 57 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 58 | Poll::Pending => Poll::Pending, 59 | }; 60 | } 61 | 62 | return match Pin::new(&mut self.acceptor).poll(cx) { 63 | Poll::Ready(Ok(handshake)) => { 64 | let is_validation = handshake 65 | .client_hello() 66 | .alpn() 67 | .into_iter() 68 | .flatten() 69 | .eq([ACME_TLS_ALPN_NAME]); 70 | if is_validation { 71 | self.validation_accept = Some(handshake.into_stream(self.config.clone())); 72 | continue; 73 | } 74 | Poll::Ready(Ok(Some(handshake))) 75 | } 76 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 77 | Poll::Pending => Poll::Pending, 78 | }; 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/acme.rs: -------------------------------------------------------------------------------- 1 | use std::sync::Arc; 2 | 3 | use crate::https_helper::{https, HttpsRequestError, Method, Response}; 4 | use crate::jose::{key_authorization_sha256, sign, sign_eab, JoseError}; 5 | use base64::engine::general_purpose::URL_SAFE_NO_PAD; 6 | use base64::Engine; 7 | use rcgen::{CustomExtension, Error as RcgenError, PKCS_ECDSA_P256_SHA256}; 8 | use ring::error::{KeyRejected, Unspecified}; 9 | use ring::rand::SystemRandom; 10 | use ring::signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, ECDSA_P256_SHA256_FIXED_SIGNING}; 11 | use rustls::{crypto::ring::sign::any_ecdsa_type, sign::CertifiedKey}; 12 | use rustls::{ 13 | pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}, 14 | ClientConfig, 15 | }; 16 | use serde::{Deserialize, Serialize}; 17 | use serde_json::json; 18 | use thiserror::Error; 19 | 20 | pub const LETS_ENCRYPT_STAGING_DIRECTORY: &str = 21 | "https://acme-staging-v02.api.letsencrypt.org/directory"; 22 | pub const LETS_ENCRYPT_PRODUCTION_DIRECTORY: &str = 23 | "https://acme-v02.api.letsencrypt.org/directory"; 24 | pub const ACME_TLS_ALPN_NAME: &[u8] = b"acme-tls/1"; 25 | 26 | #[derive(Debug)] 27 | pub struct Account { 28 | pub key_pair: EcdsaKeyPair, 29 | pub directory: Directory, 30 | pub kid: String, 31 | } 32 | 33 | static ALG: &EcdsaSigningAlgorithm = &ECDSA_P256_SHA256_FIXED_SIGNING; 34 | 35 | impl Account { 36 | pub fn generate_key_pair() -> Vec { 37 | let rng = SystemRandom::new(); 38 | let pkcs8 = EcdsaKeyPair::generate_pkcs8(ALG, &rng).unwrap(); 39 | pkcs8.as_ref().to_vec() 40 | } 41 | pub async fn create<'a, S, I>( 42 | client_config: &Arc, 43 | directory: Directory, 44 | contact: I, 45 | eab: &Option, 46 | ) -> Result 47 | where 48 | S: AsRef + 'a, 49 | I: IntoIterator, 50 | { 51 | let key_pair = Self::generate_key_pair(); 52 | Self::create_with_keypair(client_config, directory, contact, &key_pair, eab).await 53 | } 54 | pub async fn create_with_keypair<'a, S, I>( 55 | client_config: &Arc, 56 | directory: Directory, 57 | contact: I, 58 | key_pair: &[u8], 59 | eab: &Option, 60 | ) -> Result 61 | where 62 | S: AsRef + 'a, 63 | I: IntoIterator, 64 | { 65 | let key_pair = EcdsaKeyPair::from_pkcs8(ALG, key_pair, &SystemRandom::new())?; 66 | let contact: Vec<&'a str> = contact.into_iter().map(AsRef::::as_ref).collect(); 67 | 68 | let payload = if let Some(eab) = &eab.as_ref() { 69 | let eab_body = sign_eab(&key_pair, &eab.key, &eab.kid, &directory.new_account)?; 70 | 71 | json!({ 72 | "termsOfServiceAgreed": true, 73 | "contact": contact, 74 | "externalAccountBinding": eab_body, 75 | }) 76 | } else { 77 | json!({ 78 | "termsOfServiceAgreed": true, 79 | "contact": contact, 80 | }) 81 | } 82 | .to_string(); 83 | 84 | let body = sign( 85 | &key_pair, 86 | None, 87 | directory.nonce(client_config).await?, 88 | &directory.new_account, 89 | &payload, 90 | )?; 91 | let response = https( 92 | client_config, 93 | &directory.new_account, 94 | Method::Post, 95 | Some(body), 96 | ) 97 | .await?; 98 | let kid = get_header(&response, "Location")?; 99 | Ok(Account { 100 | key_pair, 101 | kid, 102 | directory, 103 | }) 104 | } 105 | async fn request( 106 | &self, 107 | client_config: &Arc, 108 | url: impl AsRef, 109 | payload: &str, 110 | ) -> Result<(Option, String), AcmeError> { 111 | let body = sign( 112 | &self.key_pair, 113 | Some(&self.kid), 114 | self.directory.nonce(client_config).await?, 115 | url.as_ref(), 116 | payload, 117 | )?; 118 | let response = https(client_config, url.as_ref(), Method::Post, Some(body)).await?; 119 | let location = get_header(&response, "Location").ok(); 120 | let body = response.text().await.map_err(HttpsRequestError::from)?; 121 | log::debug!("response: {:?}", body); 122 | Ok((location, body)) 123 | } 124 | pub async fn new_order( 125 | &self, 126 | client_config: &Arc, 127 | domains: Vec, 128 | ) -> Result<(String, Order), AcmeError> { 129 | let domains: Vec = domains.into_iter().map(Identifier::Dns).collect(); 130 | let payload = format!("{{\"identifiers\":{}}}", serde_json::to_string(&domains)?); 131 | let response = self 132 | .request(client_config, &self.directory.new_order, &payload) 133 | .await?; 134 | let url = response.0.ok_or(AcmeError::MissingHeader("Location"))?; 135 | let order = serde_json::from_str(&response.1)?; 136 | Ok((url, order)) 137 | } 138 | pub async fn auth( 139 | &self, 140 | client_config: &Arc, 141 | url: impl AsRef, 142 | ) -> Result { 143 | let payload = "".to_string(); 144 | let response = self.request(client_config, url, &payload).await?; 145 | Ok(serde_json::from_str(&response.1)?) 146 | } 147 | pub async fn challenge( 148 | &self, 149 | client_config: &Arc, 150 | url: impl AsRef, 151 | ) -> Result<(), AcmeError> { 152 | self.request(client_config, &url, "{}").await?; 153 | Ok(()) 154 | } 155 | pub async fn order( 156 | &self, 157 | client_config: &Arc, 158 | url: impl AsRef, 159 | ) -> Result { 160 | let response = self.request(client_config, &url, "").await?; 161 | Ok(serde_json::from_str(&response.1)?) 162 | } 163 | pub async fn finalize( 164 | &self, 165 | client_config: &Arc, 166 | url: impl AsRef, 167 | csr: Vec, 168 | ) -> Result { 169 | let payload = format!("{{\"csr\":\"{}\"}}", URL_SAFE_NO_PAD.encode(csr),); 170 | let response = self.request(client_config, &url, &payload).await?; 171 | Ok(serde_json::from_str(&response.1)?) 172 | } 173 | pub async fn certificate( 174 | &self, 175 | client_config: &Arc, 176 | url: impl AsRef, 177 | ) -> Result { 178 | Ok(self.request(client_config, &url, "").await?.1) 179 | } 180 | pub fn tls_alpn_01<'a>( 181 | &self, 182 | challenges: &'a [Challenge], 183 | domain: String, 184 | ) -> Result<(&'a Challenge, CertifiedKey), AcmeError> { 185 | let challenge = challenges 186 | .iter() 187 | .find(|c| c.typ == ChallengeType::TlsAlpn01); 188 | 189 | let challenge = match challenge { 190 | Some(challenge) => challenge, 191 | None => return Err(AcmeError::NoTlsAlpn01Challenge), 192 | }; 193 | let mut params = rcgen::CertificateParams::new(vec![domain])?; 194 | let key_auth = key_authorization_sha256(&self.key_pair, &challenge.token)?; 195 | params.custom_extensions = vec![CustomExtension::new_acme_identifier(key_auth.as_ref())]; 196 | 197 | let key_pair = rcgen::KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; 198 | let cert = params.self_signed(&key_pair)?; 199 | 200 | let pk_bytes = key_pair.serialize_der(); 201 | let pk_der: PrivatePkcs8KeyDer = pk_bytes.into(); 202 | let pk_der: PrivateKeyDer = pk_der.into(); 203 | let pk = any_ecdsa_type(&pk_der).unwrap(); 204 | let certified_key = CertifiedKey::new(vec![cert.der().clone()], pk); 205 | Ok((challenge, certified_key)) 206 | } 207 | } 208 | 209 | #[derive(Debug, Clone, Deserialize)] 210 | #[serde(rename_all = "camelCase")] 211 | pub struct Directory { 212 | pub new_nonce: String, 213 | pub new_account: String, 214 | pub new_order: String, 215 | } 216 | 217 | impl Directory { 218 | pub async fn discover( 219 | client_config: &Arc, 220 | url: impl AsRef, 221 | ) -> Result { 222 | let response = https(client_config, url, Method::Get, None).await?; 223 | let body = response.bytes().await.map_err(HttpsRequestError::from)?; 224 | 225 | Ok(serde_json::from_slice(&body)?) 226 | } 227 | pub async fn nonce(&self, client_config: &Arc) -> Result { 228 | let response = &https(client_config, &self.new_nonce.as_str(), Method::Head, None).await?; 229 | get_header(response, "replay-nonce") 230 | } 231 | } 232 | 233 | /// See RFC 8555 section 7.3.4 for more information. 234 | pub struct ExternalAccountKey { 235 | pub kid: String, 236 | pub key: ring::hmac::Key, 237 | } 238 | 239 | impl ExternalAccountKey { 240 | pub fn new(kid: String, key: &[u8]) -> Self { 241 | Self { 242 | kid, 243 | key: ring::hmac::Key::new(ring::hmac::HMAC_SHA256, key), 244 | } 245 | } 246 | } 247 | 248 | #[derive(Debug, Deserialize, Eq, PartialEq)] 249 | pub enum ChallengeType { 250 | #[serde(rename = "http-01")] 251 | Http01, 252 | #[serde(rename = "dns-01")] 253 | Dns01, 254 | #[serde(rename = "tls-alpn-01")] 255 | TlsAlpn01, 256 | } 257 | 258 | #[derive(Debug, Deserialize)] 259 | #[serde(rename_all = "camelCase")] 260 | pub struct Order { 261 | #[serde(flatten)] 262 | pub status: OrderStatus, 263 | pub authorizations: Vec, 264 | pub finalize: String, 265 | pub error: Option, 266 | } 267 | 268 | #[derive(Debug, Deserialize, Clone, PartialEq, Eq)] 269 | #[serde(tag = "status", rename_all = "camelCase")] 270 | pub enum OrderStatus { 271 | Pending, 272 | Ready, 273 | Valid { certificate: String }, 274 | Invalid, 275 | Processing, 276 | } 277 | 278 | #[derive(Debug, Deserialize)] 279 | #[serde(rename_all = "camelCase")] 280 | pub struct Auth { 281 | pub status: AuthStatus, 282 | pub identifier: Identifier, 283 | pub challenges: Vec, 284 | } 285 | 286 | #[derive(Debug, Deserialize)] 287 | #[serde(rename_all = "camelCase")] 288 | pub enum AuthStatus { 289 | Pending, 290 | Valid, 291 | Invalid, 292 | Revoked, 293 | Expired, 294 | Deactivated, 295 | } 296 | 297 | #[derive(Clone, Debug, Serialize, Deserialize)] 298 | #[serde(tag = "type", content = "value", rename_all = "camelCase")] 299 | pub enum Identifier { 300 | Dns(String), 301 | } 302 | 303 | #[derive(Debug, Deserialize)] 304 | pub struct Challenge { 305 | #[serde(rename = "type")] 306 | pub typ: ChallengeType, 307 | pub url: String, 308 | pub token: String, 309 | pub error: Option, 310 | } 311 | 312 | #[derive(Clone, Debug, Serialize, Deserialize)] 313 | #[serde(rename_all = "camelCase")] 314 | pub struct Problem { 315 | #[serde(rename = "type")] 316 | pub typ: Option, 317 | pub detail: Option, 318 | } 319 | 320 | #[derive(Error, Debug)] 321 | pub enum AcmeError { 322 | #[error("io error: {0}")] 323 | Io(#[from] std::io::Error), 324 | #[error("certificate generation error: {0}")] 325 | Rcgen(#[from] RcgenError), 326 | #[error("JOSE error: {0}")] 327 | Jose(#[from] JoseError), 328 | #[error("JSON error: {0}")] 329 | Json(#[from] serde_json::Error), 330 | #[error("http request error: {0}")] 331 | HttpRequest(#[from] HttpsRequestError), 332 | #[error("invalid key pair: {0}")] 333 | KeyRejected(#[from] KeyRejected), 334 | #[error("crypto error: {0}")] 335 | Crypto(#[from] Unspecified), 336 | #[error("acme service response is missing {0} header")] 337 | MissingHeader(&'static str), 338 | #[error("no tls-alpn-01 challenge found")] 339 | NoTlsAlpn01Challenge, 340 | } 341 | 342 | fn get_header(response: &Response, header: &'static str) -> Result { 343 | let h = response 344 | .headers() 345 | .get_all(header) 346 | .iter() 347 | .next_back() 348 | .and_then(|v| v.to_str().ok()) 349 | .map(|s| s.to_string()); 350 | match h { 351 | None => Err(AcmeError::MissingHeader(header)), 352 | Some(value) => Ok(value), 353 | } 354 | } 355 | -------------------------------------------------------------------------------- /src/axum.rs: -------------------------------------------------------------------------------- 1 | use crate::{AcmeAccept, AcmeAcceptor}; 2 | use rustls::ServerConfig; 3 | use std::future::Future; 4 | use std::io; 5 | use std::io::ErrorKind; 6 | use std::pin::Pin; 7 | use std::sync::Arc; 8 | use std::task::{Context, Poll}; 9 | use tokio::io::{AsyncRead, AsyncWrite}; 10 | use tokio_rustls::Accept; 11 | 12 | #[derive(Clone)] 13 | pub struct AxumAcceptor { 14 | acme_acceptor: AcmeAcceptor, 15 | config: Arc, 16 | } 17 | 18 | impl AxumAcceptor { 19 | pub fn new(acme_acceptor: AcmeAcceptor, config: Arc) -> Self { 20 | Self { 21 | acme_acceptor, 22 | config, 23 | } 24 | } 25 | } 26 | 27 | impl 28 | axum_server::accept::Accept for AxumAcceptor 29 | { 30 | type Stream = tokio_rustls::server::TlsStream; 31 | type Service = S; 32 | type Future = AxumAccept; 33 | 34 | fn accept(&self, stream: I, service: S) -> Self::Future { 35 | let acme_accept = self.acme_acceptor.accept(stream); 36 | Self::Future { 37 | config: self.config.clone(), 38 | acme_accept, 39 | tls_accept: None, 40 | service: Some(service), 41 | } 42 | } 43 | } 44 | 45 | pub struct AxumAccept { 46 | config: Arc, 47 | acme_accept: AcmeAccept, 48 | tls_accept: Option>, 49 | service: Option, 50 | } 51 | 52 | impl Unpin 53 | for AxumAccept 54 | { 55 | } 56 | 57 | impl Future 58 | for AxumAccept 59 | { 60 | type Output = io::Result<(tokio_rustls::server::TlsStream, S)>; 61 | 62 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 63 | loop { 64 | if let Some(tls_accept) = &mut self.tls_accept { 65 | return match Pin::new(&mut *tls_accept).poll(cx) { 66 | Poll::Ready(Ok(tls)) => Poll::Ready(Ok((tls, self.service.take().unwrap()))), 67 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 68 | Poll::Pending => Poll::Pending, 69 | }; 70 | } 71 | return match Pin::new(&mut self.acme_accept).poll(cx) { 72 | Poll::Ready(Ok(Some(start_handshake))) => { 73 | let config = self.config.clone(); 74 | self.tls_accept = Some(start_handshake.into_stream(config)); 75 | continue; 76 | } 77 | Poll::Ready(Ok(None)) => Poll::Ready(Err(io::Error::new( 78 | ErrorKind::Other, 79 | "TLS-ALPN-01 validation request", 80 | ))), 81 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 82 | Poll::Pending => Poll::Pending, 83 | }; 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /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( 13 | &self, 14 | domains: &[String], 15 | directory_url: &str, 16 | ) -> Result>, Self::EC>; 17 | async fn store_cert( 18 | &self, 19 | domains: &[String], 20 | directory_url: &str, 21 | cert: &[u8], 22 | ) -> Result<(), Self::EC>; 23 | } 24 | 25 | #[async_trait] 26 | pub trait AccountCache: Send + Sync { 27 | type EA: Debug; 28 | async fn load_account( 29 | &self, 30 | contact: &[String], 31 | directory_url: &str, 32 | ) -> Result>, Self::EA>; 33 | async fn store_account( 34 | &self, 35 | contact: &[String], 36 | directory_url: &str, 37 | account: &[u8], 38 | ) -> Result<(), Self::EA>; 39 | } 40 | -------------------------------------------------------------------------------- /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( 29 | &self, 30 | domains: &[String], 31 | directory_url: &str, 32 | ) -> Result>, Self::EC> { 33 | self.inner 34 | .load_cert(domains, directory_url) 35 | .await 36 | .map_err(box_err) 37 | } 38 | 39 | async fn store_cert( 40 | &self, 41 | domains: &[String], 42 | directory_url: &str, 43 | cert: &[u8], 44 | ) -> Result<(), Self::EC> { 45 | self.inner 46 | .store_cert(domains, directory_url, cert) 47 | .await 48 | .map_err(box_err) 49 | } 50 | } 51 | 52 | #[async_trait] 53 | impl AccountCache for BoxedErrCache 54 | where 55 | ::EA: 'static, 56 | { 57 | type EA = Box; 58 | async fn load_account( 59 | &self, 60 | contact: &[String], 61 | directory_url: &str, 62 | ) -> Result>, Self::EA> { 63 | self.inner 64 | .load_account(contact, directory_url) 65 | .await 66 | .map_err(box_err) 67 | } 68 | 69 | async fn store_account( 70 | &self, 71 | contact: &[String], 72 | directory_url: &str, 73 | account: &[u8], 74 | ) -> Result<(), Self::EA> { 75 | self.inner 76 | .store_account(contact, directory_url, account) 77 | .await 78 | .map_err(box_err) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /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 { 12 | cert_cache, 13 | account_cache, 14 | } 15 | } 16 | pub fn into_inner(self) -> (C, A) { 17 | (self.cert_cache, self.account_cache) 18 | } 19 | } 20 | 21 | #[async_trait] 22 | impl CertCache for CompositeCache { 23 | type EC = C::EC; 24 | async fn load_cert( 25 | &self, 26 | domains: &[String], 27 | directory_url: &str, 28 | ) -> Result>, Self::EC> { 29 | self.cert_cache.load_cert(domains, directory_url).await 30 | } 31 | 32 | async fn store_cert( 33 | &self, 34 | domains: &[String], 35 | directory_url: &str, 36 | cert: &[u8], 37 | ) -> Result<(), Self::EC> { 38 | self.cert_cache 39 | .store_cert(domains, directory_url, cert) 40 | .await 41 | } 42 | } 43 | 44 | #[async_trait] 45 | impl AccountCache 46 | for CompositeCache 47 | { 48 | type EA = A::EA; 49 | async fn load_account( 50 | &self, 51 | contact: &[String], 52 | directory_url: &str, 53 | ) -> Result>, Self::EA> { 54 | self.account_cache 55 | .load_account(contact, directory_url) 56 | .await 57 | } 58 | 59 | async fn store_account( 60 | &self, 61 | contact: &[String], 62 | directory_url: &str, 63 | account: &[u8], 64 | ) -> Result<(), Self::EA> { 65 | self.account_cache 66 | .store_account(contact, directory_url, account) 67 | .await 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/caches/dir.rs: -------------------------------------------------------------------------------- 1 | use crate::{AccountCache, CertCache}; 2 | use async_trait::async_trait; 3 | use base64::engine::general_purpose::URL_SAFE_NO_PAD; 4 | use base64::Engine; 5 | use ring::digest::{Context, SHA256}; 6 | use std::io::ErrorKind; 7 | use std::path::Path; 8 | use tokio::fs; 9 | 10 | pub struct DirCache + Send + Sync> { 11 | inner: P, 12 | } 13 | 14 | impl + Send + Sync> DirCache

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

{ 65 | type EC = std::io::Error; 66 | async fn load_cert( 67 | &self, 68 | domains: &[String], 69 | directory_url: &str, 70 | ) -> Result>, Self::EC> { 71 | let file_name = Self::cached_cert_file_name(domains, directory_url); 72 | self.read_if_exist(file_name).await 73 | } 74 | async fn store_cert( 75 | &self, 76 | domains: &[String], 77 | directory_url: &str, 78 | cert: &[u8], 79 | ) -> Result<(), Self::EC> { 80 | let file_name = Self::cached_cert_file_name(domains, directory_url); 81 | self.write(file_name, cert).await 82 | } 83 | } 84 | 85 | #[async_trait] 86 | impl + Send + Sync> AccountCache for DirCache

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