Compare commits

..

180 Commits

Author SHA1 Message Date
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
Pete Markowsky
fd23a5c3b7 Fix up endTimestamp to be Monarch compliant (#879)
Fix up endTimestamp field to be Monarch compliant.
2022-08-16 22:32:29 -04:00
Russell Hancox
ec203e8796 Project: Rename Source/santa -> Source/gui (#877) 2022-08-12 14:19:01 -04:00
Russell Hancox
57ff69208d GUI: Missed a required dependency (#876) 2022-08-12 14:02:22 -04:00
Russell Hancox
f00b7d2ded GUI: Expose SNTNotificationManager.h for the test. (#875) 2022-08-12 13:46:25 -04:00
Russell Hancox
9791fdd53c Project: Add a GH action to prevent trailing whitespace (#873) 2022-08-12 12:46:11 -04:00
Russell Hancox
26e2203f1e GUI: Improve signing chain key reporting in distributed notifications. (#874)
Also add a group for GUI unit_tests and include in the overall project tests group.
2022-08-12 11:03:21 -04:00
Russell Hancox
4a47195d12 Santa: Post distributed notification when showing block UI (#870)
Fixes #869
2022-08-11 12:34:35 -04:00
Russell Hancox
4436e221df GUI: Add silent mode configuration option. (#871)
When enabled, this option disables *all* GUI notifications from Santa. This is intended for kiosk-style machines where it is not expected for users to _ever_ execute unknown binaries.

Fixes #862
2022-08-11 09:17:07 -04:00
Russell Hancox
deccc8a148 GUI: For App Store published apps, include team ID. (#872)
With this change, the publisher field for an App Store published app will be  instead of

Fixes #758
2022-08-11 08:15:42 -04:00
Henry S
06da796a4d Docs: add link to GitHub (#868) 2022-08-08 16:38:34 -04:00
Russell Hancox
7b99a76d0d Docs: Add StaticRules to example mobileconfig (#866) 2022-08-03 10:59:18 -04:00
Pete Markowsky
c2d3e99446 Sync Protocol Docs (#860)
Initial commit of sync protocol docs.
2022-07-28 17:27:43 -04:00
Russell Hancox
6db7fea8ae syncservice: Add tests for NSData+Zlib and Postflight (#864) 2022-07-26 13:05:35 -04:00
Kathryn Hancox
6fcb4cfe63 Docs: Add recommended rollout doc (#861) 2022-07-22 13:50:25 -04:00
bfreezy
8b55ee4da5 santad: only allow root read+write permissions on sync-state.plist (#858) 2022-07-18 13:32:08 -04:00
Russell Hancox
cc3177502c Tests: Fix un-needed expectation in SNTExecutionControllerTest.allEventUpload (#857) 2022-07-15 18:03:34 -04:00
Kathryn Hancox
a49a59b109 Docs: Add sync server list (#856) 2022-07-15 16:19:17 -04:00
Kathryn Hancox
2c06c39c82 Added quick getting started page for deployments (#855) 2022-07-15 15:23:33 -04:00
Pete Markowsky
234f81ea7c Ensure KVO works for USB config options (#853)
Ensure KVO works for USB config options.
2022-07-15 15:13:55 -04:00
Russell Hancox
743c567bf8 santad: Log team ID in execution logs, where available (#850) 2022-07-15 12:41:56 -04:00
Russell Hancox
21220f1499 santad: Add DisableUnknownEventUpload option. (#852) 2022-07-15 12:30:20 -04:00
Russell Hancox
39f3ffe8fc santactl/status: Fix printing of static rules (#848) 2022-07-15 11:53:38 -04:00
Russell Hancox
fdb01928a0 santad: Fix re-establishment of syncservice connection (#849)
* santad: Fix re-establishment of syncservice connection

The previous version could lead to santad having lots of threads stuck waiting for connections
2022-07-15 11:53:17 -04:00
Russell Hancox
fbefbc5910 santasyncservice: Keep XSRF token in memory, don't send to daemon (#851) 2022-07-15 11:52:43 -04:00
Russell Hancox
9db00d143d santad: Improve caching of static rules (#847)
In #846 I forgot that  is only a count of the entries so if the config changes but the number of rules remains the same we would never update the cache. This PR moves the processing of the raw config into the KVO handler code so it is not at all in the hot-path.
2022-07-14 10:50:30 -04:00
Russell Hancox
1cc40d59d8 santad: Allow configuring a static set of rules via configuration profile (#846) 2022-07-13 17:58:13 -04:00
Russell Hancox
ba1ace56f0 Project: Delete tulsiproj, add basic doc about hedron (#845) 2022-07-12 13:53:57 -04:00
Russell Hancox
6d911e9d6e CI: Make CI workflow only run on source changes (#843) 2022-07-08 16:03:30 -04:00
Kathryn Hancox
7e2b291122 Docs: Updated home page with README files & nav changes (#841) 2022-07-08 15:53:16 -04:00
Tom Burgin
64096f5d08 adhoc build and run santa (#840)
* adhoc build and run santa

* fold ci into adhoc

* review updates

Co-authored-by: Tom Burgin <bur@chromium.org>
2022-07-07 17:09:53 -04:00
Matt W
aec1c74fab Use the message copy in the dispatch blocks (#839) 2022-07-06 21:51:02 -04:00
Russell Hancox
d4a0d77cb9 Docs: Add gemfile for running jekyll locally. (#834)
This lets us test docs site changes by running `bundle exec jekyll serve` from inside the docs folder.
2022-07-01 11:06:16 -04:00
Russell Hancox
7df209ed3f Project: Upgrade bazel rules_apple to 1.0.1 release (#830) 2022-06-28 14:23:47 -04:00
np5
b7421e4499 Add team ID to synced events (#827) 2022-06-24 20:00:55 +00:00
Eric Case
e044fe3601 Readme: http -> https link (#829) 2022-06-24 14:34:32 -04:00
425 changed files with 31447 additions and 8646 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,40 @@ build --apple_generate_dsym --define=apple.propagate_embedded_extra_outputs=yes
build --copt=-Werror
build --copt=-Wall
build --copt=-Wno-error=deprecated-declarations
build --per_file_copt=.*\.mm\$@-std=c++17
build --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
5.3.0

View File

@@ -1,13 +1,14 @@
name: Check Markdown links
name: Check Markdown
on:
on:
pull_request:
paths:
- "**.md"
jobs:
markdown-link-check:
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]+$' -- ':(exclude)*.patch'"

View File

@@ -1,51 +1,22 @@
name: CI
on:
push:
branches:
- '*'
paths:
- 'Source/**'
pull_request:
branches:
- main
paths:
- 'Source/**'
jobs:
preqs:
runs-on: ubuntu-latest
outputs:
run_build_and_tests: ${{ steps.step1.outputs.run_build_and_tests }}
steps:
- uses: actions/checkout@v2
- name: Check If We Need to Run Build/Test
id: step1
run: |
git remote add mainline https://github.com/google/santa.git
git fetch mainline main
git diff --name-only mainline/main HEAD > files.txt
echo "FILES CHANGED: $(wc -l ./files.txt)\n"
cat files.txt
build_and_run_tests=0
for file in `cat files.txt`; do
if [[ $file = Source/* ]]; then
build_and_run_test=1;
fi
done
if [[ $build_and_run_test != 0 ]]; then
echo "NEED TO RUN BUILD AND TESTS"
echo "::set-output name=run_build_and_tests::true"
else
echo "::set-output name=run_build_and_tests::false"
fi
lint:
runs-on: ubuntu-latest
needs: [preqs]
if: needs.preqs.outputs.run_build_and_tests == 'true'
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Run linters
run: ./Testing/lint.sh
@@ -53,34 +24,28 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [macos-10.15, macos-11, macos-12]
os: [macos-11, macos-12]
runs-on: ${{ matrix.os }}
needs: [preqs]
if: needs.preqs.outputs.run_build_and_tests == 'true'
steps:
- uses: actions/checkout@v2
- name: Build Userspace
run: bazel build --apple_generate_dsym -c opt :release --define=SANTA_BUILD_TYPE=ci
- uses: 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-11, macos-12]
runs-on: ${{ matrix.os }}
needs: [preqs]
if: needs.preqs.outputs.run_build_and_tests == 'true'
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Run All Tests
run: bazel test :unit_tests --define=SANTA_BUILD_TYPE=ci --test_output=errors
run: bazel test :unit_tests --define=SANTA_BUILD_TYPE=adhoc --test_output=errors
test_coverage:
runs-on: macos-11
needs: [preqs]
if: needs.preqs.outputs.run_build_and_tests == 'true'
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Generate test coverage
run: sh ./generate_cov.sh
- name: Coveralls
@@ -89,12 +54,3 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
path-to-lcov: ./bazel-out/_coverage/_coverage_report.dat
flag-name: Unit
benchmark:
runs-on: macos-11
needs: [preqs]
if: needs.preqs.outputs.run_build_and_tests == 'true'
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=ci
run: bazel test --test_strategy=exclusive --test_output=errors --runs_per_test 50 -t- :unit_tests --define=SANTA_BUILD_TYPE=adhoc

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

@@ -0,0 +1,41 @@
name: E2E
on: workflow_dispatch
jobs:
start_vm:
runs-on: e2e-host
steps:
- uses: actions/checkout@v3
- name: Start VM
run: python3 Testing/integration/actions/start_vm.py macOS_12.bundle.tar.gz
integration:
runs-on: e2e-vm
env:
VM_PASSWORD: ${{ secrets.VM_PASSWORD }}
steps:
- uses: actions/checkout@v3
- name: Install configuration profile
run: bazel run //Testing/integration:install_profile -- Testing/integration/configs/default.mobileconfig
- name: Add homebrew to PATH
run: echo "/opt/homebrew/bin/" >> $GITHUB_PATH
- 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 &
- name: Build, install, and sync santa
run: |
bazel run :reload --define=SANTA_BUILD_TYPE=adhoc
bazel run //Testing/integration:allow_sysex
sudo santactl sync --debug
- name: Run integration test binaries
run: bazel test //Testing/integration:integration_tests
- name: Test config changes
run: ./Testing/integration/test_config_changes.sh
- name: Test sync server changes
run: ./Testing/integration/test_sync_changes.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=errors \
--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*

429
.pylintrc Normal file
View File

@@ -0,0 +1,429 @@
# This Pylint rcfile contains a best-effort configuration to uphold the
# best-practices and style described in the Google Python style guide:
# https://google.github.io/styleguide/pyguide.html
#
# Its canonical open-source location is:
# https://google.github.io/styleguide/pylintrc
[MASTER]
# Files or directories to be skipped. They should be base names, not paths.
ignore=third_party
# Files or directories matching the regex patterns are skipped. The regex
# matches against base names, not paths.
ignore-patterns=
# Pickle collected data for later comparisons.
persistent=no
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Use multiple processes to speed up Pylint.
jobs=4
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
confidence=
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
#enable=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once).You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
disable=abstract-method,
apply-builtin,
arguments-differ,
attribute-defined-outside-init,
backtick,
bad-option-value,
basestring-builtin,
buffer-builtin,
c-extension-no-member,
consider-using-enumerate,
cmp-builtin,
cmp-method,
coerce-builtin,
coerce-method,
delslice-method,
div-method,
duplicate-code,
eq-without-hash,
execfile-builtin,
file-builtin,
filter-builtin-not-iterating,
fixme,
getslice-method,
global-statement,
hex-method,
idiv-method,
implicit-str-concat,
import-error,
import-self,
import-star-module-level,
inconsistent-return-statements,
input-builtin,
intern-builtin,
invalid-str-codec,
locally-disabled,
long-builtin,
long-suffix,
map-builtin-not-iterating,
misplaced-comparison-constant,
missing-function-docstring,
metaclass-assignment,
next-method-called,
next-method-defined,
no-absolute-import,
no-else-break,
no-else-continue,
no-else-raise,
no-else-return,
no-init, # added
no-member,
no-name-in-module,
no-self-use,
nonzero-method,
oct-method,
old-division,
old-ne-operator,
old-octal-literal,
old-raise-syntax,
parameter-unpacking,
print-statement,
raising-string,
range-builtin-not-iterating,
raw_input-builtin,
rdiv-method,
reduce-builtin,
relative-import,
reload-builtin,
round-builtin,
setslice-method,
signature-differs,
standarderror-builtin,
suppressed-message,
sys-max-int,
too-few-public-methods,
too-many-ancestors,
too-many-arguments,
too-many-boolean-expressions,
too-many-branches,
too-many-instance-attributes,
too-many-locals,
too-many-nested-blocks,
too-many-public-methods,
too-many-return-statements,
too-many-statements,
trailing-newlines,
unichr-builtin,
unicode-builtin,
unnecessary-pass,
unpacking-in-except,
useless-else-on-loop,
useless-object-inheritance,
useless-suppression,
using-cmp-argument,
wrong-import-order,
xrange-builtin,
zip-builtin-not-iterating,
[REPORTS]
# Set the output format. Available formats are text, parseable, colorized, msvs
# (visual studio) and html. You can also give a reporter class, eg
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages
reports=no
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details
#msg-template=
[BASIC]
# Good variable names which should always be accepted, separated by a comma
good-names=main,_
# Bad variable names which should always be refused, separated by a comma
bad-names=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Include a hint for the correct naming format with invalid-name
include-naming-hint=no
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
property-classes=abc.abstractproperty,cached_property.cached_property,cached_property.threaded_cached_property,cached_property.cached_property_with_ttl,cached_property.threaded_cached_property_with_ttl
# Regular expression matching correct function names
function-rgx=^(?:(?P<exempt>setUp|tearDown|setUpModule|tearDownModule)|(?P<camel_case>_?[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_?[a-z][a-z0-9_]*))$
# Regular expression matching correct variable names
variable-rgx=^[a-z][a-z0-9_]*$
# Regular expression matching correct constant names
const-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$
# Regular expression matching correct attribute names
attr-rgx=^_{0,2}[a-z][a-z0-9_]*$
# Regular expression matching correct argument names
argument-rgx=^[a-z][a-z0-9_]*$
# Regular expression matching correct class attribute names
class-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$
# Regular expression matching correct inline iteration names
inlinevar-rgx=^[a-z][a-z0-9_]*$
# Regular expression matching correct class names
class-rgx=^_?[A-Z][a-zA-Z0-9]*$
# Regular expression matching correct module names
module-rgx=^(_?[a-z][a-z0-9_]*|__init__)$
# Regular expression matching correct method names
method-rgx=(?x)^(?:(?P<exempt>_[a-z0-9_]+__|runTest|setUp|tearDown|setUpTestCase|tearDownTestCase|setupSelf|tearDownClass|setUpClass|(test|assert)_*[A-Z0-9][a-zA-Z0-9_]*|next)|(?P<camel_case>_{0,2}[A-Z][a-zA-Z0-9_]*)|(?P<snake_case>_{0,2}[a-z][a-z0-9_]*))$
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=(__.*__|main|test.*|.*test|.*Test)$
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=10
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager,contextlib2.contextmanager
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
[FORMAT]
# Maximum number of characters on a single line.
max-line-length=80
# TODO(https://github.com/PyCQA/pylint/issues/3352): Direct pylint to exempt
# lines made too long by directives to pytype.
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=(?x)(
^\s*(\#\ )?<?https?://\S+>?$|
^\s*(from\s+\S+\s+)?import\s+.+$)
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=yes
# Maximum number of lines in a module
max-module-lines=99999
# String used as indentation unit. The internal Google style guide mandates 2
# spaces. Google's externaly-published style guide says 4, consistent with
# PEP 8. Here, we use 2 spaces, for conformity with many open-sourced Google
# projects (like TensorFlow).
indent-string=' '
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=TODO
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=yes
[VARIABLES]
# Tells whether we should check for unused import in __init__ files.
init-import=no
# A regular expression matching the name of dummy variables (i.e. expectedly
# not used).
dummy-variables-rgx=^\*{0,2}(_$|unused_|dummy_)
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,_cb
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six,six.moves,past.builtins,future.builtins,functools
[LOGGING]
# Logging modules to check that the string format arguments are in logging
# function parameter format
logging-modules=logging,absl.logging,tensorflow.io.logging
[SIMILARITIES]
# Minimum lines number of a similarity.
min-similarity-lines=4
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
[SPELLING]
# Spelling dictionary name. Available dictionaries: none. To make it working
# install python-enchant package.
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[IMPORTS]
# Deprecated modules which should not be used, separated by a comma
deprecated-modules=regsub,
TERMIOS,
Bastion,
rexec,
sets
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled)
import-graph=
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled)
ext-import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled)
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant, absl
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls,
class_
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=StandardError,
Exception,
BaseException

21
BUILD
View File

@@ -27,10 +27,11 @@ config_setting(
visibility = [":santa_package_group"],
)
# Used to detect CI builds
# Adhoc signed - provisioning profiles are not used.
# Used for CI runs and dev builds when SIP is disabled.
config_setting(
name = "ci_build",
values = {"define": "SANTA_BUILD_TYPE=ci"},
name = "adhoc_build",
values = {"define": "SANTA_BUILD_TYPE=adhoc"},
visibility = [":santa_package_group"],
)
@@ -73,14 +74,14 @@ launchctl load /Library/LaunchAgents/com.google.santa.plist
run_command(
name = "reload",
srcs = [
"//Source/santa:Santa",
"//Source/gui:Santa",
],
cmd = """
set -e
rm -rf /tmp/bazel_santa_reload
unzip -d /tmp/bazel_santa_reload \
$${BUILD_WORKSPACE_DIRECTORY}/bazel-out/*$(COMPILATION_MODE)*/bin/Source/santa/Santa.zip >/dev/null
$${BUILD_WORKSPACE_DIRECTORY}/bazel-out/*$(COMPILATION_MODE)*/bin/Source/gui/Santa.zip >/dev/null
echo "You may be asked for your password for sudo"
sudo BINARIES=/tmp/bazel_santa_reload CONF=$${BUILD_WORKSPACE_DIRECTORY}/Conf \
$${BUILD_WORKSPACE_DIRECTORY}/Conf/install.sh
@@ -95,7 +96,7 @@ echo "Time to stop being naughty"
genrule(
name = "release",
srcs = [
"//Source/santa:Santa",
"//Source/gui:Santa",
"Conf/install.sh",
"Conf/uninstall.sh",
"Conf/com.google.santa.bundleservice.plist",
@@ -190,16 +191,10 @@ test_suite(
name = "unit_tests",
tests = [
"//Source/common:unit_tests",
"//Source/gui:unit_tests",
"//Source/santactl:unit_tests",
"//Source/santad:unit_tests",
"//Source/santametricservice:unit_tests",
"//Source/santasyncservice:unit_tests",
],
)
test_suite(
name = "benchmarks",
tests = [
"//Source/santad:SNTApplicationBenchmark",
],
)

1
CODEOWNERS Normal file
View File

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

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;
;
}

10
LICENSE
View File

@@ -200,3 +200,13 @@
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.
------------------
Files: Testing/integration/VM/*
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,13 +1,13 @@
# 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 [![CI](https://github.com/google/santa/actions/workflows/ci.yml/badge.svg)](https://github.com/google/santa/actions/workflows/ci.yml)
<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="https://raw.githubusercontent.com/google/santa/main/Source/gui/Resources/Images.xcassets/AppIcon.appiconset/santa-hat-icon-128.png" alt="Santa Icon" />
</p>
Santa is a binary authorization system for macOS. It consists of a system
extension that monitors for executions, a daemon that makes execution decisions
Santa is a binary 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
case of a block decision and a command-line utility for managing the system and
synchronizing the database with a server.
It is named Santa because it keeps track of binaries that are naughty or nice.
@@ -16,7 +16,7 @@ It is named Santa because it keeps track of binaries that are naughty or nice.
The Santa docs are stored in the
[Docs](https://github.com/google/santa/blob/main/docs) directory and published
at http://santa.dev.
at https://santa.dev.
The docs include deployment options, details on how parts of Santa work and
instructions for developing Santa itself.

View File

@@ -1,12 +1,12 @@
# 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
so that we can work on a fix before 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:
available on keyserver.ubuntu.com:
`gpg --keyserver pool.sks-keyservers.net --recv-key 0x92AFE41DAB49BBB6`
`gpg --keyserver keyserver.ubuntu.com --recv-key 0x92AFE41DAB49BBB6`

View File

@@ -1,5 +1,5 @@
load("//:helper.bzl", "santa_unit_test")
load("@rules_proto_grpc//objc:defs.bzl", "objc_proto_library")
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
package(
default_visibility = ["//:santa_package_group"],
@@ -16,26 +16,67 @@ proto_library(
],
)
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",
],
)
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",
],
)
objc_library(
name = "BranchPrediction",
hdrs = ["BranchPrediction.h"],
)
objc_library(
name = "SantaVnode",
hdrs = ["SantaVnode.h"],
)
objc_library(
name = "Platform",
hdrs = ["Platform.h"],
)
objc_library(
name = "SantaVnodeHash",
srcs = ["SantaVnodeHash.mm"],
hdrs = ["SantaVnodeHash.h"],
deps = [
":SantaCache",
":SantaVnode",
],
deps = ["//Source/common:SNTCommon"],
)
objc_library(
@@ -66,11 +107,11 @@ objc_library(
objc_library(
name = "SNTCachedDecision",
srcs = ["SNTCachedDecision.m"],
srcs = ["SNTCachedDecision.mm"],
hdrs = ["SNTCachedDecision.h"],
deps = [
":SNTCommon",
":SNTCommonEnums",
":SantaVnode",
],
)
@@ -78,33 +119,53 @@ 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"],
)
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",
":SNTStrengthify",
":SNTSystemInfo",
],
)
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"],
@@ -116,20 +177,12 @@ objc_library(
srcs = ["SNTFileInfo.m"],
hdrs = ["SNTFileInfo.h"],
deps = [
":SNTLogging",
"@FMDB",
"@MOLCodesignChecker",
],
)
cc_library(
name = "SNTCommon",
hdrs = ["SNTCommon.h"],
defines = [
"TARGET_OS_OSX",
"TARGET_OS_MAC",
],
)
objc_library(
name = "SNTLogging",
srcs = ["SNTLogging.m"],
@@ -137,19 +190,37 @@ 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"],
deps = [":SNTCommonEnums"],
sdk_frameworks = [
"Foundation",
],
deps = [
":SNTCommonEnums",
":SNTSyncConstants",
],
)
santa_unit_test(
name = "SNTRuleTest",
srcs = ["SNTRuleTest.m"],
deps = [":SNTRule"],
)
objc_library(
@@ -167,11 +238,23 @@ cc_library(
hdrs = ["SNTStrengthify.h"],
)
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(
@@ -197,6 +280,10 @@ objc_library(
name = "SNTXPCControlInterface",
srcs = ["SNTXPCControlInterface.m"],
hdrs = ["SNTXPCControlInterface.h"],
defines = select({
"//:adhoc_build": ["SANTAADHOC"],
"//conditions:default": None,
}),
deps = [
":SNTCommonEnums",
":SNTConfigurator",
@@ -241,11 +328,11 @@ objc_library(
srcs = ["SNTXPCUnprivilegedControlInterface.m"],
hdrs = ["SNTXPCUnprivilegedControlInterface.h"],
deps = [
":SNTCommon",
":SNTCommonEnums",
":SNTRule",
":SNTStoredEvent",
":SNTXPCBundleServiceInterface",
":SantaVnode",
"@MOLCertificate",
"@MOLXPCConnection",
],
@@ -267,9 +354,9 @@ santa_unit_test(
)
santa_unit_test(
name = "SNTPrefixTreeTest",
srcs = ["SNTPrefixTreeTest.mm"],
deps = [":SNTPrefixTree"],
name = "PrefixTreeTest",
srcs = ["PrefixTreeTest.mm"],
deps = [":PrefixTree"],
)
santa_unit_test(
@@ -278,13 +365,41 @@ santa_unit_test(
deps = [":SNTMetricSet"],
)
santa_unit_test(
name = "SNTCachedDecisionTest",
srcs = ["SNTCachedDecisionTest.mm"],
deps = [
"//Source/common:SNTCachedDecision",
"//Source/common:TestUtils",
"@OCMock",
],
)
test_suite(
name = "unit_tests",
tests = [
":PrefixTreeTest",
":SNTCachedDecisionTest",
":SNTFileInfoTest",
":SNTKVOManagerTest",
":SNTMetricSetTest",
":SNTPrefixTreeTest",
":SNTRuleTest",
":SantaCacheTest",
],
visibility = ["//:santa_package_group"],
)
objc_library(
name = "TestUtils",
testonly = 1,
srcs = ["TestUtils.mm"],
hdrs = ["TestUtils.h"],
sdk_dylibs = [
"bsm",
],
deps = [
":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

34
Source/common/Platform.h Normal file
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.
#ifndef SANTA__COMMON__PLATFORM_H
#define SANTA__COMMON__PLATFORM_H
#include <Availability.h>
#if defined(MAC_OS_VERSION_12_0) && \
MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_12_0
#define HAVE_MACOS_12 1
#else
#define HAVE_MACOS_12 0
#endif
#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
#endif

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

@@ -0,0 +1,302 @@
/// 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::common {
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;
}
#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);
}
uint32_t NodeCount() {
absl::ReaderMutexLock lock(&lock_);
return node_count_;
}
#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;
}
cur_byte = (uint8_t) * ++p;
} 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::common
#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::common::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

@@ -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,7 +25,9 @@
///
@interface SNTCachedDecision : NSObject
@property santa_vnode_id_t vnodeId;
- (instancetype)initWithEndpointSecurityFile:(const es_file_t *)esFile;
@property SantaVnode vnodeId;
@property SNTEventState decision;
@property NSString *decisionExtra;
@property NSString *sha256;

View File

@@ -1,4 +1,5 @@
/// 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.
@@ -15,4 +16,13 @@
#import "Source/common/SNTCachedDecision.h"
@implementation SNTCachedDecision
- (instancetype)initWithEndpointSecurityFile:(const es_file_t *)esFile {
self = [super init];
if (self) {
_vnodeId = SantaVnode::VnodeForFile(esFile);
}
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,6 +19,23 @@
/// The integer values are also stored in the database and so shouldn't be changed.
///
typedef NS_ENUM(NSInteger, SNTAction) {
SNTActionUnset,
// 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)
typedef NS_ENUM(NSInteger, SNTRuleType) {
SNTRuleTypeUnknown,
@@ -57,6 +74,7 @@ typedef NS_ENUM(NSInteger, SNTEventState) {
SNTEventStateBlockCertificate = 1 << 18,
SNTEventStateBlockScope = 1 << 19,
SNTEventStateBlockTeamID = 1 << 20,
SNTEventStateBlockLongPath = 1 << 21,
// Bits 24-31 store allow decision types
SNTEventStateAllowUnknown = 1 << 24,
@@ -117,8 +135,18 @@ typedef NS_ENUM(NSInteger, SNTMetricFormatType) {
SNTMetricFormatTypeMonarchJSON,
};
#ifdef __cplusplus
enum class FileAccessPolicyDecision {
kNoPolicy,
kDenied,
kDeniedInvalidSignature,
kAllowed,
kAllowedReadAccess,
kAllowedAuditOnly,
};
#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.
@@ -16,6 +16,8 @@
#import "Source/common/SNTCommonEnums.h"
@class SNTRule;
///
/// Singleton that provides an interface for managing configuration values on disk
/// @note This class is designed as a singleton but that is not strictly enforced.
@@ -46,6 +48,33 @@
///
@property(readonly, nonatomic) BOOL failClosed;
///
/// A set of static rules that should always apply. These can be used as a
/// fallback set of rules for management tools that should always be allowed to
/// run even if a sync server does something unexpected. It can also be used
/// as the sole source of rules, distributed with an MDM.
///
/// The value of this key should be an array containing dictionaries. Each
/// dictionary should contain the same keys used for syncing, e.g:
///
/// <key>StaticRules</key>
/// <array>
/// <dict>
/// <key>identifier</key>
/// <string>binary sha256, certificate sha256, team ID</string>
/// <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)
/// </dict>
/// </array>
///
/// The return of this property is a dictionary where the keys are the
/// identifiers of each rule, with the SNTRule as a value
///
@property(readonly, nonatomic) NSDictionary<NSString *, SNTRule *> *staticRules;
///
/// The regex of allowed paths. Regexes are specified in ICU format.
///
@@ -154,10 +183,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.
///
@@ -165,6 +194,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.
@@ -174,40 +210,67 @@
@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;
///
/// 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
@@ -216,17 +279,18 @@
///
@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
///
/// When silent mode is enabled, Santa will never show notifications for
/// blocked processes.
///
/// This can be a very confusing experience for users, use with caution.
///
/// Defaults to NO.
///
@property(readonly, nonatomic) BOOL enableSilentMode;
///
/// The text to display when opening Santa.app.
/// If unset, the default text will be displayed.
@@ -349,12 +413,6 @@
///
@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.
///
@property(readonly, nonatomic) NSString *usbBlockMessage;
///
/// If set, this over-rides the default machine ID used for syncing.
///
@@ -423,6 +481,11 @@
///
@property(nonatomic) BOOL enableAllEventUpload;
///
/// If true, events will *not* be uploaded for ALLOW_UNKNOWN events for clients in Monitor mode.
///
@property(nonatomic) BOOL disableUnknownEventUpload;
///
/// If true, forks and exits will be logged. Defaults to false.
///

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.
@@ -16,6 +16,7 @@
#include <sys/stat.h>
#import "Source/common/SNTRule.h"
#import "Source/common/SNTStrengthify.h"
#import "Source/common/SNTSystemInfo.h"
@@ -33,6 +34,10 @@
/// Was --debug passed as an argument to this process?
@property(readonly, nonatomic) BOOL debugFlag;
/// Holds the last processed hash of the static rules list.
@property(atomic) NSDictionary *cachedStaticRules;
@end
@implementation SNTConfigurator
@@ -40,10 +45,15 @@
/// 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 kSyncProxyConfigKey = @"SyncProxyConfiguration";
static NSString *const kSyncEnableCleanSyncEventUpload = @"SyncEnableCleanSyncEventUpload";
@@ -61,7 +71,8 @@ static NSString *const kMachineOwnerPlistKeyKey = @"MachineOwnerKey";
static NSString *const kMachineIDPlistFileKey = @"MachineIDPlist";
static NSString *const kMachineIDPlistKeyKey = @"MachineIDKey";
static NSString *const kAboutText = @"AboutText";
static NSString *const kEnableSilentModeKey = @"EnableSilentMode";
static NSString *const kAboutTextKey = @"AboutText";
static NSString *const kMoreInfoURLKey = @"MoreInfoURL";
static NSString *const kEventDetailURLKey = @"EventDetailURL";
static NSString *const kEventDetailTextKey = @"EventDetailText";
@@ -81,15 +92,17 @@ 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 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";
@@ -113,6 +126,7 @@ 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";
@@ -166,7 +180,8 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
kRemountUSBModeKey : array,
kEnablePageZeroProtectionKey : number,
kEnableBadSignatureProtectionKey : number,
kAboutText : string,
kEnableSilentModeKey : number,
kAboutTextKey : string,
kMoreInfoURLKey : string,
kEventDetailURLKey : string,
kEventDetailTextKey : string,
@@ -176,6 +191,7 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
kRemountUSBBlockMessage : string,
kModeNotificationMonitor : string,
kModeNotificationLockdown : string,
kStaticRules : array,
kSyncBaseURLKey : string,
kSyncProxyConfigKey : dictionary,
kClientAuthCertificateFileKey : string,
@@ -192,12 +208,14 @@ 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,
kFileAccessPolicyUpdateIntervalSec : number,
kEnableMachineIDDecoration : number,
kEnableSysxCache : number,
kEnableForkAndExitLogging : number,
kIgnoreOtherEndpointSecurityClients : number,
kEnableDebugLogging : number,
@@ -211,10 +229,12 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
kMetricExportTimeout : number,
kMetricExtraLabels : dictionary,
kEnableAllEventUploadKey : number,
kDisableUnknownEventUploadKey : number,
};
_defaults = [NSUserDefaults standardUserDefaults];
[_defaults addSuiteNamed:@"com.google.santa"];
_configState = [self readForcedConfig];
[self cacheStaticRules];
_syncState = [self readSyncStateFromDisk] ?: [NSMutableDictionary dictionary];
_debugFlag = [[NSProcessInfo processInfo].arguments containsObject:@"--debug"];
[self startWatchingDefaults];
@@ -224,7 +244,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, ^{
@@ -282,6 +305,10 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingStaticRules {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingSyncBaseURL {
return [self configStateSet];
}
@@ -290,6 +317,10 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEnableSilentMode {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingAboutText {
return [self configStateSet];
}
@@ -374,19 +405,31 @@ 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 *)keyPathsForValuesAffectingFileAccessPolicyUpdateIntervalSec {
return [self configStateSet];
}
@@ -402,8 +445,8 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self syncAndConfigStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEnableSysxCache {
return [self configStateSet];
+ (NSSet *)keyPathsForValuesAffectingDisableUnknownEventUpload {
return [self syncAndConfigStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingEnableForkAndExitLogging {
@@ -442,6 +485,26 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingBlockUSBMount {
return [self syncAndConfigStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingBannedUSBBlockMessage {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingRemountUSBMode {
return [self syncAndConfigStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingRemountUSBBlockMessage {
return [self configStateSet];
}
+ (NSSet *)keyPathsForValuesAffectingUsbBlockMessage {
return [self configStateSet];
}
#pragma mark Public Interface
- (SNTClientMode)clientMode {
@@ -540,7 +603,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;
@@ -549,6 +615,10 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return args;
}
- (NSDictionary<NSString *, SNTRule *> *)staticRules {
return self.cachedStaticRules;
}
- (NSURL *)syncBaseURL {
NSString *urlString = self.configState[kSyncBaseURLKey];
if (![urlString hasSuffix:@"/"]) urlString = [urlString stringByAppendingString:@"/"];
@@ -570,8 +640,13 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
return number ? [number boolValue] : NO;
}
- (BOOL)enableSilentMode {
NSNumber *number = self.configState[kEnableSilentModeKey];
return number ? [number boolValue] : NO;
}
- (NSString *)aboutText {
return self.configState[kAboutText];
return self.configState[kAboutTextKey];
}
- (NSURL *)moreInfoURL {
@@ -710,30 +785,53 @@ 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];
}
}
- (uint32_t)fileAccessPolicyUpdateIntervalSec {
return self.configState[kFileAccessPolicyUpdateIntervalSec]
? [self.configState[kFileAccessPolicyUpdateIntervalSec] unsignedIntValue]
: 60 * 10;
}
- (BOOL)enableMachineIDDecoration {
@@ -741,11 +839,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;
@@ -762,6 +855,17 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
[self updateSyncStateForKey:kEnableAllEventUploadKey value:@(enabled)];
}
- (BOOL)disableUnknownEventUpload {
NSNumber *n = self.syncState[kDisableUnknownEventUploadKey];
if (n) return [n boolValue];
return [self.configState[kDisableUnknownEventUploadKey] boolValue];
}
- (void)setDisableUnknownEventUpload:(BOOL)enabled {
[self updateSyncStateForKey:kDisableUnknownEventUploadKey value:@(enabled)];
}
- (BOOL)enableForkAndExitLogging {
NSNumber *number = self.configState[kEnableForkAndExitLogging];
return number ? [number boolValue] : NO;
@@ -803,8 +907,10 @@ 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];
}
///
@@ -907,7 +1013,7 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
syncState[kAllowedPathRegexKey] = [syncState[kAllowedPathRegexKey] pattern];
syncState[kBlockedPathRegexKey] = [syncState[kBlockedPathRegexKey] pattern];
[syncState writeToFile:kSyncStateFilePath atomically:YES];
[[NSFileManager defaultManager] setAttributes:@{NSFilePosixPermissions : @0644}
[[NSFileManager defaultManager] setAttributes:@{NSFilePosixPermissions : @0600}
ofItemAtPath:kSyncStateFilePath
error:NULL];
}
@@ -935,6 +1041,18 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
forcedConfig[key] = [self expressionForPattern:pattern];
}
}
#ifdef DEBUG
NSDictionary *overrides = [NSDictionary dictionaryWithContentsOfFile:kConfigOverrideFilePath];
for (NSString *key in overrides) {
id obj = overrides[key];
if (![obj isKindOfClass:self.forcedConfigKeyTypes[key]]) continue;
forcedConfig[key] = obj;
if (self.forcedConfigKeyTypes[key] == [NSRegularExpression class]) {
NSString *pattern = [obj isKindOfClass:[NSString class]] ? obj : nil;
forcedConfig[key] = [self expressionForPattern:pattern];
}
}
#endif
return forcedConfig;
}
@@ -951,12 +1069,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];
}
///
@@ -964,6 +1120,25 @@ static NSString *const kSyncCleanRequired = @"SyncCleanRequired";
///
- (void)handleChange {
self.configState = [self readForcedConfig];
[self cacheStaticRules];
}
///
/// Processes the StaticRules key to create SNTRule objects and caches them for quick use
///
- (void)cacheStaticRules {
NSArray *staticRules = self.configState[kStaticRules];
if (![staticRules isKindOfClass:[NSArray class]]) return;
NSMutableDictionary<NSString *, SNTRule *> *rules =
[NSMutableDictionary dictionaryWithCapacity:staticRules.count];
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];
}
@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,6 +12,7 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import <EndpointSecurity/EndpointSecurity.h>
#import <Foundation/Foundation.h>
@class MOLCodesignChecker;
@@ -32,6 +33,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.
///

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
@@ -48,6 +50,7 @@
@property NSFileHandle *fileHandle;
@property NSUInteger fileSize;
@property NSString *fileOwnerHomeDir;
@property NSString *sha256Storage;
// Cached properties
@property NSBundle *bundleRef;
@@ -63,6 +66,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 +99,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 +109,12 @@ extern NSString *const NSURLQuarantinePropertiesKey WEAK_IMPORT_ATTRIBUTE;
return nil;
}
_fileSize = fileStat.st_size;
_fileSize = fileStat->st_size;
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 +235,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
@@ -547,6 +572,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 +646,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 paramter 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

@@ -108,6 +108,11 @@ NSString *SNTMetricMakeStringFromMetricType(SNTMetricType metricType);
*/
+ (instancetype)sharedInstance;
/**
* Resets all the metrics in this set. Intended only for testing.
*/
- (void)reset;
/**
* Add a root label to the MetricSet.
*/

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;
}
@@ -485,6 +482,10 @@ NSString *SNTMetricMakeStringFromMetricType(SNTMetricType metricType) {
return self;
}
- (void)reset {
_metrics = [[NSMutableDictionary alloc] init];
}
- (void)addRootLabel:(NSString *)label value:(NSString *)value {
@synchronized(self) {
_rootLabels[label] = value;

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.
@@ -51,18 +51,23 @@
/// 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.
///
- (instancetype)initWithDictionary:(NSDictionary *)dict;
///
/// Sets timestamp of rule to the current time.

View File

@@ -13,6 +13,7 @@
/// limitations under the License.
#import "Source/common/SNTRule.h"
#import "Source/common/SNTSyncConstants.h"
@interface SNTRule ()
@property(readwrite) NSUInteger timestamp;
@@ -32,6 +33,15 @@
_type = type;
_customMsg = customMsg;
_timestamp = timestamp;
if (_type == SNTRuleTypeBinary || _type == SNTRuleTypeCertificate) {
NSCharacterSet *nonHex =
[[NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEF"] invertedSet];
if ([[_identifier uppercaseString] stringByTrimmingCharactersInSet:nonHex].length != 64)
return nil;
} else if (_identifier.length == 0) {
return nil;
}
}
return self;
}
@@ -48,6 +58,60 @@
return self;
}
// Converts rule information downloaded from the server into a SNTRule. Because any information
// not recorded by SNTRule is thrown away here, this method is also responsible for dealing with
// the extra bundle rule information (bundle_hash & rule_count).
- (instancetype)initWithDictionary:(NSDictionary *)dict {
if (![dict isKindOfClass:[NSDictionary class]]) return nil;
NSString *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];
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 {
return nil;
}
NSString *customMsg = dict[kRuleCustomMsg];
if (![customMsg isKindOfClass:[NSString class]] || customMsg.length == 0) {
customMsg = nil;
}
return [self initWithIdentifier:identifier state:state type:type customMsg:customMsg];
}
#pragma mark NSSecureCoding
#pragma clang diagnostic push

126
Source/common/SNTRuleTest.m Normal file
View File

@@ -0,0 +1,126 @@
/// 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/SNTRule.h"
@interface SNTRuleTest : XCTestCase
@end
@implementation SNTRuleTest
- (void)testInitWithDictionaryValid {
SNTRule *sut;
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"BINARY",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier,
@"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670");
XCTAssertEqual(sut.type, SNTRuleTypeBinary);
XCTAssertEqual(sut.state, SNTRuleStateAllow);
sut = [[SNTRule alloc] initWithDictionary:@{
@"sha256" : @"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670",
@"policy" : @"BLOCKLIST",
@"rule_type" : @"CERTIFICATE",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier,
@"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670");
XCTAssertEqual(sut.type, SNTRuleTypeCertificate);
XCTAssertEqual(sut.state, SNTRuleStateBlock);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"some-sort-of-identifier",
@"policy" : @"SILENT_BLOCKLIST",
@"rule_type" : @"TEAMID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqual(sut.type, SNTRuleTypeTeamID);
XCTAssertEqual(sut.state, SNTRuleStateSilentBlock);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670",
@"policy" : @"ALLOWLIST_COMPILER",
@"rule_type" : @"BINARY",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier,
@"b7c1e3fd640c5f211c89b02c2c6122f78ce322aa5c56eb0bb54bc422a8f8b670");
XCTAssertEqual(sut.type, SNTRuleTypeBinary);
XCTAssertEqual(sut.state, SNTRuleStateAllowCompiler);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"some-sort-of-identifier",
@"policy" : @"REMOVE",
@"rule_type" : @"TEAMID",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqual(sut.type, SNTRuleTypeTeamID);
XCTAssertEqual(sut.state, SNTRuleStateRemove);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"some-sort-of-identifier",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"TEAMID",
@"custom_msg" : @"A custom block message",
}];
XCTAssertNotNil(sut);
XCTAssertEqualObjects(sut.identifier, @"some-sort-of-identifier");
XCTAssertEqual(sut.type, SNTRuleTypeTeamID);
XCTAssertEqual(sut.state, SNTRuleStateAllow);
XCTAssertEqualObjects(sut.customMsg, @"A custom block message");
}
- (void)testInitWithDictionaryInvalid {
SNTRule *sut;
sut = [[SNTRule alloc] initWithDictionary:@{}];
XCTAssertNil(sut);
sut = [[SNTRule alloc] initWithDictionary:@{
@"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",
}];
XCTAssertNil(sut);
sut = [[SNTRule alloc] initWithDictionary:@{
@"identifier" : @"an-identifier",
@"policy" : @"ALLOWLIST",
@"rule_type" : @"OTHER_RULE_TYPE",
}];
XCTAssertNil(sut);
}
@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,6 +95,11 @@
///
@property NSArray *signingChain;
///
/// If the executed file was signed, this is the Team ID if present in the signature information.
///
@property NSString *teamID;
///
/// The user who executed the binary.
///

View File

@@ -49,6 +49,7 @@
ENCODE(self.fileBundleVersionString, @"fileBundleVersionString");
ENCODE(self.signingChain, @"signingChain");
ENCODE(self.teamID, @"teamID");
ENCODE(self.executingUser, @"executingUser");
ENCODE(self.occurrenceDate, @"occurrenceDate");
@@ -93,6 +94,7 @@
_fileBundleVersionString = DECODE(NSString, @"fileBundleVersionString");
_signingChain = DECODEARRAY(MOLCertificate, @"signingChain");
_teamID = DECODE(NSString, @"teamID");
_executingUser = DECODE(NSString, @"executingUser");
_occurrenceDate = DECODE(NSDate, @"occurrenceDate");

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;
@@ -51,6 +52,7 @@ extern NSString *const kEnableTransitiveRules;
extern NSString *const kEnableTransitiveRulesDeprecated;
extern NSString *const kEnableTransitiveRulesSuperDeprecated;
extern NSString *const kEnableAllEventUpload;
extern NSString *const kDisableUnknownEventUpload;
extern NSString *const kEvents;
extern NSString *const kFileSHA256;
@@ -92,6 +94,7 @@ extern NSString *const kCertOrg;
extern NSString *const kCertOU;
extern NSString *const kCertValidFrom;
extern NSString *const kCertValidUntil;
extern NSString *const kTeamID;
extern NSString *const kQuarantineDataURL;
extern NSString *const kQuarantineRefererURL;
extern NSString *const kQuarantineTimestamp;

View File

@@ -12,9 +12,10 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "SNTSyncConstants.h"
#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";
@@ -52,6 +53,7 @@ NSString *const kEnableTransitiveRules = @"enable_transitive_rules";
NSString *const kEnableTransitiveRulesDeprecated = @"enabled_transitive_whitelisting";
NSString *const kEnableTransitiveRulesSuperDeprecated = @"transitive_whitelisting_enabled";
NSString *const kEnableAllEventUpload = @"enable_all_event_upload";
NSString *const kDisableUnknownEventUpload = @"disable_unknown_event_upload";
NSString *const kEvents = @"events";
NSString *const kFileSHA256 = @"file_sha256";
@@ -93,6 +95,7 @@ NSString *const kCertOrg = @"org";
NSString *const kCertOU = @"ou";
NSString *const kCertValidFrom = @"valid_from";
NSString *const kCertValidUntil = @"valid_until";
NSString *const kTeamID = @"team_id";
NSString *const kQuarantineDataURL = @"quarantine_data_url";
NSString *const kQuarantineRefererURL = @"quarantine_referer_url";
NSString *const kQuarantineTimestamp = @"quarantine_timestamp";

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(

View File

@@ -20,7 +20,7 @@
@protocol SNTDaemonControlXPC <SNTUnprivilegedDaemonControlXPC>
///
/// Kernel ops
/// Cache ops
///
- (void)flushCache:(void (^)(BOOL))reply;
@@ -41,7 +41,6 @@
/// Config ops
///
- (void)setClientMode:(SNTClientMode)mode reply:(void (^)(void))reply;
- (void)setXsrfToken:(NSString *)token 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;
@@ -52,6 +51,7 @@
- (void)setEnableBundles:(BOOL)bundlesEnabled reply:(void (^)(void))reply;
- (void)setEnableTransitiveRules:(BOOL)enabled reply:(void (^)(void))reply;
- (void)setEnableAllEventUpload:(BOOL)enabled reply:(void (^)(void))reply;
- (void)setDisableUnknownEventUpload:(BOOL)enabled reply:(void (^)(void))reply;
///
/// Syncd Ops

View File

@@ -27,10 +27,16 @@ NSString *const kBundleID = @"com.google.santa.daemon";
@implementation SNTXPCControlInterface
+ (NSString *)serviceID {
#ifdef SANTAADHOC
// The mach service for an adhoc signed ES sysx uses the "endpoint-security" prefix instead of
// the teamid. In Santa's case it will be endpoint-security.com.google.santa.daemon.xpc.
return [NSString stringWithFormat:@"endpoint-security.%@.xpc", kBundleID];
#else
MOLCodesignChecker *cs = [[MOLCodesignChecker alloc] initWithSelf];
// "teamid.com.google.santa.daemon.xpc"
NSString *t = cs.signingInformation[@"teamid"];
return [NSString stringWithFormat:@"%@.%@.xpc", t, kBundleID];
#endif
}
+ (NSString *)systemExtensionID {

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,7 +16,7 @@
#import <MOLCertificate/MOLCertificate.h>
#import "Source/common/SNTCommonEnums.h"
#import "Source/common/SNTCommon.h"
#import "Source/common/SantaVnode.h"
@class SNTRule;
@class SNTStoredEvent;
@@ -31,8 +31,7 @@
/// 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
@@ -40,6 +39,7 @@
- (void)databaseRuleCounts:(void (^)(int64_t binary, int64_t certificate, int64_t compiler,
int64_t transitive, int64_t teamID))reply;
- (void)databaseEventCount:(void (^)(int64_t count))reply;
- (void)staticRuleCount:(void (^)(int64_t count))reply;
///
/// Decision ops
@@ -63,7 +63,7 @@
/// Config ops
///
- (void)watchdogInfo:(void (^)(uint64_t, uint64_t, double, double))reply;
- (void)xsrfToken:(void (^)(NSString *))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;

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"
@@ -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

@@ -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,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),
};
}

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

@@ -0,0 +1,75 @@
/// 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>
#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 XCTAssertSemaTrue(s, sec, m) \
XCTAssertEqual( \
0, dispatch_semaphore_wait((s), dispatch_time(DISPATCH_TIME_NOW, (sec)*NSEC_PER_SEC)), m)
// Helper to ensure at least `ms` milliseconds are slept, even if the sleep
// function returns early due to interrupts.
void SleepMS(long ms);
enum class ActionType {
Auth,
Notify,
};
//
// Helpers to construct various ES structs
//
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 = {});
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();
#endif

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

@@ -0,0 +1,128 @@
/// 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/SystemResources.h"
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 = strlen(s),
.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,
};
}
uint32_t MaxSupportedESMessageVersionForCurrentOS() {
// Note: ES message v3 was only in betas.
if (@available(macOS 13.0, *)) {
return 6;
} else if (@available(macOS 12.3, *)) {
return 5;
} else if (@available(macOS 11.0, *)) {
return 4;
} else if (@available(macOS 10.15.4, *)) {
return 2;
} else {
return 1;
}
}
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);
}
}

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::common {
struct Unit {};
} // namespace santa::common
#endif

View File

@@ -1,7 +1,4 @@
//
// !!! WARNING !!!
// This proto is in beta format and subject to change.
//
// Important: This schema is currently in BETA
syntax = "proto3";
@@ -10,134 +7,529 @@ import "google/protobuf/timestamp.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;
}
// 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;
}
// 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 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;
}
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;
// 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;
}
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 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;
}
// 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;
}
// 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;
};
}
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,6 @@
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"])
@@ -10,6 +12,25 @@ 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",
],
)
objc_library(
name = "SantaGUI_lib",
srcs = [
@@ -23,17 +44,16 @@ objc_library(
"SNTBinaryMessageWindowController.m",
"SNTDeviceMessageWindowController.h",
"SNTDeviceMessageWindowController.m",
"SNTMessageWindow.h",
"SNTMessageWindow.m",
"SNTMessageWindowController.h",
"SNTMessageWindowController.m",
"SNTNotificationManager.h",
"SNTNotificationManager.m",
"main.m",
],
hdrs = [
"SNTNotificationManager.h",
],
data = [
"Resources/AboutWindow.xib",
"Resources/DeviceMessageWindow.xib",
"Resources/MessageWindow.xib",
],
sdk_frameworks = [
@@ -43,12 +63,15 @@ objc_library(
"UserNotifications",
],
deps = [
":SNTAboutWindowView",
":SNTDeviceMessageWindowView",
"//Source/common:SNTBlockMessage_SantaGUI",
"//Source/common:SNTConfigurator",
"//Source/common:SNTDeviceEvent",
"//Source/common:SNTLogging",
"//Source/common:SNTStoredEvent",
"//Source/common:SNTStrengthify",
"//Source/common:SNTSyncConstants",
"//Source/common:SNTXPCControlInterface",
"//Source/common:SNTXPCNotifierInterface",
"@MOLCertificate",
@@ -74,14 +97,41 @@ macos_application(
"--force",
"--options library,kill,runtime",
],
entitlements = "Santa.app.entitlements",
entitlements = select({
"//:adhoc_build": "Santa.app-adhoc.entitlements",
# Non-adhoc builds get thier entitlements from the provisioning profile.
"//conditions:default": None,
}),
infoplists = ["Info.plist"],
minimum_os_version = "10.15",
minimum_os_version = "11.0",
provisioning_profile = select({
"//:ci_build": None,
"//:adhoc_build": None,
"//conditions:default": "//profiles:santa_dev",
}),
version = "//:version",
visibility = ["//:santa_package_group"],
deps = [":SantaGUI_lib"],
)
santa_unit_test(
name = "SNTNotificationManagerTest",
srcs = [
"SNTNotificationManagerTest.m",
],
sdk_frameworks = [
"Cocoa",
],
deps = [
":SantaGUI_lib",
"//Source/common:SNTStoredEvent",
"@OCMock",
],
)
test_suite(
name = "unit_tests",
tests = [
":SNTNotificationManagerTest",
],
visibility = ["//:santa_package_group"],
)

View File

@@ -14,11 +14,5 @@
#import <Cocoa/Cocoa.h>
@interface SNTAboutWindowController : NSWindowController
@property IBOutlet NSTextField *aboutTextField;
@property IBOutlet NSButton *moreInfoButton;
- (IBAction)openMoreInfoURL:(id)sender;
@interface SNTAboutWindowController : NSWindowController <NSWindowDelegate>
@end

View File

@@ -0,0 +1,47 @@
/// 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.
#import "Source/gui/SNTAboutWindowController.h"
#import "Source/gui/SNTAboutWindowView-Swift.h"
#import "Source/common/SNTConfigurator.h"
@implementation SNTAboutWindowController
- (void)showWindow:(id)sender {
[super showWindow:sender];
if (self.window) [self.window orderOut:sender];
self.window =
[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 0, 0)
styleMask:NSWindowStyleMaskClosable | NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
self.window.contentViewController = [SNTAboutWindowViewFactory createWithWindow:self.window];
self.window.title = @"Santa";
self.window.delegate = self;
[self.window makeKeyAndOrderFront:nil];
[self.window center];
// Add app to Cmd+Tab and Dock.
NSApp.activationPolicy = NSApplicationActivationPolicyRegular;
}
- (void)windowWillClose:(NSNotification *)notification {
// Remove app from Cmd+Tab and Dock.
NSApp.activationPolicy = NSApplicationActivationPolicyAccessory;
}
@end

View File

@@ -0,0 +1,63 @@
import SwiftUI
import santa_common_SNTConfigurator
@objc public class SNTAboutWindowViewFactory : NSObject {
@objc public static func createWith(window: NSWindow) -> NSViewController {
return NSHostingController(rootView:SNTAboutWindowView(w:window).frame(width:400, height:200))
}
}
struct SNTAboutWindowView: View {
let w: NSWindow?
let c = SNTConfigurator()
var body: some View {
VStack(spacing:20.0) {
Text("Santa").font(Font.custom("HelveticaNeue-UltraLight", size: 34.0))
if let t = c.aboutText {
Text(t).multilineTextAlignment(.center)
} else {
Text("""
Santa is an application control system for macOS.
There are no user-configurable settings.
""").multilineTextAlignment(.center)
}
HStack {
if c.moreInfoURL?.absoluteString.isEmpty == false {
Button(action: moreInfoButton) {
Text("More Info...").frame(width: 90.0)
}
}
Button(action: dismissButton) {
Text("Dismiss").frame(width: 90.0)
}
.keyboardShortcut(.defaultAction)
}.padding(10.0)
}
}
func dismissButton() {
w?.close()
}
func moreInfoButton() {
if let u = c.moreInfoURL {
NSWorkspace.shared.open(u)
}
w?.close()
}
}
// Enable previews in Xcode.
struct SNTAboutWindow_Previews: PreviewProvider {
static var previews: some View {
SNTAboutWindowView(w: nil)
}
}

View File

@@ -12,7 +12,7 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/santa/SNTAccessibleTextField.h"
#import "Source/gui/SNTAccessibleTextField.h"
@implementation SNTAccessibleTextField

View File

@@ -12,7 +12,7 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/santa/SNTAppDelegate.h"
#import "Source/gui/SNTAppDelegate.h"
#import <MOLXPCConnection/MOLXPCConnection.h>
@@ -20,8 +20,8 @@
#import "Source/common/SNTLogging.h"
#import "Source/common/SNTStrengthify.h"
#import "Source/common/SNTXPCControlInterface.h"
#import "Source/santa/SNTAboutWindowController.h"
#import "Source/santa/SNTNotificationManager.h"
#import "Source/gui/SNTAboutWindowController.h"
#import "Source/gui/SNTNotificationManager.h"
@interface SNTAppDelegate ()
@property SNTAboutWindowController *aboutWindowController;
@@ -58,7 +58,9 @@
}
- (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag {
self.aboutWindowController = [[SNTAboutWindowController alloc] init];
if (!self.aboutWindowController) {
self.aboutWindowController = [[SNTAboutWindowController alloc] init];
}
[self.aboutWindowController showWindow:self];
return NO;
}

View File

@@ -14,7 +14,7 @@
#import <Cocoa/Cocoa.h>
#import "Source/santa/SNTMessageWindowController.h"
#import "Source/gui/SNTMessageWindowController.h"
@class SNTStoredEvent;

View File

@@ -12,7 +12,7 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/santa/SNTBinaryMessageWindowController.h"
#import "Source/gui/SNTBinaryMessageWindowController.h"
#import <MOLCertificate/MOLCertificate.h>
#import <SecurityInterface/SFCertificatePanel.h>
@@ -20,7 +20,6 @@
#import "Source/common/SNTBlockMessage.h"
#import "Source/common/SNTConfigurator.h"
#import "Source/common/SNTStoredEvent.h"
#import "Source/santa/SNTMessageWindow.h"
@interface SNTBinaryMessageWindowController ()
/// The custom message to display for this event
@@ -139,7 +138,9 @@
- (NSString *)publisherInfo {
MOLCertificate *leafCert = [self.event.signingChain firstObject];
if (leafCert.commonName && leafCert.orgName) {
if ([leafCert.commonName isEqualToString:@"Apple Mac OS Application Signing"]) {
return [NSString stringWithFormat:@"App Store (Team ID: %@)", self.event.teamID];
} else if (leafCert.commonName && leafCert.orgName) {
return [NSString stringWithFormat:@"%@ - %@", leafCert.orgName, leafCert.commonName];
} else if (leafCert.commonName) {
return leafCert.commonName;

View File

@@ -14,7 +14,7 @@
#import <Cocoa/Cocoa.h>
#import "Source/common/SNTDeviceEvent.h"
#import "Source/santa/SNTMessageWindowController.h"
#import "Source/gui/SNTMessageWindowController.h"
NS_ASSUME_NONNULL_BEGIN
@@ -23,10 +23,7 @@ NS_ASSUME_NONNULL_BEGIN
///
/// Controller for a single message window.
///
@interface SNTDeviceMessageWindowController : SNTMessageWindowController
@property(weak) IBOutlet NSTextField *remountArgsLabel;
@property(weak) IBOutlet NSTextField *remountArgsTitle;
@interface SNTDeviceMessageWindowController : SNTMessageWindowController <NSWindowDelegate>
// The device event this window is for.
@property(readonly) SNTDeviceEvent *event;

View File

@@ -12,12 +12,12 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/santa/SNTDeviceMessageWindowController.h"
#import "Source/gui/SNTDeviceMessageWindowController.h"
#import "Source/gui/SNTDeviceMessageWindowView-Swift.h"
#import "Source/common/SNTBlockMessage.h"
#import "Source/common/SNTConfigurator.h"
#import "Source/common/SNTDeviceEvent.h"
#import "Source/santa/SNTMessageWindow.h"
NS_ASSUME_NONNULL_BEGIN
@@ -28,7 +28,7 @@ NS_ASSUME_NONNULL_BEGIN
@implementation SNTDeviceMessageWindowController
- (instancetype)initWithEvent:(SNTDeviceEvent *)event message:(nullable NSString *)message {
self = [super initWithWindowNibName:@"DeviceMessageWindow"];
self = [super init];
if (self) {
_event = event;
_customMessage = message;
@@ -36,12 +36,30 @@ NS_ASSUME_NONNULL_BEGIN
return self;
}
- (void)loadWindow {
[super loadWindow];
if (!self.event.remountArgs || [self.event.remountArgs count] <= 0) {
[self.remountArgsLabel removeFromSuperview];
[self.remountArgsTitle removeFromSuperview];
}
- (void)showWindow:(id)sender {
if (self.window) [self.window orderOut:sender];
self.window =
[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 0, 0)
styleMask:NSWindowStyleMaskClosable | NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
self.window.contentViewController =
[SNTDeviceMessageWindowViewFactory createWithWindow:self.window
event:self.event
customMsg:self.attributedCustomMessage];
self.window.delegate = self;
// Add app to Cmd+Tab and Dock.
NSApp.activationPolicy = NSApplicationActivationPolicyRegular;
[super showWindow:sender];
}
- (void)windowWillClose:(NSNotification *)notification {
// Remove app from Cmd+Tab and Dock.
NSApp.activationPolicy = NSApplicationActivationPolicyAccessory;
[super windowWillClose:notification];
}
- (NSAttributedString *)attributedCustomMessage {

View File

@@ -0,0 +1,76 @@
import SwiftUI
import santa_common_SNTConfigurator
import santa_common_SNTDeviceEvent
@objc public class SNTDeviceMessageWindowViewFactory : NSObject {
@objc public static func createWith(window: NSWindow, event: SNTDeviceEvent, customMsg: NSAttributedString?) -> NSViewController {
return NSHostingController(rootView:SNTDeviceMessageWindowView(window:window, event:event, customMsg:customMsg).frame(width:450, height:300))
}
}
struct SNTDeviceMessageWindowView: View {
let window: NSWindow?
let event: SNTDeviceEvent?
let customMsg: NSAttributedString?
let c = SNTConfigurator()
var body: some View {
VStack(spacing:20.0) {
Text("Santa").font(Font.custom("HelveticaNeue-UltraLight", size: 34.0))
if let t = customMsg {
if #available(macOS 12.0, *) {
let a = AttributedString(t)
Text(a).multilineTextAlignment(.center).padding(15.0)
} else {
Text(t.description).multilineTextAlignment(.center).padding(15.0)
}
} else {
Text("Mounting devices is blocked")
}
HStack(spacing:5.0) {
VStack(alignment: .trailing, spacing: 8.0) {
Text("Device Name").bold()
Text("Device BSD Path").bold()
if event!.remountArgs.count > 0 {
Text("Remount Mode").bold()
}
}
Spacer().frame(width: 10.0)
VStack(alignment: .leading, spacing: 8.0) {
Text(event!.mntonname)
Text(event!.mntfromname)
if event!.remountArgs.count > 0 {
Text(event!.readableRemountArgs())
}
}
}
HStack {
Button(action: dismissButton) {
Text("OK").frame(width: 90.0)
}
.keyboardShortcut(.defaultAction)
}.padding(10.0)
}
}
func dismissButton() {
window?.close()
}
}
// Enable previews in Xcode.
struct SNTDeviceMessageWindowView_Previews: PreviewProvider {
static var previews: some View {
SNTDeviceMessageWindowView(window: nil, event: nil, customMsg: nil)
}
}

View File

@@ -12,7 +12,7 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/santa/SNTMessageWindow.h"
#import "Source/gui/SNTMessageWindow.h"
@implementation SNTMessageWindow

View File

@@ -4,7 +4,7 @@
- (void)windowDidCloseSilenceHash:(NSString *)hash;
@end
@interface SNTMessageWindowController : NSWindowController
@interface SNTMessageWindowController : NSWindowController <NSWindowDelegate>
- (IBAction)showWindow:(id)sender;
- (IBAction)closeWindow:(id)sender;

View File

@@ -1,14 +1,17 @@
#import "Source/santa/SNTMessageWindowController.h"
#import "Source/santa/SNTMessageWindow.h"
#import "Source/gui/SNTMessageWindowController.h"
@implementation SNTMessageWindowController
- (IBAction)showWindow:(id)sender {
[(SNTMessageWindow *)self.window fadeIn:sender];
[self.window setLevel:NSPopUpMenuWindowLevel];
[self.window setMovableByWindowBackground:YES];
[self.window makeKeyAndOrderFront:sender];
[self.window center];
[NSApp activateIgnoringOtherApps:YES];
}
- (IBAction)closeWindow:(id)sender {
[(SNTMessageWindow *)self.window fadeOut:sender];
[self windowWillClose:sender];
[self.window close];
}
- (void)windowWillClose:(NSNotification *)notification {
@@ -21,12 +24,6 @@
}
}
- (void)loadWindow {
[super loadWindow];
[self.window setLevel:NSPopUpMenuWindowLevel];
[self.window setMovableByWindowBackground:YES];
}
- (NSString *)messageHash {
[self doesNotRecognizeSelector:_cmd];
return nil;

View File

@@ -15,9 +15,9 @@
#import <Cocoa/Cocoa.h>
#import "Source/common/SNTXPCNotifierInterface.h"
#import "Source/santa/SNTBinaryMessageWindowController.h"
#import "Source/santa/SNTDeviceMessageWindowController.h"
#import "Source/santa/SNTMessageWindowController.h"
#import "Source/gui/SNTBinaryMessageWindowController.h"
#import "Source/gui/SNTDeviceMessageWindowController.h"
#import "Source/gui/SNTMessageWindowController.h"
///
/// Keeps track of pending notifications and ensures only one is presented to the user at a time.

View File

@@ -12,8 +12,9 @@
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/santa/SNTNotificationManager.h"
#import "Source/gui/SNTNotificationManager.h"
#import <MOLCertificate/MOLCertificate.h>
#import <MOLXPCConnection/MOLXPCConnection.h>
#import <UserNotifications/UserNotifications.h>
@@ -23,8 +24,9 @@
#import "Source/common/SNTLogging.h"
#import "Source/common/SNTStoredEvent.h"
#import "Source/common/SNTStrengthify.h"
#import "Source/common/SNTSyncConstants.h"
#import "Source/common/SNTXPCControlInterface.h"
#import "Source/santa/SNTMessageWindowController.h"
#import "Source/gui/SNTMessageWindowController.h"
@interface SNTNotificationManager ()
@@ -90,10 +92,16 @@ static NSString *const silencedNotificationsKey = @"SilencedNotifications";
}
- (void)queueMessage:(SNTMessageWindowController *)pendingMsg {
NSString *messageHash = [pendingMsg messageHash];
// Post a distributed notification, regardless of queue state.
[self postDistributedNotification:pendingMsg];
// If GUI is in silent mode or if there's already a notification queued for
// this message, don't do anything else.
if ([SNTConfigurator configurator].enableSilentMode) return;
if ([self notificationAlreadyQueued:pendingMsg]) return;
// See if this message is silenced.
// See if this message has been user-silenced.
NSString *messageHash = [pendingMsg messageHash];
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSDate *silenceDate = [ud objectForKey:silencedNotificationsKey][messageHash];
if ([silenceDate isKindOfClass:[NSDate class]]) {
@@ -118,6 +126,52 @@ static NSString *const silencedNotificationsKey = @"SilencedNotifications";
}
}
// For blocked execution notifications, post an NSDistributedNotificationCenter
// notification with the important details from the stored event. Distributed
// notifications are system-wide broadcasts that can be sent by apps and observed
// from separate processes. This allows users of Santa to write tools that
// perform actions when we block execution, such as trigger management tools or
// display an enterprise-specific UI (which is particularly useful when combined
// with the EnableSilentMode configuration option, to disable Santa's standard UI).
- (void)postDistributedNotification:(SNTMessageWindowController *)pendingMsg {
if (![pendingMsg isKindOfClass:[SNTBinaryMessageWindowController class]]) {
return;
}
SNTBinaryMessageWindowController *wc = (SNTBinaryMessageWindowController *)pendingMsg;
NSDistributedNotificationCenter *dc = [NSDistributedNotificationCenter defaultCenter];
NSMutableArray<NSDictionary *> *signingChain =
[NSMutableArray arrayWithCapacity:wc.event.signingChain.count];
for (MOLCertificate *cert in wc.event.signingChain) {
[signingChain addObject:@{
kCertSHA256 : cert.SHA256 ?: @"",
kCertCN : cert.commonName ?: @"",
kCertOrg : cert.orgName ?: @"",
kCertOU : cert.orgUnit ?: @"",
kCertValidFrom : @([cert.validFrom timeIntervalSince1970]) ?: @0,
kCertValidUntil : @([cert.validUntil timeIntervalSince1970]) ?: @0,
}];
}
NSDictionary *userInfo = @{
kFileSHA256 : wc.event.fileSHA256 ?: @"",
kFilePath : wc.event.filePath ?: @"",
kFileBundleName : wc.event.fileBundleName ?: @"",
kFileBundleID : wc.event.fileBundleID ?: @"",
kFileBundleVersion : wc.event.fileBundleVersion ?: @"",
kFileBundleShortVersionString : wc.event.fileBundleVersionString ?: @"",
kTeamID : wc.event.teamID ?: @"",
kExecutingUser : wc.event.executingUser ?: @"",
kExecutionTime : @([wc.event.occurrenceDate timeIntervalSince1970]) ?: @0,
kPID : wc.event.pid ?: @0,
kPPID : wc.event.ppid ?: @0,
kParentName : wc.event.parentName ?: @"",
kSigningChain : signingChain,
};
[dc postNotificationName:@"com.google.santa.notification.blockedeexecution"
object:@"com.google.santa"
userInfo:userInfo];
}
- (void)showQueuedWindow {
// Notifications arrive on a background thread but UI updates must happen on the main thread.
// This includes making windows.
@@ -208,6 +262,8 @@ static NSString *const silencedNotificationsKey = @"SilencedNotifications";
#pragma mark SNTNotifierXPC protocol methods
- (void)postClientModeNotification:(SNTClientMode)clientmode {
if ([SNTConfigurator configurator].enableSilentMode) return;
UNUserNotificationCenter *un = [UNUserNotificationCenter currentNotificationCenter];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
@@ -246,6 +302,8 @@ static NSString *const silencedNotificationsKey = @"SilencedNotifications";
}
- (void)postRuleSyncNotificationWithCustomMessage:(NSString *)message {
if ([SNTConfigurator configurator].enableSilentMode) return;
UNUserNotificationCenter *un = [UNUserNotificationCenter currentNotificationCenter];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];

View File

@@ -0,0 +1,74 @@
/// 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 <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#import "Source/gui/SNTNotificationManager.h"
#import "Source/common/SNTStoredEvent.h"
@class SNTBinaryMessageWindowController;
@interface SNTNotificationManager (Testing)
- (void)hashBundleBinariesForEvent:(SNTStoredEvent *)event
withController:(SNTBinaryMessageWindowController *)controller;
@end
@interface SNTNotificationManagerTest : XCTestCase
@end
@implementation SNTNotificationManagerTest
- (void)setUp {
[super setUp];
fclose(stdout);
}
- (void)testPostBlockNotificationSendsDistributedNotification {
SNTStoredEvent *ev = [[SNTStoredEvent alloc] init];
ev.fileSHA256 = @"the-sha256";
ev.filePath = @"/Applications/Safari.app/Contents/MacOS/Safari";
ev.fileBundleName = @"Safari";
ev.fileBundlePath = @"/Applications/Safari.app";
ev.fileBundleID = @"com.apple.Safari";
ev.fileBundleVersion = @"18614.1.14.1.15";
ev.fileBundleVersionString = @"16.0";
ev.executingUser = @"rah";
ev.occurrenceDate = [NSDate dateWithTimeIntervalSince1970:1660221048];
ev.decision = SNTEventStateBlockBinary;
ev.pid = @84156;
ev.ppid = @1;
ev.parentName = @"launchd";
SNTNotificationManager *sut = OCMPartialMock([[SNTNotificationManager alloc] init]);
OCMStub([sut hashBundleBinariesForEvent:OCMOCK_ANY withController:OCMOCK_ANY]).andDo(nil);
id dncMock = OCMClassMock([NSDistributedNotificationCenter class]);
OCMStub([dncMock defaultCenter]).andReturn(dncMock);
[sut postBlockNotification:ev withCustomMessage:@""];
OCMVerify([dncMock postNotificationName:@"com.google.santa.notification.blockedeexecution"
object:@"com.google.santa"
userInfo:[OCMArg checkWithBlock:^BOOL(NSDictionary *userInfo) {
XCTAssertEqualObjects(userInfo[@"file_sha256"], @"the-sha256");
XCTAssertEqualObjects(userInfo[@"pid"], @84156);
XCTAssertEqualObjects(userInfo[@"ppid"], @1);
XCTAssertEqualObjects(userInfo[@"execution_time"], @1660221048);
return YES;
}]]);
}
@end

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.system-extension.install</key>
<true/>
</dict>
</plist>

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