-
Notifications
You must be signed in to change notification settings - Fork 3
/
import2431.py
1108 lines (943 loc) · 47.1 KB
/
import2431.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/env python
"""import2431.py - Script to import the backup into Gluu Server 3.0.x
Usage: python import2431.py <path_to_backup_folder>
Example: python import2431.py /root/backup_24
This script imports the data from backup folder generated by export2431.py.
Read complete migration procedure at:
https://www.gluu.org/docs/deployment/upgrading/
"""
import os
import os.path
import sys
import logging
import traceback
import shutil
import json
import re
import subprocess
import time
import datetime
import base64
import pyDes
import ldap
import shelve
from distutils.dir_util import copy_tree
from ldif import LDIFParser, LDIFWriter
from jsonmerge import merge
from ldifschema_utils import OpenDjSchema
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
# configure logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(name)s %(message)s',
filename='import2431.log',
filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logging.getLogger('jsonmerge').setLevel(logging.WARNING)
def progress_bar(t, n, act='', finished=None):
if not t % 50:
if finished:
i = 40
else:
i = (t*1.0/(n)) /0.025
ft = '#' * int(round(i))
ft = ft.ljust(40)
sys.stdout.write("\r[{0}] {1}".format(ft,act))
sys.stdout.flush()
if finished:
print
class DBLDIF(LDIFParser):
def __init__(self, ldif_file):
LDIFParser.__init__(self, open(ldif_file,'rb'))
db_file = os.path.basename(ldif_file)
sdb_file = os.path.join('/tmp', db_file+'.sdb')
if os.path.exists(sdb_file):
os.remove(sdb_file)
#logging.info("\nDumping %s to shelve database" % ldif_file)
self.sdb = shelve.open(sdb_file)
def handle(self, dn, entry):
self.sdb[dn] = entry
class MyLDIF(LDIFParser):
def __init__(self, input, output):
LDIFParser.__init__(self, input)
self.targetDN = None
self.targetAttr = None
self.targetEntry = None
self.DNs = []
self.lastDN = None
self.lastEntry = None
self.entries = []
def getResults(self):
return (self.targetDN, self.targetAttr)
def getDNs(self):
return self.DNs
def getLastEntry(self):
return self.lastEntry
def handle(self, dn, entry):
if self.targetDN is None:
self.targetDN = dn
self.lastDN = dn
self.DNs.append(dn)
self.entries.append(entry)
self.lastEntry = entry
if dn.lower().strip() == self.targetDN.lower().strip():
self.targetEntry = entry
if self.targetAttr in entry:
self.targetAttr = entry[self.targetAttr]
class Migration(object):
def __init__(self, backup):
self.backupDir = backup
self.ldifDir = os.path.join(backup, 'ldif')
self.certsDir = os.path.join(backup, 'etc', 'certs')
self.currentDir = os.path.dirname(os.path.realpath(__file__))
self.workingDir = os.path.join(self.currentDir, 'migration')
self.jettyDir = "/opt/gluu/jetty/"
self.os_types = ['centos', 'redhat', 'fedora', 'ubuntu', 'debian']
self.os = self.detect_os_type()
self.service = "/usr/sbin/service"
if self.os is 'centos':
self.service = "/sbin/service"
self.open_dj_conf_dir = '/opt/opendj/config/schema/'
self.slapdConf = "/opt/symas/etc/openldap/slapd.conf"
self.slapcat = "/opt/symas/bin/slapcat"
self.slapadd = "/opt/symas/bin/slapadd"
self.keytool = "/opt/jre/bin/keytool"
self.key_store = "/opt/jre/jre/lib/security/cacerts"
self.ldif_import = "/opt/opendj/bin/import-ldif"
self.ldif_export = "/opt/opendj/bin/export-ldif"
self.ldif_search = "/opt/opendj/bin/ldapsearch"
self.ldif_modify = "/opt/opendj/bin/ldapmodify"
self.ldapHost = "127.0.0.1"
self.ldapPort = "1636"
self.baseDn = "cn=directory manager,o=gluu"
self.ldappassowrd = None
self.key = None
self.oxAuthClientSecret = None
self.idpDN = None
self.encryptIdpJson = None
self.ldapDataFile = "/opt/gluu/data/main_db/data.mdb"
self.ldapSiteFile = "/opt/gluu/data/site_db/data.mdb"
self.currentData = os.path.join(self.workingDir, 'current.ldif')
self.o_gluu = os.path.join(self.workingDir, "o_gluu.ldif")
self.processTempFile = os.path.join(self.workingDir, "temp.ldif")
self.o_site_static = "/install/community-edition-setup/static/cache-refresh/o_site.ldif"
self.o_site = os.path.join(self.workingDir, "o_site.ldif")
self.attrs = 2000
self.objclasses = 2000
self.ldap_type = 'openldap'
self.gluuSchemaDir = '/opt/gluu/schema/openldap/'
self.backupVersion = 0
self.setup_properties = 'backup_2431/setup.properties'
self.customAttrs = []
def slapdConfAdd(self):
with open(self.slapdConf, 'a') as f:
f.writelines("sizelimit -1")
f.close
def slapdConfremove(self):
with open(self.slapdConf, 'a+') as f:
lines = f.readlines()
lines = lines[:-1]
f.close
def readFile(self, inFilePath):
if not os.path.exists(inFilePath):
logging.debug("Cannot read: %s. File does not exist.", inFilePath)
return None
inFilePathText = None
try:
f = open(inFilePath)
inFilePathText = f.read()
f.close
except:
logging.warning("Error reading %s", inFilePath)
logging.debug(traceback.format_exc())
return inFilePathText
def walk_function(self, a, directory, files):
for f in files:
fn = "%s/%s" % (directory, f)
targetFn = fn.replace(self.backupDir, '')
if os.path.isdir(fn):
if not os.path.exists(targetFn):
os.mkdir(targetFn)
else:
try:
logging.debug("copying %s", targetFn)
shutil.copyfile(fn, targetFn)
except:
logging.error("Error copying %s", targetFn)
def detect_os_type(self):
distro_info = self.readFile('/etc/redhat-release')
if distro_info is None:
distro_info = self.readFile('/etc/os-release')
if 'CentOS' in distro_info:
return self.os_types[0]
elif 'Red Hat' in distro_info:
return self.os_types[1]
elif 'Ubuntu' in distro_info:
return self.os_types[3]
elif 'Debian' in distro_info:
return self.os_types[4]
else:
return self.choose_from_list(self.os_types, "Operating System")
def verifyBackupData(self):
if not os.path.exists(self.backupDir):
logging.error("Backup folder %s doesn't exist! Quitting migration",
self.backupDir)
sys.exit(1)
if not os.path.exists(self.ldifDir):
logging.error("Backup doesn't contain directory for LDIF data."
" Nothing to migrate. Quitting.")
sys.exit(1)
def setupWorkDirectory(self):
if not os.path.exists(self.workingDir):
os.mkdir(self.workingDir)
else:
# Clean the directory in case its already present
shutil.rmtree(self.workingDir)
os.mkdir(self.workingDir)
def getOutput(self, args):
try:
logging.debug("Running command : %s" % " ".join(args))
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, error = p.communicate()
if error and 'Certificate was added to keystore' not in error:
logging.error(error)
logging.debug(output)
return output
except:
logging.error("Error running command : %s" % " ".join(args))
logging.error(traceback.format_exc())
sys.exit(1)
def copyCertificates(self):
# remove opendj.crt
command = ['rm','backup_2431/etc/certs/opendj.crt']
output = self.getOutput(command)
logging.info("Copying the Certificates.")
os.path.walk("%s/etc" % self.backupDir, self.walk_function, None)
logging.info("Updating the CA Certs Keystore.")
keys = ['httpd', 'idp-signing', 'idp-encryption', 'shibidp', 'asimba']
if self.ldap_type == 'openldap':
keys.append('openldap')
hostname = self.getOutput(['hostname']).strip()
# import all the keys into the keystore
for key in keys:
alias = "{0}_{1}".format(hostname, key)
filename = os.path.join(self.certsDir, key + ".crt")
if not os.path.isfile(filename):
logging.debug("Missing file: %s", filename)
continue # skip the non-existant certs
logging.debug('Deleting new %s', alias)
result = self.getOutput(
[self.keytool, '-delete', '-alias', alias, '-keystore',
self.key_store, '-storepass', 'changeit', '-noprompt'])
logging.error(result) if 'error' in result else logging.debug('Delete operation success.')
logging.debug('Importing old %s', alias)
result = self.getOutput(
[self.keytool, '-import', '-trustcacerts', '-file', filename,
'-alias', alias, '-keystore', self.key_store, '-storepass',
'changeit', '-noprompt'])
logging.error(result) if 'error' in result else logging.debug('Certificate import success.')
def stopSolserver(self):
logging.info("Stopping OpenLDAP Server.")
stop_msg = self.getOutput([self.service, 'solserver', 'stop'])
output = self.getOutput([self.service, 'solserver', 'status'])
if "is not running" in output:
return
else:
logging.error("Couldn't stop the OpenLDAP server.")
logging.error(stop_msg)
sys.exit(1)
def startSolserver(self):
logging.info("Starting OpenLDAP Server.")
start_msg = self.getOutput([self.service, 'solserver', 'start'])
output = self.getOutput([self.service, 'solserver', 'status'])
if "is running" in output:
return
else:
logging.error("Couldn't start the OpenLDAP server.")
logging.error(start_msg)
sys.exit(1)
def copyCustomFiles(self):
logging.info("Copying the custom pages and assets of webapps.")
folder_map = [(os.path.join(self.backupDir, 'opt'), '/opt')]
if self.version < 300:
custom = self.backupDir + '/var/gluu/webapps/'
folder_map = [
#(custom + 'oxauth/pages', self.jettyDir + 'oxauth/custom/pages'), #MB: this may break gluu gui
(custom + 'oxauth/resources', self.jettyDir + 'oxauth/custom/static'),
(custom + 'oxauth/libs', self.jettyDir + 'oxauth/lib/ext'),
#(custom + 'oxtrust/pages', self.jettyDir + 'identity/custom/pages'), #MB: this may break gluu gui
(custom + 'oxtrust/resources', self.jettyDir + 'identity/custom/static'),
(custom + 'oxtrust/libs', self.jettyDir + 'identity/lib/ext'),
]
for pair in folder_map:
copy_tree(pair[0], pair[1])
def stopWebapps(self):
logging.info("Stopping Webapps oxAuth and Identity.")
stop_msg = self.getOutput([self.service, 'oxauth', 'stop'])
status = self.getOutput([self.service, 'oxauth', 'status'])
if 'Jetty NOT running' not in status:
logging.error("Couldn't stop oxAuth.")
logging.error(stop_msg)
stop_msg = self.getOutput([self.service, 'identity', 'stop'])
status = self.getOutput([self.service, 'identity', 'status'])
if 'Jetty NOT running' not in status:
logging.error("Couldn't stop Identity.")
logging.error(stop_msg)
def startWebapps(self):
logging.info("Starting Webapps oxAuth and Identity.")
start_msg = self.getOutput([self.service, 'oxauth', 'start'])
status = self.getOutput([self.service, 'oxauth', 'status'])
if 'Jetty running pid' not in status:
logging.error("Couldn't stop oxAuth.")
logging.error(start_msg)
start_msg = self.getOutput([self.service, 'identity', 'start'])
status = self.getOutput([self.service, 'identity', 'status'])
if 'Jetty running pid' not in status:
logging.error("Couldn't stop Identity.")
logging.error(start_msg)
def exportInstallData(self):
self.stopLDAPServer()
logging.info("Exporting LDAP data.")
if self.ldap_type == 'openldap':
output = self.getOutput([self.slapcat, '-f', self.slapdConf,
'-l', self.currentData])
elif self.ldap_type == 'opendj':
output = self.getOutput(
[self.ldif_export, '-n', 'userRoot', '-l', self.currentData])
else:
output = "No LDAP configured."
logging.debug(output)
def convertSchema(self, f):
infile = open(f, 'r')
output = ""
atypeRegex = re.compile('^attributeTypes:\s', re.IGNORECASE)
obclassRegex = re.compile('^objectClasses:\s', re.IGNORECASE)
isOCcontinue = False
for line in infile:
if isOCcontinue:
if line[-1:] == ')':
isOCcontinue = False
else:
isOCcontinue = True
continue
line = line.replace("X-SCHEMA-FILE '100-user.ldif'",
"X-SCHEMA-FILE 'custom.schema'")
line = line.replace("X-SCHEMA-FILE '99-user.ldif'",
"X-SCHEMA-FILE 'custom.schema'")
line = line.replace("'gluu' )",
"'Gluu - custom person attribute' )")
if re.match('^dn:', line) or re.match('^objectClass:', line) or \
re.match('^cn:', line):
continue
# empty lines and the comments are copied as such
if re.match('^#', line) or re.match('^\s*$', line):
pass
elif re.match('^\s\s', line): # change the space indent to tabs
line = re.sub('^\s\s', '\t', line)
elif re.match('^\s', line):
line = re.sub('^\s', '\t', line)
# Change the keyword for attributetype
elif atypeRegex.match(line):
line = atypeRegex.sub('\nattributetype ', line, 1)
oid = 'oxAttribute:' + str(self.attrs + 1)
oidregex = re.compile('\s[\d]+\s', re.IGNORECASE)
line = oidregex.sub(' ' + oid + ' ', line, 1)
self.attrs += 1
# Change the keyword for objectclass
elif obclassRegex.match(line):
if 'SUP gluuPerson' in line and 'objectClass MAY' in line:
att = re.search(r'\((.*?)\)', line.split('objectClass MAY')[1]).group(1)
self.customAttrs.append(att)
continue
elif 'SUP gluuPerson' in line and 'objectClass MUST' in line:
att = re.search(r'\((.*?)\)', line.split('objectClass MUST')[1]).group(1)
self.customAttrs.append(att)
continue
else:
if line[-1:] == ')':
isOCcontinue = False
else:
isOCcontinue = True
continue
else:
logging.debug("Skipping Line: {}".format(line.strip()))
line = ""
output += line
infile.close()
return output
def updateUserSchema(self, infile, outfile):
with open(infile, 'r') as olduser:
with open(outfile, 'w') as newuser:
for line in olduser:
if 'SUP top' in line:
line = line.replace('SUP top', 'SUP gluuPerson')
newuser.write(line)
def collectAllSchemaInfo(self):
result = { 'attributes': {}, 'objectclasses': {} }
for sf in os.listdir(self.open_dj_conf_dir):
sch = OpenDjSchema(os.path.join(self.open_dj_conf_dir, sf))
for a in sch.attribute_names:
result['attributes'][a] = sf
for c in sch.class_names:
result['objectclasses'][c] = sf
return result
def copyCustomSchema(self):
logging.info("Checking Schema files for existance of Gluu attributes and classes")
if self.ldap_type == 'opendj':
attr_class = self.collectAllSchemaInfo()
att_dict = {
'gluuPermission': "( 1486403774573 NAME 'gluuPermission' EQUALITY caseIgnoreMatch ORDERING caseIgnoreOrderingMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 USAGE userApplications X-SCHEMA-FILE '100-user.ldif' X-ORIGIN 'gluu' )",
'imapHost': "( 1486583290517 NAME 'imapHost' EQUALITY caseIgnoreMatch ORDERING caseIgnoreOrderingMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 USAGE userApplications X-SCHEMA-FILE '100-user.ldif' X-ORIGIN 'gluu' )",
'imapUsername': "( 1486583381327 NAME 'imapUsername' EQUALITY caseIgnoreMatch ORDERING caseIgnoreOrderingMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 USAGE userApplications X-SCHEMA-FILE '100-user.ldif' X-ORIGIN 'gluu' )",
'imapPort': "( 1486583426410 NAME 'imapPort' EQUALITY caseIgnoreMatch ORDERING caseIgnoreOrderingMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 USAGE userApplications X-SCHEMA-FILE '100-user.ldif' X-ORIGIN 'gluu' )",
'imapPassword': "( 1486583480345 NAME 'imapPassword' EQUALITY caseIgnoreMatch ORDERING caseIgnoreOrderingMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 USAGE userApplications X-SCHEMA-FILE '100-user.ldif' X-ORIGIN 'gluu' )",
'imapData': "( 1486583825530 NAME 'imapData' EQUALITY caseIgnoreMatch ORDERING caseIgnoreOrderingMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 USAGE userApplications X-SCHEMA-FILE '100-user.ldif' X-ORIGIN 'gluu' )",
}
schema_77 = OpenDjSchema(os.path.join(self.open_dj_conf_dir,'77-customAttributes.ldif'))
w = False
for a in att_dict:
if not a in attr_class['attributes']:
schema_77.add_attributes(att_dict[a])
w = True
if w:
schema_77.write()
if 'gluuCustomPerson' not in attr_class['objectclasses']:
schema_opendj = OpenDjSchema(os.path.join(self.open_dj_conf_dir,'100-user.ldif'))
schema_opendj.add_classs("( 1.3.6.1.4.1.48710.1.4.101 NAME 'gluuCustomPerson' SUP top AUXILIARY MAY ( telephoneNumber $ mobile $ carLicense $ facsimileTelephoneNumber $ departmentNumber $ employeeType $ cn $ st $ manager $ street $ postOfficeBox $ employeeNumber $ preferredDeliveryMethod $ roomNumber $ secretary $ homePostalAddress $ l $ postalCode $ description $ title $ gluuPermission $ imapHost $ imapPort $ imapUsername $ imapPassword ) )")
schema_opendj.write()
else:
schema_opendj = OpenDjSchema(os.path.join(self.open_dj_conf_dir, attr_class['objectclasses']['gluuCustomPerson']))
w = False
gluuCustomPerson = schema_opendj.get_class_by_name('gluuCustomPerson')
may_list = list(gluuCustomPerson.may)
for a in ['imapHost', 'imapPort', 'imapUsername', 'imapPassword', 'gluuPermission']:
if a not in may_list:
may_list.append(a)
w = True
if w:
gluuCustomPerson.may = tuple(may_list)
schema_opendj.write()
#MB: add attribute oxSectorIdentifierURI to 101-ox.ldif
schema_101 = OpenDjSchema(os.path.join(self.open_dj_conf_dir, '101-ox.ldif'))
if not 'oxSectorIdentifierURI' in schema_101.attribute_names:
schema_101.add_attribute(
oid='oxSectorIdentifierURI-oid',
names=['oxSectorIdentifierURI'],
syntax='1.3.6.1.4.1.1466.115.121.1.15',
origin='Gluu created attribute',
desc='ox Sector Identifier URI',
equality='caseIgnoreMatch',
substr='caseIgnoreSubstringsMatch',
)
schema_101.add_attribute_to_class('pairwiseIdentifier', 'oxSectorIdentifierURI')
schema_101.add_attribute_to_class('oxAuthUmaScopeDescription', 'oxUrl')
schema_101.write()
#MB: I did not understand why we are doing followings
"""
# Process for openldap and then append the contents to custom schema
new_user = os.path.join(self.workingDir, 'new_99.ldif')
custom_schema = os.path.join(self.gluuSchemaDir, 'custom.schema')
output = ""
if os.path.isfile(schema_99):
output = self.convertSchema(schema_100)
self.updateUserSchema(schema_99, new_user)
output = output + "\n" + self.convertSchema(new_user)
else:
# If there is no 99-user file, then the schema def is in 100-user
self.updateUserSchema(schema_100, new_user)
output = self.convertSchema(new_user)
outfile2 = open(os.path.join(self.gluuSchemaDir, 'custom.schema'), 'r')
temp_schema = outfile2.read()
custArrtributes = ''
for indx, line in enumerate(self.customAttrs):
custArrtributes = custArrtributes + ' $ ' + line
if len(self.customAttrs) > 0:
customAttrs = set(custArrtributes.split(' $ '))
else:
customAttrs = []
custArrtributes = ""
if len(self.customAttrs) > 0:
for indx, line in enumerate(self.customAttrs):
if indx == 0:
custArrtributes = custArrtributes + " $ " + line
elif (indx < len(self.customAttrs) - 1):
custArrtributes = custArrtributes + line + " $ "
else:
custArrtributes = custArrtributes + line
print custArrtributes
temp_schema = temp_schema.replace(
re.search(r'\((.*?)\)', temp_schema.split('MAY')[1]).group(1),
re.search(r'\((.*?)\)', temp_schema.split('MAY')[1]).group(1) + custArrtributes)
outfile2.close()
outfile = open(custom_schema, 'w')
outfile.write(output + "\n" + temp_schema)
outfile.close()
eduperson = ""
eduPath = os.path.join("/opt", "symas", "etc", "openldap", "schema", "eduperson.schema")
input_file = open(eduPath)
try:
for i, line in enumerate(input_file):
if i == 62:
line = line + "\n" + "attributetype ( 1.3.6.1.4.1.5923.1.1.1.9"
line = line + "\n" + "\t\tNAME 'eduPersonScopedAffiliation'"
line = line + "\n" + "\t\tDESC 'eduPerson per Internet2 and EDUCAUSE'"
line = line + "\n" + "\t\tEQUALITY caseIgnoreMatch"
line = line + "\n" + "\t\tSYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )"
line = line + "\n"
line = line + "\n" + "attributetype ( 1.3.6.1.4.1.5923.1.1.1.10"
line = line + "\n" + "\t\tNAME 'eduPersonTargetedID'"
line = line + "\n" + "\t\tDESC 'eduPerson per Internet2 and EDUCAUSE'"
line = line + "\n" + "\t\tEQUALITY caseIgnoreMatch"
line = line + "\n" + "\t\tSYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )"
line = line + "\n"
line = line + "\n" + "attributetype ( 1.3.6.1.4.1.5923.1.1.1.11"
line = line + "\n" + "\t\tNAME 'eduPersonAssurance'"
line = line + "\n" + "\t\tDESC 'eduPerson per Internet2 and EDUCAUSE'"
line = line + "\n" + "\t\tEQUALITY caseIgnoreMatch"
line = line + "\n" + "\t\tSYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )"
line = line + "\n\n"
if i == 63:
line = "\n" + line
if i == 67:
line = line + "\t\teduPersonScopedAffiliation $ eduPersonTargetedID $ eduPersonAssurance $\n"
eduperson = eduperson + line
except Exception, e:
logging.log(e)
finally:
input_file.close()
f = open(eduPath, "w")
f.write(eduperson)
"""
def getEntry(self, fn, dn):
parser = MyLDIF(open(fn, 'rb'), sys.stdout)
parser.targetDN = dn
parser.parse()
return parser.targetEntry
def getDns(self, fn):
parser = MyLDIF(open(fn, 'rb'), sys.stdout)
parser.parse()
return parser.DNs
def getOldEntryMap(self):
logging.info("Preparing dn entry map")
files = os.listdir(self.ldifDir)
dnMap = {}
# get the new admin DN
admin_ldif = '/install/community-edition-setup/output/people.ldif'
admin_dn = self.getDns(admin_ldif)[0]
for fn in files:
logging.info("Processing %s to create dn entry map" % fn)
dnList = self.getDns(os.path.join(self.ldifDir, fn))
for dn in dnList:
# skip the entry of Admin DN
if fn == 'people.ldif' and admin_dn in dn:
continue
dnMap[dn] = fn
return dnMap
def convertTimeStamp(self, line):
dateString = line.replace('oxAuthAuthenticationTime:', '').strip()
try:
dateTimestamp = time.mktime(time.strptime(dateString, "%a %b %d %H:%M:%S %Z %Y"))
dateString = time.strftime("%Y%m%d%H%M%S", time.gmtime(dateTimestamp))
ts = time.time()
utc_offset = (datetime.datetime.fromtimestamp(ts) - datetime.datetime.utcfromtimestamp(ts)).total_seconds()
dateString = "%s.%03dZ" % (
time.strftime("%Y%m%d%H%M%S", time.localtime(dateTimestamp)), int(utc_offset // 60))
except ValueError:
# Data from OpenLDAP would already be in the expected format.
# The above parsing would happen only for data from OpenDJ.
pass
return "%s: %s\n" % ('oxAuthAuthenticationTime', dateString)
def convertRefreshLastUpdate(self, line):
dateString = line.replace('gluuVdsCacheRefreshLastUpdate: ', '').strip()
try:
dateTimestamp = time.mktime(time.strptime(dateString, "%a %b %d %H:%M:%S %Z %Y"))
dateString = time.strftime("%Y%m%d%H%M%S", time.gmtime(dateTimestamp))
ts = time.time()
utc_offset = (datetime.datetime.fromtimestamp(ts) - datetime.datetime.utcfromtimestamp(ts)).total_seconds()
dateString = "%s.%03dZ" % (
time.strftime("%Y%m%d%H%M%S", time.localtime(dateTimestamp)), int(utc_offset // 60))
except ValueError:
# Data from OpenLDAP would already be in the expected format.
# The above parsing would happen only for data from OpenDJ.
pass
return "%s: %s\n" % ('gluuVdsCacheRefreshLastUpdate', dateString)
def processBackupData(self):
logging.info('Processing the LDIF data.')
processed_fp = open(self.processTempFile, 'w')
ldif_writer = LDIFWriter(processed_fp,
base64_attrs=['gluuProfileConfiguration'])
currentDNs = self.getDns(self.currentData)
old_dn_map = self.getOldEntryMap()
ignoreList = ['objectClass', 'ou', 'oxIDPAuthentication',
'gluuFreeMemory', 'gluuSystemUptime',
'oxLogViewerConfig', 'gluuLastUpdate']
multivalueAttrs = ['oxTrustEmail', 'oxTrustPhoneValue', 'oxTrustImsValue',
'oxTrustPhotos', 'oxTrustAddresses', 'oxTrustRole',
'oxTrustEntitlements', 'oxTrustx509Certificate']
if self.ldap_type == 'opendj':
ignoreList.remove('oxIDPAuthentication')
# Rewriting all the new DNs in the new installation to ldif file
nodn=len(currentDNs)
for cnt, dn in enumerate(currentDNs):
progress_bar(cnt, nodn, 'Rewriting DNs')
new_entry = self.getEntry(self.currentData, dn)
if "o=site" in dn:
continue # skip all the o=site DNs
if dn not in old_dn_map.keys():
# Write to the file if there is no matching old DN data
ldif_writer.unparse(dn, new_entry)
continue
old_entry = self.getEntry(os.path.join(self.ldifDir, old_dn_map[dn]), dn)
for attr in old_entry.keys():
if attr in ignoreList:
continue
if attr not in new_entry:
new_entry[attr] = old_entry[attr]
elif old_entry[attr] != new_entry[attr]:
if len(old_entry[attr]) == 1:
try:
old_json = json.loads(old_entry[attr][0])
new_json = json.loads(new_entry[attr][0])
new_json = merge(new_json, old_json)
new_entry[attr] = [json.dumps(new_json)]
except:
if attr == 'oxScript':
new_entry[attr] = new_entry[attr]
logging.debug("Keeping new value for %s", attr)
else:
new_entry[attr] = old_entry[attr]
logging.debug("Keeping old value for %s", attr)
else:
new_entry[attr] = old_entry[attr]
logging.debug("Keep multiple old values for %s", attr)
ldif_writer.unparse(dn, new_entry)
progress_bar(0, 0, 'Rewriting DNs', True)
# Pick all the left out DNs from the old DN map and write them to the LDIF
nodn = len(old_dn_map)
ldif_shelve_dict = {}
for cnt, dn in enumerate(sorted(old_dn_map, key=len)):
progress_bar(cnt, nodn, 'Perapring DNs for 3.1.2')
if "o=site" in dn:
continue # skip all the o=site DNs
if dn in currentDNs:
continue # Already processed
cur_ldif_file = old_dn_map[dn]
if not cur_ldif_file in ldif_shelve_dict:
sdb=DBLDIF(os.path.join(self.ldifDir, cur_ldif_file))
sdb.parse()
ldif_shelve_dict[cur_ldif_file]=sdb.sdb
entry = ldif_shelve_dict[cur_ldif_file][dn]
#MB: (1) TODO: instead of processing ldif twice, appy this method for (2)
if 'ou=people' in dn:
for o in entry['objectClass']:
if o.startswith('ox-'):
entry['objectClass'].remove(o)
entry['objectClass'].append('gluuCustomPerson')
break
if 'ou=trustRelationships' in dn:
if 'gluuIsFederation' in entry:
if entry['gluuIsFederation'][0] == 'true':
entry['gluuEntityType'] = ['Federation/Aggregate']
else:
entry['gluuEntityType'] = ['Single SP']
entry['gluuSpecificRelyingPartyConfig']=['true']
LONGBASE64ENCODEDSTRING = '<rp:ProfileConfiguration xsi:type="saml:SAML2SSOProfile" \n\tincludeAttributeStatement="true"\n\tassertionLifetime="300000"\n\tassertionProxyCount="0"\n\tsignResponses="conditional"\n\tsignAssertions="never"\n\tsignRequests="conditional"\n\tencryptAssertions="conditional"\n\tencryptNameIds="never"\n/>'
if not 'gluuProfileConfiguration' in entry:
entry['gluuProfileConfiguration']=[LONGBASE64ENCODEDSTRING]
else:
entry['gluuProfileConfiguration'].append(LONGBASE64ENCODEDSTRING)
for attr in entry.keys():
if attr not in multivalueAttrs:
continue # skip conversion
attr_values = []
for val in entry[attr]:
json_value = None
try:
json_value = json.loads(val)
if type(json_value) is list:
attr_values.extend([json.dumps(v) for v in json_value])
else:
attr_values.append(val)
except:
logging.debug('Cannot parse multival %s in DN %s', attr, dn)
attr_values.append(val)
entry[attr] = attr_values
if 'oxAuthClientCustomAttributes' in entry['objectClass']:
entry['objectClass'].remove('oxAuthClientCustomAttributes')
ldif_writer.unparse(dn, entry)
# Finally
processed_fp.close()
progress_bar(0, 0, 'Perapring DNs for 3.1.2', True)
#MB: (2) replace the following with above method
# Update the Schema change for lastModifiedTime
nodn = sum(1 for line in open(self.processTempFile))
with open(self.processTempFile, 'r') as infile:
with open(self.o_gluu, 'w') as outfile:
for cnt, line in enumerate(infile):
progress_bar(cnt, nodn, 'converting Dns')
line = line.replace("lastModifiedTime", "oxLastAccessTime")
line = line.replace('oxAuthUmaResourceSet', 'oxUmaResource')
if ("gluuAttributeOrigin:" in line and line.split("gluuAttributeOrigin: ")[1][:3] == 'ox-'):
line = 'gluuAttributeOrigin: gluuCustomPerson' + '\n'
if ("gluuAttributeOrigin:" in line and 'inetOrgPerson' in line):
line = 'gluuAttributeOrigin: gluuCustomPerson' + '\n'
if 'oxAuthAuthenticationTime' in line:
line = self.convertTimeStamp(line)
if 'oxAuthenticationMode' in line:
line = 'oxAuthenticationMode: auth_ldap_server' + '\n'
if 'oxTrustAuthenticationMode' in line:
line = 'oxTrustAuthenticationMode: auth_ldap_server'+ '\n'
#MB: See (1) how we implement this
#if ("objectClass:" in line and line.split("objectClass: ")[1][:3] == 'ox-'):
# line = line.replace(line, 'objectClass: gluuCustomPerson' + '\n')
if 'oxType' not in line and 'gluuVdsCacheRefreshLastUpdate' not in line and 'objectClass: person' not in line and 'objectClass: organizationalPerson' not in line and 'objectClass: inetOrgPerson' not in line:
outfile.write(line)
# parser = MyLDIF(open(self.currentData, 'rb'), sys.stdout)
# atr = parser.parse()
base64Types = [""]
# for idx, val in enumerate(parser.entries):
# if 'displayName' in val:
# if val['displayName'][0] == 'SCIM Resource Set':
# out = CreateLDIF(parser.getDNs()[idx], val,
# base64_attrs=base64Types)
# f = open(self.o_gluu, "a")
# f.write('\n')
# f.write(out)
#data="".join(open( os.path.join(self.backupDir, 'ldif','site.ldif')).readlines()[4:-1])
#open(os.path.join(self.backupDir, 'ldif','sitetmp.ldif'),"wb").write(data)
#filenames = [self.o_site_static, os.path.join(self.backupDir, 'ldif','sitetmp.ldif')]
#with open(self.o_site, 'w') as outfile:
# for fname in filenames:
# with open(fname) as infile:
# for line in infile:
# outfile.write(line)
#os.remove(os.path.join(self.backupDir, 'ldif','sitetmp.ldif'))
progress_bar(0, 0, 'converting Dns', True)
def importDataIntoOpenldap(self):
count = len(os.listdir('/opt/gluu/data/main_db/')) - 1
backupfile = self.ldapDataFile + ".bkp_{0:02d}".format(count)
logging.debug("Moving %s to %s.", self.ldapDataFile, backupfile)
try:
shutil.move(self.ldapDataFile, backupfile)
except IOError:
logging.debug(traceback.format_exc())
count = len(os.listdir('/opt/gluu/data/site_db/')) - 1
backupfile = self.ldapSiteFile + ".bkp_{0:02d}".format(count)
logging.debug("Moving %s to %s.", self.ldapSiteFile, backupfile)
try:
shutil.move(self.ldapSiteFile, backupfile)
except IOError:
logging.debug(traceback.format_exc())
output = self.getOutput([self.slapadd, '-c', '-b', 'o=gluu', '-f',
self.slapdConf, '-l', self.o_gluu])
logging.debug(output)
output = self.getOutput([self.slapadd, '-c', '-b', 'o=site', '-f',
self.slapdConf, '-l', self.o_site])
logging.debug(output)
def importDataIntoOpenDJ(self):
command = [self.ldif_import, '-n', 'userRoot',
'-l', self.o_gluu, '-R', self.o_gluu + '.rejects']
output = self.getOutput(command)
logging.debug(output)
command = [self.ldif_import, '-n', 'site',
'-l', self.o_site, '-R', self.o_site + '.rejects']
output = self.getOutput(command)
logging.debug(output)
def importProcessedData(self):
logging.info("Importing Processed LDAP data.")
if self.ldap_type == 'openldap':
self.importDataIntoOpenldap()
else:
self.importDataIntoOpenDJ()
def getLDAPServerType(self):
choice = 0
if os.path.isfile(self.setup_properties):
data = ""
try:
with open(self.setup_properties) as f:
for line in f:
if line == 'ldap_type=openldap\n':
choice = 1
elif line == 'ldap_type=opendj\n':
choice = 2
except:
logging.error(self.setup_properties+" File not Found")
sys.exit(0)
if choice == 1:
self.ldap_type = 'openldap'
elif choice == 2:
self.ldap_type = 'opendj'
else:
logging.error("Invalid selection of LDAP Server. Cannot Migrate.")
sys.exit(1)
def stopOpenDJ(self):
logging.info('Stopping OpenDJ Directory Server...')
if (os.path.isfile('/usr/bin/systemctl')):
self.getOutput(['systemctl', 'stop', 'opendj'])
output = self.getOutput(['systemctl', 'is-active', 'opendj'])
else:
output = self.getOutput([self.service, 'opendj', 'stop'])
if output.find("Directory Server is now stopped") > 0 or \
output.strip() == "failed":
logging.info("Directory Server is now stopped")
else:
logging.error(
"OpenDJ did not stop properly. Import cannot run without "
"stopping the directory server. Exiting from import. Check"
" /opt/opendj/logs/errors")
sys.exit(1)
def startOpenDJ(self):
logging.info('Starting OpenDJ Directory Server...')
if (os.path.isfile('/usr/bin/systemctl')):
self.getOutput(['systemctl', 'start', 'opendj'])
output = self.getOutput(['systemctl', 'is-active', 'opendj'])
if output.find("Directory Server has started successfully") > 0 or \
output.strip() == "active":
logging.info("Directory Server has started successfully")
else:
# start opendj through service
output = self.getOutput([self.service, 'opendj', 'start'])
if output != "":
logging.error("OpenDJ did not start properly. Check "
"/opt/opendj/logs/errors. Restart it manually.")
sys.exit(1)
def stopLDAPServer(self):
if self.ldap_type == 'openldap':
self.stopSolserver()
else:
self.stopOpenDJ()
def startLDAPServer(self):
if self.ldap_type == 'openldap':
self.startSolserver()
else:
self.startOpenDJ()
def copyIDPFiles(self):
idp_dir = os.path.join(self.backupDir, 'opt', 'idp')
if os.path.isdir(idp_dir):
logging.info('Copying Shibboleth IDP files...')
if os.path.isdir(os.path.join(idp_dir, 'metadata')):
copy_tree(
os.path.join(self.backupDir, 'opt', 'idp', 'metadata'),
'/opt/shibboleth-idp/metadata')
if os.path.isdir(os.path.join(idp_dir, 'ssl')):
copy_tree(
os.path.join(self.backupDir, 'opt', 'idp', 'ssl'),
'/opt/shibboleth-idp/ssl')
def fixPermissions(self):
logging.info('Fixing permissions for files.')
if self.ldap_type == 'openldap':
self.getOutput(['chown', 'ldap:ldap', self.ldapDataFile])
self.getOutput(['chown', 'ldap:ldap', self.ldapSiteFile])
else:
self.getOutput(['chown', '-R', 'ldap:ldap', '/opt/opendj/db'])
def getProp(self, prop, prop_file=None):
if not prop_file:
prop_file = os.path.join(self.backupDir, 'setup.properties')
with open(prop_file, 'r') as f:
for line in f:
n = line.find('=')
if n > -1:
if line[:n]==prop:
tmp = line[n+1:].strip()
return tmp.replace('\\=','=')
def unobscure(self,s=""):
engine = pyDes.triple_des(self.key, pyDes.ECB, pad=None, padmode=pyDes.PAD_PKCS5)
cipher = pyDes.triple_des(self.key)
decrypted = cipher.decrypt(base64.b64decode(s), padmode=pyDes.PAD_PKCS5)
return decrypted
def getLdapPassword(self):
try:
with open('/etc/gluu/conf/ox-ldap.properties') as f:
for line in f:
if line.startswith("bindPassword:"):
self.ldappassowrd = line.split(":")[1].split("\n")[0].strip()
except:
logging.error("ox-ldap.properties file not Found")