-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathwifiutil.py
executable file
·1828 lines (1681 loc) · 57.4 KB
/
wifiutil.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
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
#!/usr/bin/python
__author__ = 'Zack Smith (@acidprime)'
__version__ = '1.1'
import os
import getopt
import uuid
import plistlib
import sys
import shutil
import subprocess
import commands
import re
import time
import binascii
import urllib
from Cocoa import NSData,NSString,NSDictionary,NSMutableDictionary,NSPropertyListSerialization,NSDate
from Cocoa import NSUTF8StringEncoding,NSPropertyListImmutable
from subprocess import Popen, PIPE, STDOUT
# Commands used by this script
airport = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport'
eapolclient = '/System/Library/SystemConfiguration/EAPOLController.bundle/Contents/Resources/eapolclient'
if not os.path.exists(eapolclient):
# Leopard Location, used by security command for ACL
eapolclient = '/System/Library/SystemConfiguration/EAPOLController.bundle/Resources/eapolclient'
runDirectory = os.path.dirname(os.path.abspath(__file__))
curl = '/usr/bin/curl'
dscl = '/usr/bin/dscl'
grep = '/usr/bin/grep'
kinit = '/usr/bin/kinit'
networksetup = '/usr/sbin/networksetup'
openssl = '/usr/bin/openssl'
profiles = '/usr/bin/profiles'
plutil = '/usr/bin/plutil'
sysctl = '/usr/sbin/sysctl'
security = '/usr/bin/security'
sudo = '/usr/bin/sudo'
system_profiler = '/usr/sbin/system_profiler'
uuidgen = '/usr/bin/uuidgen'
who = '/usr/bin/who'
whoami = '/usr/bin/whoami'
# Constants
UUID = os.system(uuidgen)
# Added for 10.5 support
kcutil = '%s/%s' % (runDirectory,'kcutil')
def showUsage():
print '''
wifutil: A multi OS version wireless configuration tool
Syntax:
## 802.1X PEAP Example (Username & Password are Required for non WPA2)
wifiutil --username="zsmith" --password='d0gc4t' --plist="settings.plist"
## WPA2 Example
wifiutil --plist="/Library/Preferences/com.318.wifi.plist"
Options:
-f | --plist= ## Path to a plist to read configuration information from
This will override any other provided options!
-u | --username= ## The username used to access the wireless
-p | --password= ## The password used to access the wireless
-c | --ca_server ## The Microsoft IIS Certificate portal server
-t | --cert_type ## The certificate type (name of the Template)
-d | --debug ## Echo commands (and passwords!) in clear text
-s | --secure_import ## Securely import the pkcs12 into the keychain
'''
# Check scripts as root
if not os.geteuid() == 0:
showUsage()
print '--> This script requires root access!'
sys.exit(1)
# Generate csr with openssl for a machine
def generateMachineCSR(machine_name,key,csr):
arguments = [
openssl,
'req',
'-new',
'-batch',
'-newkey',
'rsa:2048',
'-nodes',
'-keyout',
'%s' % key,
'-out',
'%s' % csr,
'-subj',
'/CN=%s$' % machine_name ,
]
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
# Generate csr with openssl for a user
def generateUserCSR(user_name,key,csr):
arguments = [
openssl,
'req',
'-new',
'-batch',
'-newkey',
'rsa:2048',
'-nodes',
'-keyout',
'%s' % key,
'-out',
'%s' % csr,
'-subj',
'/CN=%s$' % user_name,
]
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
## curl the csr up
def curlCsr(csr,cert_type,ca_url):
# Someday we might use this instead of curl
# http://trac.calendarserver.org/browser/PyKerberos
# First we get rid of some really really ugly-looking awk work to url-encode the csr
# Later versions of curl do this for us... but we don't have that luxury.
cert_request = open(csr, 'r').read()
request_dict = { 'CertRequest' : cert_request }
encoded_csr = urllib.urlencode(request_dict)
arguments = [
curl,
'--negotiate',
'-A',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5',
'-u',
':',
'-d',
encoded_csr,
'-d',
'SaveCert=yes',
'-d',
'Mode=newreq',
'-d',
"CertAttrib=CertificateTemplate:%s" % cert_type,
"%s/certfnsh.asp" % ca_url,
]
print 'Attempting to get Request ID...'
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
req_id_regex = re.search(".*location=\"certnew.cer\?ReqID=(\d+).*",out)
req_id = req_id_regex.group(1)
print 'REQ_ID: %s' % req_id
def discoverADfacts():
path = '/Library/Preferences/DirectoryService/ActiveDirectory.plist'
plist = NSDictionary.dictionaryWithContentsOfFile_(path)
if not os.path.exists(path):
print 'Active Directory plist is missing'
return False
return machineIsBound()
def machineIsBound(plist):
if not 'AD Bound to Domain' in plist:
return False
else:
return plist['AD Bound to Domain']
## Get TGT via kinit - If 2k3, use password method if 2k8
def getTGTkinit(machine_name):
arguments = [
kinit,
'-k',
'%s$' % machine_name,
]
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
def getTGTpassword():
path = '/Library/Preferences/DirectoryService/ActiveDirectory.plist'
plist = NSDictionary.dictionaryWithContentsOfFile_(path)
if 'AD Computer Password' in plist:
nsdata = plist['AD Computer Password']
print nsdata
else:
print 'This machine does not appear to have a password'
# Need expect script
## curl the csr up
def curlCert(pem,ca_url,req_id):
print "CRT is %s, CA_URL is %s" % crt,ca_url
arguments = [ curl,
'-k',
'-o',
pem,
'--negotiate',
'-u',
':',
"%s/certnew.cer?ReqID=%s&Enc=b64" % (ca_url,req_id) ,
]
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
## Pick up the cert via dscl if it's a 2k8 domain and convert it into PEM format
# dsclMachineCert('WIN-7PO3B92M2FP','/tmp/userCertificate.pem')
def dsclMachineCert(machine_name,pem):
dscl_args = [
dscl,
'-plist',
'localhost',
'read',
'/Search/Computers/%s$' % machine_name,
'userCertificate',
]
#print ' '.join(arguments)
dscl_process = Popen(dscl_args, stdout=PIPE)
out, err = dscl_process.communicate()
plist = plistlib.readPlistFromString(out)
if 'dsAttrTypeNative:userCertificate' in plist:
nsdata = plist['dsAttrTypeNative:userCertificate'][0]
user_certificate = binascii.unhexlify(''.join(nsdata.split()))
openssl_args = [
openssl,
'x509',
'-inform',
'DER',
'-outform',
'PEM',
'-out',
pem,
]
openssl_process = Popen(openssl_args,stdin=PIPE,stdout=PIPE,stderr=STDOUT)
output = openssl_process.communicate(input=user_certificate)[0]
else:
print 'This machine does not appear to have a certificate'
def dsclUserCert(pem):
dscl_args = [
dscl,
'-plist',
'localhost',
'read',
'/Active\ Directory/All\ Domains/Users/`%s`' % whoami,
'userCertificate',
]
#print ' '.join(arguments)
dscl_process = Popen(dscl_args, stdout=PIPE)
out, err = dscl_process.communicate()
plist = plistlib.readPlistFromString(out)
if 'dsAttrTypeNative:userCertificate' in plist:
nsdata = plist['dsAttrTypeNative:userCertificate'][0]
user_certificate = binascii.unhexlify(''.join(nsdata.split()))
openssl_args = [
openssl,
'x509',
'-inform',
'DER',
'-outform',
'PEM',
'-out',
pem,
]
openssl_process = Popen(openssl_args,stdin=PIPE,stdout=PIPE,stderr=STDOUT)
output = openssl_process.communicate(input=user_certificate)[0]
#def curlTrustedCert(pem,ca_cert,keychain_path):
# arguments = [ openssl,
# 'x509',
# '-in',
# pem,
# '-text',
# '|',
# grep,
# 'CA Issuers - URI:http://',
# '|',
# awk,
# '{ print $4 }'
# '|',
# sed,
# 's/URI://',
# ]
#
# execute = Popen(arguments, stdout=PIPE)
# out, err = execute.communicate()
#
# ca_url = out
#
# arguments = [ curl,
# '-o',
# ca_cert,
# ca_url,
# ]
#
# execute = Popen(arguments, stdout=PIPE)
# out, err = execute.communicate()
#
# arguments = [ security,
# 'add-trusted-cert',
# '-k',
# keychain_path,
# ca_cert,
# ]
#
## Not currently Implemented
#def evalCert(pem,keychain_path,ca_crt):
# arguments = [ security,
# 'verify-cert',
# '-c',
# pem,
# '|',
# grep,
# 'successful',
# ]
#
# execute = Popen(arguments, stdout=PIPE)
# out, err = execute.communicate()
#
# # Find out if cert is trusted
# try:
# exit_code = subprocess.check_call(execute)
# curlTrustedCert(pem,ca_cert,keychain_path)
# except subprocess.CalledProcessError as e:
# print "Certificate verification failed ...", e.returncode
def keychainPath(cert_style):
if cert_style == 'USER':
arguments = [
security,
'default-keychain',
]
execute = Popen(arguments,stdout=PIPE)
out, err = execute.communicate()
keychain_regex = re.search('.*\"(.*\.keychain)\".*',out)
return keychain_regex.group(1)
else:
return '/Library/Keychains/System.keychain'
## Pack the cert up and import it ito the keychain
def packAndImport(pem,key,pk12,machine_name,keychain_path):
uuid = UUID
secure_import = True
## Build the cert and private key into a PKCS12
arguments = [
openssl,
'pkcs12',
'-export',
'-in',
pem,
'-inkey',
key,
'-out',
pk12,
'-name',
machine_name,
'-passout',
'pass:%s' % uuid,
]
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
arguments = [
security,
'import',
pk12,
'-k',
keychain_path,
'-f',
'pkcs12',
'-P',
uuid,
]
if secure_import :
arguments.append('-x',arguments[1])
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
def createEAPProfile(path,uid,gid,networkDict):
if os.path.exists(path):
plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
else:
plist = NSMutableDictionary.alloc().init()
plist['Profiles'] = []
# item entry
_Profiles = {}
# EAPClientConfiguration
EAPClientConfiguration = {}
AcceptEAPTypes = []
_AcceptEAPTypes = networkDict['eapt']
AcceptEAPTypes = [_AcceptEAPTypes]
# Top Level EAPClientConfiguration keys
EAPClientConfiguration['AcceptEAPTypes'] = AcceptEAPTypes
EAPClientConfiguration['Description'] = 'Automatic'
EAPClientConfiguration['EAPFASTProvisionPAC'] = True
EAPClientConfiguration['EAPFASTUsePAC'] = True
EAPClientConfiguration['TLSVerifyServerCertificate'] = False
EAPClientConfiguration['TTLSInnerAuthentication'] = networkDict['iath']
EAPClientConfiguration['UserName'] = networkDict['user']
EAPClientConfiguration['UserPasswordKeychainItemID'] = networkDict['keyc']
if not osVersion['minor'] == LEOP:
EAPClientConfiguration['Wireless Security'] = networkDict['type']
# Top Level item keys
_Profiles['EAPClientConfiguration'] = EAPClientConfiguration
_Profiles['UniqueIdentifier'] = networkDict['keyc']
_Profiles['UserDefinedName'] = 'WPA: %s' % networkDict['ssid']
if not osVersion['minor'] == LEOP:
_Profiles['Wireless Security'] = networkDict['type']
# Merge the data with current plist
plist['Profiles'].append(_Profiles)
exportFile = path
plist.writeToFile_atomically_(exportFile,True)
try:
os.chown(path,uid,gid)
except:
print 'Path not found %s' % path
def getAirportMac():
# Script Created Entry
port = getPlatformPortName()
arguments = [
networksetup,
'-getmacaddress',
port
]
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
parse = out.split()
return parse[2]
def createEAPBinding(path,uid,gid,networkDict):
macAddress = getAirportMac()
if os.path.exists(path):
plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
else:
plist = NSMutableDictionary.alloc().init()
plist[macAddress] = []
_item = {}
_item['UniqueIdentifier'] = networkDict['keyc']
_item['Wireless Network'] = networkDict['ssid']
plist[macAddress].append(_item)
exportFile = path
plist.writeToFile_atomically_(exportFile,True)
try:
os.chown(path,uid,gid)
except:
print 'Path not found %s' % path
def createRecentNetwork(networkDict):
path = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist'
# Set to root as the owner for good measure
uid = 0
gid = 80
if os.path.exists(path):
plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
else:
plist = NSMutableDictionary.alloc().init()
port = getPlatformPortName()
# Check for non-existant keys
if not port in plist.keys():
plist[port] = {}
# Make sure the Array is there
if not 'RecentNetworks' in plist[port].keys():
plist[port]['RecentNetworks'] = []
_RecentNetworks = {}
_RecentNetworks['SSID_STR'] = networkDict['ssid']
_RecentNetworks['SecurityType'] = networkDict['sect']
_RecentNetworks['Unique Network ID'] = networkDict['guid']
_RecentNetworks['Unique Password ID'] = networkDict['keyc']
plist[port]['RecentNetworks'].append(_RecentNetworks)
exportFile = path
plist.writeToFile_atomically_(exportFile,True)
try:
os.chown(path,uid,gid)
except:
print 'Path not found %s' % path
def createKnownNetwork(networkDict):
print 'Creating KnownNetworks entry'
# There were some MacBook Airs that shipped with 10.5
path = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist'
# Set to root as the owner for good measure
uid = 0
gid = 80
if os.path.exists(path):
plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
else:
plist = NSMutableDictionary.alloc().init()
plist['KnownNetworks'] = {}
guid = networkDict['guid']
plist['KnownNetworks'][guid] = {}
plist['KnownNetworks'][guid]['SSID_STR'] = networkDict['ssid']
plist['KnownNetworks'][guid]['Remembered channels'] = [networkDict['chan'],]
plist['KnownNetworks'][guid]['SecurityType'] = networkDict['sect']
# If we are adding a non WPA2 Enterprise network add the keychain item
if networkDict['type'] == 'WPA2':
plist['KnownNetworks'][guid]['Unique Password ID'] = networkDict['keyc']
plist['KnownNetworks'][guid]['_timeStamp'] = NSDate.date()
exportFile = path
plist.writeToFile_atomically_(exportFile,True)
try:
os.chown(path,uid,gid)
except:
print 'Path not found %s' % path
def addKeychainPassword(arguments):
# Script Created Entry
print 'Adding password to keychain'
if(debugEnabled):printCommand(arguments)
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
print out
def createLeopEAPkeychainEntry(networkDict):
users = '/var/db/dslocal/nodes/Default/users'
listing = os.listdir(users)
for plist in listing:
# Hardware test for Air
excluded = re.compile("^((?!^_|root|daemon|nobody|com.apple.*).)*$")
if excluded.match(plist):
plistPath = '%s/%s' % (users,plist)
print 'Processing: %s' % plistPath
user = NSDictionary.dictionaryWithContentsOfFile_(plistPath)
try:
uid = int(user['uid'][0])
gid = int(user['gid'][0])
for home in user['home']:
keychain = home + '/Library/Keychains/login.keychain'
print 'Processing keychain: %s' % keychain
if os.path.exists(keychain):
if user['name'][0] == getConsoleUser():
arguments = [
security,
"add-generic-password",
'-a',
networkDict['ssid'],
'-l',
'%s-%s' % (networkDict['ssid'],networkDict['user']),
'-D',
'Internet Connect',
'-s',
networkDict['keyc'],
'-w',
networkDict['pass'],
'-T',
'group://Aiport',
'-T',
'/System/Library/CoreServices/SystemUIServer.app',
'-T',
'/Applications/System Preferences.app',
'-T',
'/usr/libexec/airportd',
'-T',
eapolclient,
keychain
]
addKeychainPassword(arguments)
try:
os.chown(keychain,uid,gid)
except:
print 'Path not found %s' % keychain
else:
print 'User will not be modified: %s' % user['name'][0]
except:
print 'Key Missing, Skipping'
def createSnowEAPkeychainEntry(networkDict):
users = '/var/db/dslocal/nodes/Default/users'
listing = os.listdir(users)
for plist in listing:
# Hardware test for Air
excluded = re.compile("^((?!^_|root|daemon|nobody|com.apple.*).)*$")
if excluded.match(plist):
plistPath = '%s/%s' % (users,plist)
print 'Processing: %s' % plistPath
user = NSDictionary.dictionaryWithContentsOfFile_(plistPath)
try:
uid = int(user['uid'][0])
gid = int(user['gid'][0])
for home in user['home']:
keychain = home + '/Library/Keychains/login.keychain'
print 'Processing keychain: %s' % keychain
if os.path.exists(keychain):
if user['name'][0] == getConsoleUser():
arguments = [
security,
"add-generic-password",
'-a',
networkDict['user'],
'-l',
'WPA: %s' % networkDict['ssid'],
'-D',
'802.1X Password',
'-s',
networkDict['keyc'],
'-w',
networkDict['pass'],
'-T',
'group://Aiport',
'-T',
'/System/Library/CoreServices/SystemUIServer.app',
'-T',
'/Applications/System Preferences.app',
'-T',
eapolclient,
keychain
]
addKeychainPassword(arguments)
try:
os.chown(keychain,uid,gid)
except:
print 'Path not found %s' % keychain
except:
print 'Key Missing, Skipping'
def createLionEAPkeychainEntry(networkDict):
users = '/var/db/dslocal/nodes/Default/users'
listing = os.listdir(users)
for plist in listing:
# Hardware test for Air
excluded = re.compile("^((?!^_|root|daemon|nobody|com.apple.*).)*$")
if excluded.match(plist):
plistPath = '%s/%s' % (users,plist)
print 'Processing: %s' % plistPath
user = NSDictionary.dictionaryWithContentsOfFile_(plistPath)
try:
uid = int(user['uid'][0])
gid = int(user['gid'][0])
for home in user['home']:
keychain = home + '/Library/Keychains/login.keychain'
print 'Processing keychain: %s' % keychain
if os.path.exists(keychain):
# Clear old value
if user['name'][0] == getConsoleUser():
arguments = [
security,
"delete-generic-password",
'-D',
'802.1X Password',
'-l',
networkDict['ssid'],
'-a',
networkDict['user'],
keychain
]
deleteKeychainPassword(arguments)
# Add New Value
arguments = [
security,
"add-generic-password",
'-a',
networkDict['user'],
'-l',
networkDict['ssid'],
'-D',
'802.1X Password',
'-s',
'com.apple.network.eap.user.item.wlan.ssid.%s' % networkDict['ssid'],
'-w',
networkDict['pass'],
'-T',
'group://Aiport',
'-T',
'/System/Library/CoreServices/SystemUIServer.app',
'-T',
'/Applications/System Preferences.app',
'-T',
eapolclient,
keychain
]
addKeychainPassword(arguments)
try:
os.chown(keychain,uid,gid)
except:
print 'Path not found %s' % keychain
except:
print 'Key Missing, Skipping'
# Need to clean this up with defaults or a dict
def genLionProfile(networkDict={}):
plist = NSMutableDictionary.alloc().init()
# EAPClientConfiguration
AcceptEAPTypes = []
_AcceptEAPTypes = networkDict['eapt']
AcceptEAPTypes = [_AcceptEAPTypes]
tlsTrustedServerNames = []
EAPClientConfiguration = {}
EAPClientConfiguration['AcceptEAPTypes'] = AcceptEAPTypes
EAPClientConfiguration['TTLSInnerAuthentication'] = networkDict['iath']
EAPClientConfiguration['UserName'] = networkDict['user']
EAPClientConfiguration['UserPassword'] = networkDict['pass']
EAPClientConfiguration['tlsTrustedServerNames'] = tlsTrustedServerNames
# PayloadContent
PayloadContent = []
_PayloadContent = {}
_PayloadContent['AuthenticationMethod'] = ''
_PayloadContent['EAPClientConfiguration'] = EAPClientConfiguration
_PayloadContent['EncryptionType'] = 'WPA'
_PayloadContent['HIDDEN_NETWORK'] = False
_PayloadContent['Interface'] = 'BuiltInWireless'
_PayloadContent['PayloadDisplayName'] = '%s-%s' % (networkDict['ssid'],networkDict['user'])
_PayloadContent['PayloadEnabled'] = True
_PayloadContent['PayloadIdentifier'] = '%s.%s.alacarte.interfaces.%s' % (networkDict['mdmh'],networkDict['puid'],networkDict['suid'])
_PayloadContent['PayloadType'] = 'com.apple.wifi.managed'
_PayloadContent['PayloadUUID'] = networkDict['suid']
_PayloadContent['PayloadVersion'] = 1
_PayloadContent['SSID_STR'] = networkDict['ssid']
PayloadContent = [_PayloadContent]
plist['PayloadContent'] = PayloadContent
plist['PayloadDisplayName'] = networkDict['orgn']
plist['PayloadIdentifier'] = '%s.%s.alacarte' % (networkDict['mdmh'],networkDict['puid'])
plist['PayloadOrganization'] = networkDict['orgn']
plist['PayloadRemovalDisallowed'] = False
plist['PayloadScope'] = networkDict['scop']
plist['PayloadType'] = 'Configuration'
plist['PayloadUUID'] = networkDict['puid']
plist['PayloadVersion'] = 1
# Show the plist on debug
if(debugEnabled):print plist
exportFile = '/tmp/.%s-%s.mobileconfig' % (networkDict['user'],networkDict['ssid'])
plist.writeToFile_atomically_(exportFile,True)
return exportFile
def networksetupExecute(arguments):
if(debugEnabled):printCommand(arguments)
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
print out
def profilesExecute(arguments):
if(debugEnabled):printCommand(arguments)
execute = Popen(arguments, stdout=PIPE)
out, err = execute.communicate()
print out
#-------------------------------------------------------------------------------
# This is currently not used as writing the keys seemed best for auto connect
def genSnowProfile(networkDict):
# EAPClientConfiguration
AcceptEAPTypes = []
_AcceptEAPTypes = networkDict['eapt']
AcceptEAPTypes = [_AcceptEAPTypes]
EAPClientConfiguration = {}
EAPClientConfiguration['AcceptEAPTypes'] = AcceptEAPTypes
EAPClientConfiguration['UserName'] = networkDict['user']
EAPClientConfiguration['UserPasswordKeychainItemID'] = networkDict['keyc']
# UserProfiles
UserProfiles = []
_UserProfiles = {}
_UserProfiles['ConnectByDefault'] = True
_UserProfiles['EAPClientConfiguration'] = EAPClientConfiguration
_UserProfiles['UniqueIdentifier'] = networkDict['keyc']
_UserProfiles['UserDefinedName'] = '%s-%s' % (networkDict['ssid'],networkDict['user'])
_UserProfiles['Wireless Network'] = networkDict['ssid']
UserProfiles = [_UserProfiles]
# 8021X
plist = NSMutableDictionary.alloc().init()
_8021X = {}
_8021X['UserProfiles'] = UserProfiles
plist['8021X'] = _8021X
print plist
exportFile = '/tmp/.importme.networkconnect'
plist.writeToFile_atomically_(exportFile,True)
return exportFile
#-------------------------------------------------------------------------------
# This is currently not used as writing the keys seemed best for auto connect
def importSnowProfile(exportFile):
arguments = [
networksetup,
"-import8021xProfiles",
"Airport",
exportFile
]
networksetupExecute(arguments)
def addPreferredNetwork(networkDict):
path = '/Library/Preferences/SystemConfiguration/preferences.plist'
plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path)
for _Sets in plist['Sets'].keys():
for Interface in plist['Sets'][_Sets]['Network']['Interface'].keys():
if 'AirPort' in plist['Sets'][_Sets]['Network']['Interface'][Interface].keys():
if not 'PreferredNetworks' in plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort'].keys():
plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort']['PreferredNetworks'] = []
_PreferredNetworks = {}
_PreferredNetworks['SSID_STR'] = networkDict['ssid']
_PreferredNetworks['SecurityType'] = networkDict['sect']
_PreferredNetworks['Unique Network ID'] = networkDict['guid']
# Add keychain item reference if not 802.1x or Open
if networkDict['type'] == 'WPA2':
_PreferredNetworks['Unique Password ID'] = networkDict['keyc']
# Fix for https://github.com/acidprime/WirelessConfig/issues/2
if 'PreferredNetworks' in plist['Sets'][_Sets]['Network']['Interface'][Interface].keys():
plist['Sets'][_Sets]['Network']['Interface'][Interface]['PreferredNetworks'].append(_PreferredNetworks)
else:
plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort']['PreferredNetworks'].append(_PreferredNetworks)
plist.writeToFile_atomically_(path,True)
def getSystemVersion():
# Our Operating System Constants
global LEOP,SNOW,LION,MLION,MAVRK
LEOP = 5
SNOW = 6
LION = 7
MLION = 8
MAVRK = 9
systemVersionPath = '/System/Library/CoreServices/SystemVersion.plist'
try:
systemVersion = plistlib.Plist.fromFile(systemVersionPath)
except:
print 'Unable to parse file at path: %s' % systemVersion
sys.exit(1)
ProductVersion = systemVersion['ProductVersion'].split('.')
returnDict = {}
returnDict['major'] = int(ProductVersion[0])
returnDict['minor'] = int(ProductVersion[1])
returnDict['bugfx'] = int(ProductVersion[2])
return returnDict
def leopardAddWireless(networkDict={}):
plistPath = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist'
# Sanity check to make sure preferences are the there.
if os.path.exists(plistPath):
pl = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
# Copy the dictionary for mutation during enumeration
copy = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
# 10.5 Style
# Grab UUID if already in network list
found = False
print 'Checking for existing Keychain GUID in KnownNetworks'
try:
for key in copy['KnownNetworks'].keys():
if copy['KnownNetworks'][key]['SSID_STR'] == networkDict['ssid']:
networkDict['guid'] = copy['KnownNetworks'][key]['Unique Password ID']
print 'Found existing reference to wireless password guid: %s' % networkDict['guid']
found = True
except:
print 'Key KnownNetworks not found'
# If this not an OPEN network then add keychain
# Updated to not add blank keychain entry for Open networks
if 'pass' in networkDict.keys() and not networkDict['type'] == "OPEN":
""" Removing Keychain entries for system due to bug in 10.5 """
#print 'Network has password generating keychain arguments...'
#keychain = '/Library/Keychains/System.keychain'
#arguments = [security,
# "add-generic-password",
# '-a',
# networkDict['ssid'],
# '-l',
# networkDict['ssid'],
# '-D',
# 'AirPort network password',
# '-s',
# networkDict['guid'],
# '-w',
# networkDict['pass'],
# '-T',
# 'group://Aiport',
# '-T',
# '/System/Library/CoreServices/SystemUIServer.app',
# '-T',
# '/Applications/System Preferences.app',
# '-T',
# '/usr/libexec/airportd',
# keychain]
#addKeychainPassword(arguments)
users = '/var/db/dslocal/nodes/Default/users'
listing = os.listdir(users)
for plist in listing:
# Hardware test for Air
excluded = re.compile("^((?!^_|root|daemon|nobody|com.apple.*).)*$")
if excluded.match(plist):
plistPath = '%s/%s' % (users,plist)
print 'Processing: %s' % plistPath
user = NSDictionary.dictionaryWithContentsOfFile_(plistPath)
try:
uid = int(user['uid'][0])
gid = int(user['gid'][0])
for home in user['home']:
keychain = home + '/Library/Keychains/login.keychain'
print 'Processing keychain: %s' % keychain
if os.path.exists(keychain):
# -U causing segmentation fault, removed sudo
if user['name'][0] == getConsoleUser():
arguments = [
security,
"add-generic-password",
'-a',
networkDict['ssid'],
'-l',
networkDict['ssid'],
'-D',
'AirPort network password',
'-s',
'AirPort Network',
'-w',
networkDict['pass'],
'-T',
'group://Aiport',
'-T',
'/System/Library/CoreServices/SystemUIServer.app',
'-T',
'/Applications/System Preferences.app',
keychain
]
addKeychainPassword(arguments)
arguments = [
kcutil,
user['home'][0],
user['name'][0],
networkDict['pass'],
configFile
]
addKeychainPassword(arguments)
try:
os.chown(keychain,uid,gid)
except:
print 'Path not found: %s' % keychain
else:
print 'Keychain file: %s does not exist' % keychain
except:
print 'User plist %s does not have a home key' % plistPath
else:
print 'No password is specified, skipping keychain actions'
port = 'Airport'
if networkDict['type'] == 'WPA2 Enterprise':
createKnownNetwork(networkDict)
createRecentNetwork(networkDict)
addUsersEAPProfile(networkDict)
createLeopEAPkeychainEntry(networkDict)
addPreferredNetwork(networkDict)
else:
# We can automatically connect to WPA PSK type networks
leopardRemoveWireless(networkDict['ssid'])
connectToNewNetwork(port,networkDict)
def leopardRemoveWireless(networkName):
plistPath = '/Library/Preferences/SystemConfiguration/preferences.plist'
# Sanity checks for the plist
if os.path.exists(plistPath):
try:
pl = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath)
except:
print 'Unable to parse file at path: %s' % plistPath
sys.exit(1)
else:
print 'File does not exist at path: %s' % plistPath