-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathFirewallUtilities.swift
704 lines (608 loc) · 22.9 KB
/
FirewallUtilities.swift
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//
// FirewallUtilities.swift
// LockdowniOS
//
// Created by Johnny Lin on 8/4/19.
// Copyright © 2019 Confirmed Inc. All rights reserved.
//
import Foundation
import NetworkExtension
import WidgetKit
import UniformTypeIdentifiers
// MARK: - Constants
// MARK: - data structures
struct ConfirmedIPRange : Codable {
var subnetMask : String
var enabled : Bool
var IPv6 : Bool
var subnetBits : Int
}
struct LockdownGroup : Codable {
//format of a lockdown default
//key: name
//value: dictionary { iconUrl: String, enabled : Boolean, domains : [String : Enabled], IPRange: [IPAddress : [subnet : String, enabled : Boolean]}
var version : Int
var internalID: String
var name: String
var iconURL : String
var enabled : Bool
var domains : Dictionary<String, Bool>
var ipRanges : Dictionary<String, ConfirmedIPRange>
var warning: String?
var accessLevel: String = "advanced"
}
struct LockdownDefaults : Codable {
var lockdownDefaults : Dictionary<String, LockdownGroup>
}
struct UserBlockListsGroup: Codable {
var name: String
var enabled: Bool = false
var domains: Set<String> = []
var description: String?
}
struct UserBlockListsDefaults: Codable {
var userBlockListsDefaults: Dictionary<String, UserBlockListsGroup>
}
//struct Domains: Codable {
// var name: String
// var isBlocked: Bool = true
//}
// MARK: - Block Metrics & Block Log
let currentCalendar = Calendar.current
let blockLogDateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a_"
return formatter
}()
enum MetricsUpdate {
enum Mode {
case incrementAndLog(host: String)
case resetIfNeeded
var incrementBy: Int {
switch self {
case .incrementAndLog:
return 1
case .resetIfNeeded:
return 0
}
}
}
enum RescheduleNotifications {
case always
case never
case withEnergySaving
var allowsScheduling: Bool {
switch self {
case .always, .withEnergySaving:
return true
case .never:
return false
}
}
}
}
func updateMetrics(_ mode: MetricsUpdate.Mode, rescheduleNotifications: MetricsUpdate.RescheduleNotifications) {
let date = Date()
// TOTAL - increment total
let totalMetrics = getTotalMetrics()
let updatedTotal = totalMetrics + mode.incrementBy
defaults.set(updatedTotal, forKey: kTotalMetrics)
if (100 ... 200) ~= updatedTotal, rescheduleNotifications.allowsScheduling {
OneTimeActions.performOnce(ifHasNotSeen: .oneHundredTrackingAttemptsBlockedNotification) {
PushNotifications.shared.scheduleOnboardingNotification(
options: rescheduleNotifications == .withEnergySaving ? [.energySaving] : []
)
}
}
// WEEKLY - reset metrics on new week and increment week
let currentWeek = currentCalendar.component(.weekOfYear, from: date)
if currentWeek != defaults.integer(forKey: kActiveWeek) {
defaults.set(0, forKey: kWeekMetrics)
defaults.set(currentWeek, forKey: kActiveWeek)
}
let weekMetrics = getWeekMetrics()
defaults.set(Int(weekMetrics + mode.incrementBy), forKey: kWeekMetrics)
// DAY - reset metric on new day and increment day and log
// set day metric
let currentDay = currentCalendar.component(.day, from: date)
if currentDay != defaults.integer(forKey: kActiveDay) {
defaults.set(0, forKey: kDayMetrics)
defaults.set(currentDay, forKey: kActiveDay)
BlockDayLog.shared.clear()
}
defaults.set(Int(getDayMetrics() + mode.incrementBy), forKey: kDayMetrics)
if #available(iOSApplicationExtension 14.0, iOS 14.0, *) {
WidgetCenter.shared.reloadAllTimelines()
}
switch mode {
case .incrementAndLog(host: let host):
guard BlockDayLog.shared.isDisabled == false else {
// block log disabled
break
}
// set log
BlockDayLog.shared.append(host: host, date: date)
case .resetIfNeeded:
// no-act
break
}
switch rescheduleNotifications {
case .always:
PushNotifications.shared.rescheduleWeeklyUpdate(options: [])
case .withEnergySaving:
PushNotifications.shared.rescheduleWeeklyUpdate(options: [.energySaving])
case .never:
// no-act
break
}
}
// MARK: - Blocked domains and lists
func setupFirewallDefaultBlockLists() {
var lockdownBlockedDomains = getLockdownBlockedDomains()
let snapchatAnalytics = LockdownGroup.init(
version: 28,
internalID: "snapchatAnalytics",
name: NSLocalizedString("Snapchat Trackers", comment: "The title of a list of trackers"),
iconURL: "snapchat_analytics_icon",
enabled: false,
domains: getDomainBlockList(filename: "snapchat_analytics"),
ipRanges: [:])
let gameAds = LockdownGroup.init(
version: 31,
internalID: "gameAds",
name: NSLocalizedString("Game Marketing", comment: "The title of a list of trackers"),
iconURL: "game_ads_icon",
enabled: true,
domains: getDomainBlockList(filename: "game_ads"),
ipRanges: [:],
accessLevel: "basic")
let clickbait = LockdownGroup.init(
version: 30,
internalID: "clickbait",
name: NSLocalizedString("Clickbait", comment: "The title of a list of trackers"),
iconURL: "clickbait_icon",
enabled: true,
domains: getDomainBlockList(filename: "clickbait"),
ipRanges: [:],
accessLevel: "basic")
let emailOpens = LockdownGroup.init(
version: 31,
internalID: "email_opens",
name: NSLocalizedString("Email Trackers", comment: "The title of a list of trackers"),
iconURL: "email_icon",
enabled: true,
domains: getDomainBlockList(filename: "email_opens"),
ipRanges: [:],
accessLevel: "basic")
let facebookInc = LockdownGroup.init(
version: 34,
internalID: "facebook_inc",
name: NSLocalizedString("Facebook & WhatsApp", comment: "The title of a list of trackers"),
iconURL: "facebook_icon",
enabled: false,
domains: getDomainBlockList(filename: "facebook_inc"),
ipRanges: [:],
warning: "This list is intended to completely block Facebook-owned apps. Do not enable it if you use apps owned by Facebook like WhatsApp, Facebook Messenger, and Instagram.")
let facebookSDK = LockdownGroup.init(
version: 29,
internalID: "facebook_sdk",
name: NSLocalizedString("Facebook Trackers", comment: "The title of a list of trackers"),
iconURL: "facebook_white_icon",
enabled: true,
domains: getDomainBlockList(filename: "facebook_sdk"),
ipRanges: [:],
accessLevel: "basic")
let marketingScripts = LockdownGroup.init(
version: 32,
internalID: "marketing_scripts",
name: NSLocalizedString("Marketing Trackers", comment: "The title of a list of trackers"),
iconURL: "marketing_icon",
enabled: true,
domains: getDomainBlockList(filename: "marketing"),
ipRanges: [:],
accessLevel: "basic")
let marketingScriptsII = LockdownGroup.init(
version: 31,
internalID: "marketing_beta_scripts",
name: NSLocalizedString("Marketing Trackers II", comment: "The title of a list of trackers"),
iconURL: "marketing_icon",
enabled: false,
domains: getDomainBlockList(filename: "marketing_beta"),
ipRanges: [:])
let googleShoppingAds = LockdownGroup.init(
version: 36,
internalID: "google_shopping_ads",
name: NSLocalizedString("Google Shopping", comment: "The title of a list of trackers"),
iconURL: "google_icon",
enabled: false,
domains: getDomainBlockList(filename: "google_shopping_ads"),
ipRanges: [:],
warning: "This blocks background Google tracking, but also blocks the shopping results at the top of Google search results. This is on by default for maximum privacy, but if you like the Google Shopping results, you can turn blocking off.")
let dataTrackers = LockdownGroup.init(
version: 36,
internalID: "data_trackers",
name: NSLocalizedString("Data Trackers", comment: "The title of a list of trackers"),
iconURL: "user_data_icon",
enabled: true,
domains: getDomainBlockList(filename: "data_trackers"),
ipRanges: [:],
accessLevel: "basic")
let generalAds = LockdownGroup.init(
version: 41,
internalID: "general_ads",
name: NSLocalizedString("General Marketing", comment: "The title of a list of trackers"),
iconURL: "ads_icon",
enabled: true,
domains: getDomainBlockList(filename: "general_ads"),
ipRanges: [:],
accessLevel: "basic")
let reporting = LockdownGroup.init(
version: 30,
internalID: "reporting",
name: NSLocalizedString("Reporting", comment: "The title of a list of trackers"),
iconURL: "reporting_icon",
enabled: true,
domains: getDomainBlockList(filename: "reporting"),
ipRanges: [:],
accessLevel: "basic")
let amazonTrackers = LockdownGroup.init(
version: 33,
internalID: "amazon_trackers",
name: NSLocalizedString("Amazon Trackers", comment: "The title of a list of trackers"),
iconURL: "amazon_icon",
enabled: true,
domains: getDomainBlockList(filename: "amazon_trackers"),
ipRanges: [:],
warning: "This blocks Amazon referral link tracking too, so enabling this list may cause errors when clicking certain links on Amazon.",
accessLevel: "basic")
let ifunnyTrackers = LockdownGroup.init(
version: 4,
internalID: "ifunnyTrackers",
name: NSLocalizedString("iFunny Trackers", comment: "The title of a list of trackers"),
iconURL: "icn_ifunny",
enabled: false,
domains: getDomainBlockList(filename: "ifunny_trackers"),
ipRanges: [:])
let advancedGaming = LockdownGroup.init(
version: 5,
internalID: "advancedGaming",
name: NSLocalizedString("Advanced Gaming", comment: "The title of a list of trackers"),
iconURL: "icn_advanced_gaming",
enabled: false,
domains: getDomainBlockList(filename: "advanced_gaming"),
ipRanges: [:])
let tiktokTrackers = LockdownGroup.init(
version: 4,
internalID: "tiktokTrackers",
name: NSLocalizedString("Tiktok Trackers", comment: "The title of a list of trackers"),
iconURL: "icn_tiktok",
enabled: false,
domains: getDomainBlockList(filename: "tiktok_trackers"),
ipRanges: [:])
let scams = LockdownGroup.init(
version: 4,
internalID: "scams",
name: NSLocalizedString("Scams", comment: "The title of a list of trackers"),
iconURL: "icn_scams",
enabled: false,
domains: getDomainBlockList(filename: "scams"),
ipRanges: [:])
let junesJourneyTrackers = LockdownGroup.init(
version: 5,
internalID: "junesJourneyTrackers",
name: NSLocalizedString("Junes Journey Trackers", comment: "The title of a list of trackers"),
iconURL: "icn-junes-journey",
enabled: false,
domains: getDomainBlockList(filename: "junes_journey_trackers"),
ipRanges: [:])
let advancedAnalytics = LockdownGroup.init(
version: 4,
internalID: "advancedAnalytics",
name: NSLocalizedString("Advanced Analytics", comment: "The title of a list of trackers"),
iconURL: "icn_advanced_analytics",
enabled: false,
domains: getDomainBlockList(filename: "advanced_analytics"),
ipRanges: [:])
let defaultLockdownSettings = [
advancedAnalytics,
junesJourneyTrackers,
scams,
tiktokTrackers,
advancedGaming,
ifunnyTrackers,
snapchatAnalytics,
gameAds,
clickbait,
emailOpens,
facebookInc,
facebookSDK,
marketingScripts,
marketingScriptsII,
googleShoppingAds,
dataTrackers,
generalAds,
reporting,
amazonTrackers];
for var defaultGroup in defaultLockdownSettings {
if let current = lockdownBlockedDomains.lockdownDefaults[defaultGroup.internalID], current.version >= defaultGroup.version {
// no version change, no action needed
} else {
if let current = lockdownBlockedDomains.lockdownDefaults[defaultGroup.internalID] {
defaultGroup.enabled = current.enabled // don't replace whether it was disabled
}
lockdownBlockedDomains.lockdownDefaults[defaultGroup.internalID] = defaultGroup
}
}
for (_, value) in lockdownBlockedDomains.lockdownDefaults {
if lockdownBlockedDomains.lockdownDefaults[value.name] != nil {
lockdownBlockedDomains.lockdownDefaults.removeValue(forKey: value.name)
}
}
defaults.set(try? PropertyListEncoder().encode(lockdownBlockedDomains), forKey: kLockdownBlockedDomains)
}
func getDomainBlockList(filename: String) -> Dictionary<String, Bool> {
var domains = [String : Bool]()
guard let path = Bundle.main.path(forResource: filename, ofType: "txt") else {
return domains
}
do {
let content = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
let lines = content.components(separatedBy: "\n")
for line in lines {
if (line.trimmingCharacters(in: CharacterSet.whitespaces) != "" && !line.starts(with: "#")) {
domains[line] = true;
}
}
} catch _ as NSError {
}
return domains
}
func getAllBlockedDomains() -> Array<String> {
let lockdownBlockedDomains = getLockdownBlockedDomains()
let userBlockedDomains = getUserBlockedDomains()
let userListsBlockedDomains = getBlockedLists()
var allBlockedDomains = Array<String>()
for (_, ldValue) in lockdownBlockedDomains.lockdownDefaults {
if ldValue.enabled {
for (key, value) in ldValue.domains {
if value {
allBlockedDomains.append(key)
}
}
}
}
for (key, value) in userBlockedDomains {
if (value as AnyObject).boolValue {
allBlockedDomains.append(key)
}
}
for (_, value) in userListsBlockedDomains.userBlockListsDefaults {
if value.enabled {
for domain in value.domains {
allBlockedDomains.append(domain)
}
}
}
return allBlockedDomains
}
func getTotalEnabled() -> Array<String> {
let lockdownBlockedDomains = getLockdownBlockedDomains()
var total = Array<String>()
for (_, ldValue) in lockdownBlockedDomains.lockdownDefaults {
if ldValue.enabled {
for (key, value) in ldValue.domains {
if value {
total.append(key)
}
}
}
}
return total
}
func getTotalDisabled() -> Array<String> {
let lockdownBlockedDomains = getLockdownBlockedDomains()
var total = Array<String>()
for (_, ldValue) in lockdownBlockedDomains.lockdownDefaults {
if !ldValue.enabled {
for (key, value) in ldValue.domains {
if value {
total.append(key)
}
}
}
}
return total
}
func getIsCombinedBlockListEmpty() -> Bool {
return (getAllBlockedDomains() + getAllWhitelistedDomains()).isEmpty
}
// MARK: - Curated Lockdown blocked domains
func getLockdownBlockedDomains() -> LockdownDefaults {
guard let lockdownDefaultsData = defaults.object(forKey: kLockdownBlockedDomains) as? Data else {
return LockdownDefaults(lockdownDefaults: [:])
}
guard let lockdownDefaults = try? PropertyListDecoder().decode(LockdownDefaults.self, from: lockdownDefaultsData) else {
return LockdownDefaults(lockdownDefaults: [:])
}
return lockdownDefaults
}
// MARK: - User blocked domains
func getUserBlockedDomains() -> Dictionary<String, Any> {
if let domains = defaults.dictionary(forKey: kUserBlockedDomains) {
return domains
}
return Dictionary()
}
func addUserBlockedDomain(domain: String) {
var domains = getUserBlockedDomains()
domains[domain] = NSNumber(value: true)
defaults.set(domains, forKey: kUserBlockedDomains)
}
func setUserBlockedDomain(domain: String, enabled: Bool) {
var domains = getUserBlockedDomains()
domains[domain] = NSNumber(value: enabled)
defaults.set(domains, forKey: kUserBlockedDomains)
}
func deleteUserBlockedDomain(domain: String) {
var domains = getUserBlockedDomains()
domains[domain] = nil
defaults.set(domains, forKey: kUserBlockedDomains)
}
// MARK: - User blocked lists
func getBlockedLists() -> UserBlockListsDefaults {
guard let listsDefaultsData = defaults.object(forKey: kUserBlockedLists) as? Data else {
return UserBlockListsDefaults(userBlockListsDefaults: [:])
}
guard let listDefaults = try? JSONDecoder().decode(UserBlockListsDefaults.self, from: listsDefaultsData) else {
return UserBlockListsDefaults(userBlockListsDefaults: [:])
}
return listDefaults
}
func addBlockedList(listName: String) {
var data = getBlockedLists()
if !data.userBlockListsDefaults.keys.contains(listName) {
data.userBlockListsDefaults[listName] = UserBlockListsGroup(name: listName, enabled: false)
let encodedData = try? JSONEncoder().encode(data)
defaults.set(encodedData, forKey: kUserBlockedLists)
}
}
func changeBlockedListName(from listName: String, to newListName: String) {
var data = getBlockedLists()
data.userBlockListsDefaults[newListName] = data.userBlockListsDefaults[listName]
data.userBlockListsDefaults[newListName]?.name = newListName
data.userBlockListsDefaults[listName] = nil
let encodedData = try? JSONEncoder().encode(data)
defaults.set(encodedData, forKey: kUserBlockedLists)
}
func deleteBlockedList(listName: String) {
var data = getBlockedLists()
data.userBlockListsDefaults[listName] = nil
let encodedData = try? JSONEncoder().encode(data)
defaults.set(encodedData, forKey: kUserBlockedLists)
}
func addDomainToBlockedList(domain: String, for listName: String) {
var data = getBlockedLists()
data.userBlockListsDefaults[listName]?.domains.insert(domain)
let encodedData = try? JSONEncoder().encode(data)
defaults.set(encodedData, forKey: kUserBlockedLists)
}
func deleteDoman(domain: String, inBlockedListName listName: String) -> UserBlockListsGroup? {
var data = getBlockedLists()
guard let index = data.userBlockListsDefaults[listName]?.domains.firstIndex(of: domain) else {
return nil
}
data.userBlockListsDefaults[listName]?.domains.remove(at: index)
let encodedData = try? JSONEncoder().encode(data)
defaults.set(encodedData, forKey: kUserBlockedLists)
return data.userBlockListsDefaults[listName]
}
extension UserBlockListsGroup {
func generateCurrentTimeStamp () -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
return (formatter.string(from: Date()) as NSString) as String
}
func exportToURL() -> URL? {
var csvString = ""
for domain in domains {
csvString = csvString.appending("\(domain)\r\n")
}
let documents = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first
let fileName = "LOCKDOWN_\(NSDate.now)"
guard let path = documents?.appendingPathComponent("/\(fileName).csv") else {
return nil
}
do {
try csvString.write(to: path, atomically: true, encoding: .utf8)
return path
} catch {
print(error.localizedDescription)
return nil
}
// guard let encoded = try? JSONEncoder().encode(self) else { return nil }
//
// let documents = FileManager.default.urls(
// for: .documentDirectory,
// in: .userDomainMask
// ).first
//
// guard let path = documents?.appendingPathComponent("/\(fileName).csv") else {
// return nil
// }
//
// do {
// try encoded.write(to: path, options: .atomicWrite)
// print(fileName)
// return path
// } catch {
// print(error.localizedDescription)
// return nil
// }
}
static func importData(from url: URL) {
// if #available(iOSApplicationExtension 14.0, *) {
// let supportedFiles: [UTType] = [UTType.data]
//
//// let controller = UIDocumentPickerViewController
//
//
//
// } else {
// // Fallback on earlier versions
// }
guard let data = try? Data(contentsOf: url)
// let list = try? JSONDecoder().decode(UserBlockListsGroup.self, from: data)
else { return }
defaults.set(data, forKey: kUserBlockedLists)
try? FileManager.default.removeItem(at: url)
}
}
//extension Domains {
//
// func generateCurrentTimeStamp () -> String {
// let formatter = DateFormatter()
// formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
// return (formatter.string(from: Date()) as NSString) as String
// }
//
// func exportToURL() -> URL? {
//
// let timeStamp = generateCurrentTimeStamp()
// let fileName = "LOCKDOWN_\(NSDate.now)"
// guard let encoded = try? JSONEncoder().encode(self) else { return nil }
//
// let documents = FileManager.default.urls(
// for: .documentDirectory,
// in: .userDomainMask
// ).first
//
// guard let path = documents?.appendingPathComponent("/\(fileName).csv") else {
// return nil
// }
//
// do {
// try encoded.write(to: path, options: .atomicWrite)
// print(fileName)
// return path
// } catch {
// print(error.localizedDescription)
// return nil
// }
// }
//
// static func importData(from url: URL) {
// guard
// let data = try? Data(contentsOf: url),
// let domain = try? JSONDecoder().decode(Domains.self, from: data)
//
//
// else { return }
// addDomainToBlockedList(domain: domain.name, for: "oop")
//
//
// try? FileManager.default.removeItem(at: url)
// }
//}