Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 38 additions & 5 deletions docs/src/content/docs/security/certificates.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ staging directory. No certificate is issued during `--dry-run`.

Reference `public` from TLS or QUIC as in the file-source example. Domains must
be unique lowercase ASCII DNS names (use punycode for internationalized names).
Every named TLS target using an ACME source must be covered by its domains.
Wildcards (`*.example.com`) are accepted only with the `acme_dns` challenge.
Every named TLS target using an ACME source must be covered by its domains; a
wildcard covers exactly one label, so `*.example.com` covers `a.example.com`
but not `example.com` or `a.b.example.com`.
There is no issuance based on incoming SNI.

`terms_of_service` is explicit acceptance of that exact URL, not blanket
Expand Down Expand Up @@ -140,6 +143,36 @@ uses the RFC 8737 critical `acmeIdentifier` extension and never enters the proxy
handler or replaces the ordinary certificate. Normal ALPN, client authentication,
fallback routing and QUIC policy are unchanged.

For DNS-01 through an [acme-dns](https://github.com/joohoi/acme-dns) server,
replace the `challenge` mapping with:

```yaml
challenge:
type: acme_dns
server_url: https://auth.acme-dns.io
username: 00000000-0000-0000-0000-000000000000
password: replace-with-acme-dns-password
subdomain: 00000000-0000-0000-0000-000000000000
propagation_delay: 10 # optional, seconds, at most 300
```

Register an account with acme-dns, then point `_acme-challenge.<domain>` at
`<subdomain>.<acme-dns zone>` with a CNAME for every configured domain
(`example.com` and `*.example.com` share one record). No inbound port is needed.

- shoes publishes the TXT value for every pending domain, waits
`propagation_delay` once, then asks the CA to validate. Keep the delay short:
the whole order must finish within 10 minutes.
- acme-dns keeps only the two newest TXT values per subdomain, so a source may
list at most two domains, e.g. `[example.com, "*.example.com"]`. Use one
source per pair for more names.
- The acme-dns server is verified against the default public CA roots, not
`ca_cert`. `server_url` must be HTTPS (HTTP only for a numeric loopback test
server) without credentials, query or fragment; `/update` is appended unless
the path already ends with it.
- `password` is redacted from debug output, and failures report only the HTTP
status, never the server's response body.

At first start, proxy and challenge listeners bind before issuance begins.
Normal handshakes for a source without a certificate fail until issuance
succeeds; `Servers ready` means listeners are bound, not that ACME has finished.
Expand Down Expand Up @@ -210,10 +243,10 @@ the check need not run as the service user.
Actual OS port conflicts,
storage ownership and permissions are checked during runtime preparation.

There is no built-in DNS-01, wildcard ACME issuance, DNS vendor API, shell hook,
Tailscale provider, or Cloudflare Origin CA provider. For wildcard certificates
or DNS-01, run an external client such as acme.sh, lego or Certbot and use a file
source. Manually supplied wildcard certificates remain supported.
Built-in DNS-01 only talks to acme-dns. There is no DNS vendor API, shell hook,
Tailscale provider, or Cloudflare Origin CA provider. For other DNS providers,
run an external client such as acme.sh, lego or Certbot and use a file source.
Manually supplied wildcard certificates remain supported.

Examples: [file rotation and reuse](/examples/certificates_files/) and
[ACME with shared TCP/QUIC consumers](/examples/certificates_acme/).
23 changes: 21 additions & 2 deletions docs/src/content/docs/zh-cn/security/certificates.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ ACME 使用 `instant-acme` 和显式配置的域。从 CA 的暂存目录开始
listen: ["0.0.0.0:8080"]
```

如文件源示例中所示,从 TLS 或 QUIC 引用 `public`。域必须是唯一的小写 ASCII DNS 名称(使用 punycode 作为国际化名称)。每个使用 ACME 源的命名 TLS 目标都必须被其域覆盖。没有根据传入的SNI进行发行。
如文件源示例中所示,从 TLS 或 QUIC 引用 `public`。域必须是唯一的小写 ASCII DNS 名称(使用 punycode 作为国际化名称)。只有 `acme_dns` 质询接受通配符(`*.example.com`)。每个使用 ACME 源的命名 TLS 目标都必须被其域覆盖;通配符只覆盖一级标签,因此 `*.example.com` 覆盖 `a.example.com`,但不覆盖 `example.com` 或 `a.b.example.com`。没有根据传入的SNI进行发行。

`terms_of_service` 明确接受该确切 URL,而不是全面接受未来条款。 shoes 在帐户操作之前检查目录的 `meta.termsOfService` 并拒绝更改的 URL。查看新条款并更新配置以接受它们。如果私有 CA 未发布任何条款,则省略此字段;随后公布的条款 URL 仍需要明确接受。该版本不支持需要外部账号绑定的账号。

Expand All @@ -79,6 +79,25 @@ HTTP-01要求:

CA 必须到达公共 TCP 端口 443,转发到覆盖每个配置域的现有最外层 shoes TLS 监听器。这不是 QUIC、ShadowTLS 或 REALITY 验证。中间的TLS终结器必须让握手通过,包括SNI和ALPN。 shoes 仅为待配置的 SNI 应答唯一提供的协议 `acme-tls/1`。短暂的质询响应使用 RFC 8737 关键 `acmeIdentifier` 扩展,并且永远不会进入代理处理程序或替换普通证书。普通 ALPN、客户端身份验证、回退路由和 QUIC 策略保持不变。

要通过 [acme-dns](https://github.com/joohoi/acme-dns) 服务器完成 DNS-01,将 `challenge` 映射替换为:

```yaml
challenge:
type: acme_dns
server_url: https://auth.acme-dns.io
username: 00000000-0000-0000-0000-000000000000
password: replace-with-acme-dns-password
subdomain: 00000000-0000-0000-0000-000000000000
propagation_delay: 10 # 可选,单位秒,最多 300
```

先在 acme-dns 注册账户,然后为每个配置的域名把 `_acme-challenge.<域名>` 用 CNAME 指向 `<subdomain>.<acme-dns 区域>`(`example.com` 与 `*.example.com` 共用一条记录)。不需要任何入站端口。

- shoes 先为每个待验证的域名发布 TXT 值,统一等待一次 `propagation_delay`,再请求 CA 验证。请保持较短的等待:整个订单必须在 10 分钟内完成。
- acme-dns 每个子域只保留最新的两个 TXT 值,因此一个源最多列出两个域名,例如 `[example.com, "*.example.com"]`。更多域名请每两个使用一个源。
- acme-dns 服务器使用默认公共 CA 根证书验证,而不是 `ca_cert`。`server_url` 必须是 HTTPS(仅数字回环测试服务器可用 HTTP),不得包含凭据、查询串或片段;除非路径已以 `/update` 结尾,否则会自动追加。
- `password` 在调试输出中会被隐藏,失败时只报告 HTTP 状态码,绝不输出服务器响应正文。

首次启动时,代理和质询监听器在发布开始之前绑定。没有证书的源的正常握手会失败,直到颁发成功为止; `Servers ready` 表示监听器已绑定,而不是 ACME 已完成。有效的缓存证书允许在 CA 中断期间立即启动。

shoes 将注册前的帐户密钥、帐户凭据、进行中的订单和 CSR 密钥以及证书/密钥对保留在一个自动替换的同步状态文件中。请勿编辑它或在来源之间共享它。在 Unix 上,状态目录必须由模式 0700 的运行用户拥有,文件使用 0600。其他平台使用其继承的文件系统访问控制;将目录放置在私有应用程序存储中。独占操作系统文件锁可防止多个进程或嵌入式生命周期拥有同一目录。安全地备份整个目录。更改 CA 或域列表需要不同的状态目录;舞台和制作绝不能共用一个。
Expand All @@ -91,6 +110,6 @@ CA 流量直接通过操作系统解析器和 shoes 受保护的 TCP 套接字

`--dry-run` 验证配置、引用、域覆盖、质询兼容性、证书材料和声明的地址冲突,而无需联系 CA、绑定端口或创建 ACME 状态。未发布的 ACME 源是有效配置,而不是自签名占位符。检查现有的可读状态是否存在 CA/域身份不匹配的情况,而无需锁定或修改它;该检查不需要以服务用户身份运行。在运行时准备期间检查实际操作系统端口冲突、存储所有权和权限。

没有内置的 DNS-01、通配符 ACME 发行、DNS 供应商 API、shell hook、Tailscale 提供商或 Cloudflare Origin CA 提供商。对于通配符证书或 DNS-01,请运行外部客户端(例如 acme.sh、lego 或 Certbot)并使用文件源。仍然支持手动提供的通配符证书。
内置 DNS-01 仅支持 acme-dns。没有 DNS 供应商 API、shell hook、Tailscale 提供商或 Cloudflare Origin CA 提供商。对于其他 DNS 提供商,请运行外部客户端(例如 acme.sh、lego 或 Certbot)并使用文件源。仍然支持手动提供的通配符证书。

示例:[文件轮换和重用](/zh-cn/examples/certificates_files/) 和 [具有共享 TCP/QUIC 使用者的 ACME](/zh-cn/examples/certificates_acme/)。
139 changes: 67 additions & 72 deletions src/certificates/acme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,55 @@ async fn connect_stream(
}
}

/// Sends one request over a fresh HTTP/1 connection; `on_head` runs before the body is read.
async fn send_http1<B>(
stream: Box<dyn crate::async_stream::AsyncStream>,
request: http::Request<B>,
on_head: impl FnOnce(&http::response::Parts) -> io::Result<()>,
) -> io::Result<(http::response::Parts, Bytes)>
where
B: hyper::body::Body + Send + 'static,
B::Data: Send,
B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
let (mut sender, connection) = hyper::client::conn::http1::Builder::new()
.max_buf_size(32 * 1024)
.handshake(hyper_util::rt::TokioIo::new(stream))
.await
.map_err(io::Error::other)?;
let response = async {
let response = sender
.send_request(request)
.await
.map_err(io::Error::other)?;
let (parts, body) = response.into_parts();
if parts
.headers
.iter()
.map(|(name, value)| name.as_str().len() + value.as_bytes().len() + 4)
.sum::<usize>()
> 32 * 1024
{
return Err(io::Error::other("ACME response headers exceed 32 KiB"));
}
on_head(&parts)?;
let bytes = Limited::new(body, MAX_RESPONSE)
.collect()
.await
.map_err(|_| io::Error::other("ACME response failed or exceeded 1 MiB"))?
.to_bytes();
Ok::<_, io::Error>((parts, bytes))
};
tokio::pin!(response, connection);
tokio::select! {
result = &mut response => result,
result = &mut connection => {
result.map_err(io::Error::other)?;
response.await
}
}
}

#[derive(Serialize)]
struct AcmeDnsPayload<'a> {
subdomain: &'a str,
Expand Down Expand Up @@ -308,38 +357,15 @@ pub(super) async fn update_acme_dns(

tokio::time::timeout(REQUEST_TIMEOUT, async {
let stream = connect_stream(&url, &tls).await?;
let (mut sender, connection) = hyper::client::conn::http1::Builder::new()
.max_buf_size(32 * 1024)
.handshake(hyper_util::rt::TokioIo::new(stream))
.await
.map_err(io::Error::other)?;
let response = async {
let response = sender
.send_request(request)
.await
.map_err(io::Error::other)?;
let (parts, body) = response.into_parts();
Limited::new(body, MAX_RESPONSE)
.collect()
.await
.map_err(|_| io::Error::other("ACME-DNS response failed or exceeded limit"))?;
// Never log the remote body; the status is enough to diagnose.
if !parts.status.is_success() {
return Err(io::Error::other(format!(
"ACME-DNS update returned HTTP {}",
parts.status
)));
}
Ok::<_, io::Error>(())
};
tokio::pin!(response, connection);
tokio::select! {
result = &mut response => result,
result = &mut connection => {
result.map_err(io::Error::other)?;
response.await
}
let (parts, _) = send_http1(stream, request, |_| Ok(())).await?;
// Never log the remote body; the status is enough to diagnose.
if !parts.status.is_success() {
return Err(io::Error::other(format!(
"ACME-DNS update returned HTTP {}",
parts.status
)));
}
Ok(())
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "ACME-DNS request timed out"))?
Expand Down Expand Up @@ -395,52 +421,21 @@ impl instant_acme::HttpClient for HttpClient {
.map_or("/", |path| path.as_str())
.parse()
.map_err(|_| invalid("invalid ACME path"))?;
let (mut sender, connection) = hyper::client::conn::http1::Builder::new()
.max_buf_size(32 * 1024)
.handshake(hyper_util::rt::TokioIo::new(stream))
.await
.map_err(io::Error::other)?;
let response = async {
let response = sender
.send_request(request)
.await
.map_err(io::Error::other)?;
let (parts, body) = response.into_parts();
if parts
.headers
.iter()
.map(|(name, value)| name.as_str().len() + value.as_bytes().len() + 4)
.sum::<usize>()
> 32 * 1024
{
return Err(io::Error::other("ACME response headers exceed 32 KiB"));
}
let retry_after = parse_retry_after(&parts.headers)?;
let (parts, bytes) = send_http1(stream, request, |parts| {
*client.last.lock() = Some(ResponseMetadata {
url: request_url,
status: parts.status,
retry_after,
retry_after: parse_retry_after(&parts.headers)?,
});
let bytes = Limited::new(body, MAX_RESPONSE)
.collect()
.await
.map_err(|_| io::Error::other("ACME response failed or exceeded 1 MiB"))?
.to_bytes();
if is_directory {
validate_directory(parts.status, &bytes, client.terms.as_deref())?;
}
Ok::<_, io::Error>(instant_acme::BytesResponse::from(
http::Response::from_parts(parts, Full::new(bytes)),
))
};
tokio::pin!(response, connection);
tokio::select! {
result = &mut response => result,
result = &mut connection => {
result.map_err(io::Error::other)?;
response.await
}
Ok(())
})
.await?;
if is_directory {
validate_directory(parts.status, &bytes, client.terms.as_deref())?;
}
Ok(instant_acme::BytesResponse::from(
http::Response::from_parts(parts, Full::new(bytes)),
))
})
.await;
result
Expand Down
22 changes: 17 additions & 5 deletions src/certificates/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,15 @@ impl Material {
}
}

/// True if `name` equals `pattern`, or `pattern` is `*.rest` and `name` is exactly one label above `rest`.
fn domain_covers(pattern: &str, name: &str) -> bool {
pattern == name
|| pattern.strip_prefix("*.").is_some_and(|rest| {
name.split_once('.')
.is_some_and(|(label, parent)| !label.is_empty() && label != "*" && parent == rest)
})
}

fn algorithm_matches(
supported: rustls::pki_types::AlgorithmIdentifier,
actual: &x509_parser::x509::AlgorithmIdentifier<'_>,
Expand Down Expand Up @@ -452,11 +461,14 @@ fn validate_acme(config: &AcmeConfig) -> io::Result<()> {
return Err(invalid("ACME requires 1 to 100 explicit domains"));
}
let mut domains = HashSet::new();
// Only DNS-01 can prove control of a wildcard name.
let dns01 = matches!(config.challenge, ChallengeConfig::AcmeDns { .. });
for domain in &config.domains {
let name = domain.strip_prefix("*.").filter(|_| dns01).unwrap_or(domain);
if domain.len() > 253
|| !domain.contains('.')
|| domain.parse::<std::net::IpAddr>().is_ok()
|| domain.split('.').any(|label| {
|| !name.contains('.')
|| name.parse::<std::net::IpAddr>().is_ok()
|| name.split('.').any(|label| {
label.is_empty()
|| label.len() > 63
|| label.starts_with('-')
Expand All @@ -468,7 +480,7 @@ fn validate_acme(config: &AcmeConfig) -> io::Result<()> {
|| !domains.insert(domain)
{
return Err(invalid(
"ACME domains must be unique lowercase ASCII DNS names; wildcards and IPs are not supported",
"ACME domains must be unique lowercase ASCII DNS names; IPs are not supported, and wildcards need the acme_dns challenge",
));
}
}
Expand Down Expand Up @@ -825,7 +837,7 @@ pub(crate) fn configure(configs: &mut [Config]) -> io::Result<Vec<Arc<Source>>>
if let Some(source) = binding
&& let Spec::Acme(acme) = &source.spec
&& let Some(sni) = sni
&& !acme.domains.iter().any(|domain| domain == sni)
&& !acme.domains.iter().any(|domain| domain_covers(domain, sni))
{
return Err(invalid(
"TLS target SNI is not in certificate_source ACME domains",
Expand Down
28 changes: 28 additions & 0 deletions src/certificates/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,34 @@ fn acme_dns_rejects_more_than_two_domains_and_redacts_password() {
assert!(!format!("{config:?}").contains("hunter2-secret"));
}

#[test]
fn wildcard_domains_require_acme_dns_and_cover_one_label() {
let dir = tempfile::tempdir().unwrap();
let state = dir.path().join("state");
let dns = "type: acme_dns, server_url: 'https://auth.example.com', username: 'user1', password: 'secret', subdomain: 'uuid-subdomain'";
let wildcard = |challenge: &str| {
managed_yaml(&state, challenge, "certificate_source: public")
.replace("domains: [proxy.test]", "domains: [proxy.test, '*.proxy.test']")
};
assert!(compile(&wildcard(dns)).is_ok());
assert!(compile(&wildcard("type: http01, listen: ['127.0.0.1:18080']")).is_err());
assert!(compile(&wildcard("type: tls_alpn01")).is_err());
for bad in ["'*.test'", "'*.*.proxy.test'", "'a.*.proxy.test'"] {
let yaml = managed_yaml(&state, dns, "certificate_source: public")
.replace("domains: [proxy.test]", &format!("domains: [{bad}]"));
assert!(compile(&yaml).is_err(), "unexpectedly accepted {bad}");
}
// A wildcard-only source serves one-label subdomains, not the apex.
let only = |sni: &str| {
managed_yaml(&state, dns, "certificate_source: public")
.replace("domains: [proxy.test]", "domains: ['*.proxy.test']")
.replace(" proxy.test:", &format!(" {sni}:"))
};
assert!(compile(&only("a.proxy.test")).is_ok());
assert!(compile(&only("proxy.test")).is_err());
assert!(compile(&only("a.b.proxy.test")).is_err());
}

#[test]
fn managed_validation_rejects_invalid_acme_dns_configs() {
let dir = tempfile::tempdir().unwrap();
Expand Down