feat: generate HIP reports through OpenConnect callbacks

This commit is contained in:
Kevin Yue committed 2026-10-02 01:38:20 +08:00
1 parent 05814e9da7
commit b750cfbf16
46 files changed
+2511 -1184

No files matched your search

+36 -8
View File
@@ -2,6 +2,11 @@ name: Build
on:
workflow_dispatch:
inputs:
build_only:
description: 'Build and test artifacts without publishing releases, images, or update feeds'
required: true
default: false
type: boolean
gp_branch:
description: 'GlobalProtect-openconnect branch to use for the snapshot release'
required: true
@@ -40,7 +45,7 @@ on:
- v*.*.*
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && 'release' || github.ref }}
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && (inputs.build_only && github.run_id || 'release') || github.ref }}
cancel-in-progress: ${{ github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/') }}
jobs:
@@ -233,11 +238,13 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
id: build
uses: docker/build-push-action@v7
with:
@@ -245,20 +252,37 @@ jobs:
file: packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Build local image for verification
if: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
uses: docker/build-push-action@v7
with:
context: .
file: packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
tags: yuezk/globalprotect-openconnect:build-test
load: true
push: false
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
image_ref="$IMAGE@$DIGEST"
if [[ "$BUILD_ONLY" == "true" ]]; then
image_ref="$IMAGE:build-test"
fi
docker run --rm "$image_ref" --help
docker run --rm --entrypoint gpauth "$image_ref" --help
docker run --rm --entrypoint sh "$image_ref" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
if: ${{ github.event_name != 'workflow_dispatch' || !inputs.build_only }}
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
@@ -360,6 +384,7 @@ jobs:
GPGUI_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }}
BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
REQUEST_ID: ${{ github.run_id }}.${{ github.run_attempt }}.macos
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
run: |
set -euo pipefail
@@ -387,6 +412,7 @@ jobs:
--arg release_tag "$RELEASE_TAG" \
--arg gp_ref "$gp_sha" \
--arg gpgui_ref "$gpgui_sha" \
--argjson build_only "$BUILD_ONLY" \
'{
ref: $workflow_ref,
inputs: {
@@ -395,7 +421,8 @@ jobs:
channel: $channel,
release_tag: $release_tag,
gp_ref: $gp_ref,
gpgui_ref: $gpgui_ref
gpgui_ref: $gpgui_ref,
build_only: $build_only
}
}' | gh api --method POST \
repos/yuezk/gpgui/actions/workflows/release-macos.yaml/dispatches \
@@ -653,7 +680,7 @@ jobs:
${{ matrix.workspace }}/gp/.build/${{ matrix.artifact_dir }}/artifacts/*
gh-release:
if: ${{ always() && (github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/')) }}
if: ${{ always() && ((github.event_name == 'workflow_dispatch' && !inputs.build_only) || startsWith(github.ref, 'refs/tags/')) }}
runs-on: ubuntu-latest
permissions:
actions: read
@@ -774,6 +801,7 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GPGUI_ACTIONS_TOKEN }}
PUBLIC_RELEASE_RESULT: ${{ needs.gh-release.result }}
BUILD_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.build_only }}
PRIVATE_RUN_ID: ${{ needs.trigger-gpgui-macos.outputs.run_id }}
PRIVATE_RUN_URL: ${{ needs.trigger-gpgui-macos.outputs.run_url }}
run: |
@@ -783,7 +811,7 @@ jobs:
echo "The private macOS workflow was not started" >&2
exit 1
fi
if [[ "$PUBLIC_RELEASE_RESULT" != "success" ]]; then
if [[ "$BUILD_ONLY" != "true" && "$PUBLIC_RELEASE_RESULT" != "success" ]]; then
gh api --method POST \
"repos/yuezk/gpgui/actions/runs/$PRIVATE_RUN_ID/cancel" >/dev/null || true
echo "The public release failed; cancelled $PRIVATE_RUN_URL" >&2
@@ -813,7 +841,7 @@ jobs:
publish-docker-image:
needs:
- build-docker-image
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
if: ${{ (github.event_name == 'workflow_dispatch' && !inputs.build_only) || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
steps:
- name: Download digests
+36
View File
@@ -1,6 +1,7 @@
name: Nix
on:
workflow_dispatch:
pull_request:
paths:
- "flake.nix"
@@ -20,6 +21,41 @@ permissions:
contents: read
jobs:
source-package:
name: source-package (${{ matrix.platform.system }})
strategy:
fail-fast: false
matrix:
platform:
- runner: ubuntu-latest
system: x86_64-linux
- runner: ubuntu-24.04-arm
system: aarch64-linux
runs-on: ${{ matrix.platform.runner }}
steps:
- name: Checkout source and dependencies
uses: actions/checkout@v6
with:
submodules: recursive
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Build current source package
run: |
nix build .#fromSource \
--extra-experimental-features "nix-command flakes" \
--print-build-logs
- name: Inspect source package
run: |
test -x result/bin/gpclient
test -x result/bin/gpauth
test -x result/bin/gpservice
test -x result/libexec/gpclient/gp-hip-script-installer
test ! -e result/libexec/gpclient/gp-hip-runner
test ! -e result/libexec/gpclient/hipreport.sh
standalone-package:
name: standalone-package (${{ matrix.platform.system }})
strategy:
Generated
+2 -1
View File
@@ -1846,6 +1846,7 @@ dependencies = [
"log-reload",
"md5",
"netdev",
"nix 0.31.3",
"openssl",
"os_info",
"oslog",
@@ -1947,7 +1948,6 @@ dependencies = [
"askama",
"chrono",
"gpapi",
"log",
"netdev",
"serde",
"serde_json",
@@ -3385,6 +3385,7 @@ dependencies = [
"cc",
"fs_extra",
"is_executable",
"libc",
"log",
"pkg-config",
]
-6
View File
@@ -145,7 +145,6 @@ install:
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
install -Dm755 target/release/gp-hip-runner $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner
install -Dm755 target/release/gp-hip-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
install -Dm755 target/release/gp-vpnc-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
@@ -159,7 +158,6 @@ install:
fi
install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
@@ -196,11 +194,9 @@ install-bsd:
fi
install -d $(DESTDIR)$(PREFIX)/libexec/gpclient
install -m 755 target/release/gp-hip-runner $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-runner
install -m 755 target/release/gp-hip-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-script-installer
install -m 755 target/release/gp-vpnc-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-vpnc-script-installer
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script
install -m 755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)$(PREFIX)/libexec/gpclient/hipreport.sh
install -d $(DESTDIR)$(PREFIX)/share/applications
install -m 644 packaging/bsd/gpgui.desktop $(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop
@@ -300,13 +296,11 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpclient
rm -f $(DESTDIR)/usr/bin/gpauth
rm -f $(DESTDIR)/usr/bin/gpservice
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
+21
View File
@@ -71,6 +71,18 @@ Options:
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command.
#### HIP reports
HIP is disabled in the CLI unless enabled explicitly. Use `--hip` to generate reports inside `gpclient`, including later reports requested by the gateway:
```bash
sudo gpclient connect <portal> --hip
```
Use `--hip=/absolute/path/to/script` for a custom executable. It runs as the `gpclient` process user unless `--hip-user` specifies another user. No installed HIP script is discovered automatically. `--hip-user` applies only to custom executables.
`gpclient hip` generates a report on demand for inspection; see `gpclient hip --help` for report inputs. The GUI's HIP tab supports generated reports, edited XML, and HIP Off on all desktop platforms. Linux, FreeBSD, and OpenBSD also support desktop-user scripts and explicitly approved root scripts.
#### External Browser Authentication
For browser-based authentication with the CLI:
@@ -294,6 +306,15 @@ NixOS does not run an imperative package-uninstall hook when a package is
removed from the system configuration. Remove an installed replacement VPN
script from the app settings before removing the package.
The `prebuilt` package and NixOS module use the published release pinned in `flake.nix`. The `fromSource` package builds the current flake checkout, including its Git submodules:
```bash
git submodule update --init --recursive
nix build .#fromSource
```
Source builds require Nix 2.27 or later for automatic submodule fetching. For a remote source flake, use a Git URL with submodules enabled, such as `git+https://github.com/yuezk/GlobalProtect-openconnect?submodules=1#fromSource`. Build output (`target`, `.build`, and `node_modules`) is excluded from the source input. Updating release asset hashes changes the prebuilt package, independently of source builds.
### Official Docker Image
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
+5 -2
View File
@@ -54,13 +54,16 @@ pub(crate) struct ConnectArgs {
#[arg(
long,
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path",
help = "Enable HIP (Host Information Profile), optionally specify a custom executable",
default_missing_value = "",
num_args=0..=1
)]
pub(super) hip: Option<String>,
#[arg(long, help = "The user used to run the HIP script")]
#[arg(
long,
help = "Run a custom HIP executable as this user; otherwise inherit the process user"
)]
pub(super) hip_user: Option<String>,
#[arg(
+38 -25
View File
@@ -20,7 +20,7 @@ use gpapi::{
};
use inquire::Text;
use log::{Level, info, warn};
use openconnect::{Vpn, VpnBuilder};
use openconnect::{HipScript, HipSource, Vpn, VpnBuilder};
use tokio::{runtime::Handle, task::JoinHandle};
use crate::session::{
@@ -352,10 +352,10 @@ impl ConnectHandler<'_> {
}
let mtu = self.args.mtu.unwrap_or(0);
let (hip, csd_wrapper) = self.determine_hip_script();
let hip_user = self.determine_hip_user();
let csd_uid = get_uid(&hip_user).map_err(GatewayConnectError::before_tunnel)?;
let os_profile = self.os_profile.borrow().clone();
let hip_source = self
.hip_source(os_profile.clone())
.map_err(GatewayConnectError::before_tunnel)?;
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
@@ -375,9 +375,7 @@ impl ConnectHandler<'_> {
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.hip(hip)
.csd_uid(csd_uid)
.csd_wrapper(csd_wrapper)
.hip_source(hip_source)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
@@ -439,16 +437,32 @@ impl ConnectHandler<'_> {
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
}
fn determine_hip_script(&self) -> (bool, Option<String>) {
if let Some(hip) = &self.args.hip {
return if hip.is_empty() {
(true, None)
} else {
(true, Some(hip.clone()))
};
fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
let user = self.determine_hip_user();
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
match script {
Some(path) if !path.is_empty() => Ok(HipSource::Script(HipScript::new(path.clone(), get_uid(&user)?)?)),
Some(_) => {
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
Ok(HipSource::Generator(Arc::new(move |request, control| {
let input = gphip::ReportInput {
profile: profile.clone(),
context: gphip::ReportContext::Connected {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
},
};
gphip::generate_report_with_control(&input, &|| control.check())
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
})))
}
None => {
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
Ok(HipSource::Disabled)
}
}
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
}
fn determine_hip_user(&self) -> Option<String> {
@@ -495,12 +509,11 @@ fn write_pid_file(lock_file: &Path) {
}
}
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
if let Some(user) = user {
get_user_by_name(user).map(|user| user.uid())
} else {
Ok(uzers::get_effective_uid())
}
fn get_uid(user: &Option<String>) -> anyhow::Result<Option<u32>> {
user
.as_ref()
.map(|user| get_user_by_name(user).map(|user| user.uid()))
.transpose()
}
fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
@@ -517,8 +530,8 @@ mod tests {
use super::*;
#[test]
fn hip_script_defaults_to_process_effective_uid() {
assert_eq!(get_uid(&None).unwrap(), uzers::get_effective_uid());
fn hip_script_defaults_to_inherited_process_identity() {
assert_eq!(get_uid(&None).unwrap(), None);
}
#[test]
@@ -530,7 +543,7 @@ mod tests {
fn explicit_hip_user_resolves_to_the_selected_account() {
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap();
let name = current.name().to_string_lossy().into_owned();
assert_eq!(get_uid(&Some(name)).unwrap(), current.uid());
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
}
#[test]
+10 -3
View File
@@ -1,9 +1,12 @@
use std::time::Duration;
use clap::Args;
use gpapi::{
clap::args::Os,
os_profile::{ClientOs, OsProfileBuilder},
process::collection::CollectionBudget,
};
use gphip::{ReportContext, ReportInput, generate_report};
use gphip::{ReportContext, ReportInput, generate_report_with_control};
#[derive(Args)]
pub(crate) struct HipArgs {
@@ -42,13 +45,17 @@ impl<'a> HipHandler<'a> {
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
let budget = CollectionBudget::new(Duration::from_secs(60));
let client_os = ClientOs::from(self.args.client_os);
let mut builder = OsProfileBuilder::new(client_os).client_version(self.args.client_version.clone());
if let Some(os_version) = self.args.os_version.as_deref() {
builder = builder.os_version(os_version);
}
if let Some(host_id) = self.args.host_id.as_deref() {
builder = builder.host_id_override(host_id);
}
let input = ReportInput {
profile: builder.build(),
profile: builder.build_with_control(&budget)?,
context: ReportContext::Connected {
cookie: self.args.cookie.clone(),
client_ip: self.args.client_ip.clone(),
@@ -56,7 +63,7 @@ impl<'a> HipHandler<'a> {
md5: self.args.md5.clone(),
},
};
println!("{}", generate_report(&input)?);
println!("{}", generate_report_with_control(&input, &budget)?);
Ok(())
}
}
-137
View File
@@ -1,137 +0,0 @@
use std::{
env, fs,
io::{self, Write},
};
use anyhow::{Context, ensure};
use clap::Parser;
use gpapi::{
clap::args::Os,
os_profile::{ClientOs, OsProfileBuilder},
};
use gphip::{ReportContext, ReportInput, generate_report, refresh_edited_report};
use gpservice::hip_runner_state::{MAX_STATE_BYTES, RunnerReport, STATE_NAME, validate_root_owned_path};
#[derive(Parser)]
struct Args {
#[arg(long)]
client_version: String,
#[arg(long, value_enum)]
client_os: Os,
#[arg(long)]
os_version: Option<String>,
#[arg(long)]
host_id: Option<String>,
#[arg(long)]
cookie: Option<String>,
#[arg(long)]
client_ip: Option<String>,
#[arg(long)]
client_ipv6: Option<String>,
#[arg(long)]
md5: Option<String>,
#[arg(long)]
preview: bool,
}
fn main() {
if let Err(err) = run() {
eprintln!("HIP report generation failed: {err:#}");
std::process::exit(1);
}
}
fn run() -> anyhow::Result<()> {
let args = Args::parse();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let original_args: Vec<_> = env::args_os().skip(1).collect();
let executable = env::current_exe().context("Cannot locate HIP runner")?;
validate_root_owned_path(&executable, true)?;
let state = executable
.parent()
.context("HIP runner has no parent")?
.join(STATE_NAME);
let metadata = fs::symlink_metadata(&state).context("Cannot inspect HIP report state")?;
ensure!(
metadata.is_file() && !metadata.file_type().is_symlink(),
"Invalid HIP report state"
);
use std::os::unix::fs::{MetadataExt, PermissionsExt};
ensure!(
metadata.uid() == 0 && metadata.permissions().mode() & 0o077 == 0,
"HIP report state is not private"
);
ensure!(
metadata.len() <= MAX_STATE_BYTES as u64,
"HIP report state is too large"
);
let bytes = fs::read(&state).context("Cannot read HIP report state")?;
ensure!(bytes.len() <= MAX_STATE_BYTES, "HIP report state is too large");
let report: RunnerReport = serde_json::from_slice(&bytes).context("Invalid HIP report state")?;
// This binary is single-threaded. Clear the VPN and desktop environment
// before host collectors invoke any external system utilities.
for (key, _) in env::vars_os() {
unsafe { env::remove_var(key) };
}
unsafe {
env::set_var("PATH", "/usr/bin:/bin:/usr/sbin:/sbin");
env::set_var("LC_ALL", "C");
env::set_var(
"HOME",
if cfg!(target_os = "macos") {
"/var/root"
} else {
"/root"
},
);
}
let report = match report {
RunnerReport::ApprovedRootScript { approval_id, owner_uid } => {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
{
let approved = gpservice::hip_approval::resolve(&approval_id, owner_uid)?;
let script_args = original_args.into_iter().filter(|arg| arg != "--preview");
let status = std::process::Command::new(approved.path)
.args(script_args)
.status()
.context("Approved HIP script did not start")?;
ensure!(status.success(), "Approved HIP script failed");
return Ok(());
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
{
let _ = (approval_id, owner_uid);
anyhow::bail!("Root HIP script approvals are unavailable on this platform");
}
}
report => report,
};
let mut builder = OsProfileBuilder::new(ClientOs::from(args.client_os)).client_version(args.client_version);
if let Some(host_id) = args.host_id {
builder = builder.host_id_override(host_id);
}
let context = if args.preview {
ReportContext::Preview
} else {
ReportContext::Connected {
cookie: args.cookie.context("Missing HIP cookie")?,
client_ip: args.client_ip,
client_ipv6: args.client_ipv6,
md5: args.md5.context("Missing HIP digest")?,
}
};
let input = ReportInput {
profile: builder.build(),
context,
};
let xml = match report {
RunnerReport::Generated => generate_report(&input)?,
RunnerReport::Edited { xml } => refresh_edited_report(&xml, &input)?,
RunnerReport::ApprovedRootScript { .. } => unreachable!("approved script returned before report generation"),
};
io::stdout().write_all(xml.as_bytes())?;
Ok(())
}
+66 -9
View File
@@ -1,6 +1,6 @@
use std::{
fs::{self, File, OpenOptions},
io::Write,
io::{Read, Write},
os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
path::{Path, PathBuf},
};
@@ -12,8 +12,6 @@ use serde::{Deserialize, Serialize};
use tempfile::Builder;
use uuid::Uuid;
use crate::hip_runner_state::validate_root_owned_path;
#[cfg(target_os = "linux")]
pub const APPROVAL_DIRECTORY: &str = "/var/lib/gpclient/hip-approvals";
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
@@ -83,22 +81,32 @@ pub fn install(request: InstallRequest, approving_uid: u32) -> anyhow::Result<Ap
let contents = request.contents()?;
let base = Path::new(APPROVAL_DIRECTORY);
fs::create_dir_all(base).context("Cannot create HIP approval directory")?;
validate_root_owned_path(base, false)?;
validate_approval_ancestors(base)?;
fs::set_permissions(base, fs::Permissions::from_mode(0o700))?;
install_at(base, &contents, request.original_path, approving_uid, 0)
}
pub fn resolve(approval_id: &str, desktop_uid: u32) -> anyhow::Result<ApprovedScript> {
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
resolve_with_control(approval_id, desktop_uid, &budget)
}
pub fn resolve_with_control(
approval_id: &str,
desktop_uid: u32,
control: &dyn gpapi::process::collection::CollectionControl,
) -> anyhow::Result<ApprovedScript> {
control.check()?;
ensure!(desktop_uid != 0, "Root is not a desktop HIP approval owner");
let base = Path::new(APPROVAL_DIRECTORY);
validate_root_owned_path(base, false)?;
resolve_at(base, approval_id, desktop_uid, 0)
validate_approval_ancestors(base)?;
resolve_at_with_control(base, approval_id, desktop_uid, 0, control)
}
pub fn revoke(approval_id: &str, approving_uid: u32) -> anyhow::Result<()> {
ensure!(approving_uid != 0, "Root cannot revoke another user's HIP approval");
let base = Path::new(APPROVAL_DIRECTORY);
validate_root_owned_path(base, false)?;
validate_approval_ancestors(base)?;
revoke_at(base, approval_id, approving_uid, 0)
}
@@ -127,7 +135,7 @@ fn status_at(
}
}
if validate_private_dir(base, file_owner).is_err()
|| (validate_root_ancestors && validate_root_owned_path(base, false).is_err())
|| (validate_root_ancestors && validate_approval_ancestors(base).is_err())
{
return Ok(HipApprovalStatus::Corrupt);
}
@@ -191,15 +199,43 @@ fn install_at(
}
fn resolve_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result<ApprovedScript> {
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
resolve_at_with_control(base, approval_id, desktop_uid, file_owner, &budget)
}
fn resolve_at_with_control(
base: &Path,
approval_id: &str,
desktop_uid: u32,
file_owner: u32,
control: &dyn gpapi::process::collection::CollectionControl,
) -> anyhow::Result<ApprovedScript> {
control.check()?;
let info = read_metadata_at(base, approval_id, desktop_uid, file_owner)?;
control.check()?;
let script = base.join(approval_id).join(SCRIPT_NAME);
validate_file(&script, file_owner, 0o500, MAX_SCRIPT_SIZE as u64)?;
let contents = fs::read(&script)?;
let mut file = File::open(&script)?;
let mut contents = Vec::new();
let mut chunk = [0_u8; 8192];
loop {
control.check()?;
let read = file.read(&mut chunk)?;
if read == 0 {
break;
}
ensure!(
contents.len() + read <= MAX_SCRIPT_SIZE,
"Approved HIP script is too large"
);
contents.extend_from_slice(&chunk[..read]);
}
ensure!(!contents.is_empty(), "Approved HIP script is empty");
ensure!(
sha256::digest(&contents) == info.sha256,
"Approved HIP script digest mismatch"
);
control.check()?;
Ok(ApprovedScript { info, path: script })
}
@@ -294,6 +330,27 @@ fn validate_file(path: &Path, owner_uid: u32, mode: u32, max_size: u64) -> anyho
Ok(())
}
/// Check every component because a trusted file below a writable parent can
/// be replaced before a later HIP refresh.
fn validate_approval_ancestors(path: &Path) -> anyhow::Result<()> {
ensure!(path.is_absolute(), "HIP approval path must be absolute");
for component in path.ancestors().take_while(|part| part.as_os_str() != "/") {
let metadata =
fs::symlink_metadata(component).with_context(|| format!("Cannot inspect {}", component.display()))?;
ensure!(
!metadata.file_type().is_symlink(),
"HIP approval path contains a symlink"
);
ensure!(metadata.uid() == 0, "HIP approval path is not root-owned");
ensure!(
metadata.permissions().mode() & 0o022 == 0,
"HIP approval path is writable by another user"
);
ensure!(metadata.is_dir(), "HIP approval parent is not a directory");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
+281 -247
View File
@@ -1,275 +1,309 @@
use std::{os::unix::process::CommandExt, process::Stdio, sync::Arc, time::Duration};
use std::{collections::HashMap, io, sync::Arc, time::Duration};
use anyhow::{Context, bail, ensure};
use gpapi::{hip::HipSource, service::request::PreviewHipReportRequest};
use tokio::{io::AsyncReadExt, process::Command};
use gpapi::{
hip::HipSource,
os_profile::HostIdentity,
service::{
request::PreviewHipReportRequest,
transport::{ServiceErrorCode, ServiceResult},
},
};
use openconnect::HipRequest;
use tokio::{
sync::{Mutex, Semaphore},
task::JoinHandle,
};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use crate::{session_registry::SessionRegistry, ws_connection::ConnectionControl};
const MAX_PREVIEW_BYTES: u64 = 1024 * 1024;
const PREVIEW_TIMEOUT: Duration = Duration::from_secs(60);
const PREVIEW_COOKIE: &str = "user=preview&domain=preview&computer=preview";
const PREVIEW_IP: &str = "192.0.2.1";
const PREVIEW_MD5: &str = "00000000000000000000000000000000";
const MAX_ACTIVE_PREVIEWS: usize = 4;
pub(crate) async fn generate(
struct PreviewTask {
connection_id: Uuid,
cancellation: CancellationToken,
worker: JoinHandle<()>,
}
pub(crate) struct PreviewJob {
pub session_id: Uuid,
pub request_id: Uuid,
pub request: PreviewHipReportRequest,
pub edited_report: Option<Arc<str>>,
pub desktop_uid: Option<u32>,
pub identity: HostIdentity,
pub registry: Arc<SessionRegistry>,
pub connection: ConnectionControl,
}
pub(crate) struct HipPreviews {
tasks: Mutex<HashMap<Uuid, PreviewTask>>,
slots: Arc<Semaphore>,
shutdown: CancellationToken,
}
impl HipPreviews {
pub(crate) fn new() -> Self {
Self {
tasks: Mutex::new(HashMap::new()),
slots: Arc::new(Semaphore::new(MAX_ACTIVE_PREVIEWS)),
shutdown: CancellationToken::new(),
}
}
pub(crate) async fn start(&self, job: PreviewJob) -> bool {
let PreviewJob {
session_id,
request_id,
request,
edited_report,
desktop_uid,
identity,
registry,
connection,
} = job;
let mut tasks = self.tasks.lock().await;
if self.shutdown.is_cancelled() || tasks.get(&session_id).is_some_and(|task| !task.worker.is_finished()) {
return false;
}
if let Some(completed) = tasks.remove(&session_id) {
let _ = completed.worker.await;
}
let Ok(slot) = Arc::clone(&self.slots).try_acquire_owned() else {
return false;
};
let cancellation = self.shutdown.child_token();
let worker_cancellation = cancellation.clone();
let connection_id = connection.connection_id();
let worker = tokio::spawn(async move {
let _slot = slot;
let generated = tokio::task::spawn_blocking(move || {
generate(request, edited_report, desktop_uid, identity, worker_cancellation)
})
.await;
let result = match generated {
Ok(Ok(xml)) => preview_result(&registry, session_id, xml),
Ok(Err(error)) => {
log::warn!("HIP preview failed: {error:#}");
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
}
Err(error) => {
log::warn!("HIP preview worker failed: {error}");
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
}
};
// A bounded connection queue must not prevent preview teardown.
let _ = connection.send(crate::ws_connection::ConnectionCommand::Reply { id: request_id, result });
});
tasks.insert(
session_id,
PreviewTask {
connection_id,
cancellation,
worker,
},
);
true
}
pub(crate) async fn cancel_connection(&self, session_id: Uuid, connection_id: Uuid) {
let mut tasks = self.tasks.lock().await;
if !tasks
.get(&session_id)
.is_some_and(|task| task.connection_id == connection_id)
{
return;
}
if let Some(task) = tasks.remove(&session_id) {
task.cancellation.cancel();
let _ = task.worker.await;
}
}
pub(crate) async fn shutdown(&self) {
self.shutdown.cancel();
let tasks = std::mem::take(&mut *self.tasks.lock().await);
for task in tasks.into_values() {
let _ = task.worker.await;
}
}
}
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
registry
.hip_preview_chunk(session_id, preview_id, 0)
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
preview_id: preview_id.to_string(),
offset: 0,
xml,
complete,
})
});
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
}
fn generate(
request: PreviewHipReportRequest,
edited_report: Option<Arc<str>>,
desktop_uid: Option<u32>,
identity: HostIdentity,
cancellation: CancellationToken,
) -> anyhow::Result<String> {
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
ensure!(
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
"Invalid HIP host ID"
);
let source = &request.source;
let execution = match source {
let budget = gpapi::process::collection::CollectionBudget::new(PREVIEW_TIMEOUT);
let check = || {
if cancellation.is_cancelled() {
return Err(io::Error::new(io::ErrorKind::Interrupted, "HIP preview cancelled"));
}
gpapi::process::collection::CollectionControl::check(&budget)
};
check()?;
let profile = crate::hip_source::profile(
&identity,
request.client_os,
Some(request.client_version.clone()),
None,
request.host_id.clone(),
None,
&check,
)?;
let input = HipRequest {
cookie: "user=preview&domain=preview&computer=preview".into(),
client_ip: Some("192.0.2.1".into()),
client_ipv6: None,
md5: "00000000000000000000000000000000".into(),
client_version: request.client_version,
client_os: request.client_os.as_str().into(),
os_version: profile.os_version().into(),
host_id: request.host_id,
local_hostname: Some(profile.computer().into()),
};
let xml = match &request.source {
HipSource::Disabled => bail!("HIP is disabled"),
HipSource::Generated | HipSource::Edited { .. } => crate::hip_source::preview_runner(edited_report)?,
HipSource::UserScript { .. } | HipSource::ApprovedRootScript { .. } => {
crate::hip_source::resolve(source, desktop_uid, false, None)?
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
HipSource::Edited { .. } => {
let xml = edited_report.context("Edited HIP report is unavailable")?;
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
}
source => {
let execution = crate::hip_source::resolve(source, desktop_uid, false, None, Some(profile))?;
let openconnect::HipSource::Script(script) = execution.source else {
bail!("HIP preview executable is unavailable");
};
let xml = script.preview(&input, &check)?;
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
xml
}
};
let script = execution
.wrapper
.as_deref()
.context("HIP preview script is unavailable")?;
let is_runner = !matches!(source, HipSource::UserScript { .. });
let mut command = Command::new(script);
command
.arg("--client-version")
.arg(&request.client_version)
.arg("--client-os")
.arg(request.client_os.as_str())
.arg("--os-version")
.arg(request.client_os.default_os_version());
if let Some(host_id) = request.host_id {
command.arg("--host-id").arg(host_id);
}
if is_runner {
command.arg("--preview");
}
command
.arg("--cookie")
.arg(PREVIEW_COOKIE)
.arg("--client-ip")
.arg(PREVIEW_IP)
.arg("--md5")
.arg(PREVIEW_MD5)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
command.as_std_mut().process_group(0);
configure_identity(&mut command, execution.uid, &request.client_version)?;
command.kill_on_drop(true);
let mut child = command.spawn().context("Failed to launch HIP preview")?;
let mut process_group = ProcessGroupGuard::new(child.id());
let mut stdout = child
.stdout
.take()
.context("HIP preview has no output stream")?
.take(MAX_PREVIEW_BYTES + 1);
let output = tokio::time::timeout(PREVIEW_TIMEOUT, async {
let mut bytes = Vec::new();
stdout.read_to_end(&mut bytes).await?;
ensure!(bytes.len() as u64 <= MAX_PREVIEW_BYTES, "HIP preview exceeds 1 MiB");
let status = child.wait().await?;
process_group.disarm();
ensure!(status.success(), "HIP preview generator failed");
Ok::<_, anyhow::Error>(String::from_utf8(bytes)?)
})
.await;
match output {
Ok(Ok(xml)) => {
if matches!(
source,
HipSource::UserScript { .. } | HipSource::ApprovedRootScript { .. }
) {
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
}
Ok(xml)
}
Ok(Err(error)) => {
terminate_group(&mut child, &mut process_group).await;
Err(error)
}
Err(_) => {
terminate_group(&mut child, &mut process_group).await;
anyhow::bail!("HIP preview timed out")
}
}
check()?;
Ok(xml)
}
fn configure_identity(command: &mut Command, uid: u32, app_version: &str) -> anyhow::Result<()> {
command
.as_std_mut()
.env_clear()
.env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
.env("LC_ALL", "C")
.env("APP_VERSION", app_version);
if uid == 0 {
command.as_std_mut().env("HOME", "/root");
return Ok(());
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
{
use nix::unistd::{Uid, User};
let user = User::from_uid(Uid::from_raw(uid))?.context("Desktop user is unavailable")?;
command
.as_std_mut()
.env("HOME", &user.dir)
.env("USER", &user.name)
.env("LOGNAME", &user.name)
.current_dir(&user.dir);
if Uid::effective().as_raw() == uid {
return Ok(());
}
// Match OpenConnect's CSD child: a single primary group, then the desktop UID.
unsafe {
command.as_std_mut().pre_exec(move || {
nix::unistd::setgid(user.gid).map_err(std::io::Error::from)?;
nix::unistd::setgroups(&[user.gid]).map_err(std::io::Error::from)?;
nix::unistd::setuid(Uid::from_raw(uid)).map_err(std::io::Error::from)?;
Ok(())
});
}
Ok(())
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
{
bail!("Custom HIP previews are unavailable on this platform")
}
}
struct ProcessGroupGuard(Option<u32>);
impl ProcessGroupGuard {
fn new(pid: Option<u32>) -> Self {
Self(pid)
}
fn kill(&mut self) {
if let Some(pid) = self.0.take() {
unsafe { nix::libc::kill(-(pid as i32), nix::libc::SIGKILL) };
}
}
fn disarm(&mut self) {
self.0 = None;
}
}
impl Drop for ProcessGroupGuard {
fn drop(&mut self) {
self.kill();
}
}
async fn terminate_group(child: &mut tokio::process::Child, process_group: &mut ProcessGroupGuard) {
process_group.kill();
let _ = child.start_kill();
let _ = child.wait().await;
}
#[cfg(all(test, any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
#[cfg(test)]
mod tests {
use super::*;
use gpapi::os_profile::ClientOs;
use std::{fs, os::unix::fs::PermissionsExt};
use std::sync::atomic::{AtomicBool, Ordering};
fn request(path: &std::path::Path) -> PreviewHipReportRequest {
PreviewHipReportRequest {
source: HipSource::UserScript {
path: path.to_string_lossy().into_owned(),
fn job(session_id: Uuid) -> PreviewJob {
let (tx, _) = tokio::sync::mpsc::channel(1);
let (connection, _) = ConnectionControl::new(Uuid::new_v4(), tx);
PreviewJob {
session_id,
request_id: Uuid::new_v4(),
request: PreviewHipReportRequest {
source: HipSource::Generated,
client_os: ClientOs::Linux,
client_version: "6.3.3".into(),
host_id: None,
},
client_os: ClientOs::Linux,
client_version: "6.3.3".into(),
host_id: Some("host-test".into()),
}
}
fn script(path: &std::path::Path, body: &str) {
fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap();
}
#[tokio::test]
async fn user_script_preview_receives_placeholders_and_validates_output() {
let uid = nix::unistd::Uid::effective().as_raw();
if uid == 0 {
return;
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("hip.sh");
script(
&path,
r#"
test "$1" = --client-version && test "$2" = 6.3.3 || exit 2
test "$3" = --client-os && test "$4" = Linux || exit 2
test "$5" = --os-version || exit 2
test "$7" = --host-id && test "$8" = host-test || exit 2
test "$9" = --cookie && test "${10}" = 'user=preview&domain=preview&computer=preview' || exit 2
test "${11}" = --client-ip && test "${12}" = 192.0.2.1 || exit 2
test "${13}" = --md5 && test "${14}" = 00000000000000000000000000000000 || exit 2
test "$#" = 14 || exit 2
test "$APP_VERSION" = 6.3.3 || exit 2
printf '%s' '<hip-report><md5-sum/><user-name/><domain/><host-name/><host-id/><ip-address/><ipv6-address/><generate-time/><hip-report-version/><categories><entry name="host-info"><client-version/><os/><os-vendor/><domain/><host-name/><host-id/></entry></categories></hip-report>'
"#,
);
let xml = generate(request(&path), None, Some(uid)).await.unwrap();
assert!(xml.starts_with("<hip-report>"));
script(&path, "printf '%s' '<not-hip/>'");
assert!(generate(request(&path), None, Some(uid)).await.is_err());
script(&path, "head -c 1048577 /dev/zero");
let err = generate(request(&path), None, Some(uid)).await.unwrap_err();
assert!(err.to_string().contains("exceeds 1 MiB"));
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn cancelling_preview_stops_its_process_group() {
let uid = nix::unistd::Uid::effective().as_raw();
if uid == 0 {
return;
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("hip.sh");
let pid_file = dir.path().join("pids");
script(
&path,
&format!(
"sleep 30 & child=$!; echo \"$$ $child\" > \"{}\"; wait",
pid_file.display()
edited_report: None,
desktop_uid: None,
identity: HostIdentity::from_parts(
"device".into(),
"host".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
),
registry: Arc::new(SessionRegistry::new(Uuid::new_v4())),
connection,
}
}
#[tokio::test]
async fn preview_admission_rejects_duplicate_session_and_global_capacity() {
let previews = HipPreviews::new();
let session_id = Uuid::new_v4();
let cancellation = previews.shutdown.child_token();
let worker_cancellation = cancellation.clone();
let worker = tokio::spawn(async move { worker_cancellation.cancelled().await });
let connection_id = Uuid::new_v4();
previews.tasks.lock().await.insert(
session_id,
PreviewTask {
connection_id,
cancellation,
worker,
},
);
assert!(!previews.start(job(session_id)).await);
previews.cancel_connection(session_id, connection_id).await;
let _all_slots = Arc::clone(&previews.slots)
.acquire_many_owned(MAX_ACTIVE_PREVIEWS as u32)
.await
.unwrap();
assert!(!previews.start(job(Uuid::new_v4())).await);
previews.shutdown().await;
}
#[tokio::test]
async fn closing_preview_owner_waits_for_worker_teardown() {
let previews = HipPreviews::new();
let session_id = Uuid::new_v4();
let connection_id = Uuid::new_v4();
let cancellation = previews.shutdown.child_token();
let worker_cancellation = cancellation.clone();
let stopped = Arc::new(AtomicBool::new(false));
let worker_stopped = Arc::clone(&stopped);
let worker = tokio::spawn(async move {
worker_cancellation.cancelled().await;
tokio::task::yield_now().await;
worker_stopped.store(true, Ordering::SeqCst);
});
previews.tasks.lock().await.insert(
session_id,
PreviewTask {
connection_id,
cancellation,
worker,
},
);
previews.cancel_connection(session_id, Uuid::new_v4()).await;
assert!(!stopped.load(Ordering::SeqCst));
previews.cancel_connection(session_id, connection_id).await;
assert!(stopped.load(Ordering::SeqCst));
assert!(previews.tasks.lock().await.is_empty());
previews.shutdown().await;
assert!(!previews.start(job(session_id)).await);
}
#[test]
fn cancelled_preview_does_not_start_collection() {
let preview = job(Uuid::new_v4());
let cancelled = CancellationToken::new();
cancelled.cancel();
let error = generate(preview.request, None, None, preview.identity, cancelled).unwrap_err();
assert_eq!(
error.downcast_ref::<io::Error>().unwrap().kind(),
io::ErrorKind::Interrupted
);
let preview = tokio::spawn(generate(request(&path), None, Some(uid)));
let pids = tokio::time::timeout(Duration::from_secs(3), async {
loop {
if let Ok(pids) = fs::read_to_string(&pid_file) {
break pids;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
let child_pid = pids.split_whitespace().nth(1).unwrap().parse::<u32>().unwrap();
preview.abort();
assert!(preview.await.unwrap_err().is_cancelled());
tokio::time::timeout(Duration::from_secs(3), async {
loop {
let state = fs::read_to_string(format!("/proc/{child_pid}/stat"))
.ok()
.and_then(|stat| stat.rsplit_once(") ").and_then(|(_, fields)| fields.chars().next()));
if state.is_none_or(|state| state == 'Z') {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
}
-59
View File
@@ -1,59 +0,0 @@
use std::{
fs,
os::unix::fs::{MetadataExt, PermissionsExt},
path::Path,
};
use anyhow::{Context, ensure};
use serde::{Deserialize, Serialize};
pub const RUNNER_NAME: &str = "gp-hip-runner";
pub const STATE_NAME: &str = "report.json";
pub const MAX_STATE_BYTES: usize = 512 * 1024;
#[derive(Deserialize, Serialize)]
#[serde(tag = "source", rename_all = "camelCase")]
pub enum RunnerReport {
Generated,
Edited { xml: String },
ApprovedRootScript { approval_id: String, owner_uid: u32 },
}
/// Check every component because a trusted file below a writable parent can
/// be replaced before a later HIP refresh.
pub fn validate_root_owned_path(path: &Path, file: bool) -> anyhow::Result<()> {
ensure!(path.is_absolute(), "HIP runner path must be absolute");
for component in path.ancestors().take_while(|part| part.as_os_str() != "/") {
let metadata =
fs::symlink_metadata(component).with_context(|| format!("Cannot inspect {}", component.display()))?;
ensure!(!metadata.file_type().is_symlink(), "HIP runner path contains a symlink");
ensure!(metadata.uid() == 0, "HIP runner path is not root-owned");
ensure!(
metadata.permissions().mode() & 0o022 == 0,
"HIP runner path is writable by another user"
);
if component == path && file {
ensure!(metadata.is_file(), "HIP runner is not a regular file");
ensure!(
metadata.permissions().mode() & 0o111 != 0,
"HIP runner is not executable"
);
} else {
ensure!(metadata.is_dir(), "HIP runner parent is not a directory");
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_user_owned_runner_directory() {
let temp = tempfile::tempdir().unwrap();
if unsafe { nix::libc::geteuid() } != 0 {
assert!(validate_root_owned_path(temp.path(), false).is_err());
}
}
}
+204 -214
View File
@@ -1,52 +1,36 @@
use std::{
fs::{self, OpenOptions},
io::Write,
os::unix::fs::{OpenOptionsExt, PermissionsExt},
path::{Path, PathBuf},
sync::Arc,
};
use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc};
use anyhow::{Context, bail, ensure};
use gpapi::hip::HipSource;
use gpservice::hip_runner_state::{MAX_STATE_BYTES, RUNNER_NAME, RunnerReport, STATE_NAME, validate_root_owned_path};
use tempfile::{Builder, TempDir};
use gpapi::{
hip::HipSource,
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
};
use gphip::{ReportContext, ReportInput};
use openconnect::{HipRequest, HipScript, HipScriptEnvironment};
pub(crate) struct HipExecution {
pub enabled: bool,
pub uid: u32,
pub wrapper: Option<String>,
_state_dir: Option<TempDir>,
approval: Option<(String, u32)>,
pub source: openconnect::HipSource,
approval: HipApproval,
}
impl HipExecution {
fn disabled() -> Self {
Self {
enabled: false,
uid: 0,
wrapper: None,
_state_dir: None,
approval: None,
}
pub(crate) fn into_parts(self) -> (openconnect::HipSource, HipApproval) {
(self.source, self.approval)
}
}
fn script(uid: u32, wrapper: PathBuf, state_dir: Option<TempDir>) -> Self {
Self {
enabled: true,
uid,
wrapper: Some(wrapper.to_string_lossy().into_owned()),
_state_dir: state_dir,
approval: None,
}
}
pub(crate) struct HipApproval {
identity: Option<(String, u32)>,
}
impl HipApproval {
pub(crate) fn approval_id(&self) -> Option<&str> {
self.approval.as_ref().map(|(id, _)| id.as_str())
self.identity.as_ref().map(|(id, _)| id.as_str())
}
pub(crate) fn approval_is_valid(&self) -> bool {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
if let Some((id, uid)) = &self.approval {
if let Some((id, uid)) = &self.identity {
return gpservice::hip_approval::resolve(id, *uid).is_ok();
}
true
@@ -58,43 +42,67 @@ pub(crate) fn resolve(
desktop_uid: Option<u32>,
brokered_macos: bool,
edited_report: Option<Arc<str>>,
profile: Option<OsProfile>,
) -> anyhow::Result<HipExecution> {
match source {
HipSource::Disabled => Ok(HipExecution::disabled()),
HipSource::Generated => stage_runner(RunnerReport::Generated),
HipSource::Edited { .. } => {
let xml = edited_report.context("Edited HIP report was not uploaded for this connection")?;
gphip::validate_edited_report(&xml)?;
stage_runner(RunnerReport::Edited { xml: xml.to_string() })
let approval;
let source = match source {
HipSource::Disabled => {
approval = None;
openconnect::HipSource::Disabled
}
HipSource::Generated | HipSource::Edited { .. } => {
let profile = profile.context("HIP generator identity is unavailable")?;
approval = None;
let xml = match source {
HipSource::Edited { .. } => {
let xml = edited_report.context("Edited HIP report was not uploaded for this connection")?;
gphip::validate_edited_report(&xml)?;
Some(xml)
}
_ => None,
};
openconnect::HipSource::Generator(Arc::new(move |request, control| {
generate(&profile, xml.as_deref(), request, &|| control.check(), false).map_err(generation_error)
}))
}
HipSource::UserScript { path } => {
if cfg!(target_os = "macos") || brokered_macos {
bail!("Custom HIP scripts are unavailable on macOS");
}
approval = None;
ensure_custom_available(brokered_macos)?;
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?;
ensure!(uid != 0, "HIP custom scripts require a non-root desktop user");
let path = PathBuf::from(path);
ensure!(path.is_absolute(), "HIP custom script path must be absolute");
let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?;
ensure!(
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0,
"HIP custom script must be an executable regular file"
);
Ok(HipExecution::script(uid, path, None))
let script =
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
openconnect::HipSource::Script(script)
}
HipSource::ApprovedRootScript { approval_id } => {
if cfg!(target_os = "macos") || brokered_macos {
bail!("Custom HIP scripts are unavailable on macOS");
}
ensure_custom_available(brokered_macos)?;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
{
let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?;
gpservice::hip_approval::resolve(approval_id, owner_uid)?;
let mut execution = stage_runner(RunnerReport::ApprovedRootScript {
approval_id: approval_id.clone(),
owner_uid,
})?;
execution.approval = Some((approval_id.clone(), owner_uid));
Ok(execution)
let approved = gpservice::hip_approval::resolve(approval_id, owner_uid)?;
let id = approval_id.clone();
let path = approved.path;
let expected = path.clone();
let script = HipScript::new(path.to_string_lossy().into_owned(), Some(0))?
.with_environment(script_environment(0)?)?
.with_validator(move |control| {
control.check()?;
let current = gpservice::hip_approval::resolve_with_control(&id, owner_uid, &|| control.check())
.map_err(generation_error)?;
if current.path != expected {
return Err(io::Error::other("Approved HIP executable changed"));
}
control.check()
});
approval = Some((approval_id.clone(), owner_uid));
openconnect::HipSource::Script(script)
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
{
@@ -102,190 +110,172 @@ pub(crate) fn resolve(
bail!("Root HIP script approvals are unavailable on this platform")
}
}
}
}
pub(crate) fn preview_runner(edited_report: Option<Arc<str>>) -> anyhow::Result<HipExecution> {
let report = if let Some(xml) = edited_report {
gphip::validate_edited_report(&xml)?;
RunnerReport::Edited { xml: xml.to_string() }
} else {
RunnerReport::Generated
};
stage_runner(report)
Ok(HipExecution {
source,
approval: HipApproval { identity: approval },
})
}
fn stage_runner(report: RunnerReport) -> anyhow::Result<HipExecution> {
let source = packaged_runner()?;
let base = runner_state_base();
fs::create_dir_all(base).context("Cannot create HIP runtime directory")?;
validate_root_owned_path(base, false)?;
fs::set_permissions(base, fs::Permissions::from_mode(0o700))?;
let state_dir = Builder::new().prefix("session-").tempdir_in(base)?;
fs::set_permissions(state_dir.path(), fs::Permissions::from_mode(0o700))?;
validate_root_owned_path(state_dir.path(), false)?;
let runner = state_dir.path().join(RUNNER_NAME);
fs::copy(&source, &runner).context("Cannot stage HIP runner")?;
fs::set_permissions(&runner, fs::Permissions::from_mode(0o500))?;
validate_root_owned_path(&runner, true)?;
verify_staged_runner(&runner)?;
let encoded_state = serde_json::to_vec(&report)?;
fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> {
ensure!(
encoded_state.len() <= MAX_STATE_BYTES,
"HIP runner state exceeds its size limit"
!cfg!(target_os = "macos") && !brokered_macos,
"Custom HIP scripts are unavailable on macOS"
);
let state = state_dir.path().join(STATE_NAME);
let mut state_file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&state)?;
state_file.write_all(&encoded_state)?;
state_file.flush()?;
Ok(HipExecution::script(0, runner, Some(state_dir)))
}
fn runner_state_base() -> &'static Path {
#[cfg(target_os = "macos")]
{
Path::new("/private/var/db/gpclient/hip")
}
#[cfg(target_os = "linux")]
{
Path::new("/var/lib/gpclient/hip")
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
{
Path::new("/var/db/gpclient/hip")
}
}
fn packaged_runner() -> anyhow::Result<PathBuf> {
#[cfg(target_os = "macos")]
let path = std::env::current_exe()
.context("Cannot locate HIP runner")?
.with_file_name(RUNNER_NAME);
#[cfg(target_os = "linux")]
let path = PathBuf::from("/usr/libexec/gpclient/gp-hip-runner");
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
let path = PathBuf::from("/usr/local/libexec/gpclient/gp-hip-runner");
#[cfg(not(target_os = "macos"))]
validate_root_owned_path(&path, true)?;
#[cfg(target_os = "macos")]
verify_packaged_macos_runner(&path)?;
ensure!(path.is_file(), "Bundled HIP runner is missing");
Ok(path)
}
#[cfg(target_os = "macos")]
fn verify_packaged_macos_runner(path: &Path) -> anyhow::Result<()> {
use std::process::Command;
let service = std::env::current_exe()?;
let app = service
.parent()
.and_then(Path::parent)
.and_then(Path::parent)
.context("gpservice is not in an app bundle")?;
ensure!(
path.parent() == service.parent(),
"HIP runner is outside the app Helpers directory"
);
let status = Command::new("/usr/bin/codesign")
.args(["--verify", "--deep", "--strict"])
.arg(app)
.status()?;
ensure!(status.success(), "HIP application bundle signature is invalid");
Ok(())
}
#[cfg(target_os = "macos")]
fn verify_staged_runner(path: &Path) -> anyhow::Result<()> {
use std::process::Command;
let status = Command::new("/usr/bin/codesign")
.args(["--verify", "--strict"])
.arg(path)
.status()?;
ensure!(status.success(), "Staged HIP runner signature is invalid");
let service = std::env::current_exe()?;
ensure!(
signing_team(path)? == signing_team(&service)?,
"HIP runner and service have different signing teams"
);
// The staged runner has no app Frameworks directory. Reject any library
// reference that could resolve through a writable bundle or search path.
let output = Command::new("/usr/bin/otool").arg("-L").arg(path).output()?;
ensure!(output.status.success(), "Cannot inspect HIP runner libraries");
for library in String::from_utf8(output.stdout)?
.lines()
.skip(1)
.filter_map(|line| line.trim().split_whitespace().next())
{
ensure!(
library.starts_with("/usr/lib/") || library.starts_with("/System/Library/"),
"HIP runner loads a library outside the trusted system paths"
);
pub(crate) fn generate(
profile: &OsProfile,
edited: Option<&str>,
request: &HipRequest,
control: &dyn gpapi::process::collection::CollectionControl,
preview: bool,
) -> anyhow::Result<String> {
control.check()?;
let context = if preview {
ReportContext::Preview
} else {
ReportContext::Connected {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
}
};
let input = ReportInput {
profile: profile.clone(),
context,
};
match edited {
Some(xml) => gphip::refresh_edited_report_with_control(xml, &input, control),
None => gphip::generate_report_with_control(&input, control),
}
Ok(())
}
#[cfg(target_os = "macos")]
fn signing_team(path: &Path) -> anyhow::Result<String> {
let output = std::process::Command::new("/usr/bin/codesign")
.args(["-d", "--verbose=4"])
.arg(path)
.output()?;
ensure!(output.status.success(), "Cannot inspect code signature");
let details = String::from_utf8(output.stderr)?;
details
.lines()
.find_map(|line| line.strip_prefix("TeamIdentifier="))
.filter(|team| !team.is_empty() && *team != "not set")
.map(str::to_owned)
.context("Signed HIP binary has no team identifier")
pub(crate) fn script_environment(uid: u32) -> anyhow::Result<HipScriptEnvironment> {
let user =
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.context("HIP execution user is unavailable")?;
let home = user.dir.to_string_lossy().into_owned();
Ok(HipScriptEnvironment {
variables: vec![
(
"PATH".into(),
gpapi::process::collection::command_path(uid == 0)?
.into_string()
.map_err(|_| anyhow::anyhow!("HIP command path is not valid UTF-8"))?,
),
("LC_ALL".into(), "C".into()),
("HOME".into(), home.clone()),
("USER".into(), user.name.clone()),
("LOGNAME".into(), user.name),
],
cwd: home,
})
}
#[cfg(not(target_os = "macos"))]
fn verify_staged_runner(_path: &Path) -> anyhow::Result<()> {
Ok(())
pub(crate) fn profile(
identity: &HostIdentity,
os: ClientOs,
version: Option<String>,
os_version: Option<String>,
host_id: Option<String>,
hostname: Option<String>,
control: &dyn gpapi::process::collection::CollectionControl,
) -> io::Result<OsProfile> {
let identity = HostIdentity::from_parts(
hostname.unwrap_or_else(|| identity.computer().into()),
host_id.unwrap_or_else(|| identity.host_id().into()),
identity.serialno().into(),
identity.mac_addr().into(),
);
let mut builder = OsProfileBuilder::new(os).host_identity(identity);
if let Some(version) = version {
builder = builder.client_version(version);
}
if let Some(os_version) = os_version {
builder = builder.os_version(os_version);
}
builder.build_with_control(control)
}
fn generation_error(error: anyhow::Error) -> io::Error {
match error.downcast::<io::Error>() {
Ok(error) => error,
Err(error) => io::Error::other(error),
}
}
#[cfg(test)]
mod tests {
use super::*;
use gpapi::os_profile::ClientOs;
#[test]
fn disabled_has_no_script_on_both_gui_platforms() {
for brokered_macos in [false, true] {
let execution = resolve(&HipSource::Disabled, None, brokered_macos, None).unwrap();
assert!(!execution.enabled);
assert!(execution.wrapper.is_none());
}
fn fixture_profile() -> OsProfile {
profile(
&HostIdentity::from_parts(
"device".into(),
"host".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
),
ClientOs::Linux,
Some("6.3.3".into()),
Some("negotiated-version".into()),
None,
None,
&gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
)
.unwrap()
}
#[test]
fn custom_source_cannot_choose_root_or_run_on_macos() {
fn callback_configuration_needs_no_files_or_root_identity() {
let generated = resolve(&HipSource::Generated, None, true, None, Some(fixture_profile())).unwrap();
assert!(matches!(generated.source, openconnect::HipSource::Generator(_)));
let disabled = resolve(&HipSource::Disabled, None, true, None, Some(fixture_profile())).unwrap();
assert!(matches!(disabled.source, openconnect::HipSource::Disabled));
}
#[test]
fn profile_retains_negotiated_identity_and_os_version() {
let identity = HostIdentity::from_parts(
"original".into(),
"original-id".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
);
let profile = profile(
&identity,
ClientOs::Mac,
Some("6.3.3".into()),
Some("negotiated-os".into()),
Some("negotiated-host".into()),
Some("negotiated-name".into()),
&gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
)
.unwrap();
assert_eq!(profile.os_version(), "negotiated-os");
assert_eq!(profile.host_identity().host_id(), "negotiated-host");
assert_eq!(profile.host_identity().computer(), "negotiated-name");
assert_eq!(profile.host_identity().serialno(), "serial");
}
#[test]
fn callback_errors_preserve_cancellation() {
let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into());
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
#[test]
fn custom_source_cannot_run_on_macos_or_choose_root_without_approval() {
let source = HipSource::UserScript {
path: "/tmp/hip.sh".into(),
};
assert!(resolve(&source, None, false, None).is_err());
assert!(resolve(&source, Some(0), false, None).is_err());
assert!(resolve(&source, Some(1000), true, None).is_err());
assert!(resolve(&source, None, false, None, None).is_err());
assert!(resolve(&source, Some(0), false, None, None).is_err());
assert!(resolve(&source, Some(1000), true, None, Some(fixture_profile())).is_err());
#[cfg(target_os = "macos")]
assert!(resolve(&source, Some(1000), false, None).is_err());
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[test]
fn root_source_requires_a_bound_user_and_installed_approval() {
let source = HipSource::ApprovedRootScript {
approval_id: "00000000-0000-4000-8000-000000000000".into(),
};
assert!(resolve(&source, None, false, None).is_err());
assert!(resolve(&source, Some(0), false, None).is_err());
assert!(resolve(&source, Some(1000), false, None).is_err());
assert!(resolve(&source, Some(1000), false, None, None).is_err());
}
}
-1
View File
@@ -1,5 +1,4 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub mod hip_approval;
pub mod hip_runner_state;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub mod vpnc_script;
+49 -8
View File
@@ -242,7 +242,7 @@ struct ActiveAttempt {
info: ConnectInfo,
allow_extend_session: bool,
_identity_files: Vec<tempfile::NamedTempFile>,
_hip_execution: crate::hip_source::HipExecution,
_hip_approval: crate::hip_source::HipApproval,
}
pub(crate) struct VpnTask {
@@ -309,7 +309,7 @@ impl VpnTask {
}
_ = approval_poll.tick() => {
if self.active.as_ref().is_some_and(|active| {
active._hip_execution.approval_id().is_some() && !active._hip_execution.approval_is_valid()
active._hip_approval.approval_id().is_some() && !active._hip_approval.approval_is_valid()
}) {
warn!("Active HIP script approval is no longer valid; disconnecting VPN");
self.lifecycle.request_disconnect();
@@ -379,14 +379,57 @@ impl VpnTask {
return;
}
};
let hip = match crate::hip_source::resolve(args.hip_source(), desktop_uid, self.brokered_macos, edited_report) {
let profile = if matches!(
args.hip_source(),
gpapi::hip::HipSource::Generated | gpapi::hip::HipSource::Edited { .. }
) {
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
let check = || {
if self.cancel_token.is_cancelled() || self.lifecycle.is_stop_requested(attempt) {
return Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"HIP setup cancelled",
));
}
gpapi::process::collection::CollectionControl::check(&budget)
};
let profile = gpapi::os_profile::HostIdentity::collect_with_control(&check).and_then(|identity| {
crate::hip_source::profile(
&identity,
args.os().unwrap_or(gpapi::os_profile::ClientOs::Linux),
args.client_version(),
args.os_version(),
args.host_id(),
args.local_hostname(),
&check,
)
});
match profile {
Ok(profile) => Some(profile),
Err(error) => {
warn!("Failed to collect the HIP identity: {error}");
self.finish_attempt(attempt);
return;
}
}
} else {
None
};
let hip = match crate::hip_source::resolve(
args.hip_source(),
desktop_uid,
self.brokered_macos,
edited_report,
profile,
) {
Ok(execution) => execution,
Err(err) => {
warn!("Failed to select the HIP script user: {err}");
warn!("Failed to configure the HIP report: {err}");
self.finish_attempt(attempt);
return;
}
};
let (hip_source, hip_approval) = hip.into_parts();
let vpn = match vpn_builder
.user_agent(args.user_agent())
.os(args.openconnect_os())
@@ -396,9 +439,7 @@ impl VpnTask {
.certificate(identity.certificate.clone())
.sslkey(identity.sslkey.clone())
.key_password(args.key_password())
.hip(hip.enabled)
.csd_uid(hip.uid)
.csd_wrapper(hip.wrapper.clone())
.hip_source(hip_source)
.reconnect_timeout(args.reconnect_timeout())
.mtu(args.mtu())
.disable_ipv6(args.disable_ipv6())
@@ -450,7 +491,7 @@ impl VpnTask {
info: info.clone(),
allow_extend_session,
_identity_files: identity.files,
_hip_execution: hip,
_hip_approval: hip_approval,
});
self.send_state(VpnState::Connecting(Box::new(info)));
thread::spawn(move || {
+25 -23
View File
@@ -184,6 +184,10 @@ impl WsConnection {
}
}
ctx
.hip_previews
.cancel_connection(permit.session_id, control.connection_id())
.await;
ctx
.remove_connection(control.connection_id(), permit.session_id, generation)
.await;
@@ -459,29 +463,27 @@ async fn handle_client_message(
} else {
None
};
let registry = Arc::clone(ctx.registry());
let control = control.clone();
tokio::spawn(async move {
let result = match crate::hip_preview::generate(preview, edited_report, desktop_uid).await {
Ok(xml) => match registry.store_hip_preview(session_id, xml) {
Ok(preview_id) => match registry.hip_preview_chunk(session_id, preview_id, 0) {
Ok((xml, complete)) => ServiceResult::HipPreviewChunk {
preview_id: preview_id.to_string(),
offset: 0,
xml,
complete,
},
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"),
},
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"),
},
Err(error) => {
warn!("HIP preview failed: {error:#}");
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
}
};
control.send_reply(id, result).await;
});
if !ctx
.hip_previews
.start(crate::hip_preview::PreviewJob {
session_id,
request_id: id,
request: preview,
edited_report,
desktop_uid,
identity: ctx.host_identity().await,
registry: Arc::clone(ctx.registry()),
connection: control.clone(),
})
.await
{
control
.send(ConnectionCommand::Reply {
id,
result: ServiceResult::rejected(ServiceErrorCode::Busy, "HIP preview is already running"),
})
.map_err(|_| ())?;
}
return Ok(());
}
+7
View File
@@ -39,6 +39,7 @@ pub(crate) struct WsServerContext {
dispatcher: Arc<RequestDispatcher>,
state: Mutex<ServiceState>,
handshake_slots: Arc<Semaphore>,
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
}
impl WsServerContext {
@@ -58,6 +59,7 @@ impl WsServerContext {
connections: HashMap::new(),
}),
handshake_slots: Arc::new(Semaphore::new(16)),
hip_previews: crate::hip_preview::HipPreviews::new(),
}
}
@@ -65,6 +67,10 @@ impl WsServerContext {
self.product_version
}
pub async fn host_identity(&self) -> HostIdentity {
self.state.lock().await.snapshot.host_info.host_identity.clone()
}
pub fn registry(&self) -> &Arc<SessionRegistry> {
&self.registry
}
@@ -243,6 +249,7 @@ impl WsServer {
info!("WS server cancelled");
}
}
self.ctx.hip_previews.shutdown().await;
let _ = shutdown_tx.send(()).await;
}
+1
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license = "MIT"
[dependencies]
nix = { version = "0.31", features = ["fs", "signal", "process"] }
common = { path = "../common" }
anyhow.workspace = true
base64.workspace = true
+127 -61
View File
@@ -1,3 +1,6 @@
use std::{io, time::Duration};
use crate::process::collection::{CollectionBudget, CollectionControl};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -20,8 +23,39 @@ impl HostIdentity {
Self::collect_with_host_id(None)
}
pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result<Self> {
Self::collect_with_host_id_and_control(None, control)
}
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
RuntimeNativeHostIdentity::collect(host_id).into_host_identity()
match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
Ok(identity) => identity,
Err(error) => {
log::warn!("Host identity collection was unavailable: {error}");
Self::default_with_host_id(host_id)
}
}
}
/// Best-effort convenience callers retain the established derived identity
/// when native collection is unavailable. Controlled HIP callers get errors.
pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self {
Self::from_parts(
fallback_hostname(),
resolve_host_id(host_id, fallback_host_id),
String::new(),
primary_mac_colon().unwrap_or_default(),
)
}
pub(crate) fn collect_with_host_id_and_control(
host_id: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<Self> {
control.check()?;
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
control.check()?;
Ok(identity)
}
#[cfg(test)]
@@ -29,7 +63,8 @@ impl HostIdentity {
Self::from_parts(computer, host_id, serialno, mac_addr)
}
pub(crate) fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
/// Construct a host identity from an already collected or negotiated snapshot.
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
let host_id = non_empty(host_id, fallback_host_id());
let computer = non_empty(computer, fallback_hostname());
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
@@ -163,12 +198,12 @@ fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
#[cfg(target_os = "macos")]
mod platform {
use std::process::Command;
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
primary_mac_colon, resolve_host_id,
};
use crate::process::collection::{CollectionControl, CollectorCommands};
use std::io;
pub(super) struct RuntimeNativeHostIdentity;
@@ -177,74 +212,80 @@ mod platform {
ClientOs::Mac
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<NativeHostIdentitySnapshot> {
let commands = CollectorCommands::new(control);
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
control.check()?;
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
NativeHostIdentitySnapshot {
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
let serial_number = collect_macos_serial_number(&commands)?;
control.check()?;
Ok(NativeHostIdentitySnapshot {
host_id,
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
serial_number: collect_macos_serial_number(),
computer,
serial_number,
mac_address: native_mac,
}
})
}
}
fn macos_computer_name() -> Option<String> {
["ComputerName", "LocalHostName"].into_iter().find_map(|name| {
let output = Command::new("scutil").args(["--get", name]).output().ok()?;
if !output.status.success() {
return None;
}
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run(program, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
String::from_utf8(output.stdout)
.ok()
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
for name in ["ComputerName", "LocalHostName"] {
if let Some(value) = output(commands, "scutil", &["--get", name])?
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
})
}
fn macos_builtin_mac() -> Option<String> {
macos_networksetup_mac("Wi-Fi")
.or_else(|| macos_networksetup_mac("AirPort"))
.or_else(macos_system_profiler_wifi_mac)
}
fn macos_networksetup_mac(port_name: &str) -> Option<String> {
let output = Command::new("networksetup")
.arg("-listallhardwareports")
.output()
.ok()?;
if !output.status.success() {
return None;
{
return Ok(Some(value));
}
}
Ok(None)
}
let stdout = String::from_utf8(output.stdout).ok()?;
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
for name in ["Wi-Fi", "AirPort"] {
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
return Ok(Some(mac));
}
}
}
macos_system_profiler_wifi_mac(commands)
}
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = port == port_name;
in_port = port == name;
continue;
}
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn macos_system_profiler_wifi_mac() -> Option<String> {
let output = Command::new("system_profiler").arg("SPNetworkDataType").output().ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
return Ok(None);
};
let mut in_wifi = false;
for line in stdout.lines() {
let trimmed = line.trim();
@@ -252,29 +293,24 @@ mod platform {
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
continue;
}
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
return normalize_mac_colon(mac);
return Ok(normalize_mac_colon(mac));
}
}
None
Ok(None)
}
fn collect_macos_serial_number() -> Option<String> {
let output = Command::new("ioreg")
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
return Ok(None);
};
Ok(stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
})
}))
}
}
@@ -291,7 +327,17 @@ mod platform {
ClientOs::Windows
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
@@ -373,7 +419,17 @@ mod platform {
ClientOs::Linux
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
debug!("Runtime host-id source: explicit override ({})", host_id);
}
@@ -476,6 +532,15 @@ mod platform {
mod tests {
use super::*;
#[test]
fn controlled_identity_collection_propagates_cancellation() {
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = HostIdentity::collect_with_control(&control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
#[test]
fn collect_produces_non_empty_identity() {
let identity = HostIdentity::collect();
@@ -528,7 +593,8 @@ mod tests {
#[test]
fn native_snapshot_uses_host_id_as_derivation_seed() {
let native = RuntimeNativeHostIdentity::collect(None);
let native =
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
assert!(!native.host_id.is_empty());
}
+114 -21
View File
@@ -3,6 +3,9 @@ mod serial_number;
pub use host_identity::HostIdentity;
use crate::process::collection::{CollectionBudget, CollectionControl};
use std::{io, time::Duration};
use common::constants::{GP_CLIENT_VERSION_LINUX, GP_CLIENT_VERSION_MACOS, GP_CLIENT_VERSION_WINDOWS, GP_USER_AGENT};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -366,6 +369,7 @@ impl OsProfile {
pub struct OsProfileBuilder {
client_os: ClientOs,
client_version: Option<String>,
os_version_override: Option<String>,
computer_name_override: Option<String>,
host_id_override: Option<String>,
host_identity: Option<HostIdentity>,
@@ -377,6 +381,7 @@ impl OsProfileBuilder {
Self {
client_os,
client_version: None,
os_version_override: None,
computer_name_override: None,
host_id_override: None,
host_identity: None,
@@ -394,6 +399,13 @@ impl OsProfileBuilder {
self
}
/// Preserve an explicitly negotiated operating system version.
pub fn os_version(mut self, version: impl Into<String>) -> Self {
let version = version.into();
self.os_version_override = if version.trim().is_empty() { None } else { Some(version) };
self
}
pub fn host_identity(mut self, identity: HostIdentity) -> Self {
self.host_identity = Some(identity);
self
@@ -411,31 +423,67 @@ impl OsProfileBuilder {
self
}
/// Build a best-effort profile with a bounded native collection budget.
/// Use `build_with_control` when interruption or timeout must be reported.
pub fn build(self) -> OsProfile {
match self
.clone()
.build_with_control(&CollectionBudget::new(Duration::from_secs(60)))
{
Ok(profile) => profile,
Err(error) => {
log::warn!("OS profile collection was unavailable: {error}");
let identity = self
.host_identity
.clone()
.unwrap_or_else(|| HostIdentity::default_with_host_id(self.host_id_override.as_deref()));
let (os_version, software_version) = match self.client_os {
ClientOs::Mac => (
format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"),
DEFAULT_MACOS_VERSION.into(),
),
os => (target::os_version(os), target::software_version(os)),
};
self.finish(identity, os_version, software_version)
}
}
}
pub fn build_with_control(self, control: &dyn CollectionControl) -> io::Result<OsProfile> {
control.check()?;
let host_identity = match (&self.host_identity, &self.host_id_override) {
(Some(identity), _) => identity.clone(),
(None, host_id) => HostIdentity::collect_with_host_id_and_control(host_id.as_deref(), control)?,
};
let (os_version, software_version) = if self.client_os == ClientOs::Mac {
let version = macos_version_with_control(control)?;
(format!("Apple Mac OS X {version}"), version)
} else {
(
target::os_version(self.client_os),
target::software_version(self.client_os),
)
};
control.check()?;
Ok(self.finish(host_identity, os_version, software_version))
}
fn finish(self, host_identity: HostIdentity, default_os_version: String, software_version: String) -> OsProfile {
let client_version = self
.client_version
.filter(|v| !v.trim().is_empty())
.unwrap_or_else(|| self.client_os.default_client_version().to_string());
let host_identity = match (self.host_identity, self.host_id_override) {
(Some(identity), _) => identity,
(None, host_id) => HostIdentity::collect_with_host_id(host_id.as_deref()),
};
.filter(|version| !version.trim().is_empty())
.unwrap_or_else(|| self.client_os.default_client_version().into());
let profile_identity =
ProfileHostIdentity::for_client_os(self.client_os, &host_identity, self.computer_name_override);
let os_version = target::os_version(self.client_os);
let software_version = target::software_version(self.client_os);
let os_vendor = target::os_vendor(self.client_os);
let os_version = self.os_version_override.unwrap_or(default_os_version);
let user_agent = self
.user_agent
.unwrap_or_else(|| format!("{}/{} ({})", GP_USER_AGENT, client_version, os_version));
.unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})"));
OsProfile {
client_os: self.client_os,
os_version,
software_version,
os_vendor,
os_vendor: target::os_vendor(self.client_os),
client_version,
host_identity,
profile_identity,
@@ -500,14 +548,28 @@ fn runtime_distro_or(fallback: &str) -> String {
}
fn macos_version() -> String {
if runtime_client_os() == ClientOs::Mac {
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_MACOS_VERSION.to_string(),
v => v.to_string(),
}
} else {
DEFAULT_MACOS_VERSION.to_string()
macos_version_with_control(&CollectionBudget::new(Duration::from_secs(60))).unwrap_or_else(|error| {
log::warn!("Operating system version collection was unavailable: {error}");
DEFAULT_MACOS_VERSION.into()
})
}
fn macos_version_with_control(control: &dyn CollectionControl) -> io::Result<String> {
control.check()?;
#[cfg(target_os = "macos")]
{
let commands = crate::process::collection::CollectorCommands::new(control);
let version = commands
.run("sw_vers", &["-productVersion"])?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|version| version.trim().to_string())
.filter(|version| !version.is_empty());
control.check()?;
Ok(version.unwrap_or_else(|| DEFAULT_MACOS_VERSION.into()))
}
#[cfg(not(target_os = "macos"))]
Ok(DEFAULT_MACOS_VERSION.into())
}
fn macos_os_string() -> String {
@@ -691,6 +753,37 @@ mod target_identity {
mod tests {
use super::*;
#[test]
fn controlled_profile_collection_propagates_cancellation_and_deadline() {
let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = OsProfileBuilder::new(ClientOs::Mac)
.build_with_control(&cancelled)
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let expired = CollectionBudget::new(Duration::ZERO);
let error = OsProfileBuilder::new(ClientOs::Linux)
.build_with_control(&expired)
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}
#[test]
fn negotiated_os_version_is_used_in_profile_and_user_agent() {
let identity = HostIdentity::from_parts(
"device".into(),
"host".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.client_version("6.3.3")
.os_version("negotiated-system-version")
.build();
assert_eq!(profile.os_version(), "negotiated-system-version");
assert!(profile.user_agent().contains("negotiated-system-version"));
}
#[test]
fn csc_support_defaults_match_official_profiles() {
assert!(!ClientOs::Linux.default_csc_support());
+296
View File
@@ -0,0 +1,296 @@
use std::{
fs,
io::{self, Read},
os::unix::{
fs::{MetadataExt, PermissionsExt},
process::CommandExt,
},
path::{Path, PathBuf},
process::{Child, Command, Output, Stdio},
thread,
time::{Duration, Instant},
};
use nix::{
fcntl::{FcntlArg, OFlag, fcntl},
sys::signal::{Signal, killpg},
unistd::Pid,
};
/// Invocation control borrowed by collection; interruption must never be treated
/// as an unavailable optional product.
pub trait CollectionControl {
fn check(&self) -> io::Result<()>;
}
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
fn check(&self) -> io::Result<()> {
self()
}
}
pub struct CollectionBudget {
deadline: Instant,
}
impl CollectionBudget {
pub fn new(timeout: Duration) -> Self {
Self {
deadline: Instant::now() + timeout,
}
}
}
impl CollectionControl for CollectionBudget {
fn check(&self) -> io::Result<()> {
if Instant::now() >= self.deadline {
Err(io::Error::new(
io::ErrorKind::TimedOut,
"Device information collection timed out",
))
} else {
Ok(())
}
}
}
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
const TOOL_DIRECTORIES: &[&str] = &[
"/usr/bin",
"/usr/sbin",
"/bin",
"/sbin",
"/usr/local/bin",
"/usr/local/sbin",
];
pub struct CollectorCommands<'a> {
control: &'a dyn CollectionControl,
}
impl<'a> CollectorCommands<'a> {
pub fn new(control: &'a dyn CollectionControl) -> Self {
Self { control }
}
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
TOOL_DIRECTORIES
.iter()
.find_map(|directory| resolve_executable(&Path::new(directory).join(name), uzers::get_effective_uid() == 0))
}
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let Some(path) = self.resolve(name) else {
return Ok(None);
};
self.run_path(&path, args)
}
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let home = if uzers::get_effective_uid() == 0 {
if cfg!(target_os = "macos") {
"/var/root"
} else {
"/root"
}
} else {
"/"
};
let mut command = Command::new(path);
command
.args(args)
.env_clear()
.env("PATH", command_path(uzers::get_effective_uid() == 0)?)
.env("LC_ALL", "C")
.env("HOME", home)
.current_dir("/")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.process_group(0);
let child = match command.spawn() {
Ok(child) => child,
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => {
return Ok(None);
}
Err(error) => return Err(error),
};
let mut child = CollectionChild(child);
let mut stdout = child.0.stdout.take().expect("collector stdout was piped");
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
fcntl(
&stdout,
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
)
.map_err(io::Error::from)?;
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
let mut eof = false;
let mut status = None;
loop {
self.control.check()?;
if !eof {
match stdout.read(&mut buffer) {
Ok(0) => eof = true,
Ok(length) => {
if output.len() + length > COMMAND_OUTPUT_LIMIT {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Device information collector output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
continue;
}
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
Err(error) => return Err(error),
}
}
if status.is_none() {
status = child.0.try_wait()?;
}
if eof && let Some(status) = status {
return Ok(Some(Output {
status,
stdout: output,
stderr: Vec::new(),
}));
}
thread::sleep(Duration::from_millis(10));
}
}
}
fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
let resolved = fs::canonicalize(path).ok()?;
let metadata = fs::metadata(&resolved).ok()?;
if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 && (!require_root || root_owned_path(&resolved)) {
Some(resolved)
} else {
None
}
}
/// Known command directories, canonicalized and restricted to trusted root
/// ownership when used for privileged execution.
pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> {
let directories = TOOL_DIRECTORIES.iter().filter_map(|directory| {
let resolved = fs::canonicalize(directory).ok()?;
if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) {
Some(resolved)
} else {
None
}
});
std::env::join_paths(directories).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))
}
fn root_owned_path(path: &Path) -> bool {
path.ancestors().all(|part| {
fs::symlink_metadata(part).is_ok_and(|metadata| {
metadata.uid() == 0 && metadata.permissions().mode() & 0o022 == 0 && !metadata.file_type().is_symlink()
})
})
}
struct CollectionChild(Child);
impl Drop for CollectionChild {
fn drop(&mut self) {
// Also stop descendants retaining the pipe after the direct child exits.
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
let _ = self.0.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn root_command_path_contains_only_trusted_canonical_directories() {
let path = command_path(true).unwrap();
let directories: Vec<_> = std::env::split_paths(&path).collect();
assert!(!directories.is_empty());
for directory in directories {
assert!(directory.is_dir());
assert!(root_owned_path(&directory));
assert_eq!(directory, fs::canonicalize(&directory).unwrap());
}
}
#[test]
fn executable_resolution_returns_target_not_mutable_symlink() {
let dir = tempfile::tempdir().unwrap();
let link = dir.path().join("tool");
std::os::unix::fs::symlink("/bin/sh", &link).unwrap();
let resolved = resolve_executable(&link, false).unwrap();
fs::remove_file(&link).unwrap();
std::os::unix::fs::symlink("/bin/echo", &link).unwrap();
assert_eq!(resolved, fs::canonicalize("/bin/sh").unwrap());
assert_ne!(resolved, fs::canonicalize(&link).unwrap());
}
#[test]
fn cancellation_stops_running_collector() {
let started = Instant::now();
let control = || {
if started.elapsed() >= Duration::from_millis(100) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
let error = CollectorCommands::new(&control)
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30 & wait"])
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
assert!(started.elapsed() < Duration::from_secs(2));
}
#[test]
fn collector_has_private_environment_and_cwd() {
let budget = CollectionBudget::new(Duration::from_secs(2));
let output = CollectorCommands::new(&budget)
.run_path(
Path::new("/bin/sh"),
&[
"-c",
"printf '%s|%s|%s' \"$LC_ALL\" \"$PWD\" \"${SENTINEL_OUTPUT_JSON-unset}\"",
],
)
.unwrap()
.unwrap();
assert!(output.status.success());
assert_eq!(String::from_utf8(output.stdout).unwrap(), "C|/|unset");
}
#[test]
fn deadline_stops_collector_instead_of_hanging() {
let budget = CollectionBudget::new(Duration::from_millis(100));
let started = Instant::now();
let error = CollectorCommands::new(&budget)
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30"])
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
assert!(started.elapsed() < Duration::from_secs(2));
}
#[test]
fn collector_output_is_bounded() {
let budget = CollectionBudget::new(Duration::from_secs(2));
let error = CollectorCommands::new(&budget)
.run_path(Path::new("/bin/sh"), &["-c", "yes x"])
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
}
#[test]
fn cancellation_is_not_an_optional_missing_product() {
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = CollectorCommands::new(&control).run("not-installed", &[]).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
}
+2
View File
@@ -8,3 +8,5 @@ pub mod auth_launcher;
pub mod gui_launcher;
pub mod service_launcher;
pub mod users;
pub mod collection;
-1
View File
@@ -10,7 +10,6 @@ gpapi = { path = "../gpapi" }
anyhow.workspace = true
askama.workspace = true
chrono.workspace = true
log.workspace = true
netdev.workspace = true
serde.workspace = true
serde_json.workspace = true
+167 -169
View File
@@ -1,10 +1,11 @@
use anyhow::{bail, ensure};
use askama::Template;
use gpapi::os_profile::{ClientOs, OsProfile};
use log::debug;
use serde::Deserialize;
use std::collections::HashMap;
use std::process::Command;
use std::{io, time::Duration};
use gpapi::process::collection::{CollectionBudget, CollectionControl, CollectorCommands};
use xmltree::Element;
#[cfg(target_os = "macos")]
@@ -82,49 +83,62 @@ fn unique_child<'a>(parent: &'a Element, name: &str) -> anyhow::Result<&'a Eleme
Ok(child)
}
const CURRENT_TOP_LEVEL_FIELDS: &[&str] = &[
"md5-sum",
"user-name",
"domain",
"host-name",
"host-id",
"ip-address",
"ipv6-address",
"generate-time",
];
const CURRENT_HOST_INFO_FIELDS: &[&str] = &["client-version", "os", "os-vendor", "domain", "host-name", "host-id"];
/// Refresh only session and current-host fields in a saved HIP report.
/// User-edited categories, products, and network-interface entries remain intact.
/// Refresh current identity/session values without running product collectors.
pub fn refresh_edited_report(edited_xml: &str, input: &ReportInput) -> anyhow::Result<String> {
let budget = CollectionBudget::new(Duration::from_secs(60));
refresh_edited_report_with_control(edited_xml, input, &budget)
}
pub fn refresh_edited_report_with_control(
edited_xml: &str,
input: &ReportInput,
control: &dyn CollectionControl,
) -> anyhow::Result<String> {
control.check()?;
let mut edited = validate_edited_report(edited_xml)?;
let current = validate_edited_report(&generate_report(input)?)?;
for field in CURRENT_TOP_LEVEL_FIELDS {
copy_field(&mut edited, &current, field)?;
let cookie_params = cookie_params(input);
let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity();
control.check()?;
let domain = format!("{}.internal", identity.domain);
let generate_time = get_current_time_components().0;
for (name, value) in [
("md5-sum", input.context.md5()),
("user-name", report_user_name(input, &cookie_params)),
("domain", domain.as_str()),
("host-name", identity.host_name.as_str()),
("host-id", identity.host_id.as_str()),
("ip-address", identity.default_ipv4()),
("ipv6-address", identity.default_ipv6()),
("generate-time", generate_time.as_str()),
] {
set_field(&mut edited, name, value)?;
}
let edited_host = host_info_mut(&mut edited)?;
let current_host = host_info(&current)?;
for field in CURRENT_HOST_INFO_FIELDS {
copy_field(edited_host, current_host, field)?;
let host_info = host_info_mut(&mut edited)?;
for (name, value) in [
("client-version", input.profile.client_version()),
("os", identity.os_version.as_str()),
("os-vendor", identity.os_vendor.as_str()),
("domain", domain.as_str()),
("host-name", identity.host_name.as_str()),
("host-id", identity.host_id.as_str()),
] {
set_field(host_info, name, value)?;
}
let refreshed = write_xml(&edited)?;
validate_edited_report(&refreshed)?;
control.check()?;
Ok(refreshed)
}
fn copy_field(target: &mut Element, source: &Element, name: &str) -> anyhow::Result<()> {
let value = unique_child(source, name)?.children.clone();
fn set_field(target: &mut Element, name: &str, value: &str) -> anyhow::Result<()> {
let field = target
.get_mut_child(name)
.ok_or_else(|| anyhow::anyhow!("HIP report is missing <{name}>"))?;
field.children = value;
field.children = vec![xmltree::XMLNode::Text(value.to_owned())];
Ok(())
}
#[cfg(test)]
fn host_info(root: &Element) -> anyhow::Result<&Element> {
unique_child(root, "categories")?
.children
@@ -194,24 +208,39 @@ pub struct ReportInput {
/// Generate the same XML report used by `gpclient hip`.
pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
let cookie_params: HashMap<String, String> = serde_urlencoded::from_str(input.context.cookie()).unwrap_or_default();
let budget = CollectionBudget::new(Duration::from_secs(60));
generate_report_with_control(input, &budget)
}
pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
control.check()?;
let cookie_params = cookie_params(input);
let (generate_time, day, month, year) = get_current_time_components();
let user_name = match input.context {
ReportContext::Preview => "[available after connection]",
ReportContext::Connected { .. } => cookie_params.get("user").map(String::as_str).unwrap_or(""),
};
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect();
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect(control)?;
let template = HipReportTemplate {
client_version: input.profile.client_version(),
generate_time,
day,
month,
year,
user_name,
user_name: report_user_name(input, &cookie_params),
host_info,
md5: input.context.md5(),
};
format_xml(&template.render()?)
let report = format_xml(&template.render()?)?;
control.check()?;
Ok(report)
}
fn cookie_params(input: &ReportInput) -> HashMap<String, String> {
serde_urlencoded::from_str(input.context.cookie()).unwrap_or_default()
}
fn report_user_name<'a>(input: &ReportInput, cookie_params: &'a HashMap<String, String>) -> &'a str {
match input.context {
ReportContext::Preview => "[available after connection]",
ReportContext::Connected { .. } => cookie_params.get("user").map(String::as_str).unwrap_or(""),
}
}
#[derive(Template)]
@@ -397,7 +426,7 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
/// Single entry point for collecting host info — dispatches per-OS
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
fn collect(&self) -> HostInfo {
fn collect_identity(&self) -> HostInfo {
let runtime_iface = self.collect_network_interface();
let primary = self.adapt_primary_interface(&runtime_iface);
@@ -412,10 +441,10 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
software_version: self.profile.software_version().to_string(),
domain: self.domain_for_profile(),
network_interfaces: interfaces,
defender: self.defender_for_profile(),
clamav: self.clamav_for_profile(),
sentinel: self.sentinel_for_profile(),
ufw: self.ufw_for_profile(),
defender: None,
clamav: None,
sentinel: None,
ufw: None,
}
}
@@ -463,102 +492,81 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> {
}
}
fn defender_for_profile(&self) -> Option<DefenderInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_microsoft_defender_blocking(),
ClientOs::Mac | ClientOs::Windows => None,
fn collect(&self, control: &dyn CollectionControl) -> io::Result<HostInfo> {
control.check()?;
let mut info = self.collect_identity();
control.check()?;
let commands = CollectorCommands::new(control);
if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() {
info.defender = detect_microsoft_defender(&commands)?;
info.clamav = detect_clamav(&commands)?;
info.ufw = detect_ufw(&commands)?;
}
}
fn clamav_for_profile(&self) -> Option<ClamAvInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_clamav(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
fn ufw_for_profile(&self) -> Option<UfwInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_ufw(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
fn sentinel_for_profile(&self) -> Option<SentinelInfo> {
#[cfg(target_os = "macos")]
if self.profile.client_os() == ClientOs::Mac && self.profile.is_native() {
return sentinel_macos::detect();
info.sentinel = sentinel_macos::detect(&commands)?;
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() {
return sentinel_unix::detect();
info.sentinel = sentinel_unix::detect(&commands)?;
}
None
control.check()?;
Ok(info)
}
}
fn detect_clamav() -> Option<ClamAvInfo> {
let version_out = Command::new("clamscan").arg("--version").output().ok()?;
if !version_out.status.success() {
debug!("clamscan not found or failed");
return None;
}
let version_str = String::from_utf8(version_out.stdout).ok()?;
let (version, definitions_version) = parse_clamav_version(&version_str)?;
let rtp_out = Command::new("systemctl")
.args(["is-active", "clamav-onaccess.service"])
.output()
.ok()?;
let real_time_protection = rtp_out.status.success();
Some(ClamAvInfo {
fn detect_clamav(commands: &CollectorCommands<'_>) -> io::Result<Option<ClamAvInfo>> {
let Some(version_str) = command_text(commands, "clamscan", &["--version"])? else {
return Ok(None);
};
let Some((version, definitions_version)) = parse_clamav_version(&version_str) else {
return Ok(None);
};
let real_time_protection = commands
.run("systemctl", &["is-active", "clamav-onaccess.service"])?
.is_some_and(|output| output.status.success());
Ok(Some(ClamAvInfo {
version,
definitions_version,
real_time_protection,
})
}))
}
fn detect_ufw() -> Option<UfwInfo> {
let version_out = Command::new("ufw").arg("version").output().ok()?;
if !version_out.status.success() {
debug!("ufw not found or failed");
return None;
}
let version_str = String::from_utf8(version_out.stdout).ok()?;
let version = parse_ufw_version(&version_str)?;
let is_root = uzers::get_effective_uid() == 0;
let status_out = ufw_status_command(is_root).output().ok()?;
if !status_out.status.success() {
if is_root {
log::warn!("ufw status failed while running as root");
} else {
log::warn!("sudo -n ufw status failed. You may need to configure sudoers to allow execution without a password.");
}
return None;
}
let status_str = String::from_utf8(status_out.stdout).ok()?;
let is_enabled = parse_ufw_status(&status_str)?;
Some(UfwInfo { version, is_enabled })
}
fn ufw_status_command(is_root: bool) -> Command {
let mut command = if is_root {
Command::new("ufw")
} else {
let mut command = Command::new("sudo");
command.args(["-n", "ufw"]);
command
fn detect_ufw(commands: &CollectorCommands<'_>) -> io::Result<Option<UfwInfo>> {
let Some(version_str) = command_text(commands, "ufw", &["version"])? else {
return Ok(None);
};
let Some(version) = parse_ufw_version(&version_str) else {
return Ok(None);
};
let Some(ufw) = commands.resolve("ufw") else {
return Ok(None);
};
let output = if uzers::get_effective_uid() == 0 {
commands.run_path(&ufw, &["status"])?
} else {
commands.run("sudo", &["-n", &ufw.to_string_lossy(), "status"])?
};
let Some(output) = output.filter(|output| output.status.success()) else {
return Ok(None);
};
let Some(is_enabled) = String::from_utf8(output.stdout)
.ok()
.as_deref()
.and_then(parse_ufw_status)
else {
return Ok(None);
};
Ok(Some(UfwInfo { version, is_enabled }))
}
command.arg("status").env("LC_ALL", "C");
command
fn command_text(commands: &CollectorCommands<'_>, name: &str, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run(name, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn parse_clamav_version(output: &str) -> Option<(String, Option<String>)> {
@@ -603,24 +611,11 @@ fn parse_ufw_status(output: &str) -> Option<bool> {
}
}
fn detect_microsoft_defender_blocking() -> Option<DefenderInfo> {
let output = Command::new("mdatp")
.arg("health")
.arg("--output")
.arg("json")
.output()
.ok()?;
if !output.status.success() {
debug!("mdatp health command failed");
return None;
}
let json = String::from_utf8(output.stdout).ok()?;
let defender = parse_defender_info(&json)?;
debug!("Detected Microsoft Defender: {:?}", defender);
Some(defender)
fn detect_microsoft_defender(commands: &CollectorCommands<'_>) -> io::Result<Option<DefenderInfo>> {
let Some(json) = command_text(commands, "mdatp", &["health", "--output", "json"])? else {
return Ok(None);
};
Ok(parse_defender_info(&json))
}
fn parse_defender_info(json: &str) -> Option<DefenderInfo> {
@@ -702,9 +697,19 @@ fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> Strin
#[cfg(test)]
mod tests {
const CURRENT_TOP_LEVEL_FIELDS: &[&str] = &[
"md5-sum",
"user-name",
"domain",
"host-name",
"host-id",
"ip-address",
"ipv6-address",
"generate-time",
];
const CURRENT_HOST_INFO_FIELDS: &[&str] = &["client-version", "os", "os-vendor", "domain", "host-name", "host-id"];
use super::*;
use gpapi::os_profile::OsProfileBuilder;
use std::ffi::OsStr;
fn make_input(profile: OsProfile) -> ReportInput {
ReportInput {
@@ -728,7 +733,7 @@ mod tests {
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.os_vendor, "Linux");
}
@@ -739,7 +744,7 @@ mod tests {
let profile = make_profile(ClientOs::Mac);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.os_vendor, "Apple");
}
@@ -750,7 +755,7 @@ mod tests {
let profile = make_profile(ClientOs::Windows);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.os_vendor, "Microsoft");
}
@@ -761,7 +766,7 @@ mod tests {
let profile = make_profile(ClientOs::Linux);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.host_id, profile.host_id());
}
@@ -775,7 +780,7 @@ mod tests {
let profile = make_profile(client_os);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity();
assert_eq!(info.host_id, profile.host_id());
}
@@ -800,7 +805,7 @@ mod tests {
fn mac_report_renders_detected_sentinel_products() {
let input = make_input(make_profile(ClientOs::Mac));
let cookie_params = HashMap::new();
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect();
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity();
host_info.sentinel = Some(SentinelInfo {
version: "25.3.4.8365".to_string(),
real_time_protection: true,
@@ -831,7 +836,7 @@ mod tests {
fn linux_report_renders_detected_sentinel_antimalware() {
let input = make_input(make_profile(ClientOs::Linux));
let cookie_params = HashMap::new();
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect();
let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity();
host_info.sentinel = Some(SentinelInfo {
version: "25.2.2.14".to_string(),
real_time_protection: true,
@@ -911,9 +916,22 @@ mod tests {
.children
.push(xmltree::XMLNode::Element(custom_category));
let earliest = chrono::Local::now().naive_local().and_utc().timestamp();
let refreshed_xml = refresh_edited_report(&write_xml(&saved).unwrap(), &input).unwrap();
let latest = chrono::Local::now().naive_local().and_utc().timestamp();
let refreshed = validate_edited_report(&refreshed_xml).unwrap();
for field in CURRENT_TOP_LEVEL_FIELDS {
let timestamp = chrono::NaiveDateTime::parse_from_str(
&unique_child(&refreshed, "generate-time").unwrap().get_text().unwrap(),
"%m/%d/%Y %H:%M:%S",
)
.unwrap()
.and_utc()
.timestamp();
assert!((earliest..=latest).contains(&timestamp));
for field in CURRENT_TOP_LEVEL_FIELDS
.iter()
.filter(|field| **field != "generate-time")
{
assert_eq!(
unique_child(&refreshed, field).unwrap().get_text(),
unique_child(&current, field).unwrap().get_text()
@@ -992,24 +1010,4 @@ mod tests {
assert_eq!(parse_ufw_status("Status: inactive\n"), Some(false));
assert_eq!(parse_ufw_status("Status: unknown\n"), None);
}
#[test]
fn runs_ufw_status_directly_as_root() {
let command = ufw_status_command(true);
assert_eq!(command.get_program(), OsStr::new("ufw"));
assert!(command.get_args().eq(["status"].into_iter().map(OsStr::new)));
}
#[test]
fn runs_ufw_status_through_non_interactive_sudo_as_non_root() {
let command = ufw_status_command(false);
assert_eq!(command.get_program(), OsStr::new("sudo"));
assert!(
command
.get_args()
.eq(["-n", "ufw", "status"].into_iter().map(OsStr::new))
);
}
}
+30 -24
View File
@@ -1,34 +1,44 @@
use std::{
fs,
fs, io,
os::unix::fs::{MetadataExt, PermissionsExt},
path::Path,
process::Command,
};
use gpapi::process::collection::CollectorCommands;
use super::SentinelInfo;
const SENTINELCTL: &str = "/Library/Sentinel/sentinel-agent.bundle/Contents/MacOS/sentinelctl";
pub(super) fn detect() -> Option<SentinelInfo> {
pub(super) fn detect(commands: &CollectorCommands<'_>) -> io::Result<Option<SentinelInfo>> {
if !trusted_cli(Path::new(SENTINELCTL)) {
return None;
return Ok(None);
}
let status = run(&["status"])?;
let status = parse_status(&status)?;
let Some(status) = run(commands, &["status"])? else {
return Ok(None);
};
let Some(status) = parse_status(&status) else {
return Ok(None);
};
let real_time_protection = if status.active {
let scan_status = run(&["scan-on-write"])?;
parse_yes_no(scan_status.trim().strip_prefix("scan-on-write:")?)?
let Some(scan_status) = run(commands, &["scan-on-write"])? else {
return Ok(None);
};
let Some(enabled) = scan_status.trim().strip_prefix("scan-on-write:").and_then(parse_yes_no) else {
return Ok(None);
};
enabled
} else {
false
};
let firewall_enabled = run(&["firewall", "enabled"]).as_deref().and_then(parse_yes_no);
Some(SentinelInfo {
let firewall_enabled = run(commands, &["firewall", "enabled"])?
.as_deref()
.and_then(parse_yes_no);
Ok(Some(SentinelInfo {
version: status.version,
real_time_protection,
firewall_enabled,
})
}))
}
fn trusted_cli(path: &Path) -> bool {
@@ -47,17 +57,13 @@ fn trusted_cli(path: &Path) -> bool {
})
}
fn run(args: &[&str]) -> Option<String> {
let output = Command::new(SENTINELCTL)
.args(args)
.env("LC_ALL", "C")
.env_remove("SENTINEL_OUTPUT_JSON")
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
fn run(commands: &CollectorCommands<'_>, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run_path(Path::new(SENTINELCTL), args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
struct AgentStatus {
+34 -24
View File
@@ -1,33 +1,47 @@
use std::{
fs,
fs, io,
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
process::Command,
};
use gpapi::process::collection::CollectorCommands;
use super::SentinelInfo;
const SENTINEL_DIR: &str = "/opt/sentinelone";
pub(super) fn detect() -> Option<SentinelInfo> {
let cli = trusted_cli()?;
let version = parse_version(&run(&cli, &["version"])?)?;
let agent_enabled = parse_enabled(&run(&cli, &["control", "status"])?, "Agent state")?;
pub(super) fn detect(commands: &CollectorCommands<'_>) -> io::Result<Option<SentinelInfo>> {
let Some(cli) = trusted_cli() else {
return Ok(None);
};
let Some(version) = run(commands, &cli, &["version"])?.as_deref().and_then(parse_version) else {
return Ok(None);
};
let Some(agent_enabled) = run(commands, &cli, &["control", "status"])?
.as_deref()
.and_then(|status| parse_enabled(status, "Agent state"))
else {
return Ok(None);
};
let real_time_protection = if agent_enabled {
let policy = run(&cli, &["policy", "status"])?;
let on_write = parse_enabled(&policy, "On-Write:")?;
let on_execute = parse_enabled(&policy, "On-Execute:")?;
let Some(policy) = run(commands, &cli, &["policy", "status"])? else {
return Ok(None);
};
let (Some(on_write), Some(on_execute)) = (
parse_enabled(&policy, "On-Write:"),
parse_enabled(&policy, "On-Execute:"),
) else {
return Ok(None);
};
on_write || on_execute
} else {
false
};
Some(SentinelInfo {
Ok(Some(SentinelInfo {
version,
real_time_protection,
firewall_enabled: None,
})
}))
}
fn trusted_cli() -> Option<PathBuf> {
@@ -72,17 +86,13 @@ fn trusted_dir(path: &Path, owner: u32) -> bool {
metadata.is_dir() && metadata.uid() == owner && metadata.permissions().mode() & 0o022 == 0
}
fn run(cli: &Path, args: &[&str]) -> Option<String> {
let output = Command::new(cli)
.args(args)
.env("LC_ALL", "C")
.env_remove("SENTINEL_OUTPUT_JSON")
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
fn run(commands: &CollectorCommands<'_>, cli: &Path, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run_path(cli, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn parse_version(output: &str) -> Option<String> {
+1
View File
@@ -7,6 +7,7 @@ links = "openconnect"
[dependencies]
log.workspace = true
libc = "0.2"
is_executable.workspace = true
[build-dependencies]
+8
View File
@@ -157,6 +157,14 @@ fn main() {
let deps_dir = PathBuf::from(manifest_dir).join("deps");
let oc_dst = build_openconnect(&deps_dir, &out_dir);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_BUILD={}",
oc_dst.join("build").display()
);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_SOURCE={}",
out_dir.join("openconnect_build").display()
);
// Only statically link libxml2 if `LIBXML2_STATIC` is set
if env::var("LIBXML2_STATIC").is_ok() {
+437
View File
@@ -0,0 +1,437 @@
use crate::{HipControl, HipRequest, HipScript, HipSource, Vpn};
use std::{
ffi::{CString, c_char, c_int, c_void},
io,
marker::PhantomData,
panic::{AssertUnwindSafe, catch_unwind},
};
#[link(name = "vpn")]
unsafe extern "C" {
fn vpn_collect_hip_report(
script: *const HipScriptRaw,
request: *const HipRequestRaw,
control: *const HipControlRaw,
generate: Option<HipGenerateFn>,
data: *mut c_void,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int;
}
#[repr(C)]
pub(crate) struct HipRequestRaw {
cookie: *const c_char,
client_ip: *const c_char,
client_ipv6: *const c_char,
md5: *const c_char,
client_version: *const c_char,
client_os: *const c_char,
os_version: *const c_char,
host_id: *const c_char,
local_hostname: *const c_char,
}
#[repr(C)]
pub(crate) struct HipControlRaw {
pub data: *mut c_void,
pub check: unsafe extern "C" fn(*mut c_void) -> c_int,
}
pub(crate) type HipGenerateFn =
extern "C" fn(*mut c_void, *const HipRequestRaw, *const HipControlRaw, *mut c_char, usize, *mut usize) -> c_int;
#[repr(C)]
#[derive(Debug)]
pub(crate) struct HipScriptRaw {
pub path: *const c_char,
pub uid: u32,
pub uid_present: c_int,
pub validation_data: *mut c_void,
pub validate: Option<extern "C" fn(*mut c_void, *const HipControlRaw) -> c_int>,
pub environment: *const *const c_char,
pub cwd: *const c_char,
}
impl Default for HipScriptRaw {
fn default() -> Self {
Self {
path: std::ptr::null(),
uid: 0,
uid_present: 0,
validation_data: std::ptr::null_mut(),
validate: None,
environment: std::ptr::null(),
cwd: std::ptr::null(),
}
}
}
impl HipScriptRaw {
pub fn from_script(script: &HipScript) -> Self {
Self {
path: script.path.as_ptr(),
uid: script.user.unwrap_or(0),
uid_present: script.user.is_some().into(),
validation_data: script as *const _ as *mut _,
validate: script.validator.as_ref().map(|_| validate_hip_script as _),
environment: std::ptr::null(),
cwd: script.cwd.as_ref().map_or(std::ptr::null(), |value| value.as_ptr()),
}
}
}
pub(crate) fn script_environment(script: &HipScript) -> Vec<*const c_char> {
match &script.environment {
Some(values) => values
.iter()
.map(|value| value.as_ptr())
.chain(std::iter::once(std::ptr::null()))
.collect(),
None => Vec::new(),
}
}
fn error_code(error: io::Error) -> c_int {
let errno = error.raw_os_error().unwrap_or_else(|| match error.kind() {
io::ErrorKind::Interrupted => libc::EINTR,
io::ErrorKind::TimedOut => libc::ETIMEDOUT,
io::ErrorKind::InvalidInput | io::ErrorKind::InvalidData => libc::EINVAL,
io::ErrorKind::PermissionDenied => libc::EPERM,
io::ErrorKind::NotFound => libc::ENOENT,
_ => libc::EIO,
});
-errno
}
unsafe fn request_string(pointer: *const c_char) -> io::Result<Option<String>> {
if pointer.is_null() {
return Ok(None);
}
unsafe { std::ffi::CStr::from_ptr(pointer) }
.to_str()
.map(|s| Some(s.to_owned()))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid HIP request encoding"))
}
unsafe fn read_hip_request(raw: &HipRequestRaw) -> io::Result<HipRequest> {
unsafe {
Ok(HipRequest {
cookie: request_string(raw.cookie)?.unwrap_or_default(),
client_ip: request_string(raw.client_ip)?,
client_ipv6: request_string(raw.client_ipv6)?,
md5: request_string(raw.md5)?.unwrap_or_default(),
client_version: request_string(raw.client_version)?.unwrap_or_default(),
client_os: request_string(raw.client_os)?.unwrap_or_default(),
os_version: request_string(raw.os_version)?.unwrap_or_default(),
host_id: request_string(raw.host_id)?,
local_hostname: request_string(raw.local_hostname)?,
})
}
}
pub(crate) extern "C" fn generate_hip_report(
data: *mut c_void,
request: *const HipRequestRaw,
control: *const HipControlRaw,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
let vpn = unsafe { &*(data as *const Vpn) };
let HipSource::Generator(generate) = &vpn.hip_source else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No HIP generator"));
};
let request = unsafe { read_hip_request(&*request)? };
let control = HipControl {
raw: unsafe { &*control },
_thread: PhantomData,
};
control.check()?;
let report = generate(&request, &control)?;
control.check()?;
if report.len() > capacity {
return Err(io::Error::from_raw_os_error(libc::E2BIG));
}
unsafe {
std::ptr::copy_nonoverlapping(report.as_ptr(), output.cast(), report.len());
*written = report.len();
}
Ok(())
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
extern "C" fn validate_hip_script(data: *mut c_void, control: *const HipControlRaw) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| {
let script = unsafe { &*(data as *const HipScript) };
let control = HipControl {
raw: unsafe { &*control },
_thread: PhantomData,
};
control.check()?;
if let Some(validate) = &script.validator {
validate(&control)?;
}
control.check()
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
pub(crate) fn preview_hip_script(
script: &HipScript,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
let mut raw = HipScriptRaw::from_script(script);
let environment = script_environment(script);
if !environment.is_empty() {
raw.environment = environment.as_ptr();
}
collect_hip_report(&raw, None, std::ptr::null_mut(), request, check)
}
fn collect_hip_report(
script_raw: &HipScriptRaw,
generate: Option<HipGenerateFn>,
data: *mut c_void,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
let values = [
Some(request.cookie.as_str()),
request.client_ip.as_deref(),
request.client_ipv6.as_deref(),
Some(request.md5.as_str()),
Some(request.client_version.as_str()),
Some(request.client_os.as_str()),
Some(request.os_version.as_str()),
request.host_id.as_deref(),
request.local_hostname.as_deref(),
]
.into_iter()
.map(|value| value.map(CString::new).transpose())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP request contains NUL"))?;
let ptr = |i: usize| values[i].as_ref().map_or(std::ptr::null(), |value| value.as_ptr());
let raw = HipRequestRaw {
cookie: ptr(0),
client_ip: ptr(1),
client_ipv6: ptr(2),
md5: ptr(3),
client_version: ptr(4),
client_os: ptr(5),
os_version: ptr(6),
host_id: ptr(7),
local_hostname: ptr(8),
};
let control = HipControlRaw {
data: &check as *const _ as *mut _,
check: preview_check,
};
let mut output = vec![0u8; 1024 * 1024 + 1];
let mut written = 0;
let result = unsafe {
vpn_collect_hip_report(
script_raw,
&raw,
&control,
generate,
data,
output.as_mut_ptr().cast(),
1024 * 1024,
&mut written,
)
};
if result < 0 {
return Err(io::Error::from_raw_os_error(-result));
}
output.truncate(written);
String::from_utf8(output).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "HIP output is not UTF-8"))
}
unsafe extern "C" fn preview_check(data: *mut c_void) -> c_int {
let check = unsafe { &*(data as *const &dyn Fn() -> io::Result<()>) };
match catch_unwind(AssertUnwindSafe(check)) {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
#[cfg(test)]
mod hip_tests {
use super::*;
use std::{
fs,
os::unix::fs::PermissionsExt,
sync::atomic::{AtomicUsize, Ordering},
time::{Duration, Instant},
};
fn provider(generate: impl Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync + 'static) -> Vpn {
Vpn::builder("vpn.example", "cookie")
.script_path("/bin/sh".to_owned())
.hip_source(HipSource::Generator(std::sync::Arc::new(generate)))
.build()
.unwrap()
}
fn collect(vpn: &Vpn, script: &HipScriptRaw, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
collect_hip_report(
script,
Some(generate_hip_report),
vpn as *const _ as *mut _,
&HipRequest::default(),
check,
)
}
struct ScriptFixture(std::path::PathBuf);
impl ScriptFixture {
fn new(contents: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let directory = std::env::temp_dir().join(format!(
"gp-hip-script-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&directory).unwrap();
let path = directory.join("script");
fs::write(&path, format!("#!/bin/sh\n{contents}\n")).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
Self(directory)
}
fn script(&self, user: Option<u32>) -> HipScript {
HipScript::new(self.0.join("script").to_str().unwrap().to_owned(), user).unwrap()
}
}
impl Drop for ScriptFixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn callback_outputs_are_bounded_and_validated_by_c() {
let raw = HipScriptRaw::default();
for (report, errno) in [
(String::new(), libc::EINVAL),
("x\0x".to_owned(), libc::EINVAL),
("x".repeat(1024 * 1024 + 1), libc::E2BIG),
] {
let vpn = provider(move |_, _| Ok(report.clone()));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap_err().raw_os_error(), Some(errno));
}
let vpn = provider(|_, _| Ok("x".repeat(1024 * 1024)));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap().len(), 1024 * 1024);
}
#[test]
fn callback_panics_and_control_errors_do_not_cross_ffi() {
let vpn = provider(|_, _| panic!("test generator panic"));
assert_eq!(
collect(&vpn, &Default::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
);
let vpn = provider(|_, _| Err(io::Error::from(io::ErrorKind::TimedOut)));
assert_eq!(
collect(&vpn, &Default::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::ETIMEDOUT)
);
let vpn = provider(|_, _| panic!("Canceled provider must not run"));
assert_eq!(
collect(&vpn, &Default::default(), &|| Err(io::Error::from(
io::ErrorKind::Interrupted
)))
.unwrap_err()
.raw_os_error(),
Some(libc::EINTR)
);
}
#[test]
fn explicit_script_wins_and_uid_presence_is_preserved() {
let fixture = ScriptFixture::new("printf '<script/>'");
let script = fixture.script(None);
let raw = HipScriptRaw::from_script(&script);
assert_eq!(raw.uid_present, 0);
let vpn = provider(|_, _| panic!("Script must win"));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap(), "<script/>");
let script = fixture.script(Some(unsafe { libc::getuid() }));
assert_eq!(HipScriptRaw::from_script(&script).uid_present, 1);
assert_eq!(script.preview(&HipRequest::default(), &|| Ok(())).unwrap(), "<script/>");
}
#[test]
fn validator_refusal_prevents_execution_and_errors_propagate() {
let fixture = ScriptFixture::new("touch executed; printf '<script/>'");
let script = fixture
.script(None)
.with_validator(|_| Err(io::Error::from(io::ErrorKind::PermissionDenied)));
assert_eq!(
script
.preview(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EPERM)
);
assert!(!fixture.0.join("executed").exists());
let script = fixture.script(None).with_validator(|_| panic!("test validator panic"));
assert_eq!(
script
.preview(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
);
}
#[test]
fn child_environment_and_cwd_are_explicit_without_parent_mutation() {
let fixture = ScriptFixture::new("printf '%s:%s' \"$HIP_TEST_VALUE\" \"$PWD\"");
let cwd = fs::canonicalize(&fixture.0).unwrap().to_str().unwrap().to_owned();
let script = fixture
.script(None)
.with_environment(crate::HipScriptEnvironment {
variables: vec![("HIP_TEST_VALUE".into(), "child".into())],
cwd: cwd.clone(),
})
.unwrap();
assert_eq!(
script.preview(&HipRequest::default(), &|| Ok(())).unwrap(),
format!("child:{cwd}")
);
assert!(std::env::var_os("HIP_TEST_VALUE").is_none());
}
#[test]
fn script_empty_nul_and_nonzero_outputs_fail() {
for contents in ["true", "printf '\\000'", "printf '<script/>'; exit 1"] {
let fixture = ScriptFixture::new(contents);
assert_eq!(
fixture
.script(None)
.preview(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EINVAL)
);
}
}
#[test]
fn cancellation_and_deadline_kill_descendants_and_reap_child() {
for errno in [libc::EINTR, libc::ETIMEDOUT] {
let fixture = ScriptFixture::new("sleep 20 &\nwait\nprintf '<script/>'");
let start = Instant::now();
let check = || {
if start.elapsed() > Duration::from_millis(80) {
Err(io::Error::from_raw_os_error(errno))
} else {
Ok(())
}
};
assert_eq!(
fixture
.script(None)
.preview(&HipRequest::default(), &check)
.unwrap_err()
.raw_os_error(),
Some(errno)
);
assert!(start.elapsed() < Duration::from_secs(2));
}
}
}
+9 -3
View File
@@ -1,6 +1,10 @@
mod hip;
use crate::Vpn;
use hip::HipGenerateFn;
pub(crate) use hip::{HipControlRaw, HipScriptRaw, generate_hip_report, preview_hip_script, script_environment};
use log::{debug, info, trace, warn};
use std::ffi::{c_char, c_int, c_long, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)]
@@ -28,8 +32,8 @@ pub(crate) struct ConnectOptions {
pub key_password: *const c_char,
pub servercert: *const c_char,
pub csd_uid: u32,
pub csd_wrapper: *const c_char,
pub hip_script: HipScriptRaw,
pub generate_hip: Option<HipGenerateFn>,
pub reconnect_timeout: u32,
pub mtu: u32,
@@ -94,7 +98,9 @@ pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *cons
}
let bytes = unsafe { std::slice::from_raw_parts(report.cast::<u8>(), length) };
if let Ok(report) = std::str::from_utf8(bytes) {
vpn.on_hip_report_submitted(report);
if catch_unwind(AssertUnwindSafe(|| vpn.on_hip_report_submitted(report))).is_err() {
warn!("HIP submission observer failed");
}
}
}
+27 -5
View File
@@ -86,8 +86,8 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
INFO("VPNC_SCRIPT: %s", options->script);
INFO("SCRIPT_TUN: %d", options->script_tun);
INFO("CSD_USER: %d", options->csd_uid);
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
INFO("CSD_USER: %d", options->hip_script.uid);
INFO("CSD_WRAPPER: %s", options->hip_script.path);
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
INFO("MTU: %d", options->mtu);
INFO("DISABLE_IPV6: %d", options->disable_ipv6);
@@ -168,9 +168,14 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_xmlpost(vpninfo, 0);
}
if (options->csd_wrapper) {
openconnect_setup_csd(vpninfo, options->csd_uid, 1,
options->csd_wrapper);
openconnect_set_gp_hip_generator(vpninfo, options->user_data, options->generate_hip);
if (options->hip_script.path) {
result = openconnect_set_gp_hip_script(vpninfo, options->hip_script.path,
options->hip_script.uid_present, options->hip_script.uid,
options->hip_script.validation_data, options->hip_script.validate,
options->hip_script.environment, options->hip_script.cwd);
if (result)
goto cleanup;
}
if (options->mtu > 0) {
@@ -225,3 +230,20 @@ int vpn_write_cancel(int fd)
} while (written < 0 && errno == EINTR);
return written == 1 ? 0 : (written < 0 ? errno : EIO);
}
int vpn_collect_hip_report(const vpn_hip_script *script,
const struct openconnect_gp_hip_request *request,
const struct openconnect_gp_hip_control *control, openconnect_gp_hip_generate_fn generate, void *data,
char *output, size_t capacity, size_t *written)
{
struct openconnect_info *vpninfo = openconnect_vpninfo_new("HIP preview", NULL, NULL, NULL, print_progress, NULL);
int result;
if (!vpninfo)
return -ENOMEM;
openconnect_set_gp_hip_generator(vpninfo, data, generate);
result = openconnect_set_gp_hip_script(vpninfo, script->path, script->uid_present,
script->uid, script->validation_data, script->validate, script->environment, script->cwd);
if (!result) result = openconnect_collect_gp_hip_report(vpninfo, request, control, output, capacity, written);
openconnect_vpninfo_free(vpninfo);
return result;
}
+14 -2
View File
@@ -19,6 +19,16 @@ typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
typedef void (*vpn_hip_report_callback)(void *user_data, const char *report,
size_t length);
typedef struct vpn_hip_script {
const char *path;
uid_t uid;
int uid_present;
void *validation_data;
openconnect_gp_hip_validate_fn validate;
const char *const *environment;
const char *cwd;
} vpn_hip_script;
typedef struct vpn_options {
void *user_data;
vpn_hip_report_callback on_hip_report_submitted;
@@ -42,8 +52,8 @@ typedef struct vpn_options {
const char *key_password;
const char *servercert;
const uid_t csd_uid;
const char *csd_wrapper;
vpn_hip_script hip_script;
openconnect_gp_hip_generate_fn generate_hip;
const int reconnect_timeout;
const int mtu;
@@ -55,6 +65,8 @@ typedef struct vpn_options {
} vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *,
const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *);
extern int vpn_attach_command_pipe(void *user_data, int fd);
extern void vpn_detach_command_pipe(void *user_data);
+115
View File
@@ -0,0 +1,115 @@
use std::{ffi::CString, io, marker::PhantomData, rc::Rc, sync::Arc};
use crate::{ffi, vpn_utils::check_executable};
pub type HipGenerator = dyn Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync;
type HipValidator = dyn Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync;
#[derive(Default)]
pub enum HipSource {
#[default]
Disabled,
Generator(Arc<HipGenerator>),
Script(HipScript),
}
/// Current gateway and negotiated identity inputs for one report invocation.
#[derive(Clone, Default)]
pub struct HipRequest {
pub cookie: String,
pub client_ip: Option<String>,
pub client_ipv6: Option<String>,
pub md5: String,
pub client_version: String,
pub client_os: String,
pub os_version: String,
pub host_id: Option<String>,
pub local_hostname: Option<String>,
}
/// Borrowed cancellation and deadline control. It must stay on the invocation thread.
pub struct HipControl<'a> {
pub(crate) raw: &'a ffi::HipControlRaw,
pub(crate) _thread: PhantomData<Rc<()>>,
}
impl HipControl<'_> {
pub fn check(&self) -> io::Result<()> {
let result = unsafe { (self.raw.check)(self.raw.data) };
if result < 0 {
Err(io::Error::from_raw_os_error(-result))
} else {
Ok(())
}
}
}
pub struct HipScriptEnvironment {
pub variables: Vec<(String, String)>,
pub cwd: String,
}
pub struct HipScript {
pub(crate) path: CString,
pub(crate) user: Option<u32>,
pub(crate) validator: Option<Arc<HipValidator>>,
pub(crate) environment: Option<Vec<CString>>,
pub(crate) cwd: Option<CString>,
}
impl HipScript {
pub fn new(path: String, user: Option<u32>) -> io::Result<Self> {
if !std::fs::metadata(&path)?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"HIP executable is not a regular file",
));
}
check_executable(&path)?;
let path = c_string(path)?;
Ok(Self {
path,
user,
validator: None,
environment: None,
cwd: None,
})
}
pub fn with_validator(
mut self,
validator: impl Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync + 'static,
) -> Self {
self.validator = Some(Arc::new(validator));
self
}
/// A child-local replacement environment and working directory, never process-global changes.
pub fn with_environment(mut self, environment: HipScriptEnvironment) -> io::Result<Self> {
let variables = environment
.variables
.into_iter()
.map(|(key, value)| {
if key.is_empty() || key.contains('=') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid HIP environment key",
));
}
c_string(format!("{key}={value}"))
})
.collect::<io::Result<Vec<_>>>()?;
self.environment = Some(variables);
self.cwd = Some(c_string(environment.cwd)?);
Ok(self)
}
/// Collect using the same OpenConnect subprocess machinery as connected submissions.
pub fn preview(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::preview_hip_script(self, request, check)
}
}
fn c_string(value: String) -> io::Result<CString> {
CString::new(value).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP value contains NUL"))
}
+2
View File
@@ -1,6 +1,8 @@
mod ffi;
mod hip;
mod vpn;
mod vpn_utils;
pub use hip::*;
pub use vpn::*;
pub use vpn_utils::*;
+25 -48
View File
@@ -6,8 +6,8 @@ use std::{
use log::{info, warn};
use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
use crate::vpn_utils::{check_executable, find_vpnc_script};
use crate::{HipSource, ffi};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>;
type OnHipReportCallback = RwLock<Option<Arc<dyn Fn(&str) + Send + Sync>>>;
@@ -119,8 +119,7 @@ pub struct Vpn {
key_password: Option<CString>,
servercert: Option<CString>,
csd_uid: u32,
csd_wrapper: Option<CString>,
pub(crate) hip_source: HipSource,
reconnect_timeout: u32,
mtu: u32,
@@ -141,8 +140,14 @@ impl Vpn {
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
self.callback.write().unwrap().replace(Box::new(on_connected));
let options = self.build_connect_options();
let mut options = self.build_connect_options();
let environment = match &self.hip_source {
HipSource::Script(script) => ffi::script_environment(script),
_ => Vec::new(),
};
if !environment.is_empty() {
options.hip_script.environment = environment.as_ptr();
}
ffi::connect(&options)
}
@@ -205,8 +210,14 @@ impl Vpn {
key_password: Self::option_to_ptr(&self.key_password),
servercert: Self::option_to_ptr(&self.servercert),
csd_uid: self.csd_uid,
csd_wrapper: Self::option_to_ptr(&self.csd_wrapper),
hip_script: match &self.hip_source {
HipSource::Script(script) => ffi::HipScriptRaw::from_script(script),
_ => Default::default(),
},
generate_hip: match &self.hip_source {
HipSource::Generator(_) => Some(ffi::generate_hip_report),
_ => None,
},
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
@@ -263,9 +274,7 @@ pub struct VpnBuilder {
sslkey: Option<String>,
key_password: Option<String>,
hip: bool,
csd_uid: u32,
csd_wrapper: Option<String>,
hip_source: HipSource,
reconnect_timeout: u32,
mtu: u32,
@@ -297,9 +306,7 @@ impl VpnBuilder {
sslkey: None,
key_password: None,
hip: false,
csd_uid: 0,
csd_wrapper: None,
hip_source: HipSource::Disabled,
reconnect_timeout: 300,
mtu: 0,
@@ -377,18 +384,8 @@ impl VpnBuilder {
self
}
pub fn hip(mut self, hip: bool) -> Self {
self.hip = hip;
self
}
pub fn csd_uid(mut self, csd_uid: u32) -> Self {
self.csd_uid = csd_uid;
self
}
pub fn csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
self.csd_wrapper = csd_wrapper.into();
pub fn hip_source(mut self, hip_source: HipSource) -> Self {
self.hip_source = hip_source;
self
}
@@ -435,23 +432,6 @@ impl VpnBuilder {
}
}
fn determine_csd_wrapper(&self) -> Result<Option<&str>, VpnError> {
if !self.hip {
return Ok(None);
}
match &self.csd_wrapper {
Some(csd_wrapper) if !csd_wrapper.is_empty() => {
check_executable(csd_wrapper).map_err(|e| VpnError::new(e.to_string()))?;
Ok(Some(csd_wrapper))
}
_ => {
let s = find_csd_wrapper().ok_or_else(|| VpnError::new(String::from("Failed to find csd wrapper")))?;
Ok(Some(s))
}
}
}
pub fn build(self) -> Result<Vpn, VpnError> {
let script = self.determine_script()?.to_owned();
let script = if self.script_is_path {
@@ -459,7 +439,6 @@ impl VpnBuilder {
} else {
script
};
let csd_wrapper = self.determine_csd_wrapper()?.map(|s| s.to_owned());
let user_agent = self.user_agent.unwrap_or_default();
let os = self.os.unwrap_or("linux".to_string());
@@ -485,8 +464,7 @@ impl VpnBuilder {
key_password: self.key_password.as_deref().map(Self::to_cstring),
servercert: None,
csd_uid: self.csd_uid,
csd_wrapper: csd_wrapper.as_deref().map(Self::to_cstring),
hip_source: self.hip_source,
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
@@ -611,8 +589,7 @@ mod tests {
sslkey: None,
key_password: None,
servercert: None,
csd_uid: 0,
csd_wrapper: None,
hip_source: HipSource::Disabled,
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
-19
View File
@@ -19,21 +19,6 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/local/etc/vpnc/vpnc-script",
];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/hipreport.sh",
"/usr/libexec/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
#[cfg(target_arch = "aarch64")]
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
];
fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
for location in locations.iter() {
let path = Path::new(location);
@@ -49,10 +34,6 @@ pub fn find_vpnc_script() -> Option<&'static str> {
find_executable(VPNC_SCRIPT_LOCATIONS)
}
pub fn find_csd_wrapper() -> Option<&'static str> {
find_executable(CSD_WRAPPER_LOCATIONS)
}
/// If file exists, check if it is executable
pub fn check_executable(file: &str) -> Result<(), io::Error> {
let path = Path::new(file);
+78
View File
@@ -0,0 +1,78 @@
"""Local TLS GlobalProtect fixture accepting HIP and raw SSL tunnel setup."""
import socket
import ssl
import sys
import threading
from urllib.parse import parse_qs
cert, key, records = sys.argv[1:]
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert, key)
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen()
state = {"configs": 0, "checks": 0, "reports": 0}
lock = threading.Lock()
def serve(connection):
try:
with context.wrap_socket(connection, server_side=True) as stream:
buffer = b""
while True:
while b"\r\n\r\n" not in buffer:
data = stream.recv(4096)
if not data:
return
buffer += data
headers, buffer = buffer.split(b"\r\n\r\n", 1)
method, path, _ = headers.split(b"\r\n", 1)[0].decode().split()
if method == "GET" and path.startswith("/ssl-tunnel-connect.sslvpn?"):
stream.sendall(b"START_TUNNEL")
while stream.recv(4096):
pass
return
length = 0
for header in headers.split(b"\r\n")[1:]:
name, value = header.split(b":", 1)
if name.lower() == b"content-length":
length = int(value)
while len(buffer) < length:
buffer += stream.recv(4096)
body, buffer = buffer[:length], buffer[length:]
form = parse_qs(body.decode())
status = "200 OK"
with lock:
if path == "/ssl-vpn/getconfig.esp":
state["configs"] += 1
ip = "10.0.0.1"
response = f"<response><ip-address>{ip}</ip-address><gw-address>127.0.0.1</gw-address><ssl-tunnel-url>/ssl-tunnel-connect.sslvpn</ssl-tunnel-url></response>"
elif path == "/ssl-vpn/hipreportcheck.esp":
state["checks"] += 1
needed = "no" if state["checks"] == 4 else "yes"
response = f"<response><hip-report-needed>{needed}</hip-report-needed></response>"
elif path == "/ssl-vpn/hipreport.esp":
state["reports"] += 1
seq = state["reports"]
expected_ip = "10.0.0.1"
assert form.get("authcookie") == ["test" if seq < 3 else "refreshed"]
expected = f'<hip seq="{seq}" ip="{expected_ip}"/>'
assert form.get("report") == [expected], form
assert form.get("client-ip") == [expected_ip], form
with open(records, "a", encoding="utf-8") as output:
output.write(expected + "\n")
if seq == 4:
status = "403 Forbidden"
response = "<response/>"
else:
raise AssertionError(path)
payload = response.encode()
stream.sendall(f"HTTP/1.1 {status}\r\nContent-Length: {len(payload)}\r\nContent-Type: text/xml\r\nConnection: keep-alive\r\n\r\n".encode() + payload)
except (ConnectionError, ssl.SSLError):
pass
print(listener.getsockname()[1], flush=True)
while True:
connection, _ = listener.accept()
threading.Thread(target=serve, args=(connection,), daemon=True).start()
+74
View File
@@ -0,0 +1,74 @@
/* Integration harness: exercise setup and the actual connected periodic branch. */
#include <config.h>
#include "openconnect-internal.h"
#include <assert.h>
#include <stdarg.h>
struct state { int generated, accepted; };
static int accept_cert(void *data, const char *reason) { return 0; }
static void progress(void *data, int level, const char *format, ...) {
if (level > PRG_INFO) return;
va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args);
}
static int generate(void *data, const struct openconnect_gp_hip_request *request,
const struct openconnect_gp_hip_control *control, char *output, size_t capacity, size_t *written)
{
struct state *state = data;
int length;
assert(!control->check(control->data));
assert(!strcmp(request->client_os, "Linux"));
assert(!strcmp(request->client_version, "6.3.3"));
assert(!strcmp(request->host_id, "test-host"));
assert(request->cookie && request->md5 && strlen(request->md5) == 32);
if (state->generated >= 2) assert(strstr(request->cookie, "authcookie=refreshed"));
state->generated++;
length = snprintf(output, capacity, "<hip seq=\"%d\" ip=\"%s\"/>", state->generated, request->client_ip);
assert(length > 0 && length < capacity);
*written = length;
return 0;
}
static void submitted(void *data, const char *report, size_t length) {
struct state *state = data;
assert(report && length > 0);
state->accepted++;
}
static int periodic(struct openconnect_info *vpninfo) {
int timeout = 1000;
vpninfo->trojan_interval = 1;
vpninfo->last_trojan = time(NULL) - 2;
return gpst_mainloop(vpninfo, &timeout, 0);
}
int main(int argc, char **argv) {
struct state state = {0};
struct openconnect_info *vpninfo;
assert(argc == 2);
openconnect_init_ssl();
vpninfo = openconnect_vpninfo_new("HIP protocol test", accept_cert, NULL, NULL, progress, &state);
assert(vpninfo);
assert(!openconnect_set_protocol(vpninfo, "gp"));
assert(!openconnect_set_reported_os(vpninfo, "linux"));
assert(!openconnect_parse_url(vpninfo, argv[1]));
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=test&portal=test&domain=test&computer=test"));
assert(!openconnect_set_gp_app_version(vpninfo, "6.3.3"));
assert(!openconnect_set_gp_host_id(vpninfo, "test-host"));
openconnect_disable_dtls(vpninfo);
openconnect_set_gp_hip_generator(vpninfo, &state, generate);
openconnect_set_gp_hip_report_callback(vpninfo, &state, submitted);
assert(!openconnect_make_cstp_connection(vpninfo));
assert(vpninfo->ssl_fd >= 0 && state.generated == 1 && state.accepted == 1);
assert(!periodic(vpninfo));
assert(state.generated == 2 && state.accepted == 2);
/* A real reconnect re-fetches configuration and uses refreshed session inputs. */
openconnect_close_https(vpninfo, 0);
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=refreshed&portal=test&domain=test&computer=test"));
assert(!openconnect_make_cstp_connection(vpninfo));
assert(state.generated == 3 && state.accepted == 3);
/* Fourth gateway check says no report needed. */
assert(!periodic(vpninfo));
assert(state.generated == 3 && state.accepted == 3);
/* Fifth submission is rejected; observer must not see it. */
assert(periodic(vpninfo));
assert(state.generated == 4 && state.accepted == 3);
openconnect_vpninfo_free(vpninfo);
return 0;
}
+139
View File
@@ -0,0 +1,139 @@
use std::{
fs,
io::{BufRead, BufReader},
os::unix::process::CommandExt,
path::PathBuf,
process::{Child, Command, Stdio},
sync::mpsc,
time::{Duration, Instant},
};
struct ChildGuard(Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
unsafe {
libc::kill(-(self.0.id() as i32), libc::SIGKILL);
}
let _ = self.0.kill();
let _ = self.0.wait();
}
}
struct TestDirectory(PathBuf);
impl Drop for TestDirectory {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn c_protocol_submits_initial_periodic_and_reconnect_reports() {
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD"));
let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE"));
let directory = TestDirectory(std::env::temp_dir().join(format!("gp-hip-protocol-{}", std::process::id())));
fs::create_dir(&directory.0).unwrap();
let executable = directory.0.join("hip-protocol");
let flags = Command::new("pkg-config")
.args([
"--cflags",
"libxml-2.0",
if cfg!(target_os = "macos") { "openssl" } else { "gnutls" },
])
.output()
.unwrap();
assert!(flags.status.success());
let compile_command = Command::new(build.join("libtool"))
.args(["--mode=link", "cc"])
.arg(manifest.join("tests/hip_protocol.c"))
.arg("-I")
.arg(&build)
.arg("-I")
.arg(&source)
.arg("-I")
.arg(source.join("json"))
.args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
.arg(build.join("libopenconnect.la"))
.arg("-o")
.arg(&executable)
.process_group(0)
.stdout(Stdio::from(fs::File::create(directory.0.join("compile.log")).unwrap()))
.stderr(Stdio::from(
fs::File::options()
.append(true)
.open(directory.0.join("compile.log"))
.unwrap(),
))
.spawn()
.unwrap();
let mut compile_command = ChildGuard(compile_command);
wait_bounded(
&mut compile_command,
Duration::from_secs(30),
&directory.0.join("compile.log"),
);
let records = directory.0.join("submissions");
let certificates = manifest.join("deps/openconnect/tests/certs");
let server = Command::new("python3")
.arg(manifest.join("tests/hip_gateway.py"))
.arg(certificates.join("server-cert.pem"))
.arg(certificates.join("server-key.pem"))
.arg(&records)
.process_group(0)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.unwrap();
let mut server = ChildGuard(server);
let stdout = server.0.stdout.take().unwrap();
let (tx, rx) = mpsc::channel();
let reader = std::thread::spawn(move || {
let mut port = String::new();
let result = BufReader::new(stdout).read_line(&mut port).map(|_| port);
let _ = tx.send(result);
});
let port = match rx.recv_timeout(Duration::from_secs(3)) {
Ok(result) => result.expect("Fake gateway startup failed"),
Err(error) => {
let _ = server.0.kill();
let _ = server.0.wait();
let _ = reader.join();
panic!("Fake gateway startup timed out: {error}");
}
};
reader.join().unwrap();
let port: u16 = port.trim().parse().expect("Fake gateway did not start");
let log = fs::File::create(directory.0.join("client.log")).unwrap();
let mut client = ChildGuard(
Command::new(build.join("libtool"))
.args(["--mode=execute"])
.arg(executable)
.arg(format!("https://127.0.0.1:{port}"))
.process_group(0)
.stdout(log.try_clone().unwrap())
.stderr(log)
.spawn()
.unwrap(),
);
wait_bounded(&mut client, Duration::from_secs(15), &directory.0.join("client.log"));
let reports = fs::read_to_string(records).unwrap();
assert_eq!(
reports,
"<hip seq=\"1\" ip=\"10.0.0.1\"/>\n<hip seq=\"2\" ip=\"10.0.0.1\"/>\n<hip seq=\"3\" ip=\"10.0.0.1\"/>\n<hip seq=\"4\" ip=\"10.0.0.1\"/>\n"
);
}
fn wait_bounded(child: &mut ChildGuard, timeout: Duration, log: &std::path::Path) {
let deadline = Instant::now() + timeout;
loop {
if let Some(status) = child.0.try_wait().unwrap() {
assert!(status.success(), "{}", fs::read_to_string(log).unwrap());
return;
}
assert!(
Instant::now() < deadline,
"HIP protocol test process timed out: {}",
fs::read_to_string(log).unwrap()
);
std::thread::sleep(Duration::from_millis(20));
}
}
+24 -29
View File
@@ -1,5 +1,6 @@
{
inputs = {
self.submodules = true;
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
flake-utils.url = "github:numtide/flake-utils";
naersk = {
@@ -30,6 +31,7 @@
pname = "globalprotect-openconnect";
version = cargoToml.workspace.package.version;
releaseTag = "v2.6.5";
releaseVersion = "2.6.5";
toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
@@ -45,14 +47,10 @@
bsdtar --extract --file ${archive} --directory "$out" --strip-components 1
'';
sourceArchive = pkgs.fetchurl {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${releaseTag}/globalprotect-openconnect-${version}.tar.gz";
hash = "sha256-VFWbF2BfJ9CtXkjQjkgmBGCZnYgB5ZLctqcqUKuhswg=";
};
src = unpackReleaseAsset {
name = "globalprotect-openconnect-${version}-source";
archive = sourceArchive;
src = lib.cleanSourceWith {
src = lib.cleanSource ./.;
filter = path: type:
!(builtins.elem (builtins.baseNameOf path) [ "target" ".build" "node_modules" ]);
};
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
@@ -68,7 +66,7 @@
};
gpgui = unpackReleaseAsset {
name = "gpgui-${version}-${cpu}";
name = "gpgui-${releaseVersion}-${cpu}";
archive = gpguiArchive;
};
@@ -78,12 +76,12 @@
};
binaryArchive = pkgs.fetchurl {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${releaseTag}/globalprotect-openconnect_${version}_${cpu}.bin.tar.xz";
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${releaseTag}/globalprotect-openconnect_${releaseVersion}_${cpu}.bin.tar.xz";
hash = binaryHashes.${cpu};
};
binaryPackage = unpackReleaseAsset {
name = "globalprotect-openconnect-${version}-${cpu}-binary";
name = "globalprotect-openconnect-${releaseVersion}-${cpu}-binary";
archive = binaryArchive;
};
@@ -121,11 +119,7 @@
libayatana-appindicator
];
rewriteSourceInstallPaths = ''
substituteInPlace $out/libexec/gpclient/hipreport.sh \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
''
+ lib.optionalString pkgs.stdenv.isLinux ''
rewriteSourceInstallPaths = lib.optionalString pkgs.stdenv.isLinux ''
substituteInPlace $out/share/applications/gpgui.desktop \
--replace-fail /usr/bin/gpclient $out/bin/gpclient
@@ -180,7 +174,12 @@
'';
fromSource = naersk'.buildPackage {
inherit pname version src;
inherit pname version;
src = assert lib.assertMsg
(builtins.pathExists (src + "/crates/openconnect/deps/openconnect/configure.ac")
&& builtins.pathExists (src + "/crates/openconnect/deps/libxml2/configure.ac"))
"Source builds require initialized Git submodules; use a git+ flake URL with submodules=1.";
src;
name = "globalprotect-openconnect";
# Must be set to true to avoid issues with the Tauri build process
@@ -222,8 +221,7 @@
{
postPatch = ''
substituteInPlace crates/openconnect/src/vpn_utils.rs \
--replace-fail /usr/libexec/gpclient/vpnc-script $out/libexec/gpclient/vpnc-script \
--replace-fail /usr/libexec/gpclient/hipreport.sh $out/libexec/gpclient/hipreport.sh
--replace-fail /usr/libexec/gpclient/vpnc-script $out/libexec/gpclient/vpnc-script
substituteInPlace crates/common/src/constants.rs \
--replace-fail /usr/bin/gpclient $out/bin/gpclient \
@@ -236,12 +234,8 @@
--replace-fail /usr/bin/gpgui-helper $out/bin/gpgui-helper \
--replace-fail /usr/bin/gpgui $out/bin/gpgui
if [ -f apps/gpservice/src/hip_source.rs ]; then
substituteInPlace crates/common/src/constants.rs \
--replace-fail /usr/libexec/gpclient/gp-hip-script-installer $out/libexec/gpclient/gp-hip-script-installer
substituteInPlace apps/gpservice/src/hip_source.rs \
--replace-fail /usr/libexec/gpclient/gp-hip-runner $out/libexec/gpclient/gp-hip-runner
fi
substituteInPlace crates/common/src/constants.rs \
--replace-fail /usr/libexec/gpclient/gp-hip-script-installer $out/libexec/gpclient/gp-hip-script-installer
'';
};
@@ -249,8 +243,7 @@
cp -r packaging/files/usr/libexec $out/libexec
''
+ lib.optionalString pkgs.stdenv.isLinux ''
if [ -f $out/bin/gp-hip-runner ]; then
install -Dm755 $out/bin/gp-hip-runner $out/libexec/gpclient/gp-hip-runner
if [ -f $out/bin/gp-hip-script-installer ]; then
install -Dm755 $out/bin/gp-hip-script-installer $out/libexec/gpclient/gp-hip-script-installer
fi
@@ -270,7 +263,8 @@
};
prebuiltFiles = pkgs.stdenv.mkDerivation {
inherit pname version;
inherit pname;
version = releaseVersion;
src = binaryPackage;
dontBuild = true;
@@ -381,7 +375,8 @@
};
prebuilt = pkgs.stdenv.mkDerivation {
inherit pname version;
inherit pname;
version = releaseVersion;
dontUnpack = true;
-4
View File
@@ -3,7 +3,6 @@ install:
install -Dm755 artifacts/usr/bin/gpclient $(DESTDIR)/usr/bin/gpclient
install -Dm755 artifacts/usr/bin/gpservice $(DESTDIR)/usr/bin/gpservice
install -Dm755 artifacts/usr/libexec/gpclient/gp-hip-runner $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner
install -Dm755 artifacts/usr/libexec/gpclient/gp-hip-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
install -Dm755 artifacts/usr/bin/gpauth $(DESTDIR)/usr/bin/gpauth
install -Dm755 artifacts/usr/bin/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper
@@ -13,7 +12,6 @@ install:
fi
install -Dm755 artifacts/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
install -Dm755 artifacts/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
install -Dm755 artifacts/usr/libexec/gpclient/gp-vpnc-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
# Install the disconnect hooks
@@ -39,14 +37,12 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpclient
rm -f $(DESTDIR)/usr/bin/gpservice
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer
rm -f $(DESTDIR)/usr/bin/gpauth
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
rm -f $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
+1 -2
View File
@@ -38,8 +38,7 @@ RUN RUSTFLAGS="-C target-feature=-crt-static" \
RUN install -Dm755 target/release/gpclient /out/usr/bin/gpclient \
&& install -Dm755 target/release/gpauth /out/usr/bin/gpauth \
&& install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script /out/usr/libexec/gpclient/vpnc-script \
&& install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh /out/usr/libexec/gpclient/hipreport.sh
&& install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script /out/usr/libexec/gpclient/vpnc-script
FROM alpine:${ALPINE_VERSION}
@@ -1,21 +0,0 @@
#!/bin/sh
# Wrapper for gpclient hip
LINUX_GPCLIENT_BIN="/usr/bin/gpclient"
ARM64_HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient"
LOCAL_GPCLIENT_BIN="/usr/local/bin/gpclient"
GPCLIENT_BIN=""
if [ -x "$LINUX_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$LINUX_GPCLIENT_BIN"
elif [ -x "$ARM64_HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$ARM64_HOMEBREW_GPCLIENT_BIN"
elif [ -x "$LOCAL_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$LOCAL_GPCLIENT_BIN"
else
echo "Error: gpclient binary not found." >&2
exit 1
fi
exec "$GPCLIENT_BIN" hip "$@"
@@ -72,8 +72,6 @@ make build
%defattr(-,root,root)
%{_bindir}/*
%{_libexecdir}/gpclient/vpnc-script
%{_libexecdir}/gpclient/hipreport.sh
%{_libexecdir}/gpclient/gp-hip-runner
%{_libexecdir}/gpclient/gp-hip-script-installer
%{_libexecdir}/gpclient/gp-vpnc-script-installer
%{_datadir}/applications/gpgui.desktop
+5 -5
View File
@@ -11,7 +11,7 @@ FLAKE_FILE="$PROJECT_DIR/flake.nix"
usage() {
echo "Usage: $0 [version] [release-tag]"
echo
echo "Updates flake.nix fetchurl hashes from the published GitHub release assets."
echo "Updates flake.nix prebuilt package hashes from the published GitHub release assets."
echo "When version is omitted, the workspace package version from Cargo.toml is used."
echo "When release-tag is omitted, v<version> is used. Use snapshot to test snapshot assets."
}
@@ -79,32 +79,32 @@ release_url() {
echo "https://github.com/$REPO/releases/download/$release_tag/$asset"
}
source_hash="$(prefetch_hash "$(release_url "globalprotect-openconnect-$version.tar.gz")")"
gpgui_x86_64_hash="$(prefetch_hash "$(release_url "gpgui_x86_64.bin.tar.xz")")"
gpgui_aarch64_hash="$(prefetch_hash "$(release_url "gpgui_aarch64.bin.tar.xz")")"
binary_x86_64_hash="$(prefetch_hash "$(release_url "globalprotect-openconnect_${version}_x86_64.bin.tar.xz")")"
binary_aarch64_hash="$(prefetch_hash "$(release_url "globalprotect-openconnect_${version}_aarch64.bin.tar.xz")")"
SOURCE_HASH="$source_hash" \
GPGUI_X86_64_HASH="$gpgui_x86_64_hash" \
GPGUI_AARCH64_HASH="$gpgui_aarch64_hash" \
BINARY_X86_64_HASH="$binary_x86_64_hash" \
BINARY_AARCH64_HASH="$binary_aarch64_hash" \
RELEASE_TAG="$release_tag" \
RELEASE_VERSION="$version" \
perl -0pi -e '
s|(releaseTag = ")[^"]+(";)|$1 . $ENV{"RELEASE_TAG"} . $2|e;
s|(url = "https://github\.com/yuezk/GlobalProtect-openconnect/releases/download/\$\{releaseTag\}/globalprotect-openconnect-\$\{version\}\.tar\.gz";\n\s*hash = ")[^"]+(";)|$1 . $ENV{"SOURCE_HASH"} . $2|e;
s|(releaseVersion = ")[^"]+(";)|$1 . $ENV{"RELEASE_VERSION"} . $2|e;
s|(gpguiHashes = \{\n\s*x86_64 = ")[^"]+(";)|$1 . $ENV{"GPGUI_X86_64_HASH"} . $2|e;
s|(gpguiHashes = \{\n\s*x86_64 = "[^"]+";\n\s*aarch64 = ")[^"]+(";)|$1 . $ENV{"GPGUI_AARCH64_HASH"} . $2|e;
s|(binaryHashes = \{\n\s*x86_64 = ")[^"]+(";)|$1 . $ENV{"BINARY_X86_64_HASH"} . $2|e;
s|(binaryHashes = \{\n\s*x86_64 = "[^"]+";\n\s*aarch64 = ")[^"]+(";)|$1 . $ENV{"BINARY_AARCH64_HASH"} . $2|e;
' "$FLAKE_FILE"
grep -F "$source_hash" "$FLAKE_FILE" > /dev/null
grep -F "$gpgui_x86_64_hash" "$FLAKE_FILE" > /dev/null
grep -F "$gpgui_aarch64_hash" "$FLAKE_FILE" > /dev/null
grep -F "$binary_x86_64_hash" "$FLAKE_FILE" > /dev/null
grep -F "$binary_aarch64_hash" "$FLAKE_FILE" > /dev/null
grep -F "releaseTag = \"$release_tag\";" "$FLAKE_FILE" > /dev/null
grep -F "releaseVersion = \"$version\";" "$FLAKE_FILE" > /dev/null
echo "Updated flake.nix hashes for v$version assets from $release_tag"