-
Notifications
You must be signed in to change notification settings - Fork 31
/
sal-submit
executable file
·389 lines (319 loc) · 12.9 KB
/
sal-submit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#!/usr/local/sal/Python.framework/Versions/Current/bin/python3
"""sal-submit
Coordinates running checkin modules and submitting their results to Sal.
"""
import argparse
import logging
import json
import os
import pathlib
import plistlib
import re
import stat
import subprocess
import tempfile
import requests.exceptions
import sal
from Foundation import NSDate
CHECKIN_MODULES_DIR = "/usr/local/sal/checkin_modules"
def main():
args = get_args()
log_level = get_log_level(args)
logging.basicConfig(level=log_level, format="%(asctime)s %(levelname)s %(message)s", datefmt="%Y-%m-%dT%H:%M:%S%z")
logging.info("%s Version: %s", os.path.basename(__file__), sal.__version__)
logging.info("Sal client prefs:")
prefs = sal.prefs_report()
if args.url:
prefs["ServerURL"] = {"value": args.url, "forced": "commandline"}
if args.key:
prefs["key"] = {"value": args.key, "forced": "commandline"}
for k, v in prefs.items():
logging.info(
f'\t{k}: {v["value"]} ({"profile" if v["forced"] else "prefs"})'
)
exit_if_not_root()
if sal.wait_for_script("sal-submit"):
exit("Another instance of sal-submit is already running. Exiting.")
if sal.wait_for_script("managedsoftwareupdate"):
exit("managedsoftwareupdate is running. Exiting.")
logging.info("Processing checkin modules...")
script_results = sal.run_scripts(CHECKIN_MODULES_DIR)
for message in script_results:
logging.info(message)
submission = sal.get_checkin_results()
run_type = get_run_type(submission)
run_plugins(run_type)
remove_blacklisted_messages()
remove_skipped_facts()
sanitize_submission()
report = sal.get_checkin_results()
sal.setup_sal_client()
if args.url:
sal.get_sal_client().base_url = args.url
logging.info("Server URL overridden with %s", args.url)
if args.key:
sesh = sal.get_sal_client().auth = ("sal", args.key)
# Override the key in the report, since it's used for querying.
report["Sal"]["extra_data"]["key"] = args.key
logging.info("Machine group key overridden with %s", args.key)
logging.debug("Checkin submission:")
logging.debug(json.dumps(report, indent=4, default=sal.serializer))
response = send_checkin(report)
if response and response.status_code == 200:
sal.set_sal_pref("LastCheckDate", NSDate.new())
sal.clean_results()
# Speed up manual runs by skipping these potentially slow-running,
# and infrequently changing tasks.
if run_type != "manual":
send_inventory(submission["Machine"]["extra_data"]["serial"])
send_catalogs()
send_profiles(submission["Machine"]["extra_data"]["serial"])
pathlib.Path("/Users/Shared/.com.salopensource.sal.run").unlink(missing_ok=True)
logging.info("Checkin complete.")
def get_log_level(args):
"""Set the verbosity based on options."""
loglevel = logging.INFO
if args.debug:
loglevel = logging.DEBUG
return loglevel
def get_args():
"""Return commandline options."""
parser = argparse.ArgumentParser()
parser.add_argument(
"-d",
"--debug",
default=False,
action="store_true",
help="Enable full debug output.",
)
parser.add_argument(
"-v",
"--verbose",
default=False,
action="store_true",
help="Deprecated. Does nothing",
)
parser.add_argument(
"-u", "--url", default=None, help="Override the server URL for testing."
)
parser.add_argument(
"-k", "--key", default=None, help="Override the machine group key."
)
return parser.parse_args()
def exit_if_not_root():
"""Exit if the executing user is not root."""
if os.geteuid() != 0:
exit("Manually running this script requires sudo.")
def get_run_type(submission):
munki = submission.get("Munki", {})
munki_extras = munki.get("extra_data", {})
return munki_extras.get("runtype", "")
def run_plugins(run_type):
logging.info("Processing plugins...")
plugin_results_path = pathlib.Path("/usr/local/sal/plugin_results.plist")
try:
run_external_scripts(run_type)
plugin_results = get_plugin_results(plugin_results_path)
finally:
plugin_results_path.unlink(missing_ok=True)
sal.set_checkin_results("plugin_results", plugin_results)
def run_external_scripts(run_type):
external_scripts_dir = pathlib.Path("/usr/local/sal/external_scripts")
if external_scripts_dir.exists():
for folder in external_scripts_dir.iterdir():
if str(folder).startswith("."):
continue
for script in folder.iterdir():
if script.stat().st_mode & stat.S_IXUSR:
try:
subprocess.check_call(
[script, run_type],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
logging.info("%s ran successfully.", script)
except OSError:
logging.warning("Couldn't run %s", script)
except subprocess.CalledProcessError:
logging.warning("%s had errors during execution!", script)
else:
logging.warning("'%s' is not executable! Skipping.", script)
def get_plugin_results(plugin_results_plist):
""" Read external data plist if it exists and return a list."""
plist_data = []
if plugin_results_plist.exists():
try:
plist_data = plistlib.loads(plugin_results_plist.read_bytes())
except plistlib.InvalidFileException:
logging.warning("Could not read external data plist.")
else:
logging.warning("No external data plist found.")
return sal.unobjctify(plist_data)
def remove_blacklisted_messages():
patterns = sal.sal_pref("MessageBlacklistPatterns", [])
if patterns:
compiled = [re.compile(p) for p in patterns]
update = False
submission = sal.get_checkin_results()
for results in submission.values():
if not isinstance(results, dict):
# Handle any non-dict keys like plugin_results
continue
removals = []
for message in results.get("messages", []):
subject = message.get("text", "")
if any(p.search(subject) for p in compiled):
removals.append(message)
if removals:
update = True
for removal in removals:
logging.debug("Removing message: '%s'", removal)
results["messages"].remove(removal)
if update:
sal.save_results(submission)
def remove_skipped_facts():
if skip_facts := sal.sal_pref("SkipFacts"):
update = False
submission = sal.get_checkin_results()
for results in submission.values():
if not isinstance(results, dict):
# Handle any non-dict keys like plugin_results
continue
removals = []
for fact in results.get("facts", []):
if fact in skip_facts:
removals.append(fact)
if removals:
update = True
for removal in removals:
logging.debug("Removing fact: '%s'", removal)
results["facts"].pop(removal)
if update:
sal.save_results(submission)
def sanitize_submission():
"""Clean submission json"""
# Make sure we're not shipping up any null chars.
submission = sal.get_checkin_results()
# json will serialize null chars to '\\u0000', so we raw string it
# not escape, and replace it with nothing.
submission_str = json.dumps(submission).replace(r"\\u0000", "")
sal.save_results(json.loads(submission_str))
def send_checkin(report):
logging.info("Sending report")
try:
response = sal.get_sal_client().post("checkin/", json=report)
except requests.exceptions.RequestException as error:
logging.error("Failed to send report")
logging.error(error)
response = None
return response
def send_inventory(serial):
logging.info("Processing inventory...")
managed_install_dir = sal.mac_pref(
"ManagedInstalls", "ManagedInstallDir", "/Library/Managed Installs"
)
inventory_plist = pathlib.Path(managed_install_dir) / "ApplicationInventory.plist"
logging.info("ApplicationInventory.plist Path: %s", inventory_plist)
if inventory := inventory_plist.read_bytes():
inventory_hash = sal.get_hash(inventory_plist)
logging.info(f"Inventory hash: {inventory_hash}")
serverhash = None
sal_client = sal.get_sal_client()
try:
response = sal_client.get(f"inventory/hash/{serial}/")
except requests.exceptions.RequestException as error:
logging.error("Failed to get inventory hash")
logging.error(error)
return
if response.status_code == 200 and response.text != inventory_hash:
logging.info("Inventory is out of date; submitting...")
inventory_submission = {
"serial": serial,
"base64bz2inventory": sal.submission_encode(inventory),
}
try:
sal_client.post("inventory/submit/", data=inventory_submission)
except requests.exceptions.RequestException as error:
logging.error("Failed to submit inventory")
logging.error(error)
def send_catalogs():
logging.info("Processing catalogs...")
managed_install_dir = sal.mac_pref(
"ManagedInstalls", "ManagedInstallDir", "/Library/Managed Installs"
)
catalog_dir = pathlib.Path(managed_install_dir) / "catalogs"
check_list = []
if catalog_dir.exists():
for catalog_file in catalog_dir.iterdir():
# don't operate on hidden files (.DS_Store etc)
if not str(catalog_file).startswith("."):
catalog_hash = sal.get_hash(catalog_file)
check_list.append(
{"name": str(catalog_file), "sha256hash": catalog_hash}
)
catalog_check_plist = plistlib.dumps(check_list)
sal_client = sal.get_sal_client()
machine_group_key = sal_client.auth[1]
hash_submission = {
"key": machine_group_key,
"catalogs": sal.submission_encode(catalog_check_plist),
}
try:
response = sal_client.post("catalog/hash/", data=hash_submission)
except requests.exceptions.RequestException as error:
logging.error("Failed to get catalog hashes")
logging.error(error)
return
try:
remote_data = plistlib.loads(response.content)
except plistlib.InvalidFileException:
remote_data = []
for catalog in check_list:
if catalog not in remote_data:
contents = (pathlib.Path(catalog_dir) / catalog["name"]).read_bytes()
catalog_submission = {
"key": machine_group_key,
"base64bz2catalog": sal.submission_encode(contents),
"name": catalog["name"],
"sha256hash": catalog["sha256hash"],
}
logging.info("Submitting Catalog: %s", catalog["name"])
try:
sal_client.post("catalog/submit/", data=catalog_submission)
except requests.exceptions.RequestException as error:
logging.error("Error while submitting Catalog: %s", catalog["name"])
logging.error(error)
def send_profiles(serial):
logging.info("Processing profiles...")
temp_dir = tempfile.mkdtemp()
profile_out = pathlib.Path(temp_dir) / "profiles.plist"
cmd = ["/usr/bin/profiles", "-C", "-o", profile_out]
dev_null = open(os.devnull, "w")
try:
subprocess.call(cmd, stdout=dev_null)
except OSError:
logging.warning("Couldn't output profiles.")
return
profiles = plistlib.loads(profile_out.read_bytes())
profile_out.unlink()
# Drop all of the payload info we're not going to actual store.
for profile in profiles["_computerlevel"]:
cleansed_payloads = [
_payload_cleanse(p) for p in profile.get("ProfileItems", [])
]
profile["ProfileItems"] = cleansed_payloads
logging.debug(profiles)
profile_submission = {
"serial": serial,
"base64bz2profiles": sal.submission_encode(plistlib.dumps(profiles)),
}
try:
sal.get_sal_client().post("profiles/submit/", data=profile_submission)
except requests.exceptions.RequestException as error:
logging.error("Failed to submit profiles")
logging.error(error)
def _payload_cleanse(payload):
stored = ("PayloadIdentifier", "PayloadUUID", "PayloadType")
return {k: payload.get(k, "None") for k in stored}
if __name__ == "__main__":
main()