-
Notifications
You must be signed in to change notification settings - Fork 261
/
stronghold.py
400 lines (303 loc) · 17.7 KB
/
stronghold.py
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
390
391
392
393
394
395
396
397
398
399
400
# STRONGHOLD
# @author Aaron Lichtman
# Built-in modules
import sys
import subprocess as sp
from time import sleep
# 3rd party modules
import click
import inquirer
from colorama import Fore, Style
# Local modules
from constants import Constants
def prompt_yes_no(top_line="", bottom_line=""):
"""Print question and return True or False depending on user selection from list.
bottom_line should be used for one liners. Otherwise, it's the second line you want printed.
Deprecated comment: Thanks, @shobrook"""
# One liner. Only bottom_line should be printed + stylized
if top_line is "":
questions = [inquirer.List('choice',
message=Fore.GREEN + Style.BRIGHT + bottom_line + Fore.YELLOW,
choices=[' Yes', ' No'],
),
]
# else top_line is not ""
else:
print(Fore.GREEN + Style.BRIGHT + " " + top_line)
questions = [inquirer.List('choice',
message=Fore.GREEN + bottom_line + Fore.YELLOW,
choices=[' Yes', ' No'],
),
]
answers = inquirer.prompt(questions)
return answers.get('choice').strip() == 'Yes'
def print_section_header(title, COLOR):
"""Prints variable sized section header"""
block = "#" * (len(title) + 2)
print(COLOR + Style.BRIGHT + block)
print("#", title)
print(block + "\n" + Style.RESET_ALL)
def print_confirmation(action):
"""Prints confirmation of action in bright yellow."""
print(Fore.YELLOW + Style.BRIGHT + action + Style.RESET_ALL + "\n")
def print_abort(config_type):
"""Prints abort message in bright red."""
print(Fore.RED + Style.BRIGHT + "\nInvalid sudo password.", config_type, "configuration aborted." + Style.RESET_ALL)
sleep(1)
def splash_intro():
print(Fore.GREEN + Style.BRIGHT +
"\n .d8888b. 888 888 888 888 \n" +
"d88P Y88b 888 888 888 888 \n" +
"Y88b. 888 888 888 888 \n" +
" \"Y888b. 888888 888d888 .d88b. 88888b. .d88b. 88888b. .d88b. 888 .d88888 \n" +
" \"Y88b. 888 888P\" d88\"\"88b 888 \"88b d88P\"88b 888 \"88b d88\"\"88b 888 d88\" 888 \n" +
" \"888 888 888 888 888 888 888 888 888 888 888 888 888 888 888 888 \n" +
"Y88b d88P Y88b. 888 Y88..88P 888 888 Y88b 888 888 888 Y88..88P 888 Y88b 888 \n" +
" \"Y8888P\" \"Y888 888 `Y88P\' 888 888 `Y88888 888 888 `Y88P\' 888 `Y88888 \n" +
" 888 \n" +
" Y8b d88P \n" +
" \"Y88P\n" + Style.RESET_ALL)
print(Fore.RED + Style.BRIGHT + "Built by Aaron Lichtman. (Github: alichtman)\n" + Style.RESET_ALL)
print(Fore.BLUE + Style.BRIGHT + "Stronghold is a security configuration tool for MacOS Sierra and High Sierra.")
print("You may be asked for a sudo password." + Style.RESET_ALL + "\n")
print_section_header("BEFORE STARTING", Fore.RED)
print(Fore.RED + Style.BRIGHT + "\t0. Make the terminal window as large as possible.")
print("\t1. Ensure you have up-to-date system backups.")
print("\t2. Read the prompts carefully.\n" + Style.RESET_ALL)
if not prompt_yes_no(bottom_line="I have read the above carefully and want to continue"):
sys.exit(0)
# I have prayed to the sudo gods many times.
# Proceed at your own risk.
def firewall_config():
"""Firewall configuration options."""
print_section_header("FIREWALL", Fore.BLUE)
if prompt_yes_no(top_line="-> Turn on firewall?",
bottom_line="This helps protect your Mac from being attacked over the internet."):
print_confirmation("Enabling firewall...")
# If sudo password incorrect, abort and return from firewall config.
if sp.run("sudo -E -v", shell=True, stdout=sp.PIPE).returncode != 0:
print_abort("Firewall")
return
# Load default firewall config.
sp.run('sudo launchctl load /System/Library/LaunchDaemons/com.apple.alf.agent.plist', shell=True, stdout=sp.PIPE)
sp.run('sudo launchctl load /System/Library/LaunchAgents/com.apple.alf.useragent.plist', shell=True, stdout=sp.PIPE)
sp.run('sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on', shell=True, stdout=sp.PIPE)
# Logging
if prompt_yes_no(top_line="-> Turn on logging?",
bottom_line="If there IS an infection, logs are useful for determining the source."):
print_confirmation("Enabling logging...")
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setloggingmode', 'on'], stdout=sp.PIPE)
# Stealth Mode
if prompt_yes_no(top_line="-> Turn on stealth mode?",
bottom_line="Your Mac will not respond to ICMP ping requests or connection attempts from closed TCP and UDP networks."):
print_confirmation("Enabling stealth mode...")
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setstealthmode', 'on'], stdout=sp.PIPE)
# Remote login
if not prompt_yes_no(top_line="-> Do you use SSH?",
bottom_line="If no, remote login will be turned off."):
print_confirmation("Disabling ssh daemon...")
sp.run('sudo systemsetup -f -setremotelogin off', shell=True, stdout=sp.PIPE)
# Apache server
if not prompt_yes_no(top_line="-> Do you want Apache to autostart?",
bottom_line="Apache is a web server. If you are unfamiliar with it, disable it."):
print_confirmation("Disabling httpd...")
sp.run('sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist', shell=True, stdout=sp.PIPE)
print_confirmation("Resetting firewall to finalize changes...")
sp.run('sudo pkill -HUP socketfilterfw', shell=True, stdout=sp.PIPE)
def system_protection_config():
"""System protection configuration options."""
print_section_header("GENERAL SYSTEM PROTECTION", Fore.BLUE)
# Enable Gatekeeper
if prompt_yes_no(top_line="-> Enable Gatekeeper?",
bottom_line="Defend against malware by enforcing code signing and verifying downloaded applications before letting them to run."):
print_confirmation("Enabling Gatekeeper...")
sp.run('sudo spctl --master-enable', shell=True, stdout=sp.PIPE)
sp.run('sudo spctl --enable --label "Developer ID"', shell=True, stdout=sp.PIPE)
# Disable automatic software whitelisting
if prompt_yes_no(top_line="-> Prevent automatic software whitelisting?",
bottom_line="Both built-in and downloaded software will require user approval for whitelisting."):
print_confirmation("Preventing automatic whitelisting...")
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setallowsigned', 'off'], stdout=sp.PIPE)
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setallowsignedapp', 'off'], stdout=sp.PIPE)
# Captive Portal
if prompt_yes_no(top_line="-> Disable Captive Portal Assistant and force login through browser on untrusted networks?",
bottom_line="Captive Portal could be triggered and direct you to a malicious site WITHOUT any user interaction."):
print_confirmation("Disabling Captive Portal Assistant...")
sp.run(['sudo', 'defaults', 'write', '/Library/Preferences/SystemConfiguration/com.apple.captive.control', 'Active', '-bool', 'false'], stdout=sp.PIPE)
def metadata_storage_config():
"""User metadata configuration options."""
print_section_header("METADATA STORAGE", Fore.BLUE)
###
# Language Modeling Data
###
if prompt_yes_no(top_line="-> Clear language modeling metadata?",
bottom_line="This includes user spelling, typing and suggestion data."):
print_confirmation("Removing language modeling data...")
sp.run('rm -rfv "~/Library/LanguageModeling/*" "~/Library/Spelling/*" "~/Library/Suggestions/*"', shell=True, stdout=sp.PIPE)
if prompt_yes_no(bottom_line="-> Disable language modeling data collection?"):
print_confirmation("Disabling language modeling data collection...")
sp.run('sudo chmod -R 000 ~/Library/LanguageModeling ~/Library/Spelling ~/Library/Suggestions', shell=True, stdout=sp.PIPE)
sp.run('sudo chflags -R uchg ~/Library/LanguageModeling ~/Library/Spelling ~/Library/Suggestions', shell=True, stdout=sp.PIPE)
###
# QuickLook and Quarantine Data
###
if prompt_yes_no(top_line="-> Clear QuickLook metadata?",
bottom_line="This will erase spotlight user data."):
print_confirmation("Removing QuickLook metadata...")
sp.run('rm -rfv "~/Library/Application Support/Quick Look/*"', shell=True, stdout=sp.PIPE)
###
# Downloads Metadata
###
# TODO: BUG --> /bin/sh: /Users/alichtman/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2: Operation not permitted
if prompt_yes_no(bottom_line="-> Clear Downloads metadata?"):
print_confirmation("Removing Downloads metadata...")
sp.run(':>~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2', shell=True, stdout=sp.PIPE)
if prompt_yes_no(bottom_line="-> Disable metadata collection from Downloads?"):
print_confirmation("Disabling Quarantine data collection from downloaded files...")
sp.run('sudo chflags schg ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2', shell=True, stdout=sp.PIPE)
# TODO: ERRORS
# chmod: ~/Library/Application Support/Quick Look: No such file or directory
# chflags: ~/Library/Application Support/Quick Look: No such file or directory
# if prompt_yes_no(bottom_line="Disable QuickLook data logging?"):
# print_confirmation("Disabling QuickLook data logging...")
# sp.run('sudo chmod -R 000 "~/Library/Application Support/Quick Look"', shell=True, stdout=sp.PIPE)
# sp.run('sudo chflags -R uchg "~/Library/Application Support/Quick Look"', shell=True, stdout=sp.PIPE)
###
# Siri Metadata
###
if prompt_yes_no(bottom_line="-> Clear SiriAnalytics database?"):
print_confirmation("Clearing SiriAnalytics database...")
sp.run('rm -rfv ~/Library/Assistant/SiriAnalytics.db', shell=True, stdout=sp.PIPE)
def user_safety_config():
"""User Safety configuration options."""
print_section_header("USER SAFETY", Fore.BLUE)
if prompt_yes_no(top_line="-> Lock Mac as soon as screen saver starts?",
bottom_line="If your screen is black or on screensaver mode, you'll be prompted for a password to login every time."):
print_confirmation("Configuring account lock on screensaver...")
sp.run(['defaults', 'write', 'com.apple.screensaver', 'askForPassword', '-int', '1'], stdout=sp.PIPE)
sp.run(['defaults', 'write', 'com.apple.screensaver', 'askForPasswordDelay', '-int', '0'], stdout=sp.PIPE)
if prompt_yes_no(top_line="-> Display all file extensions?",
bottom_line="This prevents malware from disguising itself as another file type."):
print_confirmation("Configuring display of all file extensions...")
sp.run(['defaults', 'write', 'NSGlobalDomain', 'AppleShowAllExtensions', '-bool', 'true'], stdout=sp.PIPE)
if prompt_yes_no(top_line="-> Disable saving to the cloud by default?",
bottom_line="This prevents sensitive documents from being unintentionally stored on the cloud."):
print_confirmation("Disabling cloud saving by default...")
sp.run(['defaults', 'write', 'NSGlobalDomain', 'NSDocumentSaveNewDocumentsToCloud', '-bool', 'false'], stdout=sp.PIPE)
if prompt_yes_no(top_line="-> Show hidden files in Finder?",
bottom_line="This lets you see all files on the system without having to use the terminal."):
print_confirmation("Displaying hidden files in Finder...")
sp.run(['defaults', 'write', 'com.apple.finder', 'AppleShowAllFiles', '-boolean', 'true'], shell=True, stdout=sp.PIPE)
if prompt_yes_no(top_line="-> Disable printer sharing?",
bottom_line="Offers redundancy in case the Firewall was not configured."):
print_confirmation("Disabling printer sharing...")
sp.run(['cupsctl', '--no-share-printers'], shell=True, stdout=sp.PIPE)
# Reset finder after messing with it.
print_confirmation("Resetting Finder to finalize changes...")
sp.run(['killAll', 'Finder'], stdout=sp.PIPE)
def final_configuration():
print_section_header("FINAL CONFIGURATION STEPS", Fore.BLUE)
print(Fore.RED + Style.BRIGHT + "WARNING: Secure Configuration not complete! At a minimum, a full restart is necessary." + Style.RESET_ALL)
print(Fore.YELLOW + Style.BRIGHT + "\nNEXT STEPS...\n")
print("1. Fully disable Siri: https://apple.stackexchange.com/a/258981")
print("2. Enable FileVault. (Check if it's enabled by running `$ fdesetup status`)")
print("3. Make sure everything in the Settings > Sharing menu is disabled if you're not using it.")
print("4. For the most secure configuration, check out Objective-See's Free OSX Security Tools: https://objective-see.com/products.html")
print("\nIf you have any suggestions for stronghold, open an issue at: https://github.com/alichtman/stronghold/issues/new" + Style.RESET_ALL)
sys.exit()
# Removed due to sudo reboot bug.
# if prompt_yes_no(top_line="-> Restart your Mac right now?",
# bottom_line="This is necessary for some configuration changes to take effect."):
# print_confirmation("Configuration complete after restart!")
# print(Fore.YELLOW + Style.BRIGHT + "Restarting in 5 seconds..." + Style.RESET_ALL)
# sleep(1)
# print(Fore.YELLOW + Style.BRIGHT + "4..." + Style.RESET_ALL)
# sleep(1)
# print(Fore.YELLOW + Style.BRIGHT + "3..." + Style.RESET_ALL)
# sleep(1)
# print(Fore.YELLOW + Style.BRIGHT + "2..." + Style.RESET_ALL)
# sleep(1)
# print(Fore.YELLOW + Style.BRIGHT + "1..." + Style.RESET_ALL)
# sleep(1)
# if sp.run(['sudo', 'shutdown', '-r', 'now'], shell=True, stdout=sp.PIPE) != 0:
# print(Fore.RED + Style.BRIGHT + "WARNING: Configuration not complete! A full restart is necessary." + Style.RESET_ALL)
# sys.exit()
# else:
# print(Fore.RED + Style.BRIGHT + "WARNING: Configuration not complete! A full restart is necessary." + Style.RESET_ALL)
# sys.exit()
def lockdown_procedure():
"""Set secure config without any user interaction."""
print("----------")
print_section_header("LOCKDOWN", Fore.BLUE)
print_confirmation("Set secure configuration without user interaction.")
# Get sudo priv
sp.run("sudo -E -v", shell=True, stdout=sp.PIPE)
####
# FIREWALL
####
sp.run(['sudo', 'launchctl', 'load', '/System/Library/LaunchDaemons/com.apple.alf.agent.plist'], stdout=sp.PIPE)
sp.run(['sudo', 'launchctl', 'load', '/System/Library/LaunchAgents/com.apple.alf.useragent.plist'], stdout=sp.PIPE)
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setglobalstate', 'on'], stdout=sp.PIPE)
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setloggingmode', 'on'], stdout=sp.PIPE)
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setstealthmode', 'on'], stdout=sp.PIPE)
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setallowsigned', 'off'], stdout=sp.PIPE)
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setallowsignedapp', 'off'], stdout=sp.PIPE)
sp.run(['sudo', 'pkill', '-HUP', 'socketfilterfw'], stdout=sp.PIPE)
####
# SYSTEM PROTECTION
####
sp.run('sudo spctl --master-enable', shell=True, stdout=sp.PIPE)
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setallowsigned', 'off'], stdout=sp.PIPE)
sp.run(['sudo', '/usr/libexec/ApplicationFirewall/socketfilterfw', '--setallowsignedapp', 'off'], stdout=sp.PIPE)
sp.run(['sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.captive.control Active -bool false'], stdout=sp.PIPE)
####
# METADATA STORAGE
####
sp.run(['rm', '-rfv', '"~/Library/LanguageModeling/*"', '"~/Library/Spelling/*"', '"~/Library/Suggestions/*"'])
sp.run(['rm', '-rfv', '"~/Library/Application Support/Quick Look/*"'], stdout=sp.PIPE)
sp.run([':>~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2'], shell=True, stdout=sp.PIPE)
####
# DAEMONS
####
sp.run('sudo systemsetup -f -setremotelogin off', shell=True, stdout=sp.PIPE)
sp.run('sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist', shell=True, stdout=sp.PIPE)
####
# USER SAFETY
####
sp.run(['defaults', 'write', 'com.apple.screensaver', 'askForPassword', '-int', '1'], stdout=sp.PIPE)
sp.run(['defaults', 'write', 'com.apple.screensaver', 'askForPasswordDelay', '-int', '0'], stdout=sp.PIPE)
sp.run(['defaults', 'write', 'NSGlobalDomain', 'AppleShowAllExtensions', '-bool', 'true'], stdout=sp.PIPE)
sp.run(['defaults', 'write', 'NSGlobalDomain', 'NSDocumentSaveNewDocumentsToCloud', '-bool', 'false'], stdout=sp.PIPE)
sp.run(['defaults', 'write', 'com.apple.finder', 'AppleShowAllFiles', '-boolean', 'true'], shell=True, stdout=sp.PIPE)
sp.run(['killAll', 'Finder'], stdout=sp.PIPE)
####
# RESTART
####
final_configuration()
# Click custom help
CONTEXT_SETTINGS = dict(help_option_names=['-h', '-help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('-lockdown', is_flag=True, default=False, help="Set secure configuration without user interaction.")
@click.option('-v', is_flag=True, default=False, help='Display version and author information and exit.')
def cli(lockdown, v):
"""Securely configure your Mac.
Developed by Aaron Lichtman -> (Github: alichtman)"""
# Print author and version information and exit
if v:
print('stronghold v{0} by {1} -> Github: {2}'.format(Constants.VERSION,
Constants.AUTHOR_FULL_NAME,
Constants.AUTHOR_GITHUB,))
sys.exit()
# Lockdown
if lockdown:
lockdown_procedure()
# interactive walk-through
else:
splash_intro()
firewall_config()
system_protection_config()
metadata_storage_config()
user_safety_config()
final_configuration()
if __name__ == '__main__':
cli()