From b750cfbf16ce21905b6200b9ab360d8785b3ff93 Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Fri, 2 Oct 2026 01:38:20 +0800 Subject: [PATCH] feat: generate HIP reports through OpenConnect callbacks --- .github/workflows/build.yaml | 44 +- .github/workflows/nix.yaml | 36 ++ Cargo.lock | 3 +- Makefile | 6 - README.md | 21 + apps/gpclient/src/connect/args.rs | 7 +- apps/gpclient/src/connect/gateway.rs | 63 ++- apps/gpclient/src/hip.rs | 13 +- apps/gpservice/src/bin/gp-hip-runner.rs | 137 ----- apps/gpservice/src/hip_approval.rs | 75 ++- apps/gpservice/src/hip_preview.rs | 528 ++++++++++-------- apps/gpservice/src/hip_runner_state.rs | 59 -- apps/gpservice/src/hip_source.rs | 418 +++++++------- apps/gpservice/src/lib.rs | 1 - apps/gpservice/src/vpn_task.rs | 57 +- apps/gpservice/src/ws_connection.rs | 48 +- apps/gpservice/src/ws_server.rs | 7 + crates/gpapi/Cargo.toml | 1 + crates/gpapi/src/os_profile/host_identity.rs | 188 +++++-- crates/gpapi/src/os_profile/mod.rs | 135 ++++- crates/gpapi/src/process/collection.rs | 296 ++++++++++ crates/gpapi/src/process/mod.rs | 2 + crates/gphip/Cargo.toml | 1 - crates/gphip/src/lib.rs | 336 ++++++----- crates/gphip/src/sentinel_macos.rs | 54 +- crates/gphip/src/sentinel_unix.rs | 58 +- crates/openconnect/Cargo.toml | 1 + crates/openconnect/build.rs | 8 + crates/openconnect/deps/openconnect | 2 +- crates/openconnect/src/ffi/hip.rs | 437 +++++++++++++++ crates/openconnect/src/ffi/mod.rs | 12 +- crates/openconnect/src/ffi/vpn.c | 32 +- crates/openconnect/src/ffi/vpn.h | 16 +- crates/openconnect/src/hip.rs | 115 ++++ crates/openconnect/src/lib.rs | 2 + crates/openconnect/src/vpn.rs | 73 +-- crates/openconnect/src/vpn_utils.rs | 19 - crates/openconnect/tests/hip_gateway.py | 78 +++ crates/openconnect/tests/hip_protocol.c | 74 +++ crates/openconnect/tests/hip_protocol.rs | 139 +++++ flake.nix | 53 +- packaging/binary/Makefile.in | 4 - packaging/docker/alpine/Dockerfile | 3 +- .../files/usr/libexec/gpclient/hipreport.sh | 21 - .../rpm/globalprotect-openconnect.spec.in | 2 - scripts/update-flake-hashes.sh | 10 +- 46 files changed, 2511 insertions(+), 1184 deletions(-) delete mode 100644 apps/gpservice/src/bin/gp-hip-runner.rs delete mode 100644 apps/gpservice/src/hip_runner_state.rs create mode 100644 crates/gpapi/src/process/collection.rs create mode 100644 crates/openconnect/src/ffi/hip.rs create mode 100644 crates/openconnect/src/hip.rs create mode 100644 crates/openconnect/tests/hip_gateway.py create mode 100644 crates/openconnect/tests/hip_protocol.c create mode 100644 crates/openconnect/tests/hip_protocol.rs delete mode 100755 packaging/files/usr/libexec/gpclient/hipreport.sh diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index e92100b..3981b2f 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -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 diff --git a/.github/workflows/nix.yaml b/.github/workflows/nix.yaml index 06d28b6..d2ab38a 100644 --- a/.github/workflows/nix.yaml +++ b/.github/workflows/nix.yaml @@ -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: diff --git a/Cargo.lock b/Cargo.lock index b078751..e4bec29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", ] diff --git a/Makefile b/Makefile index abec552..155dd50 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/README.md b/README.md index 784b66b..a66667a 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,18 @@ Options: > **Tip:** Use `gpclient help ` 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 --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: diff --git a/apps/gpclient/src/connect/args.rs b/apps/gpclient/src/connect/args.rs index 0e7beb5..ae2b785 100644 --- a/apps/gpclient/src/connect/args.rs +++ b/apps/gpclient/src/connect/args.rs @@ -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, - #[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, #[arg( diff --git a/apps/gpclient/src/connect/gateway.rs b/apps/gpclient/src/connect/gateway.rs index f1d5857..0e23d95 100644 --- a/apps/gpclient/src/connect/gateway.rs +++ b/apps/gpclient/src/connect/gateway.rs @@ -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) { - 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 { + 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::().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 { @@ -495,12 +509,11 @@ fn write_pid_file(lock_file: &Path) { } } -fn get_uid(user: &Option) -> anyhow::Result { - 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) -> anyhow::Result> { + 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] diff --git a/apps/gpclient/src/hip.rs b/apps/gpclient/src/hip.rs index f978638..b733351 100644 --- a/apps/gpclient/src/hip.rs +++ b/apps/gpclient/src/hip.rs @@ -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(()) } } diff --git a/apps/gpservice/src/bin/gp-hip-runner.rs b/apps/gpservice/src/bin/gp-hip-runner.rs deleted file mode 100644 index 77cec1e..0000000 --- a/apps/gpservice/src/bin/gp-hip-runner.rs +++ /dev/null @@ -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, - #[arg(long)] - host_id: Option, - #[arg(long)] - cookie: Option, - #[arg(long)] - client_ip: Option, - #[arg(long)] - client_ipv6: Option, - #[arg(long)] - md5: Option, - #[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(()) -} diff --git a/apps/gpservice/src/hip_approval.rs b/apps/gpservice/src/hip_approval.rs index 3173a6e..1da7461 100644 --- a/apps/gpservice/src/hip_approval.rs +++ b/apps/gpservice/src/hip_approval.rs @@ -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 anyhow::Result { + 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 { + 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 { + 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 { + 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::*; diff --git a/apps/gpservice/src/hip_preview.rs b/apps/gpservice/src/hip_preview.rs index 850ebe1..a4b2a71 100644 --- a/apps/gpservice/src/hip_preview.rs +++ b/apps/gpservice/src/hip_preview.rs @@ -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>, + pub desktop_uid: Option, + pub identity: HostIdentity, + pub registry: Arc, + pub connection: ConnectionControl, +} + +pub(crate) struct HipPreviews { + tasks: Mutex>, + slots: Arc, + 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(®istry, 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>, desktop_uid: Option, + identity: HostIdentity, + cancellation: CancellationToken, ) -> anyhow::Result { 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); - -impl ProcessGroupGuard { - fn new(pid: Option) -> 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' '' -"#, - ); - let xml = generate(request(&path), None, Some(uid)).await.unwrap(); - assert!(xml.starts_with("")); - - script(&path, "printf '%s' ''"); - 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::().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::().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(); } } diff --git a/apps/gpservice/src/hip_runner_state.rs b/apps/gpservice/src/hip_runner_state.rs deleted file mode 100644 index 4300a7e..0000000 --- a/apps/gpservice/src/hip_runner_state.rs +++ /dev/null @@ -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()); - } - } -} diff --git a/apps/gpservice/src/hip_source.rs b/apps/gpservice/src/hip_source.rs index 3ad351c..f8d19c9 100644 --- a/apps/gpservice/src/hip_source.rs +++ b/apps/gpservice/src/hip_source.rs @@ -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, - _state_dir: Option, - 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) -> 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, brokered_macos: bool, edited_report: Option>, + profile: Option, ) -> anyhow::Result { - 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>) -> anyhow::Result { - 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 { - 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 { - #[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 { + 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 { - 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 { + 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, + os_version: Option, + host_id: Option, + hostname: Option, + control: &dyn gpapi::process::collection::CollectionControl, +) -> io::Result { + 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::() { + 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()); } } diff --git a/apps/gpservice/src/lib.rs b/apps/gpservice/src/lib.rs index e04c42c..aad8b6c 100644 --- a/apps/gpservice/src/lib.rs +++ b/apps/gpservice/src/lib.rs @@ -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; diff --git a/apps/gpservice/src/vpn_task.rs b/apps/gpservice/src/vpn_task.rs index 30c28f8..ed7d195 100644 --- a/apps/gpservice/src/vpn_task.rs +++ b/apps/gpservice/src/vpn_task.rs @@ -242,7 +242,7 @@ struct ActiveAttempt { info: ConnectInfo, allow_extend_session: bool, _identity_files: Vec, - _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 || { diff --git a/apps/gpservice/src/ws_connection.rs b/apps/gpservice/src/ws_connection.rs index bb2e702..ab47ea2 100644 --- a/apps/gpservice/src/ws_connection.rs +++ b/apps/gpservice/src/ws_connection.rs @@ -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(()); } diff --git a/apps/gpservice/src/ws_server.rs b/apps/gpservice/src/ws_server.rs index 9055264..474528f 100644 --- a/apps/gpservice/src/ws_server.rs +++ b/apps/gpservice/src/ws_server.rs @@ -39,6 +39,7 @@ pub(crate) struct WsServerContext { dispatcher: Arc, state: Mutex, handshake_slots: Arc, + 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 { &self.registry } @@ -243,6 +249,7 @@ impl WsServer { info!("WS server cancelled"); } } + self.ctx.hip_previews.shutdown().await; let _ = shutdown_tx.send(()).await; } diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 20521c7..e5664c7 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -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 diff --git a/crates/gpapi/src/os_profile/host_identity.rs b/crates/gpapi/src/os_profile/host_identity.rs index 1f4fcd9..5bdd1e3 100644 --- a/crates/gpapi/src/os_profile/host_identity.rs +++ b/crates/gpapi/src/os_profile/host_identity.rs @@ -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::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 { + 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 { + 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 { - ["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> { + 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> { + 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 { - 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 { - 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> { + 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 { 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 { - 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> { + 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 { - 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> { + 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 { + 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 { + 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()); } diff --git a/crates/gpapi/src/os_profile/mod.rs b/crates/gpapi/src/os_profile/mod.rs index c8aa942..0e4b414 100644 --- a/crates/gpapi/src/os_profile/mod.rs +++ b/crates/gpapi/src/os_profile/mod.rs @@ -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, + os_version_override: Option, computer_name_override: Option, host_id_override: Option, host_identity: Option, @@ -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) -> 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 { + 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 { + 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()); diff --git a/crates/gpapi/src/process/collection.rs b/crates/gpapi/src/process/collection.rs new file mode 100644 index 0000000..d50acce --- /dev/null +++ b/crates/gpapi/src/process/collection.rs @@ -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 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 { + 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> { + 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> { + 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 { + 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 { + 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); + } +} diff --git a/crates/gpapi/src/process/mod.rs b/crates/gpapi/src/process/mod.rs index e45e056..6f75661 100644 --- a/crates/gpapi/src/process/mod.rs +++ b/crates/gpapi/src/process/mod.rs @@ -8,3 +8,5 @@ pub mod auth_launcher; pub mod gui_launcher; pub mod service_launcher; pub mod users; + +pub mod collection; diff --git a/crates/gphip/Cargo.toml b/crates/gphip/Cargo.toml index e83c07a..eeb2538 100644 --- a/crates/gphip/Cargo.toml +++ b/crates/gphip/Cargo.toml @@ -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 diff --git a/crates/gphip/src/lib.rs b/crates/gphip/src/lib.rs index c6be5d8..8fbb2b0 100644 --- a/crates/gphip/src/lib.rs +++ b/crates/gphip/src/lib.rs @@ -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 { + 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 { + 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, ¤t, 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(¤t)?; - 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 { - let cookie_params: HashMap = 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 { + 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 { + serde_urlencoded::from_str(input.context.cookie()).unwrap_or_default() +} + +fn report_user_name<'a>(input: &ReportInput, cookie_params: &'a HashMap) -> &'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 { - match self.profile.client_os() { - ClientOs::Linux => detect_microsoft_defender_blocking(), - ClientOs::Mac | ClientOs::Windows => None, + fn collect(&self, control: &dyn CollectionControl) -> io::Result { + 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 { - match self.profile.client_os() { - ClientOs::Linux => detect_clamav(), - ClientOs::Mac | ClientOs::Windows => None, - } - } - - fn ufw_for_profile(&self) -> Option { - match self.profile.client_os() { - ClientOs::Linux => detect_ufw(), - ClientOs::Mac | ClientOs::Windows => None, - } - } - - fn sentinel_for_profile(&self) -> Option { #[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 { - 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> { + 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 { - 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> { + 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> { + 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)> { @@ -603,24 +611,11 @@ fn parse_ufw_status(output: &str) -> Option { } } -fn detect_microsoft_defender_blocking() -> Option { - 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> { + 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 { @@ -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 = 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 = 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 = 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 = 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 = 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(×tamp)); + for field in CURRENT_TOP_LEVEL_FIELDS + .iter() + .filter(|field| **field != "generate-time") + { assert_eq!( unique_child(&refreshed, field).unwrap().get_text(), unique_child(¤t, 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)) - ); - } } diff --git a/crates/gphip/src/sentinel_macos.rs b/crates/gphip/src/sentinel_macos.rs index 3e30cd2..c3068a9 100644 --- a/crates/gphip/src/sentinel_macos.rs +++ b/crates/gphip/src/sentinel_macos.rs @@ -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 { +pub(super) fn detect(commands: &CollectorCommands<'_>) -> io::Result> { 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 { - 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> { + Ok( + commands + .run_path(Path::new(SENTINELCTL), args)? + .filter(|output| output.status.success()) + .and_then(|output| String::from_utf8(output.stdout).ok()), + ) } struct AgentStatus { diff --git a/crates/gphip/src/sentinel_unix.rs b/crates/gphip/src/sentinel_unix.rs index a710493..a7ec60c 100644 --- a/crates/gphip/src/sentinel_unix.rs +++ b/crates/gphip/src/sentinel_unix.rs @@ -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 { - 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> { + 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 { @@ -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 { - 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> { + 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 { diff --git a/crates/openconnect/Cargo.toml b/crates/openconnect/Cargo.toml index 7dba5e1..19f63d4 100644 --- a/crates/openconnect/Cargo.toml +++ b/crates/openconnect/Cargo.toml @@ -7,6 +7,7 @@ links = "openconnect" [dependencies] log.workspace = true +libc = "0.2" is_executable.workspace = true [build-dependencies] diff --git a/crates/openconnect/build.rs b/crates/openconnect/build.rs index daf79a5..25fdf5f 100644 --- a/crates/openconnect/build.rs +++ b/crates/openconnect/build.rs @@ -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() { diff --git a/crates/openconnect/deps/openconnect b/crates/openconnect/deps/openconnect index 821a8d2..9cf2c36 160000 --- a/crates/openconnect/deps/openconnect +++ b/crates/openconnect/deps/openconnect @@ -1 +1 @@ -Subproject commit 821a8d26d076f3659e88663d1ca1f6f301a5c300 +Subproject commit 9cf2c361aa6d383c3708749814c0bd4b35f4a5e9 diff --git a/crates/openconnect/src/ffi/hip.rs b/crates/openconnect/src/ffi/hip.rs new file mode 100644 index 0000000..778e5f7 --- /dev/null +++ b/crates/openconnect/src/ffi/hip.rs @@ -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, + 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 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> { + 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 { + 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 { + 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, + data: *mut c_void, + request: &HipRequest, + check: &dyn Fn() -> io::Result<()>, +) -> io::Result { + 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::, _>>() + .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 + 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 { + 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) -> 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 '