mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
refactor: replace OpenSSL transports and certificate imports
This commit is contained in:
59 files changed
+1072
-1151
No files matched your search
@@ -62,9 +62,9 @@ jobs:
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y autoconf automake gettext libtool pkg-config \
|
||||
clang libclang-dev libgtk-4-dev libxml2-dev libssl-dev \
|
||||
clang libclang-dev libgtk-4-dev libxml2-dev \
|
||||
libgnutls28-dev liblz4-dev libwayland-dev libxkbcommon-dev libdbus-1-dev
|
||||
pkg-config --exists gtk4 openssl dbus-1 wayland-client xkbcommon
|
||||
pkg-config --exists gtk4 gnutls dbus-1 wayland-client xkbcommon
|
||||
- name: Install the NSH compiler
|
||||
run: rustup toolchain install 1.97.0 --profile minimal
|
||||
- name: Cache public crate downloads
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
sudo apt-get install -y autoconf automake gettext libtool pkg-config \
|
||||
clang libclang-dev libgtk-4-dev libxml2-dev libssl-dev \
|
||||
libgnutls28-dev liblz4-dev libwayland-dev libxkbcommon-dev libdbus-1-dev
|
||||
pkg-config --exists gtk4 openssl dbus-1 wayland-client xkbcommon
|
||||
pkg-config --exists gtk4 gnutls dbus-1 wayland-client xkbcommon
|
||||
- name: Install macOS dependencies
|
||||
if: matrix.platform == 'macos'
|
||||
env:
|
||||
|
||||
@@ -63,7 +63,6 @@ jobs:
|
||||
make \
|
||||
namcap \
|
||||
nettle \
|
||||
openssl \
|
||||
patch \
|
||||
pkgconf \
|
||||
librsvg \
|
||||
|
||||
Generated
+278
-51
@@ -222,6 +222,45 @@ dependencies = [
|
||||
"winnow 1.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
|
||||
dependencies = [
|
||||
"asn1-rs-derive",
|
||||
"asn1-rs-impl",
|
||||
"displaydoc",
|
||||
"nom",
|
||||
"num-traits",
|
||||
"rusticata-macros",
|
||||
"thiserror 2.0.21",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs-derive"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"synstructure 0.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs-impl"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atk"
|
||||
version = "0.18.2"
|
||||
@@ -842,6 +881,18 @@ version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "cms"
|
||||
version = "0.3.0-pre.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "758d5272932ff167e96ec9641a04d96ab1901cccc5ea9f47c15b4cbaa6f9ea53"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"der",
|
||||
"spki",
|
||||
"x509-cert",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.5"
|
||||
@@ -1248,6 +1299,20 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der-parser"
|
||||
version = "10.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
"displaydoc",
|
||||
"nom",
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"rusticata-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.8.0"
|
||||
@@ -2054,6 +2119,7 @@ version = "3.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.23.1",
|
||||
"cc",
|
||||
"chacha20poly1305 0.11.0",
|
||||
"chrono",
|
||||
"clap",
|
||||
@@ -2068,18 +2134,21 @@ dependencies = [
|
||||
"log",
|
||||
"log-reload",
|
||||
"md5",
|
||||
"native-tls",
|
||||
"netdev",
|
||||
"nix",
|
||||
"openssl",
|
||||
"os_info",
|
||||
"oslog",
|
||||
"p12-keystore",
|
||||
"pem",
|
||||
"pkcs8",
|
||||
"pkg-config",
|
||||
"proptest",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
"rustls",
|
||||
"rustls-pemfile",
|
||||
"sec1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
@@ -2096,7 +2165,6 @@ dependencies = [
|
||||
"urlencoding",
|
||||
"uuid",
|
||||
"uzers",
|
||||
"version-compare",
|
||||
"whoami",
|
||||
"x509-cert",
|
||||
"xmltree",
|
||||
@@ -2483,22 +2551,6 @@ dependencies = [
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-tls"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"native-tls",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.21"
|
||||
@@ -3016,6 +3068,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
|
||||
[[package]]
|
||||
name = "libappindicator"
|
||||
version = "0.9.0"
|
||||
@@ -3222,6 +3280,12 @@ version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.8.9"
|
||||
@@ -3281,23 +3345,6 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
|
||||
|
||||
[[package]]
|
||||
name = "native-tls"
|
||||
version = "0.2.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"openssl",
|
||||
"openssl-probe",
|
||||
"openssl-sys",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ndk"
|
||||
version = "0.9.0"
|
||||
@@ -3401,6 +3448,16 @@ dependencies = [
|
||||
"memoffset",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "7.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ntapi"
|
||||
version = "0.4.3"
|
||||
@@ -3410,12 +3467,31 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -3698,6 +3774,15 @@ dependencies = [
|
||||
"objc2-security",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oid-registry"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@@ -3813,6 +3898,29 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "p12-keystore"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c2ed4fa0ec7ec58b657d4184680c57da9e203e97771d29a566028869a5193e0"
|
||||
dependencies = [
|
||||
"cbc",
|
||||
"cms",
|
||||
"der",
|
||||
"des",
|
||||
"hex",
|
||||
"hmac",
|
||||
"pkcs12",
|
||||
"pkcs5",
|
||||
"pkcs8",
|
||||
"rand 0.10.3",
|
||||
"rc2",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"x509-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "palette"
|
||||
version = "0.7.7"
|
||||
@@ -3988,6 +4096,21 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs12"
|
||||
version = "0.2.0-pre.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8059bd79345d1d1c125656025814704bab5cdd204b1cefd5fab59b0fdd7476d2"
|
||||
dependencies = [
|
||||
"cms",
|
||||
"const-oid",
|
||||
"der",
|
||||
"digest 0.11.3",
|
||||
"spki",
|
||||
"x509-cert",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs5"
|
||||
version = "0.8.1"
|
||||
@@ -4386,6 +4509,15 @@ version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
|
||||
|
||||
[[package]]
|
||||
name = "rc2"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ceda21af1ae61033b63175653a1af86cae399d79cd03ca80ba347eb3a6c4a7fe"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
@@ -4471,21 +4603,21 @@ dependencies = [
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-tls",
|
||||
"hyper-util",
|
||||
"js-sys",
|
||||
"log",
|
||||
"mime",
|
||||
"native-tls",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"rustls-platform-verifier",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -4526,6 +4658,15 @@ dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusticata-macros"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
|
||||
dependencies = [
|
||||
"nom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.5"
|
||||
@@ -4546,12 +4687,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-native-certs"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
|
||||
dependencies = [
|
||||
"openssl-probe",
|
||||
"rustls-pki-types",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pemfile"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.15.1"
|
||||
@@ -4561,6 +4724,33 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-platform-verifier"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
|
||||
dependencies = [
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"jni 0.22.4",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-platform-verifier-android",
|
||||
"rustls-webpki",
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-platform-verifier-android"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.15"
|
||||
@@ -4693,6 +4883,16 @@ dependencies = [
|
||||
"sha2 0.11.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"
|
||||
dependencies = [
|
||||
"der",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
@@ -5278,6 +5478,17 @@ dependencies = [
|
||||
"futures-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.14.0"
|
||||
@@ -5774,16 +5985,6 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-native-tls"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
|
||||
dependencies = [
|
||||
"native-tls",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-rustls"
|
||||
version = "0.26.6"
|
||||
@@ -6460,6 +6661,15 @@ dependencies = [
|
||||
"system-deps",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com"
|
||||
version = "0.39.1"
|
||||
@@ -6957,6 +7167,23 @@ dependencies = [
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-parser"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
"data-encoding",
|
||||
"der-parser",
|
||||
"lazy_static",
|
||||
"nom",
|
||||
"oid-registry",
|
||||
"rusticata-macros",
|
||||
"thiserror 2.0.21",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xattr"
|
||||
version = "1.6.1"
|
||||
@@ -7012,7 +7239,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"synstructure",
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7053,7 +7280,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"synstructure",
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ is_executable = "1.0"
|
||||
log = "0.4"
|
||||
# RUST_LOG accepts user-supplied Unicode property filters through env_logger.
|
||||
regex = { version = "1", default-features = false, features = ["std", "perf", "unicode"] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["native-tls", "charset", "http2", "system-proxy", "json", "form", "query"] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "charset", "http2", "system-proxy", "json", "form", "query"] }
|
||||
openssl = "0.10"
|
||||
pem = "4"
|
||||
xmltree = { version = "0.12", features = ["attribute-order"] }
|
||||
|
||||
@@ -67,7 +67,6 @@ Commands:
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
Options:
|
||||
--fix-openssl Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats.
|
||||
--ignore-tls-errors Ignore the TLS errors
|
||||
--lock-file <LOCK_FILE> Path to the gpclient PID lock file
|
||||
--log-format <LOG_FORMAT> Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text. [default: text] [possible values: text, json]
|
||||
@@ -77,7 +76,6 @@ Options:
|
||||
-V, --version Print version
|
||||
```
|
||||
|
||||
The `--fix-openssl` option is available on Linux, FreeBSD, and OpenBSD. macOS uses native TLS and GnuTLS and does not accept this option.
|
||||
|
||||
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ clap.workspace = true
|
||||
log.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||
tempfile.workspace = true
|
||||
compile-time.workspace = true
|
||||
|
||||
home = "0.5.12"
|
||||
@@ -33,3 +32,6 @@ tauri = { workspace = true, optional = true }
|
||||
default = ["webview-auth"]
|
||||
webview-auth = ["auth/webview-auth", "dep:tauri", "dep:tauri-build"]
|
||||
release-devtools = ["auth/release-devtools"]
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
+11
-29
@@ -6,8 +6,6 @@ use clap::Parser;
|
||||
use clap::Subcommand;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use gpapi::auth::AuthWindowTheme;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use gpapi::utils::openssl;
|
||||
use gpapi::{
|
||||
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
|
||||
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
|
||||
@@ -20,8 +18,6 @@ use gpapi::{
|
||||
use log::info;
|
||||
use serde_json::json;
|
||||
use std::net::IpAddr;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
@@ -89,7 +85,7 @@ struct Cli {
|
||||
key_password: Option<String>,
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
|
||||
#[arg(long, hide = true)]
|
||||
fix_openssl: bool,
|
||||
|
||||
#[arg(long, help = "Ignore TLS errors")]
|
||||
@@ -149,11 +145,6 @@ enum CliCommand {
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
@@ -164,19 +155,12 @@ impl Args for Cli {
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn prepare_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if self.fix_openssl {
|
||||
info!("Fixing OpenSSL environment");
|
||||
let file = openssl::fix_openssl_env()?;
|
||||
|
||||
return Ok(Some(file));
|
||||
log::warn!("--fix-openssl is deprecated and has no effect. It will be removed in a future release.");
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
if self.browser_listen.is_some()
|
||||
&& !matches!(self.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote"))
|
||||
{
|
||||
@@ -189,8 +173,6 @@ impl Cli {
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
gpapi::utils::env_utils::patch_gui_runtime_env(self.hidpi);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let openssl_conf = self.prepare_openssl()?;
|
||||
|
||||
let server = normalize_server(self.server.as_deref().expect("server is required for authentication"))?;
|
||||
let gp_params = self.build_gp_params();
|
||||
@@ -230,8 +212,6 @@ impl Cli {
|
||||
|
||||
print_auth_result(auth_result, Some(&auth_host_id));
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
drop(openssl_conf);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -243,8 +223,6 @@ impl Cli {
|
||||
self.clean,
|
||||
self.window_title.clone(),
|
||||
self.window_theme,
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
openssl_conf,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -338,9 +316,13 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn openssl_option_is_available_only_on_supported_platforms() {
|
||||
fn deprecated_openssl_option_remains_supported_but_hidden() {
|
||||
let result = Cli::try_parse_from(["gpauth", "portal.example.com", "--fix-openssl"]);
|
||||
assert_eq!(result.is_ok(), !cfg!(target_os = "macos"));
|
||||
for flag in ["-h", "--help"] {
|
||||
let help = Cli::try_parse_from(["gpauth", flag]).err().unwrap().to_string();
|
||||
assert!(!help.contains("--fix-openssl"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -348,12 +330,12 @@ mod tests {
|
||||
use gpapi::error::ServerTlsErrorKind;
|
||||
let tls = ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::LegacyRenegotiation,
|
||||
kind: ServerTlsErrorKind::Certificate,
|
||||
};
|
||||
let outcome = auth_outcome(Err(anyhow::Error::new(tls).context("retry failed")), None);
|
||||
assert_eq!(
|
||||
serde_json::to_value(outcome).unwrap(),
|
||||
json!({"serverTlsError": {"server": "https://vpn.example.com", "kind": "legacyRenegotiation"}})
|
||||
json!({"serverTlsError": {"server": "https://vpn.example.com", "kind": "certificate"}})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(auth_outcome(Err(anyhow::anyhow!("rejected")), None)).unwrap(),
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
use auth::{WebviewAuthenticator, apply_auth_theme};
|
||||
use gpapi::{auth::AuthWindowTheme, gp_params::GpParams};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use log::info;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tauri::RunEvent;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
use crate::cli::print_auth_result;
|
||||
|
||||
@@ -16,7 +10,6 @@ pub async fn authenticate(
|
||||
clean: bool,
|
||||
window_title: Option<String>,
|
||||
window_theme: AuthWindowTheme,
|
||||
#[cfg(not(target_os = "macos"))] mut openssl_conf: Option<NamedTempFile>,
|
||||
) -> anyhow::Result<()> {
|
||||
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
|
||||
|
||||
@@ -46,16 +39,7 @@ pub async fn authenticate(
|
||||
Ok(())
|
||||
})
|
||||
.build(crate::tauri_context::get())?
|
||||
.run(move |_app_handle, _event| {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if let RunEvent::Exit = _event {
|
||||
if let Some(file) = openssl_conf.take() {
|
||||
if let Err(err) = file.close() {
|
||||
info!("Error closing OpenSSL config file: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
.run(|_, _| {});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#![cfg(not(target_os = "macos"))]
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn deprecated_flag_warns_without_changing_auth_output_or_configuration() {
|
||||
const WARNING: &str = "--fix-openssl is deprecated and has no effect. It will be removed in a future release.";
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let configuration = directory.path().join("openssl.cnf");
|
||||
std::fs::write(&configuration, "existing user configuration").unwrap();
|
||||
for deprecated in [false, true] {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_gpauth"));
|
||||
command.arg("portal.example.com");
|
||||
if deprecated {
|
||||
command.arg("--fix-openssl");
|
||||
}
|
||||
// Reject invalid options before authentication, without making a network request.
|
||||
let output = command
|
||||
.args(["--browser-listen", "127.0.0.1", "--log-format", "json"])
|
||||
.env("OPENSSL_CONF", &configuration)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
let logs = String::from_utf8(output.stderr).unwrap();
|
||||
let records = logs
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
records.iter().filter(|record| record["message"] == WARNING).count(),
|
||||
usize::from(deprecated)
|
||||
);
|
||||
assert!(logs.contains("requires '--browser manual'"));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&configuration).unwrap(),
|
||||
"existing user configuration"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,6 @@ sysinfo.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
whoami.workspace = true
|
||||
tempfile.workspace = true
|
||||
reqwest.workspace = true
|
||||
directories.workspace = true
|
||||
compile-time.workspace = true
|
||||
@@ -40,3 +39,6 @@ webview-auth = ["gpapi/webview-auth"]
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
gpvpnc = { path = "../../crates/gpvpnc" }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
+12
-31
@@ -5,16 +5,12 @@ use std::{
|
||||
|
||||
use anyhow::bail;
|
||||
use clap::{Parser, Subcommand};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use gpapi::utils::openssl;
|
||||
use gpapi::{
|
||||
clap::{Args, InfoLevelVerbosity, handle_error},
|
||||
log_format::{LogFormat, write_json_record},
|
||||
};
|
||||
use log::info;
|
||||
use sysinfo::{Pid, System};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
use tempfile::NamedTempFile;
|
||||
use tokio::fs;
|
||||
|
||||
use crate::{
|
||||
@@ -36,8 +32,6 @@ const VERSION: &str = concat!(
|
||||
);
|
||||
|
||||
pub(crate) struct SharedArgs<'a> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(crate) fix_openssl: bool,
|
||||
pub(crate) ignore_tls_errors: bool,
|
||||
pub(crate) lock_file: &'a Path,
|
||||
pub(crate) verbose: &'a InfoLevelVerbosity,
|
||||
@@ -96,10 +90,7 @@ struct Cli {
|
||||
command: CliCommand,
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[arg(
|
||||
long,
|
||||
help = "Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats."
|
||||
)]
|
||||
#[arg(long, hide = true)]
|
||||
fix_openssl: bool,
|
||||
#[arg(long, help = "Ignore the TLS errors")]
|
||||
ignore_tls_errors: bool,
|
||||
@@ -127,11 +118,6 @@ struct Cli {
|
||||
}
|
||||
|
||||
impl Args for Cli {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
@@ -169,17 +155,14 @@ impl Cli {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
|
||||
if self.fix_openssl {
|
||||
let file = openssl::fix_openssl_env()?;
|
||||
return Ok(Some(file));
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if self.fix_openssl
|
||||
&& !(matches!(&self.command, CliCommand::Connect(args) if args.background) && self.background_worker_fd.is_none())
|
||||
{
|
||||
log::warn!("--fix-openssl is deprecated and has no effect. It will be removed in a future release.");
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
if let CliCommand::Connect(args) = &self.command {
|
||||
if args.dashboard {
|
||||
crate::dashboard::validate(self.log_format)?;
|
||||
@@ -214,13 +197,7 @@ impl Cli {
|
||||
None
|
||||
};
|
||||
|
||||
// The temp file will be dropped automatically when the file handle is dropped
|
||||
// So, declare it here to ensure it's not dropped
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _file = self.fix_openssl()?;
|
||||
let shared_args = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: self.fix_openssl,
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
lock_file: &self.lock_file,
|
||||
verbose: &self.verbose,
|
||||
@@ -370,9 +347,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openssl_option_is_available_only_on_supported_platforms() {
|
||||
fn deprecated_openssl_option_remains_supported_but_hidden() {
|
||||
let result = Cli::try_parse_from(["gpclient", "--fix-openssl", "diagnostics"]);
|
||||
assert_eq!(result.is_ok(), !cfg!(target_os = "macos"));
|
||||
for flag in ["-h", "--help"] {
|
||||
let help = Cli::try_parse_from(["gpclient", flag]).err().unwrap().to_string();
|
||||
assert!(!help.contains("--fix-openssl"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -138,9 +138,6 @@ impl ConnectHandler<'_> {
|
||||
.log_format(self.shared_args.log_format)
|
||||
.verbose(verbose);
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let auth_launcher = auth_launcher.fix_openssl(self.shared_args.fix_openssl);
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let use_default_browser = external_browser_supported && self.args.default_browser;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
|
||||
@@ -98,8 +98,6 @@ async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
@@ -144,8 +142,6 @@ async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_reject
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
@@ -192,8 +188,6 @@ async fn rendering_recovery_fetches_new_prelogin_metadata_and_preserves_gateway_
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
@@ -227,8 +221,6 @@ async fn cancellation_during_recovery_prelogin_stops_request() {
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
@@ -295,8 +287,6 @@ async fn auth_crash_uses_fresh_saml_and_clean_once_with_shared_budget() {
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
@@ -355,8 +345,6 @@ async fn exhausted_auth_recovery_is_terminal_before_portal_gateway_fallback() {
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
@@ -503,8 +491,6 @@ printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}'
|
||||
let lock = directory.join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
|
||||
@@ -185,11 +185,11 @@ impl<'a> ConnectHandler<'a> {
|
||||
|
||||
match identity_error {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
| RequestIdentityError::LegacyKeyConversion(_)
|
||||
| RequestIdentityError::UnsupportedKeyFormat
|
||||
| RequestIdentityError::InvalidKey
|
||||
| RequestIdentityError::InvalidCertificate
|
||||
| RequestIdentityError::IncompletePkcs12
|
||||
| RequestIdentityError::AmbiguousPkcs12
|
||||
| RequestIdentityError::InvalidPkcs12(_) => return Err(err),
|
||||
RequestIdentityError::NoKey => {
|
||||
let format = self.shared_args.log_format;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#![cfg(not(target_os = "macos"))]
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn background_worker_warns_once_for_the_deprecated_flag() {
|
||||
const WARNING: &str = "--fix-openssl is deprecated and has no effect. It will be removed in a future release.";
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
for deprecated in [false, true] {
|
||||
let log = directory.path().join(format!("background-{deprecated}.log"));
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_gpclient"));
|
||||
if deprecated {
|
||||
command.arg("--fix-openssl");
|
||||
}
|
||||
let output = command
|
||||
.arg("--lock-file")
|
||||
.arg(directory.path().join("client.pid"))
|
||||
.args([
|
||||
"--log-format",
|
||||
"json",
|
||||
"connect",
|
||||
"vpn.example.test",
|
||||
"--background",
|
||||
"--certificate",
|
||||
])
|
||||
// Fail identity preparation before authentication or a network connection.
|
||||
.arg(directory.path().join("missing.pem"))
|
||||
.arg("--log-file")
|
||||
.arg(&log)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
let mut records = String::from_utf8(output.stderr).unwrap();
|
||||
records.push_str(&std::fs::read_to_string(log).unwrap());
|
||||
assert!(records.contains("Failed to read client identity"), "{records}");
|
||||
assert_eq!(records.matches(WARNING).count(), usize::from(deprecated), "{records}");
|
||||
}
|
||||
}
|
||||
@@ -73,5 +73,11 @@ async fn embedded_collector_reports_missing_helpers_without_recursing_or_exposin
|
||||
report["fields"]["env.XDG_CURRENT_DESKTOP"]["value"],
|
||||
"TestDesktop Injected: secret"
|
||||
);
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("Using 'UnsafeLegacyServerConnect'"));
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
.matches("--fix-openssl is deprecated and has no effect. It will be removed in a future release.")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
@@ -33,7 +33,12 @@ impl<'a> FileDownloader<'a> {
|
||||
}
|
||||
|
||||
pub async fn download(&self) -> anyhow::Result<NamedTempFile> {
|
||||
let res = reqwest::get(self.url).await?.error_for_status()?;
|
||||
let res = gpapi::utils::request::client_builder()
|
||||
.build()?
|
||||
.get(self.url)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
let content_length = res.content_length().unwrap_or(0);
|
||||
|
||||
info!("Content length: {}", content_length);
|
||||
@@ -79,7 +84,12 @@ impl<'a> ChecksumFetcher<'a> {
|
||||
}
|
||||
|
||||
pub async fn fetch(&self) -> anyhow::Result<String> {
|
||||
let res = reqwest::get(self.url).await?.error_for_status()?;
|
||||
let res = gpapi::utils::request::client_builder()
|
||||
.build()?
|
||||
.get(self.url)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
let checksum = res.text().await?.trim().to_string();
|
||||
|
||||
Ok(checksum)
|
||||
|
||||
@@ -14,7 +14,10 @@ base64.workspace = true
|
||||
dns-lookup = { workspace = true, optional = true }
|
||||
log.workspace = true
|
||||
reqwest.workspace = true
|
||||
native-tls = "0.2"
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-pemfile = "2"
|
||||
p12-keystore = "0.4.1"
|
||||
sec1 = { version = "0.8.1", default-features = false, features = ["der"] }
|
||||
pem.workspace = true
|
||||
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
|
||||
x509-cert = { version = "0.3", default-features = false }
|
||||
@@ -54,16 +57,15 @@ env_logger = { workspace = true, optional = true }
|
||||
log-reload = { version = "0.1", optional = true }
|
||||
|
||||
[target.'cfg(any(target_os="macos", target_os="ios"))'.dependencies]
|
||||
security-framework = "3"
|
||||
oslog = { version = "0.2", default-features = false, optional = true }
|
||||
|
||||
# Dependencies for Linux and other OSes only
|
||||
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(not(any(target_os = "macos", target_os = "ios")))'.dependencies]
|
||||
openssl.workspace = true
|
||||
version-compare = "0.2"
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
pkg-config = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=src/utils/certificate/gnutls.c");
|
||||
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
if !matches!(target.as_str(), "macos" | "linux" | "freebsd" | "openbsd") {
|
||||
return;
|
||||
}
|
||||
let mut package = pkg_config::Config::new();
|
||||
package.atleast_version("3.6").cargo_metadata(false);
|
||||
let library = package
|
||||
.probe("gnutls")
|
||||
.expect("GnuTLS development files are required for desktop certificate import");
|
||||
let mut build = cc::Build::new();
|
||||
build.file("src/utils/certificate/gnutls.c");
|
||||
for include in library.include_paths {
|
||||
build.include(include);
|
||||
}
|
||||
build.compile("gp_certificate_import");
|
||||
// GNU linkers must see the shim before its GnuTLS dependency (--as-needed).
|
||||
package
|
||||
.cargo_metadata(true)
|
||||
.probe("gnutls")
|
||||
.expect("GnuTLS was probed above");
|
||||
}
|
||||
@@ -11,8 +11,6 @@ use crate::{
|
||||
pub mod args;
|
||||
|
||||
pub trait Args {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool;
|
||||
fn ignore_tls_errors(&self) -> bool;
|
||||
|
||||
/// How this program renders its logs.
|
||||
@@ -43,14 +41,6 @@ fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
|
||||
// users already see; keep it exactly.
|
||||
let mut hints = Vec::new();
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if kind == ServerTlsErrorKind::LegacyRenegotiation && !args.fix_openssl() {
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
"Re-run it with the `--fix-openssl` option to work around this issue, e.g.:\n\n{program} --fix-openssl {rest}"
|
||||
));
|
||||
}
|
||||
|
||||
if kind == ServerTlsErrorKind::Certificate && !args.ignore_tls_errors() {
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
@@ -204,18 +194,11 @@ mod tests {
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: bool,
|
||||
ignore_tls_errors: bool,
|
||||
log_format: LogFormat,
|
||||
}
|
||||
|
||||
impl Args for TestArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
@@ -260,31 +243,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hints_distinguish_legacy_and_unknown_tls_and_respect_both_flags() {
|
||||
let legacy = ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::LegacyRenegotiation,
|
||||
};
|
||||
let hints = retry_hints(&anyhow!(legacy.clone()), &TestArgs::default());
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(hints.is_empty());
|
||||
} else {
|
||||
assert_eq!(hints.len(), 1);
|
||||
assert!(hints[0].contains("--fix-openssl"));
|
||||
}
|
||||
let args = TestArgs {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: true,
|
||||
ignore_tls_errors: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(retry_hints(&anyhow!(legacy), &args).is_empty());
|
||||
assert!(retry_hints(&anyhow!(certificate_error()), &args).is_empty());
|
||||
let other = ServerTlsError {
|
||||
fn unknown_tls_failure_does_not_suggest_bypassing_certificate_validation() {
|
||||
let error = ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::Other,
|
||||
};
|
||||
assert!(retry_hints(&anyhow!(other), &TestArgs::default()).is_empty());
|
||||
assert!(retry_hints(&anyhow!(error), &TestArgs::default()).is_empty());
|
||||
}
|
||||
|
||||
/// Suggesting an option the user already passed is noise, and in JSON mode it
|
||||
|
||||
@@ -4,13 +4,6 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::PortalError;
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
#[path = "server_tls/apple.rs"]
|
||||
mod backend;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
#[path = "server_tls/openssl.rs"]
|
||||
mod backend;
|
||||
|
||||
/// A VPN HTTP TLS failure. The server identifies the configured VPN origin,
|
||||
/// not necessarily the peer that failed after an HTTP redirect.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -25,7 +18,6 @@ pub struct ServerTlsError {
|
||||
pub enum ServerTlsErrorKind {
|
||||
Certificate,
|
||||
ClientCertificateRequired,
|
||||
LegacyRenegotiation,
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -43,7 +35,6 @@ impl fmt::Display for ServerTlsError {
|
||||
let message = match self.kind {
|
||||
ServerTlsErrorKind::Certificate => "The server's certificate could not be verified",
|
||||
ServerTlsErrorKind::ClientCertificateRequired => "The server requires a client certificate",
|
||||
ServerTlsErrorKind::LegacyRenegotiation => "The server requires unsafe legacy TLS renegotiation",
|
||||
ServerTlsErrorKind::Other => "A secure connection to the server could not be established",
|
||||
};
|
||||
write!(f, "{message}: {}", self.server)
|
||||
@@ -70,122 +61,25 @@ impl ServerTlsErrorKind {
|
||||
|
||||
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
|
||||
let mut source = Some(error);
|
||||
let mut fallback = None;
|
||||
while let Some(error) = source {
|
||||
if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
|
||||
return Some(tls.kind);
|
||||
}
|
||||
if let Some(kind) = backend::classify(error) {
|
||||
return Some(kind);
|
||||
}
|
||||
if let Some(tls) = error.downcast_ref::<native_tls::Error>() {
|
||||
let kind = classify_native(tls);
|
||||
if kind != ServerTlsErrorKind::Other {
|
||||
return Some(kind);
|
||||
}
|
||||
fallback = Some(kind);
|
||||
if let Some(tls) = error.downcast_ref::<rustls::Error>() {
|
||||
return Some(match tls {
|
||||
rustls::Error::InvalidCertificate(_) => ServerTlsErrorKind::Certificate,
|
||||
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
|
||||
ServerTlsErrorKind::ClientCertificateRequired
|
||||
}
|
||||
_ => ServerTlsErrorKind::Other,
|
||||
});
|
||||
}
|
||||
source = error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.and_then(|error| error.get_ref().map(|inner| inner as &(dyn Error + 'static)))
|
||||
.or_else(|| error.source());
|
||||
}
|
||||
fallback
|
||||
}
|
||||
|
||||
fn classify_native(error: &native_tls::Error) -> ServerTlsErrorKind {
|
||||
// native-tls hides some backend reason codes and verification results. Keep
|
||||
// backend text matching here, scoped to a confirmed native TLS error.
|
||||
let detail = format!("{error:?}").to_ascii_lowercase();
|
||||
classify_native_detail(&detail)
|
||||
}
|
||||
|
||||
fn classify_native_detail(detail: &str) -> ServerTlsErrorKind {
|
||||
// native-tls forwards Security.framework's Debug representation, but hides
|
||||
// its OSStatus from the public error chain. Prefer that status to localized
|
||||
// text, including for peer alerts that can mention a rejected client cert.
|
||||
if let Some(code) = detail
|
||||
.strip_prefix("error { code: ")
|
||||
.and_then(|detail| detail.split_once(','))
|
||||
.and_then(|(code, _)| code.parse::<i32>().ok())
|
||||
{
|
||||
return classify_macos_status(code);
|
||||
}
|
||||
if detail.contains("unsafe legacy renegotiation") {
|
||||
return ServerTlsErrorKind::LegacyRenegotiation;
|
||||
}
|
||||
if detail.contains("alert certificate required") {
|
||||
return ServerTlsErrorKind::ClientCertificateRequired;
|
||||
}
|
||||
let certificate = [
|
||||
"certificate verify failed",
|
||||
"certificate verification failed",
|
||||
"certificate was not trusted",
|
||||
"certificate is not trusted",
|
||||
"self signed certificate",
|
||||
"hostname mismatch",
|
||||
"certificate has expired",
|
||||
"certificate is not yet valid",
|
||||
"certificate has been revoked",
|
||||
]
|
||||
.iter()
|
||||
.any(|reason| detail.contains(reason));
|
||||
if certificate {
|
||||
ServerTlsErrorKind::Certificate
|
||||
} else {
|
||||
ServerTlsErrorKind::Other
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_macos_status(code: i32) -> ServerTlsErrorKind {
|
||||
if code == -9863 {
|
||||
return ServerTlsErrorKind::ClientCertificateRequired;
|
||||
}
|
||||
// Local server-certificate validation failures from Security/SecBase.h.
|
||||
// Peer alerts (errSSLPeer*) reject our client certificate; protocol/cipher,
|
||||
// keychain, and internal errors also cannot be fixed by skipping server trust.
|
||||
let certificate = matches!(
|
||||
code,
|
||||
-9807 // errSSLXCertChainInvalid
|
||||
| -9812 // errSSLUnknownRootCert
|
||||
| -9813 // errSSLNoRootCert
|
||||
| -9814 // errSSLCertExpired
|
||||
| -9815 // errSSLCertNotYetValid
|
||||
| -9843 // errSSLHostNameMismatch
|
||||
| -9884 // errSSLATSLeafCertificateHashAlgorithmViolation
|
||||
| -9885 // errSSLATSCertificateHashAlgorithmViolation
|
||||
| -9886 // errSSLATSCertificateTrustViolation
|
||||
| -67602 // errSecHostNameMismatch
|
||||
| -67603 // errSecUnknownCriticalExtensionFlag
|
||||
| -67604 // errSecNoBasicConstraints
|
||||
| -67605 // errSecNoBasicConstraintsCA
|
||||
| -67606 // errSecInvalidAuthorityKeyID
|
||||
| -67607 // errSecInvalidSubjectKeyID
|
||||
| -67608 // errSecInvalidKeyUsageForPolicy
|
||||
| -67609 // errSecInvalidExtendedKeyUsage
|
||||
| -67610 // errSecInvalidIDLinkage
|
||||
| -67611 // errSecPathLengthConstraintExceeded
|
||||
| -67612 // errSecInvalidRoot
|
||||
| -67629 // errSecSSLBadExtendedKeyUsage
|
||||
| -67654 // errSecTrustSettingDeny
|
||||
| -67818 // errSecCertificateExpired
|
||||
| -67819 // errSecCertificateNotValidYet
|
||||
| -67820 // errSecCertificateRevoked
|
||||
| -67821 // errSecCertificateSuspended
|
||||
| -67826 // errSecInvalidCertAuthority
|
||||
| -67843 // errSecNotTrusted
|
||||
| -67899 // errSecCertificatePolicyNotAllowed
|
||||
| -67900 // errSecCertificateNameNotAllowed
|
||||
| -67901 // errSecCertificateValidityPeriodTooLong
|
||||
| -67902 // errSecCertificateIsCA
|
||||
| -67903 // errSecCertificateDuplicateExtension
|
||||
| -67904 // errSecMissingQualifiedCertStatement
|
||||
);
|
||||
if certificate {
|
||||
ServerTlsErrorKind::Certificate
|
||||
} else {
|
||||
ServerTlsErrorKind::Other
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -207,39 +101,26 @@ mod tests {
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn explicit_client_certificate_requirement_has_a_distinct_kind() {
|
||||
let kind = classify_native_detail("error { code: -9863, message: \"localized message\" }");
|
||||
assert_eq!(serde_json::to_value(kind).unwrap(), "clientCertificateRequired");
|
||||
assert_eq!(
|
||||
classify_native_detail("error { code: -9842, message: \"client cert requested\" }"),
|
||||
ServerTlsErrorKind::Other
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macos_certificate_statuses_do_not_depend_on_the_error_message() {
|
||||
for code in [-67818, -67819, -67820, -67843, -67602, -67629, -67899, -67901] {
|
||||
let detail = format!("error {{ code: {code}, message: \"localized message\" }}");
|
||||
fn typed_tls_causes_distinguish_local_trust_from_peer_alerts() {
|
||||
for reason in [
|
||||
rustls::CertificateError::Expired,
|
||||
rustls::CertificateError::UnknownIssuer,
|
||||
] {
|
||||
let error = std::io::Error::other(std::io::Error::other(rustls::Error::InvalidCertificate(reason)));
|
||||
assert_eq!(classify(&error), Some(ServerTlsErrorKind::Certificate));
|
||||
}
|
||||
for alert in [
|
||||
rustls::AlertDescription::UnknownCA,
|
||||
rustls::AlertDescription::BadCertificate,
|
||||
] {
|
||||
assert_eq!(
|
||||
classify_native_detail(&detail),
|
||||
ServerTlsErrorKind::Certificate,
|
||||
"{code}"
|
||||
classify(&rustls::Error::AlertReceived(alert)),
|
||||
Some(ServerTlsErrorKind::Other)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macos_peer_alerts_and_handshake_errors_are_not_certificate_validation_failures() {
|
||||
for (code, message) in [
|
||||
(-9800, "SSL protocol error"),
|
||||
(-9801, "Cipher Suite negotiation failure"),
|
||||
(-9828, "peer certificate has expired"),
|
||||
(-9831, "unknown certificate authority"),
|
||||
(-9850, "weak ephemeral DH key"),
|
||||
] {
|
||||
let detail = format!("error {{ code: {code}, message: \"{message}\" }}").to_ascii_lowercase();
|
||||
assert_eq!(classify_native_detail(&detail), ServerTlsErrorKind::Other, "{code}");
|
||||
}
|
||||
let required = rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired);
|
||||
assert_eq!(classify(&required), Some(ServerTlsErrorKind::ClientCertificateRequired));
|
||||
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None);
|
||||
}
|
||||
|
||||
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
||||
@@ -335,7 +216,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
|
||||
let (address, worker) = server(false);
|
||||
let error = reqwest::Client::builder()
|
||||
let error = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
@@ -354,7 +235,7 @@ mod tests {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = format!("https://{}", listener.local_addr().unwrap());
|
||||
drop(listener);
|
||||
let error = reqwest::Client::builder()
|
||||
let error = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
@@ -365,17 +246,6 @@ mod tests {
|
||||
assert_eq!(classify(&error), None);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
#[test]
|
||||
fn wrapped_macos_io_status_retains_the_client_certificate_requirement() {
|
||||
let error = std::io::Error::other(std::io::Error::other(security_framework::base::Error::from(-9863)));
|
||||
let server = url::Url::parse("https://vpn.example.com/login?token=secret").unwrap();
|
||||
let tls = ServerTlsError::from_request(&server, &error).unwrap();
|
||||
assert_eq!(tls.kind, ServerTlsErrorKind::ClientCertificateRequired);
|
||||
assert_eq!(tls.server, "https://vpn.example.com");
|
||||
assert_eq!(classify(&std::io::Error::other("alert certificate required")), None);
|
||||
}
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
#[test]
|
||||
fn rendering_recovery_retains_client_certificate_requirement() {
|
||||
@@ -436,19 +306,11 @@ mod tests {
|
||||
worker.join().unwrap();
|
||||
let kind =
|
||||
ServerTlsErrorKind::from_error(&error).unwrap_or_else(|| panic!("{operation}: unclassified: {error:?}"));
|
||||
// Secure Transport's TLS 1.2 handshake can return only a generic peer alert.
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
kind,
|
||||
ServerTlsErrorKind::ClientCertificateRequired | ServerTlsErrorKind::Other
|
||||
));
|
||||
} else {
|
||||
assert_eq!(
|
||||
kind,
|
||||
ServerTlsErrorKind::ClientCertificateRequired,
|
||||
"{operation}: {error:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
kind,
|
||||
ServerTlsErrorKind::ClientCertificateRequired,
|
||||
"{operation}: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -484,6 +346,78 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
|
||||
use crate::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
portal::{PreloginOptions, prelogin},
|
||||
};
|
||||
let fixture = |name: &str| format!("{}/tests/files/client-identity/{name}", env!("CARGO_MANIFEST_DIR"));
|
||||
for (certificate, key, password) in [
|
||||
(
|
||||
"rsa-cert.pem",
|
||||
Some("rsa-traditional-aes256.pem"),
|
||||
Some("fixture-password"),
|
||||
),
|
||||
("ec-cert.pem", Some("ec-traditional-des3.pem"), Some("fixture-password")),
|
||||
("rsa-cert.pem", Some("rsa-pbes1-3des.pem"), Some("fixture-password")),
|
||||
("rsa-cert.pem", Some("rsa-pbes2-scrypt.pem"), Some("fixture-password")),
|
||||
("ec-cert.pem", Some("ec-sec1.pem"), None),
|
||||
("modern.p12", None, Some("fixture-password")),
|
||||
("legacy-rc2.p12", None, Some("fixture-password")),
|
||||
("empty-password.p12", None, None),
|
||||
("no-bag-ids.p12", None, None),
|
||||
] {
|
||||
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
||||
let mut builder =
|
||||
GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()));
|
||||
builder
|
||||
.ignore_tls_errors(true)
|
||||
.certificate(Some(fixture(certificate)))
|
||||
.sslkey(key.map(fixture))
|
||||
.key_password(password.map(str::to_owned));
|
||||
let mut params = builder.build();
|
||||
params
|
||||
.prepare_client_identity()
|
||||
.unwrap_or_else(|error| panic!("{certificate}/{key:?}: {error:?}"));
|
||||
let result = prelogin(&address, ¶ms, PreloginOptions::default()).await;
|
||||
worker.join().unwrap();
|
||||
assert!(matches!(
|
||||
result.unwrap_or_else(|error| panic!("{certificate}/{key:?}: {error:?}")),
|
||||
crate::portal::Prelogin::Saml(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Point at the GnuTLS fixture configured without RFC 5746, with a trusted test root.
|
||||
#[tokio::test]
|
||||
#[ignore = "requires GP_TLS_TEST_SERVER and GP_TLS_TEST_CA for the external GnuTLS fixture"]
|
||||
async fn tls12_peer_without_renegotiation_extension_uses_default_policy() {
|
||||
let server = std::env::var("GP_TLS_TEST_SERVER").unwrap();
|
||||
let root = std::fs::read(std::env::var("GP_TLS_TEST_CA").unwrap()).unwrap();
|
||||
let client = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.add_root_certificate(reqwest::Certificate::from_pem(&root).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(client.get(&server).send().await.unwrap().status().is_success());
|
||||
let error = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(&server)
|
||||
.send()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error)
|
||||
.unwrap()
|
||||
.kind,
|
||||
ServerTlsErrorKind::Certificate
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_response_reads_preserve_the_transport_cause() {
|
||||
for status in [200, 403] {
|
||||
@@ -500,7 +434,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
let response = reqwest::Client::builder()
|
||||
let response = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
use std::error::Error;
|
||||
|
||||
use super::{ServerTlsErrorKind, classify_macos_status};
|
||||
|
||||
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
|
||||
error
|
||||
.downcast_ref::<security_framework::base::Error>()
|
||||
.map(|error| classify_macos_status(error.code()))
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use std::error::Error;
|
||||
|
||||
use super::ServerTlsErrorKind;
|
||||
|
||||
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
|
||||
let stack = error.downcast_ref::<openssl::error::ErrorStack>().or_else(|| {
|
||||
error
|
||||
.downcast_ref::<openssl::ssl::Error>()
|
||||
.and_then(openssl::ssl::Error::ssl_error)
|
||||
})?;
|
||||
// ERR_LIB_SSL and SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED from sslerr.h.
|
||||
stack
|
||||
.errors()
|
||||
.iter()
|
||||
.any(|error| error.library_code() == 20 && error.reason_code() == 1116)
|
||||
.then_some(ServerTlsErrorKind::ClientCertificateRequired)
|
||||
}
|
||||
@@ -161,7 +161,7 @@ impl GpParams {
|
||||
}
|
||||
|
||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||
let mut builder = Client::builder()
|
||||
let mut builder = crate::utils::request::client_builder()
|
||||
.tls_info(true)
|
||||
.danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||
.user_agent(self.user_agent());
|
||||
|
||||
@@ -33,8 +33,6 @@ pub struct SamlAuthLauncher<'a> {
|
||||
certificate: Option<&'a str>,
|
||||
sslkey: Option<&'a str>,
|
||||
key_password: Option<&'a str>,
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: bool,
|
||||
ignore_tls_errors: bool,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
hidpi: bool,
|
||||
@@ -67,8 +65,6 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
certificate: None,
|
||||
sslkey: None,
|
||||
key_password: None,
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fix_openssl: false,
|
||||
ignore_tls_errors: false,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
hidpi: false,
|
||||
@@ -115,12 +111,6 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn fix_openssl(mut self, fix_openssl: bool) -> Self {
|
||||
self.fix_openssl = fix_openssl;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
|
||||
self.ignore_tls_errors = ignore_tls_errors;
|
||||
self
|
||||
@@ -229,11 +219,6 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
auth_cmd.arg("--client-version").arg(client_version);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if self.fix_openssl {
|
||||
auth_cmd.arg("--fix-openssl");
|
||||
}
|
||||
|
||||
if self.ignore_tls_errors {
|
||||
auth_cmd.arg("--ignore-tls-errors");
|
||||
}
|
||||
@@ -419,13 +404,8 @@ mod tests {
|
||||
#[test]
|
||||
fn launches_with_platform_tls_options() {
|
||||
let launcher = SamlAuthLauncher::new("vpn.example.com").ignore_tls_errors(true);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let launcher = launcher.fix_openssl(true);
|
||||
let args = child_args(launcher);
|
||||
assert_eq!(
|
||||
args.iter().any(|arg| arg == "--fix-openssl"),
|
||||
!cfg!(target_os = "macos")
|
||||
);
|
||||
assert!(!args.iter().any(|arg| arg == "--fix-openssl"));
|
||||
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
|
||||
}
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ async fn gateway_fixture(
|
||||
requests
|
||||
});
|
||||
let transport = GatewayTransport {
|
||||
client: Client::builder()
|
||||
client: crate::utils::request::client_builder()
|
||||
.redirect(Policy::none())
|
||||
.no_proxy()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#include <gnutls/gnutls.h>
|
||||
#include <gnutls/x509.h>
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
|
||||
/* Only decrypted PKCS#8 leaves this interface. The Rust owner releases it with
|
||||
* gp_key_free, so GnuTLS allocation and wiping stay with the native allocator. */
|
||||
int gp_key_import(const unsigned char *input, size_t length, int pem,
|
||||
const char *password, unsigned char **output, size_t *output_length) {
|
||||
gnutls_x509_privkey_t key = NULL;
|
||||
gnutls_datum_t exported = {NULL, 0};
|
||||
int result;
|
||||
*output = NULL;
|
||||
*output_length = 0;
|
||||
if (length > UINT_MAX) return 3;
|
||||
result = gnutls_global_init();
|
||||
if (result < 0) return 3;
|
||||
result = gnutls_x509_privkey_init(&key);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t data = {(unsigned char *)input, (unsigned int)length};
|
||||
result = gnutls_x509_privkey_import2(key, &data,
|
||||
pem ? GNUTLS_X509_FMT_PEM : GNUTLS_X509_FMT_DER, password, 0);
|
||||
}
|
||||
if (result >= 0) {
|
||||
result = gnutls_x509_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER,
|
||||
NULL, GNUTLS_PKCS_PLAIN, &exported);
|
||||
}
|
||||
if (key != NULL) gnutls_x509_privkey_deinit(key);
|
||||
gnutls_global_deinit();
|
||||
if (result >= 0) {
|
||||
*output = exported.data;
|
||||
*output_length = exported.size;
|
||||
return 0;
|
||||
}
|
||||
if (result == GNUTLS_E_DECRYPTION_FAILED) return 1;
|
||||
if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE)
|
||||
return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
void gp_key_free(unsigned char *data, size_t length) {
|
||||
if (data != NULL) {
|
||||
gnutls_memset(data, 0, length);
|
||||
gnutls_free(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::ffi::{c_char, c_int};
|
||||
|
||||
use pkcs8::SecretDocument;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn gp_key_import(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
pem: c_int,
|
||||
password: *const c_char,
|
||||
output: *mut *mut u8,
|
||||
output_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_key_free(data: *mut u8, length: usize);
|
||||
}
|
||||
|
||||
struct ExportedKey {
|
||||
data: *mut u8,
|
||||
length: usize,
|
||||
}
|
||||
|
||||
impl Drop for ExportedKey {
|
||||
fn drop(&mut self) {
|
||||
// The shim owns the allocation and wipes it before releasing it.
|
||||
unsafe { gp_key_free(self.data, self.length) };
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
anyhow::ensure!(
|
||||
!passphrase.as_bytes().contains(&0),
|
||||
"Private key passphrases containing NUL are not supported"
|
||||
);
|
||||
let mut password = Zeroizing::new(passphrase.as_bytes().to_vec());
|
||||
password.push(0);
|
||||
let mut exported = ExportedKey {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
// All input slices remain live for the call; the output is owned by the guard.
|
||||
let result = unsafe {
|
||||
gp_key_import(
|
||||
bytes.as_ptr(),
|
||||
bytes.len(),
|
||||
i32::from(pem),
|
||||
password.as_ptr().cast(),
|
||||
&mut exported.data,
|
||||
&mut exported.length,
|
||||
)
|
||||
};
|
||||
match result {
|
||||
0 => {
|
||||
anyhow::ensure!(!exported.data.is_null() && exported.length > 0, "Invalid private key");
|
||||
// A successful shim call returns an initialized allocation of this length.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(exported.data, exported.length) };
|
||||
SecretDocument::try_from(bytes).map_err(|_| RequestIdentityError::InvalidKey.into())
|
||||
}
|
||||
1 => Err(RequestIdentityError::DecryptError("PEM").into()),
|
||||
2 => Err(RequestIdentityError::UnsupportedEncryption.into()),
|
||||
_ => Err(RequestIdentityError::InvalidKey.into()),
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
//! Optional compatibility conversion for standalone PKCS#12 PBE-SHA1-3DES keys.
|
||||
//! The executable is a runtime option, not a linked or bundled dependency.
|
||||
use std::{
|
||||
io::{ErrorKind, Read, Write},
|
||||
os::{fd::AsFd, unix::process::CommandExt},
|
||||
process::{Child, Command, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
sys::signal::{Signal, killpg},
|
||||
unistd::Pid,
|
||||
};
|
||||
use pkcs8::SecretDocument;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::request::RequestIdentityError::{self, LegacyKeyConversion};
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_OUTPUT: u64 = 1024 * 1024;
|
||||
const MAX_PASSWORD_BYTES: usize = 1023;
|
||||
|
||||
// The converter owns a separate process group, including wrapper descendants.
|
||||
// Clean up that group and reap the direct child on every return path.
|
||||
struct Converter(Child);
|
||||
|
||||
impl Drop for Converter {
|
||||
fn drop(&mut self) {
|
||||
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn nonblocking(pipe: &impl AsFd) -> anyhow::Result<()> {
|
||||
fcntl(pipe, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))
|
||||
.map_err(|_| LegacyKeyConversion("could not configure converter pipes"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Read at most one chunk per iteration so a busy pipe cannot starve the deadline.
|
||||
// Returns true only after EOF; inherited pipes remain subject to the deadline.
|
||||
fn read_output(pipe: &mut impl Read, output: &mut Zeroizing<Vec<u8>>, limit: u64) -> anyhow::Result<bool> {
|
||||
let mut buffer = Zeroizing::new([0u8; 8192]);
|
||||
match pipe.read(buffer.as_mut_slice()) {
|
||||
Ok(0) => Ok(true),
|
||||
Ok(count) => {
|
||||
if output.len() as u64 + count as u64 > limit {
|
||||
return Err(LegacyKeyConversion("converter output exceeds the size limit").into());
|
||||
}
|
||||
output.extend_from_slice(&buffer[..count]);
|
||||
Ok(false)
|
||||
}
|
||||
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => Ok(false),
|
||||
Err(_) => Err(LegacyKeyConversion("could not read converter output").into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
// The command's line reader reserves one byte for a terminator. The linked
|
||||
// OpenSSL API accepted 1024 bytes, but the CLI would truncate that password.
|
||||
if passphrase.len() > MAX_PASSWORD_BYTES {
|
||||
return Err(LegacyKeyConversion("the password exceeds OpenSSL's 1023-byte input limit").into());
|
||||
}
|
||||
// OpenSSL's pipe password source reads one line. Never silently truncate it.
|
||||
if passphrase.contains(['\r', '\n', '\0']) {
|
||||
return Err(LegacyKeyConversion("the password cannot be passed through OpenSSL's line-based input").into());
|
||||
}
|
||||
|
||||
// Only encrypted input touches disk, in a private temporary file. The
|
||||
// original file is never changed and decrypted output stays in memory.
|
||||
let mut input = tempfile::NamedTempFile::new()?;
|
||||
input.write_all(pem::encode(&pem::Pem::new("ENCRYPTED PRIVATE KEY", der)).as_bytes())?;
|
||||
let child = Command::new("openssl")
|
||||
.args([
|
||||
"pkcs8", "-topk8", "-nocrypt", "-inform", "PEM", "-outform", "DER", "-in",
|
||||
])
|
||||
.arg(input.path())
|
||||
.args(["-passin", "stdin"])
|
||||
.env("LC_ALL", "C")
|
||||
.process_group(0)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|_| LegacyKeyConversion("the openssl executable is unavailable"))?;
|
||||
let mut converter = Converter(child);
|
||||
let mut stdin = converter.0.stdin.take();
|
||||
let mut stdout = converter.0.stdout.take().unwrap();
|
||||
let mut stderr = converter.0.stderr.take().unwrap();
|
||||
nonblocking(stdin.as_ref().unwrap())?;
|
||||
nonblocking(&stdout)?;
|
||||
nonblocking(&stderr)?;
|
||||
let mut password = Zeroizing::new(passphrase.as_bytes().to_vec());
|
||||
password.push(b'\n');
|
||||
let mut written = 0;
|
||||
let mut input_failed = false;
|
||||
let mut output = Zeroizing::new(Vec::new());
|
||||
let mut diagnostic = Zeroizing::new(Vec::new());
|
||||
let mut output_done = false;
|
||||
let mut diagnostic_done = false;
|
||||
let mut status = None;
|
||||
let started = Instant::now();
|
||||
let status = loop {
|
||||
if started.elapsed() >= TIMEOUT {
|
||||
return Err(LegacyKeyConversion("conversion timed out").into());
|
||||
}
|
||||
if let Some(pipe) = stdin.as_mut() {
|
||||
match pipe.write(&password[written..]) {
|
||||
Ok(0) => {
|
||||
input_failed = true;
|
||||
stdin = None;
|
||||
}
|
||||
Ok(count) => {
|
||||
written += count;
|
||||
if written == password.len() {
|
||||
stdin = None;
|
||||
}
|
||||
}
|
||||
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
|
||||
Err(_) => {
|
||||
input_failed = true;
|
||||
stdin = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !output_done {
|
||||
output_done = read_output(&mut stdout, &mut output, MAX_OUTPUT)?;
|
||||
}
|
||||
if !diagnostic_done {
|
||||
diagnostic_done = read_output(&mut stderr, &mut diagnostic, 16 * 1024)?;
|
||||
}
|
||||
if status.is_none() {
|
||||
status = converter
|
||||
.0
|
||||
.try_wait()
|
||||
.map_err(|_| LegacyKeyConversion("could not wait for the converter"))?;
|
||||
}
|
||||
if let Some(status) = status {
|
||||
if output_done && diagnostic_done && stdin.is_none() {
|
||||
break status;
|
||||
}
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
if status.success() && input_failed {
|
||||
return Err(LegacyKeyConversion("could not send the password").into());
|
||||
}
|
||||
|
||||
if !status.success() {
|
||||
// Never include the command's output in user-facing errors: it can contain
|
||||
// key material. Preserve the old Linux password retry contract only for
|
||||
// an explicit decryption failure, not missing cipher/provider support.
|
||||
if [b"bad decrypt".as_slice(), b"pkcs12 cipherfinal error".as_slice()]
|
||||
.iter()
|
||||
.any(|message| diagnostic.windows(message.len()).any(|window| window == *message))
|
||||
{
|
||||
return Err(RequestIdentityError::DecryptError("PEM").into());
|
||||
}
|
||||
return Err(LegacyKeyConversion("this OpenSSL installation cannot decrypt the key").into());
|
||||
}
|
||||
SecretDocument::try_from(output.as_slice()).map_err(|_| LegacyKeyConversion("invalid converted key").into())
|
||||
}
|
||||
@@ -1,18 +1,20 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "pkcs12/macos.rs"]
|
||||
pub(super) mod pkcs12_identity;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
#[path = "pkcs12/openssl.rs"]
|
||||
pub(super) mod pkcs12_identity;
|
||||
#[cfg(target_os = "ios")]
|
||||
#[path = "pkcs12/ios.rs"]
|
||||
pub(super) mod pkcs12_identity;
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
#[path = "traditional_key/apple.rs"]
|
||||
pub(super) mod traditional_key;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
#[path = "traditional_key/openssl.rs"]
|
||||
pub(super) mod traditional_key;
|
||||
pub(super) mod pkcs12;
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
pub(super) mod legacy_pkcs8;
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
#[path = "gnutls.rs"]
|
||||
mod legacy_key;
|
||||
#[cfg(not(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
#[path = "unsupported.rs"]
|
||||
mod legacy_key;
|
||||
|
||||
pub(super) use legacy_key::decrypt as decrypt_key;
|
||||
@@ -0,0 +1,72 @@
|
||||
use p12_keystore::Pkcs12Archive;
|
||||
use rustls::{
|
||||
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
|
||||
sign::CertifiedKey,
|
||||
};
|
||||
|
||||
use crate::utils::request::{RequestIdentityError, pem_request_identity};
|
||||
|
||||
pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<reqwest::Identity> {
|
||||
anyhow::ensure!(
|
||||
passphrase.is_none_or(|password| !password.as_bytes().contains(&0)),
|
||||
"PKCS#12 passphrases containing NUL are not supported"
|
||||
);
|
||||
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| {
|
||||
if passphrase.is_none() {
|
||||
RequestIdentityError::NoPassphrase("PKCS#12")
|
||||
} else {
|
||||
RequestIdentityError::InvalidPkcs12(error)
|
||||
}
|
||||
})?;
|
||||
if archive.keys.is_empty() || archive.certs.is_empty() {
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
if archive.keys.len() != 1 {
|
||||
return Err(RequestIdentityError::AmbiguousPkcs12.into());
|
||||
}
|
||||
let key = &archive.keys[0].key;
|
||||
let provider = rustls::crypto::ring::default_provider();
|
||||
let mut certs = Vec::new();
|
||||
for bag in &archive.certs {
|
||||
if !certs
|
||||
.iter()
|
||||
.any(|cert: &&p12_keystore::Certificate| cert.as_der() == bag.cert.as_der())
|
||||
{
|
||||
certs.push(&bag.cert);
|
||||
}
|
||||
}
|
||||
let matches: Vec<_> = certs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, cert)| {
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
|
||||
CertifiedKey::from_der(
|
||||
vec![CertificateDer::from(cert.as_der().to_vec())],
|
||||
private_key,
|
||||
&provider,
|
||||
)
|
||||
.is_ok()
|
||||
.then_some(index)
|
||||
})
|
||||
.collect();
|
||||
let leaf = match matches.as_slice() {
|
||||
[leaf] => *leaf,
|
||||
[] => return Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
_ => return Err(RequestIdentityError::AmbiguousPkcs12.into()),
|
||||
};
|
||||
let mut current = certs.remove(leaf);
|
||||
let mut chain = Vec::new();
|
||||
loop {
|
||||
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
|
||||
if current.subject() == current.issuer() {
|
||||
break;
|
||||
}
|
||||
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else {
|
||||
break;
|
||||
};
|
||||
current = certs.remove(parent);
|
||||
}
|
||||
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
pem_request_identity(&chain, key.as_bytes())
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use security_framework::import_export::Pkcs12ImportOptions;
|
||||
pub(in crate::utils) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
|
||||
if let Ok(imports) = Pkcs12ImportOptions::new().passphrase(password).import(bytes)
|
||||
&& !imports.last().is_some_and(|item| item.identity.is_some())
|
||||
{
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
use security_framework::{import_export::Pkcs12ImportOptions, os::macos::keychain::CreateOptions};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
pub(in crate::utils) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
|
||||
// native-tls assumes a successful import has a last item with an identity.
|
||||
// Incomplete archives violate that assumption and panic. Inspect them first
|
||||
// in a private temporary keychain, never the user's default keychain.
|
||||
let directory = tempfile::tempdir()?;
|
||||
let keychain = CreateOptions::new()
|
||||
.password(&uuid::Uuid::new_v4().to_string())
|
||||
.create(directory.path().join("identity.keychain"))?;
|
||||
if let Ok(imports) = Pkcs12ImportOptions::new()
|
||||
.keychain(keychain)
|
||||
.passphrase(password)
|
||||
.import(bytes)
|
||||
&& !imports.last().is_some_and(|item| item.identity.is_some())
|
||||
{
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
// Leave failed imports to reqwest so password errors retain their existing
|
||||
// classification and native error chain.
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
use openssl::pkcs12::Pkcs12;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
pub(in crate::utils) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
|
||||
// Parse errors belong to the existing native TLS importer. A successful parse
|
||||
// lets us report incomplete archives without suggesting a password change.
|
||||
if let Ok(archive) = Pkcs12::from_der(bytes).and_then(|archive| archive.parse2(password))
|
||||
&& (archive.pkey.is_none() || archive.cert.is_none())
|
||||
{
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use pkcs8::SecretDocument;
|
||||
|
||||
use crate::utils::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
|
||||
|
||||
pub(in crate::utils) fn normalize(
|
||||
_bytes: &[u8],
|
||||
format: TraditionalKeyFormat,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<SecretDocument> {
|
||||
Err(
|
||||
match format {
|
||||
TraditionalKeyFormat::EncryptedPem => RequestIdentityError::UnsupportedEncryption,
|
||||
TraditionalKeyFormat::PlainPem | TraditionalKeyFormat::Sec1Der => RequestIdentityError::UnsupportedKeyFormat,
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
use openssl::{
|
||||
error::ErrorStack,
|
||||
pkey::{Id, PKey},
|
||||
};
|
||||
use pkcs8::SecretDocument;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
|
||||
|
||||
pub(in crate::utils) fn normalize(
|
||||
bytes: &[u8],
|
||||
format: TraditionalKeyFormat,
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<SecretDocument> {
|
||||
let key = match format {
|
||||
TraditionalKeyFormat::Sec1Der => PKey::private_key_from_der(bytes),
|
||||
TraditionalKeyFormat::PlainPem => PKey::private_key_from_pem_passphrase(bytes, b""),
|
||||
TraditionalKeyFormat::EncryptedPem => {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
anyhow::ensure!(
|
||||
!passphrase.as_bytes().contains(&0),
|
||||
"Private key passphrases containing NUL are not supported"
|
||||
);
|
||||
PKey::private_key_from_pem_passphrase(bytes, passphrase.as_bytes())
|
||||
}
|
||||
}
|
||||
.map_err(import_error)?;
|
||||
if !matches!(key.id(), Id::RSA | Id::EC) {
|
||||
return Err(RequestIdentityError::UnsupportedKeyFormat.into());
|
||||
}
|
||||
let der = Zeroizing::new(
|
||||
key
|
||||
.private_key_to_pkcs8()
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?,
|
||||
);
|
||||
Ok(SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?)
|
||||
}
|
||||
|
||||
fn import_error(error: ErrorStack) -> RequestIdentityError {
|
||||
// Inspect only known backend reasons. Never expose the native error stack or
|
||||
// turn an unclassified decoder failure into a password retry loop.
|
||||
if error.errors().iter().any(|error| error.reason() == Some("bad decrypt")) {
|
||||
RequestIdentityError::DecryptError("PEM")
|
||||
} else if error.errors().iter().any(|error| error.reason() == Some("unsupported")) {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
} else {
|
||||
RequestIdentityError::InvalidKey
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! PEM/DER normalization; usable key and certificate imports stay with native TLS.
|
||||
//! PEM/DER normalization before rustls validates usable keys and identities.
|
||||
use pkcs8::{
|
||||
AlgorithmIdentifierRef, EncryptedPrivateKeyInfoRef, ObjectIdentifier, PrivateKeyInfoRef, SecretDocument,
|
||||
der::{
|
||||
@@ -8,13 +8,7 @@ use pkcs8::{
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{certificate::traditional_key, request::RequestIdentityError};
|
||||
|
||||
pub(super) enum TraditionalKeyFormat {
|
||||
Sec1Der,
|
||||
PlainPem,
|
||||
EncryptedPem,
|
||||
}
|
||||
use super::{certificate, request::RequestIdentityError};
|
||||
|
||||
struct PemBlock {
|
||||
tag: String,
|
||||
@@ -26,7 +20,9 @@ impl PemBlock {
|
||||
fn encoded(&self) -> Zeroizing<Vec<u8>> {
|
||||
let mut block = pem::Pem::new(&self.tag, self.contents.as_slice());
|
||||
*block.headers_mut() = self.headers.clone();
|
||||
let encoded = Zeroizing::new(pem::encode(&block).into_bytes());
|
||||
let encoded = Zeroizing::new(
|
||||
pem::encode_config(&block, pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF)).into_bytes(),
|
||||
);
|
||||
// The PEM crate owns a copy of the decoded private key as well.
|
||||
drop(Zeroizing::new(block.into_contents()));
|
||||
encoded
|
||||
@@ -77,13 +73,13 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
|
||||
if !matches!(block.tag.as_str(), "RSA PRIVATE KEY" | "EC PRIVATE KEY") {
|
||||
return Err(RequestIdentityError::InvalidKey.into());
|
||||
}
|
||||
traditional_key::normalize(&block.encoded(), TraditionalKeyFormat::EncryptedPem, passphrase)?
|
||||
certificate::decrypt_key(&block.encoded(), true, passphrase)?
|
||||
} else {
|
||||
match block.tag.as_str() {
|
||||
"PRIVATE KEY" => SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?,
|
||||
"RSA PRIVATE KEY" => {
|
||||
// PKCS#8 stores the original PKCS#1 bytes inside an RSA algorithm envelope.
|
||||
// Native TLS validates the RSA key, as it does for existing PKCS#8 input.
|
||||
// Rustls validates the RSA key along with the certificate.
|
||||
let algorithm = AlgorithmIdentifierRef {
|
||||
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
|
||||
parameters: Some(AnyRef::NULL),
|
||||
@@ -94,11 +90,8 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
|
||||
}
|
||||
"ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?,
|
||||
"EC PRIVATE KEY" => {
|
||||
if pem_input {
|
||||
traditional_key::normalize(&block.encoded(), TraditionalKeyFormat::PlainPem, passphrase)?
|
||||
} else {
|
||||
traditional_key::normalize(der, TraditionalKeyFormat::Sec1Der, passphrase)?
|
||||
}
|
||||
sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
return Ok(block.encoded());
|
||||
}
|
||||
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
|
||||
}
|
||||
@@ -172,12 +165,9 @@ fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocumen
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
if algorithm != pkcs8::pkcs5::pbes2::PBES2_OID {
|
||||
// PKCS#12 PBE-SHA1-3DES inside standalone PKCS#8 is not implemented by
|
||||
// RustCrypto. Only this known legacy scheme uses the optional executable.
|
||||
// RustCrypto. Only this known legacy scheme uses the native importer.
|
||||
if algorithm == pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3") {
|
||||
#[cfg(feature = "desktop")]
|
||||
return super::certificate::legacy_pkcs8::decrypt(der, passphrase);
|
||||
#[cfg(not(feature = "desktop"))]
|
||||
return Err(RequestIdentityError::UnsupportedEncryption.into());
|
||||
return certificate::decrypt_key(der, false, passphrase);
|
||||
}
|
||||
return Err(RequestIdentityError::UnsupportedEncryption.into());
|
||||
}
|
||||
|
||||
@@ -45,7 +45,10 @@ impl LockFile {
|
||||
Ok(content) => {
|
||||
let url = format!("http://127.0.0.1:{}/health", content.trim());
|
||||
|
||||
match reqwest::get(&url).await {
|
||||
let Ok(client) = crate::utils::request::client_builder().build() else {
|
||||
return false;
|
||||
};
|
||||
match client.get(&url).send().await {
|
||||
Ok(resp) => resp.status().is_success(),
|
||||
Err(_) => false,
|
||||
}
|
||||
|
||||
@@ -11,8 +11,6 @@ pub mod env_utils;
|
||||
mod identity_encoding;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod lock_file;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
pub mod openssl;
|
||||
pub mod redact;
|
||||
pub mod request;
|
||||
#[cfg(feature = "tauri")]
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
use std::path::Path;
|
||||
|
||||
use log::{info, warn};
|
||||
use regex::Regex;
|
||||
use tempfile::NamedTempFile;
|
||||
use version_compare::{Cmp, compare_to};
|
||||
|
||||
pub fn openssl_conf() -> String {
|
||||
let option = get_openssl_option();
|
||||
|
||||
format!(
|
||||
"openssl_conf = openssl_init
|
||||
|
||||
[openssl_init]
|
||||
ssl_conf = ssl_sect
|
||||
providers = provider_sect
|
||||
|
||||
[ssl_sect]
|
||||
system_default = system_default_sect
|
||||
|
||||
[system_default_sect]
|
||||
Options = {}
|
||||
|
||||
[provider_sect]
|
||||
default = default_sect
|
||||
legacy = legacy_sect
|
||||
|
||||
[default_sect]
|
||||
activate = 1
|
||||
|
||||
[legacy_sect]
|
||||
activate = 1
|
||||
",
|
||||
option
|
||||
)
|
||||
}
|
||||
|
||||
pub fn fix_openssl<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
|
||||
let content = openssl_conf();
|
||||
std::fs::write(path, content)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn fix_openssl_env() -> anyhow::Result<NamedTempFile> {
|
||||
let openssl_conf = NamedTempFile::new()?;
|
||||
let openssl_conf_path = openssl_conf.path();
|
||||
|
||||
fix_openssl(openssl_conf_path)?;
|
||||
unsafe { std::env::set_var("OPENSSL_CONF", openssl_conf_path) };
|
||||
|
||||
Ok(openssl_conf)
|
||||
}
|
||||
|
||||
// See: https://stackoverflow.com/questions/75763525/curl-35-error0a000152ssl-routinesunsafe-legacy-renegotiation-disabled
|
||||
fn get_openssl_option() -> &'static str {
|
||||
let version_str = openssl::version::version();
|
||||
let default_option = "UnsafeLegacyServerConnect";
|
||||
|
||||
let Some(version) = extract_openssl_version(version_str) else {
|
||||
warn!("Failed to extract OpenSSL version from '{}'", version_str);
|
||||
return default_option;
|
||||
};
|
||||
|
||||
let older_than_3_0_4 = match compare_to(version, "3.0.4", Cmp::Lt) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
warn!("Failed to compare OpenSSL version: {}", version);
|
||||
return default_option;
|
||||
}
|
||||
};
|
||||
|
||||
if older_than_3_0_4 {
|
||||
info!("Using 'UnsafeLegacyRenegotiation' option");
|
||||
"UnsafeLegacyRenegotiation"
|
||||
} else {
|
||||
info!("Using 'UnsafeLegacyServerConnect' option");
|
||||
default_option
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_openssl_version(version: &str) -> Option<&str> {
|
||||
let re = Regex::new(r"OpenSSL (\d+\.\d+\.\d+[^\s]*)").unwrap();
|
||||
re.captures(version).and_then(|caps| caps.get(1)).map(|m| m.as_str())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_extract_version() {
|
||||
let input = "OpenSSL 3.4.0 22 Oct 2024 (Library: OpenSSL 3.4.0 22 Oct 2024)";
|
||||
assert_eq!(extract_openssl_version(input), Some("3.4.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_different_format() {
|
||||
let input = "OpenSSL 1.1.1t 7 Feb 2023";
|
||||
assert_eq!(extract_openssl_version(input), Some("1.1.1t"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_input() {
|
||||
let input = "Invalid string without version";
|
||||
assert_eq!(extract_openssl_version(input), None);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use anyhow::{Context, ensure};
|
||||
use reqwest::Identity;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{certificate::pkcs12_identity, identity_encoding};
|
||||
use super::{certificate::pkcs12, identity_encoding};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RequestIdentityError {
|
||||
@@ -18,10 +18,6 @@ pub enum RequestIdentityError {
|
||||
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
|
||||
)]
|
||||
UnsupportedEncryption,
|
||||
#[error(
|
||||
"Could not convert the legacy private key with OpenSSL: {0}. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
|
||||
)]
|
||||
LegacyKeyConversion(&'static str),
|
||||
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")]
|
||||
UnsupportedKeyFormat,
|
||||
#[error("Invalid private key")]
|
||||
@@ -31,7 +27,9 @@ pub enum RequestIdentityError {
|
||||
#[error("The PKCS#12 file must contain both a client certificate and its private key")]
|
||||
IncompletePkcs12,
|
||||
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")]
|
||||
InvalidPkcs12(#[source] reqwest::Error),
|
||||
InvalidPkcs12(#[source] p12_keystore::error::Error),
|
||||
#[error("The PKCS#12 file must contain one matching client identity")]
|
||||
AmbiguousPkcs12,
|
||||
}
|
||||
|
||||
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
|
||||
@@ -91,16 +89,7 @@ impl ClientIdentity {
|
||||
let (identity, passphrase) = match &key {
|
||||
Some(key) => (pem_request_identity(&certificate, key)?, None),
|
||||
None => {
|
||||
pkcs12_identity::ensure_complete(&certificate, passphrase.unwrap_or_default())?;
|
||||
// A blank settings field is stored as None. Try the empty password so
|
||||
// passwordless archives work, but keep prompting for protected ones.
|
||||
let identity = Identity::from_pkcs12_der(&certificate, passphrase.unwrap_or_default()).map_err(|error| {
|
||||
if passphrase.is_none() {
|
||||
RequestIdentityError::NoPassphrase("PKCS#12")
|
||||
} else {
|
||||
RequestIdentityError::InvalidPkcs12(error)
|
||||
}
|
||||
})?;
|
||||
let identity = pkcs12::identity(&certificate, passphrase)?;
|
||||
(
|
||||
identity,
|
||||
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
|
||||
@@ -160,13 +149,22 @@ impl ClientIdentityFiles {
|
||||
}
|
||||
}
|
||||
|
||||
fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
|
||||
pub(super) fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
|
||||
let error_context =
|
||||
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
|
||||
let identity = Identity::from_pkcs8_pem(certificate, key).context(error_context)?;
|
||||
// Native TLS may defer the certificate/key match check until connector creation.
|
||||
// Build the same client used for requests without making a network connection.
|
||||
reqwest::Client::builder()
|
||||
let mut combined = Zeroizing::new(certificate.to_vec());
|
||||
combined.push(b'\n');
|
||||
combined.extend_from_slice(key);
|
||||
let identity = Identity::from_pem(&combined).context(error_context)?;
|
||||
let certificates = rustls_pemfile::certs(&mut std::io::Cursor::new(certificate))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context(error_context)?;
|
||||
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(key))
|
||||
.context(error_context)?
|
||||
.context(error_context)?;
|
||||
rustls::sign::CertifiedKey::from_der(certificates, private_key, &rustls::crypto::ring::default_provider())
|
||||
.context(error_context)?;
|
||||
client_builder()
|
||||
.no_proxy()
|
||||
.identity(identity.clone())
|
||||
.build()
|
||||
@@ -202,6 +200,14 @@ fn write_identity_file(
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// Ordinary Reqwest construction with the shared rustls provider initialized.
|
||||
pub fn client_builder() -> reqwest::ClientBuilder {
|
||||
if rustls::crypto::CryptoProvider::get_default().is_none() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
}
|
||||
reqwest::Client::builder().tls_backend_rustls()
|
||||
}
|
||||
|
||||
/// General request clients may load an identity directly. Session owners call
|
||||
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
|
||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
@@ -241,7 +247,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_identity_preserves_password_errors_and_builds_a_native_request_client() {
|
||||
fn create_identity_preserves_password_errors_and_builds_a_request_client() {
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(CERTIFICATE).unwrap();
|
||||
source.write_all(ENCRYPTED_KEY).unwrap();
|
||||
@@ -255,7 +261,7 @@ mod tests {
|
||||
}
|
||||
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
drop(source);
|
||||
reqwest::Client::builder().identity(identity).build().unwrap();
|
||||
client_builder().identity(identity).build().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -277,10 +283,7 @@ mod tests {
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&path).exists());
|
||||
reqwest::Client::builder()
|
||||
.identity(identity.request_identity())
|
||||
.build()
|
||||
.unwrap();
|
||||
client_builder().identity(identity.request_identity()).build().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Public identity compatibility and native import behavior.
|
||||
//! Public identity compatibility and owned material lifecycle.
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use gpapi::utils::request::{ClientIdentity, RequestIdentityError};
|
||||
@@ -31,23 +31,9 @@ fn rsa_pkcs8_loads_without_a_password() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ec_pkcs8_records_native_import_compatibility() {
|
||||
let result = load("ec-cert.pem", "ec-pkcs8.pem", None);
|
||||
if cfg!(target_os = "macos") {
|
||||
// Apple native-tls import currently rejects this P-256 PKCS#8 fixture.
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.downcast_ref::<reqwest::Error>()
|
||||
.unwrap()
|
||||
.is_builder()
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
result.unwrap().key_data().unwrap(),
|
||||
fs::read(fixture("ec-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
fn ec_pkcs8_loads_on_every_platform() {
|
||||
let identity = load("ec-cert.pem", "ec-pkcs8.pem", None).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), fs::read(fixture("ec-pkcs8.pem")).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -63,23 +49,13 @@ fn encrypted_pkcs8_keys_normalize_to_the_same_private_key() {
|
||||
("ec-pbes2.pem", "ec-pkcs8.pem", "ec-cert.pem"),
|
||||
] {
|
||||
let result = load(certificate, key, Some(PASSWORD));
|
||||
if cfg!(target_os = "macos") && certificate == "ec-cert.pem" {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.downcast_ref::<reqwest::Error>()
|
||||
.unwrap()
|
||||
.is_builder()
|
||||
);
|
||||
} else {
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key}: {error}"));
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture(expected)).unwrap(),
|
||||
"{key}"
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
}
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key}: {error}"));
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture(expected)).unwrap(),
|
||||
"{key}"
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
for (password, missing) in [(None, true), (Some("incorrect"), false)] {
|
||||
let error = load(certificate, key, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
@@ -128,7 +104,7 @@ fn rsa_pkcs1_normalizes_to_pkcs8_in_separate_and_combined_files() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_rsa_pkcs1_is_rejected_by_native_import() {
|
||||
fn malformed_rsa_pkcs1_is_rejected_before_connection() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("invalid-key.pem");
|
||||
fs::write(&source, pem::encode(&pem::Pem::new("RSA PRIVATE KEY", vec![0x30, 0]))).unwrap();
|
||||
@@ -138,7 +114,11 @@ fn malformed_rsa_pkcs1_is_rejected_by_native_import() {
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<reqwest::Error>().is_some());
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("Check that the private key matches the certificate")
|
||||
);
|
||||
}
|
||||
|
||||
fn check_archive(name: &str, password: &str) {
|
||||
@@ -211,15 +191,12 @@ fn pkcs12_password_errors_explain_how_to_recover() {
|
||||
assert!(message.contains("PKCS#12"), "{message}");
|
||||
assert!(message.contains("password") && message.contains("file"), "{message}");
|
||||
assert!(!format!("{error:?}").contains("incorrect"));
|
||||
assert!(error.chain().any(|cause| cause.is::<reqwest::Error>()));
|
||||
assert!(error.chain().any(|cause| cause.is::<p12_keystore::error::Error>()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// Apple's native importer rejects this empty-password fixture; its native
|
||||
// compatibility decision is covered by archive_snapshot_and_pfx_preserve_native_import_contract.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn empty_pkcs12_password_survives_loading_and_transport() {
|
||||
let archive = fs::read(fixture("empty-password.p12")).unwrap();
|
||||
for password in [None, Some("")] {
|
||||
@@ -239,26 +216,6 @@ fn pkcs12_accepts_non_ascii_passwords() {
|
||||
|
||||
#[test]
|
||||
fn legacy_rc2_pkcs12_checks_password_and_archive_integrity() {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if std::env::var_os("GP_IDENTITY_LEGACY_TEST_CHILD").is_none() {
|
||||
// OpenSSL providers are process-global. Exercise the existing legacy-mode
|
||||
// configuration in an isolated process, without affecting parallel tests.
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let config = directory.path().join("openssl.cnf");
|
||||
fs::write(&config, gpapi::utils::openssl::openssl_conf()).unwrap();
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"legacy_rc2_pkcs12_checks_password_and_archive_integrity",
|
||||
"--nocapture",
|
||||
])
|
||||
.env("OPENSSL_CONF", config)
|
||||
.env("GP_IDENTITY_LEGACY_TEST_CHILD", "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
return;
|
||||
}
|
||||
check_archive("legacy-rc2.p12", PASSWORD);
|
||||
}
|
||||
|
||||
@@ -307,7 +264,12 @@ fn pbes2_legacy_ciphers_remain_supported() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "desktop")]
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn legacy_pkcs8_conversion_preserves_the_key_and_password_errors() {
|
||||
let identity = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
@@ -326,121 +288,65 @@ fn legacy_pkcs8_conversion_preserves_the_key_and_password_errors() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(feature = "desktop")]
|
||||
fn legacy_pkcs8_matches_previous_linux_openssl_processing() {
|
||||
let encrypted = fs::read(fixture("rsa-pbes1-3des.pem")).unwrap();
|
||||
let previous = openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, PASSWORD.as_bytes())
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8()
|
||||
.unwrap();
|
||||
let identity = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), previous);
|
||||
assert!(openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, b"incorrect").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "desktop")]
|
||||
fn legacy_pkcs8_converter_failures_are_terminal_and_modern_keys_need_no_executable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
const CHILD: &str = "GP_LEGACY_CONVERTER_TEST";
|
||||
if let Ok(case) = std::env::var(CHILD) {
|
||||
let started = std::time::Instant::now();
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap_err();
|
||||
assert!(
|
||||
started.elapsed() < std::time::Duration::from_secs(12),
|
||||
"conversion exceeded its deadline"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
let message = format!("{error:?}");
|
||||
assert!(message.contains("Convert the key to modern PKCS#8"));
|
||||
assert!(!message.contains(PASSWORD));
|
||||
assert!(!message.contains("PRIVATE KEY"));
|
||||
if case == "missing" {
|
||||
assert!(message.contains("unavailable"));
|
||||
} else if case.starts_with("timeout") {
|
||||
assert!(message.contains("timed out"));
|
||||
}
|
||||
for key in ["rsa-pkcs8.pem", "rsa-pbes2-sha256.pem"] {
|
||||
let identity = load("rsa-cert.pem", key, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// PATH is process-global; isolate executable discovery from parallel tests.
|
||||
for (case, script) in [
|
||||
("missing", None),
|
||||
(
|
||||
"unsupported",
|
||||
Some("#!/bin/sh\nprintf 'unsupported: fixture-password PRIVATE KEY' >&2\nexit 1\n"),
|
||||
),
|
||||
("invalid-output", Some("#!/bin/sh\nprintf 'invalid converted key'\n")),
|
||||
("timeout-wrapper", Some("#!/bin/sh\n/bin/sleep 14\n")),
|
||||
("timeout-exited-wrapper", Some("#!/bin/sh\n/bin/sleep 14 &\nexit 0\n")),
|
||||
] {
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn identity_import_does_not_use_converter_executables() {
|
||||
const CHILD: &str = "GP_IDENTITY_NO_COMMANDS";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
if let Some(script) = script {
|
||||
let executable = directory.path().join("openssl");
|
||||
fs::write(&executable, script).unwrap();
|
||||
fs::set_permissions(executable, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"legacy_pkcs8_converter_failures_are_terminal_and_modern_keys_need_no_executable",
|
||||
"--nocapture",
|
||||
])
|
||||
.args(["--exact", "identity_import_does_not_use_converter_executables"])
|
||||
.env(CHILD, "1")
|
||||
.env("PATH", directory.path())
|
||||
.env(CHILD, case)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "converter case: {case}");
|
||||
assert!(status.success());
|
||||
return;
|
||||
}
|
||||
for key in ["rsa-pkcs8.pem", "rsa-traditional-aes256.pem", "rsa-pbes1-3des.pem"] {
|
||||
let identity = load("rsa-cert.pem", key, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
check_archive("legacy-rc2.p12", PASSWORD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn encrypted_key_import_accepts_long_passwords() {
|
||||
for length in [1023, 1024] {
|
||||
let identity = load(
|
||||
"rsa-cert.pem",
|
||||
&format!("rsa-pbes1-3des-password-{length}.pem"),
|
||||
Some(&"x".repeat(length)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "desktop")]
|
||||
fn legacy_converter_reports_its_password_length_limit_without_requesting_a_retry() {
|
||||
let password = "x".repeat(1024);
|
||||
let encrypted = fs::read(fixture("rsa-pbes1-3des-password-1024.pem")).unwrap();
|
||||
// The previous linked API accepted this boundary. The CLI cannot carry it;
|
||||
// report that limitation rather than calling the correct password wrong.
|
||||
openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, password.as_bytes()).unwrap();
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des-password-1024.pem", Some(&password)).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
assert!(error.to_string().contains("1023-byte"));
|
||||
let accepted = load(
|
||||
"rsa-cert.pem",
|
||||
"rsa-pbes1-3des-password-1023.pem",
|
||||
Some(&"x".repeat(1023)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
accepted.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "desktop")]
|
||||
fn legacy_conversion_keeps_original_files_and_rejects_line_breaks_in_passwords() {
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn encrypted_key_import_keeps_original_files_and_redacts_passwords() {
|
||||
let original = fs::read(fixture("rsa-pbes1-3des.pem")).unwrap();
|
||||
for password in [
|
||||
PASSWORD,
|
||||
@@ -452,16 +358,15 @@ fn legacy_conversion_keeps_original_files_and_rejects_line_breaks_in_passwords()
|
||||
let result = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(password));
|
||||
if password == PASSWORD {
|
||||
result.unwrap();
|
||||
} else if password != "incorrect" {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
));
|
||||
} else {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::DecryptError("PEM"))
|
||||
));
|
||||
let error = result.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains(password));
|
||||
if !password.contains('\0') {
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::DecryptError("PEM"))
|
||||
));
|
||||
}
|
||||
}
|
||||
assert_eq!(fs::read(fixture("rsa-pbes1-3des.pem")).unwrap(), original);
|
||||
}
|
||||
@@ -535,7 +440,7 @@ fn prepared_pem_round_trip_retains_snapshot_and_private_file_lifecycle() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_snapshot_and_pfx_preserve_native_import_contract() {
|
||||
fn archive_snapshot_and_pfx_preserve_prepared_identity() {
|
||||
use zeroize::Zeroizing;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("identity.pfx");
|
||||
@@ -554,12 +459,7 @@ fn archive_snapshot_and_pfx_preserve_native_import_contract() {
|
||||
assert!(restored.key_data().is_none());
|
||||
assert!(!format!("{restored:?}").contains(PASSWORD));
|
||||
let empty = fs::read(fixture("empty-password.p12")).unwrap();
|
||||
// Preserve the native backend's existing empty-password decision.
|
||||
let expected = reqwest::Identity::from_pkcs12_der(&empty, "").is_ok();
|
||||
assert_eq!(
|
||||
ClientIdentity::from_data(Zeroizing::new(empty), None, Some("")).is_ok(),
|
||||
expected
|
||||
);
|
||||
assert!(ClientIdentity::from_data(Zeroizing::new(empty), None, Some("")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -712,11 +612,62 @@ fn mismatched_certificate_key_is_rejected_before_request_client_creation() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "desktop"))]
|
||||
#[test]
|
||||
fn portable_legacy_pkcs8_is_explicitly_unsupported() {
|
||||
for password in [None, Some(PASSWORD)] {
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des.pem", password).unwrap_err();
|
||||
fn pkcs12_without_bag_ids_or_mac_matches_the_key_instead_of_bag_order() {
|
||||
let data = fs::read(fixture("no-bag-ids.p12")).unwrap();
|
||||
let archive = p12_keystore::Pkcs12Archive::from_pkcs12(&data, "").unwrap();
|
||||
assert!(archive.keys[0].local_key_id.is_none());
|
||||
assert!(archive.certs.iter().all(|bag| bag.local_key_id.is_none()));
|
||||
assert_eq!(
|
||||
archive.certs[0].cert.as_der(),
|
||||
pem::parse(fs::read(fixture("root.pem")).unwrap()).unwrap().contents()
|
||||
);
|
||||
for password in [None, Some("")] {
|
||||
let identity = ClientIdentity::from_data(data.clone().into(), None, password).unwrap();
|
||||
assert_eq!(identity.certificate_data(), data);
|
||||
assert!(identity.key_data().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_rejects_mismatched_and_multiple_identities() {
|
||||
for (name, ambiguous) in [("mismatched.p12", false), ("multiple-identities.p12", true)] {
|
||||
let error = ClientIdentity::load(fixture(name).to_str().unwrap(), None, None).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::AmbiguousPkcs12) => assert!(ambiguous),
|
||||
Some(RequestIdentityError::InvalidCertificate) => assert!(!ambiguous),
|
||||
other => panic!("{name}: unexpected archive error: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_identity_accepts_certificate_pem_without_a_final_newline() {
|
||||
let certificate = fs::read(fixture("rsa-cert.pem")).unwrap();
|
||||
let certificate = certificate.trim_ascii_end().to_vec();
|
||||
let key = fs::read(fixture("rsa-pkcs8.pem")).unwrap();
|
||||
let identity = ClientIdentity::from_data(
|
||||
zeroize::Zeroizing::new(certificate.clone()),
|
||||
Some(zeroize::Zeroizing::new(key)),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_pkcs12_password_rejects_nul_before_native_tunnel_setup() {
|
||||
let password = "private\0password";
|
||||
let error = ClientIdentity::load(fixture("no-bag-ids.p12").to_str().unwrap(), None, Some(password)).unwrap_err();
|
||||
assert!(error.to_string().contains("NUL"));
|
||||
assert!(!format!("{error:?}").contains(password));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
#[test]
|
||||
fn ios_reports_unsupported_legacy_encryption_without_a_native_importer() {
|
||||
for key in ["rsa-pbes1-3des.pem", "rsa-traditional-aes256.pem"] {
|
||||
let error = load("rsa-cert.pem", key, Some(PASSWORD)).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
|
||||
@@ -12,9 +12,9 @@ OPENSSL_BIN=/path/to/openssl bash generate.sh
|
||||
```
|
||||
|
||||
Generation is random; it replaces the keys, certificates, and archives together.
|
||||
The test runner reads checked-in files. Legacy standalone conversion tests
|
||||
require an `openssl` executable on PATH (OpenSSL or compatible LibreSSL).
|
||||
No fixture generation is needed to run the tests.
|
||||
The test runner reads checked-in files and needs no converter executable.
|
||||
No fixture generation is needed to run the tests. OpenSSL is used only by the
|
||||
optional fixture-generation script, not identity import.
|
||||
|
||||
| Files | Contents |
|
||||
| --- | --- |
|
||||
@@ -24,38 +24,32 @@ No fixture generation is needed to run the tests.
|
||||
| `{rsa,ec}-traditional-{aes128,aes192,aes256,des3}.pem` | Traditional encrypted PEM with AES-CBC or 3DES-CBC; password `fixture-password` |
|
||||
| `rsa-pbes2-sha1.pem`, `rsa-pbes2-sha256.pem` | Encrypted PKCS#8, AES256-CBC/PBKDF2 with SHA1 or SHA256 PRF |
|
||||
| `rsa-pbes2-aes-{128,192}-cbc-{sha1,sha256}.pem` | AES128/192-CBC with PBKDF2 SHA1/SHA256 |
|
||||
| `rsa-pbes2-des3-{sha1,sha256}.pem` | PBES2 3DES-CBC with PBKDF2 SHA1/SHA256; distinct from the legacy PBE scheme handled by optional conversion |
|
||||
| `rsa-pbes2-des3-{sha1,sha256}.pem` | PBES2 3DES-CBC with PBKDF2 SHA1/SHA256; distinct from the PKCS#12 PBE scheme handled by GnuTLS |
|
||||
| `rsa-pbes2-des.pem` | PBES2 DES-CBC/PBKDF2-SHA256; Rust processing requires no native legacy provider |
|
||||
| `rsa-pbes2-scrypt.pem` | PBES2 AES256-CBC with scrypt |
|
||||
| `rsa-pbes1-3des-password-{1023,1024}.pem` | Same legacy encryption with passwords at the CLI input boundary; the linked importer accepts 1024 bytes, while the converter reports its 1023-byte limit explicitly |
|
||||
| `rsa-pbes1-3des.pem` | Legacy PKCS#12 SHA1/3DES scheme inside standalone encrypted PKCS#8; optional OpenSSL executable conversion case |
|
||||
| `empty-password.p12` | RSA leaf/key/root with an empty password, preserving native backend acceptance |
|
||||
| `rsa-pbes1-3des-password-{1023,1024}.pem` | Same encryption with 1023- and 1024-byte passwords; both import without executable line limits |
|
||||
| `rsa-pbes1-3des.pem` | Legacy PKCS#12 SHA1/3DES scheme inside standalone encrypted PKCS#8; private GnuTLS import case |
|
||||
| `empty-password.p12` | RSA leaf/key/root with an empty password, accepted with omitted or empty password |
|
||||
| `ec-pbes2.pem` | Encrypted EC PKCS#8, AES256-CBC/PBKDF2-SHA256 |
|
||||
| `modern.p12`, `unicode-password.p12` | Leaf/key/root, AES256-CBC/PBKDF2-SHA256, SHA256 MAC; RSA and EC respectively |
|
||||
| `certificate-only.pfx`, `key-only.pfx` | Incomplete PKCS#12 archives: certificate without key, and key without certificate; password `fixture-password` |
|
||||
| `legacy-rc2.p12` | Issue #437 case: RC2-40 certificate bags, SHA1/3DES key bag, SHA1 MAC |
|
||||
|
||||
`tests/client_identity.rs` records native import compatibility and the owned
|
||||
identity lifecycle. `tests/identity_encoding.rs` covers container normalization:
|
||||
DER certificates and keys, RSA PKCS#1, Linux/BSD EC SEC1 and traditional encrypted
|
||||
PEM, first-key selection, malformed encryption headers, and archive extension
|
||||
capitalization. macOS rejects SEC1 and traditional encrypted PEM before password
|
||||
handling. Its native importer also rejects the P-256 PKCS#8 PEM fixture, although
|
||||
its native PKCS#12 import accepts the EC archive. Legacy-provider setup is isolated
|
||||
in a child process on Linux/BSD.
|
||||
`tests/client_identity.rs` covers all supported key families, password failures,
|
||||
archive integrity, certificate/key matching, retained snapshots, private-file
|
||||
permissions and cleanup. `tests/identity_encoding.rs` covers PEM/DER, RSA PKCS#1,
|
||||
EC SEC1, traditional encrypted PEM, first-key selection, malformed encryption
|
||||
headers and archive extension capitalization. Rustls validates RSA and EC keys
|
||||
on all supported targets; desktop legacy encrypted-key imports use GnuTLS.
|
||||
PBES2, including scrypt, stays in Rust. The no-executable child test runs with an
|
||||
empty PATH and imports both legacy key families and RC2 PKCS#12.
|
||||
|
||||
Standalone PKCS#8 PBE-SHA1-3DES uses optional OpenSSL executable conversion,
|
||||
with missing/wrong passwords preserving the old Linux prompt/retry contract.
|
||||
Other unsupported schemes retain explicit conversion guidance. PBES2 DES/3DES
|
||||
use Rust processing and need no executable. Child-process tests isolate PATH
|
||||
for absent/unsupported/stalled converters, invalid output, and secret-free errors.
|
||||
Timeout coverage includes wrappers whose descendants retain pipes after the
|
||||
wrapper exits or is killed; all pipe I/O shares the process deadline.
|
||||
Linux/BSD additionally compare the result with the former linked OpenSSL importer.
|
||||
Archive integrity checks change the UTF-16 friendly name without changing the
|
||||
MAC. Decrypted output is compared with independent plaintext fixture keys.
|
||||
Unit tests in `utils/request.rs` cover missing keys, large local files and request
|
||||
client construction.
|
||||
|
||||
The tests check archive integrity by changing the UTF-16 friendly name without
|
||||
changing the MAC, and compare normalized PEM output against the independent
|
||||
checked-in plaintext key. Public integration tests cover first-key selection,
|
||||
retained snapshots, private-file permissions and cleanup, `.pfx`, empty-password
|
||||
backend behavior, and chain retention. Unit tests in `utils/request.rs` cover
|
||||
missing keys, large local files, and native request-client construction.
|
||||
The unencrypted, MAC-less `no-bag-ids.p12`, `mismatched.p12`, and
|
||||
`multiple-identities.p12` contain only the same public test keys/certificates.
|
||||
They exercise PKCS#12 bags without optional attributes, reversed certificate
|
||||
order/unrelated certificates, and terminal mismatched/ambiguous identities.
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Assemble public, unencrypted PKCS#12 fixtures; no cryptography is performed."""
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def pem(name):
|
||||
lines = (ROOT / name).read_text().splitlines()
|
||||
return base64.b64decode("".join(line for line in lines if not line.startswith("-----")))
|
||||
|
||||
|
||||
def tlv(tag, content):
|
||||
length = len(content)
|
||||
encoded = length.to_bytes(max(1, (length.bit_length() + 7) // 8), "big")
|
||||
prefix = bytes([length]) if length < 128 else bytes([128 + len(encoded)]) + encoded
|
||||
return bytes([tag]) + prefix + content
|
||||
|
||||
|
||||
def sequence(*items):
|
||||
return tlv(0x30, b"".join(items))
|
||||
|
||||
|
||||
def oid(value):
|
||||
return tlv(6, bytes.fromhex(value))
|
||||
|
||||
|
||||
def explicit(content):
|
||||
return tlv(0xA0, content)
|
||||
|
||||
|
||||
def data(content):
|
||||
return sequence(oid("2a864886f70d010701"), explicit(tlv(4, content)))
|
||||
|
||||
|
||||
def key(name):
|
||||
return sequence(oid("2a864886f70d010c0a0101"), explicit(pem(name)))
|
||||
|
||||
|
||||
def certificate(name):
|
||||
cert_bag = sequence(oid("2a864886f70d01091601"), explicit(tlv(4, pem(name))))
|
||||
return sequence(oid("2a864886f70d010c0a0103"), explicit(cert_bag))
|
||||
|
||||
|
||||
def archive(name, *bags):
|
||||
(ROOT / name).write_bytes(sequence(tlv(2, b"\x03"), data(sequence(data(sequence(*bags))))))
|
||||
|
||||
|
||||
archive("no-bag-ids.p12", certificate("root.pem"), certificate("ec-cert.pem"),
|
||||
key("rsa-pkcs8.pem"), certificate("rsa-cert.pem"))
|
||||
archive("mismatched.p12", key("rsa-pkcs8.pem"), certificate("ec-cert.pem"), certificate("root.pem"))
|
||||
archive("multiple-identities.p12", key("rsa-pkcs8.pem"), key("ec-pkcs8.pem"),
|
||||
certificate("rsa-cert.pem"), certificate("ec-cert.pem"))
|
||||
@@ -75,3 +75,6 @@ done
|
||||
-name fixture -passout pass:fixture-password -out certificate-only.pfx
|
||||
"$openssl_bin" pkcs12 -export -nocerts -inkey rsa-pkcs8.pem \
|
||||
-name fixture -passout pass:fixture-password -out key-only.pfx
|
||||
|
||||
# Plain PKCS#12 bags let the import tests omit optional IDs and reorder bags.
|
||||
python3 "$(dirname "$0")/generate-plain-pfx.py"
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -65,41 +65,40 @@ fn encrypted_der_preserves_password_errors() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ec_sec1_normalizes_on_linux_and_bsd_and_is_terminal_on_macos() {
|
||||
fn ec_sec1_pem_and_der_are_portable() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("ec.der");
|
||||
fs::write(&key, pem::parse(bytes("ec-sec1.pem")).unwrap().contents()).unwrap();
|
||||
for source in [fixture("ec-sec1.pem"), key] {
|
||||
for password in [None, Some(PASSWORD)] {
|
||||
let result = load(&fixture("ec-cert.pem"), &source, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedKeyFormat)
|
||||
));
|
||||
} else {
|
||||
assert_eq!(result.unwrap().key_data().unwrap(), bytes("ec-pkcs8.pem"));
|
||||
}
|
||||
let identity = load(&fixture("ec-cert.pem"), &source, password).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), bytes("ec-sec1.pem"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traditional_encrypted_pem_has_platform_specific_support_and_password_errors() {
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn traditional_encrypted_pem_preserves_password_errors() {
|
||||
for algorithm in ["rsa", "ec"] {
|
||||
for cipher in ["aes128", "aes192", "aes256", "des3"] {
|
||||
let certificate = fixture(&format!("{algorithm}-cert.pem"));
|
||||
let key = fixture(&format!("{algorithm}-traditional-{cipher}.pem"));
|
||||
for password in [None, Some("incorrect"), Some(PASSWORD)] {
|
||||
let result = load(&certificate, &key, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
} else if password == Some(PASSWORD) {
|
||||
if password == Some(PASSWORD) {
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key:?}: {error}"));
|
||||
assert_eq!(identity.key_data().unwrap(), bytes(&format!("{algorithm}-pkcs8.pem")));
|
||||
let actual = openssl::pkey::PKey::private_key_from_pem(identity.key_data().unwrap()).unwrap();
|
||||
let expected = openssl::pkey::PKey::private_key_from_pem(&bytes(&format!("{algorithm}-pkcs8.pem"))).unwrap();
|
||||
assert!(
|
||||
actual.public_eq(&expected),
|
||||
"{key:?}: imported key differs from the fixture"
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
} else {
|
||||
let error = result.unwrap_err();
|
||||
@@ -115,7 +114,12 @@ fn traditional_encrypted_pem_has_platform_specific_support_and_password_errors()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn traditional_passphrase_with_nul_returns_a_redacted_terminal_error() {
|
||||
let error = load(
|
||||
&fixture("rsa-cert.pem"),
|
||||
@@ -130,11 +134,16 @@ fn traditional_passphrase_with_nul_returns_a_redacted_terminal_error() {
|
||||
for diagnostic in [error.to_string(), format!("{error:?}")] {
|
||||
assert!(!diagnostic.contains("secret-password"));
|
||||
assert!(!diagnostic.contains("do-not-log"));
|
||||
assert!(!diagnostic.contains("115, 101, 99, 114, 101, 116"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn first_traditional_encrypted_key_controls_combined_pem_loading() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
@@ -144,24 +153,14 @@ fn first_traditional_encrypted_key_controls_combined_pem_loading() {
|
||||
combined.extend(bytes("rsa-traditional-aes256.pem"));
|
||||
combined.extend(bytes("rsa-pkcs8.pem"));
|
||||
fs::write(&source, &combined).unwrap();
|
||||
for password in [None, Some(PASSWORD)] {
|
||||
let result = ClientIdentity::load(source.to_str().unwrap(), None, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
} else if password.is_none() {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase("PEM"))
|
||||
));
|
||||
} else {
|
||||
let identity = result.unwrap();
|
||||
assert_eq!(identity.certificate_data(), chain);
|
||||
assert_eq!(identity.key_data().unwrap(), bytes("rsa-pkcs8.pem"));
|
||||
}
|
||||
}
|
||||
let error = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase("PEM"))
|
||||
));
|
||||
let identity = ClientIdentity::load(source.to_str().unwrap(), None, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(identity.certificate_data(), chain);
|
||||
assert_eq!(identity.key_data().unwrap(), bytes("rsa-pkcs8.pem"));
|
||||
assert_eq!(fs::read(source).unwrap(), combined);
|
||||
}
|
||||
|
||||
|
||||
@@ -112,15 +112,13 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
.without("libpcsclite", None)
|
||||
.without("libpskc", None)
|
||||
.without("gssapi", None)
|
||||
.with("gnutls", None)
|
||||
.without("openssl", None)
|
||||
.with("gnutls-tss2", Some("no"))
|
||||
.with("vpnc-script", Some("/etc/vpnc/vpnc-script")); // Specify vpnc-script, otherwise it will fail on macOS
|
||||
|
||||
if target_os() == "macos" {
|
||||
config
|
||||
.disable_static()
|
||||
.enable_shared()
|
||||
.with("gnutls", None)
|
||||
.without("openssl", None);
|
||||
config.disable_static().enable_shared();
|
||||
config.ldflag("-liconv");
|
||||
config.env("LIBS", "-liconv");
|
||||
}
|
||||
@@ -140,7 +138,7 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
let lib_dir = dst.join("lib");
|
||||
let include_dir = dst.join("include");
|
||||
|
||||
if target_os() == "macos" {
|
||||
{
|
||||
let configuration = std::fs::read_to_string(dst.join("build/config.h"))
|
||||
.expect("Failed to read the OpenConnect TLS backend configuration");
|
||||
assert!(
|
||||
@@ -148,8 +146,11 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
&& !configuration
|
||||
.lines()
|
||||
.any(|line| line == "#define OPENCONNECT_OPENSSL 1"),
|
||||
"macOS OpenConnect must use GnuTLS"
|
||||
"OpenConnect must use GnuTLS"
|
||||
);
|
||||
}
|
||||
|
||||
if target_os() == "macos" {
|
||||
// Do not embed Cargo's temporary build directory in consumers of this library.
|
||||
let library = std::fs::canonicalize(lib_dir.join("libopenconnect.dylib")).unwrap();
|
||||
let library_name = library.file_name().unwrap().to_str().unwrap();
|
||||
|
||||
@@ -15,7 +15,6 @@ depends="
|
||||
libxml2
|
||||
lz4
|
||||
nettle
|
||||
openssl
|
||||
p11-kit
|
||||
polkit
|
||||
webkit2gtk-4.1
|
||||
@@ -39,7 +38,6 @@ makedepends="
|
||||
lz4-dev
|
||||
make
|
||||
nettle-dev
|
||||
openssl-dev
|
||||
p11-kit-dev
|
||||
patch
|
||||
pkgconf
|
||||
|
||||
@@ -21,7 +21,6 @@ pkgbase = globalprotect-openconnect-git
|
||||
makedepends = appmenu-gtk-module
|
||||
makedepends = librsvg
|
||||
makedepends = cargo
|
||||
depends = openssl
|
||||
depends = webkit2gtk-4.1
|
||||
depends = libappindicator-gtk3
|
||||
depends = libsecret
|
||||
|
||||
@@ -10,7 +10,7 @@ url="https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
license=('GPL3')
|
||||
|
||||
makedepends=(git pkg-config make autoconf automake gettext libtool patch curl wget file appmenu-gtk-module librsvg cargo)
|
||||
depends=(openssl webkit2gtk-4.1 libappindicator-gtk3 libsecret libxml2 zlib lz4 gnutls libp11-kit nettle gmp shared-mime-info desktop-file-utils xdg-utils)
|
||||
depends=(webkit2gtk-4.1 libappindicator-gtk3 libsecret libxml2 zlib lz4 gnutls libp11-kit nettle gmp shared-mime-info desktop-file-utils xdg-utils)
|
||||
optdepends=('wmctrl: for window management')
|
||||
|
||||
conflicts=('globalprotect-openconnect')
|
||||
@@ -38,9 +38,6 @@ prepare() {
|
||||
}
|
||||
|
||||
build() {
|
||||
# Must unset the CFLAGS, otherwise the build fails on linking openssl, don't know why
|
||||
unset CFLAGS
|
||||
|
||||
cd "${_pkgname_prefix}"
|
||||
cargo build --frozen --release
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ Build-Depends: debhelper (>= 9),
|
||||
patch,
|
||||
pkg-config,
|
||||
make (>= 4),
|
||||
libssl-dev,
|
||||
libxml2-dev,
|
||||
zlib1g-dev,
|
||||
liblz4-dev,
|
||||
|
||||
@@ -21,7 +21,6 @@ RUN apk add --no-cache \
|
||||
lz4-dev \
|
||||
make \
|
||||
nettle-dev \
|
||||
openssl-dev \
|
||||
p11-kit-dev \
|
||||
patch \
|
||||
pkgconf \
|
||||
@@ -55,7 +54,6 @@ RUN apk add --no-cache \
|
||||
libxml2 \
|
||||
lz4-libs \
|
||||
nettle \
|
||||
openssl \
|
||||
p11-kit \
|
||||
zlib \
|
||||
&& addgroup -g 1000 gp \
|
||||
|
||||
@@ -9,7 +9,7 @@ arch=('x86_64' 'aarch64')
|
||||
url="https://github.com/yuezk/GlobalProtect-openconnect"
|
||||
license=('GPL3')
|
||||
makedepends=('make' 'pkg-config' 'cargo' 'file' 'autoconf' 'automake' 'gettext' 'libtool' 'patch')
|
||||
depends=('webkit2gtk-4.1' 'libappindicator-gtk3' 'librsvg' 'libsecret' 'openssl' 'appmenu-gtk-module'
|
||||
depends=('webkit2gtk-4.1' 'libappindicator-gtk3' 'librsvg' 'libsecret' 'appmenu-gtk-module'
|
||||
'gnutls' 'libxml2' 'zlib' 'lz4' 'libp11-kit' 'nettle' 'gmp' 'xdg-utils')
|
||||
optdepends=('wmctrl: for window management')
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ BuildRequires: gettext
|
||||
BuildRequires: gcc-c++
|
||||
BuildRequires: cargo
|
||||
BuildRequires: pkg-config
|
||||
BuildRequires: (openssl-devel or libopenssl-devel)
|
||||
BuildRequires: libxml2-devel
|
||||
BuildRequires: zlib-devel
|
||||
BuildRequires: (lz4-devel or liblz4-devel)
|
||||
|
||||
Reference in new issue
Block a user