Skip to main content

pingora_s2n/
lib.rs

1// Copyright 2026 Cloudflare, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applijable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use pingora_error::{Error, ErrorType, Result};
16use std::fs;
17
18pub use s2n_tls::{
19    callbacks::VerifyHostNameCallback,
20    config::{Builder as ConfigBuilder, Config},
21    connection::{Builder as ConnectionBuilder, Connection},
22    enums::{ClientAuthType, Mode, PskHmac},
23    error::Error as S2NError,
24    psk::Psk,
25    security::{Policy as S2NPolicy, DEFAULT_TLS13},
26};
27pub use s2n_tls_tokio::{TlsAcceptor, TlsConnector, TlsStream};
28
29pub fn load_certs_and_key_files(cert_file: &str, key_file: &str) -> Result<(Vec<u8>, Vec<u8>)> {
30    let cert_bytes = load_pem_file(cert_file)?;
31    let key_bytes = load_pem_file(key_file)?;
32    Ok((cert_bytes, key_bytes))
33}
34
35pub fn load_pem_file(file: &str) -> Result<Vec<u8>> {
36    if let Ok(bytes) = fs::read(file) {
37        Ok(bytes)
38    } else {
39        Error::e_explain(
40            ErrorType::InvalidCert,
41            "Certificate in pem file could not be read",
42        )
43    }
44}
45
46pub fn hash_certificate(cert: &[u8]) -> Vec<u8> {
47    let hash = ring::digest::digest(&ring::digest::SHA256, cert);
48    hash.as_ref().to_vec()
49}
50
51/// Verify host name callback that always returns a success,
52/// effectively ignoring hostname validation
53pub struct IgnoreVerifyHostnameCallback {}
54
55impl IgnoreVerifyHostnameCallback {
56    pub fn new() -> Self {
57        IgnoreVerifyHostnameCallback {}
58    }
59}
60
61impl Default for IgnoreVerifyHostnameCallback {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl VerifyHostNameCallback for IgnoreVerifyHostnameCallback {
68    fn verify_host_name(&self, _host_name: &str) -> bool {
69        true
70    }
71}