Created
January 24, 2020 18:36
-
-
Save hafta/bca83004cdf7542dbf71b46e629ec0af to your computer and use it in GitHub Desktop.
Mac python code to check if a given process is sandboxed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import argparse | |
import ctypes | |
import errno | |
import os | |
import sys | |
SUCCESS_EXIT_CODE = 0 | |
ERROR_EXIT_CODE = 1 | |
def main(): | |
rv = SUCCESS_EXIT_CODE | |
parser = argparse.ArgumentParser(description='Report if a given process ' | |
'on macOS is sandboxed using the undocumented sandbox_check function ' | |
'(Mac-specific.)') | |
parser.add_argument("PID", nargs='*', | |
help="PID of a processes to check", default=[]) | |
args = parser.parse_args() | |
if not args.PID: | |
parser.print_help() | |
else: | |
for pid_string in args.PID: | |
# Convert argument PID string to integer | |
pid = 0; | |
try: | |
pid = int(pid_string) | |
except: | |
print "ERROR: %s is not a PID, skipping" % (pid_string) | |
rv = ERROR_EXIT_CODE | |
continue | |
# Does a process with PID exist? | |
if not pid_exists(pid): | |
print "ERROR: no process with PID %d" % (pid) | |
rv = ERROR_EXIT_CODE | |
continue | |
# Is the process sandboxed? | |
# Note: false positive possible if process exits after | |
# pid_exists() check above, but before sandbox_check(). | |
is_sandboxed = sandbox_check(pid) | |
is_sandboxed_label = '' | |
if is_sandboxed is True: | |
is_sandboxed_label = "sandboxed" | |
else: | |
is_sandboxed_label = "NOT sandboxed" | |
print "PID %d is %s" % (pid, is_sandboxed_label) | |
sys.exit(rv) | |
def sandbox_check(pid): | |
lib = ctypes.cdll.LoadLibrary('/usr/lib/system/libsystem_sandbox.dylib') | |
return lib.sandbox_check(pid, 0, 0) is 1 | |
# https://stackoverflow.com/questions/568271/ | |
# how-to-check-if-there-exists-a-process-with-a-given-pid-in-python | |
def pid_exists(pid): | |
try: | |
os.kill(pid, 0) | |
except OSError as err: | |
if err.errno == errno.ESRCH: | |
return False | |
elif err.errno == errno.EPERM: | |
return True | |
else: | |
raise | |
else: | |
return True | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment