Compare commits

..

387 Commits

Author SHA1 Message Date
Pete Markowsky
9f41fbb124 Fix: Change uint64 fields in syncv1.proto to uint32 for backwards compatibility (#1422)
Change the uint64 fields in the syncv1.proto to uint32 to ensure backwards compatibility.

This also updates the SNTSyncEventUpload code to use the uint32 values and updates sync protocol docs.
2024-09-08 15:46:30 -04:00
Matt W
ff0efe952b Use proper CanWrite method to safeguard TTY struct access (#1420) 2024-08-21 16:29:33 -04:00
Tom Burgin
c711129ac9 s/NSDictionary/NSBundle/ (#1418) 2024-08-15 12:36:01 -04:00
Russell Hancox
a56f6c5447 Project: Update rules_apple to 3.8.0 (#1417) 2024-08-13 14:20:19 -04:00
Russell Hancox
fadc9b505b sync: Drop rules_* fields in postflight to uint32 (#1415)
* sync: Drop rules_* fields in postflight to uint32

This lets the protobuf json serializer to send the values as ints (like NSJSONSerialization did) instead of strings. This will cause problems if someone has 4B rules but that's probably a sign of bigger problems
2024-08-12 15:40:01 -04:00
Tom Burgin
c7766d5993 length and count check (#1413) 2024-08-09 17:17:13 -04:00
Russell Hancox
341abf044b sync: Fix Content-Type logic bug, add test (#1412) 2024-08-08 17:43:53 -04:00
Tom Burgin
b1cf83a7e3 switch to CFBundleCopyInfoDictionaryInDirectory (#1411) 2024-08-08 16:30:33 -04:00
Russell Hancox
013b0b40af sync: Remove debug logging of request JSON. (#1410)
This was helpful while switching to the protobuf lib but due to the way SLOGD works it isn't limited to just debug invocations and is quite noisy
2024-08-08 14:06:52 -04:00
Russell Hancox
6093118ba1 sync: Improve logging when connection restored, avoid retries. (#1408)
* sync: Improve logging when connection restored, avoid retries.

Don't retry requests if the error is that the machine is offline
2024-07-31 13:29:25 -04:00
Russell Hancox
6719d4c32a sync: Upgrade from SCNetworkReachability -> nw_path_monitor (#1406) 2024-07-31 10:53:16 -04:00
Russell Hancox
1ce4756771 santad: Synchronize access to metric callback array (#1405) 2024-07-29 12:09:03 -04:00
Russell Hancox
9a7dcefb92 sync: Fix serial_num field name (#1404)
Disable the preserve_proto_field_names option when marshalling JSON requests as this prevents the json_name attribute on fields from working properly. Add that attribute to all fields so that they marshal as expected. Stop setting the always_print_enums_as_ints field as the value we're setting to is the default anyway.

Also add a test that preflight request data looks as expected.
2024-07-29 12:08:21 -04:00
Russell Hancox
59382bc3ac sync: Handle missing error string for abnormal statuses (#1402) 2024-07-25 10:48:16 -04:00
Russell Hancox
0725fccc7f Docs: Add DismissText key to configuration.md (#1400) 2024-07-24 15:35:59 -04:00
Russell Hancox
166c0420e5 GUI: Make dismiss button configurable, change default text back to dismiss (#1399) 2024-07-23 13:33:29 -04:00
Matt W
f4ec2d51ab Fix check for deprecated clean sync key (#1397) 2024-07-17 20:10:38 -04:00
Russell Hancox
d54ec98bd5 GUI: Update activation policy for binary blocks (#1396)
Also fix threading issues with the `queueMessage:` method.
2024-07-17 10:29:35 -04:00
Matt W
bbeb653c77 Improve handling of sync response default values (#1395)
* Improve default value handling for sync proto processing

* Fix capitalization of new enum values in comments

* Fix/add tests, update some docs

* Update more docs

* Lint

* Remove comment. Add LEGACY_NAMES tag for the linter
2024-07-16 12:33:31 -04:00
Matt W
52ffe5fc50 sync: Allow empty data for 200 responses (#1394) 2024-07-10 16:50:53 -04:00
Russell Hancox
ffd77fef9d common: Remove debug log when signing ID is missing. (#1393)
This log line gets spit out in santactl fileinfo output in a way that makes the command harder to use for various things
2024-07-10 15:44:07 -04:00
Evangelos Mamalakis
47648d2d5c Handle non-200 HTTP responses in SNTSyncStage performRequest (#1392)
* Handle non-200 HTTP responses in SNTSyncStage performRequest

If we receive a non-200 HTTP response, we should return an error
instead of parsing the response to an empty protobuf message.

* Fix nil check

---------

Co-authored-by: Matt W <436037+mlw@users.noreply.github.com>
2024-07-10 15:43:26 -04:00
Pete Markowsky
208b4a6ebc sync: Add machine_id field to facilitate a GRPC version of the protocol (#1390) 2024-07-09 16:35:26 -04:00
Russell Hancox
7f86366672 sync: Parse response as proto when SyncEnableProtoTransfer enabled (#1391) 2024-07-09 12:24:34 -04:00
Russell Hancox
9e7847740f sync: Handle parse errors, add UNKNOWN_CLIENT_MODE to enum (#1389) 2024-07-09 11:55:06 -04:00
Tom Burgin
348ff8c006 fileinfo: add --filter-inclusive (#1388)
* filter inclusive

* remove print method

* update help
2024-07-09 13:29:37 +00:00
Matt W
476cd21653 Convert santa::santad::event_providers and santa::santad (#1387) 2024-07-05 14:48:22 -04:00
Matt W
7bf11abca0 Convert santa::santad::event_providers::endpoint_security (#1386) 2024-07-05 14:13:10 -04:00
Matt W
466546f548 Namespace simplification pt2 (#1385)
* Convert santa::santad::logs::endpoint_security::serializers::Utilities

* Convert santa::santad::logs::endpoint_security::writers

* Convert santa::santad::logs::endpoint_security::serializers

* Convert santa::santad::logs::endpoint_security and santatest

* Lint

* Change type alias names to not conflict with sysinfo.h
2024-07-05 12:21:01 -04:00
Matt W
73c18851f9 Adopt namespace naming guidelines - part 1 (#1384) 2024-07-04 22:19:32 -04:00
Tom Burgin
650f6fac97 cap q (#1383) 2024-07-03 16:58:47 -04:00
Matt W
9764f1bd69 Use class member access operator for underlying ES message (#1381) 2024-07-03 12:17:00 -04:00
Matt W
688d560b62 Add protobuf serialization for new login/logout events (#1380) 2024-07-03 09:35:25 -04:00
Matt W
b6af5ade60 Add string serialization for new login/logout events (#1379) 2024-07-02 22:40:05 -04:00
Matt W
08ce693096 Login/logout events (#1371)
* WIP Basic new enriched types, hooked up serializers

* WIP Expanded enriched types, finished basic string logging

* WIP Standardize instigator and event user strings.

* WIP Remove sudo event for now. Fix proto types.

* Update proto field names. Fix builds on older SDKs.

* Fix more issues with builds on older SDKs.

* Even more build fixes for older SDKs

* Fix basic string test build on older sdks

* More fixes for older SDKs

* WIP Started on proto encoding and tests

* WIP expanded proto support for new events

* Lint. Fix recorder tests for missing event types

* WIP continued expanding proto support for new events

* WIP finished proto support for all new event types

* WIP Comment all new messages and fields in santa.proto

* WIP Use different impl to set strings to sidestep internal absl issues

* Temporarily removing serializer impls and tests to reduce PR size

* Lint fixes

* PR feedback
2024-07-02 16:41:01 -04:00
Russell Hancox
85cfa641ce Project: Update several bazel modules (#1378) 2024-06-28 13:23:46 -04:00
Matt W
72ed5ee4f9 Drop macos 11 (#1377)
* Drop macOS 11 support

* More changes after rebase, add basic macOS 15 support
2024-06-28 12:58:07 -04:00
Matt W
ecf7040b87 Proto tests min version support (#1376)
* Protobuf event tests should only apply to applicable versions

* Address local/remote lint issues

* Address more local/remote lint issues
2024-06-28 10:52:17 -04:00
Matt W
cedbc0da19 Add tests to ensure EventTypeToString handles all subscriptions (#1374) 2024-06-26 15:46:29 -04:00
Russell Hancox
ef9348e6f5 santad: Fix metrics for AuthSignal events (#1373) 2024-06-26 12:35:30 -04:00
Russell Hancox
b23b528082 docs: Update references to SNTXPCConnection (#1372) 2024-06-21 09:39:12 -04:00
Evangelos Mamalakis
587ac2ddc8 Fix santd title in docs (#1368) 2024-06-18 19:49:16 +02:00
Matt W
14729210d3 Use new Apple docs link for global proxy settings constants (#1367)
* Use new Apple docs link for global proxy settings constants

* Missed a file...

* WIP test workflow change

* WIP Fix link

* Remove trailing whitespace
2024-06-18 13:15:36 -04:00
Toast
c3d29e3c4a docs: Add Identifier Conventions (#1366) 2024-06-18 09:48:03 -04:00
Pete Markowsky
4b0ad39413 Add a Signing ID Format Helper (#1365) 2024-06-11 14:51:23 -04:00
Matt W
e8b7fdff64 Modernize docs (Round 1) (#1363)
* WIP Major modernization effort for many of the Santa docs

* Update IPC concept doc and diagram

* WIP - Apply suggestions from code review

Only some of the comments are included in this first commit.

Co-authored-by: Kathryn May <44557882+kathancox@users.noreply.github.com>
Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>

* WIP - Part 2 - Apply suggestions from code review

Adding some more suggestions. Still more to go through.

Co-authored-by: Kathryn May <44557882+kathancox@users.noreply.github.com>
Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>

* WIP Adding more PR suggestions

* WIP - Apply suggestions from code review

More commits from reviewers

Co-authored-by: Kathryn May <44557882+kathancox@users.noreply.github.com>
Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>

* WIP - Apply suggestions from code review

More PR suggestions

Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>
Co-authored-by: Kathryn May <44557882+kathancox@users.noreply.github.com>

* WIP addressed more PR feedback

* WIP - More PR feedback

* WIP - More PR feedback on bundle identification. Link updates

* WIP - Clarify bundle events

* WIP - clarify how to request bundle binary events

* Update santad setup tasks

* Fix doc link

* Update docs/binaries/santa-gui.md

Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>

---------

Co-authored-by: Kathryn May <44557882+kathancox@users.noreply.github.com>
Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>
2024-06-07 10:17:07 -04:00
Russell Hancox
35d42d0134 sync: Add option to sync using binary protos (#1364) 2024-06-04 13:53:01 -04:00
Russell Hancox
a42dd6e120 santad: Add signal auth to tamper resistence. (#1360)
Prior to this change, root users could kill the com.google.santa.daemon process. 
It would be immediately restarted by sysextd but this opens a very brief
window where protection is lost. Hooking AUTH_SIGNAL and blocking all
signals to the santad process except those sent by launchd lets us block
this without breaking upgrades, reboots, etc.

This leaves `launchctl kill` and friends as an avenue, so we're also
hooking for exec and blocking executions of launchctl that reference
com.google.santa.daemon except in known safe cases.
2024-06-03 13:41:25 -04:00
Russell Hancox
53a2bbdd1e docs: Document new EventDetailURL keys (#1361) 2024-05-30 12:29:00 -04:00
Pete Markowsky
e417d8847f Project: Update check-markdown workflow to use Lychee (#1362) 2024-05-30 10:10:36 -04:00
Russell Hancox
a23b67d5de sync: Add a protobuf for the existing sync protocol (#1359)
This PR is intended to have no impact on existing sync servers. The fields and enum values in the protobuf have been named such that their JSON equivalents match the existing constants we have in the codebase.

Adding this provides a few benefits:

1. The protobuf serves as canonical documentation of the protocol in a form that's much easier to read than the existing code.
2. Protobuf parsing of JSON is likely to be better than our hand-written version.
3. We can (in a later PR) add a configuration option to use binary encoding instead of JSON, saving network during syncs.
4. Servers written in other languages are easier to write and update as time goes on, especially as we extend the protocol.
2024-05-29 14:22:49 -04:00
Russell Hancox
7502bc247f santactl/fileinfo: Include teamID/platform prefix in signing ID (#1356) 2024-05-21 12:48:48 -04:00
Russell Hancox
cf4dab55e0 santactl/rule: Allow adding signing ID and team ID rules by file path (#1357) 2024-05-21 12:48:27 -04:00
Matt W
e43ad30d4e Fix NSSecureCoding adoption in SNTFileAccessEvent (#1358) 2024-05-21 11:35:07 -04:00
np5
d8928ac320 Add cdhash, teamID, and signingID to bundle events (#1353)
Fix #1352
2024-05-20 10:45:36 -04:00
Matt W
ac1c9d8b05 Fix stat metrics accounting. Refactor setting metrics to be more general. (#1354) 2024-05-17 12:15:48 -04:00
Matt W
9b184ed4fb Add metric for when the file on disk is not the file being evaluated (#1348)
* Add metrics for stat change detection

* Fix test related issues due to partially constructed messages

* lint

* Convert errno to enum class StatResult

* Cleanup from PR feedback
2024-05-16 16:13:29 -04:00
Russell Hancox
67883c5200 GUI: Fix unicode rendering of attributed messages (#1351)
Also added a test to stop this from happening again
2024-05-15 16:27:28 -04:00
Russell Hancox
8e1e155c23 Project: Re-enable layering_checks (#1350) 2024-05-15 14:05:58 -04:00
Russell Hancox
fb6aa850b3 santad: Drop QoS of notify handling queue (#1349)
Bumping from BACKGROUND to DEFAULT had the desired impact of processing events faster and reducing memory usage but had a larger-than-expected increase in CPU usage. UTILITY is in the middle of these two and better fits the desired priority.
2024-05-15 11:53:31 -04:00
czcx
7f06b8c11a Docs: Minor grammar & correctness fixes in known-limitations.md. (#1345) 2024-05-14 13:06:45 -04:00
Matt W
978b33e450 Adopt --preserve-metadata flag to simplify resigning with entitlements (#1346) 2024-05-10 13:40:19 -04:00
Russell Hancox
f00ad32edd santad: Bump QoS of notify handling queue (#1342)
The use of the background queue is a historical artifact from when Santa had its own kernel extension with separate in-kernel queues for processing AUTH & NOTIFY type events. With the move to ES and the larger number of event types that we now notify on, running at the background QoS carries a small risk that the thread processing these events is not given a chance to run often enough that the queue grows and increases memory usage.
2024-05-09 15:44:14 -04:00
Pete Markowsky
7b0d2fdbb8 Add necessary dep for SNTPolicyProcessorTest (#1343) 2024-05-09 15:29:17 -04:00
Russell Hancox
1672e52b7b Project: Disable layering_check in all BUILD files (#1344) 2024-05-09 15:25:19 -04:00
Pete Markowsky
6cca5ab27d Update SNTPolicyProcessor to use a map (#1304)
* Update SNTPolicyProcessor to use a map instead of a giant switch statement

Update SNTPolicyProcessor to use a map instead of a giant switch statement.

Add unit tests for the method that sets SNTCachedDecision values.

* Remove unneccessary OCMock dep in BUILD file.

* Fix typo in method signature.

* Incorporate review feedback.

* Upper case UpdateCachedDecisionSigningInfo

* Update SNTPolicyProcessor.h

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>

* Update SNTPolicyProcessor.mm

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>

* Fix typo

* Fix linter issues.

* Fixed up more linter issues.

---------

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
2024-05-09 14:38:12 -04:00
Matt W
7e4af5e337 Update to Abseil 20240116.1. Fix includes. (#1341) 2024-05-09 12:33:46 -04:00
Russell Hancox
5ea4431901 Project: Move fuzzing rules to bzlmod, fix santa_unit_test (#1339) 2024-05-08 11:50:04 -04:00
Tom Burgin
b53818f556 SNTBlockMessage: add more template options (#1337)
* update event detail url

* refactor template mappings

* re-enable testEventDetailURLForFileAccessEvent

* null

* missed one

* update comment
2024-05-07 09:20:50 -04:00
Tom Burgin
0f5e551345 Project: Fix lint.sh to bubble up all errors, switch from pylint to pyink, fix existing lint errors (#1338) 2024-05-06 16:47:32 -04:00
Nick Gregory
51b0f7146d Testing: update E2E to use JIT runners (#1335)
* inject jit runner token into e2e vm

* split out vm updating

* argparse + logging

* restore update/start vm steps

* pr review comments

* rm gcp.json and verify runner sha
2024-05-06 09:10:04 -04:00
czcx
f5882b3146 docs: Fix grammar and typo in syncing-overview 2024-04-30 12:58:34 -04:00
Rohan Sharma
59c146b4af README: Fix typo in landing page (#1332) 2024-04-30 12:25:53 -04:00
czcx
aaa2b0e259 Docs: Grammar updates on doc index 2024-04-29 17:23:39 -04:00
czcx
9c6fd0677f README: Minor grammar issue fix (#1329) 2024-04-29 15:53:52 -04:00
Russell Hancox
344a35aaf6 Project: Migrate to bazel modules (#1324)
This includes updating to rules_apple 3.5.1 and protobuf 26.1, as well as updating several tests to no longer use the data attribute to pass in testdata.
2024-04-11 17:19:30 -04:00
Matt W
45e36fa501 Bump protobuf to v26.1, update to use new interfaces. (#1317) 2024-04-11 14:22:43 -04:00
Nick Gregory
d5a7c5f1fa ProcessTree: add the first annotation, originator (4/4) (#1296) 2024-04-11 13:35:53 -04:00
Pete Markowsky
22aca6b505 Add macOS-14 to the test matrix. (#1323) 2024-04-05 15:09:04 -04:00
Pete Markowsky
375f7bd9cc Fix: Update code to use the new MOLCodesignChecker interfaces for codesigning info (#1322)
* Update code to use the  new MOLCodesignChecker interfaces for codesigning info.
2024-04-05 12:27:33 -04:00
Matt W
7d58665e87 Bump MOLCodesignChecker tag to latest (#1321) 2024-04-05 10:39:08 -04:00
Ryan Diers
3b2d02f38d GUI: Restore default button type to MessageWindow for blocked events (#1316) 2024-03-28 15:02:01 -04:00
Nick Gregory
57fc2b0253 Add missing EndpointSecurity dylib (#1315) 2024-03-25 13:41:20 -04:00
Nick Gregory
262adfecbd Fix BUILD deps (#1314) 2024-03-25 13:19:13 -04:00
Jason McCandless
1606657bb3 Add CDHash to rule evaluation order doc. (#1313) 2024-03-22 18:13:58 -04:00
Matt W
b379819cfa Overrides disabled when running tests unless explicitly enabled (#1312)
* Emit a log warning when overrides were applied

* Overrides now disabled in tests unless explicitly enabled

* Remove log message. Check for xctest instead of bazel env vars.

* Typo
2024-03-22 16:44:45 -04:00
Pete Markowsky
b9f6005411 Fix: Do not flush authcache when receiving duplicate block rules from the sync service (#1310)
* Change the behavior of addedRulesShouldFlushDecisionCache to flush when 1000 non-allowlist rules are added or a remove rule is encountered or any new non-allowlist rules are added

* Add tests for cache flushing behavior.
2024-03-22 11:24:42 -04:00
Russell Hancox
e31aa5cf39 Tests: Fix SNTRuleTableTest in the presence of local static rules (#1311) 2024-03-19 18:06:39 -04:00
Nick Gregory
77d191ae26 ProcessTree: integrate process tree throughout the event processing lifecycle (3/4) (#1281)
* process annotations: thread the tree through santa

* Update enricher to read annotations from the ProcessTree

* rebase changes

* add configuration for annotations, disabling the tree entirely if none are enabled

* lingering build dep

* use tree factory constructor

* fix configurator

* build fixes

* rebase fixes

* fix tests

* review comments

* lint

* english hard

* record metrics even when event only used for process tree
2024-03-14 11:31:51 -04:00
Pete Markowsky
160195a1d4 Implement NSSecureCoding for SNTRuleIdentifiers (#1307)
* Fix an issue with santactl fileinfo by implementing NSSecureCoding for SNTRuleIdentifiers.
2024-03-11 10:03:49 -04:00
Matt W
f2ce92650b Add required dep for internal builds (#1302) 2024-03-05 15:39:59 -05:00
Matt W
e89cdbcf64 Add support for CDHash rule types (#1301)
* Support CDHash rules

* Ensure hardened runtime for cdhash eval. Update docs.

* minor fixups

* Clarify docs
2024-03-05 15:07:36 -05:00
Pete Markowsky
6a697e00ea Added clean flags for JSON rule import (#1300)
* Add --clean and --clean-all flags to the santactl rule command to allow clearing the rule database when importing rules via JSON.
2024-03-03 11:12:53 -05:00
Matt W
74d8fe30d1 Creating transitive rules for rename events should fallback to destination path (#1299)
* Transitive rules should fallback to destination for RENAME events

* Add tests to exercise fallback for rename events
2024-02-28 17:09:07 -05:00
Matt W
7513c75f88 Refactor rule and count lookups (#1298)
* Refactor rule and count lookups

* Remove commented out code

* Change rule count types to int64_t. SNTRuleIdentifiers properties now RO.
2024-02-26 15:09:51 -05:00
Matt W
9bee43130e Make FileChangesRegex apply to all file change event types (#1294)
* Make FileChangesRegex apply to all file change event types

* Handle older SDKs

* Formatting

* Remove debug log
2024-02-22 10:12:02 -05:00
Nick Gregory
7fa23d4b97 Some more lint fixes (#1295)
* lint fixes

* more lint
2024-02-20 15:39:24 -05:00
Nick Gregory
42eb0a3669 ProcessTree: add macOS specific loader and ES adapter (2/4) (#1237)
* ProcessTree: add macos-specific loader and event adapter

* lingering darwin->macos

* lint

* remove defunct client id

* struct rename

* and one last header update

* use EndpointSecurityAPI in adapter

* expose esapi in message
2024-02-20 13:56:54 -05:00
Russell Hancox
1ea26f0ac9 docs: Document that *PathRegex does not work on symlinks (#1290) 2024-02-13 18:53:17 -05:00
Nick Gregory
c35e9978d3 ProcessTree: fix missing direct deps (#1288)
* hmm

* more lint and add another dep
2024-02-09 10:33:57 -05:00
Matt W
e4c0d56bb6 Remove proc tree tests for now as the code isn't yet included in santa builds (#1287) 2024-02-08 16:01:47 -05:00
Matt W
908b1bcabe Add build dep for internal process (#1286) 2024-02-08 15:43:01 -05:00
Matt W
64e81bedc6 Respect fail closed on deadlines (#1285)
* Responses to events about to exceed deadline should respect FailClosed

* Only respect FailClosed when in Lockdown mode. Update docs.

* FailClosed in Configurator now wraps checking client mode

* PR feedback

* Fix execution controller tests with new FailClosed logic
2024-02-08 15:12:05 -05:00
Matt W
5dfab22fa7 Fix automatically denied events with small deadlines (#1284)
* Fix automatically denied events with small deadlines

* Fix up additional tests that had defined deadline interactions
2024-02-08 10:25:06 -05:00
Nick Gregory
5248e2a7eb Fix import issues and lint (#1282)
* lint

* case insensitive filesystems ahhhh

* tidy

* one last header
2024-02-07 17:46:42 -05:00
Nick Gregory
e8db89c57c ProcessTree: add core process tree logic (1/4) (#1236)
* ProcessTree: add core process tree logic

* make Step implicitly called by Handle* methods

* lint

* naming convention

* widen pidversion to be generic

* move os specific backfill to os specific impl

* simplify ts checking

* retain/release a whole vec of pids

* document processtoken

* lint

* namespace

* add process tree to project-wide unit test target

* case change annotations

* case change annotations

* remove stray comment

* default initialize seen_timestamps

* fix missing initialization of refcnt and tombstoned

* reshuffle pb namespace

* pr review

* move annotation registration to tree construction

* use factory function for tree construction
2024-02-05 14:30:54 -05:00
Matt W
70474aba3e Sync clean all (#1275)
* WIP Clean syncs now leave non-transitive rules by default

* WIP Get existing tests compiling and passing

* Remove clean all sync server key. Basic tests.

* Add SNTConfiguratorTest, test deprecated key migration

* Revert changes to santactl status output

* Add new preflight response sync type key, lots of tests

* Rework configurator flow a bit so calls cannot be made out of order

* Comment clean sync states. Test all permutations.

* Update docs for new sync keys

* Doc updates as requested in PR
2024-01-24 09:26:20 -05:00
Pete Markowsky
f4ad76b974 Make santactl status always print out transitive rule status if set (#1277)
* Make santactl status always print out transitive rule status even when not using a sync service.

* Fix typo in SNTCommandRule.m.

* Updated JSON values to put transitive_rules in the daemon section.
2024-01-22 12:16:47 -05:00
hugo-syn
3b7061ea62 chore: Fix typo s/occured/occurred/ (#1274)
Signed-off-by: hugo-syn <hugo.vincent@synacktiv.com>
2024-01-18 10:50:01 -05:00
hugo-syn
280d93ee08 chore: Fix multiple typos (#1273)
Signed-off-by: hugo-syn <hugo.vincent@synacktiv.com>
2024-01-18 09:17:52 -05:00
Matt W
f73463117f Add back support for EnableForkAndExitLogging config key (#1271) 2024-01-14 13:42:06 -05:00
Matt W
f93e1a56a0 Docs add missing config keys (#1270)
* Add missing config keys

* Use more consistent wording

* More consistent whitespace

* Reorder constants to appropriate section groups

* Update docs/deployment/configuration.md

Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>

---------

Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>
2024-01-13 00:08:16 -05:00
Pete Markowsky
d5195b55d2 Added documentation to clarify clean sync with zero rule behavior (#1259)
* Added documentation to clarify clean sync with zero rule behaivor.

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
2024-01-09 16:10:27 -05:00
Matt W
15e5874d43 Fix wrong srcs paths (#1265) 2024-01-03 10:49:08 -05:00
Matt W
5e6fa09f1c Change build target visibility (#1264)
* Change build target visibility

* Add dependent headers as srcs. Remove unnecessary visibility.
2024-01-03 10:21:33 -05:00
Matt W
ce2777ae94 Fix santactl rule --check (#1262)
* Fix santactl rule check to only strictly show rule info

* Reorganized to make more testable, added tests
2024-01-03 09:52:14 -05:00
Matt W
f8a20d35b4 Fix issue with drop count calculations (#1256) 2023-12-13 17:01:11 -05:00
Matt W
2e69370524 Event drop metrics (#1253)
* Add dropped event detection and metrics

* Update metrics test for drop counts

* Comment new interface
2023-12-07 15:23:51 -05:00
Russell Hancox
f9b4e00e0c GUI: Change default button text to "Open..." (#1254) 2023-12-06 14:19:27 -05:00
Matt W
e2e83a099c Initial support for some scoped types (#1250)
* Add some scoped types to handle automatic releasing

* style

* comment typo
2023-12-05 18:51:07 -05:00
Matt W
2cbf15566a Revert "Project: Remove provisioning_profiles attributes from command-line tool rules (#1247)" (#1251)
This reverts commit 65c660298c.
2023-12-05 15:48:36 -05:00
Nick Gregory
1596990c65 reorder e2e tests (#1249) 2023-12-04 13:01:30 -05:00
Matt W
221664436f Expand debug logging for transitive rule failure case (#1248) 2023-11-30 15:47:48 -05:00
Russell Hancox
65c660298c Project: Remove provisioning_profiles attributes from command-line tool rules (#1247) 2023-11-30 13:50:38 -05:00
Matt W
2b5d55781c Revert back to C++17 for now (#1246) 2023-11-29 21:39:48 -05:00
Matt W
84e6d6ccff Fix USB state issue in santactl status (#1244) 2023-11-29 17:56:35 -05:00
Matt W
c16f90f5f9 Fix test issue caused by move to C++20 (#1245)
* Fix test issue caused by move to C++20

* Use spaceship operator as is the style of the time

* lint

* Add include
2023-11-29 16:52:23 -05:00
Matt W
d503eae4d9 Bump to C++20 (#1243) 2023-11-29 09:57:45 -05:00
Matt W
818518bb38 Ignore TeamID and SigningID rules for dev signed code (#1241)
* Ignore TID/SID rules for dev signed code

* Handle code paths from santactl

* Don't bother evaluating isProdSignedCallback if not necessary

* PR feedback. Link to docs.
2023-11-27 11:21:17 -05:00
Matt W
f499654951 Experimental metrics (#1238)
* Experimental metrics

* Fix tests, old platform builds

* Use more recent availability checks

* Update macro name, undef after usage
2023-11-20 13:02:58 -05:00
Matt W
a5e8d77d06 Entitlements logging config options (#1233)
* WIP add config support to filter logged entitlements

* Add EntitlementInfo proto message to store if entitlements were filtered

* Log cleanup

* Address PR feedback

* Address PR feedback
2023-11-13 09:39:32 -05:00
Matt W
edac42e8b8 Fix internal build issues, minor cleanup. (#1231) 2023-11-09 17:26:31 -05:00
Matt W
ce5e3d0ee4 Add support for logging entitlements in EXEC events (#1225)
* Add support for logging entitlements in EXEC events

* Standardize entitlement dictionary formatting
2023-11-09 16:26:57 -05:00
Pete Markowsky
3e51ec6b8a Add name for white space check (#1223)
* Add a name to the whitespace check in the check-markdown workflow.

* Pin workflow steps.
2023-11-09 15:26:51 -05:00
Travis Lane
ed227f43d4 Explicitly cast strings to std::string_view (#1230)
GoogleTest when built with GTEST_HAS_ABSL fails to convert these strings
to a `std::string_view`. Lets instead explicitly convert them to a
`std::string_view`.
2023-11-08 17:05:08 -05:00
Nick Gregory
056ed75bf1 dismiss santa popup after integration tests (#1226) 2023-11-07 14:42:03 -05:00
Matt W
8f5f8de245 Only remount on startup if remount args are set (#1222) 2023-11-06 09:10:34 -05:00
Matt W
7c58648c35 Bump hedron commit. Minor WORKSPACE fixups. (#1221) 2023-11-03 10:03:11 -04:00
Matt W
3f3751eb18 Fix remount issue for APFS formatted drives (#1220)
* Fix issue mounting APFS drives with MNT_JOURNALED

* typo
2023-11-02 22:20:35 -04:00
Matt W
7aa2d69ce6 Add OnStartUSBOptions to santactl status (#1219) 2023-11-02 20:30:05 -04:00
Matt W
f9a937a6e4 Record metrics for device manager startup operations (#1218)
* Record metrics for device manager startup operations

* Update help text

* Update help text
2023-11-02 20:27:57 -04:00
Matt W
d2cbddd3fb Support remounting devices at startup with correct flags (#1216)
* Support remounting devices at startup with correct flags

* Add missing force remount condition
2023-11-02 14:37:28 -04:00
Pete Markowsky
ea7e11fc22 Add Support for CS_INVALIDATED events (#1210)
Add support for logging when codesigning has become invalidated for a process.

This adds support to the Recorder to log when codesigning is invalidated as reported by the Endpoint Security Framework's
ES_EVENT_TYPE_NOTIFY_CS_INVALIDATED event.
2023-11-02 10:04:18 -04:00
Nick Gregory
7530b8f5c1 Add E2E testing for usb (#1214)
* e2e test usb mounting

* no poweroff

* no start

* drive usb via sync server since its up

sudo santactl status

sudo?

* revert nostart/nopoweroff

* bump VMCLI minimum os version
2023-11-01 11:44:00 -04:00
Matt W
64bb34b2ca Additional build deps (#1215)
* Update build deps

* lint
2023-10-31 14:16:28 -04:00
Matt W
c5c6037085 Unmount USB on start (#1211)
* WIP Allow configuring Santa to unmount existing mass storage devices on startup

* WIP fixup existing tests

* Add unmount on startup tests
2023-10-31 13:34:10 -04:00
Matt W
275a8ed607 Support printing bundle info via santactl fileinfo command (#1213) 2023-10-31 13:19:00 -04:00
Nick Gregory
28dd6cbaed Enable e2e testing on macOS 14 (#1209)
* e2e for macos 14

* no shutdown

* gh path

* dismiss santa popup after bad binary

* sleep for ui

* re-enable start vm

* re-enable poweroff

* tabs

* ratchet checkout actions in e2e
2023-10-30 17:45:37 -04:00
Pete Markowsky
8c466b4408 Fix issue preventing rule import / export from working (#1199)
* Fix issue preventing rule import / export from working.

* Removed unused --json option from help string.

* Document that import and export as taking a path argument.
2023-10-25 16:47:14 -04:00
p-harrison
373c676306 Update syncing-overview.md (#1205)
Update the syncing-overview.md document to note that FCM based push notifications are not currently available outside the internal Google deployment of Santa.
2023-10-25 14:17:22 -04:00
p-harrison
d214d510e5 Update configuration.md to note that push notifications not widely available (#1204)
Update the configuration.md document to note that FCM based push notifications are not currently available outside the internal Google deployment of Santa
2023-10-25 14:11:15 -04:00
Pete Markowsky
6314fe04e3 Remove mention of KEXT from README.md (#1202)
* Remove mention of kext from README.md
2023-10-25 14:07:43 -04:00
p-harrison
11d9c29daa docs: Update configuration.md to explain EnableDebugLogging (#1203)
Update configuration.md with details of the EnableDebugLogging configuration key.  Also some minor formatting changes.
2023-10-16 10:29:45 -04:00
Matt W
60238f0ed2 Minor doc updates. Add missing FAA config options. (#1197)
* Minor doc updates. Add missing FAA config options.

* Fix typo. Add higher res icon.
2023-10-06 12:30:36 -04:00
Russell Hancox
7aa731a76f santactl/sync: Drop root requirement (#1196)
Previously the sync command required root in order to establish a connection to santad with enough privilege to use the XPC methods for adding rules. Now that santasyncservice exists this requirement is no longer necessary and there is no risk in allowing unprivileged users to initiate a sync.

We still ensure that privileges are dropped, just in case someone does execute as root.
2023-09-29 12:56:15 -04:00
Matt W
5a383ebd9a Only eval TID and SID rules when the binary signature is valid (#1191)
* Only eval TID and SID rules when the binary signature is valid

* Simplify setting sid on cached decision
2023-09-28 10:11:01 -04:00
Pete Markowsky
913af692e8 Fix missing Santa block gif. (#1193) 2023-09-27 14:53:45 -04:00
p-harrison
4d6140d047 Update sync-protocol.md (#1187)
Fields like pid, ppid, execution_time, current_sessions etc. are not supplied in Event uploads when the decision is BUNDLE_BINARY (ie. Events generated by the bundle scanning service, rather than actual executions) so I have marked these as not required in the API definition.
Few other small formatting tidy-ups while I was there.
2023-09-19 12:20:42 -04:00
Matt W
2edd2ddfd2 Remove superfluous import (#1188) 2023-09-18 23:01:22 -04:00
Matt W
1515929752 Add ability to specify custom event URLs and button text for FAA dialog (#1186)
* Allow per-policy and per-rule FAA URL and button text

* Add format string support to the custom URL. Added SNTBlockMessageTest.

* Add event URL to TTY message.

* Allow rule specific policy to "clear" global to remove buttons for the rule

* Remove extra beta label for FAA
2023-09-18 22:33:19 -04:00
Pete Markowsky
fc2c7ffb71 Used ratchet to pin GitHub actions to specific hashes. (#1184)
Pin GitHub actions to a specific version.
2023-09-18 15:30:10 -04:00
Kent Ma
98ee36850a Use 'set -xo pipefail' instead (#1185) 2023-09-14 15:37:06 -04:00
Matt W
6f4a48866c Internal build fixes (#1183)
* Address internal build issues

* lint
2023-09-13 22:17:41 -04:00
Matt W
51ca19b238 Fix layering issue for imported module (#1182) 2023-09-13 20:59:07 -04:00
Pete Markowsky
b8d7ed0c07 Add basic support for importing and exporting rules to/from JSON (#1170)
* Add basic support for importing and exporting rules to/from JSON.
2023-09-13 17:46:49 -04:00
Matt W
ff6bf0701d Add ability to override File Access actions via config and sync settings (#1175)
* Support new config (and sync config) option to override file access action.

* Adopt override action config in file access client

* Add sync service and file access client tests

* Require override action to be specific values. Add new sync setting to docs.
2023-09-13 15:47:49 -04:00
Matt W
3be45fd6c0 UI For Blocked File Access (#1174)
* WIP: UI: open cert modal, hookup silence checkbox. Add cert helper funcs.

* Popup dialog on file access violation. Support config-based and custom messages.

* Send message to TTY on file access rule violation

* TTYWriter Write now takes an es_process_t. Fix async data lifespan issue.

* Dedupe TTY message printing per process per rule

* Some minor swift beautification

* Remove main app from dock when showing file access dialog

* Update header docs

* Remove define guards for ObjC header file

* Update Source/common/CertificateHelpers.h

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>

* Fix comment typo

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>

* Use #import for ObjC headers

* Use #import for ObjC header

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>

* lint

* Comment use of escape sequences

---------

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
2023-09-13 15:45:56 -04:00
Matt W
d2e5aec635 Update Protobuf and Abseil versions (#1179) 2023-09-12 11:00:14 -04:00
Pete Markowsky
be1169ffcb Make Transitive Allowlisting Work with Signing ID rules (#1177)
* Make transitive allowlisting work with Signing ID rules

* Update rules.md to include SIGNINGID rules for transitive allowlisting.
2023-09-11 14:28:23 -04:00
Matt W
181c3ae573 Bump bazel and build_bazel_rules_apple versions (#1178)
* Bump bazel and build_bazel_rules_apple versions

* Minor change in Source dir to trigger github build actions

* Declare some archives higher up due to deps changes
2023-09-11 13:41:38 -04:00
Pete Markowsky
5f0755efbf Add Tests for #1165 Behavior. (#1173) 2023-09-04 19:48:44 -04:00
p-harrison
f0165089a4 Update rules.md with more detail on Transitive/Compiler rules (#1172)
Updated the description of Transitive/Compiler rules to clarify that only rules of type BINARY are allowed.
2023-09-01 10:21:19 -04:00
kyoshisuki
5c98ef6897 Update troubleshooting.md (#1169) 2023-08-30 09:01:16 -04:00
p-harrison
e2f8ca9569 Remove logupload stage from syncing-overview.md (#1168)
The logupload stage was referred to in this document but was removed in #331.

FYI this document also refers to santactl performing syncs, which I believe is now handled by santasyncservice, but I am not familiar enough with it to document sorry.
2023-08-29 12:04:33 -04:00
Matt W
2029e239ca Fix issue where client mode was almost always logged as "Unknown" (#1165) 2023-08-28 09:50:21 -04:00
p-harrison
cae3578b62 Document SyncExtraHeaders in configuration.md (#1166)
Document the SyncExtraHeaders configuration option added in #1144
2023-08-28 09:30:12 -04:00
Pete Markowsky
16a8c651d5 Restore file_bundle_hash & file_bundle_binary_count (#1164) 2023-08-25 11:09:02 -04:00
Matt W
4fdc1e5e41 Use default event detail button text when a custom URL is set (#1161) 2023-08-23 15:22:24 +00:00
Matt W
1cdd04f9eb Additional metrics for File Access Authorizer client (#1160)
* WIP additional file access authorizer metrics

* Update flush metrics test. Refactor friend MetricsPeer class.
2023-08-23 15:20:13 +00:00
Matt W
4d0af8838f Fix new buildifier issues (#1162) 2023-08-23 11:18:05 -04:00
p-harrison
0400e29264 Correction to sync-protocol.md (#1159)
Removes  file_bundle_binary_count and file_bunde_hash from the Rule definition and examples

These were accidentally added to the Rule definition and examples, rather than to the Event section in #1130.

Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>
2023-08-21 12:19:51 -04:00
p-harrison
2c6da7158d Add SigningID/TeamID to Event definition in sync-protocol.md (#1158)
Added SigningID/TeamID to Event definition

Added SigningID and TeamID to the definition of Events in the EventUpload stage

Documented SigningID and TeamID in the definition of Events in the EventUpload stage
2023-08-21 09:54:56 -04:00
Russell Hancox
b0ab761568 sync: Send rules_received and rules_processed fields in postflight request (#1156) 2023-08-19 00:45:49 +02:00
Matt W
b02336613a Remove references to old EnableSystemExtension config key (#1155) 2023-08-18 11:47:14 -04:00
Matt W
bd86145679 Add mount from information to disk appear events (#1153) 2023-08-17 08:00:01 -04:00
Matt W
6dfd5ba084 Fix issue where re config types couldn't be overridden (#1151) 2023-08-14 23:40:48 +02:00
Pete Markowsky
72e292d80e Add support for was_mmaped_writeable to file write monitoring when using macOS 13+ (#1148)
Add support for was_mmaped_writeable to file write monitoring when using macOS 13

In macOS 13 close events now have a new field was_mapped_writable that lets us
track if the file was mmaped writable.  Often developer tools use mmap to
avoid large numbers of write syscalls (e.g. the go toolchain) and this improves
transitive allow listing with those tools.
2023-08-14 15:25:48 -04:00
p-harrison
6588c2342b Added TransitiveWhitelisting explanation to rules.md (#1150)
* Added TransitiveWhitelisting explanation to rules.md

Added a section to explain TransitiveWhitelisting and Transitive/Compiler rules

* Update docs/concepts/rules.md

Co-authored-by: Matt W <436037+mlw@users.noreply.github.com>

* Update docs/concepts/rules.md

Co-authored-by: Matt W <436037+mlw@users.noreply.github.com>

---------

Co-authored-by: Matt W <436037+mlw@users.noreply.github.com>
2023-08-14 12:04:24 -04:00
Russell Hancox
d82e64aa5f Project: Split integration VM license into its own LICENSE file (#1147) 2023-08-08 13:29:06 -04:00
Ivan Tadeu Ferreira Antunes Filho
a9c1c730be Project: Cast some enums to int (#1146)
Allows the string displaying the enum to format it using %d.

Fixes the error: `error: format specifies type 'int' but the argument has type 'T' [-Werror,-Wformat]`
2023-08-08 13:08:11 -04:00
Matt W
6c4362d8bb Add hot cache for targets of read only policies (#1145)
* Add hot cache for file reads

* Clear cache on policy change

* Prevent unbounded cache growth

* Move cache impl to its own class

* Add some additional tests

* Cleanup

* Comment cleanup

* Switch to absl containers

* Use default absl::Hash instead of custom hasher

* Removing another reference to PairHash

* Remove unused imports
2023-08-08 12:38:33 -04:00
Russell Hancox
c1189493e8 sync/UI: Add ability to send custom URLs for blocking rules. (#1140)
This allows a sync server to send a `custom_url` field along with a rule blocking execution and this will be used as the URL for the "open" button in place of the normally generated URL.
2023-08-04 15:01:45 -04:00
Russell Hancox
aaa0d40841 sync: Add SyncExtraHeaders config option. (#1144)
* sync: Add SyncExtraHeaders config option.

Fixes #1143
2023-08-03 23:16:59 -04:00
Matt W
a424c4afca Only update daemon settings when sync settings explicitly set (#1142) 2023-08-03 16:18:40 -04:00
Matt W
2847397b66 Have distributed notifications delivered immediately (#1141) 2023-08-03 15:49:10 -04:00
Matt W
ad8b4b6646 Check if spool dir has changed before estimating size (#1138) 2023-08-03 14:54:14 -04:00
alexgraehl
39ee9e7d48 sync: Change backoff in SNTSyncStage.m to be exponential (#1135)
* Change backoff in SNTSyncStage.m to be exponential instead of linear
* Improves the log message to indicate that the job will ALWAYS abort after N retries. Previously, it was not clear why it would try 5 times and then give up.
2023-07-26 15:55:37 -04:00
Matt W
3cccacc3fb Add additional dep to satisfy import issue (#1134) 2023-07-26 12:50:29 -04:00
Matt W
6ed5bcd808 Enforce expected case for various rule type identifiers (#1132)
* Bump DB version. Ensure proper casing for rule identifiers on insert.

* Minor comment fixes, more test cases

* Handle SigningIDs using the delimiter character

* lint

* PR feedback
2023-07-26 12:31:28 -04:00
Matt W
bcac65a23e Wire up TTYWriter instance to the file access client (#1129) 2023-07-26 00:11:36 -04:00
Matt W
03fcd0c906 Add more file access config options (#1128)
* New file access config options supporting silencing and custom messages

* Rename custom message key
2023-07-26 00:01:04 -04:00
p-harrison
d3b71a3ba8 Update sync-protocol.md to include SIGNINGID rule type (#1130)
* Update sync-protocol.md

Couple of formatting changes, added SIGNINGID as a rule type

* Update docs/development/sync-protocol.md

Co-authored-by: Matt W <436037+mlw@users.noreply.github.com>

---------

Co-authored-by: Matt W <436037+mlw@users.noreply.github.com>
2023-07-25 14:31:13 -04:00
Pete Markowsky
9e124f4c51 Add kSyncEnableCleanSyncEventUpload to the _forcedConfigKeyTypes dict (#1123)
* Add kSyncEnableCleanSyncEventUpload to the _forcedConfigTypes dict.

* Add KVO helper.

---------

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
2023-07-06 17:39:51 -04:00
Matt W
cd719ccef4 Fix issue with invalid lengths (#1122)
* Fix issue with invalid lengths

* Disable clang format around a small block of code for now
2023-07-06 11:22:18 -04:00
Matt W
dde42ee686 Fix check to detect changes to StaticRules (#1121) 2023-06-30 16:39:52 -04:00
Pete Markowsky
d144e27798 Fix rule evaluation for TeamID and SigningID rules when encountering broken signatures. (#1120) 2023-06-30 09:54:27 -04:00
Matt W
afc2c216b8 Add include for proto status stub (#1119) 2023-06-29 13:32:14 -04:00
Matt W
03d7556f22 Use angle brackets for includes (#1118) 2023-06-29 11:55:46 -04:00
Nick Gregory
020827b091 Fix memleak in fsspool (#1115) 2023-06-29 10:17:08 -04:00
Russell Hancox
baa31a5db0 Conf: Update notarization_tool in signing script (#1116) 2023-06-28 22:32:58 -04:00
Pete Markowsky
9ba7075596 Add macOS 13 to the test matrix. (#1113) 2023-06-27 13:22:36 -04:00
Pete Markowsky
5d08538639 Add Support for Logging to JSON (beta feature) (#1112)
* Add support for logging protobuf to JSON.

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
2023-06-23 10:06:45 -04:00
Matt W
e73bafb596 Fix build issues due to macOS 13.3 SDK changes (#1110)
* Fix minor build issues due to changes in the macOS 13.3 SDK

* Disable -Wunknown-warning-option
2023-06-20 22:23:55 -04:00
Matt W
1e92d109a7 Basic dialog functionality when access to a watch item is denied (#1106)
* Basic working prototype to display a UI on blocked file access

* Force watch items policies to be silent for now

* Remove unused view

* Refactor to not use newer SwiftUI features

* Address PR feedback
2023-06-19 14:00:35 -04:00
Matt W
6a6aa6dce8 Abstract TTY writing so multiple writers can be synchronized (#1108)
* Abstract TTY writing so multiple writers can be synchronized

* Address PR feedback
2023-06-13 20:19:50 -04:00
Matt W
0715033d6a Migrate to new SNTRuleType enum values (#1107)
* Migrate to new SNTRuleType enum values

* Bump table version. Fix comments to address PR feedback.

* Add log message when a downgrade detected
2023-06-09 11:50:42 -04:00
Matt W
123d7a2d6a Update docs for signing id rules (#1105)
* Update docs for signing id rules

* Formatting, Address PR feedback
2023-05-30 13:27:29 -04:00
Matt W
7b4d997589 Fix missing check for FileChangesRegex (#1102) 2023-05-22 16:13:06 -04:00
Matt W
5307bd9b7f Fix precedence for static rule evaluation, update santactl fileinfo output. (#1100) 2023-05-18 15:05:23 -04:00
Matt W
0622e6de71 Handle database downgrade scenarios gracefully (#1099) 2023-05-17 04:31:40 +02:00
Russell Hancox
e7c32ae87d Update SECURITY.md (#1098) 2023-05-12 10:30:58 -04:00
Matt W
deaf3a638c Add new rule type for Signing IDs (#1090)
* WIP: Signing ID rules

* WIP: More work supporting signing ID rules

* Expanded exec controller tests for signing ID and team ID

* wip all current tests now pass

* Added integration tests

* Branch cleanup

* Update protobuf tests for signing id reason types

* Remove old commented out code

---------

Co-authored-by: Russell Hancox <russell@hancox.us>
2023-05-12 09:22:46 -04:00
Matt W
8a7f1142a8 Stop unmuting the default mute set unnecessarily. (#1095)
* Stop unmuting the default mute set unnecessarily.

* lint

* Added note to docs explaining operations from default mute set binaries aren't logged
2023-05-10 09:07:13 -04:00
Matt W
c180205059 Return unique_ptr from Enrich instead of shared_ptr (#1093) 2023-05-08 10:55:38 -04:00
Matt W
337df0aa31 Don't establish the FAA client pre-macOS 13 (#1091)
* Don't establish the FAA client pre-macOS 13

* Only watch FAA keys on macOS 13 and newer
2023-05-05 15:33:34 -04:00
Russell Hancox
e2b099aa50 santactl/rule: Fix --path argument (#1089)
Fixes #1088
2023-05-04 17:57:59 -04:00
Pete Markowsky
fc4e29f34c Docs: Added instructions for how to use config-overrides.plist (#1077)
* Added instructions for how to use config-overrides

---------

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
2023-05-01 16:16:11 -04:00
Matt W
bf3b6bc6e2 Inject additional dependencies into the serializers (#1078)
* Injects dependecies for decision cache and client mode lookup

* Fix up tests

* Stored client mode at decision time. Remove clientMode func injection.

* PR Feedback, group property members
2023-05-01 15:13:54 -04:00
Matt W
b810fc81e1 Add support to file monitoring config to invert process exceptions (#1083)
* Add support to file monitoring config to invert process exceptions

* Update docs

* Added link to github issue
2023-05-01 15:04:40 -04:00
Matt W
3b3aa999c5 Switch SNTEventState to uint64_t, reposition flag values and masks (#1086) 2023-05-01 14:37:11 -04:00
Faizan
59428f3be3 docs: Fix documentation for clean sync field in the preflight request. (#1082)
The 'request_clean_sync' field is set here: https://github.com/google/santa/blob/main/Source/santasyncservice/SNTSyncPreflight.m#L76
The constant is defined here: https://github.com/google/santa/blob/main/Source/common/SNTSyncConstants.m#L27
2023-04-27 23:38:44 -04:00
Jason McCandless
ae6451a9b2 docs: Clarify that execution_time, file_bundle_hash_millis and quarantine_timestamp are float64 (#1080) 2023-04-27 18:54:02 -04:00
Russell Hancox
feac080fa7 sync: Permit XSRF header between sync stages/sessions (#1081) 2023-04-27 10:52:35 -04:00
Nick Gregory
d0f2a0ac4d One more TSAN fix (#1079) 2023-04-26 17:30:06 +02:00
Pete Markowsky
7fc06ea9d8 Make the sync client content encoding a tunable (#1076)
Make the sync client content encoding a tunable.

This makes the sync client's content encoding a tunable so that it can be
compatible with more sync servers.

Removed the "backwards compatibility" config option.

---------

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
2023-04-24 15:00:29 +02:00
Russell Hancox
1dfeeac936 README: Add more badges (#1075) 2023-04-21 09:54:33 -04:00
Matt W
ac9b5d9399 Cache flush metrics (#1074)
* Added a reason enum when flushing auth result cache

* Set metrics when auth result cache is flushed.
2023-04-20 16:47:06 -04:00
Matt W
7f3f1c5448 Process unmount events first (#1073) 2023-04-19 11:13:13 -04:00
Russell Hancox
46efd6893f config: Add EnableSilentTTYMode key to disable TTY notifications. (#1072)
Fixes #1067
2023-04-19 10:38:24 -04:00
Matt W
50232578d6 Fix string length issues (#1070) 2023-04-13 10:03:52 -04:00
Russell Hancox
d83be03a20 sync: Add more complete XSSI prefix to be stripped. (#1068)
Sync will try stripping both the new longer prefix and the existing short prefix if the response data begins with either. This should have no impact on existing sync servers but will allow sync servers in the future to use the longer prefix if they wish.
2023-04-07 15:27:41 -04:00
Russell Hancox
119b29b534 GUI: Device event window, handle empty remount args (#1066) 2023-04-05 16:34:05 -04:00
Matt W
be87b3eaf2 Change types of repeated args and envs fields (#1063)
* Change types of repeated args and envs fields

* Update args and env testdata strings to base64

* Remove whitespace
2023-03-31 13:18:09 -04:00
Russell Hancox
0fe672817e sync: Fix case of empty header name (#1062) 2023-03-28 11:50:11 -04:00
Russell Hancox
c3b2fbf512 sync: Allow server to override the header for transmitting XSRF tokens (#1060)
This change allows a sync server to change the header that Santa will use to send XSRF tokens on subsequent requests by putting the header name in the  header.
2023-03-27 18:11:11 -04:00
Matt W
2984d98cb9 Document SigningID and PlatformBinary exception keys (#1059)
* Document SigningID and PlatformBinary exception keys

* Minor spacing
2023-03-25 11:34:06 -04:00
Nick Gregory
5295faef0e Fix a couple last TSAN failures (#1056)
* Skip testHandleMessage when testing with tsan

* fix other 2 tsan failures

* change action_env->test_env in bazelrc for sanitizers

* revert Source/santactl/BUILD formatting
2023-03-23 11:11:29 -04:00
Liam Nicholson
0209344f62 santad: Fix SD Card Block not operating on Internal SD Card Readers (#1055) 2023-03-22 17:54:11 -04:00
Matt W
53ca5eb811 Support filesystem monitoring config embedded in main Santa config (#1054)
* Allow setting file access policy in main Santa config

* Add some tests
2023-03-20 16:47:34 -04:00
Matt W
33c7aab9f1 Basic rate limiting for File Access Authorizer (#1053)
* WIP basic rate limiting support

* WIP added basic metrics when rate limited

* Hookup new metrics

* Cleanup old TODO

* PR feedback, update comments
2023-03-20 15:58:49 -04:00
Pål-Magnus Slåtto
f6d837ac31 chore(ci): Upgrade workflows to non-deprecated runtimes (#1052) 2023-03-15 09:42:16 -04:00
Matt W
5e0a383662 Properly report "file access client enabled" metrics (#1051) 2023-03-14 15:01:03 -04:00
Russell Hancox
8055b451bb Config: Ignore static rules with an invalid identifier (#1049) 2023-03-07 10:33:13 -05:00
Russell Hancox
c5e7736eef santactl/rule: Validate identifier is a valid SHA-256 for binary/cert rules (#1045)
Previously validation only applied when using the --sha256 flag, now it applies to --identifier too unless adding a team ID rule. The validation is also a bit more robust.

Fixes #1044
2023-03-01 13:44:44 -05:00
Matt W
61558048c0 Add basic metrics to report when the FAM client is enabled (#1043) 2023-02-17 11:57:18 -05:00
Matt W
cf0e3fd3db Add support for platform binary to process exceptions (#1041)
* Add support for platform bianry to process exceptions

* Fun with bool types
2023-02-17 11:30:46 -05:00
Matt W
15519c6de8 Clear ES cache when watch items change (#1042) 2023-02-17 11:04:08 -05:00
Pete Markowsky
a415679980 Fix sync protocol diagram. (#1037) 2023-02-08 16:13:08 -05:00
Nick Gregory
27ae60e265 Small test fixes to make sanitizers happy (#1030)
* Small test fixes to make sanitizers happy

* lint

* missing authclient

* new MockEndpointSecurityAPI per subtest
2023-02-06 20:16:22 +00:00
Matt W
29a50f072c Report log type in santactl status (#1036)
* Report log type in santactl status

* Remove unnecessary fallback case
2023-02-06 14:59:42 -05:00
Matt W
a97e82e316 Replace SNTDecisionCache dictionary with SantaCache (#1034)
* Replace SNTDecisionCache dictionary with SantaCache

* PR feedback. Fix tests.
2023-02-03 15:58:53 -05:00
Russell Hancox
532120ac02 Configurator: Return an unsafe_unretained pointer to avoid needless retain/release (#1035) 2023-02-03 15:55:15 -05:00
Russell Hancox
ec934854fc santactl & syncservice: Use synchronousRemoteObjectProxy where it makes sense (#1033) 2023-02-03 14:31:37 -05:00
Matt W
ad0e2abdac Restart daemon on log type change (#1031)
* WIP register for event log type changes. Flush metrics.

* Add Flush to writer interface. Flush logger on log type change.

* Standardize non-thread-safe method names
2023-02-03 11:04:57 -05:00
Matt W
dc11ea6534 Rework timeout handling in metrics HTTP writer (#1029)
* Change HTTP writer to use session config timeouts

* Remove unnecessary block variable

* Fix tests

* Revert serializer changes for now

* Remove setting timeoutIntervalForRequest
2023-02-02 10:58:28 -05:00
Matt W
3acf3c1d00 Use cached sizes when serializing (#1028) 2023-01-30 16:08:38 -05:00
Matt W
41bc3d2542 Perf: Translocate cache, reserve proto repeated fields (#1027)
* Translocate cache, reserve proto repeated fields

* Remove copy/paste
2023-01-30 12:18:32 -05:00
Pete Markowsky
45a5d4e800 Fix: Rewrite the SNTMetricHTTPWriter to avoid potential stack corruption (#1019)
* Updated the SNTMetricHTTPWriter to use a for loop to prevent crashes caused by writing to stop.

* Make requests serial again.

* Fix the typo,  I just pushed.

* Ensure we only lookup the timeout value once.

* Make SNTConfigurator assignment only happen once.
2023-01-30 11:53:26 -05:00
Matt W
82bd981f31 Fix team ID and signing ID checks (#1026)
* Fix policy checks with missing team/signing ids

* Update docs to clarify how symbolic links are handled
2023-01-30 09:14:27 -05:00
Russell Hancox
6480d9c99b docs: fix width of sidebar on larger windows (#1025) 2023-01-27 15:38:46 -05:00
Henry S
7e963080b3 add updated description (#1023)
Zentral has gained many more Santa-specific workflows since adding to this section in 2017. The updated description takes this into account.
2023-01-27 15:38:14 -05:00
Matt W
e58cd7d125 Remove Default column (#1024) 2023-01-27 15:28:31 -05:00
Russell Hancox
db597e413b docs: Support wider pages, fix syntax highlighting of plist (#1022) 2023-01-27 15:18:45 -05:00
Matt W
78f46896d5 Try with more vertical space (#1021) 2023-01-27 14:37:02 -05:00
Matt W
cc0742dbfb Fsmon docs table width (#1020)
* markdown spaces lol

* markdown vertical spaces lol

* more spaces why not
2023-01-27 14:32:58 -05:00
Matt W
9c2f76af72 Initial docs for file access auth feature (#1017)
* Initial docs for file access auth feature

* Apply suggestions from code review

Co-authored-by: Kathryn Hancox <44557882+kathancox@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: Kathryn Hancox <44557882+kathancox@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: Kathryn Hancox <44557882+kathancox@users.noreply.github.com>

* Updates based on PR feedback

---------

Co-authored-by: Kathryn Hancox <44557882+kathancox@users.noreply.github.com>
2023-01-27 14:08:34 -05:00
Matt W
a3ed5ccb40 Log type metrics (#1018)
* Add event log type to metrics

* lint

* PR Feedback
2023-01-27 10:22:09 -05:00
Nick Gregory
b4149816c7 Add new continuous test run with various sanitizers (#1016)
* continuous tests with sanitizer matrix

* dyld insert lib

* remove msan config and upload logs
2023-01-26 16:00:47 -05:00
Matt W
2313d6338d Remove extra expectation in test (#1015) 2023-01-26 11:42:14 -05:00
Russell Hancox
414fbff721 Project: Fix module maps for swift libraries and their dependencies (#1014) 2023-01-26 09:15:30 -05:00
Matt W
5a2e42e9b4 Reduce calls into configurator (#1013) 2023-01-25 16:51:13 -05:00
Matt W
f8d1b2e880 Reduce proto warning severity (#1012) 2023-01-25 14:37:00 -05:00
Matt W
5f4d2a92fc Ensure watch item names conform to naming requirements (#1011)
* Ensure watch item names conform to naming requirements

* Only compile regex once
2023-01-25 13:27:27 -05:00
Russell Hancox
4ccffdca01 GUI: Migrate DeviceMessageWindow to SwiftUI (#1010) 2023-01-25 12:16:31 -05:00
Nick Gregory
e60bbe1b55 shadow rules_python for fuzzing (#1009) 2023-01-23 11:11:48 -05:00
Russell Hancox
eee2149439 GUI: Re-write AboutWindow view in SwiftUI (#1007) 2023-01-20 13:43:50 -05:00
Russell Hancox
dcbbc33e5e Revert "Configurator: Apply config updates in non-daemon processes (#1003)" (#1008)
This reverts commit 1e88b88ee6.
2023-01-20 13:30:06 -05:00
Matt W
ebe5166d77 Prevent recursive reconnect attempts (#1005) 2023-01-19 10:03:15 -05:00
Matt W
6e5a530df5 Low hanging fruit perf changes (#1004)
* Some minor changes for some easy perf wins based on trace info

* Manually track buffer offsets in File writer

* Add metrics tests

* Call members from appropriate shared object
2023-01-18 15:14:48 -05:00
Russell Hancox
1e88b88ee6 Configurator: Apply config updates in non-daemon processes (#1003) 2023-01-18 10:00:39 -05:00
Nick Gregory
2d74f36ddb Reconnect to santametrics service on failure (#1001)
* Reconnect to santametrics service on failure

* use logging macros
2023-01-12 10:41:36 -05:00
Matt W
3a3564f36b Add watch item state to santactl status (#1000)
* Add method to get WatchItems state

* Update santactl status with watch items state

* Update status label

* PR feedback - add missing dispatch_group_leave
2023-01-12 10:38:12 -05:00
Matt W
d3c7cbbcc3 Rename type aliases (#999) 2023-01-11 11:30:11 -05:00
Matt W
1ff6967934 Support configuring signing IDs for process exceptions (#998) 2023-01-11 09:42:32 -05:00
Matt W
53877f6114 Adopt new FS Access Auth config format and policy application logic (#994)
* WIP parsing new watch item config format

* Change WatchItemPolicy param order. Define policy default constants.

* rename write_only policy member to allow_read_access

* WIP parsing new config format, WatchItemsTest all pass

* Restructured process config parsing. Added tons of tests.

* Abstract NSError creation to a function

* Better errors. Bubble up NSErrors to reduce duplicate messages. More Tests.

* Validate min string lengths. Add a bunch more tests.

* Adopt new policy process logic and add tests

* Address PR feedback
2023-01-10 16:40:13 -05:00
Matt W
8c50af4041 Add policy version and name to basic string serializer (#997) 2023-01-10 13:17:21 -05:00
Russell Hancox
d0d4508f77 docs: Fix deployment/configuration doc (#996) 2023-01-10 09:23:52 -05:00
Matt W
df3aac5baf Change name of santa config keys for file access monitoring (#995) 2023-01-09 21:08:57 -05:00
Nick Gregory
e289056e5e lower fuzz case timeout to 5s (#993) 2023-01-09 12:28:45 -05:00
Matt W
4adad2ecfa More event type support (#992)
* Add truncate and create support

* Add metrics support
2023-01-06 12:51:40 -05:00
Matt W
dc1a3c27c2 Add more event coverage in the file access client (#991)
* Support more file access protection event types

* Update tests for new events and method signatures

* lint

* Add metrics for new event types

* Add support for LINK event

* Fix spacing
2023-01-05 13:03:21 -05:00
Nick Gregory
a2f8030482 Fuzz embedded plist reading (#990)
* fuzz embedded plist reading

* remove newline

* consolidate size checking

* brackets

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
2023-01-03 14:22:31 -05:00
Matt W
338a4f738f Opportunistically use ES cache when possible (#989)
* WIP fixing up ES cacheability in file access client

* Removed old code from before simplification

* Add more tests
2023-01-03 14:09:21 -05:00
Nick Gregory
845d72eebd Fix nightly run cron specification (#986) 2022-12-28 17:36:54 -05:00
Nick Gregory
ca81270bff Fix SNTFileInfo Fuzzing (#985)
* fix SNTFileInfo fd leak

* auto poweroff VM after fuzzing

* lint
2022-12-27 16:20:32 -05:00
Matt W
42cf1b232a Adopt new ES APIs to watch target paths in tamper client (#984) 2022-12-22 16:49:25 -05:00
Nick Gregory
57285c48dd use new public api for booting VM into recoveryOS (#983) 2022-12-22 16:27:38 -05:00
Nick Gregory
2279cd8662 Run fuzzing in a VM (#982)
* run fuzzing in a vm

* no use cleaning up since each VM is pristine
2022-12-22 13:52:46 -05:00
Nick Gregory
9423beecc8 fix spinloop when no override config is specified (#981) 2022-12-22 13:51:46 -05:00
Pete Markowsky
b18d4a0e30 Fix SNTFileInfoTest for macOS 13 (#977)
* Fix SNTFileInfoTest for macOS 13
2022-12-22 10:37:22 -05:00
Russell Hancox
290ebed15e Allstar: Add fuzzing artifact (#980) 2022-12-22 09:13:53 -05:00
Matt W
435868aa7a Add build targets, lint (#978) 2022-12-21 22:56:20 -05:00
Nick Gregory
2e3952a31d Revitalize Fuzzing (#976)
* snapshot using rules_fuzzing, but this probably wont work because nothing supports objc

* working fuzz

* clean up

* install libclang_rt.fuzzer_osx automatically; add to CI

* retain corpus

* restore old fuzzing stuff

* corpus

* move fuzz to separate timed action

* review
2022-12-21 15:29:07 -05:00
Matt W
60f53bc20a Adopt new ES APIs to monitor target paths (#975)
* WIP begin adopting new ES APIs inverting target mute paths

* Track subscription status so as not to unnecessarily enable/disable

* Properly chain call to invert target mute paths. Fix using wrong Message obj.

* Add base client tests

* Support compiling on older platforms

* More changes to support compiling on older platforms

* Only enable watch items periodic task on macOS 13

* Add more asserts to test

* Disable ES caching for now

* lint
2022-12-20 21:15:01 -05:00
Russell Hancox
fec3766da4 Project: Upgrade MOLAuthenticatingURLSession to v3.1 (#974) 2022-12-19 15:12:09 -05:00
Matt W
ae63055f34 Fix golden test data for macOS 13 (#972) 2022-12-19 14:47:06 -05:00
Russell Hancox
e5a0c3c1c0 sync: Fix deduplication in reachability handler (#973) 2022-12-19 14:42:18 -05:00
Matt W
5680c69164 Address policy consistency issues (#971)
* Change FindPolicyForPath to operate on vector of inputs

* Adopt new interface to find all policies simultaneously

* Fix tests to use new FindPoliciesForPath signature
2022-12-19 14:20:05 -05:00
Nick Gregory
8a978c1e75 Update LICENSE for VM code (#970) 2022-12-16 12:21:49 -05:00
Matt W
6aa7c9ba86 Fix import issues (#969)
* Fix import issues

* lint
2022-12-15 16:10:26 -05:00
Matt W
6adef6a714 Track path types for current/new watch items (#968)
* Move WatchItemPolicy to its own header. Add path type enum.

* When tracking current/new paths, also track path types

* lint
2022-12-15 15:44:47 -05:00
Nick Gregory
1d8c105257 absl_guarded_by (#967) 2022-12-15 13:34:32 -05:00
Matt W
e2d7cf04fc Fix under retain (#966) 2022-12-15 12:50:59 -05:00
Nick Gregory
9d448071f7 Lint the E2E start-vm Python script (#965)
* appease the linter

* add python to the lint script
2022-12-14 17:37:56 -05:00
Nick Gregory
cd6c0e7120 Introduce end-to-end testing (#919)
* initial e2e work

* switch to entitlements property instead of codesignopts hack

* bring moroz patches in

* go ahead and switch to upstream

* lint

* no need to install gcs every time

* codeowners

* add comments

* move to new e2e workflow

* rename e2e workflow
2022-12-14 11:15:55 -05:00
Matt W
ec5e8177fb Serialize File Access events (#964)
* WIP skeleton code for file access event serialization

* Added basic string serializer for file access event

* Added proto string serializer for file access event
2022-12-14 11:04:37 -05:00
Russell Hancox
8e10c103cb santad: Flush cache when StaticRules are changed (#963) 2022-12-13 16:57:13 -05:00
Matt W
db6c14ea10 Enrich file access events, prepare for logging (#962)
* WIP refactor file access class to setup logging

* Combined GetPathTarget1 and 2, added some tests.

* Change method name to not be abbrv.

* Remove unnecessary includes

* PR feedback: fix missing path sep, add comments

* Fix test issue
2022-12-12 16:37:47 -05:00
Matt W
4a4f1a971c Fix issue where wrong variable was used (#961) 2022-12-09 15:07:30 -05:00
Matt W
c5c82a18ff Dynamically enable/disable FS Access client based on config (#959)
* WIP Dynamic watch item config loading. Dynamic event handler protocol.

* Clients can now register with WatchItems to be enabled/disabled

* Handle dynamic fs monitor config add/modify/delete, dynamic enable/disable clients

* Update WatchItemsTest to use new constructor

* Better check handling value changes

* Add missing mock config value to fix integration test
2022-12-09 11:54:54 -05:00
Russell Hancox
f702c7a281 Tests: Fix SNTEndpointSecurityFileAccessAuthorizerTest (#958) 2022-12-08 15:46:51 -05:00
Russell Hancox
958ef52698 Config: In debug builds, allow config to be overriden from a plist file. (#957) 2022-12-08 15:07:59 -05:00
Matt W
068ec885b2 pemdas (#955)
* pemdas

* lint
2022-12-07 17:07:05 -05:00
Matt W
e572f047c0 Import fix (#953) 2022-12-07 14:07:13 -05:00
Matt W
b904a329d9 FS Access Config Version, Policy decision enums (#951)
* Add policy version to config. Return policy decision as enum.

* Check EnableBadSignatureProtection config when evaluating instigating procs

* Draft proto update for file access

* Revert "Draft proto update for file access"

This reverts commit 5d7e9a9e03.

* Change return type to work around OCMock partial mocking issues

* lint
2022-12-07 13:33:35 -05:00
Matt W
d19343bccd Draft proto for new FileAccess log (#952)
* Draft proto for new FileAccess log

* Update Source/common/santa.proto

Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>

Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>
2022-12-07 13:06:47 -05:00
Matt W
09cd78d756 Initial work for File Access Authorizer Client (#949)
* WIP Initial work for new fs watcher client

* WIP basic working mechanics of applying policy to OPEN events

* WIP now support allowing access based on cdhash

* WIP lint fix

* WIP check instigator cdhash and cert hash against policy

* WIP Fix test issue in base ES client class

* WIP Fix test issue in water items test

* Added secondary lookup cache for cert hashes and fallback lookups

* Adopt new SantaVnode name

* Adopt min macOS 11. Adopt new SantaCacheHasher for SantaVnode.

* Rename the es client to FileAccessAuthorizer

* Added some more tests

* Added MockLogger and a lot more tests.

* Removed currently unused subscriptions. Don't enable FS client by default

* lint

* lint after rebase

* Use strtoul for hex string conversion. Update comments.

* PR feedback
2022-12-06 19:52:32 -05:00
Russell Hancox
f169b69944 santad: Change workaround for glob header with blocks, free glob-allocated memory (#948) 2022-12-05 15:52:17 -05:00
Russell Hancox
40f9872c54 Tests: Fix some assertions comparing strings (#947) 2022-12-05 12:54:04 -05:00
Matt W
5718f2e582 Watch items (#937)
* WIP started work on parsing config

* WIP Basics of parsing config and generating new policy

* WIP Reapplying config updates functionally complete. Needs a lot more tests.

* Test cleanup, added using decl for watch items tree type

* More WatchItems tests and test polishing.

* Remove test print function. Formatting.

* Commented use of __BLOCKS__ undef

* Return a shared_ptr from factory

* Change WatchItemsPolicy to store sets instead of vectors

* Remove unnecessary WatchItem, replace with string

* Typo

* Update error messages to not make it sound like parse errors are recoverable
2022-12-01 13:41:05 -05:00
Liam Nicholson
04fd742114 Include SD Card Mounting in the USB Block Functionality (#938) 2022-12-01 10:25:54 -05:00
Matt W
194a3a6d4a Remove SNTCommon (#945)
* Move santa_action_t to SNTCommonEnums and rename to SNTAction

* Move likely and unlikely macros to a new BranchPrediction header

* Remove SNTCommon.h. Move SantaVnode to its own header.

* Add SantaVnodeHash

* Fix build deps
2022-12-01 09:14:54 -05:00
Matt W
e1dc50fb36 Drop macOS 10.15 (#944)
* Drop macOS 10.15 support

* lint
2022-11-29 20:20:48 -05:00
Matt W
9ff2f0d631 Swtich from task_info to libproc for system resource info (#939)
* Swtich from task_info to libproc for system resource info

* Fix return value

* Convert nanos to seconds

* Make GetTimebase static. Expose NanosToMachTime.

* Abstract return or GetTaskInfo to new type.
2022-11-29 16:50:37 -05:00
Matt W
85058ec290 Rename santa_vnode_id_t to SantaVnode (#943)
* Rename santa_vnode_id_t to SantaVnode. Add factory.

* Change types of SantaVnode to match stat(2)
2022-11-28 23:45:14 -05:00
Russell Hancox
6e90673f71 docs: Update keyserver address in SECURITY (#941) 2022-11-28 19:35:02 -05:00
Russell Hancox
a58cee908f docs: Fix typo in sync-protocol, h/t to @maxwbuckley (#940) 2022-11-28 17:21:45 -05:00
Russell Hancox
80b26955b4 GUI: Fix distributed notifications in silent mode (#936) 2022-11-16 09:53:56 -05:00
Matt W
6a84023548 Prefix tree updates (#931)
* WIP Rename SNTPrefixTree to PrefixTree

* WIP Implement the new PrefixTree and tests

* Add Unit type. Fix build and tests.

* lint

* Make NodeCount accessor for tests

* Updated comments
2022-11-14 13:16:49 +00:00
Russell Hancox
e70acefb5c Docs: Fix type of {allowed,blocked}_path_regex keys in preflight (#934) 2022-11-07 15:36:10 -05:00
Matt W
41c918ee87 Don't add messages when accumulated bytes exceeds threshold (#932)
* Don't add messages when accumulated bytes exceeds threshold

* Add a leniency factor

* lint
2022-11-07 12:24:49 -05:00
Matt W
1adb6d2726 Update spool to flush on size thresholds instead of batch counts (#930) 2022-11-03 14:55:51 -04:00
Matt W
8c531a256b metrics and logging cleanup (#928)
* Metrics and ambiguous log cleanup

* Fix test
2022-11-01 14:47:49 +00:00
Russell Hancox
5829363733 GUI: Fix EnableSilentMode key (#927) 2022-11-01 10:11:21 -04:00
Pete Markowsky
379f283c62 Update Known Limitations for USB Mass Storage Blocking (#924)
* Updated known limitations.
2022-10-28 20:21:38 -04:00
Matt W
2082345c02 Change order that ES clients are enabled (#923) 2022-10-29 00:15:26 +00:00
Matt W
dd8f81a60e Fix issue in test that would crash on some platforms (#922) 2022-10-28 20:14:53 -04:00
Matt W
8ccb0813f1 More import fixes (#921)
* More import fixes

* lint
2022-10-28 15:57:01 -04:00
Matt W
b24e7e42bf Event metrics (#918)
* WIP. Record event count and processing time metrics. Tests don't currently build.

* Updated tests

* Fix field names

* Remove unused target

* formatting

* Cleanup from PR comments
2022-10-28 14:25:07 -04:00
Pete Markowsky
4821ebebd5 Fix: duplicates bug in SNTMetricSet when using multiple fields (#920)
Fix duplicates bug in SNTMetricSet when using multiple fields names.

This also fixes the santactl metric command and golden files for tests.
2022-10-28 13:50:08 -04:00
Matt W
efeaa82618 Fix issue with transposed remount/banned block messages (#917) 2022-10-26 20:54:17 -04:00
videlanicolas
3f3de02644 USB: usbBlockMessage is not being used. (#915) 2022-10-26 17:42:49 -04:00
Matt W
f6c9456ea7 Fix some more includes (#914) 2022-10-25 16:52:19 -04:00
Matt W
2aaff051c8 Various changes to fix import (#913) 2022-10-25 16:16:44 -04:00
Matt W
2df7e91c87 Change include to import (#912) 2022-10-24 11:56:02 -04:00
Matt W
37644acd01 Update build docs. Fixes #910 (#911) 2022-10-24 09:55:37 -04:00
Matt W
899ca89e23 Proto minimization (#909)
* Create Light variants of File and ProcessInfo messages to reduce disk/wire byte counts

* Updated golden test data
2022-10-21 19:48:37 -04:00
Matt W
e7281f1c55 Spool writer (#908)
* Spool writer and santactl command to print proto file

* Make valid JSON for multiple paths. Can now create proto/spool logger. Updated logger tests.

* Make fsspool writer and fsspool log batch writer injectable

* Add spool writer tests

* Updated help text for santactl printlog

* Include file cleanup

* Fix dispatch source destruction

* Change config keys for the new Spool writer

* Spool settings now configurable

* Fix param order

* Remove some test sleeps related to control flow
2022-10-21 16:43:12 -04:00
Matt W
bf0ca24ae7 Machine id proto (#907)
* Add MachineID to all BasicString serialized log messages

* machine_id now a top level proto field

* Remove commented code
2022-10-19 10:51:38 -04:00
np5
4fe8b7908f sync: Fix USB blocking config sync (#890) 2022-10-18 10:01:20 -04:00
Matt W
a8dd332402 Update include paths and add include guard (#905) 2022-10-14 17:58:36 -04:00
Matt W
6631b0a8e3 More import fixes (#904)
* Layering check disable

* workaround for layering issue
2022-10-14 17:20:20 -04:00
Matt W
07e09db608 Import fixes (#902)
* Apply clang-format to cc files

* Modify binaryproto namespace

* Add more required includes

* Add proto includes

* Assert message parsing succeeds in test

* Add optional keyword to proto fields to track presence. TESTS BROKEN.

* Update golden test data
2022-10-14 15:51:53 -04:00
Matt W
d041a48c97 Fsspool adopt (#900)
* Added fsspool library, tests

* Cleanup

* Remove extra visibility from BUILD file

* Import foundation so the linter doesn't complain
2022-10-13 20:47:52 -04:00
Matt W
1683e09cc8 Proto serializer (#897)
* Initial proto serializer with close event

* Define move ctors for enriched types, delete copy ctors

* More event proto serialization. Commonized proto test code.

* Started work serializing exec event. Added serializer utilities.

* More progress serializing exec event

* Add mroe test data. Test restructure to permit fine grained mocking.

* Env/FD ES types now wrapped in EndpointSecurityAPI. Added calls to proto serializer.

* Add fd type names to proto

* Version compat. Script and Working Dir encoding.

* Add process start time

* Serialize Link event

* Add null check, mainly to fix tests

* Handle versioned expectations

* Each test now build msg in callbacks to set better expectations

* Serialize rename event and tests

* Serialize unlink event and tests

* Serialize allowlist and bundle events. Add utilities tests.

* Formatting

* Disk event proto serialization and tests

* Fix test only issues

* Rename santa_new.proto to santa.proto

* Change fd type int and string to an enum

* Proto namespace now versioned

* Added comments to proto schema

* Add proto support to indicate if fd list truncated
2022-10-13 13:52:41 -04:00
Ivan Tadeu Ferreira Antunes Filho
d6c73e0c6c common: Make SNTCommonEnums a textual header (#896)
This change fixes -wunused-variable warnings. The header is not valid by itself and should be declared as a textual header rather than as a header.
2022-10-03 13:15:33 -04:00
Matt W
72969a3c92 Fix crash flushing cache on unmount events (#895) 2022-09-27 21:54:35 -04:00
Matt W
d2dbed78dd Return a value from the test block (#894) 2022-09-27 15:07:20 -04:00
Matt W
8fa91e4ff0 Build deps (#893)
* Too bad we can't require explicit build deps...

* More deps
2022-09-23 13:55:48 -04:00
Matt W
551763146d Linter and BUILD deps fixups (#892)
* Minor changes to address lint issues

* Add more BUILD deps

* Include cleanup

* Even more BUILD deps

* Still more BUILD deps
2022-09-23 11:18:58 -04:00
Matt W
7a7f0cd5a8 Ingestion fixups (#891) 2022-09-22 12:30:34 -04:00
Matt W
fcb49701b3 ES and Logging Interfaces Redesign (#888)
* Initial structure for ES wrappers, enriched types, logging

* Basic working ES and logging functionality

* Add in oneTBB and thread-safe-lru deps

* Added a bunch of enriched types

* Auto-mute self when establishing ES client

* Basic auth, tamper client. Syslog of all events. Basic compiler tracking.

* Update copyright header blobs, convert some tabs to spaces

* Auth result cache. Fix getting translocation path.

* Added remaining cache methods

* Add AuthResultCache to Recorder client. Cache now operates on es_file_t.

* Hooked up SNTPrefixTree

* Fix CompilerController for RENAME. Fix AllowList logging missing path.

* Block loading Santa kext

* Added device manager client

* Properly log DiskAppear events

* Fix build to adopt new adhoc build

* Handle clearing cache on UNMOUNT events

* Ignore other ES clients if configured

* Remove SNTAllowlistInfo. Rename AllowList to Allowlist. Minor cleanup.

* Recorder now logs asynchronously. Enricher now returns shared_ptrs.

* Added File writer. Added timestamps to BasicStream serializer.

* Skip calling stat in SNTFileInfo when path given by ES.

* Fix build issue

* Address draft PR feedback

* santactl integrated, XPC works, fix file writer bug

* Integrate syncservice. Start observing some config changes.

* Add metrics service wrapper

* Add metrics config observers and metrics interval reset.

* Start better dependency control. Add Null logger support.

* Added more deps

* Added more deps

* Fix issue where metric service wasn't starting

* Add missing variant include

* Fix missing parent proc name

* Added googletest and new unit test macro

* Started expanding AuthResultCacheTest

* Properly mock EndpointSecurityAPI

* Finished AuthResultCacheTest

* bazelrc now builds all C++ as C++17. Added LoggerTest.

* Add FileTest. Abstract some File constants to Logger.

* Added Empty serializer test

* Started work on BasicStringTest. Fixed some BasicString serialization bugs.

* Added Unlink BasicString serialization test

* Added some more tests. Commonized some test code

* Finished BasicStringTest. Converted to XCTest.

* Standardize esapi variable naming

* Bubble up gTest expect failures to XCTest failures

* AuthResultCacheTest now uses XCTest. Added common TestUtils.h

* EmptyTest now uses XCTest.

* FileTest now uses XCTest

* LoggerTest now uses XCTest. Removed santa_unit_gtest bazel macro.

* Added ClientTest

* Add basic Enricher tests

* Add MessageTest. Make more TestUtils.

* Rename metrics to Metrics

* Add MetricsTest.

* Apply template pattern to Serializer

* Add SNTDecisionCacheTest.

* Add SNTCachedDecisionTest.

* Testing with coveralls debug mode

* Allow manual CI runs

* Remove unused property

* Started work on SNTEndpointSecurityClientTest.

* WIP SNTEndpointSecurityClientTest, fix test run issue

* Added more base ES client tests

* Add more base ES client tests

* Base ES client tests done. Added serializer utils/tests. Expanded basic string tests.

* Add utils test to test suite

* Add copy ctor. Add test output to bazel coverage.

* Single thread bazel coverage

* Updaload coverage file

* Updaload coverage file

* Old gen cov test

* Restructure message handlers to enable better testability

* Added enable tests for all ES clients

* Made a single MockEndpointSecurityAPI class to share everywhere

* Added most of SNTCompilerControllerTest

* Cleanup SNTCompilerControllerTest

* Started expanding Auth client test

* Finished up the Authorizer tests

* Move to using enum class for notify/auth instead of bool

* WIP for tamper resistance test. ASAN issues.

* Add OCMock patch to fix test issue on ARM Macs

* Changed patches directory name to external_patches

* Update WORKSPACE path

* Finished up Tamper Resistance tests

* Finished up Recorder tests.

* Move SNTExecutionControllerTest to ObjC++

* Initial work to port SNTExecutionControllerTest

* Finished porting SNTExecutionControllerTest.

* Added SNTExecutionControllerTest to list of unit tests

* Ported SNTEndpointSecurityDeviceManager.

* Test cleanup, use MockESAPI expectation helpers

* Verify SNTEndpointSecurityDeviceManager expectations differently

* Test cleanup, omit gTest param list where unused

* Log message cleanup

* Rename SNTApplicationTest to santad_test.mm

* Finished porting santad_test, formerly SNTApplicationTest

* Fix SNTEndpointSecurityDeviceManager issues

* Pulled in missed fixes. Updated tests.

* Renamed lowercase filenames to match rest of codebase

* Fix non-static dispatch_once_t, and noisy watching compiler log message

* WIP Started process of removing components no longer used

* WIP Continued process of removing components no longer used

* BUILD file cleanup. Proto warning. Removed unused global

* Rename SNTEventProvider to SNTEndpointSecurityEventHandler

* Rename SNTEndpointSecurityEventHandler protocol

* Remove EnableSysxCache option. Remove --quick flag used during dev.

* Ran testing/fix.sh

* Addmissing param to fix.sh that was omitting .mm files.

* clang-format

* Fix linter: find cmd missing .mm ext, git grep exclude patch files.

* Use MakeESProcess default params in tests

* Move variables to camelCase in objc classes

* More case changes

* Sanitize strings

* Change dispatch queue priorities and standardize daemon queue naming

* Exclude patch files in markdown check

* Ensure string log messages end with newline

* Fix BasicStringTest

* Disable clang-format in code producing different results in local/remote versions

* Moved to using date ranges in copyright notices as per current guidelines

* Update Source/common/SNTConfigurator.h

Suggestion adding whitespace in comment to fix clang-format mangling

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>

* Removed santa_panic macro used in one place

* Updated comment about ES cachability

* Pin oneTBB to specific commit

* Address outstanding WORKSPACE 'canonical reproducible form' messages

* Use string append instead of ostringstream due to benchmark results

* Remove use of freind classes in EnrichedTypes.h

* Added SNTKVOManager, removed observers from SNTConfigurator.

* Fixed SNTEndpointSecurityRecorderTest class name

* Reduce usage of the auto keyword

* Each SNTKVOManager instance now adds its own observer

* Replaced more auto keywords with real types.

* Remove leftover code coverage debugging from ci.yml

* Updated comment

* Memoize SNTFileInfo sha256. Reduce some cache sizes.

* Fix issue checking for translocated paths

* Use more performant NSURL creation method

* Fix lint issue

* Address PR feedback

* Use an array literal for kvo objects

* Fix some clang tidy and import issues

* Replace third party LRU cache with SantaCache for now

* Fix clang tidy issues

* Address PR feedback

* Fix comment typo

Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>

* Added todo for when we adopt macOS 13

Co-authored-by: Russell Hancox <russellhancox@users.noreply.github.com>
Co-authored-by: Pete Markowsky <pmarkowsky@users.noreply.github.com>
2022-09-22 10:18:41 -04:00
Russell Hancox
c9ef723fc5 Project: Update bazel and apple-rules (#887) 2022-08-29 17:52:27 -04:00
Pete Markowsky
dc6732ef04 Refactor the SNTApplicationTest unit tests to function correctly (#885)
* Refactor the SNTApplicationTest unit tests to function correctly.

The tests were originally written in a table style and were impacted by the lack of mocking the configurator. This caused issues with static rules to impact the unit tests.

Additionally added improved logging messages for critical binaries and a todo for macOS 13 unit tests.

Added goodbinary and rules.db test files to allstar's ignored paths.
2022-08-29 13:18:04 -04:00
Russell Hancox
a48900a4ae Allstar: Pre-emptively check-in binary_artifacts.yaml to exclude test binaries (#884) 2022-08-25 09:32:43 -04:00
Russell Hancox
bb49118d94 README: Try again, this time replacing the correct bit (#883) 2022-08-24 16:26:30 -04:00
Russell Hancox
456333d6d2 README: Fix logo link, remove coverage badge (#882) 2022-08-24 16:22:37 -04:00
498 changed files with 46550 additions and 11513 deletions

View File

@@ -0,0 +1,19 @@
# Ignore reason: These crafted binaries are used in tests
ignorePaths:
- Fuzzing/common/MachOParse_corpus/ret0
- Source/common/testdata/bad_pagezero
- Source/common/testdata/missing_pagezero
- Source/common/testdata/missing_pagezero
- Source/common/testdata/missing_pagezero
- Source/common/testdata/32bitplist
- Source/common/testdata/BundleExample.app/Contents/MacOS/BundleExample
- Source/common/testdata/DirectoryBundle/Contents/MacOS/DirectoryBundle
- Source/common/testdata/DirectoryBundle/Contents/Resources/BundleExample.app/Contents/MacOS/BundleExample
- Source/santad/testdata/binaryrules/badbinary
- Source/santad/testdata/binaryrules/goodbinary
- Source/santad/testdata/binaryrules/badcert
- Source/santad/testdata/binaryrules/banned_teamid_allowed_binary
- Source/santad/testdata/binaryrules/banned_teamid
- Source/santad/testdata/binaryrules/goodcert
- Source/santad/testdata/binaryrules/noop
- Source/santad/testdata/binaryrules/rules.db

View File

@@ -3,3 +3,45 @@ build --apple_generate_dsym --define=apple.propagate_embedded_extra_outputs=yes
build --copt=-Werror
build --copt=-Wall
build --copt=-Wno-error=deprecated-declarations
# Disable -Wunknown-warning-option because deprecated-non-prototype
# isn't recognized on older SDKs
build --copt=-Wno-unknown-warning-option
build --copt=-Wno-error=deprecated-non-prototype
build --per_file_copt=.*\.mm\$@-std=c++17
build --cxxopt=-std=c++17
build --host_cxxopt=-std=c++17
build --copt=-DSANTA_OPEN_SOURCE=1
build --cxxopt=-DSANTA_OPEN_SOURCE=1
# Many config options for sanitizers pulled from
# https://github.com/protocolbuffers/protobuf/blob/main/.bazelrc
build:san-common --strip=never
build:san-common --copt="-Wno-macro-redefined"
build:san-common --copt="-D_FORTIFY_SOURCE=0"
build:san-common --copt="-O1"
build:san-common --copt="-fno-omit-frame-pointer"
build:asan --config=san-common
build:asan --copt="-fsanitize=address"
build:asan --copt="-DADDRESS_SANITIZER"
build:asan --linkopt="-fsanitize=address"
build:asan --test_env="ASAN_OPTIONS=log_path=/tmp/san_out"
build:tsan --config=san-common
build:tsan --copt="-fsanitize=thread"
build:tsan --copt="-DTHREAD_SANITIZER=1"
build:tsan --linkopt="-fsanitize=thread"
build:tsan --test_env="TSAN_OPTIONS=log_path=/tmp/san_out:halt_on_error=true"
build:ubsan --config=san-common
build:ubsan --copt="-fsanitize=undefined"
build:ubsan --copt="-DUNDEFINED_SANITIZER=1"
build:ubsan --copt="-fno-sanitize=function" --copt="-fno-sanitize=vptr"
build:ubsan --linkopt="-fsanitize=undefined"
build:ubsan --test_env="UBSAN_OPTIONS=log_path=/tmp/san_out"
build:fuzz --config=san-common
build:fuzz --@rules_fuzzing//fuzzing:cc_engine=@rules_fuzzing//fuzzing/engines:libfuzzer
build:fuzz --@rules_fuzzing//fuzzing:cc_engine_instrumentation=libfuzzer
build:fuzz --@rules_fuzzing//fuzzing:cc_engine_sanitizer=asan

View File

@@ -1 +1 @@
5.0.0
7.0.0

View File

@@ -9,6 +9,12 @@ jobs:
markdown-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- uses: gaurav-nelson/github-action-markdown-link-check@v1
- run: "! git grep -EIn $'[ \t]+$'"
- name: "Checkout Santa"
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # ratchet:actions/checkout@v4
- name: "Check for deadlinks"
uses: lycheeverse/lychee-action@2b973e86fc7b1f6b36a93795fe2c9c6ae1118621 # ratchet:lycheeverse/lychee-action@v1
with:
fail: true
- name: "Check for trailing whitespace and newlines"
if: '!cancelled()'
run: "! git grep -EIn $'[ \t]+$' -- ':(exclude)*.patch'"

View File

@@ -1,5 +1,4 @@
name: CI
on:
push:
branches:
@@ -11,54 +10,42 @@ on:
- main
paths:
- 'Source/**'
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # ratchet:actions/checkout@v3
- name: Run linters
run: ./Testing/lint.sh
build_userspace:
strategy:
fail-fast: false
matrix:
os: [macos-10.15, macos-11, macos-12]
os: [macos-12, macos-13, macos-14]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Build Userspace
run: bazel build --apple_generate_dsym -c opt :release --define=SANTA_BUILD_TYPE=adhoc
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # ratchet:actions/checkout@v3
- name: Build Userspace
run: bazel build --apple_generate_dsym -c opt :release --define=SANTA_BUILD_TYPE=adhoc
unit_tests:
strategy:
fail-fast: false
matrix:
os: [macos-10.15, macos-11, macos-12]
os: [macos-12, macos-13, macos-14]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # ratchet:actions/checkout@v3
- name: Run All Tests
run: bazel test :unit_tests --define=SANTA_BUILD_TYPE=adhoc --test_output=errors
test_coverage:
runs-on: macos-11
runs-on: macos-14
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # ratchet:actions/checkout@v3
- name: Generate test coverage
run: sh ./generate_cov.sh
- name: Coveralls
uses: coverallsapp/github-action@master
uses: coverallsapp/github-action@09b709cf6a16e30b0808ba050c7a6e8a5ef13f8d # ratchet:coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
path-to-lcov: ./bazel-out/_coverage/_coverage_report.dat
flag-name: Unit
benchmark:
runs-on: macos-11
steps:
- uses: actions/checkout@v2
- name: Run All Tests
run: ./Testing/benchmark.sh

View File

@@ -1,13 +1,13 @@
name: continuous
on:
schedule:
- cron: '* 10 * * *' # Every day at 10:00 UTC
- cron: '0 10 * * *' # Every day at 10:00 UTC
workflow_dispatch: # Allows you to run this workflow manually from the Actions tab
jobs:
preqs:
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Checks for flaky tests
run: bazel test --test_strategy=exclusive --test_output=errors --runs_per_test 50 -t- :unit_tests --define=SANTA_BUILD_TYPE=adhoc

67
.github/workflows/e2e.yml vendored Normal file
View File

@@ -0,0 +1,67 @@
name: E2E
on:
schedule:
- cron: '0 4 * * *' # Every day at 4:00 UTC (not to interfere with fuzzing)
workflow_dispatch:
jobs:
update_vm:
runs-on: e2e-host
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # ratchet:actions/checkout@v3
- name: Update VM
env:
GCS_KEY: ${{ secrets.GCS_SERVICE_ACCOUNT_KEY }}
run: |
export GOOGLE_APPLICATION_CREDENTIALS=/tmp/gcp.json
echo "${GCS_KEY}" > ${GOOGLE_APPLICATION_CREDENTIALS}
function cleanup {
rm /tmp/gcp.json
}
trap cleanup EXIT
python3 Testing/integration/actions/update_vm.py macOS_14.bundle.tar.gz
start_vm:
runs-on: e2e-host
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # ratchet:actions/checkout@v3
- name: Start VM
env:
RUNNER_REG_TOKEN: ${{ secrets.RUNNER_REG_TOKEN }}
run: python3 Testing/integration/actions/start_vm.py macOS_14.bundle.tar.gz
integration:
runs-on: e2e-vm
env:
VM_PASSWORD: ${{ secrets.VM_PASSWORD }}
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # ratchet:actions/checkout@v3
- name: Add homebrew to PATH
run: echo "/opt/homebrew/bin/" >> $GITHUB_PATH
- name: Install configuration profile
run: bazel run //Testing/integration:install_profile -- Testing/integration/configs/default.mobileconfig
- name: Build, install, and sync santa
run: |
bazel run :reload --define=SANTA_BUILD_TYPE=adhoc
bazel run //Testing/integration:allow_sysex
- name: Test config changes
run: ./Testing/integration/test_config_changes.sh
- name: Build, install, and start moroz
run: |
bazel build @com_github_groob_moroz//cmd/moroz:moroz
cp bazel-bin/external/com_github_groob_moroz/cmd/moroz/moroz_/moroz /tmp/moroz
/tmp/moroz -configs="$GITHUB_WORKSPACE/Testing/integration/configs/moroz_default/global.toml" -use-tls=false &
sudo santactl sync --debug
- name: Run integration test binaries
run: |
bazel test //Testing/integration:integration_tests
sleep 3
bazel run //Testing/integration:dismiss_santa_popup || true
- name: Test sync server changes
run: ./Testing/integration/test_sync_changes.sh
- name: Test USB blocking
run: ./Testing/integration/test_usb.sh
- name: Poweroff
if: ${{ always() }}
run: sudo shutdown -h +1

35
.github/workflows/fuzz.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: Fuzzing
on:
schedule:
- cron: '0 6 * * *' # Every day at 6:00 UTC
workflow_dispatch: # Allows you to run this workflow manually from the Actions tab
jobs:
start_vm:
runs-on: e2e-host
steps:
- uses: actions/checkout@v3
- name: Start VM
run: python3 Testing/integration/actions/start_vm.py macOS_13.bundle.tar.gz
fuzz:
runs-on: e2e-vm
steps:
- uses: actions/checkout@v3
- name: Setup libfuzzer
run: Fuzzing/install_libclang_fuzzer.sh
- name: Fuzz
run: |
for target in $(bazel query 'kind(fuzzing_launcher, //Fuzzing:all)'); do
bazel run --config=fuzz $target -- -- -max_len=32768 -runs=1000000 -timeout=5
done
- name: Upload crashes
uses: actions/upload-artifact@v1
if: failure()
with:
name: artifacts
path: /tmp/fuzzing/artifacts
- name: Poweroff VM
if: ${{ always() }}
run: sudo shutdown -h +1

30
.github/workflows/sanitizers.yml vendored Normal file
View File

@@ -0,0 +1,30 @@
name: sanitizers
on:
schedule:
- cron: '0 16 * * *'
workflow_dispatch:
jobs:
test:
runs-on: macos-latest
strategy:
matrix:
sanitizer: [asan, tsan, ubsan]
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.sanitizer }}
run: |
CLANG_VERSION=$(clang --version | head -n 1 | cut -d' ' -f 4)
DYLIB_PATH="$(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/${CLANG_VERSION}/lib/darwin/libclang_rt.${{ matrix.sanitizer }}_osx_dynamic.dylib"
bazel test --config=${{ matrix.sanitizer }} \
--test_strategy=exclusive --test_output=all \
--test_env=DYLD_INSERT_LIBRARIES=${DYLIB_PATH} \
--runs_per_test 5 -t- :unit_tests \
--define=SANTA_BUILD_TYPE=adhoc
- name: Upload logs
uses: actions/upload-artifact@v1
if: failure()
with:
name: logs
path: /tmp/san_out*

2
.gitignore vendored
View File

@@ -2,7 +2,7 @@
*.profraw
*.provisionprofile
bazel-*
Pods
MODULE.bazel.lock
Santa.xcodeproj/*
Santa.xcworkspace/*
CoverageData/*

5
.pyink-config Normal file
View File

@@ -0,0 +1,5 @@
[tool.pyink]
pyink = true
line-length = 80
pyink-indentation = 2
pyink-use-majority-quotes = true

11
BUILD
View File

@@ -1,7 +1,9 @@
load("@build_bazel_rules_apple//apple:versioning.bzl", "apple_bundle_version")
load("//:helper.bzl", "run_command")
package(default_visibility = ["//:santa_package_group"])
package(
default_visibility = ["//:santa_package_group"],
)
licenses(["notice"])
@@ -198,10 +200,3 @@ test_suite(
"//Source/santasyncservice:unit_tests",
],
)
test_suite(
name = "benchmarks",
tests = [
"//Source/santad:SNTApplicationBenchmark",
],
)

1
CODEOWNERS Normal file
View File

@@ -0,0 +1 @@
* @google/macendpoints

View File

@@ -2,5 +2,5 @@
# Example NOTARIZATION_TOOL wrapper.
/usr/bin/xcrun altool --notarize-app "${2}" --primary-bundle-id "${4}" \
-u "${NOTARIZATION_USERNAME}" -p "${NOTARIZATION_PASSWORD}"
/usr/bin/xcrun notarytool submit "${2}" --wait \
--apple-id "${NOTARIZATION_USERNAME}" --password "${NOTARIZATION_PASSWORD}"

View File

@@ -28,8 +28,6 @@
# tool around the tool to use for notarization. The tool must take 2 flags:
# --file
# - pointing at a zip file containing the artifact to notarize
# --primary-bundle-id
# - specifying the CFBundleID of the artifact being notarized
[[ -n "${NOTARIZATION_TOOL}" ]] || die "NOTARIZATION_TOOL unset"
# ARTIFACTS_DIR is a required environment variable pointing at a directory to
@@ -55,11 +53,10 @@ readonly RELEASE_NAME="santa-$(/usr/bin/defaults read "${INPUT_APP}/Contents/Inf
readonly SCRATCH=$(/usr/bin/mktemp -d "${TMPDIR}/santa-"XXXXXX)
readonly APP_PKG_ROOT="${SCRATCH}/app_pkg_root"
readonly APP_PKG_SCRIPTS="${SCRATCH}/pkg_scripts"
readonly ENTITLEMENTS="${SCRATCH}/entitlements"
readonly SCRIPT_PATH="$(/usr/bin/dirname -- ${BASH_SOURCE[0]})"
/bin/mkdir -p "${APP_PKG_ROOT}" "${APP_PKG_SCRIPTS}" "${ENTITLEMENTS}"
/bin/mkdir -p "${APP_PKG_ROOT}" "${APP_PKG_SCRIPTS}"
readonly DMG_PATH="${ARTIFACTS_DIR}/${RELEASE_NAME}.dmg"
readonly TAR_PATH="${ARTIFACTS_DIR}/${RELEASE_NAME}.tar.gz"
@@ -67,19 +64,9 @@ readonly TAR_PATH="${ARTIFACTS_DIR}/${RELEASE_NAME}.tar.gz"
# Sign all of binaries/bundles. Maintain inside-out ordering where necessary
for ARTIFACT in "${INPUT_SANTACTL}" "${INPUT_SANTABS}" "${INPUT_SANTAMS}" "${INPUT_SANTASS}" "${INPUT_SYSX}" "${INPUT_APP}"; do
BN=$(/usr/bin/basename "${ARTIFACT}")
EN="${ENTITLEMENTS}/${BN}.entitlements"
echo "extracting ${BN} entitlements"
/usr/bin/codesign -d --entitlements "${EN}" "${ARTIFACT}"
if [[ -s "${EN}" ]]; then
EN="--entitlements ${EN}"
else
EN=""
fi
echo "codesigning ${BN}"
/usr/bin/codesign --sign "${SIGNING_IDENTITY}" --keychain "${SIGNING_KEYCHAIN}" \
${EN} --timestamp --force --generate-entitlement-der \
--preserve-metadata=entitlements --timestamp --force --generate-entitlement-der \
--options library,kill,runtime "${ARTIFACT}"
done
@@ -92,7 +79,7 @@ for ARTIFACT in "${INPUT_SYSX}" "${INPUT_APP}"; do
echo "notarizing ${BN}"
PBID=$(/usr/bin/defaults read "${ARTIFACT}/Contents/Info.plist" CFBundleIdentifier)
"${NOTARIZATION_TOOL}" --file "${SCRATCH}/${BN}.zip" --primary-bundle-id "${PBID}"
"${NOTARIZATION_TOOL}" --file "${SCRATCH}/${BN}.zip"
done
# Staple the App.
@@ -166,8 +153,7 @@ echo "verifying pkg signature"
/usr/sbin/pkgutil --check-signature "${SCRATCH}/${RELEASE_NAME}/${RELEASE_NAME}.pkg" || die "bad pkg signature"
echo "notarizing pkg"
"${NOTARIZATION_TOOL}" --file "${SCRATCH}/${RELEASE_NAME}/${RELEASE_NAME}.pkg" \
--primary-bundle-id "com.google.santa"
"${NOTARIZATION_TOOL}" --file "${SCRATCH}/${RELEASE_NAME}/${RELEASE_NAME}.pkg"
echo "stapling pkg"
/usr/bin/xcrun stapler staple "${SCRATCH}/${RELEASE_NAME}/${RELEASE_NAME}.pkg" || die "failed to staple pkg"
@@ -179,7 +165,7 @@ echo "wrapping pkg in dmg"
-srcfolder "${SCRATCH}/${RELEASE_NAME}/" "${DMG_PATH}" || die "failed to wrap pkg in dmg"
echo "notarizing dmg"
"${NOTARIZATION_TOOL}" --file "${DMG_PATH}" --primary-bundle-id "com.google.santa"
"${NOTARIZATION_TOOL}" --file "${DMG_PATH}"
echo "stapling dmg"
/usr/bin/xcrun stapler staple "${DMG_PATH}" || die "failed to staple dmg"

11
Fuzzing/BUILD Normal file
View File

@@ -0,0 +1,11 @@
load("fuzzing.bzl", "objc_fuzz_test")
objc_fuzz_test(
name = "MachOParse",
srcs = ["common/MachOParse.mm"],
corpus = glob(["common/MachOParse_corpus/*"]),
linkopts = ["-lsqlite3"],
deps = [
"//Source/common:SNTFileInfo",
],
)

View File

@@ -0,0 +1,40 @@
#import <Foundation/Foundation.h>
#include <libproc.h>
#include <stddef.h>
#include <stdint.h>
#import "Source/common/SNTFileInfo.h"
int get_num_fds() {
return proc_pidinfo(getpid(), PROC_PIDLISTFDS, 0, NULL, 0) / PROC_PIDLISTFD_SIZE;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
static NSString *tmpPath =
[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
int num_fds_pre = get_num_fds();
@autoreleasepool {
NSData *input = [NSData dataWithBytesNoCopy:(void *)data length:size freeWhenDone:false];
[input writeToFile:tmpPath atomically:false];
NSError *error;
SNTFileInfo *fi = [[SNTFileInfo alloc] initWithResolvedPath:tmpPath error:&error];
if (!fi || error != nil) {
NSLog(@"Error: %@", error);
return -1;
}
// Mach-O Parsing
[fi architectures];
[fi isMissingPageZero];
[fi infoPlist];
}
if (num_fds_pre != get_num_fds()) {
abort();
}
return 0;
}

Binary file not shown.

20
Fuzzing/fuzzing.bzl Normal file
View File

@@ -0,0 +1,20 @@
"""Utilities for fuzzing Santa"""
load("@rules_fuzzing//fuzzing:cc_defs.bzl", "cc_fuzz_test")
def objc_fuzz_test(name, srcs, deps, corpus, linkopts = [], **kwargs):
native.objc_library(
name = "%s_lib" % name,
srcs = srcs,
deps = deps,
**kwargs
)
cc_fuzz_test(
name = name,
deps = [
"%s_lib" % name,
],
linkopts = linkopts,
corpus = corpus,
)

View File

@@ -0,0 +1,14 @@
#!/bin/bash
# Xcode doesn't include the fuzzer runtime, but the one LLVM ships is compatible with Apple clang.
set -uexo pipefail
CLANG_VERSION=$(clang --version | head -n 1 | cut -d' ' -f 4)
DST_PATH="$(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/${CLANG_VERSION}/lib/darwin/libclang_rt.fuzzer_osx.a"
if [ -f ${DST_PATH} ]; then
exit 0;
fi
curl -O -L https://github.com/llvm/llvm-project/releases/download/llvmorg-${CLANG_VERSION}/clang+llvm-${CLANG_VERSION}-x86_64-apple-darwin.tar.xz
tar xvf clang+llvm-${CLANG_VERSION}-x86_64-apple-darwin.tar.xz clang+llvm-${CLANG_VERSION}-x86_64-apple-darwin/lib/clang/${CLANG_VERSION}/lib/darwin/libclang_rt.fuzzer_osx.a
cp clang+llvm-${CLANG_VERSION}-x86_64-apple-darwin/lib/clang/${CLANG_VERSION}/lib/darwin/libclang_rt.fuzzer_osx.a ${DST_PATH}

View File

@@ -1,4 +0,0 @@
bin
llvm-*.src
llvm-*.src.tar.xz

View File

@@ -1,109 +0,0 @@
#!/usr/bin/env bash
LLVM_VERSION='5.0.1'
LLVM_COMPILERRT_TARBALL_NAME="llvm-${LLVM_VERSION}.src.tar.xz"
LLVM_COMPILERRT_SRC_FOLDER_NAME=`echo "${LLVM_COMPILERRT_TARBALL_NAME}" | cut -d '.' -f 1-4`
LLVM_COMPILERRT_TARBALL_URL="http://releases.llvm.org/${LLVM_VERSION}/${LLVM_COMPILERRT_TARBALL_NAME}"
LIBFUZZER_FOLDER="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
LOG_FILE=`mktemp`
main() {
echo "libFuzzer build script"
echo " > Checking dependencies..."
checkDependencies || return 1
echo " > Entering libFuzzer folder..."
cd "${LIBFUZZER_FOLDER}" > /dev/null 2>&1
if [ $? -ne 0 ] ; then
echo "Failed to enter the libFuzzer folder: ${LIBFUZZER_FOLDER}"
return 1
fi
if [ ! -f "${LLVM_COMPILERRT_TARBALL_NAME}" ] ; then
echo " > Downloading the LLVM tarball..."
curl "${LLVM_COMPILERRT_TARBALL_URL}" -o "${LLVM_COMPILERRT_TARBALL_NAME}" > "${LOG_FILE}" 2>&1
if [ $? -ne 0 ] ; then
dumpLogFile "Failed to download the LLVM tarball"
return 1
fi
else
echo " > An existing LLVM tarball was found"
fi
if [ -d "${LLVM_COMPILERRT_SRC_FOLDER_NAME}" ] ; then
echo " > Deleting existing LLVM folder..."
rm -rf "${LLVM_COMPILERRT_SRC_FOLDER_NAME}" > "${LOG_FILE}" 2>&1
if [ $? -ne 0 ] ; then
dumpLogFile "Failed to delete the existing source folder"
return 1
fi
fi
echo " > Extracting the LLVM tarball..."
tar xf "${LLVM_COMPILERRT_TARBALL_NAME}" > "${LOG_FILE}" 2>&1
if [ $? -ne 0 ] ; then
rm "${LLVM_COMPILERRT_TARBALL_NAME}" "${LLVM_COMPILERRT_SRC_FOLDER_NAME}"
dumpLogFile "Failed to extract the LLVM tarball"
return 1
fi
if [ -d "bin" ] ; then
echo " > Deleting existing bin folder..."
rm -rf "bin" > "${LOG_FILE}" 2>&1
if [ $? -ne 0 ] ; then
dumpLogFile "Failed to delete the existing bin folder"
return 1
fi
fi
mkdir "bin" > "${LOG_FILE}" 2>&1
if [ $? -ne 0 ] ; then
dumpLogFile "Failed to create the bin folder"
return 1
fi
echo " > Building libFuzzer..."
( cd "bin" && "../${LLVM_COMPILERRT_SRC_FOLDER_NAME}/lib/Fuzzer/build.sh" ) > "${LOG_FILE}" 2>&1
if [ $? -ne 0 ] ; then
dumpLogFile "Failed to build the library"
return 1
fi
printf "\nFinished building libFuzzer\n"
rm "${LOG_FILE}"
return 0
}
checkDependencies() {
executable_list=( "clang++" "curl" "tar" )
for executable in "${executable_list[@]}" ; do
which "${executable}" > /dev/null 2>&1
if [ $? -ne 0 ] ; then
echo "The following program was not found: ${executable}"
return 1
fi
done
return 0
}
dumpLogFile() {
if [ $# -eq 1 ] ; then
local message="$1"
else
local message="An error has occurred"
fi
printf "${message}\n"
printf "Log file follows\n===\n"
cat "${LOG_FILE}"
printf "\n===\n"
rm "${LOG_FILE}"
}
main $@
exit $?

View File

@@ -20,6 +20,7 @@
#import "SNTCommandController.h"
#import "SNTRule.h"
#import "SNTXPCControlInterface.h"
#import "Source/common/SNTCommonEnums.h"
extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size) {
if (size > 16) {
@@ -28,7 +29,7 @@ extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size
return 1;
}
santa_vnode_id_t vnodeID = {};
SantaVnode vnodeID = {};
std::memcpy(&vnodeID, data, size);
MOLXPCConnection *daemonConn = [SNTXPCControlInterface configuredConnection];
@@ -41,14 +42,14 @@ extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size
[[daemonConn remoteObjectProxy]
checkCacheForVnodeID:vnodeID
withReply:^(santa_action_t action) {
if (action == ACTION_RESPOND_ALLOW) {
withReply:^(SNTAction action) {
if (action == SNTActionRespondAllow) {
std::cerr << "File exists in [whitelist] kernel cache" << std::endl;
;
} else if (action == ACTION_RESPOND_DENY) {
} else if (action == SNTActionRespondDeny) {
std::cerr << "File exists in [blacklist] kernel cache" << std::endl;
;
} else if (action == ACTION_UNSET) {
} else if (action == SNTActionUnset) {
std::cerr << "File does not exist in cache" << std::endl;
;
}

View File

@@ -18,6 +18,7 @@
#import <MOLXPCConnection/MOLXPCConnection.h>
#import "SNTCommandController.h"
#import "SNTCommonEnums.h"
#import "SNTRule.h"
#import "SNTXPCControlInterface.h"
@@ -58,7 +59,7 @@ extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *data, std::size_t size
[daemonConn resume];
[[daemonConn remoteObjectProxy]
databaseRuleAddRules:@[ newRule ]
cleanSlate:NO
ruleCleanup:SNTRuleCleanupNone
reply:^(NSError *error) {
if (!error) {
if (newRule.state == SNTRuleStateRemove) {

View File

@@ -200,3 +200,4 @@
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

56
MODULE.bazel Normal file
View File

@@ -0,0 +1,56 @@
module(name = "santa")
bazel_dep(name = "apple_support", version = "1.15.1", repo_name = "build_bazel_apple_support")
bazel_dep(name = "abseil-cpp", version = "20240116.2", repo_name = "com_google_absl")
bazel_dep(name = "rules_python", version = "0.33.2")
bazel_dep(name = "rules_cc", version = "0.0.9")
bazel_dep(name = "rules_apple", version = "3.8.0", repo_name = "build_bazel_rules_apple")
bazel_dep(name = "rules_swift", version = "2.0.0-rc1", repo_name = "build_bazel_rules_swift")
bazel_dep(name = "rules_fuzzing", version = "0.5.2")
bazel_dep(name = "protobuf", version = "27.2", repo_name = "com_google_protobuf")
bazel_dep(name = "googletest", version = "1.14.0.bcr.1", repo_name = "com_google_googletest")
# MOLCertificate
bazel_dep(name = "molcertificate", version = "2.1", repo_name = "MOLCertificate")
git_override(
module_name = "molcertificate",
commit = "34f0ccf68a34a07cc636ada89057c529f90bec3a",
remote = "https://github.com/google/macops-molcertificate.git",
)
# MOLAuthenticatingURLSession
bazel_dep(name = "molauthenticatingurlsession", version = "3.0", repo_name = "MOLAuthenticatingURLSession")
git_override(
module_name = "molauthenticatingurlsession",
commit = "0a50a67f29d635a4012981714c1dedef9ac25fe6",
remote = "https://github.com/google/macops-molauthenticatingurlsession.git",
)
# MOLCodesignChecker
bazel_dep(name = "molcodesignchecker", version = "3.0", repo_name = "MOLCodesignChecker")
git_override(
module_name = "molcodesignchecker",
commit = "5060bcc8baa90bae3b0ca705d14850328bbbec53",
remote = "https://github.com/google/macops-molcodesignchecker.git",
)
# MOLXPCConnection
bazel_dep(name = "molxpcconnection", version = "2.1", repo_name = "MOLXPCConnection")
git_override(
module_name = "molxpcconnection",
commit = "da816dc49becac96d941ef6a5c4153ed39d1fe7c",
remote = "https://github.com/russellhancox/macops-molxpcconnection.git",
)
# FMDB
non_module_deps = use_extension("//:non_module_deps.bzl", "non_module_deps")
use_repo(non_module_deps, "FMDB")
use_repo(non_module_deps, "OCMock")
# Hedron's Compile Commands Extractor
bazel_dep(name = "hedron_compile_commands", dev_dependency = True)
git_override(
module_name = "hedron_compile_commands",
commit = "0e990032f3c5a866e72615cf67e5ce22186dcb97",
remote = "https://github.com/hedronvision/bazel-compile-commands-extractor.git",
)

View File

@@ -1,10 +1,16 @@
# Santa [![CI](https://github.com/google/santa/actions/workflows/ci.yml/badge.svg)](https://github.com/google/santa/actions/workflows/ci.yml) [![Coverage Status](https://coveralls.io/repos/github/google/santa/badge.svg?branch=main)](https://coveralls.io/github/google/santa?branch=main)
# Santa
[![license](https://img.shields.io/github/license/google/santa)](https://github.com/google/santa/blob/main/LICENSE)
[![CI](https://github.com/google/santa/actions/workflows/ci.yml/badge.svg)](https://github.com/google/santa/actions/workflows/ci.yml)
[![latest release](https://img.shields.io/github/v/release/google/santa.svg)](https://github.com/google/santa/releases/latest)
[![latest release date](https://img.shields.io/github/release-date/google/santa.svg)](https://github.com/google/santa/releases/latest)
[![downloads](https://img.shields.io/github/downloads/google/santa/latest/total)](https://github.com/google/santa/releases/latest)
<p align="center">
<img src="https://raw.githubusercontent.com/google/santa/main/Source/santa/Resources/Images.xcassets/AppIcon.appiconset/santa-hat-icon-128.png" alt="Santa Icon" />
<img src="./docs/images/santa-sleigh-256.png" height="128" alt="Santa Icon" />
</p>
Santa is a binary authorization system for macOS. It consists of a system
Santa is a binary and file access authorization system for macOS. It consists of a system
extension that monitors for executions, a daemon that makes execution decisions
based on the contents of a local database, a GUI agent that notifies the user in
case of a block decision and a command-line utility for managing the system and
@@ -15,7 +21,7 @@ It is named Santa because it keeps track of binaries that are naughty or nice.
# Docs
The Santa docs are stored in the
[Docs](https://github.com/google/santa/blob/main/docs) directory and published
[Docs](https://github.com/google/santa/blob/main/docs) directory and are published
at https://santa.dev.
The docs include deployment options, details on how parts of Santa work and
@@ -42,9 +48,7 @@ disclosure reporting.
the events database. In LOCKDOWN mode, only listed binaries are allowed to
run.
* Event logging: When the kext is loaded, all binary launches are logged. When
in either mode, all unknown or denied binaries are stored in the database to
enable later aggregation.
* Event logging: When the system extension is loaded, all binary launches are logged. When in either mode, all unknown or denied binaries are stored in the database to enable later aggregation.
* Certificate-based rules, with override levels: Instead of relying on a
binary's hash (or 'fingerprint'), executables can be allowed/blocked by their
@@ -134,7 +138,7 @@ A tool like Santa doesn't really lend itself to screenshots, so here's a video
instead.
<p align="center"> <img src="https://thumbs.gfycat.com/MadFatalAmphiuma-small.gif" alt="Santa Block Video" /> </p>
<p align="center"> <img src="./docs/images/santa-block.gif" alt="Santa Block Video" /> </p>
# Contributing
Patches to this project are very much welcome. Please see the

View File

@@ -1,12 +1,14 @@
# Reporting a Vulnerability
If you believe you have found a security vulnerability, we would appreciate private disclosure
so that we can work on a fix before disclosure. Any vulnerabilities reported to us will be
If you believe you have found a security vulnerability, we would appreciate a private report
so that we can work on and release a fix before public disclosure. Any vulnerabilities reported to us will be
disclosed publicly either when a new version with fixes is released or 90 days has passed,
whichever comes first.
To report vulnerabilities to us privately, please e-mail `santa-team@google.com`.
If you want to encrypt your e-mail, you can use our GPG key `0x92AFE41DAB49BBB6`
available on pool.sks-keyservers.net:
To report vulnerabilities to us privately, either:
`gpg --keyserver pool.sks-keyservers.net --recv-key 0x92AFE41DAB49BBB6`
1) Report the vulnerability [through GitHub](https://github.com/google/santa/security/advisories/new).
2) E-mail `santa-team@google.com`. If you want to encrypt your e-mail, you can use our GPG key `0x92AFE41DAB49BBB6` available on keyserver.ubuntu.com:
`gpg --keyserver keyserver.ubuntu.com --recv-key 0x92AFE41DAB49BBB6`

View File

@@ -1,5 +1,5 @@
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("//:helper.bzl", "santa_unit_test")
load("@rules_proto_grpc//objc:defs.bzl", "objc_proto_library")
package(
default_visibility = ["//:santa_package_group"],
@@ -11,31 +11,153 @@ proto_library(
name = "santa_proto",
srcs = ["santa.proto"],
deps = [
"//Source/santad/ProcessTree:process_tree_proto",
"@com_google_protobuf//:any_proto",
"@com_google_protobuf//:timestamp_proto",
],
)
objc_proto_library(
name = "santa_objc_proto",
copts = ["-fno-objc-arc"],
non_arc_srcs = ["Santa.pbobjc.m"],
protos = [":santa_proto"],
cc_proto_library(
name = "santa_cc_proto",
deps = [":santa_proto"],
)
# Note: Simple wrapper for a `cc_proto_library` target which cannot be directly
# depended upon by an `objc_library` target.
cc_library(
name = "santa_cc_proto_library_wrapper",
hdrs = ["santa_proto_include_wrapper.h"],
deps = [
":santa_cc_proto",
],
)
objc_library(
name = "SystemResources",
srcs = ["SystemResources.mm"],
hdrs = ["SystemResources.h"],
deps = [
":SNTLogging",
],
)
objc_library(
name = "SNTDeepCopy",
srcs = ["SNTDeepCopy.m"],
hdrs = ["SNTDeepCopy.h"],
)
cc_library(
name = "SantaCache",
hdrs = ["SantaCache.h"],
deps = ["//Source/common:SNTCommon"],
deps = [":BranchPrediction"],
)
santa_unit_test(
name = "SantaCacheTest",
srcs = [
"SantaCache.h",
"SantaCacheTest.mm",
srcs = ["SantaCacheTest.mm"],
deps = [
":SantaCache",
],
)
# This target shouldn't be used directly.
# Use a more specific scoped type instead.
objc_library(
name = "ScopedTypeRef",
hdrs = ["ScopedTypeRef.h"],
visibility = ["//Source/common:__pkg__"],
)
objc_library(
name = "ScopedCFTypeRef",
hdrs = ["ScopedCFTypeRef.h"],
deps = [
":ScopedTypeRef",
],
)
santa_unit_test(
name = "ScopedCFTypeRefTest",
srcs = ["ScopedCFTypeRefTest.mm"],
sdk_frameworks = [
"Security",
],
deps = [
":ScopedCFTypeRef",
],
)
objc_library(
name = "ScopedIOObjectRef",
hdrs = ["ScopedIOObjectRef.h"],
sdk_frameworks = [
"IOKit",
],
deps = [
":ScopedTypeRef",
],
)
santa_unit_test(
name = "ScopedIOObjectRefTest",
srcs = ["ScopedIOObjectRefTest.mm"],
sdk_frameworks = [
"IOKit",
],
deps = [
":ScopedIOObjectRef",
"//Source/santad:EndpointSecuritySerializerUtilities",
],
)
objc_library(
name = "BranchPrediction",
hdrs = ["BranchPrediction.h"],
)
objc_library(
name = "SantaVnode",
hdrs = ["SantaVnode.h"],
)
objc_library(
name = "Platform",
hdrs = ["Platform.h"],
)
objc_library(
name = "String",
hdrs = ["String.h"],
)
objc_library(
name = "SantaVnodeHash",
srcs = ["SantaVnodeHash.mm"],
hdrs = ["SantaVnodeHash.h"],
deps = [
":SantaCache",
":SantaVnode",
],
)
objc_library(
name = "CertificateHelpers",
srcs = ["CertificateHelpers.m"],
hdrs = ["CertificateHelpers.h"],
deps = [
"@MOLCertificate",
],
)
objc_library(
name = "SigningIDHelpers",
srcs = ["SigningIDHelpers.m"],
hdrs = ["SigningIDHelpers.h"],
deps = [
":SNTLogging",
"@MOLCodesignChecker",
],
deps = ["//Source/common:SNTCommon"],
)
objc_library(
@@ -44,6 +166,7 @@ objc_library(
hdrs = ["SNTBlockMessage.h"],
deps = [
":SNTConfigurator",
":SNTFileAccessEvent",
":SNTLogging",
":SNTStoredEvent",
":SNTSystemInfo",
@@ -57,7 +180,7 @@ objc_library(
defines = ["SANTAGUI"],
deps = [
":SNTConfigurator",
":SNTDeviceEvent",
":SNTFileAccessEvent",
":SNTLogging",
":SNTStoredEvent",
":SNTSystemInfo",
@@ -66,11 +189,11 @@ objc_library(
objc_library(
name = "SNTCachedDecision",
srcs = ["SNTCachedDecision.m"],
srcs = ["SNTCachedDecision.mm"],
hdrs = ["SNTCachedDecision.h"],
deps = [
":SNTCommon",
":SNTCommonEnums",
":SantaVnode",
],
)
@@ -78,26 +201,42 @@ objc_library(
name = "SNTDeviceEvent",
srcs = ["SNTDeviceEvent.m"],
hdrs = ["SNTDeviceEvent.h"],
module_name = "santa_common_SNTDeviceEvent",
sdk_frameworks = [
"Foundation",
],
deps = [
":SNTCommonEnums",
],
)
objc_library(
name = "SNTAllowlistInfo",
srcs = ["SNTAllowlistInfo.m"],
hdrs = ["SNTAllowlistInfo.h"],
name = "SNTFileAccessEvent",
srcs = ["SNTFileAccessEvent.m"],
hdrs = ["SNTFileAccessEvent.h"],
module_name = "santa_common_SNTFileAccessEvent",
sdk_frameworks = [
"Foundation",
],
deps = [
":CertificateHelpers",
":SNTStoredEvent",
],
)
objc_library(
name = "SNTCommonEnums",
hdrs = ["SNTCommonEnums.h"],
textual_hdrs = ["SNTCommonEnums.h"],
)
objc_library(
name = "SNTConfigurator",
srcs = ["SNTConfigurator.m"],
hdrs = ["SNTConfigurator.h"],
module_name = "santa_common_SNTConfigurator",
sdk_frameworks = [
"Foundation",
],
deps = [
":SNTCommonEnums",
":SNTRule",
@@ -106,6 +245,23 @@ objc_library(
],
)
objc_library(
name = "SNTKVOManager",
srcs = ["SNTKVOManager.mm"],
hdrs = ["SNTKVOManager.h"],
deps = [
":SNTLogging",
],
)
santa_unit_test(
name = "SNTKVOManagerTest",
srcs = ["SNTKVOManagerTest.mm"],
deps = [
":SNTKVOManager",
],
)
objc_library(
name = "SNTDropRootPrivs",
srcs = ["SNTDropRootPrivs.m"],
@@ -117,20 +273,13 @@ objc_library(
srcs = ["SNTFileInfo.m"],
hdrs = ["SNTFileInfo.h"],
deps = [
":SNTLogging",
":SantaVnode",
"@FMDB",
"@MOLCodesignChecker",
],
)
cc_library(
name = "SNTCommon",
hdrs = ["SNTCommon.h"],
defines = [
"TARGET_OS_OSX",
"TARGET_OS_MAC",
],
)
objc_library(
name = "SNTLogging",
srcs = ["SNTLogging.m"],
@@ -138,18 +287,27 @@ objc_library(
deps = [":SNTConfigurator"],
)
cc_library(
name = "SNTPrefixTree",
srcs = ["SNTPrefixTree.cc"],
hdrs = ["SNTPrefixTree.h"],
copts = ["-std=c++11"],
deps = [":SNTLogging"],
objc_library(
name = "PrefixTree",
hdrs = ["PrefixTree.h"],
deps = [
":SNTLogging",
"@com_google_absl//absl/synchronization",
],
)
objc_library(
name = "Unit",
hdrs = ["Unit.h"],
)
objc_library(
name = "SNTRule",
srcs = ["SNTRule.m"],
hdrs = ["SNTRule.h"],
sdk_frameworks = [
"Foundation",
],
deps = [
":SNTCommonEnums",
":SNTSyncConstants",
@@ -159,7 +317,17 @@ objc_library(
santa_unit_test(
name = "SNTRuleTest",
srcs = ["SNTRuleTest.m"],
deps = [":SNTRule"],
deps = [
":SNTCommonEnums",
":SNTRule",
":SNTSyncConstants",
],
)
objc_library(
name = "SNTRuleIdentifiers",
srcs = ["SNTRuleIdentifiers.m"],
hdrs = ["SNTRuleIdentifiers.h"],
)
objc_library(
@@ -181,13 +349,19 @@ objc_library(
name = "SNTSyncConstants",
srcs = ["SNTSyncConstants.m"],
hdrs = ["SNTSyncConstants.h"],
sdk_frameworks = [
"Foundation",
],
)
objc_library(
name = "SNTSystemInfo",
srcs = ["SNTSystemInfo.m"],
hdrs = ["SNTSystemInfo.h"],
sdk_frameworks = ["IOKit"],
sdk_frameworks = [
"Foundation",
"IOKit",
],
)
objc_library(
@@ -221,6 +395,7 @@ objc_library(
":SNTCommonEnums",
":SNTConfigurator",
":SNTRule",
":SNTRuleIdentifiers",
":SNTStoredEvent",
":SNTXPCUnprivilegedControlInterface",
"@MOLCodesignChecker",
@@ -261,11 +436,12 @@ objc_library(
srcs = ["SNTXPCUnprivilegedControlInterface.m"],
hdrs = ["SNTXPCUnprivilegedControlInterface.h"],
deps = [
":SNTCommon",
":SNTCommonEnums",
":SNTRule",
":SNTRuleIdentifiers",
":SNTStoredEvent",
":SNTXPCBundleServiceInterface",
":SantaVnode",
"@MOLCertificate",
"@MOLXPCConnection",
],
@@ -287,9 +463,9 @@ santa_unit_test(
)
santa_unit_test(
name = "SNTPrefixTreeTest",
srcs = ["SNTPrefixTreeTest.mm"],
deps = [":SNTPrefixTree"],
name = "PrefixTreeTest",
srcs = ["PrefixTreeTest.mm"],
deps = [":PrefixTree"],
)
santa_unit_test(
@@ -298,13 +474,72 @@ santa_unit_test(
deps = [":SNTMetricSet"],
)
santa_unit_test(
name = "SNTCachedDecisionTest",
srcs = ["SNTCachedDecisionTest.mm"],
deps = [
"//Source/common:SNTCachedDecision",
"//Source/common:TestUtils",
"@OCMock",
],
)
santa_unit_test(
name = "SNTBlockMessageTest",
srcs = ["SNTBlockMessageTest.m"],
sdk_frameworks = [
"AppKit",
],
deps = [
":SNTBlockMessage_SantaGUI",
":SNTConfigurator",
":SNTFileAccessEvent",
":SNTStoredEvent",
":SNTSystemInfo",
"@OCMock",
],
)
santa_unit_test(
name = "SNTConfiguratorTest",
srcs = ["SNTConfiguratorTest.m"],
deps = [
":SNTCommonEnums",
":SNTConfigurator",
"@OCMock",
],
)
test_suite(
name = "unit_tests",
tests = [
":PrefixTreeTest",
":SNTBlockMessageTest",
":SNTCachedDecisionTest",
":SNTConfiguratorTest",
":SNTFileInfoTest",
":SNTKVOManagerTest",
":SNTMetricSetTest",
":SNTPrefixTreeTest",
":SNTRuleTest",
":SantaCacheTest",
":ScopedCFTypeRefTest",
":ScopedIOObjectRefTest",
],
visibility = ["//:santa_package_group"],
)
objc_library(
name = "TestUtils",
testonly = 1,
srcs = ["TestUtils.mm"],
hdrs = ["TestUtils.h"],
sdk_dylibs = [
"bsm",
],
deps = [
":Platform",
":SystemResources",
"@OCMock",
"@com_google_googletest//:gtest",
],
)

View File

@@ -0,0 +1,22 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__BRANCHPREDICTION_H
#define SANTA__COMMON__BRANCHPREDICTION_H
// Helpful macros to use when the the outcome is largely known
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#endif

View File

@@ -0,0 +1,43 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <Foundation/Foundation.h>
#import <MOLCertificate/MOLCertificate.h>
#include <sys/cdefs.h>
__BEGIN_DECLS
/**
Return a string representing publisher info from the provided certs
@param certs A certificate chain
@param teamID A team ID to be displayed for apps from the App Store
@return A string that tries to be more helpful to users by extracting
appropriate information from the certificate chain.
*/
NSString *Publisher(NSArray<MOLCertificate *> *certs, NSString *teamID);
/**
Return an array of the underlying SecCertificateRef's for the given array
of MOLCertificates.
@param certs An array of MOLCertificates
@return An array of SecCertificateRefs. WARNING: If the refs need to be used
for a long time be careful to properly CFRetain/CFRelease the returned items.
*/
NSArray<id> *CertificateChain(NSArray<MOLCertificate *> *certs);
__END_DECLS

View File

@@ -0,0 +1,42 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/common/CertificateHelpers.h"
#include <Security/SecCertificate.h>
NSString *Publisher(NSArray<MOLCertificate *> *certs, NSString *teamID) {
MOLCertificate *leafCert = [certs firstObject];
if ([leafCert.commonName isEqualToString:@"Apple Mac OS Application Signing"]) {
return [NSString stringWithFormat:@"App Store (Team ID: %@)", teamID];
} else if (leafCert.commonName && leafCert.orgName) {
return [NSString stringWithFormat:@"%@ - %@", leafCert.orgName, leafCert.commonName];
} else if (leafCert.commonName) {
return leafCert.commonName;
} else if (leafCert.orgName) {
return leafCert.orgName;
} else {
return nil;
}
}
NSArray<id> *CertificateChain(NSArray<MOLCertificate *> *certs) {
NSMutableArray *certArray = [NSMutableArray arrayWithCapacity:[certs count]];
for (MOLCertificate *cert in certs) {
[certArray addObject:(id)cert.certRef];
}
return certArray;
}

41
Source/common/Platform.h Normal file
View File

@@ -0,0 +1,41 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__PLATFORM_H
#define SANTA__COMMON__PLATFORM_H
#include <Availability.h>
#if defined(MAC_OS_VERSION_13_0) && \
MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_13_0
#define HAVE_MACOS_13 1
#else
#define HAVE_MACOS_13 0
#endif
#if defined(MAC_OS_VERSION_14_0) && \
MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
#define HAVE_MACOS_14 1
#else
#define HAVE_MACOS_14 0
#endif
#if defined(MAC_OS_VERSION_15_0) && \
MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_15_0
#define HAVE_MACOS_15 1
#else
#define HAVE_MACOS_15 0
#endif
#endif

305
Source/common/PrefixTree.h Normal file
View File

@@ -0,0 +1,305 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__PREFIXTREE_H
#define SANTA__COMMON__PREFIXTREE_H
#include <sys/syslimits.h>
#include <optional>
#import "Source/common/SNTLogging.h"
#include "absl/synchronization/mutex.h"
#if SANTA_PREFIX_TREE_DEBUG
#define DEBUG_LOG LOGD
#else
#define DEBUG_LOG(format, ...) // NOP
#endif
namespace santa {
template <typename ValueT>
class PrefixTree {
private:
// Forward declaration
enum class NodeType;
class TreeNode;
public:
PrefixTree(uint32_t max_depth = PATH_MAX)
: root_(new TreeNode()), max_depth_(max_depth), node_count_(0) {}
~PrefixTree() { PruneLocked(root_); }
bool InsertPrefix(const char *s, ValueT value) {
absl::MutexLock lock(&lock_);
return InsertLocked(s, value, NodeType::kPrefix);
}
bool InsertLiteral(const char *s, ValueT value) {
absl::MutexLock lock(&lock_);
return InsertLocked(s, value, NodeType::kLiteral);
}
bool HasPrefix(const char *input) {
absl::ReaderMutexLock lock(&lock_);
return HasPrefixLocked(input);
}
std::optional<ValueT> LookupLongestMatchingPrefix(const char *input) {
if (!input) {
return std::nullopt;
}
absl::ReaderMutexLock lock(&lock_);
return LookupLongestMatchingPrefixLocked(input);
}
void Reset() {
absl::MutexLock lock(&lock_);
PruneLocked(root_);
root_ = new TreeNode();
node_count_ = 0;
}
uint32_t NodeCount() {
absl::ReaderMutexLock lock(&lock_);
return node_count_;
}
#if SANTA_PREFIX_TREE_DEBUG
void Print() {
char buf[max_depth_ + 1];
memset(buf, 0, sizeof(buf));
absl::ReaderMutexLock lock(&lock_);
PrintLocked(root_, buf, 0);
}
#endif
private:
ABSL_EXCLUSIVE_LOCKS_REQUIRED(lock_)
bool InsertLocked(const char *input, ValueT value, NodeType node_type) {
const char *p = input;
TreeNode *node = root_;
while (*p) {
uint8_t cur_byte = (uint8_t)*p;
TreeNode *child_node = node->children_[cur_byte];
if (!child_node) {
// Current node doesn't exist...
// Create the rest of the nodes in the tree for the given string
// Keep a pointer to where this new branch starts from. If the
// input length exceeds max_depth, the new branch will need to
// be pruned.
TreeNode *branch_start_node = node;
uint8_t branch_start_byte = (uint8_t)*p;
do {
TreeNode *new_node = new TreeNode();
node->children_[cur_byte] = new_node;
node = new_node;
node_count_++;
// Check current depth...
if (p - input >= max_depth_) {
// Attempted to add a string that exceeded max depth
// Prune tree from start of this new branch
PruneLocked(branch_start_node->children_[branch_start_byte]);
branch_start_node->children_[branch_start_byte] = nullptr;
return false;
}
// Disabling clang format due to local/remote version differences.
// clang-format off
cur_byte = (uint8_t)*++p;
// clang-format on
} while (*p);
node->node_type_ = node_type;
node->value_ = value;
return true;
} else if (*(p + 1) == '\0') {
// Current node exists and we're at the end of our input...
// Note: The current node's data will be overwritten
// Only increment node count if the previous node type wasn't already a
// prefix or literal type (in which case it was already counted)
if (child_node->node_type_ == NodeType::kInner) {
node_count_++;
}
child_node->node_type_ = node_type;
child_node->value_ = value;
return true;
}
node = child_node;
p++;
}
// Should only get here when input is an empty string
return false;
}
ABSL_SHARED_LOCKS_REQUIRED(lock_)
bool HasPrefixLocked(const char *input) {
TreeNode *node = root_;
const char *p = input;
while (*p) {
node = node->children_[(uint8_t)*p++];
if (!node) {
break;
}
if (node->node_type_ == NodeType::kPrefix ||
(*p == '\0' && node->node_type_ == NodeType::kLiteral)) {
return true;
}
}
return false;
}
ABSL_SHARED_LOCKS_REQUIRED(lock_)
std::optional<ValueT> LookupLongestMatchingPrefixLocked(const char *input) {
TreeNode *node = root_;
TreeNode *match = nullptr;
const char *p = input;
while (*p) {
node = node->children_[(uint8_t)*p++];
if (!node) {
break;
}
if (node->node_type_ == NodeType::kPrefix ||
(*p == '\0' && node->node_type_ == NodeType::kLiteral)) {
match = node;
}
}
return match ? std::make_optional<ValueT>(match->value_) : std::nullopt;
}
ABSL_EXCLUSIVE_LOCKS_REQUIRED(lock_)
void PruneLocked(TreeNode *target) {
if (!target) {
return;
}
// For deep trees, a recursive approach will generate too many stack frames.
// Since the depth of the tree is configurable, err on the side of caution
// and use a "stack" to walk the tree in a non-recursive manner.
TreeNode **stack = new TreeNode *[node_count_ + 1];
if (!stack) {
LOGE(@"Unable to prune tree!");
return;
}
uint32_t count = 0;
// Seed the "stack" with a starting node.
stack[count++] = target;
// Start at the target node and walk the tree to find and delete all the
// sub-nodes.
while (count) {
TreeNode *node = stack[--count];
for (int i = 0; i < 256; ++i) {
if (!node->children_[i]) {
continue;
}
stack[count++] = node->children_[i];
}
delete node;
--node_count_;
}
delete[] stack;
}
#if SANTA_PREFIX_TREE_DEBUG
ABSL_SHARED_LOCKS_REQUIRED(lock_)
void PrintLocked(TreeNode *node, char *buf, uint32_t depth) {
for (size_t i = 0; i < 256; i++) {
TreeNode *cur_node = node->children_[i];
if (cur_node) {
buf[depth] = i;
if (cur_node->node_type_ != NodeType::kInner) {
printf("\t%s (type: %s)\n", buf,
cur_node->node_type_ == NodeType::kPrefix ? "prefix" : "literal");
}
PrintLocked(cur_node, buf, depth + 1);
buf[depth] = '\0';
}
}
}
#endif
enum class NodeType {
kInner = 0,
kPrefix,
kLiteral,
};
///
/// TreeNode is a wrapper class that represents one byte.
/// 1 node can represent a whole ASCII character.
/// For example a pointer to the 'A' node will be stored at children[0x41].
/// It takes 1-4 nodes to represent a UTF-8 encoded Unicode character.
///
/// The path for "/🤘" would look like this:
/// children[0x2f] -> children[0xf0] -> children[0x9f] -> children[0xa4]
/// -> children[0x98]
///
/// The path for "/dev" is:
/// children[0x2f] -> children[0x64] -> children[0x65] -> children[0x76]
///
/// Lookups of children are O(1).
///
/// Having the nodes represented by a smaller width, such as a nibble (1/2
/// byte), would drastically decrease the memory footprint but would double
/// required dereferences.
///
/// TODO(bur): Potentially convert this into a full on radix tree.
///
class TreeNode {
public:
TreeNode() : children_(), node_type_(NodeType::kInner) {}
~TreeNode() = default;
TreeNode *children_[256];
PrefixTree::NodeType node_type_;
ValueT value_;
};
TreeNode *root_;
const uint32_t max_depth_;
uint32_t node_count_ ABSL_GUARDED_BY(lock_);
absl::Mutex lock_;
};
} // namespace santa
#endif

View File

@@ -0,0 +1,224 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <XCTest/XCTest.h>
#define SANTA_PREFIX_TREE_DEBUG 1
#include "Source/common/PrefixTree.h"
using santa::PrefixTree;
@interface PrefixTreeTest : XCTestCase
@end
@implementation PrefixTreeTest
- (void)testBasic {
PrefixTree<int> tree;
XCTAssertFalse(tree.HasPrefix("/foo/bar/baz"));
XCTAssertFalse(tree.HasPrefix("/foo/bar.txt"));
XCTAssertFalse(tree.HasPrefix("/baz"));
XCTAssertTrue(tree.InsertPrefix("/foo", 12));
XCTAssertTrue(tree.InsertPrefix("/bar", 34));
XCTAssertTrue(tree.InsertLiteral("/foo/bar", 56));
// Re-inserting something that exists is allowed
XCTAssertTrue(tree.InsertLiteral("/foo", 78));
XCTAssertTrue(tree.InsertPrefix("/foo", 56));
XCTAssertTrue(tree.HasPrefix("/foo/bar/baz"));
XCTAssertTrue(tree.HasPrefix("/foo/bar.txt"));
XCTAssertFalse(tree.HasPrefix("/baz"));
// Empty strings are not supported
XCTAssertFalse(tree.InsertLiteral("", 0));
XCTAssertFalse(tree.InsertPrefix("", 0));
}
- (void)testHasPrefix {
PrefixTree<int> tree;
XCTAssertTrue(tree.InsertPrefix("/foo", 0));
XCTAssertTrue(tree.InsertLiteral("/bar", 0));
XCTAssertTrue(tree.InsertLiteral("/baz", 0));
XCTAssertTrue(tree.InsertLiteral("/qaz", 0));
// Check that a tree with a matching prefix is successful
XCTAssertTrue(tree.HasPrefix("/foo.txt"));
// This shouldn't succeed because `/bar` `/baz` and `qaz` are literals
XCTAssertFalse(tree.HasPrefix("/bar.txt"));
XCTAssertFalse(tree.HasPrefix("/baz.txt"));
XCTAssertFalse(tree.HasPrefix("/qaz.txt"));
// Now change `/bar` to a prefix type and retest HasPrefix
// `/bar.txt` should now succeed, but `/baz.txt` should still not pass
XCTAssertTrue(tree.InsertPrefix("/bar", 0));
XCTAssertTrue(tree.HasPrefix("/bar.txt"));
XCTAssertFalse(tree.HasPrefix("/baz.txt"));
XCTAssertFalse(tree.HasPrefix("/qaz.txt"));
// Insert a new prefix string to allow `/baz.txt` to have a valid prefix
XCTAssertTrue(tree.InsertPrefix("/b", 0));
XCTAssertTrue(tree.HasPrefix("/baz.txt"));
XCTAssertFalse(tree.HasPrefix("/qaz.txt"));
// An exact match on a literal allows HasPrefix to succeed
XCTAssertTrue(tree.InsertLiteral("/qaz.txt", 0));
XCTAssertTrue(tree.HasPrefix("/qaz.txt"));
}
- (void)testLookupLongestMatchingPrefix {
PrefixTree<int> tree;
XCTAssertTrue(tree.InsertPrefix("/foo", 12));
XCTAssertTrue(tree.InsertPrefix("/bar", 34));
XCTAssertTrue(tree.InsertPrefix("/foo/bar.txt", 56));
std::optional<int> value;
// Matching exact prefix
value = tree.LookupLongestMatchingPrefix("/foo");
XCTAssertEqual(value.value_or(0), 12);
// Ensure changing node type works as expected
// Literals must match exactly.
value = tree.LookupLongestMatchingPrefix("/foo/bar.txt.tmp");
XCTAssertEqual(value.value_or(0), 56);
XCTAssertTrue(tree.InsertLiteral("/foo/bar.txt", 90));
value = tree.LookupLongestMatchingPrefix("/foo/bar.txt.tmp");
XCTAssertEqual(value.value_or(0), 12);
// Inserting over an exiting node returns the new value
XCTAssertTrue(tree.InsertPrefix("/foo", 78));
value = tree.LookupLongestMatchingPrefix("/foo");
XCTAssertEqual(value.value_or(0), 78);
// No matching prefix
value = tree.LookupLongestMatchingPrefix("/asdf");
XCTAssertEqual(value.value_or(0), 0);
}
- (void)testNodeCounts {
const uint32_t maxDepth = 100;
PrefixTree<int> tree(100);
XCTAssertEqual(tree.NodeCount(), 0);
// Start with a small string
XCTAssertTrue(tree.InsertPrefix("asdf", 0));
XCTAssertEqual(tree.NodeCount(), 4);
// Add a couple more characters to the existing string
XCTAssertTrue(tree.InsertPrefix("asdfgh", 0));
XCTAssertEqual(tree.NodeCount(), 6);
// Inserting a string that exceeds max depth doesn't increase node count
XCTAssertFalse(tree.InsertPrefix(std::string(maxDepth + 10, 'A').c_str(), 0));
XCTAssertEqual(tree.NodeCount(), 6);
// Add a new string that is a prefix of an existing string
// This should increment the count by one since a new terminal node exists
XCTAssertTrue(tree.InsertPrefix("as", 0));
XCTAssertEqual(tree.NodeCount(), 7);
// Re-inserting onto an existing node shouldn't modify the count
tree.InsertLiteral("as", 0);
tree.InsertPrefix("as", 0);
XCTAssertEqual(tree.NodeCount(), 7);
}
- (void)testReset {
// Ensure resetting a tree removes all content
PrefixTree<int> tree;
tree.Reset();
XCTAssertEqual(tree.NodeCount(), 0);
XCTAssertTrue(tree.InsertPrefix("asdf", 0));
XCTAssertTrue(tree.InsertPrefix("qwerty", 0));
XCTAssertTrue(tree.HasPrefix("asdf"));
XCTAssertTrue(tree.HasPrefix("qwerty"));
XCTAssertEqual(tree.NodeCount(), 10);
tree.Reset();
XCTAssertFalse(tree.HasPrefix("asdf"));
XCTAssertFalse(tree.HasPrefix("qwerty"));
XCTAssertEqual(tree.NodeCount(), 0);
}
- (void)testComplexValues {
class Foo {
public:
Foo(int x) : x_(x) {}
int X() { return x_; }
private:
int x_;
};
PrefixTree<std::shared_ptr<Foo>> tree;
XCTAssertTrue(tree.InsertPrefix("foo", std::make_shared<Foo>(123)));
XCTAssertTrue(tree.InsertPrefix("bar", std::make_shared<Foo>(456)));
std::optional<std::shared_ptr<Foo>> value;
value = tree.LookupLongestMatchingPrefix("foo");
XCTAssertTrue(value.has_value() && value->get()->X() == 123);
value = tree.LookupLongestMatchingPrefix("bar");
XCTAssertTrue(value.has_value() && value->get()->X() == 456);
value = tree.LookupLongestMatchingPrefix("asdf");
XCTAssertFalse(value.has_value());
}
- (void)testThreading {
uint32_t count = 4096;
auto t = new PrefixTree<int>(count * (uint32_t)[NSUUID UUID].UUIDString.length);
__block NSMutableArray *UUIDs = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count; ++i) {
[UUIDs addObject:[NSUUID UUID].UUIDString];
}
__block _Atomic BOOL stop = NO;
// Create a bunch of background noise.
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (uint64_t i = 0; i < UINT64_MAX; ++i) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
t->HasPrefix([UUIDs[i % count] UTF8String]);
});
if (stop) return;
}
});
// Fill up the tree.
dispatch_apply(count, dispatch_get_global_queue(0, 0), ^(size_t i) {
XCTAssertEqual(t->InsertPrefix([UUIDs[i] UTF8String], 0), true);
});
// Make sure every leaf byte is found.
dispatch_apply(count, dispatch_get_global_queue(0, 0), ^(size_t i) {
XCTAssertTrue(t->HasPrefix([UUIDs[i] UTF8String]));
});
stop = YES;
}
@end

View File

@@ -18,6 +18,9 @@
#import <Foundation/Foundation.h>
#endif
#import "Source/common/SNTFileAccessEvent.h"
#import "Source/common/SNTStoredEvent.h"
@class SNTStoredEvent;
@interface SNTBlockMessage : NSObject
@@ -38,11 +41,15 @@
+ (NSAttributedString *)attributedBlockMessageForEvent:(SNTStoredEvent *)event
customMessage:(NSString *)customMessage;
+ (NSAttributedString *)attributedBlockMessageForFileAccessEvent:(SNTFileAccessEvent *)event
customMessage:(NSString *)customMessage;
///
/// Return a URL generated from the EventDetailURL configuration key
/// after replacing templates in the URL with values from the event.
///
+ (NSURL *)eventDetailURLForEvent:(SNTStoredEvent *)event;
+ (NSURL *)eventDetailURLForEvent:(SNTStoredEvent *)event customURL:(NSString *)url;
+ (NSURL *)eventDetailURLForFileAccessEvent:(SNTFileAccessEvent *)event customURL:(NSString *)url;
///
/// Strip HTML from a string, replacing <br /> with newline.

View File

@@ -15,10 +15,15 @@
#import "Source/common/SNTBlockMessage.h"
#import "Source/common/SNTConfigurator.h"
#import "Source/common/SNTFileAccessEvent.h"
#import "Source/common/SNTLogging.h"
#import "Source/common/SNTStoredEvent.h"
#import "Source/common/SNTSystemInfo.h"
static id ValueOrNull(id value) {
return value ?: [NSNull null];
}
@implementation SNTBlockMessage
+ (NSAttributedString *)formatMessage:(NSString *)message {
@@ -51,7 +56,11 @@
#ifdef SANTAGUI
NSData *htmlData = [fullHTML dataUsingEncoding:NSUTF8StringEncoding];
return [[NSAttributedString alloc] initWithHTML:htmlData documentAttributes:NULL];
NSDictionary *options = @{
NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding),
};
return [[NSAttributedString alloc] initWithHTML:htmlData options:options documentAttributes:NULL];
#else
NSString *strippedHTML = [self stringFromHTML:fullHTML];
if (!strippedHTML) {
@@ -82,6 +91,18 @@
return [SNTBlockMessage formatMessage:message];
}
+ (NSAttributedString *)attributedBlockMessageForFileAccessEvent:(SNTFileAccessEvent *)event
customMessage:(NSString *)customMessage {
NSString *message = customMessage;
if (!message.length) {
message = [[SNTConfigurator configurator] fileAccessBlockMessage];
if (!message.length) {
message = @"Access to a file has been denied.";
}
}
return [SNTBlockMessage formatMessage:message];
}
+ (NSString *)stringFromHTML:(NSString *)html {
NSError *error;
NSXMLDocument *xml = [[NSXMLDocument alloc] initWithXMLString:html options:0 error:&error];
@@ -109,46 +130,113 @@
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
+ (NSURL *)eventDetailURLForEvent:(SNTStoredEvent *)event {
+ (NSString *)replaceFormatString:(NSString *)str
withDict:(NSDictionary<NSString *, NSString *> *)replacements {
__block NSString *formatStr = str;
[replacements enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
if ((id)value != [NSNull null]) {
formatStr = [formatStr stringByReplacingOccurrencesOfString:key withString:value];
}
}];
return formatStr;
}
//
// The following "format strings" will be replaced in the URL provided by
// `+eventDetailURLForEvent:customURL:templateMapping:`.
//
// %file_identifier% - The SHA-256 of the binary being executed.
// %bundle_or_file_identifier% - The hash of the bundle containing this file or the file itself,
// if no bundle hash is present.
// %file_bundle_id% - The bundle id of the binary, if any.
// %team_id% - The Team ID if present in the signature information.
// %signing_id% - The Signing ID if present in the signature information.
// %cdhash% - If signed, the CDHash.
// %username% - The executing user's name.
// %machine_id% - The configured machine ID for this host.
// %hostname% - The machine's FQDN.
// %uuid% - The machine's UUID.
// %serial% - The machine's serial number.
//
+ (NSDictionary *)eventDetailTemplateMappingForEvent:(SNTStoredEvent *)event {
SNTConfigurator *config = [SNTConfigurator configurator];
return @{
@"%file_sha%" : ValueOrNull(event.fileSHA256 ? event.fileBundleHash ?: event.fileSHA256 : nil),
@"%file_identifier%" : ValueOrNull(event.fileSHA256),
@"%bundle_or_file_identifier%" :
ValueOrNull(event.fileSHA256 ? event.fileBundleHash ?: event.fileSHA256 : nil),
@"%username%" : ValueOrNull(event.executingUser),
@"%file_bundle_id%" : ValueOrNull(event.fileBundleID),
@"%team_id%" : ValueOrNull(event.teamID),
@"%signing_id%" : ValueOrNull(event.signingID),
@"%cdhash%" : ValueOrNull(event.cdhash),
@"%machine_id%" : ValueOrNull(config.machineID),
@"%hostname%" : ValueOrNull([SNTSystemInfo longHostname]),
@"%uuid%" : ValueOrNull([SNTSystemInfo hardwareUUID]),
@"%serial%" : ValueOrNull([SNTSystemInfo serialNumber]),
};
}
//
// Everything from `+eventDetailTemplateMappingForEvent:` with the following file access
// specific templates.
//
// %rule_version% - The version of the rule that was violated.
// %rule_name% - The name of the rule that was violated.
// %accessed_path% - The path accessed by the binary.
//
+ (NSDictionary *)fileAccessEventDetailTemplateMappingForEvent:(SNTFileAccessEvent *)event {
NSMutableDictionary *d = [self eventDetailTemplateMappingForEvent:event].mutableCopy;
[d addEntriesFromDictionary:@{
@"%rule_version%" : ValueOrNull(event.ruleVersion),
@"%rule_name%" : ValueOrNull(event.ruleName),
@"%accessed_path%" : ValueOrNull(event.accessedPath),
}];
return d;
}
// Returns either the generated URL for the passed in event, or an NSURL from the passed in custom
// URL string. If the custom URL string is the string "null", nil will be returned. If no custom
// URL is passed and there is no configured EventDetailURL template, nil will be returned.
// The "format strings" in `templateMapping` will be replaced in the URL, if they are present.
+ (NSURL *)eventDetailURLForEvent:(SNTStoredEvent *)event
customURL:(NSString *)url
templateMapping:(NSDictionary *)templateMapping {
SNTConfigurator *config = [SNTConfigurator configurator];
NSString *hostname = [SNTSystemInfo longHostname];
NSString *uuid = [SNTSystemInfo hardwareUUID];
NSString *serial = [SNTSystemInfo serialNumber];
NSString *formatStr = config.eventDetailURL;
if (!formatStr.length) return nil;
if (event.fileSHA256) {
// This key is deprecated, use %file_identifier% or %bundle_or_file_identifier%
formatStr =
[formatStr stringByReplacingOccurrencesOfString:@"%file_sha%"
withString:event.fileBundleHash ?: event.fileSHA256];
formatStr = [formatStr stringByReplacingOccurrencesOfString:@"%file_identifier%"
withString:event.fileSHA256];
formatStr =
[formatStr stringByReplacingOccurrencesOfString:@"%bundle_or_file_identifier%"
withString:event.fileBundleHash ?: event.fileSHA256];
}
if (event.executingUser) {
formatStr = [formatStr stringByReplacingOccurrencesOfString:@"%username%"
withString:event.executingUser];
}
if (config.machineID) {
formatStr = [formatStr stringByReplacingOccurrencesOfString:@"%machine_id%"
withString:config.machineID];
}
if (hostname.length) {
formatStr = [formatStr stringByReplacingOccurrencesOfString:@"%hostname%" withString:hostname];
}
if (uuid.length) {
formatStr = [formatStr stringByReplacingOccurrencesOfString:@"%uuid%" withString:uuid];
}
if (serial.length) {
formatStr = [formatStr stringByReplacingOccurrencesOfString:@"%serial%" withString:serial];
NSString *formatStr = url;
if (!formatStr.length) {
formatStr = config.eventDetailURL;
if (!formatStr.length) {
return nil;
}
}
return [NSURL URLWithString:formatStr];
if ([formatStr isEqualToString:@"null"]) {
return nil;
}
formatStr = [SNTBlockMessage replaceFormatString:formatStr withDict:templateMapping];
NSURL *u = [NSURL URLWithString:formatStr];
if (!u) {
LOGW(@"Unable to generate event detail URL for string '%@'", formatStr);
}
return u;
}
+ (NSURL *)eventDetailURLForEvent:(SNTStoredEvent *)event customURL:(NSString *)url {
return [self eventDetailURLForEvent:event
customURL:url
templateMapping:[self eventDetailTemplateMappingForEvent:event]];
}
+ (NSURL *)eventDetailURLForFileAccessEvent:(SNTFileAccessEvent *)event customURL:(NSString *)url {
return [self eventDetailURLForEvent:event
customURL:url
templateMapping:[self fileAccessEventDetailTemplateMappingForEvent:event]];
}
@end

View File

@@ -0,0 +1,129 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#import "Source/common/SNTBlockMessage.h"
#import "Source/common/SNTConfigurator.h"
#include "Source/common/SNTFileAccessEvent.h"
#include "Source/common/SNTStoredEvent.h"
#import "Source/common/SNTSystemInfo.h"
@interface SNTBlockMessageTest : XCTestCase
@property id mockConfigurator;
@property id mockSystemInfo;
@end
@implementation SNTBlockMessageTest
- (void)setUp {
self.mockConfigurator = OCMClassMock([SNTConfigurator class]);
OCMStub([self.mockConfigurator configurator]).andReturn(self.mockConfigurator);
OCMStub([self.mockConfigurator machineID]).andReturn(@"my_mid");
self.mockSystemInfo = OCMClassMock([SNTSystemInfo class]);
OCMStub([self.mockSystemInfo longHostname]).andReturn(@"my_hn");
OCMStub([self.mockSystemInfo hardwareUUID]).andReturn(@"my_u");
OCMStub([self.mockSystemInfo serialNumber]).andReturn(@"my_s");
}
- (void)testFormatMessage {
NSString *input = @"Testing with somé Ünicode çharacters";
NSAttributedString *got = [SNTBlockMessage formatMessage:input];
XCTAssertEqualObjects([got string], input);
}
- (void)testEventDetailURLForEvent {
SNTStoredEvent *se = [[SNTStoredEvent alloc] init];
se.fileSHA256 = @"my_fi";
se.executingUser = @"my_un";
se.fileBundleID = @"s.n.t";
se.cdhash = @"abc";
se.teamID = @"SNT";
se.signingID = @"SNT:s.n.t";
NSString *url = @"http://"
@"localhost?fs=%file_sha%&fi=%file_identifier%&bfi=%bundle_or_file_identifier%&"
@"fbid=%file_bundle_id%&ti=%team_id%&si=%signing_id%&ch=%cdhash%&"
@"un=%username%&mid=%machine_id%&hn=%hostname%&u=%uuid%&s=%serial%";
NSString *wantUrl = @"http://"
@"localhost?fs=my_fi&fi=my_fi&bfi=my_fi&"
@"fbid=s.n.t&ti=SNT&si=SNT:s.n.t&ch=abc&"
@"un=my_un&mid=my_mid&hn=my_hn&u=my_u&s=my_s";
NSURL *gotUrl = [SNTBlockMessage eventDetailURLForEvent:se customURL:url];
// Set fileBundleHash and test again for newly expected values
se.fileBundleHash = @"my_fbh";
wantUrl = @"http://"
@"localhost?fs=my_fbh&fi=my_fi&bfi=my_fbh&"
@"fbid=s.n.t&ti=SNT&si=SNT:s.n.t&ch=abc&"
@"un=my_un&mid=my_mid&hn=my_hn&u=my_u&s=my_s";
gotUrl = [SNTBlockMessage eventDetailURLForEvent:se customURL:url];
XCTAssertEqualObjects(gotUrl.absoluteString, wantUrl);
XCTAssertNil([SNTBlockMessage eventDetailURLForEvent:se customURL:nil]);
XCTAssertNil([SNTBlockMessage eventDetailURLForEvent:se customURL:@"null"]);
}
- (void)testEventDetailURLForFileAccessEvent {
SNTFileAccessEvent *fae = [[SNTFileAccessEvent alloc] init];
fae.ruleVersion = @"my_rv";
fae.ruleName = @"my_rn";
fae.fileSHA256 = @"my_fi";
fae.fileBundleID = @"s.n.t";
fae.cdhash = @"abc";
fae.teamID = @"SNT";
fae.signingID = @"SNT:s.n.t";
fae.accessedPath = @"my_ap";
fae.executingUser = @"my_un";
NSString *url =
@"http://"
@"localhost?rv=%rule_version%&rn=%rule_name%&fi=%file_identifier%&"
@"fbid=%file_bundle_id%&ti=%team_id%&si=%signing_id%&ch=%cdhash%&"
@"ap=%accessed_path%&un=%username%&mid=%machine_id%&hn=%hostname%&u=%uuid%&s=%serial%";
NSString *wantUrl = @"http://"
@"localhost?rv=my_rv&rn=my_rn&fi=my_fi&"
@"fbid=s.n.t&ti=SNT&si=SNT:s.n.t&ch=abc&"
@"ap=my_ap&un=my_un&mid=my_mid&hn=my_hn&u=my_u&s=my_s";
NSURL *gotUrl = [SNTBlockMessage eventDetailURLForFileAccessEvent:fae customURL:url];
XCTAssertEqualObjects(gotUrl.absoluteString, wantUrl);
XCTAssertNil([SNTBlockMessage eventDetailURLForFileAccessEvent:fae customURL:nil]);
XCTAssertNil([SNTBlockMessage eventDetailURLForFileAccessEvent:fae customURL:@"null"]);
}
- (void)testEventDetailURLMissingDetails {
SNTStoredEvent *se = [[SNTStoredEvent alloc] init];
se.fileSHA256 = @"my_fi";
NSString *url = @"http://localhost?fi=%file_identifier%";
NSString *wantUrl = @"http://localhost?fi=my_fi";
NSURL *gotUrl = [SNTBlockMessage eventDetailURLForEvent:se customURL:url];
XCTAssertEqualObjects(gotUrl.absoluteString, wantUrl);
}
@end

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -12,10 +12,11 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <EndpointSecurity/EndpointSecurity.h>
#import <Foundation/Foundation.h>
#import "Source/common/SNTCommonEnums.h"
#import "Source/common/SNTCommon.h"
#import "Source/common/SantaVnode.h"
@class MOLCertificate;
@@ -24,8 +25,13 @@
///
@interface SNTCachedDecision : NSObject
@property santa_vnode_id_t vnodeId;
- (instancetype)init;
- (instancetype)initWithEndpointSecurityFile:(const es_file_t *)esFile;
- (instancetype)initWithVnode:(SantaVnode)vnode NS_DESIGNATED_INITIALIZER;
@property SantaVnode vnodeId;
@property SNTEventState decision;
@property SNTClientMode decisionClientMode;
@property NSString *decisionExtra;
@property NSString *sha256;
@@ -33,10 +39,15 @@
@property NSString *certCommonName;
@property NSArray<MOLCertificate *> *certChain;
@property NSString *teamID;
@property NSString *signingID;
@property NSString *cdhash;
@property NSDictionary *entitlements;
@property BOOL entitlementsFiltered;
@property NSString *quarantineURL;
@property NSString *customMsg;
@property NSString *customURL;
@property BOOL silentBlock;
@end

View File

@@ -1,4 +1,5 @@
/// Copyright 2021 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -12,21 +13,24 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/common/SNTAllowlistInfo.h"
#import "Source/common/SNTCachedDecision.h"
@implementation SNTAllowlistInfo
@implementation SNTCachedDecision
- (instancetype)initWithPid:(pid_t)pid
pidversion:(int)pidver
targetPath:(NSString *)targetPath
sha256:(NSString *)hash {
- (instancetype)init {
return [self initWithVnode:(SantaVnode){}];
}
- (instancetype)initWithEndpointSecurityFile:(const es_file_t *)esFile {
return [self initWithVnode:SantaVnode::VnodeForFile(esFile)];
}
- (instancetype)initWithVnode:(SantaVnode)vnode {
self = [super init];
if (self) {
_pid = pid;
_pidversion = pidver;
_targetPath = targetPath;
_sha256 = hash;
_vnodeId = vnode;
}
return self;
}
@end

View File

@@ -0,0 +1,36 @@
/// Copyright 2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <XCTest/XCTest.h>
#import "Source/common/SNTCachedDecision.h"
#include "Source/common/TestUtils.h"
@interface SNTCachedDecisionTest : XCTestCase
@end
@implementation SNTCachedDecisionTest
- (void)testSNTCachedDecisionInit {
// Ensure the vnodeId field is properly set from the es_file_t
struct stat sb = MakeStat();
es_file_t file = MakeESFile("foo", sb);
SNTCachedDecision *cd = [[SNTCachedDecision alloc] initWithEndpointSecurityFile:&file];
XCTAssertEqual(sb.st_ino, cd.vnodeId.fileid);
XCTAssertEqual(sb.st_dev, cd.vnodeId.fsid);
}
@end

View File

@@ -1,102 +0,0 @@
/// Copyright 2015 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Common defines between daemon <-> client
///
#ifndef SANTA__COMMON__COMMON_H
#define SANTA__COMMON__COMMON_H
#include <stdint.h>
#include <sys/param.h>
// Branch prediction
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
typedef enum {
ACTION_UNSET = 0,
// REQUESTS
ACTION_REQUEST_SHUTDOWN = 10,
ACTION_REQUEST_BINARY = 11,
// RESPONSES
ACTION_RESPOND_ALLOW = 20,
ACTION_RESPOND_DENY = 21,
ACTION_RESPOND_TOOLONG = 22,
ACTION_RESPOND_ACK = 23,
ACTION_RESPOND_ALLOW_COMPILER = 24,
// The following response is stored only in the kernel decision cache.
// It is removed by SNTCompilerController
ACTION_RESPOND_ALLOW_PENDING_TRANSITIVE = 25,
// NOTIFY
ACTION_NOTIFY_EXEC = 30,
ACTION_NOTIFY_WRITE = 31,
ACTION_NOTIFY_RENAME = 32,
ACTION_NOTIFY_LINK = 33,
ACTION_NOTIFY_EXCHANGE = 34,
ACTION_NOTIFY_DELETE = 35,
ACTION_NOTIFY_WHITELIST = 36,
ACTION_NOTIFY_FORK = 37,
ACTION_NOTIFY_EXIT = 38,
// ERROR
ACTION_ERROR = 99,
} santa_action_t;
#define RESPONSE_VALID(x) \
(x == ACTION_RESPOND_ALLOW || x == ACTION_RESPOND_DENY || \
x == ACTION_RESPOND_ALLOW_COMPILER || \
x == ACTION_RESPOND_ALLOW_PENDING_TRANSITIVE)
// Struct to manage vnode IDs
typedef struct santa_vnode_id_t {
uint64_t fsid;
uint64_t fileid;
#ifdef __cplusplus
bool operator==(const santa_vnode_id_t &rhs) const {
return fsid == rhs.fsid && fileid == rhs.fileid;
}
#endif
} santa_vnode_id_t;
typedef struct {
santa_action_t action;
santa_vnode_id_t vnode_id;
uid_t uid;
gid_t gid;
pid_t pid;
int pidversion;
pid_t ppid;
char path[MAXPATHLEN];
char newpath[MAXPATHLEN];
char ttypath[MAXPATHLEN];
// For file events, this is the process name.
// For exec requests, this is the parent process name.
// While process names can technically be 4*MAXPATHLEN, that never
// actually happens, so only take MAXPATHLEN and throw away any excess.
char pname[MAXPATHLEN];
// This points to a copy of the original ES message.
void *es_message;
// This points to an NSArray of the process arguments.
void *args_array;
} santa_message_t;
#endif // SANTA__COMMON__COMMON_H

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -19,12 +19,38 @@
/// The integer values are also stored in the database and so shouldn't be changed.
///
typedef NS_ENUM(NSInteger, SNTRuleType) {
SNTRuleTypeUnknown,
typedef NS_ENUM(NSInteger, SNTAction) {
SNTActionUnset,
SNTRuleTypeBinary = 1,
SNTRuleTypeCertificate = 2,
SNTRuleTypeTeamID = 3,
// REQUESTS
// If an operation is awaiting a cache decision from a similar operation
// currently being processed, it will poll about every 5 ms for an answer.
SNTActionRequestBinary,
// RESPONSES
SNTActionRespondAllow,
SNTActionRespondDeny,
SNTActionRespondAllowCompiler,
};
#define RESPONSE_VALID(x) \
(x == SNTActionRespondAllow || x == SNTActionRespondDeny || x == SNTActionRespondAllowCompiler)
// Supported Rule Types
//
// Note: These enum values should be in order of decreasing precedence as
// evaluated by Santa. When adding new enum values, leave some space so that
// additional rules can be added without violating this. The ordering isn't
// strictly necessary but improves readability and may preemptively prevent
// issues should SQLite behavior change.
typedef NS_ENUM(NSInteger, SNTRuleType) {
SNTRuleTypeUnknown = 0,
SNTRuleTypeCDHash = 500,
SNTRuleTypeBinary = 1000,
SNTRuleTypeSigningID = 2000,
SNTRuleTypeCertificate = 3000,
SNTRuleTypeTeamID = 4000,
};
typedef NS_ENUM(NSInteger, SNTRuleState) {
@@ -46,31 +72,36 @@ typedef NS_ENUM(NSInteger, SNTClientMode) {
SNTClientModeLockdown = 2,
};
typedef NS_ENUM(NSInteger, SNTEventState) {
typedef NS_ENUM(uint64_t, SNTEventState) {
// Bits 0-15 bits store non-decision types
SNTEventStateUnknown = 0,
SNTEventStateBundleBinary = 1,
// Bits 16-23 store deny decision types
SNTEventStateBlockUnknown = 1 << 16,
SNTEventStateBlockBinary = 1 << 17,
SNTEventStateBlockCertificate = 1 << 18,
SNTEventStateBlockScope = 1 << 19,
SNTEventStateBlockTeamID = 1 << 20,
// Bits 16-39 store deny decision types
SNTEventStateBlockUnknown = 1ULL << 16,
SNTEventStateBlockBinary = 1ULL << 17,
SNTEventStateBlockCertificate = 1ULL << 18,
SNTEventStateBlockScope = 1ULL << 19,
SNTEventStateBlockTeamID = 1ULL << 20,
SNTEventStateBlockLongPath = 1ULL << 21,
SNTEventStateBlockSigningID = 1ULL << 22,
SNTEventStateBlockCDHash = 1ULL << 23,
// Bits 24-31 store allow decision types
SNTEventStateAllowUnknown = 1 << 24,
SNTEventStateAllowBinary = 1 << 25,
SNTEventStateAllowCertificate = 1 << 26,
SNTEventStateAllowScope = 1 << 27,
SNTEventStateAllowCompiler = 1 << 28,
SNTEventStateAllowTransitive = 1 << 29,
SNTEventStateAllowPendingTransitive = 1 << 30,
SNTEventStateAllowTeamID = 1 << 31,
// Bits 40-63 store allow decision types
SNTEventStateAllowUnknown = 1ULL << 40,
SNTEventStateAllowBinary = 1ULL << 41,
SNTEventStateAllowCertificate = 1ULL << 42,
SNTEventStateAllowScope = 1ULL << 43,
SNTEventStateAllowCompiler = 1ULL << 44,
SNTEventStateAllowTransitive = 1ULL << 45,
SNTEventStateAllowPendingTransitive = 1ULL << 46,
SNTEventStateAllowTeamID = 1ULL << 47,
SNTEventStateAllowSigningID = 1ULL << 48,
SNTEventStateAllowCDHash = 1ULL << 49,
// Block and Allow masks
SNTEventStateBlock = 0xFF << 16,
SNTEventStateAllow = 0xFF << 24
SNTEventStateBlock = 0xFFFFFFULL << 16,
SNTEventStateAllow = 0xFFFFFFULL << 40,
};
typedef NS_ENUM(NSInteger, SNTRuleTableError) {
@@ -93,6 +124,7 @@ typedef NS_ENUM(NSInteger, SNTEventLogType) {
SNTEventLogTypeSyslog,
SNTEventLogTypeFilelog,
SNTEventLogTypeProtobuf,
SNTEventLogTypeJSON,
SNTEventLogTypeNull,
};
@@ -111,14 +143,70 @@ typedef NS_ENUM(NSInteger, SNTSyncStatusType) {
SNTSyncStatusTypeUnknown,
};
typedef NS_ENUM(NSInteger, SNTSyncContentEncoding) {
SNTSyncContentEncodingNone,
SNTSyncContentEncodingDeflate,
SNTSyncContentEncodingGzip,
};
typedef NS_ENUM(NSInteger, SNTMetricFormatType) {
SNTMetricFormatTypeUnknown,
SNTMetricFormatTypeRawJSON,
SNTMetricFormatTypeMonarchJSON,
};
typedef NS_ENUM(NSInteger, SNTOverrideFileAccessAction) {
SNTOverrideFileAccessActionNone,
SNTOverrideFileAccessActionAuditOnly,
SNTOverrideFileAccessActionDiable,
};
typedef NS_ENUM(NSInteger, SNTDeviceManagerStartupPreferences) {
SNTDeviceManagerStartupPreferencesNone,
SNTDeviceManagerStartupPreferencesUnmount,
SNTDeviceManagerStartupPreferencesForceUnmount,
SNTDeviceManagerStartupPreferencesRemount,
SNTDeviceManagerStartupPreferencesForceRemount,
};
typedef NS_ENUM(NSInteger, SNTSyncType) {
SNTSyncTypeNormal,
SNTSyncTypeClean,
SNTSyncTypeCleanAll,
};
typedef NS_ENUM(NSInteger, SNTRuleCleanup) {
SNTRuleCleanupNone,
SNTRuleCleanupAll,
SNTRuleCleanupNonTransitive,
};
#ifdef __cplusplus
enum class FileAccessPolicyDecision {
kNoPolicy,
kDenied,
kDeniedInvalidSignature,
kAllowed,
kAllowedReadAccess,
kAllowedAuditOnly,
};
enum class StatChangeStep {
kNoChange = 0,
kMessageCreate,
kCodesignValidation,
};
enum class StatResult {
kOK = 0,
kStatError,
kDevnoInodeMismatch,
};
#endif
static const char *kSantaDPath =
"/Applications/Santa.app/Contents/Library/SystemExtensions/"
"com.google.santa.daemon.systemextension/Contents/MacOS/com.google.santa.daemon";
static const char *kSantaCtlPath = "/Applications/Santa.app/Contents/MacOS/santactl";
static const char *kSantaAppPath = "/Applications/Santa.app";

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -40,7 +40,8 @@
///
/// Enable Fail Close mode. Defaults to NO.
/// This controls Santa's behavior when a failure occurs, such as an
/// inability to read a file. By default, to prevent bugs or misconfiguration
/// inability to read a file and as a default response when deadlines
/// are about to expire. By default, to prevent bugs or misconfiguration
/// from rendering a machine inoperable Santa will fail open and allow
/// execution. With this setting enabled, Santa will fail closed if the client
/// is in LOCKDOWN mode, offering a higher level of security but with a higher
@@ -65,7 +66,8 @@
/// <key>rule_type</key>
/// <string>BINARY</string> (one of BINARY, CERTIFICATE or TEAMID)
/// <key>policy</key>
/// <string>BLOCKLIST</string> (one of ALLOWLIST, ALLOWLIST_COMPILER, BLOCKLIST, SILENT_BLOCKLIST)
/// <string>BLOCKLIST</string> (one of ALLOWLIST, ALLOWLIST_COMPILER, BLOCKLIST,
/// SILENT_BLOCKLIST)
/// </dict>
/// </array>
///
@@ -182,10 +184,10 @@
/// SNTEventLogTypeSyslog "syslog": Sent to ASL or ULS (if built with the 10.12 SDK or later).
/// SNTEventLogTypeFilelog "file": Sent to a file on disk. Use eventLogPath to specify a path.
/// SNTEventLogTypeNull "null": Logs nothing
/// SNTEventLogTypeProtobuf "protobuf": (BETA) Sent to a file on disk, using maildir format. Use
/// mailDirectory to specify a path. Use mailDirectoryFileSizeThresholdKB,
/// mailDirectorySizeThresholdMB and mailDirectoryEventMaxFlushTimeSec to configure
/// additional maildir format settings.
/// SNTEventLogTypeProtobuf "protobuf": (BETA) Sent to a file on disk, using a maildir-like
/// format. Use spoolDirectory to specify a path. Use spoolDirectoryFileSizeThresholdKB,
/// spoolDirectorySizeThresholdMB and spoolDirectoryEventMaxFlushTimeSec to configure
/// additional settings.
/// Defaults to SNTEventLogTypeFilelog.
/// For mobileconfigs use EventLogType as the key and syslog or filelog strings as the value.
///
@@ -193,6 +195,13 @@
///
@property(readonly, nonatomic) SNTEventLogType eventLogType;
///
/// Returns the raw value of the EventLogType configuration key instead of being
/// converted to the SNTEventLogType enum. If the key is not set, the default log
/// type is returned.
///
@property(readonly, nonatomic) NSString *eventLogTypeRaw;
///
/// If eventLogType is set to Filelog, eventLogPath will provide the path to save logs.
/// Defaults to /var/db/santa/santa.log.
@@ -202,57 +211,85 @@
@property(readonly, nonatomic) NSString *eventLogPath;
///
/// If eventLogType is set to protobuf, mailDirectory will provide the base path used for
/// saving logs using the maildir format.
/// Defaults to /var/db/santa/mail.
/// If eventLogType is set to protobuf, spoolDirectory will provide the base path used for
/// saving logs using a maildir-like format.
/// Defaults to /var/db/santa/spool.
///
/// @note: This property is KVO compliant, but should only be read once at santad startup.
///
@property(readonly, nonatomic) NSString *mailDirectory;
@property(readonly, nonatomic) NSString *spoolDirectory;
///
/// If eventLogType is set to protobuf, mailDirectoryFileSizeThresholdKB sets the per-file size
/// limit for files saved in the mailDirectory.
/// If eventLogType is set to protobuf, spoolDirectoryFileSizeThresholdKB sets the per-file size
/// limit for files saved in the spoolDirectory.
/// Defaults to 250.
///
/// @note: This property is KVO compliant, but should only be read once at santad startup.
///
@property(readonly, nonatomic) NSUInteger spoolDirectoryFileSizeThresholdKB;
///
/// If eventLogType is set to protobuf, spoolDirectorySizeThresholdMB sets the total size
/// limit for all files saved in the spoolDirectory.
/// Defaults to 100.
///
/// @note: This property is KVO compliant, but should only be read once at santad startup.
///
@property(readonly, nonatomic) NSUInteger mailDirectoryFileSizeThresholdKB;
@property(readonly, nonatomic) NSUInteger spoolDirectorySizeThresholdMB;
///
/// If eventLogType is set to protobuf, mailDirectorySizeThresholdMB sets the total size
/// limit for all files saved in the mailDirectory.
/// Defaults to 500.
///
/// @note: This property is KVO compliant, but should only be read once at santad startup.
///
@property(readonly, nonatomic) NSUInteger mailDirectorySizeThresholdMB;
///
/// If eventLogType is set to protobuf, mailDirectoryEventMaxFlushTimeSec sets the maximum amount
/// If eventLogType is set to protobuf, spoolDirectoryEventMaxFlushTimeSec sets the maximum amount
/// of time an event will be stored in memory before being written to disk.
/// Defaults to 5.0.
/// Defaults to 15.0.
///
/// @note: This property is KVO compliant, but should only be read once at santad startup.
///
@property(readonly, nonatomic) float mailDirectoryEventMaxFlushTimeSec;
@property(readonly, nonatomic) float spoolDirectoryEventMaxFlushTimeSec;
///
/// If set, contains the filesystem access policy configuration.
///
/// @note: The property fileAccessPolicyPlist will be ignored if
/// fileAccessPolicy is set.
/// @note: This property is KVO compliant.
///
@property(readonly, nonatomic) NSDictionary *fileAccessPolicy;
///
/// If set, contains the path to the filesystem access policy config plist.
///
/// @note: This property will be ignored if fileAccessPolicy is set.
/// @note: This property is KVO compliant.
///
@property(readonly, nonatomic) NSString *fileAccessPolicyPlist;
///
/// This is the message shown to the user when access to a file is blocked
/// by a binary due to some rule in the current File Access policy if that rule
/// doesn't provide a custom message. If this is not configured, a reasonable
/// default is provided.
///
/// @note: This property is KVO compliant.
///
@property(readonly, nonatomic) NSString *fileAccessBlockMessage;
///
/// If fileAccessPolicyPlist is set, fileAccessPolicyUpdateIntervalSec
/// sets the number of seconds between times that the configuration file is
/// re-read and policies reconstructed.
/// Defaults to 600 seconds (10 minutes)
///
/// @note: This property is KVO compliant, but should only be read once at santad startup.
///
@property(readonly, nonatomic) uint32_t fileAccessPolicyUpdateIntervalSec;
///
/// Enabling this appends the Santa machine ID to the end of each log line. If nothing
/// has been overriden, this is the host's UUID.
/// has been overridden, this is the host's UUID.
/// Defaults to NO.
///
@property(readonly, nonatomic) BOOL enableMachineIDDecoration;
///
/// Use an internal cache for decisions instead of relying on the caching
/// mechanism built-in to the EndpointSecurity framework. This may increase
/// performance, particularly when Santa is run alongside other system
/// extensions.
/// Has no effect if the system extension is not being used. Defaults to NO.
///
@property(readonly, nonatomic) BOOL enableSysxCache;
#pragma mark - GUI Settings
///
@@ -265,6 +302,14 @@
///
@property(readonly, nonatomic) BOOL enableSilentMode;
///
/// When silent TTY mode is enabled, Santa will not emit TTY notifications for
/// blocked processes.
///
/// Defaults to NO.
///
@property(readonly, nonatomic) BOOL enableSilentTTYMode;
///
/// The text to display when opening Santa.app.
/// If unset, the default text will be displayed.
@@ -302,6 +347,11 @@
///
@property(readonly, nonatomic) NSString *eventDetailText;
///
/// This string represents the text to show on the "Dismiss" button in the UI instead of "Dismiss".
///
@property(readonly, nonatomic) NSString *dismissText;
///
/// In lockdown mode this is the message shown to the user when an unknown binary
/// is blocked. If this message is not configured, a reasonable default is provided.
@@ -348,14 +398,41 @@
///
@property(readonly, nonatomic) NSURL *syncBaseURL;
///
/// If enabled, syncing will use binary protobufs for transfer instead
/// of JSON. Defaults to NO.
///
@property(readonly, nonatomic) BOOL syncEnableProtoTransfer;
///
/// Proxy settings for syncing.
/// This dictionary is passed directly to NSURLSession. The allowed keys
/// are loosely documented at
/// https://developer.apple.com/documentation/cfnetwork/global_proxy_settings_constants.
/// https://developer.apple.com/documentation/cfnetwork/global-proxy-settings-constants.
///
@property(readonly, nonatomic) NSDictionary *syncProxyConfig;
///
/// Extra headers to include in all requests made during syncing.
/// Keys and values must all be strings, any other type will be silently ignored.
/// Some headers cannot be set through this key, including:
///
/// * Content-Encoding
/// * Content-Length
/// * Content-Type
/// * Connection
/// * Host
/// * Proxy-Authenticate
/// * Proxy-Authorization
/// * WWW-Authenticate
///
/// The header "Authorization" is also documented by Apple to be one that will
/// be ignored but this is not really the case, at least at present. If you
/// are able to use a different header for this that would be safest but if not
/// using Authorization /should/ be fine.
///
@property(readonly, nonatomic) NSDictionary *syncExtraHeaders;
///
/// The machine owner.
///
@@ -372,9 +449,11 @@
@property(nonatomic) NSDate *ruleSyncLastSuccess;
///
/// If YES a clean sync is required.
/// Type of sync required (e.g. normal, clean, etc.).
///
@property(nonatomic) BOOL syncCleanRequired;
@property(nonatomic) SNTSyncType syncTypeRequired;
#pragma mark - USB Settings
///
/// USB Mount Blocking. Defaults to false.
@@ -382,16 +461,43 @@
@property(nonatomic) BOOL blockUSBMount;
///
/// Comma-seperated `$ mount -o` arguments used for forced remounting of USB devices. Default
/// Comma-separated `$ mount -o` arguments used for forced remounting of USB devices. Default
/// to fully allow/deny without remounting if unset.
///
@property(nonatomic) NSArray<NSString *> *remountUSBMode;
///
/// When `blockUSBMount` is set, this is the message shown to the user when a device is blocked
/// If this message is not configured, a reasonable default is provided.
/// If set, defines the action that should be taken on existing USB mounts when
/// Santa starts up.
///
@property(readonly, nonatomic) NSString *usbBlockMessage;
/// Supported values are:
/// * "Unmount": Unmount mass storage devices
/// * "ForceUnmount": Force unmount mass storage devices
///
///
/// Note: Existing mounts with mount flags that are a superset of RemountUSBMode
/// are unaffected and left mounted.
///
@property(readonly, nonatomic) SNTDeviceManagerStartupPreferences onStartUSBOptions;
///
/// If set, will override the action taken when a file access rule violation
/// occurs. This setting will apply across all rules in the file access policy.
///
/// Possible values are
/// * "AuditOnly": When a rule is violated, it will be logged, but the access
/// will not be blocked
/// * "Disable": No access will be logged or blocked.
///
/// If not set, no override will take place and the file acces spolicy will
/// apply as configured.
///
@property(readonly, nonatomic) SNTOverrideFileAccessAction overrideFileAccessAction;
///
/// Set the action that will override file access policy config action
///
- (void)setSyncServerOverrideFileAccessAction:(NSString *)action;
///
/// If set, this over-rides the default machine ID used for syncing.
@@ -492,6 +598,12 @@
///
@property(readonly, nonatomic) BOOL enableBackwardsCompatibleContentEncoding;
///
/// If set, "santactl sync" will use the supplied "Content-Encoding", possible
/// settings include "gzip", "deflate", "none". If empty defaults to "deflate".
///
@property(readonly, nonatomic) SNTSyncContentEncoding syncClientContentEncoding;
///
/// Contains the FCM project name.
///
@@ -542,6 +654,24 @@
///
@property(readonly, nonatomic) NSUInteger metricExportTimeout;
///
/// List of prefix strings for which individual entitlement keys with a matching
/// prefix should not be logged.
///
@property(readonly, nonatomic) NSArray<NSString *> *entitlementsPrefixFilter;
///
/// List of TeamIDs for which entitlements should not be logged. Use the string
/// "platform" to refer to platform binaries.
///
@property(readonly, nonatomic) NSArray<NSString *> *entitlementsTeamIDFilter;
///
/// List of enabled process annotations.
/// This property is not KVO compliant.
///
@property(readonly, nonatomic) NSArray<NSString *> *enabledProcessAnnotations;
///
/// Retrieve an initialized singleton configurator object using the default file path.
///

View File

@@ -1,4 +1,4 @@
/// Copyright 2021 Google Inc. All rights reserved.
/// Copyright 2014-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -20,6 +20,21 @@
#import "Source/common/SNTStrengthify.h"
#import "Source/common/SNTSystemInfo.h"
// Ensures the given object is an NSArray and only contains NSString value types
static NSArray<NSString *> *EnsureArrayOfStrings(id obj) {
if (![obj isKindOfClass:[NSArray class]]) {
return nil;
}
for (id item in obj) {
if (![item isKindOfClass:[NSString class]]) {
return nil;
}
}
return obj;
}
@interface SNTConfigurator ()
/// A NSUserDefaults object set to use the com.google.santa suite.
@property(readonly, nonatomic) NSUserDefaults *defaults;
@@ -37,6 +52,10 @@
/// Holds the last processed hash of the static rules list.
@property(atomic) NSDictionary *cachedStaticRules;
@property(readonly, nonatomic) NSString *syncStateFilePath;
@property(nonatomic, copy) BOOL (^syncStateAccessAuthorizerBlock)();
@end
@implementation SNTConfigurator
@@ -44,13 +63,19 @@
/// The hard-coded path to the sync state file.
NSString *const kSyncStateFilePath = @"/var/db/santa/sync-state.plist";
#ifdef DEBUG
NSString *const kConfigOverrideFilePath = @"/var/db/santa/config-overrides.plist";
#endif
/// The domain used by mobileconfig.
static NSString *const kMobileConfigDomain = @"com.google.santa";
/// The keys managed by a mobileconfig.
static NSString *const kStaticRules = @"StaticRules";
static NSString *const kSyncBaseURLKey = @"SyncBaseURL";
static NSString *const kSyncEnableProtoTransfer = @"SyncEnableProtoTransfer";
static NSString *const kSyncProxyConfigKey = @"SyncProxyConfiguration";
static NSString *const kSyncExtraHeadersKey = @"SyncExtraHeaders";
static NSString *const kSyncEnableCleanSyncEventUpload = @"SyncEnableCleanSyncEventUpload";
static NSString *const kClientAuthCertificateFileKey = @"ClientAuthCertificateFile";
static NSString *const kClientAuthCertificatePasswordKey = @"ClientAuthCertificatePassword";
@@ -67,10 +92,12 @@ static NSString *const kMachineIDPlistFileKey = @"MachineIDPlist";
static NSString *const kMachineIDPlistKeyKey = @"MachineIDKey";
static NSString *const kEnableSilentModeKey = @"EnableSilentMode";
static NSString *const kEnableSilentTTYModeKey = @"EnableSilentTTYMode";
static NSString *const kAboutTextKey = @"AboutText";
static NSString *const kMoreInfoURLKey = @"MoreInfoURL";
static NSString *const kEventDetailURLKey = @"EventDetailURL";
static NSString *const kEventDetailTextKey = @"EventDetailText";
static NSString *const kDismissTextKey = @"DismissText";
static NSString *const kUnknownBlockMessage = @"UnknownBlockMessage";
static NSString *const kBannedBlockMessage = @"BannedBlockMessage";
static NSString *const kBannedUSBBlockMessage = @"BannedUSBBlockMessage";
@@ -81,35 +108,51 @@ static NSString *const kModeNotificationLockdown = @"ModeNotificationLockdown";
static NSString *const kEnablePageZeroProtectionKey = @"EnablePageZeroProtection";
static NSString *const kEnableBadSignatureProtectionKey = @"EnableBadSignatureProtection";
static NSString *const kFailClosedKey = @"FailClosed";
static NSString *const kDisableUnknownEventUploadKey = @"DisableUnknownEventUpload";
static NSString *const kFileChangesRegexKey = @"FileChangesRegex";
static NSString *const kFileChangesPrefixFiltersKey = @"FileChangesPrefixFilters";
static NSString *const kEventLogType = @"EventLogType";
static NSString *const kEventLogPath = @"EventLogPath";
static NSString *const kMailDirectory = @"MailDirectory";
static NSString *const kMailDirectoryFileSizeThresholdKB = @"MailDirectoryFileSizeThresholdKB";
static NSString *const kMailDirectorySizeThresholdMB = @"MailDirectorySizeThresholdMB";
static NSString *const kMailDirectoryEventMaxFlushTimeSec = @"MailDirectoryEventMaxFlushTimeSec";
static NSString *const kSpoolDirectory = @"SpoolDirectory";
static NSString *const kSpoolDirectoryFileSizeThresholdKB = @"SpoolDirectoryFileSizeThresholdKB";
static NSString *const kSpoolDirectorySizeThresholdMB = @"SpoolDirectorySizeThresholdMB";
static NSString *const kSpoolDirectoryEventMaxFlushTimeSec = @"SpoolDirectoryEventMaxFlushTimeSec";
static NSString *const kFileAccessPolicy = @"FileAccessPolicy";
static NSString *const kFileAccessPolicyPlist = @"FileAccessPolicyPlist";
static NSString *const kFileAccessBlockMessage = @"FileAccessBlockMessage";
static NSString *const kFileAccessPolicyUpdateIntervalSec = @"FileAccessPolicyUpdateIntervalSec";
static NSString *const kEnableMachineIDDecoration = @"EnableMachineIDDecoration";
static NSString *const kEnableSysxCache = @"EnableSysxCache";
static NSString *const kEnableForkAndExitLogging = @"EnableForkAndExitLogging";
static NSString *const kIgnoreOtherEndpointSecurityClients = @"IgnoreOtherEndpointSecurityClients";
static NSString *const kEnableDebugLogging = @"EnableDebugLogging";
static NSString *const kEnableBackwardsCompatibleContentEncoding =
@"EnableBackwardsCompatibleContentEncoding";
static NSString *const kClientContentEncoding = @"SyncClientContentEncoding";
static NSString *const kFCMProject = @"FCMProject";
static NSString *const kFCMEntity = @"FCMEntity";
static NSString *const kFCMAPIKey = @"FCMAPIKey";
static NSString *const kEntitlementsPrefixFilterKey = @"EntitlementsPrefixFilter";
static NSString *const kEntitlementsTeamIDFilterKey = @"EntitlementsTeamIDFilter";
static NSString *const kOnStartUSBOptions = @"OnStartUSBOptions";
static NSString *const kMetricFormat = @"MetricFormat";
static NSString *const kMetricURL = @"MetricURL";
static NSString *const kMetricExportInterval = @"MetricExportInterval";
static NSString *const kMetricExportTimeout = @"MetricExportTimeout";
static NSString *const kMetricExtraLabels = @"MetricExtraLabels";
static NSString *const kEnabledProcessAnnotations = @"EnabledProcessAnnotations";
// The keys managed by a sync server or mobileconfig.
static NSString *const kClientModeKey = @"ClientMode";
static NSString *const kFailClosedKey = @"FailClosed";
static NSString *const kBlockUSBMountKey = @"BlockUSBMount";
static NSString *const kRemountUSBModeKey = @"RemountUSBMode";
static NSString *const kEnableTransitiveRulesKey = @"EnableTransitiveRules";
@@ -119,21 +162,24 @@ static NSString *const kAllowedPathRegexKeyDeprecated = @"WhitelistRegex";
static NSString *const kBlockedPathRegexKey = @"BlockedPathRegex";
static NSString *const kBlockedPathRegexKeyDeprecated = @"BlacklistRegex";
static NSString *const kEnableAllEventUploadKey = @"EnableAllEventUpload";
static NSString *const kDisableUnknownEventUploadKey = @"DisableUnknownEventUpload";
// TODO(markowsky): move these to sync server only.
static NSString *const kMetricFormat = @"MetricFormat";
static NSString *const kMetricURL = @"MetricURL";
static NSString *const kMetricExportInterval = @"MetricExportInterval";
static NSString *const kMetricExportTimeout = @"MetricExportTimeout";
static NSString *const kMetricExtraLabels = @"MetricExtraLabels";
static NSString *const kOverrideFileAccessActionKey = @"OverrideFileAccessAction";
// The keys managed by a sync server.
static NSString *const kFullSyncLastSuccess = @"FullSyncLastSuccess";
static NSString *const kRuleSyncLastSuccess = @"RuleSyncLastSuccess";
static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
static NSString *const kSyncCleanRequiredDeprecated = @"SyncCleanRequired";
static NSString *const kSyncTypeRequired = @"SyncTypeRequired";
- (instancetype)init {
return [self initWithSyncStateFile:kSyncStateFilePath
syncStateAccessAuthorizer:^BOOL() {
// Only access the sync state if a sync server is configured and running as root
return self.syncBaseURL != nil && geteuid() == 0;
}];
}
- (instancetype)initWithSyncStateFile:(NSString *)syncStateFilePath
syncStateAccessAuthorizer:(BOOL (^)(void))syncStateAccessAuthorizer {
self = [super init];
if (self) {
Class number = [NSNumber class];
@@ -155,8 +201,10 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
kRemountUSBModeKey : array,
kFullSyncLastSuccess : date,
kRuleSyncLastSuccess : date,
kSyncCleanRequired : number,
kSyncCleanRequiredDeprecated : number,
kSyncTypeRequired : number,
kEnableAllEventUploadKey : number,
kOverrideFileAccessActionKey : string,
};
_forcedConfigKeyTypes = @{
kClientModeKey : number,
@@ -171,13 +219,16 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
kBlockedPathRegexKeyDeprecated : re,
kBlockUSBMountKey : number,
kRemountUSBModeKey : array,
kOnStartUSBOptions : string,
kEnablePageZeroProtectionKey : number,
kEnableBadSignatureProtectionKey : number,
kEnableSilentModeKey : string,
kEnableSilentModeKey : number,
kEnableSilentTTYModeKey : number,
kAboutTextKey : string,
kMoreInfoURLKey : string,
kEventDetailURLKey : string,
kEventDetailTextKey : string,
kDismissTextKey : string,
kUnknownBlockMessage : string,
kBannedBlockMessage : string,
kBannedUSBBlockMessage : string,
@@ -186,11 +237,15 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
kModeNotificationLockdown : string,
kStaticRules : array,
kSyncBaseURLKey : string,
kSyncEnableProtoTransfer : number,
kSyncEnableCleanSyncEventUpload : number,
kSyncProxyConfigKey : dictionary,
kSyncExtraHeadersKey : dictionary,
kClientAuthCertificateFileKey : string,
kClientAuthCertificatePasswordKey : string,
kClientAuthCertificateCNKey : string,
kClientAuthCertificateIssuerKey : string,
kClientContentEncoding : string,
kServerAuthRootsDataKey : data,
kServerAuthRootsFileKey : string,
kMachineOwnerKey : string,
@@ -201,16 +256,18 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
kMachineIDPlistKeyKey : string,
kEventLogType : string,
kEventLogPath : string,
kMailDirectory : string,
kMailDirectoryFileSizeThresholdKB : number,
kMailDirectorySizeThresholdMB : number,
kMailDirectoryEventMaxFlushTimeSec : number,
kSpoolDirectory : string,
kSpoolDirectoryFileSizeThresholdKB : number,
kSpoolDirectorySizeThresholdMB : number,
kSpoolDirectoryEventMaxFlushTimeSec : number,
kFileAccessPolicy : dictionary,
kFileAccessPolicyPlist : string,
kFileAccessBlockMessage : string,
kFileAccessPolicyUpdateIntervalSec : number,
kEnableMachineIDDecoration : number,
kEnableSysxCache : number,
kEnableForkAndExitLogging : number,
kIgnoreOtherEndpointSecurityClients : number,
kEnableDebugLogging : number,
kEnableBackwardsCompatibleContentEncoding : number,
kFCMProject : string,
kFCMEntity : string,
kFCMAPIKey : string,
@@ -221,12 +278,26 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
kMetricExtraLabels : dictionary,
kEnableAllEventUploadKey : number,
kDisableUnknownEventUploadKey : number,
kOverrideFileAccessActionKey : string,
kEntitlementsPrefixFilterKey : array,
kEntitlementsTeamIDFilterKey : array,
kEnabledProcessAnnotations : array,
};
_syncStateFilePath = syncStateFilePath;
_syncStateAccessAuthorizerBlock = syncStateAccessAuthorizer;
_defaults = [NSUserDefaults standardUserDefaults];
[_defaults addSuiteNamed:@"com.google.santa"];
_configState = [self readForcedConfig];
[self cacheStaticRules];
_syncState = [self readSyncStateFromDisk] ?: [NSMutableDictionary dictionary];
if ([self migrateDeprecatedSyncStateKeys]) {
// Save the updated sync state if any keys were migrated.
[self saveSyncStateToDisk];
}
_debugFlag = [[NSProcessInfo processInfo].arguments containsObject:@"--debug"];
[self startWatchingDefaults];
}
@@ -235,7 +306,10 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
#pragma mark Singleton retriever
+ (instancetype)configurator {
// The returned value is marked unsafe_unretained to avoid unnecessary retain/release handling.
// The object returned is guaranteed to exist for the lifetime of the process so there's no need
// to do this handling.
+ (__unsafe_unretained instancetype)configurator {
static SNTConfigurator *sharedConfigurator;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
@@ -301,6 +375,18 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingSyncEnableProtoTransfer {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingSyncExtraHeaders {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEnableCleanSyncEventUpload {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEnablePageZeroProtection {
return [self configStateSet];
}
@@ -325,6 +411,10 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingDismissText {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingUnknownBlockMessage {
return [self configStateSet];
}
@@ -381,7 +471,7 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self syncStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingSyncCleanRequired {
+ (NSSet *)keyPathsForValuesAffectingSyncTypeRequired {
return [self syncStateSet];
}
@@ -393,19 +483,35 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingMailDirectory {
+ (NSSet *)keyPathsForValuesAffectingSpoolDirectory {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingMailDirectoryFileSizeThresholdKB {
+ (NSSet *)keyPathsForValuesAffectingSpoolDirectoryFileSizeThresholdKB {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingMailDirectorySizeThresholdMB {
+ (NSSet *)keyPathsForValuesAffectingSpoolDirectorySizeThresholdMB {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingMailDirectoryEventMaxFlushTimeSec {
+ (NSSet *)keyPathsForValuesAffectingSpoolDirectoryEventMaxFlushTimeSec {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingFileAccessPolicy {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingFileAccessPolicyPlist {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingFileAccessBlockMessage {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingFileAccessPolicyUpdateIntervalSec {
return [self configStateSet];
}
@@ -425,10 +531,6 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self syncAndConfigStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEnableSysxCache {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEnableForkAndExitLogging {
return [self configStateSet];
}
@@ -441,10 +543,6 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEnableBackwardsCompatibleContentEncoding {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingFcmProject {
return [self configStateSet];
}
@@ -474,17 +572,29 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
}
+ (NSSet *)keyPathsForValuesAffectingRemountUSBMode {
return [self configStateSet];
return [self syncAndConfigStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingRemountUSBBlockMessage {
return [self syncAndConfigStateSet];
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingUsbBlockMessage {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingOverrideFileAccessActionKey {
return [self syncAndConfigStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEntitlementsPrefixFilter {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEntitlementsTeamIDFilter {
return [self configStateSet];
}
#pragma mark Public Interface
- (SNTClientMode)clientMode {
@@ -509,8 +619,7 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
- (BOOL)failClosed {
NSNumber *n = self.configState[kFailClosedKey];
if (n) return [n boolValue];
return NO;
return [n boolValue] && self.clientMode == SNTClientModeLockdown;
}
- (BOOL)enableTransitiveRules {
@@ -583,7 +692,10 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
}
- (NSArray<NSString *> *)remountUSBMode {
NSArray<NSString *> *args = self.configState[kRemountUSBModeKey];
NSArray<NSString *> *args = self.syncState[kRemountUSBModeKey];
if (!args) {
args = (NSArray<NSString *> *)self.configState[kRemountUSBModeKey];
}
for (id arg in args) {
if (![arg isKindOfClass:[NSString class]]) {
return nil;
@@ -592,6 +704,22 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return args;
}
- (SNTDeviceManagerStartupPreferences)onStartUSBOptions {
NSString *action = [self.configState[kOnStartUSBOptions] lowercaseString];
if ([action isEqualToString:@"unmount"]) {
return SNTDeviceManagerStartupPreferencesUnmount;
} else if ([action isEqualToString:@"forceunmount"]) {
return SNTDeviceManagerStartupPreferencesForceUnmount;
} else if ([action isEqualToString:@"remount"]) {
return SNTDeviceManagerStartupPreferencesRemount;
} else if ([action isEqualToString:@"forceremount"]) {
return SNTDeviceManagerStartupPreferencesForceRemount;
} else {
return SNTDeviceManagerStartupPreferencesNone;
}
}
- (NSDictionary<NSString *, SNTRule *> *)staticRules {
return self.cachedStaticRules;
}
@@ -603,10 +731,19 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return url;
}
- (BOOL)syncEnableProtoTransfer {
NSNumber *number = self.configState[kSyncEnableProtoTransfer];
return number ? [number boolValue] : NO;
}
- (NSDictionary *)syncProxyConfig {
return self.configState[kSyncProxyConfigKey];
}
- (NSDictionary *)syncExtraHeaders {
return self.configState[kSyncExtraHeadersKey];
}
- (BOOL)enablePageZeroProtection {
NSNumber *number = self.configState[kEnablePageZeroProtectionKey];
return number ? [number boolValue] : YES;
@@ -622,6 +759,11 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return number ? [number boolValue] : NO;
}
- (BOOL)enableSilentTTYMode {
NSNumber *number = self.configState[kEnableSilentTTYModeKey];
return number ? [number boolValue] : NO;
}
- (NSString *)aboutText {
return self.configState[kAboutTextKey];
}
@@ -638,6 +780,10 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return self.configState[kEventDetailTextKey];
}
- (NSString *)dismissText {
return self.configState[kDismissTextKey];
}
- (NSString *)unknownBlockMessage {
return self.configState[kUnknownBlockMessage];
}
@@ -685,6 +831,20 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return self.configState[kClientAuthCertificateIssuerKey];
}
- (SNTSyncContentEncoding)syncClientContentEncoding {
NSString *contentEncoding = [self.configState[kClientContentEncoding] lowercaseString];
if ([contentEncoding isEqualToString:@"deflate"]) {
return SNTSyncContentEncodingDeflate;
} else if ([contentEncoding isEqualToString:@"gzip"]) {
return SNTSyncContentEncodingGzip;
} else if ([contentEncoding isEqualToString:@"none"]) {
return SNTSyncContentEncodingNone;
} else {
// Ensure we have the same default zlib behavior Santa's always had otherwise.
return SNTSyncContentEncodingDeflate;
}
}
- (NSData *)syncServerAuthRootsData {
return self.configState[kServerAuthRootsDataKey];
}
@@ -710,12 +870,12 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
[self updateSyncStateForKey:kRuleSyncLastSuccess value:ruleSyncLastSuccess];
}
- (BOOL)syncCleanRequired {
return [self.syncState[kSyncCleanRequired] boolValue];
- (SNTSyncType)syncTypeRequired {
return (SNTSyncType)[self.syncState[kSyncTypeRequired] integerValue];
}
- (void)setSyncCleanRequired:(BOOL)syncCleanRequired {
[self updateSyncStateForKey:kSyncCleanRequired value:@(syncCleanRequired)];
- (void)setSyncTypeRequired:(SNTSyncType)syncTypeRequired {
[self updateSyncStateForKey:kSyncTypeRequired value:@(syncTypeRequired)];
}
- (NSString *)machineOwner {
@@ -755,6 +915,8 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return SNTEventLogTypeSyslog;
} else if ([logType isEqualToString:@"null"]) {
return SNTEventLogTypeNull;
} else if ([logType isEqualToString:@"json"]) {
return SNTEventLogTypeJSON;
} else if ([logType isEqualToString:@"file"]) {
return SNTEventLogTypeFilelog;
} else {
@@ -762,30 +924,57 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
}
}
- (NSString *)eventLogTypeRaw {
return self.configState[kEventLogType] ?: @"file";
}
- (NSString *)eventLogPath {
return self.configState[kEventLogPath] ?: @"/var/db/santa/santa.log";
}
- (NSString *)mailDirectory {
return self.configState[kMailDirectory] ?: @"/var/db/santa/mail";
- (NSString *)spoolDirectory {
return self.configState[kSpoolDirectory] ?: @"/var/db/santa/spool";
}
- (NSUInteger)mailDirectoryFileSizeThresholdKB {
return self.configState[kMailDirectoryFileSizeThresholdKB]
? [self.configState[kMailDirectoryFileSizeThresholdKB] unsignedIntegerValue]
- (NSUInteger)spoolDirectoryFileSizeThresholdKB {
return self.configState[kSpoolDirectoryFileSizeThresholdKB]
? [self.configState[kSpoolDirectoryFileSizeThresholdKB] unsignedIntegerValue]
: 250;
}
- (NSUInteger)spoolDirectorySizeThresholdMB {
return self.configState[kSpoolDirectorySizeThresholdMB]
? [self.configState[kSpoolDirectorySizeThresholdMB] unsignedIntegerValue]
: 100;
}
- (NSUInteger)mailDirectorySizeThresholdMB {
return self.configState[kMailDirectorySizeThresholdMB]
? [self.configState[kMailDirectorySizeThresholdMB] unsignedIntegerValue]
: 500;
- (float)spoolDirectoryEventMaxFlushTimeSec {
return self.configState[kSpoolDirectoryEventMaxFlushTimeSec]
? [self.configState[kSpoolDirectoryEventMaxFlushTimeSec] floatValue]
: 15.0;
}
- (float)mailDirMaxFlushTime {
return self.configState[kMailDirectoryEventMaxFlushTimeSec]
? [self.configState[kMailDirectoryEventMaxFlushTimeSec] floatValue]
: 5.0;
- (NSDictionary *)fileAccessPolicy {
return self.configState[kFileAccessPolicy];
}
- (NSString *)fileAccessPolicyPlist {
// This property is ignored when kFileAccessPolicy is set
if (self.configState[kFileAccessPolicy]) {
return nil;
} else {
return self.configState[kFileAccessPolicyPlist];
}
}
- (NSString *)fileAccessBlockMessage {
return self.configState[kFileAccessBlockMessage];
}
- (uint32_t)fileAccessPolicyUpdateIntervalSec {
return self.configState[kFileAccessPolicyUpdateIntervalSec]
? [self.configState[kFileAccessPolicyUpdateIntervalSec] unsignedIntValue]
: 60 * 10;
}
- (BOOL)enableMachineIDDecoration {
@@ -793,11 +982,6 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return number ? [number boolValue] : NO;
}
- (BOOL)enableSysxCache {
NSNumber *number = self.configState[kEnableSysxCache];
return number ? [number boolValue] : YES;
}
- (BOOL)enableCleanSyncEventUpload {
NSNumber *number = self.configState[kSyncEnableCleanSyncEventUpload];
return number ? [number boolValue] : NO;
@@ -840,11 +1024,6 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [number boolValue] || self.debugFlag;
}
- (BOOL)enableBackwardsCompatibleContentEncoding {
NSNumber *number = self.configState[kEnableBackwardsCompatibleContentEncoding];
return number ? [number boolValue] : NO;
}
- (NSString *)fcmProject {
return self.configState[kFCMProject];
}
@@ -866,8 +1045,38 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
}
- (BOOL)blockUSBMount {
NSNumber *number = self.configState[kBlockUSBMountKey];
return number ? [number boolValue] : NO;
NSNumber *n = self.syncState[kBlockUSBMountKey];
if (n) return [n boolValue];
return [self.configState[kBlockUSBMountKey] boolValue];
}
- (void)setSyncServerOverrideFileAccessAction:(NSString *)action {
NSString *a = [action lowercaseString];
if ([a isEqualToString:@"auditonly"] || [a isEqualToString:@"disable"] ||
[a isEqualToString:@"none"] || [a isEqualToString:@""]) {
[self updateSyncStateForKey:kOverrideFileAccessActionKey value:action];
}
}
- (SNTOverrideFileAccessAction)overrideFileAccessAction {
NSString *action = [self.syncState[kOverrideFileAccessActionKey] lowercaseString];
if (!action) {
action = [self.configState[kOverrideFileAccessActionKey] lowercaseString];
if (!action) {
return SNTOverrideFileAccessActionNone;
}
}
// Note: `auditonly` without an underscore is a deprecated, but still accepted form.
if ([action isEqualToString:@"audit_only"] || [action isEqualToString:@"auditonly"]) {
return SNTOverrideFileAccessActionAuditOnly;
} else if ([action isEqualToString:@"disable"]) {
return SNTOverrideFileAccessActionDiable;
} else {
return SNTOverrideFileAccessActionNone;
}
}
///
@@ -921,6 +1130,16 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return self.configState[kMetricExtraLabels];
}
- (NSArray<NSString *> *)enabledProcessAnnotations {
NSArray<NSString *> *annotations = self.configState[kEnabledProcessAnnotations];
for (id annotation in annotations) {
if (![annotation isKindOfClass:[NSString class]]) {
return nil;
}
}
return annotations;
}
#pragma mark Private
///
@@ -939,12 +1158,12 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
/// Read the saved syncState.
///
- (NSMutableDictionary *)readSyncStateFromDisk {
// Only read the sync state if a sync server is configured.
if (!self.syncBaseURL) return nil;
// Only santad should read this file.
if (geteuid() != 0) return nil;
if (!self.syncStateAccessAuthorizerBlock()) {
return nil;
}
NSMutableDictionary *syncState =
[NSMutableDictionary dictionaryWithContentsOfFile:kSyncStateFilePath];
[NSMutableDictionary dictionaryWithContentsOfFile:self.syncStateFilePath];
for (NSString *key in syncState.allKeys) {
if (self.syncServerKeyTypes[key] == [NSRegularExpression class]) {
NSString *pattern = [syncState[key] isKindOfClass:[NSString class]] ? syncState[key] : nil;
@@ -954,24 +1173,54 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
continue;
}
}
return syncState;
}
///
/// Migrate any deprecated sync state keys/values to alternative keys/values.
///
/// Returns YES if any keys were migrated. Otherwise NO.
///
- (BOOL)migrateDeprecatedSyncStateKeys {
// Currently only one key to migrate
if (!self.syncState[kSyncCleanRequiredDeprecated]) {
return NO;
}
NSMutableDictionary *syncState = self.syncState.mutableCopy;
// If the kSyncTypeRequired key exists, its current value will take precedence.
// Otherwise, migrate the old value to be compatible with the new logic.
if (!self.syncState[kSyncTypeRequired]) {
syncState[kSyncTypeRequired] = [self.syncState[kSyncCleanRequiredDeprecated] boolValue]
? @(SNTSyncTypeClean)
: @(SNTSyncTypeNormal);
}
// Delete the deprecated key
syncState[kSyncCleanRequiredDeprecated] = nil;
self.syncState = syncState;
return YES;
}
///
/// Saves the current effective syncState to disk.
///
- (void)saveSyncStateToDisk {
// Only save the sync state if a sync server is configured.
if (!self.syncBaseURL) return;
// Only santad should write to this file.
if (geteuid() != 0) return;
if (!self.syncStateAccessAuthorizerBlock()) {
return;
}
// Either remove
NSMutableDictionary *syncState = self.syncState.mutableCopy;
syncState[kAllowedPathRegexKey] = [syncState[kAllowedPathRegexKey] pattern];
syncState[kBlockedPathRegexKey] = [syncState[kBlockedPathRegexKey] pattern];
[syncState writeToFile:kSyncStateFilePath atomically:YES];
[syncState writeToFile:self.syncStateFilePath atomically:YES];
[[NSFileManager defaultManager] setAttributes:@{NSFilePosixPermissions : @0600}
ofItemAtPath:kSyncStateFilePath
ofItemAtPath:self.syncStateFilePath
error:NULL];
}
@@ -979,6 +1228,14 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
self.syncState = [NSMutableDictionary dictionary];
}
- (NSArray *)entitlementsPrefixFilter {
return EnsureArrayOfStrings(self.configState[kEntitlementsPrefixFilterKey]);
}
- (NSArray *)entitlementsTeamIDFilter {
return EnsureArrayOfStrings(self.configState[kEntitlementsTeamIDFilterKey]);
}
#pragma mark Private Defaults Methods
- (NSRegularExpression *)expressionForPattern:(NSString *)pattern {
@@ -987,6 +1244,39 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL];
}
- (void)applyOverrides:(NSMutableDictionary *)forcedConfig {
// Overrides should only be applied under debug builds.
#ifdef DEBUG
if ([[[NSProcessInfo processInfo] processName] isEqualToString:@"xctest"] &&
![[[NSProcessInfo processInfo] environment] objectForKey:@"ENABLE_CONFIG_OVERRIDES"]) {
// By default, config overrides are not applied when running tests to help
// mitigate potential issues due to unexpected config values. This behavior
// can be overriden if desired by using the env variable: `ENABLE_CONFIG_OVERRIDES`.
//
// E.g.:
// bazel test --test_env=ENABLE_CONFIG_OVERRIDES=1 ...other test args...
return;
}
NSDictionary *overrides = [NSDictionary dictionaryWithContentsOfFile:kConfigOverrideFilePath];
for (NSString *key in overrides) {
id obj = overrides[key];
if (![obj isKindOfClass:self.forcedConfigKeyTypes[key]] ||
([self.forcedConfigKeyTypes[key] isKindOfClass:[NSRegularExpression class]] &&
![obj isKindOfClass:[NSString class]])) {
continue;
}
forcedConfig[key] = obj;
if (self.forcedConfigKeyTypes[key] == [NSRegularExpression class]) {
NSString *pattern = [obj isKindOfClass:[NSString class]] ? obj : nil;
forcedConfig[key] = [self expressionForPattern:pattern];
}
}
#endif
}
- (NSMutableDictionary *)readForcedConfig {
NSMutableDictionary *forcedConfig = [NSMutableDictionary dictionary];
for (NSString *key in self.forcedConfigKeyTypes) {
@@ -998,6 +1288,9 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
forcedConfig[key] = [self expressionForPattern:pattern];
}
}
[self applyOverrides:forcedConfig];
return forcedConfig;
}
@@ -1014,12 +1307,50 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
selector:@selector(defaultsChanged:)
name:NSUserDefaultsDidChangeNotification
object:nil];
#ifdef DEBUG
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
[self watchOverridesFile];
});
#endif
}
#ifdef DEBUG
- (void)watchOverridesFile {
while (![[NSFileManager defaultManager] fileExistsAtPath:kConfigOverrideFilePath]) {
[NSThread sleepForTimeInterval:0.2];
}
[self defaultsChanged:nil];
int descriptor = open([kConfigOverrideFilePath fileSystemRepresentation], O_EVTONLY);
if (descriptor < 0) {
return;
}
dispatch_source_t source =
dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
DISPATCH_VNODE_WRITE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_DELETE,
dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
dispatch_source_set_event_handler(source, ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self defaultsChanged:nil];
});
unsigned long events = dispatch_source_get_data(source);
if ((events & DISPATCH_VNODE_DELETE) || (events & DISPATCH_VNODE_RENAME)) {
dispatch_source_cancel(source);
}
});
dispatch_source_set_cancel_handler(source, ^{
close(descriptor);
[self watchOverridesFile];
});
dispatch_resume(source);
}
#endif
- (void)defaultsChanged:(void *)v {
SEL handleChange = @selector(handleChange);
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:handleChange object:nil];
[self performSelector:handleChange withObject:nil afterDelay:5.0f];
[self performSelector:handleChange withObject:nil afterDelay:1.0f];
}
///
@@ -1042,6 +1373,7 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
for (id rule in staticRules) {
if (![rule isKindOfClass:[NSDictionary class]]) return;
SNTRule *r = [[SNTRule alloc] initWithDictionary:rule];
if (!r) continue;
rules[r.identifier] = r;
}
self.cachedStaticRules = [rules copy];

View File

@@ -0,0 +1,102 @@
/// Copyright 2024 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <Foundation/Foundation.h>
#import <XCTest/XCTest.h>
#import "Source/common/SNTCommonEnums.h"
#import "Source/common/SNTConfigurator.h"
@interface SNTConfigurator (Testing)
- (instancetype)initWithSyncStateFile:(NSString *)syncStateFilePath
syncStateAccessAuthorizer:(BOOL (^)(void))syncStateAccessAuthorizer;
@property NSDictionary *syncState;
@end
@interface SNTConfiguratorTest : XCTestCase
@property NSFileManager *fileMgr;
@property NSString *testDir;
@end
@implementation SNTConfiguratorTest
- (void)setUp {
self.fileMgr = [NSFileManager defaultManager];
self.testDir =
[NSString stringWithFormat:@"%@santa-configurator-%d", NSTemporaryDirectory(), getpid()];
XCTAssertTrue([self.fileMgr createDirectoryAtPath:self.testDir
withIntermediateDirectories:YES
attributes:nil
error:nil]);
}
- (void)tearDown {
XCTAssertTrue([self.fileMgr removeItemAtPath:self.testDir error:nil]);
}
- (void)runMigrationTestsWithSyncState:(NSDictionary *)syncStatePlist
verifier:(void (^)(SNTConfigurator *))verifierBlock {
NSString *syncStatePlistPath =
[NSString stringWithFormat:@"%@/test-sync-state.plist", self.testDir];
XCTAssertTrue([syncStatePlist writeToFile:syncStatePlistPath atomically:YES]);
SNTConfigurator *cfg = [[SNTConfigurator alloc] initWithSyncStateFile:syncStatePlistPath
syncStateAccessAuthorizer:^{
// Allow all access to the test plist
return YES;
}];
NSLog(@"sync state: %@", cfg.syncState);
verifierBlock(cfg);
XCTAssertTrue([self.fileMgr removeItemAtPath:syncStatePlistPath error:nil]);
}
- (void)testInitMigratesSyncStateKeys {
// SyncCleanRequired = YES
[self runMigrationTestsWithSyncState:@{@"SyncCleanRequired" : [NSNumber numberWithBool:YES]}
verifier:^(SNTConfigurator *cfg) {
XCTAssertEqual(cfg.syncState.count, 1);
XCTAssertNil(cfg.syncState[@"SyncCleanRequired"]);
XCTAssertNotNil(cfg.syncState[@"SyncTypeRequired"]);
XCTAssertEqual([cfg.syncState[@"SyncTypeRequired"] integerValue],
SNTSyncTypeClean);
XCTAssertEqual(cfg.syncState.count, 1);
}];
// SyncCleanRequired = NO
[self runMigrationTestsWithSyncState:@{@"SyncCleanRequired" : [NSNumber numberWithBool:NO]}
verifier:^(SNTConfigurator *cfg) {
XCTAssertEqual(cfg.syncState.count, 1);
XCTAssertNil(cfg.syncState[@"SyncCleanRequired"]);
XCTAssertNotNil(cfg.syncState[@"SyncTypeRequired"]);
XCTAssertEqual([cfg.syncState[@"SyncTypeRequired"] integerValue],
SNTSyncTypeNormal);
XCTAssertEqual(cfg.syncState.count, 1);
}];
// Empty state
[self runMigrationTestsWithSyncState:@{}
verifier:^(SNTConfigurator *cfg) {
XCTAssertEqual(cfg.syncState.count, 0);
XCTAssertNil(cfg.syncState[@"SyncCleanRequired"]);
XCTAssertNil(cfg.syncState[@"SyncTypeRequired"]);
}];
}
@end

View File

@@ -0,0 +1,27 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <Foundation/Foundation.h>
@interface NSArray (SNTDeepCopy)
- (instancetype)sntDeepCopy;
@end
@interface NSDictionary (SNTDeepCopy)
- (instancetype)sntDeepCopy;
@end

View File

@@ -0,0 +1,53 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/common/SNTDeepCopy.h"
@implementation NSArray (SNTDeepCopy)
- (instancetype)sntDeepCopy {
NSMutableArray<__kindof NSObject *> *deepCopy = [NSMutableArray arrayWithCapacity:self.count];
for (id object in self) {
if ([object respondsToSelector:@selector(sntDeepCopy)]) {
[deepCopy addObject:[object sntDeepCopy]];
} else if ([object respondsToSelector:@selector(copyWithZone:)]) {
[deepCopy addObject:[object copy]];
} else {
[deepCopy addObject:object];
}
}
return deepCopy;
}
@end
@implementation NSDictionary (SNTDeepCopy)
- (instancetype)sntDeepCopy {
NSMutableDictionary<__kindof NSObject *, __kindof NSObject *> *deepCopy =
[NSMutableDictionary dictionary];
for (id key in self) {
id value = self[key];
if ([value respondsToSelector:@selector(sntDeepCopy)]) {
deepCopy[key] = [value sntDeepCopy];
} else if ([value respondsToSelector:@selector(copyWithZone:)]) {
deepCopy[key] = [value copy];
} else {
deepCopy[key] = value;
}
}
return deepCopy;
}
@end

View File

@@ -0,0 +1,53 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <Foundation/Foundation.h>
#import "Source/common/SNTStoredEvent.h"
///
/// Represents an event stored in the database.
///
@interface SNTFileAccessEvent : SNTStoredEvent <NSSecureCoding>
///
/// The watched path that was accessed
///
@property NSString *accessedPath;
///
/// The rule version and name that were violated
///
@property NSString *ruleVersion;
@property NSString *ruleName;
///
/// If the process is part of a bundle, the name of the application
///
@property NSString *application;
///
/// A string representing the publisher based on the signingChain
///
@property(readonly) NSString *publisherInfo;
///
/// Return an array of the underlying SecCertificateRef's of the signingChain
///
/// WARNING: If the refs need to be used for a long time be careful to properly
/// CFRetain/CFRelease the returned items.
///
@property(readonly) NSArray *signingChainCertRefs;
@end

View File

@@ -0,0 +1,82 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/common/SNTFileAccessEvent.h"
#import "Source/common/CertificateHelpers.h"
@implementation SNTFileAccessEvent
#define ENCODE(o) \
do { \
if (self.o) { \
[coder encodeObject:self.o forKey:@(#o)]; \
} \
} while (0)
#define DECODE(o, c) \
do { \
_##o = [decoder decodeObjectOfClass:[c class] forKey:@(#o)]; \
} while (0)
#define DECODEARRAY(o, c) \
do { \
_##o = [decoder decodeObjectOfClasses:[NSSet setWithObjects:[NSArray class], [c class], nil] \
forKey:@(#o)]; \
} while (0)
- (instancetype)init {
self = [super init];
if (self) {
}
return self;
}
+ (BOOL)supportsSecureCoding {
return YES;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
ENCODE(accessedPath);
ENCODE(ruleVersion);
ENCODE(ruleName);
ENCODE(application);
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (self) {
DECODE(accessedPath, NSString);
DECODE(ruleVersion, NSString);
DECODE(ruleName, NSString);
DECODE(application, NSString);
}
return self;
}
- (NSString *)description {
return [NSString
stringWithFormat:@"SNTFileAccessEvent: Accessed: %@, By: %@", self.accessedPath, self.filePath];
}
- (NSString *)publisherInfo {
return Publisher(self.signingChain, self.teamID);
}
- (NSArray *)signingChainCertRefs {
return CertificateChain(self.signingChain);
}
@end

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -12,8 +12,11 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <EndpointSecurity/EndpointSecurity.h>
#import <Foundation/Foundation.h>
#import "Source/common/SantaVnode.h"
@class MOLCodesignChecker;
///
@@ -32,6 +35,14 @@
///
- (instancetype)initWithPath:(NSString *)path error:(NSError **)error;
///
/// Convenience initializer.
///
/// @param esFile Pointer to an es_file_t provided by the EndpointSecurity framework.
/// Assumes that the path is a resolved path.
///
- (instancetype)initWithEndpointSecurityFile:(const es_file_t *)esFile error:(NSError **)error;
///
/// Convenience initializer.
///
@@ -211,6 +222,11 @@
///
- (NSUInteger)fileSize;
///
/// @return The devno/ino pair of the file
///
- (SantaVnode)vnode;
///
/// @return The underlying file handle.
///

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -25,6 +25,8 @@
#include <sys/stat.h>
#include <sys/xattr.h>
#import "Source/common/SNTLogging.h"
// Simple class to hold the data of a mach_header and the offset within the file
// in which that header was found.
@interface MachHeaderWithOffset : NSObject
@@ -47,7 +49,9 @@
@property NSString *path;
@property NSFileHandle *fileHandle;
@property NSUInteger fileSize;
@property SantaVnode vnode;
@property NSString *fileOwnerHomeDir;
@property NSString *sha256Storage;
// Cached properties
@property NSBundle *bundleRef;
@@ -63,6 +67,26 @@
extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE;
- (instancetype)initWithResolvedPath:(NSString *)path error:(NSError **)error {
struct stat fileStat;
if (path.length) {
lstat(path.UTF8String, &fileStat);
}
return [self initWithResolvedPath:path stat:&fileStat error:error];
}
- (instancetype)initWithEndpointSecurityFile:(const es_file_t *)esFile error:(NSError **)error {
return [self initWithResolvedPath:@(esFile->path.data) stat:&esFile->stat error:error];
}
- (instancetype)initWithResolvedPath:(NSString *)path
stat:(const struct stat *)fileStat
error:(NSError **)error {
if (!fileStat) {
// This is a programming error. Bail.
LOGE(@"NULL stat buffer unsupported");
exit(EXIT_FAILURE);
}
self = [super init];
if (self) {
_path = path;
@@ -76,9 +100,7 @@ extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE;
return nil;
}
struct stat fileStat;
lstat(_path.UTF8String, &fileStat);
if (!((S_IFMT & fileStat.st_mode) == S_IFREG)) {
if (!((S_IFMT & fileStat->st_mode) == S_IFREG)) {
if (error) {
NSString *errStr = [NSString stringWithFormat:@"Non regular file: %s", strerror(errno)];
*error = [NSError errorWithDomain:@"com.google.santa.fileinfo"
@@ -88,12 +110,13 @@ extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE;
return nil;
}
_fileSize = fileStat.st_size;
_fileSize = fileStat->st_size;
_vnode = (SantaVnode){.fsid = fileStat->st_dev, .fileid = fileStat->st_ino};
if (_fileSize == 0) return nil;
if (fileStat.st_uid != 0) {
struct passwd *pwd = getpwuid(fileStat.st_uid);
if (fileStat->st_uid != 0) {
struct passwd *pwd = getpwuid(fileStat->st_uid);
if (pwd) {
_fileOwnerHomeDir = @(pwd->pw_dir);
}
@@ -214,9 +237,13 @@ extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE;
}
- (NSString *)SHA256 {
NSString *sha256;
[self hashSHA1:NULL SHA256:&sha256];
return sha256;
// Memoize the value
if (!self.sha256Storage) {
NSString *sha256;
[self hashSHA1:NULL SHA256:&sha256];
self.sha256Storage = sha256;
}
return self.sha256Storage;
}
#pragma mark File Type Info
@@ -396,8 +423,14 @@ extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE;
return self.infoDict;
}
d = self.bundle.infoDictionary;
if (d) {
// `-[NSBundle infoDictionary]` is heavily cached, changes to the Info.plist are not realized.
// Use `CFBundleCopyInfoDictionaryInDirectory` instead, which does not appear to cache.
NSString *bundlePath = [self bundlePath];
if (bundlePath.length) {
d = CFBridgingRelease(CFBundleCopyInfoDictionaryInDirectory(
(__bridge CFURLRef)[NSURL fileURLWithPath:bundlePath]));
}
if (d.count) {
self.infoDict = d;
return self.infoDict;
}
@@ -547,6 +580,10 @@ extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE;
NSData *cmdData = [self safeSubdataWithRange:NSMakeRange(offset, sz_segment)];
if (!cmdData) return nil;
if (((struct load_command *)[cmdData bytes])->cmdsize < sizeof(struct load_command)) {
return nil;
}
if (is64) {
struct segment_command_64 *lc = (struct segment_command_64 *)[cmdData bytes];
if (lc->cmd == LC_SEGMENT_64 && memcmp(lc->segname, "__TEXT", 6) == 0) {
@@ -617,7 +654,10 @@ extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE;
///
- (NSData *)safeSubdataWithRange:(NSRange)range {
@try {
if ((range.location + range.length) > self.fileSize) return nil;
NSUInteger size;
if (__builtin_add_overflow(range.location, range.length, &size) || size > self.fileSize) {
return nil;
}
[self.fileHandle seekToFileOffset:range.location];
NSData *d = [self.fileHandle readDataOfLength:range.length];
if (d.length != range.length) return nil;

View File

@@ -34,7 +34,12 @@
- (void)testPathStandardizing {
SNTFileInfo *sut = [[SNTFileInfo alloc] initWithPath:@"/Applications/Safari.app"];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.path, @"/Applications/Safari.app/Contents/MacOS/Safari");
if (@available(macOS 13.0, *)) {
XCTAssertEqualObjects(sut.path, @"/System/Volumes/Preboot/Cryptexes/App/System/Applications/"
@"Safari.app/Contents/MacOS/Safari");
} else {
XCTAssertEqualObjects(sut.path, @"/Applications/Safari.app/Contents/MacOS/Safari");
}
sut = [[SNTFileInfo alloc] initWithPath:@"../../../../../../../../../../../../../../../bin/ls"];
XCTAssertEqualObjects(sut.path, @"/bin/ls");
@@ -90,6 +95,11 @@
}
- (void)testKext {
// Skip this test on macOS 13 as KEXTs have moved into the kernelcache.
if (@available(macOS 13.0, *)) {
return;
}
SNTFileInfo *sut = [[SNTFileInfo alloc]
initWithPath:@"/System/Library/Extensions/AppleAPIC.kext/Contents/MacOS/AppleAPIC"];

View File

@@ -0,0 +1,34 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <Foundation/Foundation.h>
// The callback type when KVO notifications are received for observed key paths.
// The first parameter is the previous value, the second parameter is the new value.
typedef void (^KVOCallback)(id oldValue, id newValue);
@interface SNTKVOManager : NSObject
// Add an observer for the selector on the given object. When a KVO notification
// is received, the callback is called. If the notification contains objects that
// are not of the expectedType, nil is passed as the argument to the callback.
// The observer is removed when the returned instance is deallocated.
- (instancetype)initWithObject:(id)object
selector:(SEL)selector
type:(Class)expectedType
callback:(KVOCallback)callback;
- (instancetype)init NS_UNAVAILABLE;
@end

View File

@@ -0,0 +1,72 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/common/SNTKVOManager.h"
#import "Source/common/SNTLogging.h"
@interface SNTKVOManager ()
@property KVOCallback callback;
@property Class expectedType;
@property NSString *keyPath;
@property id object;
@end
@implementation SNTKVOManager
- (instancetype)initWithObject:(id)object
selector:(SEL)selector
type:(Class)expectedType
callback:(KVOCallback)callback {
self = [super self];
if (self) {
NSString *selectorName = NSStringFromSelector(selector);
if (![object respondsToSelector:selector]) {
LOGE(@"Attempt to add observer for an unknown selector (%@) for object (%@)", selectorName,
[object class]);
return nil;
}
_object = object;
_keyPath = selectorName;
_expectedType = expectedType;
_callback = callback;
[object addObserver:self
forKeyPath:selectorName
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:NULL];
}
return self;
}
- (void)dealloc {
[self.object removeObserver:self forKeyPath:self.keyPath context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSString *, id> *)change
context:(void *)context {
id oldValue = [change[NSKeyValueChangeOldKey] isKindOfClass:self.expectedType]
? change[NSKeyValueChangeOldKey]
: nil;
id newValue = [change[NSKeyValueChangeNewKey] isKindOfClass:self.expectedType]
? change[NSKeyValueChangeNewKey]
: nil;
self.callback(oldValue, newValue);
}
@end

View File

@@ -0,0 +1,129 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <XCTest/XCTest.h>
#import "Source/common/SNTKVOManager.h"
@interface Foo : NSObject
@property NSNumber *propNumber;
@property NSArray *propArray;
@property id propId;
@end
@implementation Foo
@end
@interface SNTKVOManagerTest : XCTestCase
@end
@implementation SNTKVOManagerTest
- (void)testInvalidSelector {
Foo *foo = [[Foo alloc] init];
SNTKVOManager *kvo = [[SNTKVOManager alloc] initWithObject:foo
selector:NSSelectorFromString(@"doesNotExist")
type:[NSNumber class]
callback:^(id, id){
}];
XCTAssertNil(kvo);
}
- (void)testNormalOperation {
Foo *foo = [[Foo alloc] init];
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
int origVal = 123;
int update1 = 456;
int update2 = 789;
foo.propNumber = @(origVal);
// Store the values from the callback to test against expected values
__block int oldVal;
__block int newVal;
SNTKVOManager *kvo =
[[SNTKVOManager alloc] initWithObject:foo
selector:@selector(propNumber)
type:[NSNumber class]
callback:^(NSNumber *oldValue, NSNumber *newValue) {
oldVal = [oldValue intValue];
newVal = [newValue intValue];
dispatch_semaphore_signal(sema);
}];
XCTAssertNotNil(kvo);
// Ensure an update to the observed property triggers the callback
foo.propNumber = @(update1);
XCTAssertEqual(0,
dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)),
"Failed waiting for first observable update");
XCTAssertEqual(oldVal, origVal);
XCTAssertEqual(newVal, update1);
// One more time why not
foo.propNumber = @(update2);
XCTAssertEqual(0,
dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)),
"Failed waiting for second observable update");
XCTAssertEqual(oldVal, update1);
XCTAssertEqual(newVal, update2);
}
- (void)testUnexpectedTypes {
Foo *foo = [[Foo alloc] init];
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSString *origVal = @"any_val";
NSString *update = @"new_val";
foo.propId = origVal;
__block id oldVal;
__block id newVal;
SNTKVOManager *kvo = [[SNTKVOManager alloc] initWithObject:foo
selector:@selector(propId)
type:[NSString class]
callback:^(id oldValue, id newValue) {
oldVal = oldValue;
newVal = newValue;
dispatch_semaphore_signal(sema);
}];
XCTAssertNotNil(kvo);
// Update to an unexpected type (here, NSNumber instead of NSString)
foo.propId = @(123);
XCTAssertEqual(0,
dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)),
"Failed waiting for first observable update");
XCTAssertEqualObjects(oldVal, origVal);
XCTAssertNil(newVal);
// Update again with an expected type, ensure oldVal is now nil
foo.propId = update;
XCTAssertEqual(0,
dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)),
"Failed waiting for first observable update");
XCTAssertNil(oldVal);
XCTAssertEqualObjects(newVal, update);
}
@end

View File

@@ -280,15 +280,12 @@ NSString *SNTMetricMakeStringFromMetricType(SNTMetricType metricType) {
if (_fieldNames.count == 0) {
metricDict[@"fields"][@""] = @[ [self encodeMetricValueForFieldValues:@[]] ];
} else {
for (NSString *fieldName in _fieldNames) {
NSMutableArray *fieldVals = [[NSMutableArray alloc] init];
NSMutableArray *fieldVals = [[NSMutableArray alloc] init];
for (NSArray<NSString *> *fieldValues in _metricsForFieldValues) {
[fieldVals addObject:[self encodeMetricValueForFieldValues:fieldValues]];
}
metricDict[@"fields"][fieldName] = fieldVals;
for (NSArray<NSString *> *fieldValues in _metricsForFieldValues) {
[fieldVals addObject:[self encodeMetricValueForFieldValues:fieldValues]];
}
metricDict[@"fields"][[_fieldNames componentsJoinedByString:@","]] = fieldVals;
}
return metricDict;
}
@@ -608,10 +605,15 @@ NSString *SNTMetricMakeStringFromMetricType(SNTMetricType metricType) {
/** Export current state of the SNTMetricSet as an NSDictionary. */
- (NSDictionary *)export {
NSDictionary *exported = nil;
NSDictionary *exported;
NSArray *callbacks;
@synchronized(self) {
callbacks = [_callbacks mutableCopy];
}
// Invoke callbacks to ensure metrics are up to date.
for (void (^cb)(void) in _callbacks) {
for (void (^cb)(void) in callbacks) {
cb();
}
@@ -642,20 +644,9 @@ NSString *SNTMetricStringFromMetricFormatType(SNTMetricFormatType format) {
NSDictionary *SNTMetricConvertDatesToISO8601Strings(NSDictionary *metrics) {
NSMutableDictionary *mutableMetrics = [metrics mutableCopy];
id formatter;
if (@available(macOS 10.13, *)) {
NSISO8601DateFormatter *isoFormatter = [[NSISO8601DateFormatter alloc] init];
isoFormatter.formatOptions =
NSISO8601DateFormatWithInternetDateTime | NSISO8601DateFormatWithFractionalSeconds;
formatter = isoFormatter;
} else {
NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init];
[localFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
[localFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
formatter = localFormatter;
}
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
formatter.formatOptions =
NSISO8601DateFormatWithInternetDateTime | NSISO8601DateFormatWithFractionalSeconds;
for (NSString *metricName in mutableMetrics[@"metrics"]) {
NSMutableDictionary *metric = mutableMetrics[@"metrics"][metricName];

View File

@@ -672,4 +672,35 @@
output);
}
}
- (void)testEnsureMetricsWithMultipleFieldNamesSerializeOnce {
SNTMetricSet *metricSet = [[SNTMetricSet alloc] initWithHostname:@"testHost"
username:@"testUser"];
SNTMetricCounter *c =
[metricSet counterWithName:@"/santa/events"
fieldNames:@[ @"client", @"event_type" ]
helpText:@"Count of events on the host for a given ES client"];
[c incrementBy:1 forFieldValues:@[ @"device_manager", @"auth_mount" ]];
NSDictionary *expected = @{
@"/santa/events" : @{
@"description" : @"Count of events on the host for a given ES client",
@"type" : [NSNumber numberWithInt:(int)SNTMetricTypeCounter],
@"fields" : @{
@"client,event_type" : @[
@{
@"value" : @"device_manager,auth_mount",
@"created" : [NSDate date],
@"last_updated" : [NSDate date],
@"data" : [NSNumber numberWithInt:1],
},
],
},
},
};
NSDictionary *got = [metricSet export][@"metrics"];
XCTAssertEqualObjects(expected, got, @"metrics do not match expected");
}
@end

View File

@@ -1,227 +0,0 @@
/// Copyright 2018 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include "Source/common/SNTPrefixTree.h"
#include <string.h>
#include <mutex>
#define LOGD(format, ...) // NOP
#define LOGE(format, ...) // NOP
#define lck_rw_lock_shared(l) pthread_rwlock_rdlock(&l)
#define lck_rw_unlock_shared(l) pthread_rwlock_unlock(&l)
#define lck_rw_lock_exclusive(l) pthread_rwlock_wrlock(&l)
#define lck_rw_unlock_exclusive(l) pthread_rwlock_unlock(&l)
#define lck_rw_lock_shared_to_exclusive(l) \
({ \
pthread_rwlock_unlock(&l); \
false; \
})
#define lck_rw_lock_exclusive_to_shared(l) \
({ \
pthread_rwlock_unlock(&l); \
pthread_rwlock_rdlock(&l); \
})
#define lck_mtx_lock(l) l->lock()
#define lck_mtx_unlock(l) l->unlock()
SNTPrefixTree::SNTPrefixTree(uint32_t max_nodes) {
root_ = new SantaPrefixNode();
node_count_ = 0;
max_nodes_ = max_nodes;
pthread_rwlock_init(&spt_lock_, nullptr);
spt_add_lock_ = new std::mutex;
}
IOReturn SNTPrefixTree::AddPrefix(const char *prefix, uint64_t *node_count) {
// Serialize requests to AddPrefix. Otherwise one AddPrefix thread could
// overwrite whole branches of another. HasPrefix is still free to read the
// tree, until AddPrefix needs to modify it.
lck_mtx_lock(spt_add_lock_);
// Don't allow an empty prefix.
if (prefix[0] == '\0') return kIOReturnBadArgument;
LOGD("Trying to add prefix: %s", prefix);
// Enforce max tree depth.
size_t len = strnlen(prefix, max_nodes_);
// Grab a shared lock until a new branch is required.
lck_rw_lock_shared(spt_lock_);
SantaPrefixNode *node = root_;
for (size_t i = 0; i < len; ++i) {
// If there is a node in the path that is considered a prefix, stop adding.
// For our purposes we only care about the shortest path that matches.
if (node->isPrefix) break;
// Only process a byte at a time.
uint8_t value = (uint8_t)prefix[i];
// Create the child if it does not exist.
if (!node->children[value]) {
// Upgrade the shared lock.
// If the upgrade fails, the shared lock is released.
if (!lck_rw_lock_shared_to_exclusive(spt_lock_)) {
// Grab a new exclusive lock.
lck_rw_lock_exclusive(spt_lock_);
}
// Is there enough room for the rest of the prefix?
if ((node_count_ + (len - i)) > max_nodes_) {
LOGE("Prefix tree is full, can not add: %s", prefix);
if (node_count) *node_count = node_count_;
lck_rw_unlock_exclusive(spt_lock_);
lck_mtx_unlock(spt_add_lock_);
return kIOReturnNoResources;
}
// Create the rest of the prefix.
while (i < len) {
value = (uint8_t)prefix[i++];
SantaPrefixNode *new_node = new SantaPrefixNode();
node->children[value] = new_node;
++node_count_;
node = new_node;
}
// This is the end, mark the node as a prefix.
LOGD("Added prefix: %s", prefix);
node->isPrefix = true;
// Downgrade the exclusive lock
lck_rw_lock_exclusive_to_shared(spt_lock_);
} else if (i + 1 == len) {
// If the child does exist and it is the end...
// Set the new, higher prefix and prune the now dead nodes.
if (!lck_rw_lock_shared_to_exclusive(spt_lock_)) {
lck_rw_lock_exclusive(spt_lock_);
}
PruneNode(node->children[value]);
SantaPrefixNode *new_node = new SantaPrefixNode();
new_node->isPrefix = true;
node->children[value] = new_node;
++node_count_;
LOGD("Added prefix: %s", prefix);
lck_rw_lock_exclusive_to_shared(spt_lock_);
}
// Get ready for the next iteration.
node = node->children[value];
}
if (node_count) *node_count = node_count_;
lck_rw_unlock_shared(spt_lock_);
lck_mtx_unlock(spt_add_lock_);
return kIOReturnSuccess;
}
bool SNTPrefixTree::HasPrefix(const char *string) {
lck_rw_lock_shared(spt_lock_);
auto found = false;
SantaPrefixNode *node = root_;
// A well formed tree will always break this loop. Even if string doesn't
// terminate.
const char *p = string;
while (*p) {
// Only process a byte at a time.
node = node->children[(uint8_t)*p++];
// If it doesn't exist in the tree, no match.
if (!node) break;
// If it does exist, is it a prefix?
if (node->isPrefix) {
found = true;
break;
}
}
lck_rw_unlock_shared(spt_lock_);
return found;
}
void SNTPrefixTree::Reset() {
lck_rw_lock_exclusive(spt_lock_);
PruneNode(root_);
root_ = new SantaPrefixNode();
node_count_ = 0;
lck_rw_unlock_exclusive(spt_lock_);
}
void SNTPrefixTree::PruneNode(SantaPrefixNode *target) {
if (!target) return;
// For deep trees, a recursive approach will generate too many stack frames.
// Make a "stack" and walk the tree.
auto stack = new SantaPrefixNode *[node_count_ + 1];
if (!stack) {
LOGE("Unable to prune tree!");
return;
}
auto count = 0;
// Seed the "stack" with a starting node.
stack[count++] = target;
// Start at the target node and walk the tree to find and delete all the
// sub-nodes.
while (count) {
auto node = stack[--count];
for (int i = 0; i < 256; ++i) {
if (!node->children[i]) continue;
stack[count++] = node->children[i];
}
delete node;
--node_count_;
}
delete[] stack;
}
SNTPrefixTree::~SNTPrefixTree() {
lck_rw_lock_exclusive(spt_lock_);
PruneNode(root_);
root_ = nullptr;
lck_rw_unlock_exclusive(spt_lock_);
pthread_rwlock_destroy(&spt_lock_);
}

View File

@@ -1,91 +0,0 @@
/// Copyright 2018 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__SANTA_DRIVER__SANTAPREFIXTREE_H
#define SANTA__SANTA_DRIVER__SANTAPREFIXTREE_H
#include <IOKit/IOReturn.h>
#include <sys/param.h>
// Support for unit testing.
#include <pthread.h>
#include <stdint.h>
#include <mutex>
///
/// SantaPrefixTree is a simple prefix tree implementation.
/// Operations are thread safe.
///
class SNTPrefixTree {
public:
// Add a prefix to the tree.
// Optionally pass node_count to get the number of nodes after the add.
IOReturn AddPrefix(const char *, uint64_t *node_count = nullptr);
// Check if the tree has a prefix for string.
bool HasPrefix(const char *string);
// Reset the tree.
void Reset();
SNTPrefixTree(uint32_t max_nodes = kDefaultMaxNodes);
~SNTPrefixTree();
private:
///
/// SantaPrefixNode is a wrapper class that represents one byte.
/// 1 node can represent a whole ASCII character.
/// For example a pointer to the 'A' node will be stored at children[0x41].
/// It takes 1-4 nodes to represent a UTF-8 encoded Unicode character.
///
/// The path for "/🤘" would look like this:
/// children[0x2f] -> children[0xf0] -> children[0x9f] -> children[0xa4]
/// -> children[0x98]
///
/// The path for "/dev" is:
/// children[0x2f] -> children[0x64] -> children[0x65] -> children[0x76]
///
/// Lookups of children are O(1).
///
/// Having the nodes represented by a smaller width, such as a nibble (1/2
/// byte), would drastically decrease the memory footprint but would double
/// required dereferences.
///
/// TODO(bur): Potentially convert this into a full on radix tree.
///
class SantaPrefixNode {
public:
bool isPrefix;
SantaPrefixNode *children[256];
};
// PruneNode will remove the passed in node from the tree.
// The passed in node and all subnodes will be deleted.
// It is the caller's responsibility to reset the pointer to this node (held
// by the parent). If the tree is in use grab the exclusive lock.
void PruneNode(SantaPrefixNode *);
SantaPrefixNode *root_;
// Each node takes up ~2k, assuming MAXPATHLEN is 1024 max out at ~2MB.
static const uint32_t kDefaultMaxNodes = MAXPATHLEN;
uint32_t max_nodes_;
uint32_t node_count_;
pthread_rwlock_t spt_lock_;
std::mutex *spt_add_lock_;
};
#endif /* SANTA__SANTA_DRIVER__SANTAPREFIXTREE_H */

View File

@@ -1,73 +0,0 @@
/// Copyright 2018 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <XCTest/XCTest.h>
#include "Source/common/SNTPrefixTree.h"
@interface SNTPrefixTreeTest : XCTestCase
@end
@implementation SNTPrefixTreeTest
- (void)testAddAndHas {
auto t = SNTPrefixTree();
XCTAssertFalse(t.HasPrefix("/private/var/tmp/file1"));
t.AddPrefix("/private/var/tmp/");
XCTAssertTrue(t.HasPrefix("/private/var/tmp/file1"));
}
- (void)testReset {
auto t = SNTPrefixTree();
t.AddPrefix("/private/var/tmp/");
XCTAssertTrue(t.HasPrefix("/private/var/tmp/file1"));
t.Reset();
XCTAssertFalse(t.HasPrefix("/private/var/tmp/file1"));
}
- (void)testThreading {
uint32_t count = 4096;
auto t = new SNTPrefixTree(count * (uint32_t)[NSUUID UUID].UUIDString.length);
NSMutableArray *UUIDs = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count; ++i) {
[UUIDs addObject:[NSUUID UUID].UUIDString];
}
__block BOOL stop = NO;
// Create a bunch of background noise.
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (uint64_t i = 0; i < UINT64_MAX; ++i) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
t->HasPrefix([UUIDs[i % count] UTF8String]);
});
if (stop) return;
}
});
// Fill up the tree.
dispatch_apply(count, dispatch_get_global_queue(0, 0), ^(size_t i) {
XCTAssertEqual(t->AddPrefix([UUIDs[i] UTF8String]), kIOReturnSuccess);
});
// Make sure every leaf byte is found.
dispatch_apply(count, dispatch_get_global_queue(0, 0), ^(size_t i) {
XCTAssertTrue(t->HasPrefix([UUIDs[i] UTF8String]));
});
stop = YES;
}
@end

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -41,6 +41,11 @@
///
@property(copy) NSString *customMsg;
///
/// A custom URL to take the user to when this binary is blocked from executing.
///
@property(copy) NSString *customURL;
///
/// The time when this rule was last retrieved from the rules database, if rule is transitive.
/// Stored as number of seconds since 00:00:00 UTC on 1 January 2001.
@@ -51,18 +56,18 @@
/// Designated initializer.
///
- (instancetype)initWithIdentifier:(NSString *)identifier
state:(SNTRuleState)state
type:(SNTRuleType)type
customMsg:(NSString *)customMsg
timestamp:(NSUInteger)timestamp;
state:(SNTRuleState)state
type:(SNTRuleType)type
customMsg:(NSString *)customMsg
timestamp:(NSUInteger)timestamp;
///
/// Initialize with a default timestamp: current time if rule state is transitive, 0 otherwise.
///
- (instancetype)initWithIdentifier:(NSString *)identifier
state:(SNTRuleState)state
type:(SNTRuleType)type
customMsg:(NSString *)customMsg;
state:(SNTRuleState)state
type:(SNTRuleType)type
customMsg:(NSString *)customMsg;
///
/// Initialize with a dictionary received from a sync server.
@@ -74,4 +79,9 @@
///
- (void)resetTimestamp;
///
/// Returns a dictionary representation of the rule.
///
- (NSDictionary *)dictionaryRepresentation;
@end

View File

@@ -13,8 +13,16 @@
/// limitations under the License.
#import "Source/common/SNTRule.h"
#include <CommonCrypto/CommonCrypto.h>
#include <Kernel/kern/cs_blobs.h>
#include <os/base.h>
#import "Source/common/SNTSyncConstants.h"
// https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/
static const NSUInteger kExpectedTeamIDLength = 10;
@interface SNTRule ()
@property(readwrite) NSUInteger timestamp;
@end
@@ -28,6 +36,87 @@
timestamp:(NSUInteger)timestamp {
self = [super init];
if (self) {
if (identifier.length == 0) {
return nil;
}
NSCharacterSet *nonHex =
[[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"] invertedSet];
NSCharacterSet *nonUppercaseAlphaNumeric = [[NSCharacterSet
characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"] invertedSet];
switch (type) {
case SNTRuleTypeBinary: OS_FALLTHROUGH;
case SNTRuleTypeCertificate: {
// For binary and certificate rules, force the hash identifier to be lowercase hex.
identifier = [identifier lowercaseString];
identifier = [identifier stringByTrimmingCharactersInSet:nonHex];
if (identifier.length != (CC_SHA256_DIGEST_LENGTH * 2)) {
return nil;
}
break;
}
case SNTRuleTypeTeamID: {
// TeamIDs are always [0-9A-Z], so enforce that the identifier is uppercase
identifier =
[[identifier uppercaseString] stringByTrimmingCharactersInSet:nonUppercaseAlphaNumeric];
if (identifier.length != kExpectedTeamIDLength) {
return nil;
}
break;
}
case SNTRuleTypeSigningID: {
// SigningID rules are a combination of `TeamID:SigningID`. The TeamID should
// be forced to be uppercase, but because very loose rules exist for SigningIDs,
// their case will be kept as-is. However, platform binaries are expected to
// have the hardcoded string "platform" as the team ID and the case will be left
// as is.
NSArray *sidComponents = [identifier componentsSeparatedByString:@":"];
if (!sidComponents || sidComponents.count < 2) {
return nil;
}
// The first component is the TeamID
NSString *teamID = sidComponents[0];
if (![teamID isEqualToString:@"platform"]) {
teamID =
[[teamID uppercaseString] stringByTrimmingCharactersInSet:nonUppercaseAlphaNumeric];
if (teamID.length != kExpectedTeamIDLength) {
return nil;
}
}
// The rest of the components are the Signing ID since ":" a legal character.
// Join all but the last element of the components to rebuild the SigningID.
NSString *signingID = [[sidComponents
subarrayWithRange:NSMakeRange(1, sidComponents.count - 1)] componentsJoinedByString:@":"];
if (signingID.length == 0) {
return nil;
}
identifier = [NSString stringWithFormat:@"%@:%@", teamID, signingID];
break;
}
case SNTRuleTypeCDHash: {
identifier = [[identifier lowercaseString] stringByTrimmingCharactersInSet:nonHex];
if (identifier.length != CS_CDHASH_LEN * 2) {
return nil;
}
break;
}
default: {
break;
}
}
_identifier = identifier;
_state = state;
_type = type;
@@ -55,52 +144,63 @@
- (instancetype)initWithDictionary:(NSDictionary *)dict {
if (![dict isKindOfClass:[NSDictionary class]]) return nil;
self = [super init];
if (self) {
_identifier = dict[kRuleIdentifier];
if (![_identifier isKindOfClass:[NSString class]] || !_identifier.length) {
_identifier = dict[kRuleSHA256];
}
if (![_identifier isKindOfClass:[NSString class]] || !_identifier.length) return nil;
NSString *policyString = dict[kRulePolicy];
if (![policyString isKindOfClass:[NSString class]]) return nil;
if ([policyString isEqual:kRulePolicyAllowlist] ||
[policyString isEqual:kRulePolicyAllowlistDeprecated]) {
_state = SNTRuleStateAllow;
} else if ([policyString isEqual:kRulePolicyAllowlistCompiler] ||
[policyString isEqual:kRulePolicyAllowlistCompilerDeprecated]) {
_state = SNTRuleStateAllowCompiler;
} else if ([policyString isEqual:kRulePolicyBlocklist] ||
[policyString isEqual:kRulePolicyBlocklistDeprecated]) {
_state = SNTRuleStateBlock;
} else if ([policyString isEqual:kRulePolicySilentBlocklist] ||
[policyString isEqual:kRulePolicySilentBlocklistDeprecated]) {
_state = SNTRuleStateSilentBlock;
} else if ([policyString isEqual:kRulePolicyRemove]) {
_state = SNTRuleStateRemove;
} else {
return nil;
}
NSString *ruleTypeString = dict[kRuleType];
if (![ruleTypeString isKindOfClass:[NSString class]]) return nil;
if ([ruleTypeString isEqual:kRuleTypeBinary]) {
_type = SNTRuleTypeBinary;
} else if ([ruleTypeString isEqual:kRuleTypeCertificate]) {
_type = SNTRuleTypeCertificate;
} else if ([ruleTypeString isEqual:kRuleTypeTeamID]) {
_type = SNTRuleTypeTeamID;
} else {
return nil;
}
NSString *customMsg = dict[kRuleCustomMsg];
if ([customMsg isKindOfClass:[NSString class]] && customMsg.length) {
_customMsg = customMsg;
}
NSString *identifier = dict[kRuleIdentifier];
if (![identifier isKindOfClass:[NSString class]] || !identifier.length) {
identifier = dict[kRuleSHA256];
}
return self;
if (![identifier isKindOfClass:[NSString class]] || !identifier.length) return nil;
NSString *policyString = dict[kRulePolicy];
SNTRuleState state;
if (![policyString isKindOfClass:[NSString class]]) return nil;
if ([policyString isEqual:kRulePolicyAllowlist] ||
[policyString isEqual:kRulePolicyAllowlistDeprecated]) {
state = SNTRuleStateAllow;
} else if ([policyString isEqual:kRulePolicyAllowlistCompiler] ||
[policyString isEqual:kRulePolicyAllowlistCompilerDeprecated]) {
state = SNTRuleStateAllowCompiler;
} else if ([policyString isEqual:kRulePolicyBlocklist] ||
[policyString isEqual:kRulePolicyBlocklistDeprecated]) {
state = SNTRuleStateBlock;
} else if ([policyString isEqual:kRulePolicySilentBlocklist] ||
[policyString isEqual:kRulePolicySilentBlocklistDeprecated]) {
state = SNTRuleStateSilentBlock;
} else if ([policyString isEqual:kRulePolicyRemove]) {
state = SNTRuleStateRemove;
} else {
return nil;
}
NSString *ruleTypeString = dict[kRuleType];
SNTRuleType type;
if (![ruleTypeString isKindOfClass:[NSString class]]) return nil;
if ([ruleTypeString isEqual:kRuleTypeBinary]) {
type = SNTRuleTypeBinary;
} else if ([ruleTypeString isEqual:kRuleTypeCertificate]) {
type = SNTRuleTypeCertificate;
} else if ([ruleTypeString isEqual:kRuleTypeTeamID]) {
type = SNTRuleTypeTeamID;
} else if ([ruleTypeString isEqual:kRuleTypeSigningID]) {
type = SNTRuleTypeSigningID;
} else if ([ruleTypeString isEqual:kRuleTypeCDHash]) {
type = SNTRuleTypeCDHash;
} else {
return nil;
}
NSString *customMsg = dict[kRuleCustomMsg];
if (![customMsg isKindOfClass:[NSString class]] || customMsg.length == 0) {
customMsg = nil;
}
NSString *customURL = dict[kRuleCustomURL];
if (![customURL isKindOfClass:[NSString class]] || customURL.length == 0) {
customURL = nil;
}
SNTRule *r = [self initWithIdentifier:identifier state:state type:type customMsg:customMsg];
r.customURL = customURL;
return r;
}
#pragma mark NSSecureCoding
@@ -120,6 +220,7 @@
ENCODE(@(self.state), @"state");
ENCODE(@(self.type), @"type");
ENCODE(self.customMsg, @"custommsg");
ENCODE(self.customURL, @"customurl");
ENCODE(@(self.timestamp), @"timestamp");
}
@@ -130,11 +231,49 @@
_state = [DECODE(NSNumber, @"state") intValue];
_type = [DECODE(NSNumber, @"type") intValue];
_customMsg = DECODE(NSString, @"custommsg");
_customURL = DECODE(NSString, @"customurl");
_timestamp = [DECODE(NSNumber, @"timestamp") unsignedIntegerValue];
}
return self;
}
- (NSString *)ruleStateToPolicyString:(SNTRuleState)state {
switch (state) {
case SNTRuleStateAllow: return kRulePolicyAllowlist;
case SNTRuleStateAllowCompiler: return kRulePolicyAllowlistCompiler;
case SNTRuleStateBlock: return kRulePolicyBlocklist;
case SNTRuleStateSilentBlock: return kRulePolicySilentBlocklist;
case SNTRuleStateRemove: return kRulePolicyRemove;
case SNTRuleStateAllowTransitive: return @"AllowTransitive";
// This should never be hit. But is here for completion.
default: return @"Unknown";
}
}
- (NSString *)ruleTypeToString:(SNTRuleType)ruleType {
switch (ruleType) {
case SNTRuleTypeBinary: return kRuleTypeBinary;
case SNTRuleTypeCertificate: return kRuleTypeCertificate;
case SNTRuleTypeTeamID: return kRuleTypeTeamID;
case SNTRuleTypeSigningID: return kRuleTypeSigningID;
// This should never be hit. If we have rule types of Unknown then there's a
// coding error somewhere.
default: return @"Unknown";
}
}
// Returns an NSDictionary representation of the rule. Primarily use for
// exporting rules.
- (NSDictionary *)dictionaryRepresentation {
return @{
kRuleIdentifier : self.identifier,
kRulePolicy : [self ruleStateToPolicyString:self.state],
kRuleType : [self ruleTypeToString:self.type],
kRuleCustomMsg : self.customMsg ?: @"",
kRuleCustomURL : self.customURL ?: @""
};
}
#undef DECODE
#undef ENCODE
#pragma clang diagnostic pop

View File

@@ -0,0 +1,51 @@
/// Copyright 2024 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/**
* This file declares two types that are mirrors of each other.
*
* The C struct serves as a way to group and pass valid rule identifiers around
* in order to minimize interface changes needed when new rule types are added
* and also alleviate the need to allocate a short lived object.
*
* The Objective C class is used for an XPC boundary to easily pass rule
* identifiers between Santa components.
*/
#import <Foundation/Foundation.h>
struct RuleIdentifiers {
NSString *cdhash;
NSString *binarySHA256;
NSString *signingID;
NSString *certificateSHA256;
NSString *teamID;
};
@interface SNTRuleIdentifiers : NSObject <NSSecureCoding>
@property(readonly) NSString *cdhash;
@property(readonly) NSString *binarySHA256;
@property(readonly) NSString *signingID;
@property(readonly) NSString *certificateSHA256;
@property(readonly) NSString *teamID;
/// Please use `initWithRuleIdentifiers:`
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithRuleIdentifiers:(struct RuleIdentifiers)identifiers
NS_DESIGNATED_INITIALIZER;
- (struct RuleIdentifiers)toStruct;
@end

View File

@@ -0,0 +1,73 @@
/// Copyright 2024 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/common/SNTRuleIdentifiers.h"
@implementation SNTRuleIdentifiers
- (instancetype)initWithRuleIdentifiers:(struct RuleIdentifiers)identifiers {
self = [super init];
if (self) {
_cdhash = identifiers.cdhash;
_binarySHA256 = identifiers.binarySHA256;
_signingID = identifiers.signingID;
_certificateSHA256 = identifiers.certificateSHA256;
_teamID = identifiers.teamID;
}
return self;
}
- (struct RuleIdentifiers)toStruct {
return (struct RuleIdentifiers){.cdhash = self.cdhash,
.binarySHA256 = self.binarySHA256,
.signingID = self.signingID,
.certificateSHA256 = self.certificateSHA256,
.teamID = self.teamID};
}
#pragma mark NSSecureCoding
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-literal-conversion"
#define ENCODE(obj, key) \
if (obj) [coder encodeObject:obj forKey:key]
#define DECODE(cls, key) [decoder decodeObjectOfClass:[cls class] forKey:key]
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [self init];
if (self) {
_cdhash = DECODE(NSString, @"cdhash");
_binarySHA256 = DECODE(NSString, @"binarySHA256");
_signingID = DECODE(NSString, @"signingID");
_certificateSHA256 = DECODE(NSString, @"certificateSHA256");
_teamID = DECODE(NSString, @"teamID");
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
ENCODE(self.cdhash, @"cdhash");
ENCODE(self.binarySHA256, @"binarySHA256");
ENCODE(self.signingID, @"signingID");
ENCODE(self.certificateSHA256, @"certificateSHA256");
ENCODE(self.teamID, @"teamID");
}
#pragma clang diagnostic pop
@end

View File

@@ -14,6 +14,9 @@
#import <XCTest/XCTest.h>
#import "Source/common/SNTCommonEnums.h"
#import "Source/common/SNTSyncConstants.h"
#import "Source/common/SNTRule.h"
@interface SNTRuleTest : XCTestCase
@@ -25,66 +28,169 @@
SNTRule *sut;
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"some-sort-of-identifier",
@"identifier" : @"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"BINARY",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqualObjects(sut.identifier,
@"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670");
XCTAssertEqual(sut.type, SNTRuleTypeBinary);
XCTAssertEqual(sut.state, SNTRuleStateAllow);
sut = [[SNTRule alloc] initWithDictionary:@{
@"sha256" : @"some-sort-of-identifier",
@"sha256" : @"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670",
@"policy" : @"BLOCKLIST",
@"rule_type" : @"CERTIFICATE",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqualObjects(sut.identifier,
@"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670");
XCTAssertEqual(sut.type, SNTRuleTypeCertificate);
XCTAssertEqual(sut.state, SNTRuleStateBlock);
// Ensure a Binary and Certificate rules properly convert identifiers to lowercase.
for (NSString *ruleType in @[ @"BINARY", @"CERTIFICATE" ]) {
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"B7C1E3FD640C5F211C89B02C2C6122F78CE322AA5C56EB0BB54BC422A8F8B670",
@"policy" : @"BLOCKLIST",
@"rule_type" : ruleType,
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier,
@"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670");
}
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"some-sort-of-identifier",
@"identifier" : @"ABCDEFGHIJ",
@"policy" : @"SILENT_BLOCKLIST",
@"rule_type" : @"TEAMID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqualObjects(sut.identifier, @"ABCDEFGHIJ");
XCTAssertEqual(sut.type, SNTRuleTypeTeamID);
XCTAssertEqual(sut.state, SNTRuleStateSilentBlock);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"some-sort-of-identifier",
@"identifier" : @"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670",
@"policy" : @"ALLOWLIST_COMPILER",
@"rule_type" : @"BINARY",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqualObjects(sut.identifier,
@"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670");
XCTAssertEqual(sut.type, SNTRuleTypeBinary);
XCTAssertEqual(sut.state, SNTRuleStateAllowCompiler);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"some-sort-of-identifier",
@"identifier" : @"ABCDEFGHIJ",
@"policy" : @"REMOVE",
@"rule_type" : @"TEAMID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqualObjects(sut.identifier, @"ABCDEFGHIJ");
XCTAssertEqual(sut.type, SNTRuleTypeTeamID);
XCTAssertEqual(sut.state, SNTRuleStateRemove);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"some-sort-of-identifier",
@"identifier" : @"ABCDEFGHIJ",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"TEAMID",
@"custom_msg" : @"A custom block message",
@"custom_url" : @"https://example.com",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqualObjects(sut.identifier, @"ABCDEFGHIJ");
XCTAssertEqual(sut.type, SNTRuleTypeTeamID);
XCTAssertEqual(sut.state, SNTRuleStateAllow);
XCTAssertEqualObjects(sut.customMsg, @"A custom block message");
XCTAssertEqualObjects(sut.customURL, @"https://example.com");
// TeamIDs must be 10 chars in length
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"A",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"TEAMID",
}];
XCTAssertNil(sut);
// TeamIDs must be only alphanumeric chars
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"ßßßßßßßßßß",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"TEAMID",
}];
XCTAssertNil(sut);
// TeamIDs are converted to uppercase
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"abcdefghij",
@"policy" : @"REMOVE",
@"rule_type" : @"TEAMID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"ABCDEFGHIJ");
// SigningID tests
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"ABCDEFGHIJ:com.example",
@"policy" : @"REMOVE",
@"rule_type" : @"SIGNINGID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"ABCDEFGHIJ:com.example");
XCTAssertEqual(sut.type, SNTRuleTypeSigningID);
XCTAssertEqual(sut.state, SNTRuleStateRemove);
// Invalid SingingID tests:
for (NSString *ident in @[
@":com.example", // missing team ID
@"ABCDEFGHIJ:", // missing signing ID
@"ABC:com.example", // Invalid team id
@":", // missing team and signing IDs
@"", // empty string
]) {
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : ident,
@"policy" : @"REMOVE",
@"rule_type" : @"SIGNINGID",
}];
XCTAssertNil(sut);
}
// Signing ID with lower team ID has case fixed up
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"abcdefghij:com.example",
@"policy" : @"REMOVE",
@"rule_type" : @"SIGNINGID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"ABCDEFGHIJ:com.example");
// Signing ID with lower platform team ID is left alone
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"platform:com.example",
@"policy" : @"REMOVE",
@"rule_type" : @"SIGNINGID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"platform:com.example");
// Signing ID can contain the TID:SID delimiter character (":")
for (NSString *ident in @[
@"ABCDEFGHIJ:com:",
@"ABCDEFGHIJ:com:example",
@"ABCDEFGHIJ::",
@"ABCDEFGHIJ:com:example:with:more:components:",
]) {
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : ident,
@"policy" : @"ALLOWLIST",
@"rule_type" : @"SIGNINGID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, ident);
}
}
- (void)testInitWithDictionaryInvalid {
@@ -94,12 +200,19 @@
XCTAssertNil(sut);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"an-identifier",
@"identifier" : @"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670",
}];
XCTAssertNil(sut);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"an-identifier",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"BINARY",
}];
XCTAssertNil(sut);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670",
@"policy" : @"OTHERPOLICY",
@"rule_type" : @"BINARY",
}];
@@ -113,4 +226,63 @@
XCTAssertNil(sut);
}
- (void)testRuleDictionaryRepresentation {
NSDictionary *expectedTeamID = @{
@"identifier" : @"ABCDEFGHIJ",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"TEAMID",
@"custom_msg" : @"A custom block message",
@"custom_url" : @"https://example.com",
};
SNTRule *sut = [[SNTRule alloc] initWithDictionary:expectedTeamID];
NSDictionary *dict = [sut dictionaryRepresentation];
XCTAssertEqualObjects(expectedTeamID, dict);
NSDictionary *expectedBinary = @{
@"identifier" : @"84de9c61777ca36b13228e2446d53e966096e78db7a72c632b5c185b2ffe68a6",
@"policy" : @"BLOCKLIST",
@"rule_type" : @"BINARY",
@"custom_msg" : @"",
@"custom_url" : @"",
};
sut = [[SNTRule alloc] initWithDictionary:expectedBinary];
dict = [sut dictionaryRepresentation];
XCTAssertEqualObjects(expectedBinary, dict);
}
- (void)testRuleStateToPolicyString {
NSDictionary *expected = @{
@"identifier" : @"84de9c61777ca36b13228e2446d53e966096e78db7a72c632b5c185b2ffe68a6",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"BINARY",
@"custom_msg" : @"A custom block message",
@"custom_url" : @"https://example.com",
};
SNTRule *sut = [[SNTRule alloc] initWithDictionary:expected];
sut.state = SNTRuleStateBlock;
XCTAssertEqualObjects(kRulePolicyBlocklist, [sut dictionaryRepresentation][kRulePolicy]);
sut.state = SNTRuleStateSilentBlock;
XCTAssertEqualObjects(kRulePolicySilentBlocklist, [sut dictionaryRepresentation][kRulePolicy]);
sut.state = SNTRuleStateAllow;
XCTAssertEqualObjects(kRulePolicyAllowlist, [sut dictionaryRepresentation][kRulePolicy]);
sut.state = SNTRuleStateAllowCompiler;
XCTAssertEqualObjects(kRulePolicyAllowlistCompiler, [sut dictionaryRepresentation][kRulePolicy]);
// Invalid states
sut.state = SNTRuleStateRemove;
XCTAssertEqualObjects(kRulePolicyRemove, [sut dictionaryRepresentation][kRulePolicy]);
}
/*
- (void)testRuleTypeToString {
SNTRule *sut = [[SNTRule alloc] init];
XCTAssertEqual(kRuleTypeBinary, [sut ruleTypeToString:@""]);//SNTRuleTypeBinary]);
XCTAssertEqual(kRuleTypeCertificate,[sut ruleTypeToString:SNTRuleTypeCertificate]);
XCTAssertEqual(kRuleTypeTeamID, [sut ruleTypeToString:SNTRuleTypeTeamID]);
XCTAssertEqual(kRuleTypeSigningID,[sut ruleTypeToString:SNTRuleTypeSigningID]);
}*/
@end

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -95,12 +95,21 @@
///
@property NSArray *signingChain;
///
/// If the executed file was signed, this is the Team ID if present in the signature information.
///
@property NSString *teamID;
///
/// If the executed file was signed, this is the Signing ID if present in the signature information.
///
@property NSString *signingID;
///
/// If the executed file was signed, this is the CDHash of the binary.
///
@property NSString *cdhash;
///
/// The user who executed the binary.
///

View File

@@ -50,6 +50,8 @@
ENCODE(self.signingChain, @"signingChain");
ENCODE(self.teamID, @"teamID");
ENCODE(self.signingID, @"signingID");
ENCODE(self.cdhash, @"cdhash");
ENCODE(self.executingUser, @"executingUser");
ENCODE(self.occurrenceDate, @"occurrenceDate");
@@ -95,10 +97,12 @@
_signingChain = DECODEARRAY(MOLCertificate, @"signingChain");
_teamID = DECODE(NSString, @"teamID");
_signingID = DECODE(NSString, @"signingID");
_cdhash = DECODE(NSString, @"cdhash");
_executingUser = DECODE(NSString, @"executingUser");
_occurrenceDate = DECODE(NSDate, @"occurrenceDate");
_decision = (SNTEventState)[DECODE(NSNumber, @"decision") intValue];
_decision = (SNTEventState)[DECODE(NSNumber, @"decision") unsignedLongLongValue];
_pid = DECODE(NSNumber, @"pid");
_ppid = DECODE(NSNumber, @"ppid");
_parentName = DECODE(NSString, @"parentName");

View File

@@ -1,4 +1,4 @@
/// Copyright 2016 Google Inc. All rights reserved.
/// Copyright 2016-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -12,10 +12,14 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#define STRONGIFY(var) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
__strong __typeof(var) var = (Weak_##var); \
// clang-format off
#define STRONGIFY(var) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
__strong __typeof(var) var = (Weak_##var); \
_Pragma("clang diagnostic pop")
#define WEAKIFY(var) __weak __typeof(var) Weak_##var = (var);
// clang-format on

View File

@@ -14,7 +14,8 @@
#import <Foundation/Foundation.h>
extern NSString *const kXSRFToken;
extern NSString *const kDefaultXSRFTokenHeader;
extern NSString *const kXSRFTokenHeader;
extern NSString *const kSerialNumber;
extern NSString *const kHostname;
@@ -31,7 +32,8 @@ extern NSString *const kClientModeMonitor;
extern NSString *const kClientModeLockdown;
extern NSString *const kBlockUSBMount;
extern NSString *const kRemountUSBMode;
extern NSString *const kCleanSync;
extern NSString *const kCleanSyncDeprecated;
extern NSString *const kSyncType;
extern NSString *const kAllowedPathRegex;
extern NSString *const kAllowedPathRegexDeprecated;
extern NSString *const kBlockedPathRegex;
@@ -41,6 +43,8 @@ extern NSString *const kCertificateRuleCount;
extern NSString *const kCompilerRuleCount;
extern NSString *const kTransitiveRuleCount;
extern NSString *const kTeamIDRuleCount;
extern NSString *const kSigningIDRuleCount;
extern NSString *const kCDHashRuleCount;
extern NSString *const kFullSyncInterval;
extern NSString *const kFCMToken;
extern NSString *const kFCMFullSyncInterval;
@@ -52,6 +56,7 @@ extern NSString *const kEnableTransitiveRulesDeprecated;
extern NSString *const kEnableTransitiveRulesSuperDeprecated;
extern NSString *const kEnableAllEventUpload;
extern NSString *const kDisableUnknownEventUpload;
extern NSString *const kOverrideFileAccessAction;
extern NSString *const kEvents;
extern NSString *const kFileSHA256;
@@ -65,11 +70,15 @@ extern NSString *const kDecisionAllowBinary;
extern NSString *const kDecisionAllowCertificate;
extern NSString *const kDecisionAllowScope;
extern NSString *const kDecisionAllowTeamID;
extern NSString *const kDecisionAllowSigningID;
extern NSString *const kDecisionAllowCDHash;
extern NSString *const kDecisionBlockUnknown;
extern NSString *const kDecisionBlockBinary;
extern NSString *const kDecisionBlockCertificate;
extern NSString *const kDecisionBlockScope;
extern NSString *const kDecisionBlockTeamID;
extern NSString *const kDecisionBlockSigningID;
extern NSString *const kDecisionBlockCDHash;
extern NSString *const kDecisionUnknown;
extern NSString *const kDecisionBundleBinary;
extern NSString *const kLoggedInUsers;
@@ -94,6 +103,8 @@ extern NSString *const kCertOU;
extern NSString *const kCertValidFrom;
extern NSString *const kCertValidUntil;
extern NSString *const kTeamID;
extern NSString *const kSigningID;
extern NSString *const kCDHash;
extern NSString *const kQuarantineDataURL;
extern NSString *const kQuarantineRefererURL;
extern NSString *const kQuarantineTimestamp;
@@ -117,7 +128,10 @@ extern NSString *const kRuleType;
extern NSString *const kRuleTypeBinary;
extern NSString *const kRuleTypeCertificate;
extern NSString *const kRuleTypeTeamID;
extern NSString *const kRuleTypeSigningID;
extern NSString *const kRuleTypeCDHash;
extern NSString *const kRuleCustomMsg;
extern NSString *const kRuleCustomURL;
extern NSString *const kCursor;
extern NSString *const kBackoffInterval;
@@ -129,6 +143,9 @@ extern NSString *const kLogSync;
extern const NSUInteger kDefaultEventBatchSize;
extern NSString *const kPostflightRulesReceived;
extern NSString *const kPostflightRulesProcessed;
///
/// kDefaultFullSyncInterval
/// kDefaultFCMFullSyncInterval

View File

@@ -14,7 +14,8 @@
#import "Source/common/SNTSyncConstants.h"
NSString *const kXSRFToken = @"X-XSRF-TOKEN";
NSString *const kDefaultXSRFTokenHeader = @"X-XSRF-TOKEN";
NSString *const kXSRFTokenHeader = @"X-XSRF-TOKEN-HEADER";
NSString *const kSerialNumber = @"serial_num";
NSString *const kHostname = @"hostname";
@@ -31,7 +32,8 @@ NSString *const kBlockUSBMount = @"block_usb_mount";
NSString *const kRemountUSBMode = @"remount_usb_mode";
NSString *const kClientModeMonitor = @"MONITOR";
NSString *const kClientModeLockdown = @"LOCKDOWN";
NSString *const kCleanSync = @"clean_sync";
NSString *const kCleanSyncDeprecated = @"clean_sync";
NSString *const kSyncType = @"sync_type";
NSString *const kAllowedPathRegex = @"allowed_path_regex";
NSString *const kAllowedPathRegexDeprecated = @"whitelist_regex";
NSString *const kBlockedPathRegex = @"blocked_path_regex";
@@ -41,10 +43,13 @@ NSString *const kCertificateRuleCount = @"certificate_rule_count";
NSString *const kCompilerRuleCount = @"compiler_rule_count";
NSString *const kTransitiveRuleCount = @"transitive_rule_count";
NSString *const kTeamIDRuleCount = @"teamid_rule_count";
NSString *const kSigningIDRuleCount = @"signingid_rule_count";
NSString *const kCDHashRuleCount = @"cdhash_rule_count";
NSString *const kFullSyncInterval = @"full_sync_interval";
NSString *const kFCMToken = @"fcm_token";
NSString *const kFCMFullSyncInterval = @"fcm_full_sync_interval";
NSString *const kFCMGlobalRuleSyncDeadline = @"fcm_global_rule_sync_deadline";
NSString *const kOverrideFileAccessAction = @"override_file_access_action";
NSString *const kEnableBundles = @"enable_bundles";
NSString *const kEnableBundlesDeprecated = @"bundles_enabled";
@@ -66,11 +71,15 @@ NSString *const kDecisionAllowBinary = @"ALLOW_BINARY";
NSString *const kDecisionAllowCertificate = @"ALLOW_CERTIFICATE";
NSString *const kDecisionAllowScope = @"ALLOW_SCOPE";
NSString *const kDecisionAllowTeamID = @"ALLOW_TEAMID";
NSString *const kDecisionAllowSigningID = @"ALLOW_SIGNINGID";
NSString *const kDecisionAllowCDHash = @"ALLOW_CDHASH";
NSString *const kDecisionBlockUnknown = @"BLOCK_UNKNOWN";
NSString *const kDecisionBlockBinary = @"BLOCK_BINARY";
NSString *const kDecisionBlockCertificate = @"BLOCK_CERTIFICATE";
NSString *const kDecisionBlockScope = @"BLOCK_SCOPE";
NSString *const kDecisionBlockTeamID = @"BLOCK_TEAMID";
NSString *const kDecisionBlockSigningID = @"BLOCK_SIGNINGID";
NSString *const kDecisionBlockCDHash = @"BLOCK_CDHASH";
NSString *const kDecisionUnknown = @"UNKNOWN";
NSString *const kDecisionBundleBinary = @"BUNDLE_BINARY";
NSString *const kLoggedInUsers = @"logged_in_users";
@@ -95,6 +104,8 @@ NSString *const kCertOU = @"ou";
NSString *const kCertValidFrom = @"valid_from";
NSString *const kCertValidUntil = @"valid_until";
NSString *const kTeamID = @"team_id";
NSString *const kSigningID = @"signing_id";
NSString *const kCDHash = @"cdhash";
NSString *const kQuarantineDataURL = @"quarantine_data_url";
NSString *const kQuarantineRefererURL = @"quarantine_referer_url";
NSString *const kQuarantineTimestamp = @"quarantine_timestamp";
@@ -118,7 +129,10 @@ NSString *const kRuleType = @"rule_type";
NSString *const kRuleTypeBinary = @"BINARY";
NSString *const kRuleTypeCertificate = @"CERTIFICATE";
NSString *const kRuleTypeTeamID = @"TEAMID";
NSString *const kRuleTypeSigningID = @"SIGNINGID";
NSString *const kRuleTypeCDHash = @"CDHASH";
NSString *const kRuleCustomMsg = @"custom_msg";
NSString *const kRuleCustomURL = @"custom_url";
NSString *const kCursor = @"cursor";
NSString *const kBackoffInterval = @"backoff";
@@ -128,6 +142,9 @@ NSString *const kRuleSync = @"rule_sync";
NSString *const kConfigSync = @"config_sync";
NSString *const kLogSync = @"log_sync";
NSString *const kPostflightRulesReceived = @"rules_received";
NSString *const kPostflightRulesProcessed = @"rules_processed";
const NSUInteger kDefaultEventBatchSize = 50;
const NSUInteger kDefaultFullSyncInterval = 600;
const NSUInteger kDefaultPushNotificationsFullSyncInterval = 14400;

View File

@@ -54,4 +54,19 @@
///
+ (NSString *)modelIdentifier;
///
/// @return The Santa product version, e.g. 2024.6
///
+ (NSString *)santaProductVersion;
///
/// @return The Santa build version, e.g. 655965194
///
+ (NSString *)santaBuildVersion;
///
/// @return The full Santa versoin, e.g. 2024.6.655965194
///
+ (NSString *)santaFullVersion;
@end

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -18,8 +18,11 @@
@implementation SNTSystemInfo
+ (NSString *)serialNumber {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
io_service_t platformExpert =
IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
#pragma clang diagnostic pop
if (!platformExpert) return nil;
NSString *serial = CFBridgingRelease(IORegistryEntryCreateCFProperty(
@@ -31,8 +34,11 @@
}
+ (NSString *)hardwareUUID {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
io_service_t platformExpert =
IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
#pragma clang diagnostic pop
if (!platformExpert) return nil;
NSString *uuid = CFBridgingRelease(IORegistryEntryCreateCFProperty(
@@ -68,6 +74,21 @@
return @(model);
}
+ (NSString *)santaProductVersion {
NSDictionary *info_dict = [[NSBundle mainBundle] infoDictionary];
return info_dict[@"CFBundleShortVersionString"];
}
+ (NSString *)santaBuildVersion {
NSDictionary *info_dict = [[NSBundle mainBundle] infoDictionary];
return [[info_dict[@"CFBundleVersion"] componentsSeparatedByString:@"."] lastObject];
}
+ (NSString *)santaFullVersion {
NSDictionary *info_dict = [[NSBundle mainBundle] infoDictionary];
return info_dict[@"CFBundleVersion"];
}
#pragma mark - Internal
+ (NSDictionary *)_systemVersionDictionary {

View File

@@ -21,7 +21,7 @@
/// A block that takes the calculated bundle hash, associated events and hashing time in ms.
typedef void (^SNTBundleHashBlock)(NSString *, NSArray<SNTStoredEvent *> *, NSNumber *);
/// Protocol implemented by santabs and utilized by SantaGUI for bundle hashing
/// Protocol implemented by santabundleservice and utilized by SantaGUI for bundle hashing
@protocol SNTBundleServiceXPC
///

View File

@@ -12,6 +12,7 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/common/SNTRuleIdentifiers.h"
#import "Source/common/SNTXPCUnprivilegedControlInterface.h"
///
@@ -28,14 +29,13 @@
/// Database ops
///
- (void)databaseRuleAddRules:(NSArray *)rules
cleanSlate:(BOOL)cleanSlate
ruleCleanup:(SNTRuleCleanup)cleanupType
reply:(void (^)(NSError *error))reply;
- (void)databaseEventsPending:(void (^)(NSArray *events))reply;
- (void)databaseRemoveEventsWithIDs:(NSArray *)ids;
- (void)databaseRuleForBinarySHA256:(NSString *)binarySHA256
certificateSHA256:(NSString *)certificateSHA256
teamID:(NSString *)teamID
reply:(void (^)(SNTRule *))reply;
- (void)databaseRuleForIdentifiers:(SNTRuleIdentifiers *)identifiers
reply:(void (^)(SNTRule *))reply;
- (void)retrieveAllRules:(void (^)(NSArray<SNTRule *> *rules, NSError *error))reply;
///
/// Config ops
@@ -43,7 +43,7 @@
- (void)setClientMode:(SNTClientMode)mode reply:(void (^)(void))reply;
- (void)setFullSyncLastSuccess:(NSDate *)date reply:(void (^)(void))reply;
- (void)setRuleSyncLastSuccess:(NSDate *)date reply:(void (^)(void))reply;
- (void)setSyncCleanRequired:(BOOL)cleanReqd reply:(void (^)(void))reply;
- (void)setSyncTypeRequired:(SNTSyncType)syncType reply:(void (^)(void))reply;
- (void)setAllowedPathRegex:(NSString *)pattern reply:(void (^)(void))reply;
- (void)setBlockedPathRegex:(NSString *)pattern reply:(void (^)(void))reply;
- (void)setBlockUSBMount:(BOOL)enabled reply:(void (^)(void))reply;
@@ -52,6 +52,7 @@
- (void)setEnableTransitiveRules:(BOOL)enabled reply:(void (^)(void))reply;
- (void)setEnableAllEventUpload:(BOOL)enabled reply:(void (^)(void))reply;
- (void)setDisableUnknownEventUpload:(BOOL)enabled reply:(void (^)(void))reply;
- (void)setOverrideFileAccessAction:(NSString *)action reply:(void (^)(void))reply;
///
/// Syncd Ops

View File

@@ -34,8 +34,7 @@ NSString *const kBundleID = @"com.google.santa.daemon";
#else
MOLCodesignChecker *cs = [[MOLCodesignChecker alloc] initWithSelf];
// "teamid.com.google.santa.daemon.xpc"
NSString *t = cs.signingInformation[@"teamid"];
return [NSString stringWithFormat:@"%@.%@.xpc", t, kBundleID];
return [NSString stringWithFormat:@"%@.%@.xpc", cs.teamID, kBundleID];
#endif
}
@@ -50,9 +49,14 @@ NSString *const kBundleID = @"com.google.santa.daemon";
ofReply:YES];
[r setClasses:[NSSet setWithObjects:[NSArray class], [SNTRule class], nil]
forSelector:@selector(databaseRuleAddRules:cleanSlate:reply:)
forSelector:@selector(databaseRuleAddRules:ruleCleanup:reply:)
argumentIndex:0
ofReply:NO];
[r setClasses:[NSSet setWithObjects:[NSArray class], [SNTRule class], nil]
forSelector:@selector(retrieveAllRules:)
argumentIndex:0
ofReply:YES];
}
+ (NSXPCInterface *)controlInterface {

View File

@@ -17,13 +17,20 @@
#import "Source/common/SNTCommonEnums.h"
#import "Source/common/SNTXPCBundleServiceInterface.h"
@class SNTStoredEvent;
@class SNTDeviceEvent;
@class SNTFileAccessEvent;
@class SNTStoredEvent;
/// Protocol implemented by SantaGUI and utilized by santad
@protocol SNTNotifierXPC
- (void)postBlockNotification:(SNTStoredEvent *)event withCustomMessage:(NSString *)message;
- (void)postBlockNotification:(SNTStoredEvent *)event
withCustomMessage:(NSString *)message
andCustomURL:(NSString *)url;
- (void)postUSBBlockNotification:(SNTDeviceEvent *)event withCustomMessage:(NSString *)message;
- (void)postFileAccessBlockNotification:(SNTFileAccessEvent *)event
customMessage:(NSString *)message
customURL:(NSString *)url
customText:(NSString *)text API_AVAILABLE(macos(13.0));
- (void)postClientModeNotification:(SNTClientMode)clientmode;
- (void)postRuleSyncNotificationWithCustomMessage:(NSString *)message;
- (void)updateCountsForEvent:(SNTStoredEvent *)event

View File

@@ -44,7 +44,7 @@
// Pass true to isClean to perform a clean sync, defaults to false.
//
- (void)syncWithLogListener:(NSXPCListenerEndpoint *)logListener
isClean:(BOOL)cleanSync
syncType:(SNTSyncType)syncType
reply:(void (^)(SNTSyncStatusType))reply;
// Spindown the syncservice. The syncservice will not automatically start back up.

View File

@@ -1,4 +1,4 @@
/// Copyright 2015 Google Inc. All rights reserved.
/// Copyright 2015-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -16,12 +16,23 @@
#import <MOLCertificate/MOLCertificate.h>
#import "Source/common/SNTCommonEnums.h"
#import "Source/common/SNTCommon.h"
#import "Source/common/SNTRuleIdentifiers.h"
#import "Source/common/SantaVnode.h"
@class SNTRule;
@class SNTStoredEvent;
@class MOLXPCConnection;
struct RuleCounts {
int64_t binary;
int64_t certificate;
int64_t compiler;
int64_t transitive;
int64_t teamID;
int64_t signingID;
int64_t cdhash;
};
///
/// Protocol implemented by santad and utilized by santactl (unprivileged operations)
///
@@ -31,14 +42,12 @@
/// Cache Ops
///
- (void)cacheCounts:(void (^)(uint64_t rootCache, uint64_t nonRootCache))reply;
- (void)cacheBucketCount:(void (^)(NSArray *))reply;
- (void)checkCacheForVnodeID:(santa_vnode_id_t)vnodeID withReply:(void (^)(santa_action_t))reply;
- (void)checkCacheForVnodeID:(SantaVnode)vnodeID withReply:(void (^)(SNTAction))reply;
///
/// Database ops
///
- (void)databaseRuleCounts:(void (^)(int64_t binary, int64_t certificate, int64_t compiler,
int64_t transitive, int64_t teamID))reply;
- (void)databaseRuleCounts:(void (^)(struct RuleCounts ruleCounts))reply;
- (void)databaseEventCount:(void (^)(int64_t count))reply;
- (void)staticRuleCount:(void (^)(int64_t count))reply;
@@ -48,28 +57,25 @@
///
/// @param filePath A Path to the file, can be nil.
/// @param fileSHA256 The pre-calculated SHA256 hash for the file, can be nil. If nil the hash will
/// be calculated by this method from the filePath.
/// @param certificateSHA256 A SHA256 hash of the signing certificate, can be nil.
/// @note If fileInfo and signingCertificate are both passed in, the most specific rule will be
/// returned. Binary rules take precedence over cert rules.
/// @param identifiers The various identifiers to be used when making a decision.
///
- (void)decisionForFilePath:(NSString *)filePath
fileSHA256:(NSString *)fileSHA256
certificateSHA256:(NSString *)certificateSHA256
teamID:(NSString *)teamID
identifiers:(SNTRuleIdentifiers *)identifiers
reply:(void (^)(SNTEventState))reply;
///
/// Config ops
///
- (void)watchdogInfo:(void (^)(uint64_t, uint64_t, double, double))reply;
- (void)watchItemsState:(void (^)(BOOL, uint64_t, NSString *, NSString *, NSTimeInterval))reply;
- (void)clientMode:(void (^)(SNTClientMode))reply;
- (void)fullSyncLastSuccess:(void (^)(NSDate *))reply;
- (void)ruleSyncLastSuccess:(void (^)(NSDate *))reply;
- (void)syncCleanRequired:(void (^)(BOOL))reply;
- (void)syncTypeRequired:(void (^)(SNTSyncType))reply;
- (void)enableBundles:(void (^)(BOOL))reply;
- (void)enableTransitiveRules:(void (^)(BOOL))reply;
- (void)blockUSBMount:(void (^)(BOOL))reply;
- (void)remountUSBMode:(void (^)(NSArray<NSString *> *))reply;
///
/// Metrics ops

View File

@@ -1,4 +1,4 @@
/// Copyright 2016 Google Inc. All rights reserved.
/// Copyright 2016-2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
#include <libkern/OSAtomic.h>
#include <libkern/OSTypes.h>
#include <os/log.h>
#include <stdint.h>
#include <sys/cdefs.h>
@@ -24,12 +25,7 @@
#include <cstdlib>
#include <cstring>
#include "Source/common/SNTCommon.h"
#define panic(args...) \
printf(args); \
printf("\n"); \
abort()
#include "Source/common/BranchPrediction.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
@@ -324,8 +320,8 @@ class SantaCache {
Lock a bucket. Spins until the lock is acquired.
*/
inline void lock(struct bucket *bucket) const {
while (OSAtomicTestAndSet(7, (volatile uint8_t *)&bucket->head))
;
while (OSAtomicTestAndSet(7, (volatile uint8_t *)&bucket->head)) {
}
}
/**
@@ -334,7 +330,9 @@ class SantaCache {
inline void unlock(struct bucket *bucket) const {
if (unlikely(OSAtomicTestAndClear(7, (volatile uint8_t *)&bucket->head) ==
0)) {
panic("SantaCache::unlock(): Tried to unlock an unlocked lock");
os_log_error(OS_LOG_DEFAULT,
"SantaCache::unlock(): Tried to unlock an unlocked lock");
abort();
}
}

View File

@@ -245,7 +245,7 @@ struct S {
uint64_t first_val;
uint64_t second_val;
bool operator==(const S &rhs) {
bool operator==(const S &rhs) const {
return first_val == rhs.first_val && second_val == rhs.second_val;
}
};

View File

@@ -0,0 +1,44 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__SANTAVNODE_H
#define SANTA__COMMON__SANTAVNODE_H
#include <EndpointSecurity/EndpointSecurity.h>
#include <sys/types.h>
// Struct to manage vnode IDs
typedef struct SantaVnode {
dev_t fsid;
ino_t fileid;
#ifdef __cplusplus
bool operator==(const SantaVnode &rhs) const {
return fsid == rhs.fsid && fileid == rhs.fileid;
}
static inline SantaVnode VnodeForFile(const struct stat &sb) {
return SantaVnode{
.fsid = sb.st_dev,
.fileid = sb.st_ino,
};
}
static inline SantaVnode VnodeForFile(const es_file_t *es_file) {
return VnodeForFile(es_file->stat);
}
#endif
} SantaVnode;
#endif

View File

@@ -0,0 +1,24 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__SANTAVNODEHASH_H
#define SANTA__COMMON__SANTAVNODEHASH_H
#include "Source/common/SantaCache.h"
#include "Source/common/SantaVnode.h"
template <>
uint64_t SantaCacheHasher<SantaVnode>(SantaVnode const &t);
#endif

View File

@@ -0,0 +1,20 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include "Source/common/SantaVnodeHash.h"
template <>
uint64_t SantaCacheHasher<SantaVnode>(SantaVnode const &t) {
return (SantaCacheHasher<uint64_t>(t.fsid) << 1) ^ SantaCacheHasher<uint64_t>(t.fileid);
}

View File

@@ -0,0 +1,29 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__SCOPEDCFTYPEREF_H
#define SANTA__COMMON__SCOPEDCFTYPEREF_H
#include <CoreFoundation/CoreFoundation.h>
#include "Source/common/ScopedTypeRef.h"
namespace santa {
template <typename CFT>
using ScopedCFTypeRef = ScopedTypeRef<CFT, (CFT)NULL, CFRetain, CFRelease>;
} // namespace santa
#endif

View File

@@ -0,0 +1,141 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
#import <XCTest/XCTest.h>
#include "XCTest/XCTest.h"
#include "Source/common/ScopedCFTypeRef.h"
using santa::ScopedCFTypeRef;
@interface ScopedCFTypeRefTest : XCTestCase
@end
@implementation ScopedCFTypeRefTest
- (void)testDefaultConstruction {
// Default construction creates wraps a NULL object
ScopedCFTypeRef<CFNumberRef> scopedRef;
XCTAssertFalse(scopedRef.Unsafe());
}
- (void)testOperatorBool {
// Operator bool is `false` when object is null
{
ScopedCFTypeRef<CFNumberRef> scopedNullRef;
XCTAssertFalse(scopedNullRef.Unsafe());
XCTAssertFalse(scopedNullRef);
}
// Operator bool is `true` when object is NOT null
{
int x = 123;
CFNumberRef numRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &x);
ScopedCFTypeRef<CFNumberRef> scopedNumRef = ScopedCFTypeRef<CFNumberRef>::Assume(numRef);
XCTAssertTrue(scopedNumRef.Unsafe());
XCTAssertTrue(scopedNumRef);
}
}
// Note that CFMutableArray is used for testing, even when subtypes aren't
// needed, because it is never optimized into immortal constant values, unlike
// other types.
- (void)testAssume {
int want = 123;
int got = 0;
CFMutableArrayRef array = CFArrayCreateMutable(nullptr, /*capacity=*/0, &kCFTypeArrayCallBacks);
// Baseline state, initial retain count is 1 after object creation
XCTAssertEqual(1, CFGetRetainCount(array));
CFNumberRef numRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &want);
CFArrayAppendValue(array, numRef);
CFRelease(numRef);
XCTAssertEqual(1, CFArrayGetCount(array));
{
ScopedCFTypeRef<CFMutableArrayRef> scopedArray =
ScopedCFTypeRef<CFMutableArrayRef>::Assume(array);
// Ensure ownership was taken, and retain count remains unchanged
XCTAssertTrue(scopedArray.Unsafe());
XCTAssertEqual(1, CFGetRetainCount(scopedArray.Unsafe()));
// Make sure the object contains expected contents
CFMutableArrayRef ref = scopedArray.Unsafe();
XCTAssertEqual(1, CFArrayGetCount(ref));
XCTAssertTrue(
CFNumberGetValue((CFNumberRef)CFArrayGetValueAtIndex(ref, 0), kCFNumberIntType, &got));
XCTAssertEqual(want, got);
}
}
// Note that CFMutableArray is used for testing, even when subtypes aren't
// needed, because it is never optimized into immortal constant values, unlike
// other types.
- (void)testRetain {
int want = 123;
int got = 0;
CFMutableArrayRef array = CFArrayCreateMutable(nullptr, /*capacity=*/0, &kCFTypeArrayCallBacks);
// Baseline state, initial retain count is 1 after object creation
XCTAssertEqual(1, CFGetRetainCount(array));
CFNumberRef numRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &want);
CFArrayAppendValue(array, numRef);
CFRelease(numRef);
XCTAssertEqual(1, CFArrayGetCount(array));
{
ScopedCFTypeRef<CFMutableArrayRef> scopedArray =
ScopedCFTypeRef<CFMutableArrayRef>::Retain(array);
// Ensure ownership was taken, and retain count was incremented
XCTAssertTrue(scopedArray.Unsafe());
XCTAssertEqual(2, CFGetRetainCount(scopedArray.Unsafe()));
// Make sure the object contains expected contents
CFMutableArrayRef ref = scopedArray.Unsafe();
XCTAssertEqual(1, CFArrayGetCount(ref));
XCTAssertTrue(
CFNumberGetValue((CFNumberRef)CFArrayGetValueAtIndex(ref, 0), kCFNumberIntType, &got));
XCTAssertEqual(want, got);
}
// The original `array` object should still be valid due to the extra retain.
// Ensure the retain count has decreased since `scopedArray` went out of scope
XCTAssertEqual(1, CFArrayGetCount(array));
}
- (void)testInto {
ScopedCFTypeRef<CFURLRef> scopedURLRef =
ScopedCFTypeRef<CFURLRef>::Assume(CFURLCreateWithFileSystemPath(
kCFAllocatorDefault, CFSTR("/usr/bin/true"), kCFURLPOSIXPathStyle, YES));
ScopedCFTypeRef<SecStaticCodeRef> scopedCodeRef;
XCTAssertFalse(scopedCodeRef);
SecStaticCodeCreateWithPath(scopedURLRef.Unsafe(), kSecCSDefaultFlags,
scopedCodeRef.InitializeInto());
// Ensure the scoped object was initialized
XCTAssertTrue(scopedCodeRef);
}
@end

View File

@@ -0,0 +1,30 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__SCOPEDIOOBJECTREF_H
#define SANTA__COMMON__SCOPEDIOOBJECTREF_H
#include <IOKit/IOKitLib.h>
#include "Source/common/ScopedTypeRef.h"
namespace santa {
template <typename IOT>
using ScopedIOObjectRef =
ScopedTypeRef<IOT, (IOT)IO_OBJECT_NULL, IOObjectRetain, IOObjectRelease>;
}
#endif // namespace santa

View File

@@ -0,0 +1,104 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>
#import <XCTest/XCTest.h>
#include "Source/common/ScopedIOObjectRef.h"
#include "Source/santad/Logs/EndpointSecurity/Serializers/Utilities.h"
using santa::GetDefaultIOKitCommsPort;
using santa::ScopedIOObjectRef;
@interface ScopedIOObjectRefTest : XCTestCase
@end
@implementation ScopedIOObjectRefTest
- (void)testDefaultConstruction {
// Default construction creates wraps a NULL object
ScopedIOObjectRef<io_object_t> scopedRef;
XCTAssertFalse(scopedRef.Unsafe());
}
- (void)testOperatorBool {
// Operator bool is `false` when object is null
{
ScopedIOObjectRef<io_object_t> scopedNullRef;
XCTAssertFalse(scopedNullRef.Unsafe());
XCTAssertFalse(scopedNullRef);
}
// Operator bool is `true` when object is NOT null
{
CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
XCTAssertNotEqual((CFMutableDictionaryRef)NULL, matchingDict);
io_service_t service = IOServiceGetMatchingService(GetDefaultIOKitCommsPort(), matchingDict);
ScopedIOObjectRef<io_service_t> scopedServiceRef =
ScopedIOObjectRef<io_service_t>::Assume(service);
XCTAssertTrue(scopedServiceRef.Unsafe());
XCTAssertTrue(scopedServiceRef);
}
}
- (void)testAssume {
CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
XCTAssertNotEqual((CFMutableDictionaryRef)NULL, matchingDict);
io_service_t service = IOServiceGetMatchingService(GetDefaultIOKitCommsPort(), matchingDict);
// Baseline state, initial retain count is 1 after object creation
XCTAssertEqual(1, IOObjectGetUserRetainCount(service));
XCTAssertNotEqual(IO_OBJECT_NULL, service);
{
ScopedIOObjectRef<io_service_t> scopedIORef = ScopedIOObjectRef<io_service_t>::Assume(service);
// Ensure ownership was taken, and retain count remains unchanged
XCTAssertTrue(scopedIORef.Unsafe());
XCTAssertEqual(1, IOObjectGetUserRetainCount(scopedIORef.Unsafe()));
XCTAssertNotEqual(IO_OBJECT_NULL, scopedIORef.Unsafe());
}
}
- (void)testRetain {
CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
XCTAssertNotEqual((CFMutableDictionaryRef)NULL, matchingDict);
io_service_t service = IOServiceGetMatchingService(GetDefaultIOKitCommsPort(), matchingDict);
// Baseline state, initial retain count is 1 after object creation
XCTAssertEqual(1, IOObjectGetUserRetainCount(service));
XCTAssertNotEqual(IO_OBJECT_NULL, service);
{
ScopedIOObjectRef<io_service_t> scopedIORef = ScopedIOObjectRef<io_service_t>::Retain(service);
// Ensure ownership was taken, and retain count was incremented
XCTAssertTrue(scopedIORef.Unsafe());
XCTAssertEqual(2, IOObjectGetUserRetainCount(scopedIORef.Unsafe()));
XCTAssertNotEqual(IO_OBJECT_NULL, scopedIORef.Unsafe());
}
// The original `service` object should still be valid due to the extra retain.
// Ensure the retain count has decreased since `scopedIORef` went out of scope.
XCTAssertEqual(1, IOObjectGetUserRetainCount(service));
}
@end

View File

@@ -0,0 +1,80 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__SCOPEDTYPEREF_H
#define SANTA__COMMON__SCOPEDTYPEREF_H
#include <CoreFoundation/CoreFoundation.h>
#include <assert.h>
namespace santa {
template <typename ElementT, ElementT InvalidV, auto RetainFunc,
auto ReleaseFunc>
class ScopedTypeRef {
public:
ScopedTypeRef() : object_(InvalidV) {}
// Can be implemented safely, but not currently needed
ScopedTypeRef(ScopedTypeRef&& other) = delete;
ScopedTypeRef& operator=(ScopedTypeRef&& rhs) = delete;
ScopedTypeRef(const ScopedTypeRef& other) = delete;
ScopedTypeRef& operator=(const ScopedTypeRef& other) = delete;
// Take ownership of a given object
static ScopedTypeRef<ElementT, InvalidV, RetainFunc, ReleaseFunc> Assume(
ElementT object) {
return ScopedTypeRef<ElementT, InvalidV, RetainFunc, ReleaseFunc>(object);
}
// Retain and take ownership of a given object
static ScopedTypeRef<ElementT, InvalidV, RetainFunc, ReleaseFunc> Retain(
ElementT object) {
if (object) {
RetainFunc(object);
}
return ScopedTypeRef<ElementT, InvalidV, RetainFunc, ReleaseFunc>(object);
}
~ScopedTypeRef() {
if (object_) {
ReleaseFunc(object_);
object_ = InvalidV;
}
}
explicit operator bool() { return object_ != InvalidV; }
ElementT Unsafe() { return object_; }
// This is to be used only to take ownership of objects that are created by
// pass-by-pointer create functions. The object must not already be valid.
// In non-opt builds, this is enforced by an assert that will terminate the
// process.
ElementT* InitializeInto() {
assert(object_ == InvalidV);
return &object_;
}
private:
// Not API.
// Use Assume or Retain static methods.
ScopedTypeRef(ElementT object) : object_(object) {}
ElementT object_;
};
} // namespace santa
#endif

View File

@@ -0,0 +1,30 @@
/// Copyright 2024 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <Foundation/Foundation.h>
#import <MOLCodesignChecker/MOLCodesignChecker.h>
__BEGIN_DECLS
/**
Return a string representing normalized SigningID (prefixed with TeamID and a
colon).
@param csc A MOLCodesignChecker instance
@return An NSString formated as teamID:signingID or nil if there isn't a valid signing ID.
*/
NSString *FormatSigningID(MOLCodesignChecker *csc);
__END_DECLS

View File

@@ -0,0 +1,33 @@
/// Copyright 2024 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/common/SigningIDHelpers.h"
#import "Source/common/SNTLogging.h"
NSString *FormatSigningID(MOLCodesignChecker *csc) {
if (!csc.signingID.length) {
return nil;
}
if (!csc.teamID.length) {
if (csc.platformBinary) {
return [NSString stringWithFormat:@"%@:%@", @"platform", csc.signingID];
} else {
LOGD(@"unable to format signing ID missing team ID for non-platform binary");
return nil;
}
}
return [NSString stringWithFormat:@"%@:%@", csc.teamID, csc.signingID];
}

58
Source/common/String.h Normal file
View File

@@ -0,0 +1,58 @@
/// Copyright 2023 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__STRING_H
#define SANTA__COMMON__STRING_H
#include <EndpointSecurity/ESTypes.h>
#include <Foundation/Foundation.h>
#include <optional>
#include <string>
#include <string_view>
namespace santa {
static inline std::string_view NSStringToUTF8StringView(NSString *str) {
return std::string_view(str.UTF8String, [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
}
static inline std::string NSStringToUTF8String(NSString *str) {
return std::string(str.UTF8String, [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
}
static inline NSString *StringToNSString(const std::string &str) {
return [NSString stringWithUTF8String:str.c_str()];
}
static inline NSString *StringToNSString(const char *str) {
return [NSString stringWithUTF8String:str];
}
static inline NSString *OptionalStringToNSString(const std::optional<std::string> &optional_str) {
std::string str = optional_str.value_or("");
if (str.length() == 0) {
return nil;
} else {
return StringToNSString(str);
}
}
static inline std::string_view StringTokenToStringView(es_string_token_t es_str) {
return std::string_view(es_str.data, es_str.length);
}
} // namespace santa
#endif

View File

@@ -0,0 +1,44 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__SYSTEMRESOURCES_H
#define SANTA__COMMON__SYSTEMRESOURCES_H
#import <Foundation/Foundation.h>
#include <mach/mach_time.h>
#include <sys/cdefs.h>
#include <sys/proc_info.h>
#include <optional>
struct SantaTaskInfo {
uint64_t virtual_size;
uint64_t resident_size;
uint64_t total_user_nanos;
uint64_t total_system_nanos;
};
// Convert mach absolute time to nanoseconds
uint64_t MachTimeToNanos(uint64_t mach_time);
// Convert nanoseconds to mach absolute time
uint64_t NanosToMachTime(uint64_t nanos);
// Add some number of nanoseconds to a given mach time and return the new result
uint64_t AddNanosecondsToMachTime(uint64_t ns, uint64_t machTime);
// Get the result of proc_pidinfo with the PROC_PIDTASKINFO flavor
std::optional<SantaTaskInfo> GetTaskInfo();
#endif

View File

@@ -0,0 +1,79 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include "Source/common/SystemResources.h"
#include <dispatch/dispatch.h>
#include <libproc.h>
#include <mach/kern_return.h>
#include <unistd.h>
#include <optional>
#include "Source/common/SNTLogging.h"
static mach_timebase_info_data_t GetTimebase() {
static dispatch_once_t once_token;
static mach_timebase_info_data_t timebase;
dispatch_once(&once_token, ^{
if (mach_timebase_info(&timebase) != KERN_SUCCESS) {
// This shouldn't fail. Assume transitory and exit the program.
// Hopefully fixes itself on restart...
LOGE(@"Failed to get timebase info. Exiting.");
exit(EXIT_FAILURE);
}
});
return timebase;
}
uint64_t MachTimeToNanos(uint64_t mach_time) {
static mach_timebase_info_data_t timebase = GetTimebase();
return mach_time * timebase.numer / timebase.denom;
}
uint64_t NanosToMachTime(uint64_t nanos) {
static mach_timebase_info_data_t timebase = GetTimebase();
return nanos * timebase.denom / timebase.numer;
}
uint64_t AddNanosecondsToMachTime(uint64_t ns, uint64_t machTime) {
// Convert machtime to nanoseconds
uint64_t nanoTime = MachTimeToNanos(machTime);
// Add the nanosecond offset
nanoTime += ns;
// Convert back to machTime
return NanosToMachTime(nanoTime);
}
std::optional<SantaTaskInfo> GetTaskInfo() {
struct proc_taskinfo pti;
if (proc_pidinfo(getpid(), PROC_PIDTASKINFO, 0, &pti, PROC_PIDTASKINFO_SIZE) <
PROC_PIDTASKINFO_SIZE) {
LOGW(@"Unable to get system resource information");
return std::nullopt;
}
return SantaTaskInfo{
.virtual_size = pti.pti_virtual_size,
.resident_size = pti.pti_resident_size,
.total_user_nanos = MachTimeToNanos(pti.pti_total_user),
.total_system_nanos = MachTimeToNanos(pti.pti_total_system),
};
}

88
Source/common/TestUtils.h Normal file
View File

@@ -0,0 +1,88 @@
/// Copyright 2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__TESTUTILS_H
#define SANTA__COMMON__TESTUTILS_H
#include <EndpointSecurity/EndpointSecurity.h>
#import <XCTest/XCTest.h>
#include <bsm/libbsm.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sys/stat.h>
#include <string>
#define NOBODY_UID ((unsigned int)-2)
#define NOGROUP_GID ((unsigned int)-1)
// Bubble up googletest expectation failures to XCTest failures
#define XCTBubbleMockVerifyAndClearExpectations(mock) \
XCTAssertTrue(::testing::Mock::VerifyAndClearExpectations(mock), \
"Expected calls were not properly mocked")
// Pretty print C string match errors
#define XCTAssertCStringEqual(got, want) \
XCTAssertTrue(strcmp((got), (want)) == 0, @"\nMismatched strings.\n\t got: %s\n\twant: %s", \
(got), (want))
// Pretty print C++ string match errors
#define XCTAssertCppStringEqual(got, want) XCTAssertCStringEqual((got).c_str(), (want).c_str())
#define XCTAssertCppStringBeginsWith(got, want) \
XCTAssertTrue((got).rfind((want), 0) == 0, "\nPrefix not found.\n\t got: %s\n\twant: %s\n", \
(got).c_str(), (want).c_str())
// Note: Delta between local formatter and the one run on Github. Disable for now.
// clang-format off
#define XCTAssertSemaTrue(s, sec, m) \
XCTAssertEqual( \
0, dispatch_semaphore_wait((s), dispatch_time(DISPATCH_TIME_NOW, (sec) * NSEC_PER_SEC)), m)
// clang-format on
// Helper to ensure at least `ms` milliseconds are slept, even if the sleep
// function returns early due to interrupts.
void SleepMS(long ms);
// Helper to construct strings of a given length
NSString *RepeatedString(NSString *str, NSUInteger len);
//
// Helpers to construct various ES structs
//
enum class ActionType {
Auth,
Notify,
};
audit_token_t MakeAuditToken(pid_t pid, pid_t pidver);
/// Construct a `struct stat` buffer with each member having a unique value.
/// @param offset An optional offset to be added to each member. useful when
/// a test has multiple stats and you'd like for them each to have different
/// values across the members.
struct stat MakeStat(int offset = 0);
es_string_token_t MakeESStringToken(const char *s);
es_file_t MakeESFile(const char *path, struct stat sb = MakeStat());
es_process_t MakeESProcess(es_file_t *file, audit_token_t tok = {}, audit_token_t parent_tok = {});
es_message_t MakeESMessage(es_event_type_t et, es_process_t *proc,
ActionType action_type = ActionType::Notify,
uint64_t future_deadline_ms = 100000);
uint32_t MaxSupportedESMessageVersionForCurrentOS();
uint32_t MinSupportedESMessageVersion(es_event_type_t event_type);
#endif

320
Source/common/TestUtils.mm Normal file
View File

@@ -0,0 +1,320 @@
/// Copyright 2022 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#include "Source/common/TestUtils.h"
#include <EndpointSecurity/ESTypes.h>
#include <dispatch/dispatch.h>
#include <mach/mach_time.h>
#include <time.h>
#include <uuid/uuid.h>
#include "Source/common/Platform.h"
#include "Source/common/SystemResources.h"
NSString *RepeatedString(NSString *str, NSUInteger len) {
return [@"" stringByPaddingToLength:len withString:str startingAtIndex:0];
}
audit_token_t MakeAuditToken(pid_t pid, pid_t pidver) {
return audit_token_t{
.val =
{
0,
NOBODY_UID,
NOGROUP_GID,
NOBODY_UID,
NOGROUP_GID,
(unsigned int)pid,
0,
(unsigned int)pidver,
},
};
}
struct stat MakeStat(int offset) {
return (struct stat){
.st_dev = 1 + offset,
.st_mode = (mode_t)(2 + offset),
.st_nlink = (nlink_t)(3 + offset),
.st_ino = (uint64_t)(4 + offset),
.st_uid = NOBODY_UID,
.st_gid = NOGROUP_GID,
.st_rdev = 5 + offset,
.st_atimespec = {.tv_sec = 100 + offset, .tv_nsec = 200 + offset},
.st_mtimespec = {.tv_sec = 101 + offset, .tv_nsec = 21 + offset},
.st_ctimespec = {.tv_sec = 102 + offset, .tv_nsec = 202 + offset},
.st_birthtimespec = {.tv_sec = 103 + offset, .tv_nsec = 203 + offset},
.st_size = 6 + offset,
.st_blocks = 7 + offset,
.st_blksize = 8 + offset,
.st_flags = (uint32_t)(9 + offset),
.st_gen = (uint32_t)(10 + offset),
};
}
es_string_token_t MakeESStringToken(const char *s) {
return es_string_token_t{
.length = s ? strlen(s) : 0,
.data = s,
};
}
es_file_t MakeESFile(const char *path, struct stat sb) {
return es_file_t{
.path = MakeESStringToken(path),
.path_truncated = false,
.stat = sb,
};
}
es_process_t MakeESProcess(es_file_t *file, audit_token_t tok, audit_token_t parent_tok) {
return es_process_t{
.audit_token = tok,
.ppid = audit_token_to_pid(parent_tok),
.original_ppid = audit_token_to_pid(parent_tok),
.group_id = 111,
.session_id = 222,
.is_platform_binary = true,
.is_es_client = true,
.executable = file,
.parent_audit_token = parent_tok,
};
}
es_message_t MakeESMessage(es_event_type_t et, es_process_t *proc, ActionType action_type,
uint64_t future_deadline_ms) {
es_message_t es_msg = {
.deadline = AddNanosecondsToMachTime(future_deadline_ms * NSEC_PER_MSEC, mach_absolute_time()),
.process = proc,
.action_type =
(action_type == ActionType::Notify) ? ES_ACTION_TYPE_NOTIFY : ES_ACTION_TYPE_AUTH,
.event_type = et,
};
es_msg.version = MaxSupportedESMessageVersionForCurrentOS();
return es_msg;
}
void SleepMS(long ms) {
struct timespec ts {
.tv_sec = ms / 1000, .tv_nsec = (long)((ms % 1000) * NSEC_PER_MSEC),
};
while (nanosleep(&ts, &ts) != 0) {
XCTAssertEqual(errno, EINTR);
}
}
uint32_t MaxSupportedESMessageVersionForCurrentOS() {
// Note 1: This function only returns a subset of versions. This is due to the
// minimum supported OS build version as well as features in latest versions
// not currently being used. Capping the max means unnecessary duuplicate test
// JSON files are not needed.
//
// Note 2: The following table maps ES message versions to lmin macOS version:
// ES Version | macOS Version
// 1 | 10.15.0
// 2 | 10.15.4
// 3 | Only in a beta
// 4 | 11.0
// 5 | 12.3
// 6 | 13.0
// 7 | 14.0
// 8 | 15.0
if (@available(macOS 13.0, *)) {
return 6;
} else if (@available(macOS 12.3, *)) {
return 5;
} else {
return 4;
}
}
uint32_t MinSupportedESMessageVersion(es_event_type_t event_type) {
switch (event_type) {
// The following events are available beginning in macOS 10.15
case ES_EVENT_TYPE_AUTH_EXEC:
case ES_EVENT_TYPE_AUTH_OPEN:
case ES_EVENT_TYPE_AUTH_KEXTLOAD:
case ES_EVENT_TYPE_AUTH_MMAP:
case ES_EVENT_TYPE_AUTH_MPROTECT:
case ES_EVENT_TYPE_AUTH_MOUNT:
case ES_EVENT_TYPE_AUTH_RENAME:
case ES_EVENT_TYPE_AUTH_SIGNAL:
case ES_EVENT_TYPE_AUTH_UNLINK:
case ES_EVENT_TYPE_NOTIFY_EXEC:
case ES_EVENT_TYPE_NOTIFY_OPEN:
case ES_EVENT_TYPE_NOTIFY_FORK:
case ES_EVENT_TYPE_NOTIFY_CLOSE:
case ES_EVENT_TYPE_NOTIFY_CREATE:
case ES_EVENT_TYPE_NOTIFY_EXCHANGEDATA:
case ES_EVENT_TYPE_NOTIFY_EXIT:
case ES_EVENT_TYPE_NOTIFY_GET_TASK:
case ES_EVENT_TYPE_NOTIFY_KEXTLOAD:
case ES_EVENT_TYPE_NOTIFY_KEXTUNLOAD:
case ES_EVENT_TYPE_NOTIFY_LINK:
case ES_EVENT_TYPE_NOTIFY_MMAP:
case ES_EVENT_TYPE_NOTIFY_MPROTECT:
case ES_EVENT_TYPE_NOTIFY_MOUNT:
case ES_EVENT_TYPE_NOTIFY_UNMOUNT:
case ES_EVENT_TYPE_NOTIFY_IOKIT_OPEN:
case ES_EVENT_TYPE_NOTIFY_RENAME:
case ES_EVENT_TYPE_NOTIFY_SETATTRLIST:
case ES_EVENT_TYPE_NOTIFY_SETEXTATTR:
case ES_EVENT_TYPE_NOTIFY_SETFLAGS:
case ES_EVENT_TYPE_NOTIFY_SETMODE:
case ES_EVENT_TYPE_NOTIFY_SETOWNER:
case ES_EVENT_TYPE_NOTIFY_SIGNAL:
case ES_EVENT_TYPE_NOTIFY_UNLINK:
case ES_EVENT_TYPE_NOTIFY_WRITE:
case ES_EVENT_TYPE_AUTH_FILE_PROVIDER_MATERIALIZE:
case ES_EVENT_TYPE_NOTIFY_FILE_PROVIDER_MATERIALIZE:
case ES_EVENT_TYPE_AUTH_FILE_PROVIDER_UPDATE:
case ES_EVENT_TYPE_NOTIFY_FILE_PROVIDER_UPDATE:
case ES_EVENT_TYPE_AUTH_READLINK:
case ES_EVENT_TYPE_NOTIFY_READLINK:
case ES_EVENT_TYPE_AUTH_TRUNCATE:
case ES_EVENT_TYPE_NOTIFY_TRUNCATE:
case ES_EVENT_TYPE_AUTH_LINK:
case ES_EVENT_TYPE_NOTIFY_LOOKUP:
case ES_EVENT_TYPE_AUTH_CREATE:
case ES_EVENT_TYPE_AUTH_SETATTRLIST:
case ES_EVENT_TYPE_AUTH_SETEXTATTR:
case ES_EVENT_TYPE_AUTH_SETFLAGS:
case ES_EVENT_TYPE_AUTH_SETMODE:
case ES_EVENT_TYPE_AUTH_SETOWNER: return 1;
// The following events are available beginning in macOS 10.15.1
case ES_EVENT_TYPE_AUTH_CHDIR:
case ES_EVENT_TYPE_NOTIFY_CHDIR:
case ES_EVENT_TYPE_AUTH_GETATTRLIST:
case ES_EVENT_TYPE_NOTIFY_GETATTRLIST:
case ES_EVENT_TYPE_NOTIFY_STAT:
case ES_EVENT_TYPE_NOTIFY_ACCESS:
case ES_EVENT_TYPE_AUTH_CHROOT:
case ES_EVENT_TYPE_NOTIFY_CHROOT:
case ES_EVENT_TYPE_AUTH_UTIMES:
case ES_EVENT_TYPE_NOTIFY_UTIMES:
case ES_EVENT_TYPE_AUTH_CLONE:
case ES_EVENT_TYPE_NOTIFY_CLONE:
case ES_EVENT_TYPE_NOTIFY_FCNTL:
case ES_EVENT_TYPE_AUTH_GETEXTATTR:
case ES_EVENT_TYPE_NOTIFY_GETEXTATTR:
case ES_EVENT_TYPE_AUTH_LISTEXTATTR:
case ES_EVENT_TYPE_NOTIFY_LISTEXTATTR:
case ES_EVENT_TYPE_AUTH_READDIR:
case ES_EVENT_TYPE_NOTIFY_READDIR:
case ES_EVENT_TYPE_AUTH_DELETEEXTATTR:
case ES_EVENT_TYPE_NOTIFY_DELETEEXTATTR:
case ES_EVENT_TYPE_AUTH_FSGETPATH:
case ES_EVENT_TYPE_NOTIFY_FSGETPATH:
case ES_EVENT_TYPE_NOTIFY_DUP:
case ES_EVENT_TYPE_AUTH_SETTIME:
case ES_EVENT_TYPE_NOTIFY_SETTIME:
case ES_EVENT_TYPE_NOTIFY_UIPC_BIND:
case ES_EVENT_TYPE_AUTH_UIPC_BIND:
case ES_EVENT_TYPE_NOTIFY_UIPC_CONNECT:
case ES_EVENT_TYPE_AUTH_UIPC_CONNECT:
case ES_EVENT_TYPE_AUTH_EXCHANGEDATA:
case ES_EVENT_TYPE_AUTH_SETACL:
case ES_EVENT_TYPE_NOTIFY_SETACL: return 1;
// The following events are available beginning in macOS 10.15.4
case ES_EVENT_TYPE_NOTIFY_PTY_GRANT:
case ES_EVENT_TYPE_NOTIFY_PTY_CLOSE:
case ES_EVENT_TYPE_AUTH_PROC_CHECK:
case ES_EVENT_TYPE_NOTIFY_PROC_CHECK:
case ES_EVENT_TYPE_AUTH_GET_TASK: return 2;
// The following events are available beginning in macOS 11.0
case ES_EVENT_TYPE_AUTH_SEARCHFS:
case ES_EVENT_TYPE_NOTIFY_SEARCHFS:
case ES_EVENT_TYPE_AUTH_FCNTL:
case ES_EVENT_TYPE_AUTH_IOKIT_OPEN:
case ES_EVENT_TYPE_AUTH_PROC_SUSPEND_RESUME:
case ES_EVENT_TYPE_NOTIFY_PROC_SUSPEND_RESUME:
case ES_EVENT_TYPE_NOTIFY_CS_INVALIDATED:
case ES_EVENT_TYPE_NOTIFY_GET_TASK_NAME:
case ES_EVENT_TYPE_NOTIFY_TRACE:
case ES_EVENT_TYPE_NOTIFY_REMOTE_THREAD_CREATE:
case ES_EVENT_TYPE_AUTH_REMOUNT:
case ES_EVENT_TYPE_NOTIFY_REMOUNT: return 4;
// The following events are available beginning in macOS 11.3
case ES_EVENT_TYPE_AUTH_GET_TASK_READ:
case ES_EVENT_TYPE_NOTIFY_GET_TASK_READ:
case ES_EVENT_TYPE_NOTIFY_GET_TASK_INSPECT: return 4;
// The following events are available beginning in macOS 12.0
case ES_EVENT_TYPE_NOTIFY_SETUID:
case ES_EVENT_TYPE_NOTIFY_SETGID:
case ES_EVENT_TYPE_NOTIFY_SETEUID:
case ES_EVENT_TYPE_NOTIFY_SETEGID:
case ES_EVENT_TYPE_NOTIFY_SETREUID:
case ES_EVENT_TYPE_NOTIFY_SETREGID:
case ES_EVENT_TYPE_AUTH_COPYFILE:
case ES_EVENT_TYPE_NOTIFY_COPYFILE: return 4;
#if HAVE_MACOS_13
// The following events are available beginning in macOS 13.0
case ES_EVENT_TYPE_NOTIFY_AUTHENTICATION:
case ES_EVENT_TYPE_NOTIFY_XP_MALWARE_DETECTED:
case ES_EVENT_TYPE_NOTIFY_XP_MALWARE_REMEDIATED:
case ES_EVENT_TYPE_NOTIFY_LW_SESSION_LOGIN:
case ES_EVENT_TYPE_NOTIFY_LW_SESSION_LOGOUT:
case ES_EVENT_TYPE_NOTIFY_LW_SESSION_LOCK:
case ES_EVENT_TYPE_NOTIFY_LW_SESSION_UNLOCK:
case ES_EVENT_TYPE_NOTIFY_SCREENSHARING_ATTACH:
case ES_EVENT_TYPE_NOTIFY_SCREENSHARING_DETACH:
case ES_EVENT_TYPE_NOTIFY_OPENSSH_LOGIN:
case ES_EVENT_TYPE_NOTIFY_OPENSSH_LOGOUT:
case ES_EVENT_TYPE_NOTIFY_LOGIN_LOGIN:
case ES_EVENT_TYPE_NOTIFY_LOGIN_LOGOUT:
case ES_EVENT_TYPE_NOTIFY_BTM_LAUNCH_ITEM_ADD:
case ES_EVENT_TYPE_NOTIFY_BTM_LAUNCH_ITEM_REMOVE: return 6;
#endif
#if HAVE_MACOS_14
// The following events are available beginning in macOS 14.0
case ES_EVENT_TYPE_NOTIFY_PROFILE_ADD:
case ES_EVENT_TYPE_NOTIFY_PROFILE_REMOVE:
case ES_EVENT_TYPE_NOTIFY_SU:
case ES_EVENT_TYPE_NOTIFY_AUTHORIZATION_PETITION:
case ES_EVENT_TYPE_NOTIFY_AUTHORIZATION_JUDGEMENT:
case ES_EVENT_TYPE_NOTIFY_SUDO:
case ES_EVENT_TYPE_NOTIFY_OD_GROUP_ADD:
case ES_EVENT_TYPE_NOTIFY_OD_GROUP_REMOVE:
case ES_EVENT_TYPE_NOTIFY_OD_GROUP_SET:
case ES_EVENT_TYPE_NOTIFY_OD_MODIFY_PASSWORD:
case ES_EVENT_TYPE_NOTIFY_OD_DISABLE_USER:
case ES_EVENT_TYPE_NOTIFY_OD_ENABLE_USER:
case ES_EVENT_TYPE_NOTIFY_OD_ATTRIBUTE_VALUE_ADD:
case ES_EVENT_TYPE_NOTIFY_OD_ATTRIBUTE_VALUE_REMOVE:
case ES_EVENT_TYPE_NOTIFY_OD_ATTRIBUTE_SET:
case ES_EVENT_TYPE_NOTIFY_OD_CREATE_USER:
case ES_EVENT_TYPE_NOTIFY_OD_CREATE_GROUP:
case ES_EVENT_TYPE_NOTIFY_OD_DELETE_USER:
case ES_EVENT_TYPE_NOTIFY_OD_DELETE_GROUP:
case ES_EVENT_TYPE_NOTIFY_XPC_CONNECT: return 7;
#endif
#if HAVE_MACOS_15
case ES_EVENT_TYPE_NOTIFY_GATEKEEPER_USER_OVERRIDE: return 8;
#endif
default: return UINT32_MAX;
}
}

24
Source/common/Unit.h Normal file
View File

@@ -0,0 +1,24 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON__UNIT_H
#define SANTA__COMMON__UNIT_H
namespace santa {
struct Unit {};
} // namespace santa
#endif

View File

@@ -1,144 +1,798 @@
//
// !!! WARNING !!!
// This proto is in beta format and subject to change.
//
// Important: This schema is currently in BETA
syntax = "proto3";
import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
import "Source/santad/ProcessTree/process_tree.proto";
option objc_class_prefix = "SNTPB";
package santa;
package santa.pb.v1;
message ProcessInfo {
// User ID and associated username
message UserInfo {
optional int32 uid = 1;
optional string name = 2;
}
// Group ID and associated group name
message GroupInfo {
optional int32 gid = 1;
optional string name = 2;
}
// A process is uniquely identified on macOS by its pid and pidversion
message ProcessID {
optional int32 pid = 1;
optional int32 pidversion = 2;
optional int32 ppid = 3;
optional int32 uid = 4;
optional string user = 5;
optional int32 gid = 6;
optional string group = 7;
}
message FileModification {
enum Action {
ACTION_UNKNOWN = 0;
ACTION_DELETE = 1;
ACTION_EXCHANGE = 2;
ACTION_LINK = 3;
ACTION_RENAME = 4;
ACTION_WRITE = 5;
// Code signature information
message CodeSignature {
// The code directory hash identifies a specific version of a program
optional bytes cdhash = 1;
// The signing id of the code signature
optional string signing_id = 2;
// The team id of the code signature
optional string team_id = 3;
}
// Stat information for a file
// Mimics data from `stat(2)`
message Stat {
optional int32 dev = 1;
optional uint32 mode = 2;
optional uint32 nlink = 3;
optional uint64 ino = 4;
optional UserInfo user = 5;
optional GroupInfo group = 6;
optional int32 rdev = 7;
optional google.protobuf.Timestamp access_time = 8;
optional google.protobuf.Timestamp modification_time = 9;
optional google.protobuf.Timestamp change_time = 10;
optional google.protobuf.Timestamp birth_time = 11;
optional int64 size = 12;
optional int64 blocks = 13;
optional int32 blksize = 14;
optional uint32 flags = 15;
optional int32 gen = 16;
}
// Hash value and metadata describing hash algorithm used
message Hash {
enum HashAlgo {
HASH_ALGO_UNKNOWN = 0;
HASH_ALGO_SHA256 = 1;
}
optional Action action = 1;
optional string path = 2;
optional string newpath = 3;
optional string process = 4;
optional string process_path = 5;
optional ProcessInfo process_info = 6;
optional string machine_id = 7;
optional HashAlgo type = 1;
optional string hash = 2;
}
// File information
message FileInfo {
// File path
optional string path = 1;
// Whether or not the path is truncated
optional bool truncated = 2;
// Stat information
optional Stat stat = 3;
// Hash of file contents
optional Hash hash = 4;
}
// Light variant of `FileInfo` message to help minimize on-disk/on-wire sizes
message FileInfoLight {
// File path
optional string path = 1;
// Whether or not the path is truncated
optional bool truncated = 2;
}
// File descriptor information
message FileDescriptor {
// Enum types gathered from `<sys/proc_info.h>`
enum FDType {
FD_TYPE_UNKNOWN = 0;
FD_TYPE_ATALK = 1;
FD_TYPE_VNODE = 2;
FD_TYPE_SOCKET = 3;
FD_TYPE_PSHM = 4;
FD_TYPE_PSEM = 5;
FD_TYPE_KQUEUE = 6;
FD_TYPE_PIPE = 7;
FD_TYPE_FSEVENTS = 8;
FD_TYPE_NETPOLICY = 9;
FD_TYPE_CHANNEL = 10;
FD_TYPE_NEXUS = 11;
}
// File descriptor value
optional int32 fd = 1;
// Type of file object
optional FDType fd_type = 2;
// Unique id of the pipe for correlation with other file descriptors
// pointing to the same or other end of the same pipe
// Note: Only valid when `fd_type` is `FD_TYPE_PIPE`
optional uint64 pipe_id = 3;
}
// Process information
message ProcessInfo {
// Process ID of the process
optional ProcessID id = 1;
// Process ID of the parent process
optional ProcessID parent_id = 2;
// Process ID of the process responsible for this one
optional ProcessID responsible_id = 3;
// Original parent ID, remains stable in the event a process is reparented
optional int32 original_parent_pid = 4;
// Process group id the process belongs to
optional int32 group_id = 5;
// Session id the process belongs to
optional int32 session_id = 6;
// Effective user/group info
optional UserInfo effective_user = 7;
optional GroupInfo effective_group = 8;
// Real user/group info
optional UserInfo real_user = 9;
optional GroupInfo real_group = 10;
// Whether or not the process was signed with Apple certificates
optional bool is_platform_binary = 11;
// Whether or not the process is an ES client
optional bool is_es_client = 12;
// Code signature information for the process
optional CodeSignature code_signature = 13;
// Codesigning flags for the process (from `<Kernel/kern/cs_blobs.h>`)
optional uint32 cs_flags = 14;
// File information for the executable backing this process
optional FileInfo executable = 15;
// File information for the associated TTY
optional FileInfoLight tty = 16;
// Time the process was started
optional google.protobuf.Timestamp start_time = 17;
optional process_tree.Annotations annotations = 18;
}
// Light variant of ProcessInfo message to help minimize on-disk/on-wire sizes
message ProcessInfoLight {
// Process ID of the process
optional ProcessID id = 1;
// Process ID of the parent process
optional ProcessID parent_id = 2;
// Original parent ID, remains stable in the event a process is reparented
optional int32 original_parent_pid = 3;
// Process group id the process belongs to
optional int32 group_id = 4;
// Session id the process belongs to
optional int32 session_id = 5;
// Effective user/group info
optional UserInfo effective_user = 6;
optional GroupInfo effective_group = 7;
// Real user/group info
optional UserInfo real_user = 8;
optional GroupInfo real_group = 9;
// File information for the executable backing this process
optional FileInfoLight executable = 10;
optional process_tree.Annotations annotations = 11;
}
// Certificate information
message CertificateInfo {
// Hash of the certificate data
optional Hash hash = 1;
// Common name used in the certificate
optional string common_name = 2;
}
// Information about a single entitlement key/value pair
message Entitlement {
// The name of an entitlement
optional string key = 1;
// The value of an entitlement
optional string value = 2;
}
// Information about entitlements
message EntitlementInfo {
// Whether or not the set of reported entilements is complete or has been
// filtered (e.g. by configuration or clipped because too many to log).
optional bool entitlements_filtered = 1;
// The set of entitlements associated with the target executable
// Only top level keys are represented
// Values (including nested keys) are JSON serialized
repeated Entitlement entitlements = 2;
}
// Information about a process execution event
message Execution {
// The process that executed the new image (e.g. the process that called
// `execve(2)` or `posix_spawn(2)``)
optional ProcessInfoLight instigator = 1;
// Process info for the newly formed execution
optional ProcessInfo target = 2;
// Script file information
// Only valid when a script was executed directly and not as an argument to
// an interpreter (e.g. `./foo.sh`, not `/bin/sh ./foo.sh`)
optional FileInfo script = 3;
// The current working directory of the `target` at exec time
optional FileInfo working_directory = 4;
// List of process arguments
repeated bytes args = 5;
// List of environment variables
repeated bytes envs = 6;
// List of file descriptors
repeated FileDescriptor fds = 7;
// Whether or not the list of `fds` is complete or contains partial info
optional bool fd_list_truncated = 8;
// Whether or not the target execution was allowed
enum Decision {
DECISION_UNKNOWN = 0;
DECISION_ALLOW = 1;
DECISION_DENY = 2;
}
optional Decision decision = 9;
// The policy applied when determining the decision
enum Reason {
REASON_UNKNOWN = 0;
REASON_BINARY = 1;
REASON_CERT = 2;
REASON_COMPILER = 3;
REASON_NOT_RUNNING = 4;
REASON_PENDING_TRANSITIVE = 5;
REASON_SCOPE = 6;
REASON_TEAM_ID = 7;
REASON_TRANSITIVE = 8;
REASON_LONG_PATH = 9;
REASON_NOT_RUNNING = 10;
REASON_SIGNING_ID = 11;
REASON_CDHASH = 12;
}
optional Reason reason = 10;
// The mode Santa was in when the decision was applied
enum Mode {
MODE_UNKNOWN = 0;
MODE_LOCKDOWN = 1;
MODE_MONITOR = 2;
}
optional Mode mode = 11;
optional Decision decision = 1;
optional Reason reason = 2;
optional string explain = 3;
optional string sha256 = 4;
optional string cert_sha256 = 5;
optional string cert_cn = 6;
optional string quarantine_url = 7;
optional ProcessInfo process_info = 8;
optional Mode mode = 9;
optional string path = 10;
optional string original_path = 11;
repeated string args = 12;
optional string machine_id = 13;
optional string team_id = 14;
// Certificate information for the target executable
optional CertificateInfo certificate_info = 12;
// Additional Santa metadata
optional string explain = 13;
// Information known to LaunchServices about the target executable file
optional string quarantine_url = 14;
// The original path on disk of the target executable
// Applies when executables are translocated
optional string original_path = 15;
// Entitlement information about the target executbale
optional EntitlementInfo entitlement_info = 16;
}
message DiskAppeared {
optional string mount = 1;
optional string volume = 2;
optional string bsd_name = 3;
optional string fs = 4;
optional string model = 5;
optional string serial = 6;
optional string bus = 7;
optional string dmg_path = 8;
optional string appearance = 9;
// Information about a fork event
message Fork {
// The forking process
optional ProcessInfoLight instigator = 1;
// The newly formed child process
optional ProcessInfoLight child = 2;
}
message DiskDisappeared {
optional string mount = 1;
optional string volume = 2;
optional string bsd_name = 3;
// Information about an exit event
message Exit {
// The process that is exiting
optional ProcessInfoLight instigator = 1;
// Exit status code information
message Exited {
optional int32 exit_status = 1;
}
// Signal code
message Signaled {
optional int32 signal = 1;
}
// Information on how/why the process exited
oneof ExitType {
Exited exited = 2;
Signaled signaled = 3;
Signaled stopped = 4;
}
}
// Information about an open event
message Open {
// The process that is opening the file
optional ProcessInfoLight instigator = 1;
// The file being opened
optional FileInfo target = 2;
// Bitmask of flags used to open the file
// Note: Represents the mask applied by the kernel, not the typical `open(2)`
// flags (e.g. FREAD, FWRITE instead of O_RDONLY, O_RDWR, etc...)
optional int32 flags = 3;
}
// Information about a close event
message Close {
// The process closing the file
optional ProcessInfoLight instigator = 1;
// The file being closed
optional FileInfo target = 2;
// Whether or not the file was written to
optional bool modified = 3;
}
// Information about an exchagedata event
// This event is not applicable to all filesystems (notably APFS)
message Exchangedata {
// The process that is exchanging the data
optional ProcessInfoLight instigator = 1;
// File information for the two files in the exchangedata operation
optional FileInfo file1 = 2;
optional FileInfo file2 = 3;
}
// Information about a rename event
message Rename {
// The process renaming the file
optional ProcessInfoLight instigator = 1;
// The source file being renamed
optional FileInfo source = 2;
// The target path when the rename is complete
optional string target = 3;
// Whether or not the target path previously existed
optional bool target_existed = 4;
}
// Information about an unlink event
message Unlink {
// The process deleting the file
optional ProcessInfoLight instigator = 1;
// The file being deleted
optional FileInfo target = 2;
}
// Information about a processes codesigning invalidation event
message CodesigningInvalidated {
optional ProcessInfoLight instigator = 1;
}
// Information about a link event
message Link {
// The process performing the link
optional ProcessInfoLight instigator = 1;
// The source file being linked
optional FileInfo source = 2;
// The path of the new link
optional string target = 3;
}
// Information about when disks are added or removed
message Disk {
// Whether the disk just appeared or disappeared from the system
enum Action {
ACTION_UNKNOWN = 0;
ACTION_APPEARED = 1;
ACTION_DISAPPEARED = 2;
}
optional Action action = 1;
// Volume path
optional string mount = 2;
// Volume name
optional string volume = 3;
// Media BSD name
optional string bsd_name = 4;
// Kind of volume
optional string fs = 5;
// Device vendor and model information
optional string model = 6;
// Serial number of the device
optional string serial = 7;
// Device protocol
optional string bus = 8;
// Path of the DMG
optional string dmg_path = 9;
// Time device appeared/disappeared
optional google.protobuf.Timestamp appearance = 10;
// Path mounted from
optional string mount_from = 11;
}
// Information emitted when Santa captures bundle information
message Bundle {
// This is the hash of the file within the bundle that triggered the event
optional string sha256 = 1;
optional Hash file_hash = 1;
// This is the hash of the hashes of all executables in the bundle
optional string bundle_hash = 2;
optional Hash bundle_hash = 2;
// Name of the bundle
optional string bundle_name = 3;
// Bundle identifier
optional string bundle_id = 4;
// Bundle path
optional string bundle_path = 5;
// Path of the file within the bundle that triggered the event
optional string path = 6;
}
message Fork {
optional ProcessInfo process_info = 1;
}
message Exit {
optional ProcessInfo process_info = 1;
}
// Information for a transitive allowlist rule
message Allowlist {
optional int32 pid = 1;
optional int32 pidversion = 2;
optional string path = 3;
optional string sha256 = 4;
// The process that caused the allowlist rule to be generated
optional ProcessInfoLight instigator = 1;
// The file the new allowlist rule applies to
optional FileInfo target = 2;
}
message SantaMessage {
google.protobuf.Timestamp event_time = 1;
// Information about access to a watched path
message FileAccess {
// The process that attempted to access the watched path
optional ProcessInfo instigator = 1;
oneof message {
FileModification file_modification = 2;
Execution execution = 3;
DiskAppeared disk_appeared = 4;
DiskDisappeared disk_disappeared = 5;
Bundle bundle = 6;
Fork fork = 7;
Exit exit = 8;
Allowlist allowlist = 9;
// The path that was accessed
optional FileInfoLight target = 2;
// The version of the policy when the decision was made
optional string policy_version = 3;
// The name of the specific policy that triggered this log
optional string policy_name = 4;
// The event type that attempted to access the watched path
enum AccessType {
ACCESS_TYPE_UNKNOWN = 0;
ACCESS_TYPE_OPEN = 1;
ACCESS_TYPE_RENAME = 2;
ACCESS_TYPE_UNLINK = 3;
ACCESS_TYPE_LINK = 4;
ACCESS_TYPE_CLONE = 5;
ACCESS_TYPE_EXCHANGEDATA = 6;
ACCESS_TYPE_COPYFILE = 7;
ACCESS_TYPE_CREATE = 8;
ACCESS_TYPE_TRUNCATE = 9;
}
optional AccessType access_type = 5;
// Whether the operation was allowed or denied and why
enum PolicyDecision {
POLICY_DECISION_UNKNOWN = 0;
POLICY_DECISION_DENIED = 1;
POLICY_DECISION_DENIED_INVALID_SIGNATURE = 2;
POLICY_DECISION_ALLOWED_AUDIT_ONLY = 3;
}
optional PolicyDecision policy_decision = 6;
}
// Session identifier for a graphical session
// Note: Identifiers are opaque and have no meaning outside of correlating Santa
// events with the same identifier
message GraphicalSession {
optional uint32 id = 1;
}
// Information about a socket address and its type
message SocketAddress {
// The socket address
optional bytes address = 1;
enum Type {
TYPE_UNKNOWN = 0;
TYPE_NONE = 1;
TYPE_IPV4 = 2;
TYPE_IPV6 = 3;
TYPE_NAMED_SOCKET = 4;
}
// The type of the socket address
optional Type type = 2;
}
// Information about a user logging in via loginwindow
message LoginWindowSessionLogin {
// The process that emitted the login event
optional ProcessInfoLight instigator = 1;
// Name of the user logging in
optional UserInfo user = 2;
// Graphical session information for this session
optional GraphicalSession graphical_session = 3;
}
// Information about a user logging out via loginwindow
message LoginWindowSessionLogout {
// The process that emitted the logout event
optional ProcessInfoLight instigator = 1;
// Name of the user logging out
optional UserInfo user = 2;
// Graphical session information for this session
optional GraphicalSession graphical_session = 3;
}
// Information about a user locking their session via loginwindow
message LoginWindowSessionLock {
// The process that emitted the lock event
optional ProcessInfoLight instigator = 1;
// Name of the user locking their session
optional UserInfo user = 2;
// Graphical session information for this session
optional GraphicalSession graphical_session = 3;
}
// Information about a user unlocking their session via loginwindow
message LoginWindowSessionUnlock {
// The process that emitted the unlock event
optional ProcessInfoLight instigator = 1;
// Name of the user unlocking their session
optional UserInfo user = 2;
// Graphical session information for this session
optional GraphicalSession graphical_session = 3;
}
// Information about loginwindow events
message LoginWindowSession {
oneof event {
LoginWindowSessionLogin login = 1;
LoginWindowSessionLogout logout = 2;
LoginWindowSessionLock lock = 3;
LoginWindowSessionUnlock unlock = 4;
}
}
// Information about a login event from the `login(1)` utility
message Login {
// The process that emitted the login event
optional ProcessInfoLight instigator = 1;
// Whether or not the login was successful
optional bool success = 2;
// Login failure message, if applicable
optional bytes failure_message = 3;
// Information about the user that attempted to log in
// Note: `uid` data may not always exist on failed attempts
optional UserInfo user = 4;
}
// Information about a logout event from the `login(1)` utility
message Logout {
// The process that emitted the logout event
optional ProcessInfoLight instigator = 1;
// Information about the user that logged out
optional UserInfo user = 2;
}
// Information about login and logout events from the `login(1)` utility
message LoginLogout {
oneof event {
Login login = 1;
Logout logout = 2;
}
}
// Information related to Screen Sharing attaching to a graphical session
message ScreenSharingAttach {
// The process that emitted the attach event
optional ProcessInfoLight instigator = 1;
// Whether or not the attach was successful
optional bool success = 2;
// Source address information
optional SocketAddress source = 3;
// Apple ID of the viewer
optional bytes viewer = 4;
// Type of authentication used
optional bytes authentication_type = 5;
// User that attempted authentication, if applicable
optional UserInfo authentication_user = 6;
// Username of the loginwindow session, if available
optional UserInfo session_user = 7;
// Whether or not there was an existing session
optional bool existing_session = 8;
// Graphical session information for this session
optional GraphicalSession graphical_session = 9;
}
// Information related to Screen Sharing detaching from a graphical session
message ScreenSharingDetach {
// The process that emitted the detach event
optional ProcessInfoLight instigator = 1;
// Source address information
optional SocketAddress source = 2;
// Apple ID of the viewer
optional bytes viewer = 3;
// Graphical session information for this session
optional GraphicalSession graphical_session = 4;
}
// Information about Screen Sharing attach and detach events
message ScreenSharing {
oneof event {
ScreenSharingAttach attach = 1;
ScreenSharingDetach detach = 2;
}
}
// Information about SSH login events from the macOS OpenSSH implementation
message OpenSSHLogin {
// The process that emitted the login event
optional ProcessInfoLight instigator = 1;
enum Result {
RESULT_UNKNOWN = 0;
RESULT_LOGIN_EXCEED_MAXTRIES = 1;
RESULT_LOGIN_ROOT_DENIED = 2;
RESULT_AUTH_SUCCESS = 3;
RESULT_AUTH_FAIL_NONE = 4;
RESULT_AUTH_FAIL_PASSWD = 5;
RESULT_AUTH_FAIL_KBDINT = 6;
RESULT_AUTH_FAIL_PUBKEY = 7;
RESULT_AUTH_FAIL_HOSTBASED = 8;
RESULT_AUTH_FAIL_GSSAPI = 9;
RESULT_INVALID_USER = 10;
}
// The result of the login attempt
// Note: Successful if type == `RESULT_AUTH_SUCCESS`
optional Result result = 2;
// Source address of the connection
optional SocketAddress source = 3;
// Name of the user that attempted to login
// Note: `uid` data may not always exist on failed attempts
optional UserInfo user = 4;
}
// Information about SSH logout events from the macOS OpenSSH implementation
message OpenSSHLogout {
// The process that emitted the logout event
optional ProcessInfoLight instigator = 1;
// Source address of the connection
optional SocketAddress source = 2;
// Information about the user that logged out
optional UserInfo user = 3;
}
// Information about login/logout events from the macOS OpenSSH implementation
message OpenSSH {
oneof event {
OpenSSHLogin login = 1;
OpenSSHLogout logout = 2;
}
}
// A message encapsulating a single event
message SantaMessage {
// Machine ID of the host emitting this log
// Only valid when EnableMachineIDDecoration configuration option is set
optional string machine_id = 1;
// Timestamp when the event occurred
optional google.protobuf.Timestamp event_time = 2;
// Timestamp when Santa finished processing the event
optional google.protobuf.Timestamp processed_time = 3;
// Event type being described by this message
oneof event {
Execution execution = 10;
Fork fork = 11;
Exit exit = 12;
Close close = 13;
Rename rename = 14;
Unlink unlink = 15;
Link link = 16;
Exchangedata exchangedata = 17;
Disk disk = 18;
Bundle bundle = 19;
Allowlist allowlist = 20;
FileAccess file_access = 21;
CodesigningInvalidated codesigning_invalidated = 22;
LoginWindowSession login_window_session = 23;
LoginLogout login_logout = 24;
ScreenSharing screen_sharing = 25;
OpenSSH open_ssh = 26;
};
}
message SantaMessageBatch {
repeated SantaMessage messages = 1;
}
message LogBatch {

View File

@@ -0,0 +1,20 @@
/// Copyright 2022 Google LLC
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// https://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#ifndef SANTA__COMMON_SANTA_PROTO_INCLUDE_WRAPPER_H
#define SANTA__COMMON_SANTA_PROTO_INCLUDE_WRAPPER_H
#include "Source/common/santa.pb.h"
#endif

View File

@@ -1,4 +1,5 @@
load("@build_bazel_rules_apple//apple:macos.bzl", "macos_application")
load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library")
load("//:helper.bzl", "santa_unit_test")
licenses(["notice"])
@@ -11,6 +12,36 @@ exports_files([
"Resources/Images.xcassets/AppIcon.appiconset/santa-hat-icon-256.png",
])
swift_library(
name = "SNTAboutWindowView",
srcs = ["SNTAboutWindowView.swift"],
generates_header = 1,
deps = ["//Source/common:SNTConfigurator"],
)
swift_library(
name = "SNTDeviceMessageWindowView",
srcs = [
"SNTDeviceMessageWindowView.swift",
],
generates_header = 1,
deps = [
"//Source/common:SNTConfigurator",
"//Source/common:SNTDeviceEvent",
],
)
swift_library(
name = "SNTFileAccessMessageWindowView",
srcs = [
"SNTFileAccessMessageWindowView.swift",
],
generates_header = 1,
deps = [
"//Source/common:SNTFileAccessEvent",
],
)
objc_library(
name = "SantaGUI_lib",
srcs = [
@@ -24,8 +55,8 @@ objc_library(
"SNTBinaryMessageWindowController.m",
"SNTDeviceMessageWindowController.h",
"SNTDeviceMessageWindowController.m",
"SNTMessageWindow.h",
"SNTMessageWindow.m",
"SNTFileAccessMessageWindowController.h",
"SNTFileAccessMessageWindowController.m",
"SNTMessageWindowController.h",
"SNTMessageWindowController.m",
"SNTNotificationManager.h",
@@ -36,8 +67,6 @@ objc_library(
"SNTNotificationManager.h",
],
data = [
"Resources/AboutWindow.xib",
"Resources/DeviceMessageWindow.xib",
"Resources/MessageWindow.xib",
],
sdk_frameworks = [
@@ -47,9 +76,14 @@ objc_library(
"UserNotifications",
],
deps = [
":SNTAboutWindowView",
":SNTDeviceMessageWindowView",
":SNTFileAccessMessageWindowView",
"//Source/common:CertificateHelpers",
"//Source/common:SNTBlockMessage_SantaGUI",
"//Source/common:SNTConfigurator",
"//Source/common:SNTDeviceEvent",
"//Source/common:SNTFileAccessEvent",
"//Source/common:SNTLogging",
"//Source/common:SNTStoredEvent",
"//Source/common:SNTStrengthify",
@@ -85,7 +119,7 @@ macos_application(
"//conditions:default": None,
}),
infoplists = ["Info.plist"],
minimum_os_version = "10.15",
minimum_os_version = "12.0",
provisioning_profile = select({
"//:adhoc_build": None,
"//conditions:default": "//profiles:santa_dev",

Some files were not shown because too many files have changed in this diff Show More