From 6735a4fd19058179d70ac2e3c1468f345168a975 Mon Sep 17 00:00:00 2001 From: O M Date: Wed, 2 Dec 2026 19:00:34 -0500 Subject: [PATCH] Inventory packages on EFS, Azure Files, and Filestore. A library installed on a shared filesystem never became a CVE finding, because the root-volume scan does not read that mount. Co-authored-by: Cursor --- README.md | 10 +- docs/ARCHITECTURE.md | 6 +- docs/ROADMAP.md | 8 +- docs/adr/012-shared-filesystem-packages.md | 45 ++ go.mod | 7 +- go.sum | 14 +- internal/cmd/scan_workload.go | 2 +- internal/cmd/scan_workload_aws.go | 17 +- internal/cmd/scan_workload_azure.go | 17 +- internal/cmd/scan_workload_container.go | 2 +- internal/cmd/scan_workload_fs.go | 286 ++++++++++ internal/cmd/scan_workload_gcp.go | 17 +- internal/cmd/scan_workload_image.go | 37 +- internal/cmd/scan_workload_test.go | 22 + internal/graph/store.go | 109 +++- internal/graph/store_test.go | 82 +++ internal/workload/aws/fs.go | 198 +++++++ internal/workload/aws/fs_test.go | 123 +++++ internal/workload/aws/image.go | 12 +- internal/workload/aws/scan.go | 34 +- internal/workload/azure/fs.go | 201 +++++++ internal/workload/azure/fs_test.go | 91 ++++ internal/workload/azure/image.go | 23 +- internal/workload/azure/scan.go | 3 + internal/workload/fs.go | 588 +++++++++++++++++++++ internal/workload/fs_test.go | 129 +++++ internal/workload/gcp/fs.go | 212 ++++++++ internal/workload/gcp/fs_test.go | 62 +++ internal/workload/gcp/image.go | 23 +- internal/workload/gcp/scan.go | 11 +- 30 files changed, 2295 insertions(+), 96 deletions(-) create mode 100644 docs/adr/012-shared-filesystem-packages.md create mode 100644 internal/cmd/scan_workload_fs.go create mode 100644 internal/workload/aws/fs.go create mode 100644 internal/workload/aws/fs_test.go create mode 100644 internal/workload/azure/fs.go create mode 100644 internal/workload/azure/fs_test.go create mode 100644 internal/workload/fs.go create mode 100644 internal/workload/fs_test.go create mode 100644 internal/workload/gcp/fs.go create mode 100644 internal/workload/gcp/fs_test.go diff --git a/README.md b/README.md index 4995ca5..a3f085d 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ OpenSourceOM Core is the platform behind [opensourceom.org](https://opensourceom Traditional scanners flood you with CVEs and misconfigurations. OpenSourceOM connects the dots — showing which findings sit on paths from the internet to your sensitive data and privileged identities. -> **Status:** Phase 3 has shipped. Phase 4 is open: `om scan workload` inventories Linux root volumes, boot images, container layers, and function bundles. Shared filesystems are still open. Phase 5 (secret and malware findings on that storage) is open. Further rule packs stay open for contributors ([#10](https://github.com/OpenSourceOM/core/issues/10)). See the [roadmap](./docs/ROADMAP.md). +> **Status:** Phase 3 has shipped. Phase 4's ordered path has shipped: `om scan workload` inventories Linux root volumes, boot images, container layers, function bundles, and shared filesystems. Phase 5 (secret and malware findings on that storage) is open. Further rule packs stay open for contributors ([#10](https://github.com/OpenSourceOM/core/issues/10)). See the [roadmap](./docs/ROADMAP.md). ## Why this exists @@ -109,6 +109,9 @@ export AWS_REGION=us-east-1 # ./om scan workload function aws # ./om scan workload function azure # ./om scan workload function gcp +# sudo -E ./om scan workload fs aws +# sudo -E ./om scan workload fs azure +# sudo -E ./om scan workload fs gcp # Or ingest a custom collector (stdout is a graph batch) go build -o example-collector ./examples/collector @@ -171,6 +174,9 @@ An API token is created only when an admin asks for one, from the console or wit ./om scan workload function aws ./om scan workload function azure ./om scan workload function gcp +./om scan workload fs aws # instance that can already mount the EFS filesystem +./om scan workload fs azure # VM that can already mount the file share +./om scan workload fs gcp # instance on the Filestore VPC ./om scan plugin -- ./my-collector ``` @@ -197,7 +203,7 @@ Full documentation: [opensourceom.org](https://opensourceom.org) (docs at [opens | **1** | Attack path queries, CVE enrichment, web UI, Azure/GCP collectors | | **2** | CSPM rules, blast radius, K8s connector, exports | | **3** | Plugin SDK, Helm, embedded rule pack, demo graph, inventory-backed CVEs, crown-jewel datastores, attack-path findings, and cloud audit context (CloudTrail, Activity Log, Admin Activity). Shipped. | -| **4** | Package inventory from persistent workload storage. Linux root volumes, boot images, container layers, and function bundles ship with `om scan workload`. Shared filesystems are open. | +| **4** | Package inventory from persistent workload storage. Linux root volumes, boot images, container layers, function bundles, and shared filesystems ship with `om scan workload`. | | **5** | Secret and malware findings on storage Phase 4 already opens. Kind and path only. Open. | Details: [docs/ROADMAP.md](./docs/ROADMAP.md) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 46b630e..f9be551 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -88,9 +88,11 @@ Further community rule packs (PCI and additional CIS mappings) stay open for con Phase 4 writes `packages` (CPE 2.3 names and package URLs) from persistent workload storage onto the workload node that enrichment already matches. The sources, in order, are AWS Linux root volumes, Azure VM and GCE root volumes, boot images, container image layers and function bundles, and shared filesystems (EFS, Azure Files, Filestore). The scan is opt-in. `om scan aws`, `om scan azure`, and `om scan gcp` stay read-only API collectors. -`om scan workload aws` is the AWS root-volume scan. `om scan workload azure` and `om scan workload gcp` are the same walk for Azure OS disks and GCE boot disks. `om scan workload image aws`, `om scan workload image azure`, and `om scan workload image gcp` read each boot image once and add those package identifiers to instances launched from it. A package that exists only on an instance disk stays on that instance. Each of those commands runs as root on a worker in a scanner account, subscription, or project. The production account grants snapshot and share. The worker mounts the copy and stores package identifiers only. A later API scan keeps `packages`. Windows, LVM, and non-root disks are skipped. See [ADR 006](./adr/006-aws-root-volume-packages.md), [ADR 007](./adr/007-azure-gce-root-volume-packages.md), [ADR 008](./adr/008-boot-image-packages.md), and [ADR 009](./adr/009-scanner-account.md). The grants are in [deploy/connect](../deploy/connect/README.md). +`om scan workload aws` is the AWS root-volume scan. `om scan workload azure` and `om scan workload gcp` are the same walk for Azure OS disks and GCE boot disks. `om scan workload image aws`, `om scan workload image azure`, and `om scan workload image gcp` read each boot image once and add those package identifiers to instances launched from it. A package that exists only on an instance disk stays on that instance. Each of those commands runs as root on a worker in a scanner account, subscription, or project. The production account grants snapshot and share. The worker mounts the copy and stores package identifiers, plus shared-filesystem mounts from fstab and systemd units. A later API scan keeps `packages` and `filesystems`. Windows, LVM, and non-root disks are skipped. See [ADR 006](./adr/006-aws-root-volume-packages.md), [ADR 007](./adr/007-azure-gce-root-volume-packages.md), [ADR 008](./adr/008-boot-image-packages.md), and [ADR 009](./adr/009-scanner-account.md). The grants are in [deploy/connect](../deploy/connect/README.md). -`om scan workload container` reads container image layers already stored on Kubernetes workloads. `om scan workload function aws`, `om scan workload function azure`, and `om scan workload function gcp` read Lambda deployment packages, Azure Functions bundles, and Cloud Functions source. Those commands do not attach a volume. The graph stores package identifiers on the workload, beside an existing `images` list for a pod. A repository source, a zstd layer, and a foreign layer are skipped. Shared filesystems are still open. See [ADR 011](./adr/011-container-function-packages.md). +`om scan workload container` reads container image layers already stored on Kubernetes workloads. `om scan workload function aws`, `om scan workload function azure`, and `om scan workload function gcp` read Lambda deployment packages, Azure Functions bundles, and Cloud Functions source. Those commands do not attach a volume. The graph stores package identifiers on the workload, beside an existing `images` list for a pod. A repository source, a zstd layer, and a foreign layer are skipped. See [ADR 011](./adr/011-container-function-packages.md). + +`om scan workload fs aws`, `om scan workload fs azure`, and `om scan workload fs gcp` read EFS, Azure Files, and Filestore. The root-volume and boot-image scans record those mounts from fstab and systemd units. The filesystem scan runs as root on a worker that can already reach the filesystem and adds package identifiers to the workloads that list it. It does not create a mount target, a private endpoint, or a VPC authorization. See [ADR 012](./adr/012-shared-filesystem-packages.md). Phase 5 adds a finding for a secret pattern or a malware signature on storage that Phase 4 reader already opened. The finding stores the kind and the path. Object bodies and database rows are in neither phase. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 7abc63e..4fa73ea 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -60,11 +60,11 @@ The ordered path above is complete. ## Phase 4 — Workload inventory -Phase 4 is open. Cloud collectors record the VM, its exposure, and its identity. They do not record the packages installed on it. `om enrich cve` already writes a finding when `packages` on a workload matches. This phase fills that property from persistent workload storage. +The ordered path for Phase 4 is complete. Cloud collectors record the VM, its exposure, and its identity. They do not record the packages installed on it. `om enrich cve` already writes a finding when `packages` on a workload matches. This phase fills that property from persistent workload storage. The phase ends when a package found in that storage is a CVE finding on the workload the graph already stores. A block volume is the first source. Boot images, container image layers, function bundles, and shared filesystems are the rest. -The scan is opt-in and separate from `om scan aws`, `om scan azure`, and `om scan gcp`. Those commands stay read-only. Root-volume and boot-image scans run a worker in a scanner account, subscription, or project. Snapshots and mounts are removed when the scan finishes, including when it fails. Container layers and function bundles are read without a volume attach. Each scan writes CPE 2.3 names and package URLs onto the workload. File contents stay off the graph. +The scan is opt-in and separate from `om scan aws`, `om scan azure`, and `om scan gcp`. Those commands stay read-only. Root-volume and boot-image scans run a worker in a scanner account, subscription, or project. Snapshots and mounts are removed when the scan finishes, including when it fails. Container layers and function bundles are read without a volume attach. Shared filesystems are mounted read-only from a worker that can already reach them. Each scan writes CPE 2.3 names and package URLs onto the workload. File contents stay off the graph. The path, in order: @@ -72,7 +72,7 @@ The path, in order: - [x] **Azure VM and GCE root volumes** — the same walker, those snapshot APIs — [#103](https://github.com/OpenSourceOM/core/issues/103) - [x] **Boot images** — an AMI and the Azure and GCE equivalents, scanned once and applied to instances launched from that image — [#104](https://github.com/OpenSourceOM/core/issues/104) - [x] **Container image layers and function bundles** — layers for images already stored on Kubernetes workloads, plus Lambda deployment packages and the Azure and GCP equivalents. No volume attach — [#105](https://github.com/OpenSourceOM/core/issues/105) -- [ ] **Shared filesystems** — EFS, Azure Files, and Filestore, when the application is installed there and a root-volume scan would miss it — [#106](https://github.com/OpenSourceOM/core/issues/106) +- [x] **Shared filesystems** — EFS, Azure Files, and Filestore, when the application is installed there and a root-volume scan would miss it — [#106](https://github.com/OpenSourceOM/core/issues/106) `om scan workload aws` reads Linux root volumes in a production account from a worker in a scanner account. It assumes a snapshot role, shares the snapshot, copies it into the scanner account, and mounts that copy read-only. `om scan workload azure` and `om scan workload gcp` do the same from a scanner subscription or project. The grants are in `deploy/connect`. A later `om scan aws`, `om scan azure`, or `om scan gcp` leaves `packages` in place. Windows, LVM, and disks other than the root volume are skipped. See [ADR 009](./adr/009-scanner-account.md). @@ -80,6 +80,8 @@ The path, in order: `om scan workload container` reads each container image stored by `om scan k8s` once and adds those package identifiers to every Kubernetes workload that lists the image. The `images` list stays. Registry credentials stay in the operator environment. `om scan workload function aws`, `om scan workload function azure`, and `om scan workload function gcp` write a workload for each function and store package identifiers from its deployment package or container image. A repository source, a zstd layer, and a foreign layer are skipped. No snapshot or volume is attached. Bundle bytes and layer bytes are deleted after the walk. A later API scan leaves these packages in place. See [ADR 011](./adr/011-container-function-packages.md). +The ordered path above is complete. `om scan workload fs aws` reads each EFS filesystem recorded on a workload. `om scan workload fs azure` reads Azure Files, and `om scan workload fs gcp` reads Filestore. The root-volume and boot-image scans record those mounts from fstab and systemd units. The filesystem scan runs as root on a worker that can already reach the filesystem, mounts it read-only, and adds package identifiers to every workload that lists it. A package already stored stays. The command does not create a mount target, a private endpoint, or a VPC authorization. A later root-volume scan replaces `packages`, so the filesystem scan runs again after it. See [ADR 012](./adr/012-shared-filesystem-packages.md). + Object bodies and database rows stay out. They are customer data, not the installed software. A public bucket or database is already an exposure finding from the API scan. ## Phase 5 — Findings on inventoried storage diff --git a/docs/adr/012-shared-filesystem-packages.md b/docs/adr/012-shared-filesystem-packages.md new file mode 100644 index 0000000..4768af1 --- /dev/null +++ b/docs/adr/012-shared-filesystem-packages.md @@ -0,0 +1,45 @@ + + +# ADR 012: Shared filesystem package inventory + +**Status:** Accepted +**Date:** 2026-12-02 +**Phase:** 4 + +## Context + +[ADR 006](./006-aws-root-volume-packages.md) reads a block volume. An application can be installed on a filesystem mounted into the VM instead: EFS, Azure Files, or Filestore. The root-volume scan then reports the packages on the disk and misses the library on the mount. + +Those filesystems are not block volumes. A snapshot cannot be shared into the scanner account without a new network path. [Issue #106](https://github.com/OpenSourceOM/core/issues/106) says the scan uses the account's existing mount permissions and does not open the filesystem to a new network. + +## Decision + +`om scan workload fs aws`, `om scan workload fs azure`, and `om scan workload fs gcp` are subcommands of the same opt-in scan. `om scan aws`, `om scan azure`, and `om scan gcp` stay read-only. + +The root-volume scan and the boot-image scan, while the guest is mounted, read `/etc/fstab` and systemd `.mount` units. They store EFS ids, Azure Files hosts and shares, and private NFS exports on the workload as `filesystems`. File contents are not stored. The root-volume scan replaces that list, including with an empty list when the guest no longer mounts one. The boot-image scan adds mounts found on the image and does not remove mounts already stored. An API scan that omits `filesystems` keeps the list. + +The filesystem command runs as root on a worker in the account, subscription, or project being scanned, on a network that can already reach the filesystem. It mounts each recorded filesystem once, read-only, and adds the CPE 2.3 names and package URLs to every workload that lists it. Packages already stored stay. The walk reads dpkg, apk, and rpm databases at the mount root, plus Maven jars, Python distributions, and npm `package.json` files. Other file bodies are not read. + +An EFS filesystem is mounted only when `DescribeMountTargets` shows an available mount target in the worker's VPC. The command does not call `CreateMountTarget`. An Azure Files share is mounted only when the share exists in the subscription. NFS is mounted without a credential. SMB needs `--cifs-credentials`, a file `mount` reads; the path is not stored. The command does not create a private endpoint. A Filestore export is mounted only when the instance's VPC name is the worker's VPC name. The command does not add a network. + +A filesystem the account no longer has is skipped. The mount is removed when the walk finishes, including when it fails. The graph, logs, and exports store package identifiers. They do not store file contents. + +The new AWS actions are `elasticfilesystem:DescribeFileSystems`, `elasticfilesystem:DescribeMountTargets`, and `ec2:DescribeInstances`. The new Azure actions are `Microsoft.Storage/storageAccounts/read` and `Microsoft.Storage/storageAccounts/fileServices/shares/read`. The new GCP permission is `file.instances.list`. The API collectors do not gain these permissions. + +Object bodies and database rows stay out. LVM roots and data disks stay out. A filesystem that requires the EFS mount helper is not given a new credential. + +## Consequences + +The filesystem command cannot run in the scanner account. The worker has to be on the network that already mounts the filesystem. The Helm chart does not schedule it. + +A later root-volume scan replaces `packages` with what is on the disk. Run the filesystem command again after that. `om enrich cve` is unchanged. It attaches a CVE only when one of these identifiers matches. + +## References + +- [docs/ROADMAP.md](../ROADMAP.md) +- [ADR 006](./006-aws-root-volume-packages.md) +- [ADR 009](./009-scanner-account.md) +- [Issue #106](https://github.com/OpenSourceOM/core/issues/106) diff --git a/go.mod b/go.mod index 826d253..528fb7a 100644 --- a/go.mod +++ b/go.mod @@ -15,13 +15,14 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources/v3 v3.0.1 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/v3 v3.0.0 github.com/anchore/go-rpmdb v0.2.2 - github.com/aws/aws-sdk-go-v2 v1.48.2 + github.com/aws/aws-sdk-go-v2 v1.49.0 github.com/aws/aws-sdk-go-v2/config v1.33.12 github.com/aws/aws-sdk-go-v2/credentials v1.20.15 github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.7 github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.65.13 github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.2 github.com/aws/aws-sdk-go-v2/service/ecr v1.67.0 + github.com/aws/aws-sdk-go-v2/service/efs v1.52.1 github.com/aws/aws-sdk-go-v2/service/iam v1.64.6 github.com/aws/aws-sdk-go-v2/service/lambda v1.113.3 github.com/aws/aws-sdk-go-v2/service/rds v1.130.3 @@ -52,8 +53,8 @@ require ( github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.63.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.63.0 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.14 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.14 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.10 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 // indirect github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9 // indirect diff --git a/go.sum b/go.sum index 992d68d..404a14b 100644 --- a/go.sum +++ b/go.sum @@ -58,8 +58,8 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapp github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.63.0/go.mod h1:O5gqO+rsDs9p6eDe5MNSLfSIcoiw1iGqkyQbiiFCWhU= github.com/anchore/go-rpmdb v0.2.2 h1:44VC7mvFAxV9t5JUZYg3S9sqG+E94iZvyWACMDq9hSk= github.com/anchore/go-rpmdb v0.2.2/go.mod h1:Y64EbetdqhryMjtk8IzXkdCQw/aNDx+feZCT9aj6rjs= -github.com/aws/aws-sdk-go-v2 v1.48.2 h1:TDS0/5Z/UjdvmB0jg+8j6a80n5OCRyvrn3aOtZ6z0M4= -github.com/aws/aws-sdk-go-v2 v1.48.2/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY= +github.com/aws/aws-sdk-go-v2 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU= +github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 h1:MW0Iql1SOTgQPj8mCxrU/eH/K/AIDWi08ItOsXaWRLU= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25/go.mod h1:+ucVYmHYB3JqVueY0E1RHahdXAnKQbIHqybSbvOUbOM= github.com/aws/aws-sdk-go-v2/config v1.33.12 h1:IV1YARaXahwCqUIyP8IlWsP85Lil+5ozTozDQXPumRk= @@ -68,10 +68,10 @@ github.com/aws/aws-sdk-go-v2/credentials v1.20.15 h1:LUFG3364w8wKBhGxGQ2XUxCCs+y github.com/aws/aws-sdk-go-v2/credentials v1.20.15/go.mod h1:Q+tKQpy3sU1MjBqXzhZauN7ffcNRF9p7Rvw293sYwE4= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.7 h1:5GGOwjXU738VrsBT0EDFtP5JtLPmJQILp8RS6P+KqLM= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.7/go.mod h1:jY/VeijtHNuTiy5XI9HjpLiamtaaLw+KInZULfookJ8= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.14 h1:0a6o5QglM7yIYPBtuU2I0cts4GmoxKq9CI4QXhoYjwU= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.14/go.mod h1:97hjZ6DMSiOIc1yO/nkExfwEtyS3TTTwLTc4djsPV6M= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.14 h1:JxqxML276jtkfjQxKgAeSSCH5IaK2q8SxxNBLpjdd8g= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.14/go.mod h1:w22QsiUhclV6A0d6unKN6TpwWFWTRBMa1Rt/B3gs7b8= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.10 h1:iytL6kFchhbCWWEfLzMGq1+yRecF7+BOXnp70J9zNRM= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.10/go.mod h1:OaBcfeWMHPSyFqiHL/KN1zVIricTvYDNiO4XhR781eM= github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.65.13 h1:0Eohou9DEK6s1JjZnhfTWSYjRCvDH+KdJKS4SKbV+HU= @@ -80,6 +80,8 @@ github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.2 h1:JohP9To4S31937ChcN87LOGGHWc github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.2/go.mod h1:JbB+shRXmk18Y4V+GnOzGWFkIjA8ZfGSgtPUgs4X+7E= github.com/aws/aws-sdk-go-v2/service/ecr v1.67.0 h1:diXYaM5vgoy4xeHgY4Q0cAwCCwKx+cvFdjR23eKGXJk= github.com/aws/aws-sdk-go-v2/service/ecr v1.67.0/go.mod h1:hbHHpYZ/29gAnar+fh7C0BpL/ELXMwxh2q7ZqXSZePI= +github.com/aws/aws-sdk-go-v2/service/efs v1.52.1 h1:tW+u0AatytrRMTpWuYspruJEY2VGVEMHcBq07voSDuU= +github.com/aws/aws-sdk-go-v2/service/efs v1.52.1/go.mod h1:b+be7gv6fFt/gsw709moLa6RLErQY2WCdJk8eKKMxlA= github.com/aws/aws-sdk-go-v2/service/iam v1.64.6 h1:6tqE3gHbHFEvARPvlLHgRK1dXoD96ecolfPEurpYXyc= github.com/aws/aws-sdk-go-v2/service/iam v1.64.6/go.mod h1:lV0r+RVSkXRA6WhiaxW55qn8n60ObMwQShxaqrs9UeY= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8= diff --git a/internal/cmd/scan_workload.go b/internal/cmd/scan_workload.go index 297fe9b..e0eced3 100644 --- a/internal/cmd/scan_workload.go +++ b/internal/cmd/scan_workload.go @@ -10,7 +10,7 @@ var scanWorkloadCmd = &cobra.Command{ Short: "Inventory packages on workload storage", Long: `Inventory packages on workload storage. -Root volumes are "om scan workload aws", "om scan workload azure", and "om scan workload gcp". Boot images are "om scan workload image aws", "om scan workload image azure", and "om scan workload image gcp". Each of those runs as root on a worker in a scanner account, subscription, or project. It assumes a role in the account being scanned, shares a snapshot, and mounts the copy on the worker. Container layers are "om scan workload container". Function bundles are "om scan workload function aws", "om scan workload function azure", and "om scan workload function gcp". Those do not attach a volume. om scan aws, om scan azure, and om scan gcp stay read-only. The grants for the volume scans are in deploy/connect.`, +Root volumes are "om scan workload aws", "om scan workload azure", and "om scan workload gcp". Boot images are "om scan workload image aws", "om scan workload image azure", and "om scan workload image gcp". Each of those runs as root on a worker in a scanner account, subscription, or project. It assumes a role in the account being scanned, shares a snapshot, and mounts the copy on the worker. Container layers are "om scan workload container". Function bundles are "om scan workload function aws", "om scan workload function azure", and "om scan workload function gcp". Those do not attach a volume. Shared filesystems are "om scan workload fs aws", "om scan workload fs azure", and "om scan workload fs gcp". Those run as root on a worker that can already mount the filesystem. om scan aws, om scan azure, and om scan gcp stay read-only. The grants for the volume scans are in deploy/connect.`, } func init() { diff --git a/internal/cmd/scan_workload_aws.go b/internal/cmd/scan_workload_aws.go index 60c0bf8..977ef5e 100644 --- a/internal/cmd/scan_workload_aws.go +++ b/internal/cmd/scan_workload_aws.go @@ -34,7 +34,7 @@ Run it as root on an EC2 instance in the scanner account, in the same region. Pa An encrypted volume needs --kms-key, a key in the scanner account. The production key policy has to allow the scanner role to decrypt. om scan aws stays a read-only API scan. A later om scan aws keeps packages already stored on the workload. Snapshots and volumes are tagged opensourceom:scan=workload, which is how to find one left behind by a killed process. -This command reads Linux root volumes. Windows instances are skipped. LVM and disks other than the root volume are skipped. Boot images are "om scan workload image aws". Container layers are "om scan workload container". Function bundles are "om scan workload function aws". Shared filesystems are a later scan. +This command reads Linux root volumes. Windows instances are skipped. LVM and disks other than the root volume are skipped. Boot images are "om scan workload image aws". Container layers are "om scan workload container". Function bundles are "om scan workload function aws". Shared filesystems listed in fstab or a systemd mount unit are recorded for "om scan workload fs aws". Run that after this command. A later run of this command replaces packages, so run the filesystem scan again afterwards. ` + granted("Production role", awsv.Permissions) + "\n\n" + granted("Scanner role", awsv.WorkerPermissions) } @@ -74,10 +74,11 @@ func runScanWorkloadAWS(cmd *cobra.Command, args []string) error { AvailabilityZone: worker.AvailabilityZone, Region: worker.Region, }, - Only: awsWorkloadInstances, - Timeout: awsWorkloadTimeout, - Mount: awsv.NewGuest().MountReadOnly, - Walk: workload.Walk, + Only: awsWorkloadInstances, + Timeout: awsWorkloadTimeout, + Mount: awsv.NewGuest().MountReadOnly, + Walk: workload.Walk, + Filesystems: workload.SharedFilesystems, OnStart: func(instanceID, name string) { fmt.Printf("%s: snapshotting the root volume\n", workloadLabel(instanceID, name)) }, @@ -93,7 +94,13 @@ func runScanWorkloadAWS(cmd *cobra.Command, args []string) error { if err := store.SetWorkloadPackages(ctx, nodeID, res.Packages); err != nil { return err } + if err := storeSharedFilesystems(ctx, store, nodeID, res.Filesystems, true); err != nil { + return err + } fmt.Printf("%s: %d package identifiers\n", label, len(res.Packages)) + if len(res.Filesystems) > 0 { + fmt.Printf("%s: %d shared filesystems\n", label, len(res.Filesystems)) + } wrote++ return nil }) diff --git a/internal/cmd/scan_workload_azure.go b/internal/cmd/scan_workload_azure.go index afb9b54..a63b54b 100644 --- a/internal/cmd/scan_workload_azure.go +++ b/internal/cmd/scan_workload_azure.go @@ -33,7 +33,7 @@ Run it as root on an Azure VM in the scanner subscription, in the same region. A om scan azure stays a read-only API scan. A later om scan azure keeps packages already stored on the workload. Snapshots and disks are tagged opensourceom:scan=workload, which is how to find one left behind by a killed process. The copies cannot be exported. -This command reads Linux OS disks. Windows VMs are skipped. Ephemeral OS disks, unmanaged VHDs, LVM, and data disks are skipped. VMs in another region are skipped; run the command on a VM in that region. Boot images are "om scan workload image azure". +This command reads Linux OS disks. Windows VMs are skipped. Ephemeral OS disks, unmanaged VHDs, LVM, and data disks are skipped. VMs in another region are skipped; run the command on a VM in that region. Boot images are "om scan workload image azure". Shared filesystems listed in fstab or a systemd mount unit are recorded for "om scan workload fs azure". Run that after this command. A later run of this command replaces packages, so run the filesystem scan again afterwards. The graph id matches om scan azure: azure:::workload:. @@ -83,10 +83,11 @@ func runScanWorkloadAzure(cmd *cobra.Command, args []string) error { Location: worker.Location, Zone: worker.Zone, }, - Only: azureWorkloadVMs, - Timeout: azureWorkloadTimeout, - Mount: azurev.NewGuest().MountReadOnly, - Walk: workload.Walk, + Only: azureWorkloadVMs, + Timeout: azureWorkloadTimeout, + Mount: azurev.NewGuest().MountReadOnly, + Walk: workload.Walk, + Filesystems: workload.SharedFilesystems, OnStart: func(name, group string) { fmt.Printf("%s: snapshotting the OS disk\n", group+"/"+name) }, @@ -102,7 +103,13 @@ func runScanWorkloadAzure(cmd *cobra.Command, args []string) error { if err := store.SetWorkloadPackages(ctx, nodeID, res.Packages); err != nil { return err } + if err := storeSharedFilesystems(ctx, store, nodeID, res.Filesystems, true); err != nil { + return err + } fmt.Printf("%s: %d package identifiers\n", label, len(res.Packages)) + if len(res.Filesystems) > 0 { + fmt.Printf("%s: %d shared filesystems\n", label, len(res.Filesystems)) + } wrote++ return nil }) diff --git a/internal/cmd/scan_workload_container.go b/internal/cmd/scan_workload_container.go index 7613fa9..8a393c5 100644 --- a/internal/cmd/scan_workload_container.go +++ b/internal/cmd/scan_workload_container.go @@ -30,7 +30,7 @@ The command fetches each image once, walks the layers, and adds those CPE 2.3 na Registry credentials stay in the operator environment. A private registry uses an auth entry in the docker config (DOCKER_CONFIG, or ~/.docker/config.json). Credential helpers in that file are not run. An ECR registry uses the AWS credential chain, which needs ecr:GetAuthorizationToken. The token is not stored. Public images need no credentials. -A package already stored on the workload stays, including one this image does not contain. om scan k8s stays a read-only API scan and keeps packages already stored. Run om scan k8s first so the pod nodes and image refs exist. Shared filesystems are a later scan. +A package already stored on the workload stays, including one this image does not contain. om scan k8s stays a read-only API scan and keeps packages already stored. Run om scan k8s first so the pod nodes and image refs exist. Shared filesystems are "om scan workload fs". zstd layers and foreign layers are skipped.`, RunE: runScanWorkloadContainer, diff --git a/internal/cmd/scan_workload_fs.go b/internal/cmd/scan_workload_fs.go new file mode 100644 index 0000000..f510e21 --- /dev/null +++ b/internal/cmd/scan_workload_fs.go @@ -0,0 +1,286 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + "time" + + awscol "github.com/OpenSourceOM/core/internal/collectors/aws" + "github.com/OpenSourceOM/core/internal/config" + "github.com/OpenSourceOM/core/internal/graph" + "github.com/OpenSourceOM/core/internal/workload" + awsv "github.com/OpenSourceOM/core/internal/workload/aws" + azurev "github.com/OpenSourceOM/core/internal/workload/azure" + gcpv "github.com/OpenSourceOM/core/internal/workload/gcp" + "github.com/spf13/cobra" +) + +var ( + awsFSTimeout time.Duration + azureFSTimeout time.Duration + azureFSCreds string + gcpFSTimeout time.Duration +) + +var scanWorkloadFSCmd = &cobra.Command{ + Use: "fs", + Short: "Inventory packages on shared filesystems", + Long: `Inventory packages on shared filesystems. + +Each cloud is its own command: "om scan workload fs aws", "om scan workload fs azure", and "om scan workload fs gcp". Each reads EFS, Azure Files, or Filestore mounts recorded by the root-volume scan and adds those package identifiers to the workloads that mount them. Run it as root on a worker that can already reach the filesystem. The command does not create a mount target, a private endpoint, or a VPC authorization.`, +} + +var scanWorkloadFSAWSCmd = &cobra.Command{ + Use: "aws", + Short: "Inventory packages on EFS filesystems", + Long: workloadFSAWSLong(), + RunE: runScanWorkloadFSAWS, +} + +var scanWorkloadFSAzureCmd = &cobra.Command{ + Use: "azure", + Short: "Inventory packages on Azure Files shares", + Long: workloadFSAzureLong(), + RunE: runScanWorkloadFSAzure, +} + +var scanWorkloadFSGCPCmd = &cobra.Command{ + Use: "gcp", + Short: "Inventory packages on Filestore instances", + Long: workloadFSGCPLong(), + RunE: runScanWorkloadFSGCP, +} + +func workloadFSAWSLong() string { + return `Inventory packages on EFS filesystems recorded for workloads in this AWS account and region. + +Run it as root on an EC2 instance in the account being scanned, in a VPC that already has a mount target. Run "om scan workload aws" first. That command records EFS mounts from fstab and systemd units. This command mounts each filesystem once, read-only, and adds CPE 2.3 names and package URLs to every workload that lists it. Packages already stored stay. A later root-volume scan replaces packages, so run this command again after that. + +A filesystem with no mount target in this VPC is skipped. This command does not create one. File contents stay off the graph. + +IAM actions: + ` + strings.Join(awsv.FilesystemPermissions, "\n ") +} + +func workloadFSAzureLong() string { + return `Inventory packages on Azure Files shares recorded for workloads in this subscription and region. + +Run it as root on an Azure VM in the subscription being scanned, on a network that can already reach the share. Run "om scan workload azure" first. An NFS share is mounted read-only. An SMB share needs --cifs-credentials, a file mount can read. That path is not stored. This command does not create a private endpoint. + +A later root-volume scan replaces packages, so run this command again after that. File contents stay off the graph. + +Azure RBAC actions: + ` + strings.Join(azurev.FilesystemPermissions, "\n ") +} + +func workloadFSGCPLong() string { + return `Inventory packages on Filestore instances recorded for workloads in this project and region. + +Run it as root on a GCE instance in the project being scanned, on the VPC the instance is already authorized for. Run "om scan workload gcp" first. A Filestore instance on another VPC is skipped. This command does not add a network. + +A later root-volume scan replaces packages, so run this command again after that. File contents stay off the graph. + +IAM permissions: + ` + strings.Join(gcpv.FilesystemPermissions, "\n ") +} + +func runScanWorkloadFSAWS(cmd *cobra.Command, args []string) error { + if os.Geteuid() != 0 { + return fmt.Errorf("om scan workload fs aws mounts the filesystem and must run as root on the worker") + } + cfg := loadConfig() + ctx := cmd.Context() + worker, err := awsv.LookupWorker(ctx) + if err != nil { + return err + } + if err := awsv.CheckRegion(worker.Region, cfg.AWSRegion); err != nil { + return err + } + collector, err := awscol.NewCollector(ctx, cfg.AWSRegion) + if err != nil { + return err + } + store, uses, err := loadFilesystemUses(ctx, cfg, collector.AccountID, cfg.AWSRegion, "om scan workload aws") + if err != nil || uses == nil { + return err + } + defer store.Close() + scanner, err := awsv.NewFilesystemScanner(ctx, cfg.AWSRegion, worker) + if err != nil { + return err + } + scanner.Timeout = awsFSTimeout + scanner.Mount = workload.MountReadOnlyNFS + scanner.Walk = workload.WalkFS + scanner.OnStart = func(ref string) { fmt.Printf("%s: mounting\n", ref) } + wrote := 0 + err = scanner.Scan(ctx, uses, func(res awsv.FilesystemResult) error { + n, err := mergeFilesystemPackages(ctx, store, res.Ref, res.Skipped, res.WorkloadIDs, res.Packages) + wrote += n + return err + }) + fmt.Printf("Stored packages from shared filesystems on %d workloads.\n", wrote) + return err +} + +func runScanWorkloadFSAzure(cmd *cobra.Command, args []string) error { + if os.Geteuid() != 0 { + return fmt.Errorf("om scan workload fs azure mounts the filesystem and must run as root on the worker") + } + cfg := loadConfig() + if cfg.AzureSubscriptionID == "" { + return fmt.Errorf("AZURE_SUBSCRIPTION_ID is required") + } + ctx := cmd.Context() + worker, err := azurev.LookupWorker(ctx) + if err != nil { + return err + } + if !strings.EqualFold(worker.SubscriptionID, cfg.AzureSubscriptionID) { + return fmt.Errorf("this VM is in subscription %s; set AZURE_SUBSCRIPTION_ID=%s", worker.SubscriptionID, worker.SubscriptionID) + } + if azurev.ScanLocation(worker.Location) != azurev.ScanLocation(cfg.AzureLocation) { + return fmt.Errorf("this VM is in %s; set AZURE_LOCATION=%s", worker.Location, worker.Location) + } + store, uses, err := loadFilesystemUses(ctx, cfg, cfg.AzureSubscriptionID, cfg.AzureLocation, "om scan workload azure") + if err != nil || uses == nil { + return err + } + defer store.Close() + scanner, err := azurev.NewFilesystemScanner(cfg.AzureSubscriptionID) + if err != nil { + return err + } + scanner.Credentials = azureFSCreds + scanner.Timeout = azureFSTimeout + scanner.MountNFS = workload.MountReadOnlyNFS + scanner.MountCIFS = workload.MountReadOnlyCIFS + scanner.Walk = workload.WalkFS + scanner.OnStart = func(ref string) { fmt.Printf("%s: mounting\n", ref) } + wrote := 0 + err = scanner.Scan(ctx, uses, func(res azurev.FilesystemResult) error { + n, err := mergeFilesystemPackages(ctx, store, res.Ref, res.Skipped, res.WorkloadIDs, res.Packages) + wrote += n + return err + }) + fmt.Printf("Stored packages from shared filesystems on %d workloads.\n", wrote) + return err +} + +func runScanWorkloadFSGCP(cmd *cobra.Command, args []string) error { + if os.Geteuid() != 0 { + return fmt.Errorf("om scan workload fs gcp mounts the filesystem and must run as root on the worker") + } + cfg := loadConfig() + if cfg.GCPProjectID == "" { + return fmt.Errorf("GCP_PROJECT_ID is required") + } + ctx := cmd.Context() + worker, err := gcpv.LookupWorker(ctx) + if err != nil { + return err + } + if err := gcpv.CheckProject(worker.ProjectID, cfg.GCPProjectID); err != nil { + return err + } + if worker.ProjectID != cfg.GCPProjectID { + return fmt.Errorf("this instance is in project %s; set GCP_PROJECT_ID=%s", worker.ProjectID, worker.ProjectID) + } + if worker.Region() != cfg.GCPRegion { + return fmt.Errorf("this instance is in %s; set GCP_REGION=%s", worker.Region(), worker.Region()) + } + network, err := gcpv.LookupNetwork(ctx) + if err != nil { + return err + } + store, uses, err := loadFilesystemUses(ctx, cfg, cfg.GCPProjectID, cfg.GCPRegion, "om scan workload gcp") + if err != nil || uses == nil { + return err + } + defer store.Close() + scanner, err := gcpv.NewFilesystemScanner(ctx, cfg.GCPProjectID, network) + if err != nil { + return err + } + scanner.Timeout = gcpFSTimeout + scanner.Mount = workload.MountReadOnlyNFS + scanner.Walk = workload.WalkFS + scanner.OnStart = func(ref string) { fmt.Printf("%s: mounting\n", ref) } + wrote := 0 + err = scanner.Scan(ctx, uses, func(res gcpv.FilesystemResult) error { + n, err := mergeFilesystemPackages(ctx, store, res.Ref, res.Skipped, res.WorkloadIDs, res.Packages) + wrote += n + return err + }) + fmt.Printf("Stored packages from shared filesystems on %d workloads.\n", wrote) + return err +} + +func loadFilesystemUses(ctx context.Context, cfg config.Config, accountID, region, first string) (*graph.Store, []workload.FilesystemUse, error) { + store, err := openGraphStore(ctx, cfg) + if err != nil { + return nil, nil, err + } + listed, err := store.ListWorkloadFilesystems(ctx, accountID, region) + if err != nil { + store.Close() + return nil, nil, err + } + if len(listed) == 0 { + store.Close() + fmt.Printf("No shared filesystems are recorded. Run %s first.\n", first) + return nil, nil, nil + } + uses := make([]workload.FilesystemUse, len(listed)) + for i, item := range listed { + uses[i] = workload.FilesystemUse{WorkloadID: item.ID, Name: item.Name, Refs: item.Refs} + } + return store, uses, nil +} + +func mergeFilesystemPackages(ctx context.Context, store *graph.Store, ref, skipped string, ids, packages []string) (int, error) { + if skipped != "" { + fmt.Printf("%s: skipped (%s)\n", ref, skipped) + return 0, nil + } + var failed []error + wrote := 0 + for _, id := range ids { + if err := store.MergeWorkloadPackages(ctx, id, packages); err != nil { + failed = append(failed, err) + continue + } + fmt.Printf("%s: %d package identifiers on %s\n", ref, len(packages), id) + wrote++ + } + return wrote, errors.Join(failed...) +} + +func storeSharedFilesystems(ctx context.Context, store *graph.Store, id string, refs []string, replace bool) error { + if refs == nil { + return nil + } + if replace { + return store.SetWorkloadFilesystems(ctx, id, refs) + } + if len(refs) == 0 { + return nil + } + return store.MergeWorkloadFilesystems(ctx, id, refs) +} + +func init() { + scanWorkloadFSAWSCmd.Flags().DurationVar(&awsFSTimeout, "timeout", 10*time.Minute, "time limit for each filesystem") + scanWorkloadFSAzureCmd.Flags().DurationVar(&azureFSTimeout, "timeout", 10*time.Minute, "time limit for each filesystem") + scanWorkloadFSAzureCmd.Flags().StringVar(&azureFSCreds, "cifs-credentials", "", "absolute path of an SMB credentials file mount can read; the path is not stored") + scanWorkloadFSGCPCmd.Flags().DurationVar(&gcpFSTimeout, "timeout", 10*time.Minute, "time limit for each filesystem") + scanWorkloadFSCmd.AddCommand(scanWorkloadFSAWSCmd, scanWorkloadFSAzureCmd, scanWorkloadFSGCPCmd) + scanWorkloadCmd.AddCommand(scanWorkloadFSCmd) +} diff --git a/internal/cmd/scan_workload_gcp.go b/internal/cmd/scan_workload_gcp.go index 0c53446..0b670ba 100644 --- a/internal/cmd/scan_workload_gcp.go +++ b/internal/cmd/scan_workload_gcp.go @@ -33,7 +33,7 @@ Run it as root on a GCE instance in the scanner project, in the same region. GCP om scan gcp stays a read-only API scan. A later om scan gcp keeps packages already stored on the workload. Snapshots and disks are labeled opensourceom-scan=workload, which is how to find one left behind by a killed process. Label keys cannot contain a colon. -This command reads Linux boot disks. Windows instances are skipped. Local SSD boot disks, customer-supplied encryption keys, LVM, and extra disks are skipped. Instances in another region are skipped; run the command on an instance in that region. Boot images are "om scan workload image gcp". +This command reads Linux boot disks. Windows instances are skipped. Local SSD boot disks, customer-supplied encryption keys, LVM, and extra disks are skipped. Instances in another region are skipped; run the command on an instance in that region. Boot images are "om scan workload image gcp". Shared filesystems listed in fstab or a systemd mount unit are recorded for "om scan workload fs gcp". Run that after this command. A later run of this command replaces packages, so run the filesystem scan again afterwards. The graph id matches om scan gcp: gcp:::workload:. @@ -82,10 +82,11 @@ func runScanWorkloadGCP(cmd *cobra.Command, args []string) error { ProjectID: worker.ProjectID, Zone: worker.Zone, }, - Only: gcpWorkloadInstances, - Timeout: gcpWorkloadTimeout, - Mount: gcpv.NewGuest().MountReadOnly, - Walk: workload.Walk, + Only: gcpWorkloadInstances, + Timeout: gcpWorkloadTimeout, + Mount: gcpv.NewGuest().MountReadOnly, + Walk: workload.Walk, + Filesystems: workload.SharedFilesystems, OnStart: func(name, zone string) { fmt.Printf("%s: snapshotting the boot disk\n", zone+"/"+name) }, @@ -101,7 +102,13 @@ func runScanWorkloadGCP(cmd *cobra.Command, args []string) error { if err := store.SetWorkloadPackages(ctx, nodeID, res.Packages); err != nil { return err } + if err := storeSharedFilesystems(ctx, store, nodeID, res.Filesystems, true); err != nil { + return err + } fmt.Printf("%s: %d package identifiers\n", label, len(res.Packages)) + if len(res.Filesystems) > 0 { + fmt.Printf("%s: %d shared filesystems\n", label, len(res.Filesystems)) + } wrote++ return nil }) diff --git a/internal/cmd/scan_workload_image.go b/internal/cmd/scan_workload_image.go index 0b74baf..0592cac 100644 --- a/internal/cmd/scan_workload_image.go +++ b/internal/cmd/scan_workload_image.go @@ -133,9 +133,10 @@ func runScanWorkloadImageAWS(cmd *cobra.Command, args []string) error { AvailabilityZone: worker.AvailabilityZone, Region: worker.Region, }, - Timeout: awsImageTimeout, - Mount: awsv.NewGuest().MountReadOnly, - Walk: workload.Walk, + Timeout: awsImageTimeout, + Mount: awsv.NewGuest().MountReadOnly, + Walk: workload.Walk, + Filesystems: workload.SharedFilesystems, OnStart: func(imageID, name string) { fmt.Printf("%s: reading the boot image\n", workloadLabel(imageID, name)) }, @@ -158,6 +159,10 @@ func runScanWorkloadImageAWS(cmd *cobra.Command, args []string) error { failed = append(failed, err) continue } + if err := storeSharedFilesystems(ctx, store, nodeID, res.Filesystems, false); err != nil { + failed = append(failed, err) + continue + } fmt.Printf("%s: %d package identifiers\n", workloadLabel(inst.ID, inst.Name), len(res.Packages)) wrote++ } @@ -208,10 +213,11 @@ func runScanWorkloadImageAzure(cmd *cobra.Command, args []string) error { Location: worker.Location, Zone: worker.Zone, }, - Only: azureImageIDs, - Timeout: azureImageTimeout, - Mount: azurev.NewGuest().MountReadOnly, - Walk: workload.Walk, + Only: azureImageIDs, + Timeout: azureImageTimeout, + Mount: azurev.NewGuest().MountReadOnly, + Walk: workload.Walk, + Filesystems: workload.SharedFilesystems, OnStart: func(_, name string) { fmt.Printf("%s: reading the boot image\n", name) }, @@ -237,6 +243,10 @@ func runScanWorkloadImageAzure(cmd *cobra.Command, args []string) error { failed = append(failed, err) continue } + if err := storeSharedFilesystems(ctx, store, nodeID, res.Filesystems, false); err != nil { + failed = append(failed, err) + continue + } fmt.Printf("%s: %d package identifiers\n", groupLabel(vm.ResourceGroup, vm.Name), len(res.Packages)) wrote++ } @@ -285,10 +295,11 @@ func runScanWorkloadImageGCP(cmd *cobra.Command, args []string) error { ProjectID: worker.ProjectID, Zone: worker.Zone, }, - Only: gcpImageIDs, - Timeout: gcpImageTimeout, - Mount: gcpv.NewGuest().MountReadOnly, - Walk: workload.Walk, + Only: gcpImageIDs, + Timeout: gcpImageTimeout, + Mount: gcpv.NewGuest().MountReadOnly, + Walk: workload.Walk, + Filesystems: workload.SharedFilesystems, OnStart: func(_, name string) { fmt.Printf("%s: reading the boot image\n", name) }, @@ -314,6 +325,10 @@ func runScanWorkloadImageGCP(cmd *cobra.Command, args []string) error { failed = append(failed, err) continue } + if err := storeSharedFilesystems(ctx, store, nodeID, res.Filesystems, false); err != nil { + failed = append(failed, err) + continue + } fmt.Printf("%s: %d package identifiers\n", zoneLabel(inst.Zone, inst.Name), len(res.Packages)) wrote++ } diff --git a/internal/cmd/scan_workload_test.go b/internal/cmd/scan_workload_test.go index 66d6dd8..da59bb6 100644 --- a/internal/cmd/scan_workload_test.go +++ b/internal/cmd/scan_workload_test.go @@ -90,6 +90,28 @@ func TestScanWorkloadRegistered(t *testing.T) { t.Errorf("function gcp help missing %s", action) } } + fs := commandByName(t, workloadCmd, "fs") + if fs.Runnable() { + t.Fatal("om scan workload fs runs a scan; name the cloud") + } + awsFS := commandByName(t, fs, "aws") + for _, action := range awsv.FilesystemPermissions { + if !strings.Contains(awsFS.Long, action) { + t.Errorf("fs aws help missing %s", action) + } + } + azureFS := commandByName(t, fs, "azure") + for _, action := range azurev.FilesystemPermissions { + if !strings.Contains(azureFS.Long, action) { + t.Errorf("fs azure help missing %s", action) + } + } + gcpFS := commandByName(t, fs, "gcp") + for _, action := range gcpv.FilesystemPermissions { + if !strings.Contains(gcpFS.Long, action) { + t.Errorf("fs gcp help missing %s", action) + } + } } func commandByName(t *testing.T, parent *cobra.Command, name string) *cobra.Command { diff --git a/internal/graph/store.go b/internal/graph/store.go index 9754be3..f9f241c 100644 --- a/internal/graph/store.go +++ b/internal/graph/store.go @@ -88,8 +88,8 @@ func upsertBatch(ctx context.Context, tx pgx.Tx, batch Batch) error { if err != nil { return err } - // packages is written by the workload scan. An API scan that omits the - // key keeps the list already stored on the node. + // packages and filesystems are written by the workload scan. An API scan + // that omits a key keeps the value already stored on the node. _, err = tx.Exec(ctx, ` INSERT INTO nodes (id, type, name, provider, region, account_id, properties, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, now()) @@ -99,12 +99,19 @@ func upsertBatch(ctx context.Context, tx pgx.Tx, batch Batch) error { provider = EXCLUDED.provider, region = EXCLUDED.region, account_id = EXCLUDED.account_id, - properties = CASE - WHEN jsonb_exists(EXCLUDED.properties, 'packages') - OR NOT jsonb_exists(nodes.properties, 'packages') - THEN EXCLUDED.properties - ELSE EXCLUDED.properties || jsonb_build_object('packages', nodes.properties->'packages') - END, + properties = EXCLUDED.properties + || CASE + WHEN jsonb_exists(EXCLUDED.properties, 'packages') + OR NOT jsonb_exists(nodes.properties, 'packages') + THEN '{}'::jsonb + ELSE jsonb_build_object('packages', nodes.properties->'packages') + END + || CASE + WHEN jsonb_exists(EXCLUDED.properties, 'filesystems') + OR NOT jsonb_exists(nodes.properties, 'filesystems') + THEN '{}'::jsonb + ELSE jsonb_build_object('filesystems', nodes.properties->'filesystems') + END, updated_at = now() `, node.ID, node.Type, node.Name, node.Provider, node.Region, node.AccountID, props) if err != nil { @@ -437,6 +444,92 @@ func (s *Store) SetWorkloadPackages(ctx context.Context, id string, packages []s return nil } +// WorkloadFilesystems is a workload and the shared filesystems recorded on it. +type WorkloadFilesystems struct { + ID string + Name string + Refs []string +} + +// MergeWorkloadFilesystems adds shared-filesystem references on an existing workload. +// References already stored stay. A later inventory upsert that omits filesystems +// keeps the merged list. +func (s *Store) MergeWorkloadFilesystems(ctx context.Context, id string, refs []string) error { + node, err := s.GetNode(ctx, id) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("workload %s is not in the graph", id) + } + return err + } + if node.Type != NodeWorkload { + return fmt.Errorf("workload %s is not in the graph", id) + } + return s.SetWorkloadFilesystems(ctx, id, UnionPackages(packageList(node.Properties["filesystems"]), refs)) +} + +// SetWorkloadFilesystems stores shared-filesystem references on an existing workload. +// An empty list clears mounts the root no longer has. A later inventory upsert +// that omits filesystems keeps this list. +func (s *Store) SetWorkloadFilesystems(ctx context.Context, id string, refs []string) error { + if refs == nil { + refs = []string{} + } + raw, err := json.Marshal(refs) + if err != nil { + return err + } + tag, err := s.pool.Exec(ctx, ` + UPDATE nodes + SET properties = jsonb_set(COALESCE(properties, '{}'::jsonb), '{filesystems}', $2::jsonb, true), + updated_at = now() + WHERE id = $1 AND type = $3 + `, id, string(raw), NodeWorkload) + if err != nil { + return fmt.Errorf("set filesystems on %s: %w", id, err) + } + if tag.RowsAffected() == 0 { + return fmt.Errorf("workload %s is not in the graph", id) + } + return nil +} + +// ListWorkloadFilesystems returns workloads in account and region that mount +// at least one shared filesystem. A zone stored as the region matches the +// region prefix, so a GCE zone matches its region. +func (s *Store) ListWorkloadFilesystems(ctx context.Context, accountID, region string) ([]WorkloadFilesystems, error) { + if accountID == "" || region == "" { + return nil, fmt.Errorf("filesystems need an account and a region") + } + rows, err := s.pool.Query(ctx, ` + SELECT id, name, properties->'filesystems' + FROM nodes + WHERE type = $1 + AND account_id = $2 + AND (lower(region) = lower($3) OR lower(region) LIKE lower($3) || '-%') + AND jsonb_typeof(properties->'filesystems') = 'array' + AND jsonb_array_length(properties->'filesystems') > 0 + ORDER BY id + `, NodeWorkload, accountID, region) + if err != nil { + return nil, err + } + defer rows.Close() + var out []WorkloadFilesystems + for rows.Next() { + var item WorkloadFilesystems + var raw []byte + if err := rows.Scan(&item.ID, &item.Name, &raw); err != nil { + return nil, err + } + if err := json.Unmarshal(raw, &item.Refs); err != nil { + return nil, fmt.Errorf("filesystems on %s: %w", item.ID, err) + } + out = append(out, item) + } + return out, rows.Err() +} + // ReplaceFunctionWorkloads upserts function workloads and deletes other function // workloads in the same account and region. An API inventory scan does not // delete these nodes. Findings whose workload was removed are deleted with it. diff --git a/internal/graph/store_test.go b/internal/graph/store_test.go index 9a879c4..3a425ee 100644 --- a/internal/graph/store_test.go +++ b/internal/graph/store_test.go @@ -242,6 +242,88 @@ func TestUpsertKeepsPackagesWhenScanOmitsThem(t *testing.T) { } } +func TestUpsertKeepsFilesystemsWhenScanOmitsThem(t *testing.T) { + ctx := context.Background() + store := openQueryFixture(t) + const id = "aws:111122223333:us-east-1:workload:i-fs" + node := graph.Node{ + ID: id, Type: graph.NodeWorkload, Name: "web", Provider: "aws", + Region: "us-east-1", AccountID: "111122223333", + Properties: map[string]any{ + "packages": []any{"pkg:deb/ubuntu/openssl@1.1.1n-0ubuntu1"}, + "filesystems": []any{"efs:fs-aaaaaaaa"}, + }, + } + if err := store.UpsertBatch(ctx, graph.Batch{Nodes: []graph.Node{node}}); err != nil { + t.Fatal(err) + } + node.Properties = map[string]any{"image": "ami-1"} + if err := store.UpsertBatch(ctx, graph.Batch{Nodes: []graph.Node{node}}); err != nil { + t.Fatal(err) + } + got := mustNode(t, ctx, store, id) + if got.Properties["image"] != "ami-1" { + t.Fatalf("properties = %#v", got.Properties) + } + if joinPackages(t, got.Properties) != "pkg:deb/ubuntu/openssl@1.1.1n-0ubuntu1" { + t.Fatalf("packages = %#v", got.Properties["packages"]) + } + if joinedProp(t, got.Properties["filesystems"]) != "efs:fs-aaaaaaaa" { + t.Fatalf("filesystems = %#v", got.Properties["filesystems"]) + } + + if err := store.SetWorkloadPackages(ctx, id, []string{}); err != nil { + t.Fatal(err) + } + got = mustNode(t, ctx, store, id) + if joinedProp(t, got.Properties["filesystems"]) != "efs:fs-aaaaaaaa" { + t.Fatalf("filesystems were dropped: %#v", got.Properties) + } + if err := store.MergeWorkloadFilesystems(ctx, id, []string{"efs:fs-bbbbbbbb"}); err != nil { + t.Fatal(err) + } + listed, err := store.ListWorkloadFilesystems(ctx, "111122223333", "us-east-1") + if err != nil { + t.Fatal(err) + } + if len(listed) != 1 || listed[0].ID != id || strings.Join(listed[0].Refs, " ") != "efs:fs-aaaaaaaa efs:fs-bbbbbbbb" { + t.Fatalf("listed = %+v", listed) + } + + zone := graph.Node{ + ID: "gcp:prod:us-central1-a:workload:web", Type: graph.NodeWorkload, Name: "web", Provider: "gcp", + Region: "us-central1-a", AccountID: "prod", + Properties: map[string]any{"filesystems": []any{"nfs:10.1.2.3/vol1"}}, + } + if err := store.UpsertBatch(ctx, graph.Batch{Nodes: []graph.Node{zone}}); err != nil { + t.Fatal(err) + } + zones, err := store.ListWorkloadFilesystems(ctx, "prod", "us-central1") + if err != nil { + t.Fatal(err) + } + if len(zones) != 1 || zones[0].Refs[0] != "nfs:10.1.2.3/vol1" { + t.Fatalf("zones = %+v", zones) + } +} + +func joinedProp(t *testing.T, value any) string { + t.Helper() + raw, ok := value.([]any) + if !ok { + t.Fatalf("value = %#v", value) + } + parts := make([]string, len(raw)) + for i, item := range raw { + part, ok := item.(string) + if !ok { + t.Fatalf("item %d = %#v", i, item) + } + parts[i] = part + } + return strings.Join(parts, " ") +} + func TestMergeWorkloadPackagesKeepsInstanceOnlyPackages(t *testing.T) { ctx := context.Background() store := openQueryFixture(t) diff --git a/internal/workload/aws/fs.go b/internal/workload/aws/fs.go new file mode 100644 index 0000000..c7ffe4a --- /dev/null +++ b/internal/workload/aws/fs.go @@ -0,0 +1,198 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package aws + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/OpenSourceOM/core/internal/workload" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/efs" + efstypes "github.com/aws/aws-sdk-go-v2/service/efs/types" + "github.com/aws/smithy-go" +) + +// FilesystemPermissions are the IAM actions for reading EFS that a workload +// already mounts. CreateMountTarget is not one of them. +var FilesystemPermissions = []string{ + "ec2:DescribeInstances", + "elasticfilesystem:DescribeFileSystems", + "elasticfilesystem:DescribeMountTargets", +} + +// FilesystemResult is one EFS filesystem after it has been unmounted. +type FilesystemResult struct { + Ref string + Packages []string + WorkloadIDs []string + Names []string + Skipped string +} + +type efsAPI interface { + DescribeFileSystems(context.Context, *efs.DescribeFileSystemsInput, ...func(*efs.Options)) (*efs.DescribeFileSystemsOutput, error) + DescribeMountTargets(context.Context, *efs.DescribeMountTargetsInput, ...func(*efs.Options)) (*efs.DescribeMountTargetsOutput, error) +} + +type instanceVPC interface { + DescribeInstances(context.Context, *ec2.DescribeInstancesInput, ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) +} + +// FilesystemScanner mounts EFS filesystems already recorded on workloads. +// It does not create a mount target or a security group rule. +type FilesystemScanner struct { + EFS efsAPI + EC2 instanceVPC + Region string + Worker Worker + Timeout time.Duration + Mount func(ctx context.Context, source string) (root string, cleanup func() error, err error) + Walk func(root string) ([]string, error) + OnStart func(ref string) +} + +// NewFilesystemScanner uses the default AWS credential chain in the account +// being scanned. +func NewFilesystemScanner(ctx context.Context, region string, worker Worker) (*FilesystemScanner, error) { + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region)) + if err != nil { + return nil, fmt.Errorf("load aws config: %w", err) + } + return &FilesystemScanner{ + EFS: efs.NewFromConfig(cfg), + EC2: ec2.NewFromConfig(cfg), + Region: region, + Worker: worker, + }, nil +} + +// Scan reads each EFS reference once and calls write after it is unmounted. +func (s *FilesystemScanner) Scan(ctx context.Context, uses []workload.FilesystemUse, write func(FilesystemResult) error) error { + if s.EFS == nil || s.EC2 == nil || s.Mount == nil || s.Walk == nil { + return fmt.Errorf("filesystem scan is missing an EFS client, mount, or package walker") + } + if s.Worker.InstanceID == "" || s.Region == "" { + return fmt.Errorf("worker instance id and region are required") + } + vpc, err := s.workerVPC(ctx) + if err != nil { + return err + } + timeout := s.Timeout + if timeout <= 0 { + timeout = 10 * time.Minute + } + var failed []error + for _, ref := range workload.FilesystemRefs(uses, workload.KindEFS) { + ictx, cancel := context.WithTimeout(ctx, timeout) + res, scanErr := s.scanOne(ictx, ref, vpc, uses) + cancel() + if scanErr != nil { + failed = append(failed, scanErr) + continue + } + if write != nil { + if err := write(res); err != nil { + failed = append(failed, fmt.Errorf("%s: %w", ref, err)) + } + } + } + return errors.Join(failed...) +} + +func (s *FilesystemScanner) scanOne(ctx context.Context, ref, vpc string, uses []workload.FilesystemUse) (FilesystemResult, error) { + res := FilesystemResult{Ref: ref} + res.WorkloadIDs, res.Names = workload.FilesystemWorkloads(uses, ref) + id, ok := workload.ParseEFS(ref) + if !ok { + res.Skipped = "not an EFS filesystem" + return res, nil + } + _, err := s.EFS.DescribeFileSystems(ctx, &efs.DescribeFileSystemsInput{FileSystemId: aws.String(id)}) + if err != nil { + if notFound(err) { + res.Skipped = "not in this account" + return res, nil + } + return FilesystemResult{}, fmt.Errorf("%s: describe file system: %w", ref, err) + } + inVPC, err := s.mountTargetInVPC(ctx, id, vpc) + if err != nil { + return FilesystemResult{}, fmt.Errorf("%s: %w", ref, err) + } + if !inVPC { + res.Skipped = "no mount target in this VPC" + return res, nil + } + if s.OnStart != nil { + s.OnStart(ref) + } + root, cleanup, err := s.Mount(ctx, efsDNS(id, s.Region)) + if err != nil { + return FilesystemResult{}, fmt.Errorf("%s: %w", ref, err) + } + defer cleanup() + pkgs, err := s.Walk(root) + if err != nil { + if reason, ok := workload.Reason(err); ok { + res.Skipped = reason + return res, nil + } + return FilesystemResult{}, fmt.Errorf("%s: %w", ref, err) + } + res.Packages = pkgs + return res, nil +} + +func (s *FilesystemScanner) workerVPC(ctx context.Context) (string, error) { + out, err := s.EC2.DescribeInstances(ctx, &ec2.DescribeInstancesInput{InstanceIds: []string{s.Worker.InstanceID}}) + if err != nil { + return "", fmt.Errorf("describe worker: %w", err) + } + for _, reservation := range out.Reservations { + for _, inst := range reservation.Instances { + if aws.ToString(inst.InstanceId) == s.Worker.InstanceID && aws.ToString(inst.VpcId) != "" { + return aws.ToString(inst.VpcId), nil + } + } + } + return "", fmt.Errorf("worker %s has no VPC", s.Worker.InstanceID) +} + +func (s *FilesystemScanner) mountTargetInVPC(ctx context.Context, id, vpc string) (bool, error) { + input := &efs.DescribeMountTargetsInput{FileSystemId: aws.String(id)} + for { + page, err := s.EFS.DescribeMountTargets(ctx, input) + if err != nil { + return false, fmt.Errorf("describe mount targets: %w", err) + } + for _, target := range page.MountTargets { + if target.LifeCycleState == efstypes.LifeCycleStateAvailable && aws.ToString(target.VpcId) == vpc { + return true, nil + } + } + if page.NextMarker == nil || aws.ToString(page.NextMarker) == "" { + return false, nil + } + input.Marker = page.NextMarker + } +} + +func efsDNS(id, region string) string { + suffix := "amazonaws.com" + if len(region) >= 3 && region[:3] == "cn-" { + suffix = "amazonaws.com.cn" + } + return id + ".efs." + region + "." + suffix + ":/" +} + +func notFound(err error) bool { + var apiErr smithy.APIError + return errors.As(err, &apiErr) && apiErr.ErrorCode() == "FileSystemNotFound" +} diff --git a/internal/workload/aws/fs_test.go b/internal/workload/aws/fs_test.go new file mode 100644 index 0000000..79c403d --- /dev/null +++ b/internal/workload/aws/fs_test.go @@ -0,0 +1,123 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package aws + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/OpenSourceOM/core/internal/workload" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/aws/aws-sdk-go-v2/service/efs" + efstypes "github.com/aws/aws-sdk-go-v2/service/efs/types" + "github.com/aws/smithy-go" +) + +func TestFilesystemScanMountsOnceInTheWorkerVPC(t *testing.T) { + var mounted []string + scanner := &FilesystemScanner{ + EFS: &fakeEFS{systems: map[string]string{"fs-aaaaaaaa": "vpc-prod"}, missing: map[string]bool{"fs-bbbbbbbb": true}}, + EC2: &fakeVPC{vpc: "vpc-prod"}, + Region: "us-east-1", + Worker: Worker{InstanceID: "i-worker"}, + Mount: func(ctx context.Context, source string) (string, func() error, error) { + mounted = append(mounted, source) + return t.TempDir(), func() error { return nil }, nil + }, + Walk: func(string) ([]string, error) { + return []string{"pkg:npm/left-pad@1.2.3"}, nil + }, + } + uses := []workload.FilesystemUse{ + {WorkloadID: "web", Name: "web", Refs: []string{"efs:fs-aaaaaaaa", "nfs:10.0.0.5/vol1"}}, + {WorkloadID: "api", Name: "api", Refs: []string{"efs:fs-aaaaaaaa"}}, + {WorkloadID: "old", Name: "old", Refs: []string{"efs:fs-bbbbbbbb"}}, + {WorkloadID: "other", Name: "other", Refs: []string{"efs:fs-cccccccc"}}, + } + fake := scanner.EFS.(*fakeEFS) + fake.systems["fs-cccccccc"] = "vpc-other" + + var got []FilesystemResult + if err := scanner.Scan(context.Background(), uses, func(res FilesystemResult) error { + got = append(got, res) + return nil + }); err != nil { + t.Fatal(err) + } + if len(mounted) != 1 || mounted[0] != "fs-aaaaaaaa.efs.us-east-1.amazonaws.com:/" { + t.Fatalf("mounted = %v", mounted) + } + if len(got) != 3 { + t.Fatalf("results = %+v", got) + } + if got[0].Skipped != "" || strings.Join(got[0].WorkloadIDs, ",") != "web,api" || len(got[0].Packages) != 1 { + t.Fatalf("mounted result = %+v", got[0]) + } + if got[1].Ref != "efs:fs-bbbbbbbb" || got[1].Skipped != "not in this account" { + t.Fatalf("missing = %+v", got[1]) + } + if got[2].Ref != "efs:fs-cccccccc" || got[2].Skipped != "no mount target in this VPC" { + t.Fatalf("other vpc = %+v", got[2]) + } +} + +func TestFilesystemScanUnmountsWhenTheWalkFails(t *testing.T) { + unmounted := false + scanner := &FilesystemScanner{ + EFS: &fakeEFS{systems: map[string]string{"fs-aaaaaaaa": "vpc-prod"}}, + EC2: &fakeVPC{vpc: "vpc-prod"}, + Region: "us-east-1", + Worker: Worker{InstanceID: "i-worker"}, + Mount: func(ctx context.Context, source string) (string, func() error, error) { + return t.TempDir(), func() error { unmounted = true; return nil }, nil + }, + Walk: func(string) ([]string, error) { return nil, errors.New("read failed") }, + } + err := scanner.Scan(context.Background(), []workload.FilesystemUse{{ + WorkloadID: "web", Refs: []string{"efs:fs-aaaaaaaa"}, + }}, nil) + if err == nil || !unmounted { + t.Fatalf("err = %v, unmounted = %v", err, unmounted) + } +} + +type fakeEFS struct { + systems map[string]string + missing map[string]bool +} + +func (f *fakeEFS) DescribeFileSystems(ctx context.Context, in *efs.DescribeFileSystemsInput, _ ...func(*efs.Options)) (*efs.DescribeFileSystemsOutput, error) { + id := aws.ToString(in.FileSystemId) + if f.missing[id] { + return nil, &smithy.GenericAPIError{Code: "FileSystemNotFound", Message: "missing"} + } + if _, ok := f.systems[id]; !ok { + return nil, &smithy.GenericAPIError{Code: "FileSystemNotFound", Message: "missing"} + } + return &efs.DescribeFileSystemsOutput{FileSystems: []efstypes.FileSystemDescription{{FileSystemId: aws.String(id)}}}, nil +} + +func (f *fakeEFS) DescribeMountTargets(ctx context.Context, in *efs.DescribeMountTargetsInput, _ ...func(*efs.Options)) (*efs.DescribeMountTargetsOutput, error) { + id := aws.ToString(in.FileSystemId) + return &efs.DescribeMountTargetsOutput{MountTargets: []efstypes.MountTargetDescription{{ + FileSystemId: aws.String(id), + VpcId: aws.String(f.systems[id]), + LifeCycleState: efstypes.LifeCycleStateAvailable, + }}}, nil +} + +type fakeVPC struct { + vpc string +} + +func (f *fakeVPC) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) { + return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{Instances: []ec2types.Instance{{ + InstanceId: aws.String(in.InstanceIds[0]), + VpcId: aws.String(f.vpc), + }}}}}, nil +} diff --git a/internal/workload/aws/image.go b/internal/workload/aws/image.go index 4f39194..7deed82 100644 --- a/internal/workload/aws/image.go +++ b/internal/workload/aws/image.go @@ -44,11 +44,12 @@ type ImageInstance struct { // Packages is the image walk only. A package that exists only on an instance // disk is not included. type ImageResult struct { - ImageID string - Name string - Packages []string - Skipped string - Instances []ImageInstance + ImageID string + Name string + Packages []string + Filesystems []string + Skipped string + Instances []ImageInstance } type bootImage struct { @@ -306,6 +307,7 @@ func (s *Scanner) scanImage(ctx context.Context, item bootImage, instances []ec2 return ImageResult{}, fmt.Errorf("%s: %w", id, err) } res.Packages = pkgs + res.Filesystems = workload.ReadFilesystems(s.Filesystems, root) return res, nil } diff --git a/internal/workload/aws/scan.go b/internal/workload/aws/scan.go index ce7cea4..7b68972 100644 --- a/internal/workload/aws/scan.go +++ b/internal/workload/aws/scan.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/OpenSourceOM/core/internal/workload" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" @@ -69,10 +70,11 @@ type Worker struct { // Result is one instance after the snapshot has been deleted. type Result struct { - InstanceID string - Name string - Packages []string - Skipped string + InstanceID string + Name string + Packages []string + Filesystems []string + Skipped string } // Scanner snapshots Linux root volumes, reads them, and deletes what it created. @@ -81,17 +83,18 @@ type Result struct { // snapshot is shared with. When AccountID is empty, Prod is unused and the // volume is created from the snapshot in the same account as API. type Scanner struct { - API ec2API - Prod ec2API - AccountID string - KMSKeyID string - Worker Worker - Only []string - Timeout time.Duration - Poll time.Duration - Mount func(ctx context.Context, volumeID string) (root string, cleanup func() error, err error) - Walk func(root string) ([]string, error) - OnStart func(instanceID, name string) + API ec2API + Prod ec2API + AccountID string + KMSKeyID string + Worker Worker + Only []string + Timeout time.Duration + Poll time.Duration + Mount func(ctx context.Context, volumeID string) (root string, cleanup func() error, err error) + Walk func(root string) ([]string, error) + Filesystems func(root string) []string + OnStart func(instanceID, name string) cleanupErrs []error } @@ -289,6 +292,7 @@ func (s *Scanner) scanInstance(ctx context.Context, inst, worker ec2types.Instan return Result{}, fmt.Errorf("%s: %w", id, err) } res.Packages = pkgs + res.Filesystems = workload.ReadFilesystems(s.Filesystems, root) return res, nil } diff --git a/internal/workload/azure/fs.go b/internal/workload/azure/fs.go new file mode 100644 index 0000000..571080c --- /dev/null +++ b/internal/workload/azure/fs.go @@ -0,0 +1,201 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package azure + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/v3" + "github.com/OpenSourceOM/core/internal/workload" +) + +// FilesystemPermissions are the Azure RBAC actions for confirming a file share +// a workload already mounts. Creating a private endpoint is not one of them. +var FilesystemPermissions = []string{ + "Microsoft.Storage/storageAccounts/read", + "Microsoft.Storage/storageAccounts/fileServices/shares/read", +} + +// FilesystemResult is one Azure Files share after it has been unmounted. +type FilesystemResult struct { + Ref string + Packages []string + WorkloadIDs []string + Names []string + Skipped string +} + +type shareAPI interface { + Protocol(ctx context.Context, host, share string) (protocol string, ok bool, err error) +} + +// FilesystemScanner mounts Azure Files shares already recorded on workloads. +// It does not create a private endpoint or a firewall rule. +type FilesystemScanner struct { + API shareAPI + Credentials string + Timeout time.Duration + MountNFS func(ctx context.Context, source string) (root string, cleanup func() error, err error) + MountCIFS func(ctx context.Context, source, credentials string) (root string, cleanup func() error, err error) + Walk func(root string) ([]string, error) + OnStart func(ref string) +} + +// NewFilesystemScanner uses the default Azure credential. +func NewFilesystemScanner(subscriptionID string) (*FilesystemScanner, error) { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + return nil, fmt.Errorf("azure credentials: %w", err) + } + accounts, err := armstorage.NewAccountsClient(subscriptionID, cred, nil) + if err != nil { + return nil, err + } + shares, err := armstorage.NewFileSharesClient(subscriptionID, cred, nil) + if err != nil { + return nil, err + } + return &FilesystemScanner{API: &shareClient{accounts: accounts, shares: shares}}, nil +} + +// Scan reads each Azure Files reference once and calls write after it is unmounted. +func (s *FilesystemScanner) Scan(ctx context.Context, uses []workload.FilesystemUse, write func(FilesystemResult) error) error { + if s.API == nil || s.MountNFS == nil || s.MountCIFS == nil || s.Walk == nil { + return fmt.Errorf("filesystem scan is missing a storage client, mount, or package walker") + } + timeout := s.Timeout + if timeout <= 0 { + timeout = 10 * time.Minute + } + var failed []error + for _, ref := range workload.FilesystemRefs(uses, workload.KindAzureFiles) { + ictx, cancel := context.WithTimeout(ctx, timeout) + res, scanErr := s.scanOne(ictx, ref, uses) + cancel() + if scanErr != nil { + failed = append(failed, scanErr) + continue + } + if write != nil { + if err := write(res); err != nil { + failed = append(failed, fmt.Errorf("%s: %w", ref, err)) + } + } + } + return errors.Join(failed...) +} + +func (s *FilesystemScanner) scanOne(ctx context.Context, ref string, uses []workload.FilesystemUse) (FilesystemResult, error) { + res := FilesystemResult{Ref: ref} + res.WorkloadIDs, res.Names = workload.FilesystemWorkloads(uses, ref) + host, share, ok := workload.ParseAzureFiles(ref) + if !ok { + res.Skipped = "not an Azure Files share" + return res, nil + } + protocol, found, err := s.API.Protocol(ctx, host, share) + if err != nil { + return FilesystemResult{}, fmt.Errorf("%s: %w", ref, err) + } + if !found { + res.Skipped = "not in this subscription" + return res, nil + } + nfs := strings.EqualFold(protocol, string(armstorage.EnabledProtocolsNFS)) + if !nfs && s.Credentials == "" { + res.Skipped = "SMB share needs --cifs-credentials" + return res, nil + } + if s.OnStart != nil { + s.OnStart(ref) + } + var root string + var cleanup func() error + if nfs { + account, _, _ := strings.Cut(host, ".") + root, cleanup, err = s.MountNFS(ctx, host+":/"+account+"/"+share) + } else { + root, cleanup, err = s.MountCIFS(ctx, "//"+host+"/"+share, s.Credentials) + } + if err != nil { + return FilesystemResult{}, fmt.Errorf("%s: %w", ref, err) + } + defer cleanup() + pkgs, err := s.Walk(root) + if err != nil { + if reason, ok := workload.Reason(err); ok { + res.Skipped = reason + return res, nil + } + return FilesystemResult{}, fmt.Errorf("%s: %w", ref, err) + } + res.Packages = pkgs + return res, nil +} + +type shareClient struct { + accounts *armstorage.AccountsClient + shares *armstorage.FileSharesClient + groups map[string]string +} + +func (c *shareClient) Protocol(ctx context.Context, host, share string) (string, bool, error) { + if c.groups == nil { + if err := c.load(ctx); err != nil { + return "", false, err + } + } + account, _, _ := strings.Cut(host, ".") + group, ok := c.groups[account] + if !ok { + return "", false, nil + } + resp, err := c.shares.Get(ctx, group, account, share, nil) + if err != nil { + var respErr *azcore.ResponseError + if errors.As(err, &respErr) && respErr.StatusCode == http.StatusNotFound { + return "", false, nil + } + return "", false, fmt.Errorf("get file share: %w", err) + } + protocol := string(armstorage.EnabledProtocolsSMB) + if resp.FileShareProperties != nil && resp.FileShareProperties.EnabledProtocols != nil && *resp.FileShareProperties.EnabledProtocols != "" { + protocol = string(*resp.FileShareProperties.EnabledProtocols) + } + return protocol, true, nil +} + +func (c *shareClient) load(ctx context.Context) error { + c.groups = map[string]string{} + pager := c.accounts.NewListPager(nil) + for pager.More() { + page, err := pager.NextPage(ctx) + if err != nil { + return fmt.Errorf("list storage accounts: %w", err) + } + for _, account := range page.Value { + name := strings.ToLower(deref(account.Name)) + group := resourceGroup(deref(account.ID)) + if name == "" || group == "" { + continue + } + c.groups[name] = group + } + } + return nil +} + +func deref(value *string) string { + if value == nil { + return "" + } + return *value +} diff --git a/internal/workload/azure/fs_test.go b/internal/workload/azure/fs_test.go new file mode 100644 index 0000000..8461f64 --- /dev/null +++ b/internal/workload/azure/fs_test.go @@ -0,0 +1,91 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package azure + +import ( + "context" + "strings" + "testing" + + "github.com/OpenSourceOM/core/internal/workload" +) + +func TestFilesystemScanMountsNFSAndSkipsSMBWithoutCredentials(t *testing.T) { + var mounted []string + scanner := &FilesystemScanner{ + API: fakeShares{"logs.file.core.windows.net/app": "SMB", "store.file.core.windows.net/data": "NFS"}, + MountNFS: func(ctx context.Context, source string) (string, func() error, error) { + mounted = append(mounted, source) + return t.TempDir(), func() error { return nil }, nil + }, + MountCIFS: func(ctx context.Context, source, credentials string) (string, func() error, error) { + t.Fatal("mounted SMB without credentials") + return "", nil, nil + }, + Walk: func(string) ([]string, error) { return []string{"pkg:npm/left-pad@1.2.3"}, nil }, + } + var got []FilesystemResult + err := scanner.Scan(context.Background(), []workload.FilesystemUse{ + {WorkloadID: "web", Name: "web", Refs: []string{"azurefiles:logs.file.core.windows.net/app", "azurefiles:store.file.core.windows.net/data"}}, + {WorkloadID: "old", Refs: []string{"azurefiles:missing.file.core.windows.net/share"}}, + }, func(res FilesystemResult) error { + got = append(got, res) + return nil + }) + if err != nil { + t.Fatal(err) + } + if len(mounted) != 1 || mounted[0] != "store.file.core.windows.net:/store/data" { + t.Fatalf("mounted = %v", mounted) + } + if len(got) != 3 { + t.Fatalf("results = %+v", got) + } + if got[0].Skipped != "SMB share needs --cifs-credentials" { + t.Fatalf("smb = %+v", got[0]) + } + if got[1].Skipped != "not in this subscription" { + t.Fatalf("missing = %+v", got[1]) + } + if got[2].Skipped != "" || strings.Join(got[2].WorkloadIDs, ",") != "web" { + t.Fatalf("nfs = %+v", got[2]) + } +} + +func TestFilesystemScanMountsSMBWithACredentialsFile(t *testing.T) { + var creds string + scanner := &FilesystemScanner{ + API: fakeShares{"logs.file.core.windows.net/app": "SMB"}, + Credentials: "/etc/smbcredentials", + MountNFS: func(context.Context, string) (string, func() error, error) { + t.Fatal("mounted SMB as NFS") + return "", nil, nil + }, + MountCIFS: func(ctx context.Context, source, credentials string) (string, func() error, error) { + creds = source + " " + credentials + return t.TempDir(), func() error { return nil }, nil + }, + Walk: func(string) ([]string, error) { return []string{"pkg:npm/left-pad@1.2.3"}, nil }, + } + if err := scanner.Scan(context.Background(), []workload.FilesystemUse{{ + WorkloadID: "web", Refs: []string{"azurefiles:logs.file.core.windows.net/app"}, + }}, func(res FilesystemResult) error { + if res.Skipped != "" || len(res.Packages) != 1 { + t.Fatalf("result = %+v", res) + } + return nil + }); err != nil { + t.Fatal(err) + } + if creds != "//logs.file.core.windows.net/app /etc/smbcredentials" { + t.Fatalf("cifs = %s", creds) + } +} + +type fakeShares map[string]string + +func (f fakeShares) Protocol(ctx context.Context, host, share string) (string, bool, error) { + protocol, ok := f[host+"/"+share] + return protocol, ok, nil +} diff --git a/internal/workload/azure/image.go b/internal/workload/azure/image.go index 0f1aa8f..e1cf48f 100644 --- a/internal/workload/azure/image.go +++ b/internal/workload/azure/image.go @@ -48,8 +48,9 @@ type BootImage struct { // Packages is the image walk only. type ImageResult struct { BootImage - Packages []string - Skipped string + Packages []string + Filesystems []string + Skipped string } // ImageAPI is the image-disk lifecycle. Create calls wait until the disk is ready. @@ -68,14 +69,15 @@ var _ ImageAPI = (*Client)(nil) // Disk, when set, is the scanner subscription. API lists images in the // subscription being scanned. type ImageScanner struct { - API ImageAPI - Disk ImageAPI - Worker Worker - Only []string - Timeout time.Duration - Mount func(ctx context.Context, lun string) (root string, cleanup func() error, err error) - Walk func(root string) ([]string, error) - OnStart func(key, name string) + API ImageAPI + Disk ImageAPI + Worker Worker + Only []string + Timeout time.Duration + Mount func(ctx context.Context, lun string) (root string, cleanup func() error, err error) + Walk func(root string) ([]string, error) + Filesystems func(root string) []string + OnStart func(key, name string) cleanupErrs []error } @@ -168,6 +170,7 @@ func (s *ImageScanner) scanImage(ctx context.Context, img BootImage, luns []int3 return ImageResult{}, fmt.Errorf("%s: %w", imageLabel(img), err) } res.Packages = pkgs + res.Filesystems = workload.ReadFilesystems(s.Filesystems, root) return res, nil } diff --git a/internal/workload/azure/scan.go b/internal/workload/azure/scan.go index 2259621..d3694b5 100644 --- a/internal/workload/azure/scan.go +++ b/internal/workload/azure/scan.go @@ -82,6 +82,7 @@ type Result struct { Name string ResourceGroup string Packages []string + Filesystems []string Skipped string } @@ -111,6 +112,7 @@ type Scanner struct { Timeout time.Duration Mount func(ctx context.Context, lun string) (root string, cleanup func() error, err error) Walk func(root string) ([]string, error) + Filesystems func(root string) []string OnStart func(name, group string) cleanupErrs []error @@ -240,6 +242,7 @@ func (s *Scanner) scanVM(ctx context.Context, vm Machine, luns []int32) (Result, return Result{}, fmt.Errorf("%s: %w", vmLabel(res), err) } res.Packages = pkgs + res.Filesystems = workload.ReadFilesystems(s.Filesystems, root) return res, nil } diff --git a/internal/workload/fs.go b/internal/workload/fs.go new file mode 100644 index 0000000..5e12388 --- /dev/null +++ b/internal/workload/fs.go @@ -0,0 +1,588 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "bufio" + "context" + "fmt" + "io" + "io/fs" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" +) + +const ( + // KindEFS is an Amazon EFS filesystem id. + KindEFS = "efs" + // KindAzureFiles is an Azure Files host and share. + KindAzureFiles = "azurefiles" + // KindNFS is a private NFS address and export, confirmed as Filestore before a mount. + KindNFS = "nfs" + + maxFSEntries = 100000 +) + +// FilesystemUse is one workload and the shared filesystems recorded on it. +type FilesystemUse struct { + WorkloadID string + Name string + Refs []string +} + +// ReadFilesystems calls read while the root is still mounted. +// A nil read leaves the stored list unchanged. A read that returns nil stores +// an empty list, which clears mounts the root no longer has. +func ReadFilesystems(read func(string) []string, root string) []string { + if read == nil { + return nil + } + refs := read(root) + if refs == nil { + return []string{} + } + return refs +} + +// SharedFilesystems reads fstab and systemd mount units. It returns EFS, +// Azure Files, and private NFS references. Other files are not opened. +func SharedFilesystems(root string) []string { + var refs []string + refs = append(refs, fstabRefs(filepath.Join(root, "etc", "fstab"))...) + for _, dir := range []string{ + filepath.Join(root, "etc", "systemd", "system"), + filepath.Join(root, "usr", "lib", "systemd", "system"), + filepath.Join(root, "lib", "systemd", "system"), + } { + refs = append(refs, systemdRefs(dir)...) + } + return uniqueSorted(refs) +} + +// FilesystemRefs returns the sorted unique references of kind. +func FilesystemRefs(uses []FilesystemUse, kind string) []string { + prefix := kind + ":" + var refs []string + for _, use := range uses { + for _, ref := range use.Refs { + if strings.HasPrefix(ref, prefix) { + refs = append(refs, ref) + } + } + } + return uniqueSorted(refs) +} + +// FilesystemWorkloads returns the workloads that list ref. +func FilesystemWorkloads(uses []FilesystemUse, ref string) (ids, names []string) { + for _, use := range uses { + for _, candidate := range use.Refs { + if candidate == ref { + ids = append(ids, use.WorkloadID) + names = append(names, use.Name) + break + } + } + } + return ids, names +} + +// ParseEFS returns the filesystem id for an efs reference. +func ParseEFS(ref string) (string, bool) { + kind, rest, ok := strings.Cut(ref, ":") + if !ok || kind != KindEFS { + return "", false + } + return efsID(rest) +} + +// ParseAzureFiles returns the host and share for an azurefiles reference. +func ParseAzureFiles(ref string) (host, share string, ok bool) { + kind, rest, found := strings.Cut(ref, ":") + if !found || kind != KindAzureFiles { + return "", "", false + } + host, share, found = strings.Cut(rest, "/") + if !found || !azureFilesHost(host) || !shareName(share) || strings.Contains(share, "/") { + return "", "", false + } + return host, share, true +} + +// ParseNFS returns the address and export for an nfs reference. +func ParseNFS(ref string) (ip, share string, ok bool) { + kind, rest, found := strings.Cut(ref, ":") + if !found || kind != KindNFS { + return "", "", false + } + ip, share, found = strings.Cut(rest, "/") + if !found || !privateIPv4(ip) || !shareName(share) { + return "", "", false + } + return ip, share, true +} + +// WalkFS reads package databases at the mount root and language package +// metadata anywhere under it. Other file bodies are not read. +func WalkFS(root string) ([]string, error) { + root = filepath.Clean(root) + var ids []string + if HasPackageDB(root) { + got, err := Walk(root) + if err != nil && err != ErrNoPackages { + return nil, err + } + ids = append(ids, got...) + } + visited := 0 + interestingCount := 0 + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.IsDir() { + return nil + } + if entry.Type()&os.ModeSymlink != 0 { + return nil + } + rel, err := filepath.Rel(root, path) + if err != nil || rel == "." || strings.HasPrefix(rel, "..") { + return nil + } + rel = filepath.ToSlash(rel) + visited++ + if visited > maxFSEntries { + return fmt.Errorf("filesystem has more than %d entries", maxFSEntries) + } + if !interesting(rel) || isPackageDB(rel) || isOSRelease(rel) { + return nil + } + if interestingCount >= maxInterestingFile { + return fmt.Errorf("more than %d package files", maxInterestingFile) + } + info, err := entry.Info() + if err != nil { + return nil + } + found, err := languageIDsFromFile(path, rel, info.Size()) + if err != nil { + return err + } + if len(found) == 0 { + return nil + } + interestingCount++ + ids = append(ids, found...) + return nil + }) + if err != nil { + return nil, err + } + ids = uniqueSorted(ids) + if len(ids) == 0 { + return nil, ErrNoPackages + } + return ids, nil +} + +func languageIDsFromFile(path, rel string, size int64) ([]string, error) { + f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return nil, nil + } + defer f.Close() + if isJar(rel) { + return mavenIDsFromJar(f, size) + } + if size > maxMetaBytes { + return nil, nil + } + body, err := io.ReadAll(io.LimitReader(f, maxMetaBytes+1)) + if err != nil { + return nil, err + } + if int64(len(body)) > maxMetaBytes { + return nil, nil + } + return languageIDsFromMeta(rel, body), nil +} + +// MountReadOnlyNFS mounts source read-only. It does not add a route or export. +func MountReadOnlyNFS(ctx context.Context, source string) (string, func() error, error) { + return mountNetwork(ctx, source, []mountSpec{ + {"nfs4", "ro,noexec,nosuid,nodev,soft,timeo=50,retrans=2"}, + {"nfs", "ro,noexec,nosuid,nodev,vers=4,minorversion=1,soft,timeo=50,retrans=2"}, + {"nfs", "ro,noexec,nosuid,nodev,vers=3,soft,timeo=50,retrans=2"}, + }) +} + +// MountReadOnlyCIFS mounts source read-only with a credentials file. +// The file is not read here. mount reads it, and the path is not stored. +func MountReadOnlyCIFS(ctx context.Context, source, credentials string) (string, func() error, error) { + opts, err := cifsOptions(credentials) + if err != nil { + return "", nil, err + } + return mountNetwork(ctx, source, []mountSpec{{"cifs", opts}}) +} + +type mountSpec struct { + fsType string + opts string +} + +func mountNetwork(ctx context.Context, source string, tries []mountSpec) (string, func() error, error) { + if err := safeMountSource(source); err != nil { + return "", nil, err + } + target, err := os.MkdirTemp("", "om-fs-") + if err != nil { + return "", nil, err + } + var last error + for _, try := range tries { + cmd := exec.CommandContext(ctx, "mount", "-t", try.fsType, "-o", try.opts, source, target) + out, runErr := cmd.CombinedOutput() + if runErr == nil { + return target, func() error { return cleanupMount(target, Unmount) }, nil + } + text := strings.TrimSpace(string(out)) + if text == "" { + text = runErr.Error() + } + last = fmt.Errorf("mount %s: %s", source, text) + } + os.RemoveAll(target) + if last == nil { + last = fmt.Errorf("mount %s failed", source) + } + return "", nil, last +} + +func safeMountSource(source string) error { + if source == "" || strings.HasPrefix(source, "-") || strings.ContainsAny(source, " ,\t\r\n") { + return fmt.Errorf("refusing to mount %q", source) + } + return nil +} + +func cifsOptions(credentials string) (string, error) { + if credentials == "" || !filepath.IsAbs(credentials) { + return "", fmt.Errorf("SMB credentials file must be an absolute path") + } + if strings.ContainsAny(credentials, ", \t\r\n") || strings.HasPrefix(filepath.Base(credentials), "-") { + return "", fmt.Errorf("SMB credentials path cannot contain a comma, whitespace, or a dash-prefixed name") + } + return "ro,noexec,nosuid,nodev,credentials=" + credentials, nil +} + +func fstabRefs(path string) []string { + body, err := readMountFile(path) + if err != nil { + return nil + } + var refs []string + for _, line := range strings.Split(string(body), "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + fields := splitFstab(line) + if len(fields) < 3 { + continue + } + options := "" + if len(fields) >= 4 { + options = fields[3] + } + if hasBind(options) { + continue + } + if ref, ok := filesystemRef(fields[0], fields[2]); ok { + refs = append(refs, ref) + } + } + return refs +} + +func systemdRefs(dir string) []string { + entries, err := readMountDir(dir) + if err != nil { + return nil + } + var refs []string + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".mount") { + continue + } + body, err := readMountFile(filepath.Join(dir, entry.Name())) + if err != nil { + continue + } + what, fsType, options := systemdMount(body) + if what == "" || hasBind(options) { + continue + } + if ref, ok := filesystemRef(what, fsType); ok { + refs = append(refs, ref) + } + } + return refs +} + +func systemdMount(body []byte) (what, fsType, options string) { + sc := bufio.NewScanner(strings.NewReader(string(body))) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + switch strings.TrimSpace(key) { + case "What": + what = strings.TrimSpace(value) + case "Type": + fsType = strings.TrimSpace(value) + case "Options": + options = strings.TrimSpace(value) + } + } + return what, fsType, options +} + +func readMountFile(path string) ([]byte, error) { + f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return nil, err + } + defer f.Close() + body, err := io.ReadAll(io.LimitReader(f, maxMetaBytes+1)) + if err != nil { + return nil, err + } + if int64(len(body)) > maxMetaBytes { + return nil, fmt.Errorf("%s is larger than %d bytes", filepath.Base(path), maxMetaBytes) + } + return body, nil +} + +func readMountDir(path string) ([]os.DirEntry, error) { + info, err := os.Lstat(path) + if err != nil { + return nil, err + } + if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() { + return nil, os.ErrNotExist + } + return os.ReadDir(path) +} + +func filesystemRef(spec, fsType string) (string, bool) { + spec = strings.TrimSpace(spec) + fsType = strings.ToLower(strings.TrimSpace(fsType)) + if rejectedSpec(spec) { + return "", false + } + if host, share, ok := azureUNC(spec); ok { + return kindAzure(host, share), true + } + host, export, ok := splitHostExport(spec) + if !ok { + if id, ok := efsID(spec); ok { + return KindEFS + ":" + id, true + } + return "", false + } + if id, ok := efsID(host); ok { + return KindEFS + ":" + id, true + } + if azureFilesHost(host) { + share := lastSegment(export) + if share == "" { + return "", false + } + return kindAzure(host, share), true + } + if privateIPv4(host) && (fsType == "" || fsType == "nfs" || fsType == "nfs4") { + share := firstSegment(export) + if share == "" { + return "", false + } + return KindNFS + ":" + host + "/" + share, true + } + return "", false +} + +func kindAzure(host, share string) string { + return KindAzureFiles + ":" + strings.ToLower(host) + "/" + strings.ToLower(share) +} + +func rejectedSpec(spec string) bool { + if spec == "" || spec == "none" { + return true + } + lower := strings.ToLower(spec) + switch { + case strings.HasPrefix(lower, "uuid="), + strings.HasPrefix(lower, "label="), + strings.HasPrefix(lower, "/dev/"), + strings.HasPrefix(lower, "tmpfs"), + strings.HasPrefix(lower, "overlay"), + strings.HasPrefix(lower, "proc"), + strings.HasPrefix(lower, "sysfs"), + strings.HasPrefix(lower, "devpts"), + strings.HasPrefix(lower, "devtmpfs"), + strings.HasPrefix(lower, "squashfs"): + return true + default: + return false + } +} + +func azureUNC(spec string) (host, share string, ok bool) { + spec = strings.ReplaceAll(spec, `\`, `/`) + if !strings.HasPrefix(spec, "//") { + return "", "", false + } + rest := strings.TrimPrefix(spec, "//") + host, share, ok = strings.Cut(rest, "/") + if !ok || !azureFilesHost(host) || !shareName(share) || strings.Contains(share, "/") { + return "", "", false + } + return strings.ToLower(host), strings.ToLower(share), true +} + +func azureFilesHost(host string) bool { + host = strings.ToLower(strings.TrimSuffix(host, ".")) + for _, suffix := range []string{ + ".file.core.windows.net", + ".file.core.usgovcloudapi.net", + ".file.core.chinacloudapi.cn", + ".file.core.cloudapi.de", + } { + if strings.HasSuffix(host, suffix) { + label, _, ok := strings.Cut(host, ".") + return ok && shareName(label) + } + } + return false +} + +func splitHostExport(spec string) (host, export string, ok bool) { + if strings.HasPrefix(spec, "//") || strings.HasPrefix(spec, `\\`) { + return "", "", false + } + host, export, ok = strings.Cut(spec, ":") + if !ok || host == "" || strings.Contains(host, ":") { + return "", "", false + } + return host, export, true +} + +func efsID(host string) (string, bool) { + host = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), ".")) + if i := strings.Index(host, ".efs."); i > 0 { + host = host[:i] + } + if !strings.HasPrefix(host, "fs-") { + return "", false + } + hexPart := strings.TrimPrefix(host, "fs-") + if len(hexPart) != 8 && len(hexPart) != 17 { + return "", false + } + for _, r := range hexPart { + if (r < '0' || r > '9') && (r < 'a' || r > 'f') { + return "", false + } + } + return host, true +} + +func privateIPv4(host string) bool { + ip := net.ParseIP(host).To4() + if ip == nil { + return false + } + return ip[0] == 10 || (ip[0] == 172 && ip[1]&0xf0 == 16) || (ip[0] == 192 && ip[1] == 168) +} + +func firstSegment(export string) string { + export = strings.Trim(export, "/") + if export == "" || strings.Contains(export, "..") { + return "" + } + segment, _, _ := strings.Cut(export, "/") + if !shareName(segment) { + return "" + } + return segment +} + +func lastSegment(export string) string { + export = strings.Trim(export, "/") + if export == "" || strings.Contains(export, "..") { + return "" + } + if i := strings.LastIndex(export, "/"); i >= 0 { + export = export[i+1:] + } + if !shareName(export) { + return "" + } + return strings.ToLower(export) +} + +func shareName(name string) bool { + if name == "" || name == "." || name == ".." || strings.ContainsAny(name, " \\/?#") { + return false + } + return true +} + +func hasBind(options string) bool { + for _, opt := range strings.Split(options, ",") { + switch strings.TrimSpace(opt) { + case "bind", "rbind": + return true + } + } + return false +} + +func splitFstab(line string) []string { + var fields []string + var b strings.Builder + for i := 0; i < len(line); { + if line[i] == '\\' && i+3 < len(line) && isOctal(line[i+1]) && isOctal(line[i+2]) && isOctal(line[i+3]) { + value := (line[i+1]-'0')*64 + (line[i+2]-'0')*8 + (line[i+3] - '0') + b.WriteByte(value) + i += 4 + continue + } + if line[i] == ' ' || line[i] == '\t' { + if b.Len() > 0 { + fields = append(fields, b.String()) + b.Reset() + } + i++ + continue + } + b.WriteByte(line[i]) + i++ + } + if b.Len() > 0 { + fields = append(fields, b.String()) + } + return fields +} + +func isOctal(b byte) bool { + return b >= '0' && b <= '7' +} diff --git a/internal/workload/fs_test.go b/internal/workload/fs_test.go new file mode 100644 index 0000000..c10319b --- /dev/null +++ b/internal/workload/fs_test.go @@ -0,0 +1,129 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestSharedFilesystemsReadsFstabAndSystemd(t *testing.T) { + root := t.TempDir() + mustWrite(t, filepath.Join(root, "etc", "fstab"), ` +UUID=abc / ext4 defaults 0 0 +fs-0123456789abcdef0.efs.us-east-1.amazonaws.com:/ /mnt/efs nfs4 nfsvers=4.1 0 0 +fs-aaaaaaaa:/ /mnt/efs2 efs _netdev 0 0 +//Logs.file.core.windows.net/App /mnt/azure cifs vers=3.0 0 0 +store.file.core.windows.net:/store/data /mnt/nfs nfs vers=4,minorversion=1 0 0 +10.1.2.3:/vol1/app /mnt/filestore nfs defaults 0 0 +10.1.2.3:/vol1 /mnt/again nfs defaults 0 0 +8.8.8.8:/public /mnt/no nfs defaults 0 0 +/dev/nvme1n1 /data xfs defaults 0 0 +/mnt/efs /srv none bind 0 0 +`) + mustWrite(t, filepath.Join(root, "etc", "systemd", "system", "data.mount"), ` +[Mount] +What=fs-bbbbbbbb.efs.eu-west-1.amazonaws.com:/ +Where=/srv/data +Type=nfs4 +Options=ro +`) + mustWrite(t, filepath.Join(root, "usr", "lib", "systemd", "system", "bind.mount"), ` +[Mount] +What=/mnt/efs +Where=/srv +Type=none +Options=bind +`) + + got := SharedFilesystems(root) + want := []string{ + "azurefiles:logs.file.core.windows.net/app", + "azurefiles:store.file.core.windows.net/data", + "efs:fs-0123456789abcdef0", + "efs:fs-aaaaaaaa", + "efs:fs-bbbbbbbb", + "nfs:10.1.2.3/vol1", + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Fatalf("filesystems = %v", got) + } +} + +func TestWalkFSReadsPackageMetadataOnly(t *testing.T) { + root := t.TempDir() + mustWrite(t, filepath.Join(root, "var", "lib", "dpkg", "status"), ` +Package: openssl +Status: install ok installed +Architecture: amd64 +Version: 1.1.1n-0ubuntu1 + +`) + mustWrite(t, filepath.Join(root, "etc", "os-release"), "ID=ubuntu\nVERSION_ID=20.04\n") + mustWrite(t, filepath.Join(root, "app", "node_modules", "left-pad", "package.json"), `{"name":"left-pad","version":"1.2.3"}`) + mustWrite(t, filepath.Join(root, "notes.txt"), "customer record pkg:deb/ubuntu/secret@1.0\n") + + got, err := WalkFS(root) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(got, "\n") + if !strings.Contains(joined, "pkg:npm/left-pad@1.2.3") { + t.Fatalf("missing npm package: %s", joined) + } + if !strings.Contains(joined, "pkg:deb/ubuntu/openssl@1.1.1n-0ubuntu1") { + t.Fatalf("missing dpkg package: %s", joined) + } + if strings.Contains(joined, "secret") { + t.Fatalf("customer file was inventoried: %s", joined) + } +} + +func TestWalkFSEmpty(t *testing.T) { + root := t.TempDir() + mustWrite(t, filepath.Join(root, "notes.txt"), "no packages here\n") + if _, err := WalkFS(root); err != ErrNoPackages { + t.Fatalf("err = %v", err) + } +} + +func TestCIFSOptionsRejectsARelativePath(t *testing.T) { + if _, err := cifsOptions("creds"); err == nil { + t.Fatal("accepted a relative credentials path") + } + opts, err := cifsOptions("/etc/smbcredentials") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(opts, "credentials=/etc/smbcredentials") || !strings.Contains(opts, "ro") { + t.Fatalf("options = %s", opts) + } +} + +func TestFilesystemWorkloadsGroupsASharedRef(t *testing.T) { + uses := []FilesystemUse{ + {WorkloadID: "web", Name: "web", Refs: []string{"efs:fs-aaaaaaaa", "nfs:10.0.0.5/vol1"}}, + {WorkloadID: "api", Name: "api", Refs: []string{"efs:fs-aaaaaaaa"}}, + } + refs := FilesystemRefs(uses, KindEFS) + if len(refs) != 1 || refs[0] != "efs:fs-aaaaaaaa" { + t.Fatalf("refs = %v", refs) + } + ids, names := FilesystemWorkloads(uses, "efs:fs-aaaaaaaa") + if strings.Join(ids, ",") != "web,api" || strings.Join(names, ",") != "web,api" { + t.Fatalf("workloads = %v %v", ids, names) + } +} + +func mustWrite(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } +} diff --git a/internal/workload/gcp/fs.go b/internal/workload/gcp/fs.go new file mode 100644 index 0000000..2f2fb07 --- /dev/null +++ b/internal/workload/gcp/fs.go @@ -0,0 +1,212 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package gcp + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "cloud.google.com/go/compute/metadata" + "github.com/OpenSourceOM/core/internal/workload" + "google.golang.org/api/file/v1" + "google.golang.org/api/option" +) + +// FilesystemPermissions are the IAM permissions for listing Filestore the +// workloads already mount. Updating an authorized network is not one of them. +var FilesystemPermissions = []string{ + "file.instances.list", +} + +// FilesystemResult is one Filestore export after it has been unmounted. +type FilesystemResult struct { + Ref string + Packages []string + WorkloadIDs []string + Names []string + Skipped string +} + +// FilestoreShare is one export on a Filestore instance. +type FilestoreShare struct { + IP string + Share string + Network string +} + +type filestoreAPI interface { + List(ctx context.Context) ([]FilestoreShare, error) +} + +// FilesystemScanner mounts Filestore exports already recorded on workloads. +// It does not add the worker's VPC to the instance. +type FilesystemScanner struct { + API filestoreAPI + WorkerNetwork string + Timeout time.Duration + Mount func(ctx context.Context, source string) (root string, cleanup func() error, err error) + Walk func(root string) ([]string, error) + OnStart func(ref string) +} + +// NewFilesystemScanner uses application default credentials. +func NewFilesystemScanner(ctx context.Context, projectID, network string) (*FilesystemScanner, error) { + svc, err := file.NewService(ctx, option.WithScopes(file.CloudPlatformScope)) + if err != nil { + return nil, fmt.Errorf("filestore client: %w", err) + } + return &FilesystemScanner{ + API: &fileClient{svc: svc, project: projectID}, + WorkerNetwork: network, + }, nil +} + +// LookupNetwork reads the VPC of the instance this command runs on. +func LookupNetwork(ctx context.Context) (string, error) { + if !metadata.OnGCEWithContext(ctx) { + return "", fmt.Errorf("om scan workload fs gcp runs on a GCE instance in the project being scanned") + } + network, err := metadata.GetWithContext(ctx, "instance/network-interfaces/0/network") + if err != nil { + return "", fmt.Errorf("read VPC network: %w", err) + } + network = strings.TrimSpace(network) + if networkName(network) == "" { + return "", fmt.Errorf("instance metadata is missing the VPC network") + } + return network, nil +} + +// Scan reads each Filestore reference once and calls write after it is unmounted. +func (s *FilesystemScanner) Scan(ctx context.Context, uses []workload.FilesystemUse, write func(FilesystemResult) error) error { + if s.API == nil || s.Mount == nil || s.Walk == nil { + return fmt.Errorf("filesystem scan is missing a Filestore client, mount, or package walker") + } + if networkName(s.WorkerNetwork) == "" { + return fmt.Errorf("worker VPC network is required") + } + shares, err := s.API.List(ctx) + if err != nil { + return err + } + timeout := s.Timeout + if timeout <= 0 { + timeout = 10 * time.Minute + } + var failed []error + for _, ref := range workload.FilesystemRefs(uses, workload.KindNFS) { + ictx, cancel := context.WithTimeout(ctx, timeout) + res, scanErr := s.scanOne(ictx, ref, uses, shares) + cancel() + if scanErr != nil { + failed = append(failed, scanErr) + continue + } + if write != nil { + if err := write(res); err != nil { + failed = append(failed, fmt.Errorf("%s: %w", ref, err)) + } + } + } + return errors.Join(failed...) +} + +func (s *FilesystemScanner) scanOne(ctx context.Context, ref string, uses []workload.FilesystemUse, shares []FilestoreShare) (FilesystemResult, error) { + res := FilesystemResult{Ref: ref} + res.WorkloadIDs, res.Names = workload.FilesystemWorkloads(uses, ref) + ip, share, ok := workload.ParseNFS(ref) + if !ok { + res.Skipped = "not an NFS export" + return res, nil + } + match, found := findShare(shares, ip, share) + if !found { + res.Skipped = "not a Filestore instance" + return res, nil + } + if !sameVPC(s.WorkerNetwork, match.Network) { + res.Skipped = "Filestore is on another VPC" + return res, nil + } + if s.OnStart != nil { + s.OnStart(ref) + } + root, cleanup, err := s.Mount(ctx, match.IP+":/"+match.Share) + if err != nil { + return FilesystemResult{}, fmt.Errorf("%s: %w", ref, err) + } + defer cleanup() + pkgs, err := s.Walk(root) + if err != nil { + if reason, ok := workload.Reason(err); ok { + res.Skipped = reason + return res, nil + } + return FilesystemResult{}, fmt.Errorf("%s: %w", ref, err) + } + res.Packages = pkgs + return res, nil +} + +func findShare(shares []FilestoreShare, ip, share string) (FilestoreShare, bool) { + for _, item := range shares { + if item.IP == ip && strings.EqualFold(item.Share, share) { + return item, true + } + } + return FilestoreShare{}, false +} + +func sameVPC(worker, filestore string) bool { + name := networkName(worker) + return name != "" && name == networkName(filestore) +} + +func networkName(value string) string { + value = strings.Trim(strings.TrimSpace(value), "/") + if value == "" { + return "" + } + if i := strings.LastIndex(value, "/"); i >= 0 { + value = value[i+1:] + } + return value +} + +type fileClient struct { + svc *file.Service + project string +} + +func (c *fileClient) List(ctx context.Context) ([]FilestoreShare, error) { + var out []FilestoreShare + err := c.svc.Projects.Locations.Instances.List("projects/"+c.project+"/locations/-").Pages(ctx, func(resp *file.ListInstancesResponse) error { + for _, inst := range resp.Instances { + for _, share := range inst.FileShares { + if share == nil || share.Name == "" { + continue + } + for _, network := range inst.Networks { + if network == nil { + continue + } + for _, ip := range network.IpAddresses { + if ip == "" { + continue + } + out = append(out, FilestoreShare{IP: ip, Share: share.Name, Network: network.Network}) + } + } + } + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("list filestore instances: %w", err) + } + return out, nil +} diff --git a/internal/workload/gcp/fs_test.go b/internal/workload/gcp/fs_test.go new file mode 100644 index 0000000..e9b1d89 --- /dev/null +++ b/internal/workload/gcp/fs_test.go @@ -0,0 +1,62 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package gcp + +import ( + "context" + "testing" + + "github.com/OpenSourceOM/core/internal/workload" +) + +func TestFilesystemScanSkipsAnotherVPC(t *testing.T) { + var mounted []string + scanner := &FilesystemScanner{ + API: fakeFilestore{shares: []FilestoreShare{ + {IP: "10.1.2.3", Share: "vol1", Network: "projects/prod/global/networks/app"}, + {IP: "10.9.9.9", Share: "other", Network: "projects/prod/global/networks/other"}, + }}, + WorkerNetwork: "projects/123/networks/app", + Mount: func(ctx context.Context, source string) (string, func() error, error) { + mounted = append(mounted, source) + return t.TempDir(), func() error { return nil }, nil + }, + Walk: func(string) ([]string, error) { return []string{"pkg:npm/left-pad@1.2.3"}, nil }, + } + var got []FilesystemResult + err := scanner.Scan(context.Background(), []workload.FilesystemUse{{ + WorkloadID: "web", + Name: "web", + Refs: []string{"nfs:10.1.2.3/vol1", "nfs:10.9.9.9/other", "nfs:10.8.8.8/gone", "efs:fs-aaaaaaaa"}, + }}, func(res FilesystemResult) error { + got = append(got, res) + return nil + }) + if err != nil { + t.Fatal(err) + } + if len(mounted) != 1 || mounted[0] != "10.1.2.3:/vol1" { + t.Fatalf("mounted = %v", mounted) + } + if len(got) != 3 { + t.Fatalf("results = %+v", got) + } + if got[0].Skipped != "" || len(got[0].Packages) != 1 || got[0].WorkloadIDs[0] != "web" { + t.Fatalf("mounted result = %+v", got[0]) + } + if got[1].Skipped != "not a Filestore instance" { + t.Fatalf("missing = %+v", got[1]) + } + if got[2].Skipped != "Filestore is on another VPC" { + t.Fatalf("other vpc = %+v", got[2]) + } +} + +type fakeFilestore struct { + shares []FilestoreShare +} + +func (f fakeFilestore) List(context.Context) ([]FilestoreShare, error) { + return f.shares, nil +} diff --git a/internal/workload/gcp/image.go b/internal/workload/gcp/image.go index dcfef07..830c0c0 100644 --- a/internal/workload/gcp/image.go +++ b/internal/workload/gcp/image.go @@ -48,8 +48,9 @@ type BootImage struct { // Packages is the image walk only. type ImageResult struct { BootImage - Packages []string - Skipped string + Packages []string + Filesystems []string + Skipped string } // ImageAPI is the image-disk lifecycle. Create calls wait until the disk is ready. @@ -68,14 +69,15 @@ var _ ImageAPI = (*Client)(nil) // Disk, when set, is the scanner project. API lists images in the project // being scanned. type ImageScanner struct { - API ImageAPI - Disk ImageAPI - Worker Worker - Only []string - Timeout time.Duration - Mount func(ctx context.Context, device string) (root string, cleanup func() error, err error) - Walk func(root string) ([]string, error) - OnStart func(link, name string) + API ImageAPI + Disk ImageAPI + Worker Worker + Only []string + Timeout time.Duration + Mount func(ctx context.Context, device string) (root string, cleanup func() error, err error) + Walk func(root string) ([]string, error) + Filesystems func(root string) []string + OnStart func(link, name string) cleanupErrs []error } @@ -168,6 +170,7 @@ func (s *ImageScanner) scanImage(ctx context.Context, img BootImage, devices []s return ImageResult{}, fmt.Errorf("%s: %w", imageLabel(img), err) } res.Packages = pkgs + res.Filesystems = workload.ReadFilesystems(s.Filesystems, root) return res, nil } diff --git a/internal/workload/gcp/scan.go b/internal/workload/gcp/scan.go index 618d5c9..37f6a21 100644 --- a/internal/workload/gcp/scan.go +++ b/internal/workload/gcp/scan.go @@ -80,10 +80,11 @@ type Instance struct { // Result is one instance after the snapshot and disk are deleted. type Result struct { - Name string - Zone string - Packages []string - Skipped string + Name string + Zone string + Packages []string + Filesystems []string + Skipped string } // API is the snapshot and disk lifecycle. Create calls wait until the resource @@ -111,6 +112,7 @@ type Scanner struct { Timeout time.Duration Mount func(ctx context.Context, device string) (root string, cleanup func() error, err error) Walk func(root string) ([]string, error) + Filesystems func(root string) []string OnStart func(name, zone string) cleanupErrs []error @@ -238,6 +240,7 @@ func (s *Scanner) scanInstance(ctx context.Context, inst Instance, devices []str return Result{}, fmt.Errorf("%s: %w", instLabel(res), err) } res.Packages = pkgs + res.Filesystems = workload.ReadFilesystems(s.Filesystems, root) return res, nil }