-
Notifications
You must be signed in to change notification settings - Fork 27
/
NoMADSession.swift
1487 lines (1201 loc) · 59.3 KB
/
NoMADSession.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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ADUser.swift
// nomad-ad
//
// Created by Joel Rennich on 9/9/17.
// Copyright © 2018 Orchard & Grove Inc. All rights reserved.
//
import Foundation
//import NoMADPRIVATE
public protocol NoMADUserSession {
func getKerberosTicket(principal: String?, completion: @escaping (KerberosTicketResult) -> Void)
func authenticate(authTestOnly: Bool)
func changePassword(oldPassword: String, newPassword: String, completion: @escaping (String?) -> Void)
func changePassword()
func userInfo()
var delegate: NoMADUserSessionDelegate? { get set }
var state: NoMADSessionState { get }
}
public typealias KerberosTicketResult = Result<ADUserRecord, NoMADSessionError>
public protocol NoMADUserSessionDelegate: AnyObject {
func NoMADAuthenticationSucceded()
func NoMADAuthenticationFailed(error: NoMADSessionError, description: String)
func NoMADUserInformation(user: ADUserRecord)
}
public enum NoMADSessionState {
case success
case offDomain
case siteFailure
case networkLookup
case passwordChangeRequired
case unset
case lookupError
case kerbError
}
public enum NoMADSessionError: String, Error {
case OffDomain
case UnAuthenticated
case SiteError
case StateError
case AuthenticationFailure
case KerbError
case PasswordExpired = "Password has expired"
case UnknownPrincipal
case wrongRealm = "Wrong realm"
}
public enum LDAPType {
case AD
case OD
}
public enum GSSErrorKey : String {
case mechanismKey = "kGSSMechanism"
case mechanismOIDKey = "kGSSMechanismOID"
case majorErrorCodeKey = "kGSSMajorErrorCode"
case minorErrorCodeKey = "kGSSMinorErrorCode"
case descriptionKey = "NSDescription"
}
public struct GSSError {
var mechanism:String
var mechanismOID:String
var majorErrorCode:Int
var minorErrorCode:UInt
var description:String
}
public struct NoMADLDAPServer {
var host: String
var status: String
var priority: Int
var weight: Int
var timeStamp: Date
}
// MARK: Start of public class
/// A general purpose class that is the main entrypoint for interactions with Active Directory.
public class NoMADSession: NSObject {
public var state: NoMADSessionState = .offDomain // current state of affairs
weak public var delegate: NoMADUserSessionDelegate? // delegate
public var site: String = "" // current AD site
public var defaultNamingContext: String = "" // current default naming context
private var hosts = [NoMADLDAPServer]() // list of LDAP servers
private var resolver = DNSResolver() // DNS resolver object
private var maxSSF = "" // current security level in place for LDAP lookups
private var URIPrefix = "ldap://" // LDAP or LDAPS
private var current = 0 // current LDAP server from hosts
public var home = "" // current active user home
public var ldapServers: [String]? // static DCs to use instead of looking up via DNS records
// Base configuration prefs
// change these on the object as needed
public var domain: String = "" // current LDAP Domain - can be set with init
public var kerberosRealm: String = "" // Kerberos realm
public var createKerbPrefs: Bool = true // Determines if skeleton Kerb prefs should be set
public var siteIgnore: Bool = false // ignore site lookup?
public var siteForce: Bool = false // force a site?
public var siteForceSite: String = "" // what site to force
public var ldaptype: LDAPType = .AD // Type of LDAP server
public var port: Int = 389 // LDAP port typically either 389 or 636
public var anonymous: Bool = false // Anonymous LDAP lookup
public var useSSL: Bool = false // Toggle SSL
public var recursiveGroupLookup : Bool = false // Toggle recursive group lookup
// User
public var userPrincipal: String = "" // Full user principal
public var userPrincipalShort: String = "" // user shortname - necessary for any lookups to happen
public var userRecord: ADUserRecord? = nil // ADUserRecordObject containing all user information
public var userPass: String = "" // for auth
public var oldPass: String = "" // for password changes
public var newPass: String = "" // for password changes
public var customAttributes : [String]?
// conv. init with domain and user
/// Convience initializer to create a `NoMADSession` with the given domain, username, and `LDAPType`
///
/// - Parameters:
/// - domain: The AD domain for the user.
/// - user: The user's name. Either the User Principal Short, or the Users Principal name including the @domain syntax are accepted.
/// - type: The type of LDAP connection. Defaults to AD.
public init(domain: String, user: String, type: LDAPType = .AD) {
// configuration parts
self.domain = domain
self.ldaptype = type
// check for the REALM
if user.contains("@") {
self.userPrincipalShort = user.components(separatedBy: "@").first!
self.kerberosRealm = user.components(separatedBy: "@").last!.uppercased()
self.userPrincipal = user
} else {
self.userPrincipalShort = user
self.kerberosRealm = domain.uppercased()
self.userPrincipal = user + "@\(self.kerberosRealm)"
}
}
// MARK: conv functions
// Return the current server
var currentServer: String {
TCSLogWithMark("Computed currentServer accessed in state: \(String(describing: state))")
if state != .offDomain {
if hosts.isEmpty {
TCSLogWithMark("Make sure we have LDAP servers")
getHosts(domain)
}
TCSLogWithMark("Lookup the current LDAP host in: \(String(describing: hosts))")
return hosts[current].host
} else {
return ""
}
}
// MARK: DNS Main
fileprivate func parseSRVReply(_ results: inout [String]) {
if (self.resolver.error == nil) {
TCSLogWithMark("Did Receive Query Result: " + self.resolver.queryResults.description)
TCSLogWithMark("Copy \(resolver.queryResults.count) result to records")
let records = self.resolver.queryResults as! [[String:AnyObject]]
TCSLogWithMark("records dict ready: " + records.debugDescription)
for record: Dictionary in records {
TCSLogWithMark("Adding: \(String(describing: record["target"]))")
let host = record["target"] as! String
TCSLogWithMark("Created host: " + host)
results.append(host)
TCSLogWithMark("Added host to results: \(String(describing: results))")
}
} else {
TCSLogWithMark("Query Error: " + self.resolver.error.localizedDescription)
}
}
func getSRVRecords(_ domain: String, srv_type: String="_ldap._tcp.") -> [String] {
self.resolver.queryType = "SRV"
self.resolver.queryValue = srv_type + domain
// TODO: Do we need to exclude _kpasswd?
if (site != "" && !srv_type.contains("_kpasswd")) {
self.resolver.queryValue = srv_type + site + "._sites." + domain
}
var results = [String]()
TCSLogWithMark("Starting DNS query for SRV records.")
self.resolver.startQuery()
while ( !self.resolver.finished ) {
RunLoop.current.run(mode: RunLoop.Mode.default, before: Date.distantFuture)
}
parseSRVReply(&results)
TCSLogWithMark("Returning results: \(String(describing: results))")
return results
}
fileprivate func parseHostsReply() {
if (self.resolver.error == nil) {
TCSLogWithMark("Did Receive Query Result: " + self.resolver.queryResults.description)
var newHosts = [NoMADLDAPServer]()
let records = self.resolver.queryResults as! [[String:AnyObject]]
for record: Dictionary in records {
let host = record["target"] as! String
let priority = record["priority"] as! Int
let weight = record["weight"] as! Int
// let port = record["port"] as! Int
let currentServer = NoMADLDAPServer(host: host, status: "found", priority: priority, weight: weight, timeStamp: Date())
newHosts.append(currentServer)
}
// now to sort them
let fallbackHosts = self.hosts
self.hosts = newHosts.sorted { (x, y) -> Bool in
return ( x.priority <= y.priority )
}
// add back in the globally avilable DCs in case the site has gone bust
// credit to @mosen for this brilliant idea
self.hosts.append(contentsOf: fallbackHosts)
state = .success
} else {
TCSLogWithMark("Query Error: " + self.resolver.error.localizedDescription)
state = .siteFailure
self.hosts.removeAll()
}
}
fileprivate func getHosts(_ domain: String ) {
// check to see if we have static hosts
if let servers = ldapServers {
TCSLogWithMark("Using static DC list.")
var newHosts = [NoMADLDAPServer]()
for server in servers {
let host = server
let priority = 100
let weight = 100
// let port = record["port"] as! Int
let currentServer = NoMADLDAPServer(host: host, status: "found", priority: priority, weight: weight, timeStamp: Date())
newHosts.append(currentServer)
self.hosts = newHosts.sorted { (x, y) -> Bool in
return ( x.priority <= y.priority )
}
state = .success
// fake a site to put something in
site = "STATIC"
return
}
}
self.resolver.queryType = "SRV"
self.resolver.queryValue = "_ldap._tcp." + domain
if (self.site != "") {
self.resolver.queryValue = "_ldap._tcp." + self.site + "._sites." + domain
}
// check for a query already running
TCSLogWithMark("Starting DNS query for SRV records.")
self.resolver.startQuery()
while ( !self.resolver.finished ) {
RunLoop.current.run(mode: RunLoop.Mode.default, before: Date.distantFuture)
TCSLogWithMark("Waiting for DNS query to return.")
}
parseHostsReply()
}
fileprivate func testHosts() {
if state == .success {
for i in 0...( hosts.count - 1) {
if hosts[i].status != "dead" {
myLogger.logit(.info, message:"Trying host: " + hosts[i].host)
// socket test first - this could be falsely negative
// also note that this needs to return stderr
let mySocketResult = cliTask("/usr/bin/nc -G 5 -z " + hosts[i].host + " " + String(port))
if mySocketResult.contains("succeeded!") {
var attribute = "defaultNamingContext"
// if socket test works, then attempt ldapsearch to get default naming context
if ldaptype == .OD {
attribute = "namingContexts"
}
// TODO: THINK ABOUT THIS
//swapPrincipals(false)
var myLDAPResult = ""
if anonymous {
myLDAPResult = cliTask("/usr/bin/ldapsearch -N -LLL -x " + maxSSF + "-l 3 -s base -H " + URIPrefix + hosts[i].host + " " + String(port) + " " + attribute)
} else {
myLDAPResult = cliTask("/usr/bin/ldapsearch -N -LLL -Q " + maxSSF + "-l 3 -s base -H " + URIPrefix + hosts[i].host + " " + String(port) + " " + attribute)
}
// TODO: THINK ABOUT THIS
//swapPrincipals(false)
if myLDAPResult != "" && !myLDAPResult.contains("GSSAPI Error") && !myLDAPResult.contains("Can't contact") {
let ldifResult = cleanLDIF(myLDAPResult)
if ( ldifResult.count > 0 ) {
defaultNamingContext = getAttributeForSingleRecordFromCleanedLDIF(attribute, ldif: ldifResult)
hosts[i].status = "live"
hosts[i].timeStamp = Date()
myLogger.logit(.base, message:"Current LDAP Server is: " + hosts[i].host )
myLogger.logit(.base, message:"Current default naming context: " + defaultNamingContext )
current = i
break
}
}
// We didn't get an actual LDIF Result... so LDAP isn't working.
myLogger.logit(.info, message:"Server is dead by way of ldap test: " + hosts[i].host)
hosts[i].status = "dead"
hosts[i].timeStamp = Date()
break
} else {
myLogger.logit(.info, message:"Server is dead by way of socket test: " + hosts[i].host)
hosts[i].status = "dead"
hosts[i].timeStamp = Date()
}
}
}
}
guard ( hosts.count > 0 ) else {
return
}
if hosts.last!.status == "dead" {
myLogger.logit(.base, message: "All DCs in are dead! You should really fix this.")
state = .offDomain
} else {
state = .success
}
}
// MARK: Sites
// private function to get the AD site
fileprivate func findSite() {
// backup the defaultNamingContext so we can restore it at the end.
let tempDefaultNamingContext = defaultNamingContext
// Setting defaultNamingContext to "" because we're doing a search against the RootDSE
defaultNamingContext = ""
// For info on LDAP Ping: https://msdn.microsoft.com/en-us/library/cc223811.aspx
// For information on the values: https://msdn.microsoft.com/en-us/library/cc223122.aspx
let attribute = "netlogon"
// not sure if we need: (AAC=\00\00\00\00)
let searchTerm = "(&(DnsDomain=\(domain))(NtVer=\\06\\00\\00\\00))" //NETLOGON_NT_VERSION_WITH_CLOSEST_SITE
guard let ldifResult = try? getLDAPInformation([attribute], baseSearch: true, searchTerm: searchTerm, test: false, overrideDefaultNamingContext: true) else {
myLogger.logit(LogLevel.base, message: "LDAP Query failed.")
myLogger.logit(.debug, message:"Resetting default naming context to: " + tempDefaultNamingContext)
defaultNamingContext = tempDefaultNamingContext
return
}
let ldapPingBase64 = getAttributeForSingleRecordFromCleanedLDIF(attribute, ldif: ldifResult)
if ldapPingBase64 == "" {
myLogger.logit(LogLevel.base, message: "ldapPingBase64 is empty.")
myLogger.logit(.debug, message:"Resetting default naming context to: " + tempDefaultNamingContext)
defaultNamingContext = tempDefaultNamingContext
return
}
guard let ldapPing: ADLDAPPing = ADLDAPPing(ldapPingBase64String: ldapPingBase64) else {
myLogger.logit(.debug, message:"Resetting default naming context to: " + tempDefaultNamingContext)
defaultNamingContext = tempDefaultNamingContext
return
}
// calculate the site
if siteIgnore {
site = ""
myLogger.logit(.debug, message:"Sites being ignored due to preferences.")
} else if siteForce {
site = siteForceSite
myLogger.logit(.debug, message:"Site being forced to site set in preferences.")
} else {
site = ldapPing.clientSite
}
if (ldapPing.flags.contains(.DS_CLOSEST_FLAG)) {
myLogger.logit(LogLevel.info, message:"The current server is the closest server.")
} else {
if ( site != "") {
myLogger.logit(LogLevel.info, message:"Site \"\(site)\" found.")
myLogger.logit(LogLevel.notice, message: "Looking up DCs for site.")
//let domain = currentDomain
let currentHosts = hosts
getHosts(domain)
if (hosts[0].host == "") {
myLogger.logit(LogLevel.base, message: "Site \"\(site)\" has no DCs configured. Ignoring site. You should fix this.")
hosts = currentHosts
}
testHosts()
} else {
myLogger.logit(LogLevel.base, message: "Unable to find site")
}
}
myLogger.logit(.debug, message:"Resetting default naming context to: " + tempDefaultNamingContext)
defaultNamingContext = tempDefaultNamingContext
}
// MARK: LDAP Retrieval
func getLDAPInformation( _ attributes: [String], baseSearch: Bool=false, searchTerm: String="", test: Bool=true, overrideDefaultNamingContext: Bool=false) throws -> [[String:String]] {
if test {
guard testSocket(self.currentServer) else {
throw NoMADSessionError.StateError
}
}
// TODO: We need to un-comment this and figure out another way to pass a valid empty defaultNamingContext
if (overrideDefaultNamingContext == false) {
if (defaultNamingContext == "") || (defaultNamingContext.contains("GSSAPI Error")) {
testHosts()
}
}
// TODO
// ensure we're using the right kerberos credential cache
//swapPrincipals(false)
let command = "/usr/bin/ldapsearch"
var arguments: [String] = [String]()
arguments.append("-N")
if anonymous {
arguments.append("-x")
} else {
arguments.append("-Q")
}
arguments.append("-LLL")
arguments.append("-o")
arguments.append("nettimeout=1")
arguments.append("-o")
arguments.append("ldif-wrap=no")
if baseSearch {
arguments.append("-s")
arguments.append("base")
}
if maxSSF != "" {
arguments.append("-O")
arguments.append("maxssf=0")
}
arguments.append("-H")
arguments.append(URIPrefix + self.currentServer)
arguments.append("-b")
arguments.append(self.defaultNamingContext)
if ( searchTerm != "") {
arguments.append(searchTerm)
}
arguments.append(contentsOf: attributes)
let ldapResult = cliTask(command, arguments: arguments)
TCSLogWithMark("command: \(command) args: \(arguments)")
if (ldapResult.contains("GSSAPI Error") || ldapResult.contains("Can't contact")) {
throw NoMADSessionError.StateError
}
let myResult = cleanLDIF(ldapResult)
// TODO
//swapPrincipals(true)
return myResult
}
fileprivate func cleanGroups(_ groupsTemp: String?, _ groups: inout [String]) {
// clean up groups
if groupsTemp != nil {
let groupsArray = groupsTemp!.components(separatedBy: ";")
for group in groupsArray {
let a = group.components(separatedBy: ",")
var b = a[0].replacingOccurrences(of: "CN=", with: "") as String
b = b.replacingOccurrences(of: "cn=", with: "") as String
if b != "" {
groups.append(b)
}
}
myLogger.logit(.info, message: "You are a member of: " + groups.joined(separator: ", ") )
}
}
fileprivate func lookupRecursiveGroups(_ dn: String, _ groupsTemp: inout String?) {
// now to get recursive groups if asked
if recursiveGroupLookup {
let attributes = ["name"]
let searchTerm = "(member:1.2.840.113556.1.4.1941:=" + dn.replacingOccurrences(of: "\\", with: "\\\\5c") + ")"
if let ldifResult = try? getLDAPInformation(attributes, searchTerm: searchTerm) {
groupsTemp = ""
for item in ldifResult {
for components in item {
if components.key == "dn" {
groupsTemp?.append(components.value + ";")
}
}
}
}
}
}
fileprivate func parseExpirationDate(_ computedExpireDateRaw: String?, _ passwordAging: inout Bool, _ userPasswordExpireDate: inout Date, _ userPasswordUACFlag: String, _ serverPasswordExpirationDefault: inout Double, _ tempPasswordSetDate: Date) {
if computedExpireDateRaw != nil {
// Windows Server 2008 and Newer
if Int(computedExpireDateRaw!) == Int.max {
// Password doesn't expire
passwordAging = false
// Set expiration to far away from now
userPasswordExpireDate = Date.distantFuture
} else if (Int(computedExpireDateRaw!) == 0) {
// password needs to be reset
passwordAging = true
// set expirate to long ago
userPasswordExpireDate = Date.distantPast
} else {
// Password expires
passwordAging = true
userPasswordExpireDate = NSDate(timeIntervalSince1970: (Double(computedExpireDateRaw!)!)/10000000-11644473600) as Date
}
} else {
// Older then Windows Server 2008
// need to go old skool
var passwordExpirationLength: String
let attribute = "maxPwdAge"
if let ldifResult = try? getLDAPInformation([attribute], baseSearch: true) {
passwordExpirationLength = getAttributeForSingleRecordFromCleanedLDIF(attribute, ldif: ldifResult)
} else {
passwordExpirationLength = ""
}
if ( passwordExpirationLength.count > 15 ) {
passwordAging = false
} else if ( passwordExpirationLength != "" ) && userPasswordUACFlag != "" {
if ~~( Int(userPasswordUACFlag)! & 0x10000 ) {
passwordAging = false
} else {
serverPasswordExpirationDefault = Double(abs(Int(passwordExpirationLength)!)/10000000)
passwordAging = true
}
} else {
serverPasswordExpirationDefault = Double(0)
passwordAging = false
}
userPasswordExpireDate = tempPasswordSetDate.addingTimeInterval(serverPasswordExpirationDefault)
}
}
fileprivate func extractedFunc(_ attributes: [String], _ searchTerm: String) {
if let ldifResult = try? getLDAPInformation(attributes, searchTerm: searchTerm) {
let ldapResult = getAttributesForSingleRecordFromCleanedLDIF(attributes, ldif: ldifResult)
_ = ldapResult["homeDirectory"] ?? ""
_ = ldapResult["displayName"] ?? ""
_ = ldapResult["memberOf"]
_ = ldapResult["mail"] ?? ""
_ = ldapResult["uid"] ?? ""
} else {
myLogger.logit(.base, message: "Unable to find user.")
}
}
func getUserInformation() -> Bool {
// some setup
var passwordAging = true
var tempPasswordSetDate = Date()
var serverPasswordExpirationDefault = 0.0
var userPasswordExpireDate = Date()
var groups = [String]()
var userHome = ""
if ldaptype == .AD {
var attributes = ["pwdLastSet", "msDS-UserPasswordExpiryTimeComputed", "userAccountControl", "homeDirectory", "displayName", "memberOf", "mail", "userPrincipalName", "dn", "givenName", "sn", "cn", "msDS-ResultantPSO", "msDS-PrincipalName"] // passwordSetDate, computedExpireDateRaw, userPasswordUACFlag, userHomeTemp, userDisplayName, groupTemp
if customAttributes?.count ?? 0 > 0 {
attributes.append(contentsOf: customAttributes!)
}
let searchTerm = "(|(sAMAccountName="+userPrincipalShort+")(userPrincipalName="+userPrincipalShort+"@"+domain+"))"
if let ldifResult = try? getLDAPInformation(attributes, searchTerm: searchTerm) {
if ldifResult.count>1 {
TCSLogWithMark("Multiple records found. exiting")
return false
}
else if ldifResult.count==0 {
TCSLogWithMark("no user records found. exiting")
return false
}
let ldapResult = getAttributesForSingleRecordFromCleanedLDIF(attributes, ldif: ldifResult)
TCSLogWithMark(ldapResult.description)
let passwordSetDate = ldapResult["pwdLastSet"]
let computedExpireDateRaw = ldapResult["msDS-UserPasswordExpiryTimeComputed"]
let userPasswordUACFlag = ldapResult["userAccountControl"] ?? ""
let userHomeTemp = ldapResult["homeDirectory"] ?? ""
var userDisplayName = ldapResult["displayName"] ?? ""
TCSLogWithMark("userDisplayName: \(userDisplayName)")
if let mapKey = DefaultsOverride.standardOverride.object(forKey: PrefKeys.mapFullName.rawValue) as? String, mapKey.count>0, let mapValue = ldapResult[mapKey] {
userDisplayName=mapValue
TCSLogWithMark("userDisplayName: \(userDisplayName)")
}
TCSLogWithMark("userDisplayName: \(userDisplayName)")
var firstName = ldapResult["givenName"] ?? ""
if let mapKey = DefaultsOverride.standardOverride.object(forKey: PrefKeys.mapFirstName.rawValue) as? String, mapKey.count>0, let mapValue = ldapResult[mapKey] {
firstName=mapValue
}
var lastName = ldapResult["sn"] ?? ""
if let mapKey = DefaultsOverride.standardOverride.object(forKey: PrefKeys.mapLastName.rawValue) as? String, mapKey.count>0, let mapValue = ldapResult[mapKey] {
lastName=mapValue
}
var shortName = userPrincipalShort
if let mapKey = DefaultsOverride.standardOverride.object(forKey: PrefKeys.mapUserName.rawValue) as? String, mapKey.count>0, let mapValue = ldapResult[mapKey] {
shortName=mapValue
}
var groupsTemp = ldapResult["memberOf"]
let userEmail = ldapResult["mail"] ?? ""
let UPN = ldapResult["userPrincipalName"] ?? ""
let dn = ldapResult["dn"] ?? ""
let cn = ldapResult["cn"] ?? ""
let pso = ldapResult["msDS-ResultantPSO"] ?? ""
let ntName = ldapResult["msDS-PrincipalName"] ?? ""
var customAttributeResults : [String:Any]?
if customAttributes?.count ?? 0 > 0 {
var tempCustomAttr = [String:Any]()
for key in customAttributes! {
tempCustomAttr[key] = ldapResult[key] ?? ""
}
customAttributeResults = tempCustomAttr
}
if ldapResult.count == 0 {
// we didn't get a result
}
lookupRecursiveGroups(dn, &groupsTemp)
if (passwordSetDate != "") && (passwordSetDate != nil ) {
tempPasswordSetDate = NSDate(timeIntervalSince1970: (Double(passwordSetDate!)!)/10000000-11644473600) as Date
}
parseExpirationDate(computedExpireDateRaw, &passwordAging, &userPasswordExpireDate, userPasswordUACFlag, &serverPasswordExpirationDefault, tempPasswordSetDate)
cleanGroups(groupsTemp, &groups)
// clean up the home
userHome = userHomeTemp.replacingOccurrences(of: "\\", with: "/")
userHome = userHome.replacingOccurrences(of: " ", with: "%20")
// pack up user record
TCSLogWithMark("userDisplayName: \(userDisplayName)")
TCSLogWithMark("ldifResult: \(ldifResult.debugDescription)")
userRecord = ADUserRecord(userPrincipal: userPrincipal,firstName: firstName, lastName: lastName, fullName: userDisplayName, shortName: shortName, upn: UPN, email: userEmail, groups: groups, homeDirectory: userHome, passwordSet: tempPasswordSetDate, passwordExpire: userPasswordExpireDate, uacFlags: Int(userPasswordUACFlag), passwordAging: passwordAging, computedExireDate: userPasswordExpireDate, updatedLast: Date(), domain: domain, cn: cn, pso: pso, passwordLength: getComplexity(pso: pso), ntName: ntName, customAttributes: customAttributeResults, rawAttributes: ldifResult.first)
} else {
myLogger.logit(.base, message: "Unable to find user.")
}
} else {
let attributes = [ "homeDirectory", "displayName", "memberOf", "mail", "uid"] // passwordSetDate, computedExpireDateRaw, userPasswordUACFlag, userHomeTemp, userDisplayName, groupTemp
// "maxPwdAge" // passwordExpirationLength
let searchTerm = "uid=" + userPrincipalShort
extractedFunc(attributes, searchTerm)
}
// pack up the user record
return true
}
// MARK: LDAP cleanup functions
fileprivate func cleanLDIF(_ ldif: String) -> [[String:String]] {
//var myResult = [[String:String]]()
var ldifLines: [String] = ldif.components(separatedBy: CharacterSet.newlines)
var records = [[String:String]]()
var record = [String:String]()
var attributes = Set<String>()
for var i in 0..<ldifLines.count {
// save current lineIndex
let lineIndex = i
ldifLines[lineIndex] = ldifLines[lineIndex].trim()
// skip version
if i == 0 && ldifLines[lineIndex].hasPrefix("version") {
continue
}
if !ldifLines[lineIndex].isEmpty {
// fold lines
while i+1 < ldifLines.count && ldifLines[i+1].hasPrefix(" ") {
ldifLines[lineIndex] += ldifLines[i+1].trim()
i += 1
}
} else {
// end of record
if (record.count > 0) {
records.append(record)
}
record = [String:String]()
}
// skip comment
if ldifLines[lineIndex].hasPrefix("#") {
continue
}
let attribute = ldifLines[lineIndex].split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)
if attribute.count == 2 {
// Get the attribute name (before ;),
// then add to attributes array if it doesn't exist.
var attributeName = attribute[0].trim()
if let index = attributeName.firstIndex(of: ";") {
attributeName = String(attributeName[..<index])
}
if !attributes.contains(attributeName) {
attributes.insert(attributeName)
}
// Get the attribute value.
// Check if it is a URL (<), or base64 string (:)
var attributeValue = attribute[1].trim()
// If
if attributeValue.hasPrefix("<") {
// url
attributeValue = attributeValue.substring(from: attributeValue.index(after: attributeValue.startIndex)).trim()
} else if attributeValue.hasPrefix(":") {
// base64
let tempAttributeValue = attributeValue.substring(from: attributeValue.index(after: attributeValue.startIndex)).trim()
if (Data(base64Encoded: tempAttributeValue, options: NSData.Base64DecodingOptions.init(rawValue: 0)) != nil) {
//attributeValue = tempAttributeValue
attributeValue = String.init(data: Data.init(base64Encoded: tempAttributeValue)!, encoding: String.Encoding.utf8) ?? ""
} else {
attributeValue = ""
}
}
// escape double quote
attributeValue = attributeValue.replacingOccurrences(of: "\"", with: "\"\"")
// save attribute value or append it to the existing
if let val = record[attributeName] {
//record[attributeName] = "\"" + val.substringWithRange(Range<String.Index>(start: val.startIndex.successor(), end: val.endIndex.predecessor())) + ";" + attributeValue + "\""
record[attributeName] = val + ";" + attributeValue
} else {
record[attributeName] = attributeValue
}
}
}
// save last record
if record.count > 0 {
records.append(record)
}
return records
}
fileprivate func getAttributeForSingleRecordFromCleanedLDIF(_ attribute: String, ldif: [[String:String]]) -> String {
var result: String = ""
var foundAttribute = false
for record in ldif {
for (key, value) in record {
if attribute == key {
foundAttribute = true
result = value
break;
}
}
if (foundAttribute == true) {
break;
}
}
return result
}
fileprivate func getAttributesForSingleRecordFromCleanedLDIF(_ attributes: [String], ldif: [[String:String]]) -> [String:String] {
var results = [String: String]()
var foundAttribute = false
for record in ldif {
for (key, value) in record {
if attributes.contains(key) {
foundAttribute = true
results[key] = value
}
}
if (foundAttribute == true) {
break;
}
}
return results
}
fileprivate func cleanLDAPResultsMultiple(_ result: String, attribute: String) -> String {
let lines = result.components(separatedBy: "\n")
var myResult = ""
for i in lines {
if (i.contains(attribute)) {
if myResult == "" {
myResult = i.replacingOccurrences( of: attribute + ": ", with: "")
} else {
myResult = myResult + (", " + i.replacingOccurrences( of: attribute + ": ", with: ""))
}
}
}
return myResult
}
// private function that uses netcat to create a socket connection to the LDAP server to see if it's reachable.
// using ldapsearch for this can take a long time to timeout, this returns much quicker
fileprivate func testSocket( _ host: String ) -> Bool {
let mySocketResult = cliTask("/usr/bin/nc -G 5 -z " + host + " " + String(port))
if mySocketResult.contains("succeeded!") {
return true
} else {
return false
}
}
// private function to test for an LDAP defaultNamingContext from the LDAP server
// this tests for LDAP connectivity and gets the default naming context at the same time
fileprivate func testLDAP ( _ host: String ) -> Bool {
var attribute = "defaultNamingContext"
// if socket test works, then attempt ldapsearch to get default naming context
if ldaptype == .OD {
attribute = "namingContexts"
}
// TODO
//swapPrincipals(false)
var myLDAPResult = ""
if anonymous {
myLDAPResult = cliTask("/usr/bin/ldapsearch -N -LLL -x " + maxSSF + "-l 3 -s base -H " + URIPrefix + host + " " + attribute)
} else {
myLDAPResult = cliTask("/usr/bin/ldapsearch -N -LLL -Q " + maxSSF + "-l 3 -s base -H " + URIPrefix + host + " " + attribute)
}
// TODO
//swapPrincipals(true)
if myLDAPResult != "" && !myLDAPResult.contains("GSSAPI Error") && !myLDAPResult.contains("Can't contact") {
let ldifResult = cleanLDIF(myLDAPResult)
if ( ldifResult.count > 0 ) {
defaultNamingContext = getAttributeForSingleRecordFromCleanedLDIF(attribute, ldif: ldifResult)
return true
}
}
return false
}
// MARK: Kerberos preference file needs to be updated:
// This function builds new Kerb prefs with KDC included if possible
private func checkKpasswdServer() -> Bool {
if hosts.isEmpty {
TCSLogWithMark("Make sure we have LDAP servers")
getHosts(domain)
}
TCSLogWithMark("Searching for kerberos srv records")
let myKpasswdServers = getSRVRecords(domain, srv_type: "_kpasswd._tcp.")
TCSLogWithMark("New kpasswd Servers are: " + myKpasswdServers.description)
TCSLogWithMark("Current Server is: " + currentServer)
if myKpasswdServers.contains(currentServer) {
TCSLogWithMark("Found kpasswd server that matches current LDAP server.")
TCSLogWithMark("Attempting to set kpasswd server to ensure Kerberos and LDAP are in sync.")
// get the defaults for com.apple.Kerberos
let kerbPrefs = UserDefaults.init(suiteName: "com.apple.Kerberos")
// get the list defaults, or create an empty dictionary if there are none
let kerbDefaults = kerbPrefs?.dictionary(forKey: "libdefaults") ?? [String:AnyObject]()
// test to see if the domain_defaults key already exists, if not build it
if kerbDefaults["default_realm"] != nil {
TCSLogWithMark("Existing default realm. Skipping adding default realm to Kerberos prefs.")
} else {
// build a dictionary and add the KDC into it then write it back to defaults
let libDefaults = NSMutableDictionary()
libDefaults.setValue(kerberosRealm, forKey: "default_realm")
kerbPrefs?.set(libDefaults, forKey: "libdefaults")
}
// get the list of domains, or create an empty dictionary if there are none
var kerbRealms = kerbPrefs?.dictionary(forKey: "realms") ?? [String:AnyObject]()
// test to see if the realm already exists, if not build it
if kerbRealms[kerberosRealm] != nil {
TCSLogWithMark("Existing Kerberos configuration for realm. Skipping adding KDC to Kerberos prefs.")
return false
} else {
// build a dictionary and add the KDC into it then write it back to defaults
let realm = NSMutableDictionary()
//realm.setValue(myLDAPServers.currentServer, forKey: "kdc")
realm.setValue(currentServer, forKey: "kpasswd_server")
kerbRealms[kerberosRealm] = realm
kerbPrefs?.set(kerbRealms, forKey: "realms")
return true
}
} else {
myLogger.logit(LogLevel.base, message: "Couldn't find kpasswd server that matches current LDAP server. Letting system chose.")
return false