View | Details | Raw Unified | Return to bug 30722
Collapse All | Expand All

(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/syntax.py (-3 / +3 lines)
 Lines 1036-1046   class date(simple): Link Here 
1036
1036
1037
	@classmethod
1037
	@classmethod
1038
	def parse(self, text):
1038
	def parse(self, text):
1039
		if self._re_iso.match(text) != None:
1039
		if text and self._re_iso.match(text):
1040
			year, month, day = map(lambda(x): int(x), text.split('-'))
1040
			year, month, day = map(lambda(x): int(x), text.split('-'))
1041
			if 1960 < year < 2100 and 1 <= month <= 12 and 1 <= day <= 31:
1041
			if 1960 < year < 2100 and 1 <= month <= 12 and 1 <= day <= 31:
1042
				return '%02d.%02d.%s' % ( day, month, str( year )[ 2 : ] )
1042
				return '%02d.%02d.%02d' % (day, month, year % 100)
1043
		if self._re_de.match(text) != None:
1043
		if text and self._re_de.match(text):
1044
			day, month, year = map(lambda(x): int(x), text.split('.'))
1044
			day, month, year = map(lambda(x): int(x), text.split('.'))
1045
			if 0 <= year <= 99 and 1 <= month <= 12 and 1 <= day <= 31:
1045
			if 0 <= year <= 99 and 1 <= month <= 12 and 1 <= day <= 31:
1046
				return text
1046
				return text
(-)a/branches/ucs-3.1/ucs/management/univention-management-console-module-udm/umc/python/udm/__init__.py (-6 / +15 lines)
 Lines 799-812   class Instance( Base ): Link Here 
799
						except ( udm_errors.valueInvalidSyntax, udm_errors.valueError, TypeError ), e:
799
						except ( udm_errors.valueInvalidSyntax, udm_errors.valueError, TypeError ), e:
800
							subResults.append( False )
800
							subResults.append( False )
801
							subDetails.append( str(e) )
801
							subDetails.append( str(e) )
802
					result.append( { 'property' : property_name, 'valid' : subResults, 'details' : subDetails } )
802
					result.append({
803
						'property': property_name,
804
						'valid': subResults,
805
						'details': subDetails
806
						})
803
				# otherwise we have a single value
807
				# otherwise we have a single value
804
				else:
808
				else:
805
					try:
809
					try:
806
						property_obj.syntax.parse( value )
810
						property_obj.syntax.parse( value )
807
						result.append( { 'property' : property_name, 'valid' : True } )
811
						result.append({
808
					except ( udm_errors.valueInvalidSyntax, udm_errors.valueError ), e:
812
							'property': property_name,
809
						result.append( { 'property' : property_name, 'valid' : False, 'details' : str( e ) } )
813
							'valid': True
814
							})
815
					except (udm_errors.valueInvalidSyntax, udm_errors.valueError, TypeError), ex:
816
						result.append({
817
							'property': property_name,
818
							'valid': False,
819
							'details' : str(ex)
820
							})
810
821
811
			return result
822
			return result
812
823
813
- 
814
--
815
.../modules/univention/admin/syntax.py                   |   14 +++++++++-----
824
.../modules/univention/admin/syntax.py                   |   14 +++++++++-----
816
1 file changed, 9 insertions(+), 5 deletions(-)
825
1 file changed, 9 insertions(+), 5 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/syntax.py (-7 / +9 lines)
 Lines 702-708   class uid(simple): Link Here 
702
	"""
702
	"""
703
	min_length=1
703
	min_length=1
704
	max_length=16
704
	max_length=16
705
	regex = re.compile('(?u)(^[a-zA-Z0-9])[a-zA-Z0-9._-]*([a-zA-Z0-9]$)')
705
	regex = re.compile('^(?!admin$)[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$', re.UNICODE)
706
	error_message = _("Value must not contain anything other than digits, letters, dots, dash or underscore, must be at least 2 characters long, must start and end with a digit or letter, and must not be admin!")
706
	error_message = _("Value must not contain anything other than digits, letters, dots, dash or underscore, must be at least 2 characters long, must start and end with a digit or letter, and must not be admin!")
707
707
708
class uid_umlauts(simple):
708
class uid_umlauts(simple):
 Lines 1111-1117   class dnsSRVName(complex): Link Here 
1111
	"""
1111
	"""
1112
	min_elements = 2
1112
	min_elements = 2
1113
	all_required = False
1113
	all_required = False
1114
	subsyntaxes = ( ( _( 'Service' ), TwoThirdsString ), ( _( 'Protocol' ), ipProtocolSRV ), ( _( 'Extension' ), string ) )
1114
	subsyntaxes = (
1115
			(_('Service'), TwoThirdsString),
1116
			(_('Protocol'), ipProtocolSRV),
1117
			(_('Extension'), string)
1118
			)
1115
1119
1116
class postalAddress( complex ):
1120
class postalAddress( complex ):
1117
	delimiter = ', '
1121
	delimiter = ', '
 Lines 2448-2458   class LDAP_Search( select ): Link Here 
2448
	Searches can be either defined dynamically via a UDM settings/syntax
2452
	Searches can be either defined dynamically via a UDM settings/syntax
2449
	definition and using
2453
	definition and using
2450
2454
2451
	>>> LDAP_Search( syntax_name = '<NAME>' )
2455
	> LDAP_Search( syntax_name = '<NAME>' )
2452
2456
2453
	or programmatically	by directly instantiating
2457
	or programmatically by directly instantiating
2454
2458
2455
	>>> LDAP_Search( filter = '<LDAP-Search-Filter>', attribute = [ '<LDAP attributes>', ... ], value = '<LDAP attribute>', base = '<LDAP base>' )
2459
	> LDAP_Search(filter='<LDAP-Search-Filter>', attribute=['<LDAP attributes>', ...], value='<LDAP attribute>', base='<LDAP base>')
2456
	"""
2460
	"""
2457
	FILTER_PATTERN = '(&(objectClass=univentionSyntax)(cn=%s))'
2461
	FILTER_PATTERN = '(&(objectClass=univentionSyntax)(cn=%s))'
2458
2462
2459
- 
2460
--
2461
.../modules/univention/admin/handlers/users/user.py           |    9 ---------
2463
.../modules/univention/admin/handlers/users/user.py           |    9 ---------
2462
1 file changed, 9 deletions(-)
2464
1 file changed, 9 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-11 lines)
 Lines 1087-1101   def GMTOffset(): Link Here 
1087
	# returns the difference in hours between local time and GMT (is -1 for CET and CEST)
1087
	# returns the difference in hours between local time and GMT (is -1 for CET and CEST)
1088
	return time.timezone/3600
1088
	return time.timezone/3600
1089
1089
1090
def shift(string, offset):
1091
	# shifts the string #offset chars to the left
1092
	if offset<0:
1093
		for i in range(0, abs(offset)):
1094
			string=string[-1:]+string[:-1]
1095
	else:
1096
		for i in range(0, offset):
1097
			string=string[1:]+string[:1]
1098
	return string
1099
1090
1100
def load_certificate(user_certificate):
1091
def load_certificate(user_certificate):
1101
	"""Import a certificate in DER format"""
1092
	"""Import a certificate in DER format"""
1102
- 
1103
--
1104
.../univention/admin/handlers/users/user.py        |   92 ++++++++++----------
1093
.../univention/admin/handlers/users/user.py        |   92 ++++++++++----------
1105
1 file changed, 46 insertions(+), 46 deletions(-)
1094
1 file changed, 46 insertions(+), 46 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-48 / +46 lines)
 Lines 57-63   import univention.admin.uldap Link Here 
57
import univention.admin.mungeddial as mungeddial
57
import univention.admin.mungeddial as mungeddial
58
import univention.admin.handlers.settings.prohibited_username
58
import univention.admin.handlers.settings.prohibited_username
59
59
60
import univention.debug
60
import univention.debug as ud
61
import univention.password
61
import univention.password
62
62
63
translation=univention.admin.localization.translation('univention.admin.handlers.users')
63
translation=univention.admin.localization.translation('univention.admin.handlers.users')
 Lines 1003-1013   def posixDaysToDate(days): Link Here 
1003
	return time.strftime("%Y-%m-%d",time.gmtime(long(days)*3600*24))
1003
	return time.strftime("%Y-%m-%d",time.gmtime(long(days)*3600*24))
1004
1004
1005
def sambaWorkstationsMap(workstations):
1005
def sambaWorkstationsMap(workstations):
1006
	univention.debug.debug(univention.debug.ADMIN, univention.debug.ALL, 'samba: sambaWorkstationMap: in=%s; out=%s' % (workstations,string.join(workstations, ',')))
1006
	ud.debug(ud.ADMIN, ud.ALL, 'samba: sambaWorkstationMap: in=%s; out=%s' % (workstations,string.join(workstations, ',')))
1007
	return string.join(workstations, ',')
1007
	return string.join(workstations, ',')
1008
1008
1009
def sambaWorkstationsUnmap(workstations):
1009
def sambaWorkstationsUnmap(workstations):
1010
	univention.debug.debug(univention.debug.ADMIN, univention.debug.ALL, 'samba: sambaWorkstationUnmap: in=%s; out=%s' % (workstations[0],string.split(workstations[0],',')))
1010
	ud.debug(ud.ADMIN, ud.ALL, 'samba: sambaWorkstationUnmap: in=%s; out=%s' % (workstations[0],string.split(workstations[0],',')))
1011
	return string.split(workstations[0],',')
1011
	return string.split(workstations[0],',')
1012
1012
1013
def logonHoursMap(logontimes):
1013
def logonHoursMap(logontimes):
 Lines 1173-1179   def load_certificate(user_certificate): Link Here 
1173
		elif re.match('^emailAddress=', i):
1173
		elif re.match('^emailAddress=', i):
1174
			value['certificateSubjectMail']=string.split(i, '=')[1]
1174
			value['certificateSubjectMail']=string.split(i, '=')[1]
1175
1175
1176
	univention.debug.debug(univention.debug.ADMIN, univention.debug.ERROR, 'value=%s' % value)
1176
	ud.debug(ud.ADMIN, ud.ERROR, 'value=%s' % value)
1177
	return value
1177
	return value
1178
1178
1179
def mapHomePostalAddress(old):
1179
def mapHomePostalAddress(old):
 Lines 1244-1250   def unmapBase64( value ): Link Here 
1244
	try:
1244
	try:
1245
		return base64.encodestring( value[ 0 ] )
1245
		return base64.encodestring( value[ 0 ] )
1246
	except Exception, e:
1246
	except Exception, e:
1247
		univention.debug.debug(univention.debug.ADMIN, univention.debug.ERROR, 'ERROR in users.user.mapBase64(): %s' % e)
1247
		ud.debug(ud.ADMIN, ud.ERROR, 'ERROR in users.user.mapBase64(): %s' % e)
1248
	return ""
1248
	return ""
1249
1249
1250
def mapBase64( value ):
1250
def mapBase64( value ):
 Lines 1254-1260   def mapBase64( value ): Link Here 
1254
	try:
1254
	try:
1255
		return base64.decodestring( value )
1255
		return base64.decodestring( value )
1256
	except Exception, e:
1256
	except Exception, e:
1257
		univention.debug.debug(univention.debug.ADMIN, univention.debug.ERROR, 'ERROR in users.user.mapBase64(): %s' % e)
1257
		ud.debug(ud.ADMIN, ud.ERROR, 'ERROR in users.user.mapBase64(): %s' % e)
1258
	return ""
1258
	return ""
1259
1259
1260
mapping.register('userCertificate', 'userCertificate;binary', mapBase64, unmapBase64 )
1260
mapping.register('userCertificate', 'userCertificate;binary', mapBase64, unmapBase64 )
 Lines 1360-1366   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1360
				if options[opt].matches(ocs):
1360
				if options[opt].matches(ocs):
1361
					self.options.append(opt)
1361
					self.options.append(opt)
1362
		else:
1362
		else:
1363
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user.py: reset options to default by _define_options' )
1363
			ud.debug(ud.ADMIN, ud.INFO, 'users/user.py: reset options to default by _define_options' )
1364
			self._define_options( options )
1364
			self._define_options( options )
1365
1365
1366
		if 'posix' in self.options:
1366
		if 'posix' in self.options:
 Lines 1370-1394   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1370
			# shadowExpire contains the absolute date to expire the account.
1370
			# shadowExpire contains the absolute date to expire the account.
1371
1371
1372
			if 'shadowExpire' in self.oldattr and len(self.oldattr['shadowExpire']) > 0 :
1372
			if 'shadowExpire' in self.oldattr and len(self.oldattr['shadowExpire']) > 0 :
1373
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'userexpiry: %s' % posixDaysToDate(self.oldattr['shadowExpire'][0]))
1373
				ud.debug(ud.ADMIN, ud.INFO, 'userexpiry: %s' % posixDaysToDate(self.oldattr['shadowExpire'][0]))
1374
				if self.oldattr['shadowExpire'][0] != '1':
1374
				if self.oldattr['shadowExpire'][0] != '1':
1375
					self.info['userexpiry'] = posixDaysToDate(self.oldattr['shadowExpire'][0])
1375
					self.info['userexpiry'] = posixDaysToDate(self.oldattr['shadowExpire'][0])
1376
			if 'shadowLastChange' in self.oldattr and 'shadowMax' in self.oldattr and len(self.oldattr['shadowLastChange']) > 0 and len(self.oldattr['shadowMax']) > 0:
1376
			if 'shadowLastChange' in self.oldattr and 'shadowMax' in self.oldattr and len(self.oldattr['shadowLastChange']) > 0 and len(self.oldattr['shadowMax']) > 0:
1377
				try:
1377
				try:
1378
					self.info['passwordexpiry'] = posixDaysToDate(int(self.oldattr['shadowLastChange'][0]) +  int(self.oldattr['shadowMax'][0]))
1378
					self.info['passwordexpiry'] = posixDaysToDate(int(self.oldattr['shadowLastChange'][0]) +  int(self.oldattr['shadowMax'][0]))
1379
				except:
1379
				except:
1380
					univention.debug.debug(univention.debug.ADMIN, univention.debug.WARN, 'users/user: failed to calculate password expiration correctly, use only shadowMax instead')
1380
					ud.debug(ud.ADMIN, ud.WARN, 'users/user: failed to calculate password expiration correctly, use only shadowMax instead')
1381
					self.info['passwordexpiry'] = posixDaysToDate(int(self.oldattr['shadowMax'][0]))
1381
					self.info['passwordexpiry'] = posixDaysToDate(int(self.oldattr['shadowMax'][0]))
1382
1382
1383
		if 'kerberos' in self.options:
1383
		if 'kerberos' in self.options:
1384
			if self.oldattr.has_key('krb5ValidEnd'):
1384
			if self.oldattr.has_key('krb5ValidEnd'):
1385
				krb5validend=self.oldattr['krb5ValidEnd'][0]
1385
				krb5validend=self.oldattr['krb5ValidEnd'][0]
1386
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'krb5validend is: %s' %
1386
				ud.debug(ud.ADMIN, ud.INFO, 'krb5validend is: %s' %
1387
						       krb5validend)
1387
						       krb5validend)
1388
				self.info['userexpiry']="%s-%s-%s"%(krb5validend[0:4],krb5validend[4:6],krb5validend[6:8])
1388
				self.info['userexpiry']="%s-%s-%s"%(krb5validend[0:4],krb5validend[4:6],krb5validend[6:8])
1389
		elif 'samba' in self.options:
1389
		elif 'samba' in self.options:
1390
			if self.oldattr.has_key('sambaKickoffTime'):
1390
			if self.oldattr.has_key('sambaKickoffTime'):
1391
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'sambaKickoffTime is: %s' %
1391
				ud.debug(ud.ADMIN, ud.INFO, 'sambaKickoffTime is: %s' %
1392
						       self.oldattr['sambaKickoffTime'][0])
1392
						       self.oldattr['sambaKickoffTime'][0])
1393
				self.info['userexpiry']=time.strftime("%Y-%m-%d",time.gmtime(long(self.oldattr['sambaKickoffTime'][0])+(3600*24)))
1393
				self.info['userexpiry']=time.strftime("%Y-%m-%d",time.gmtime(long(self.oldattr['sambaKickoffTime'][0])+(3600*24)))
1394
1394
 Lines 1404-1411   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1404
			# FIXME: we should NEVER catch all exceptions
1404
			# FIXME: we should NEVER catch all exceptions
1405
			except Exception, e:
1405
			except Exception, e:
1406
				# at least write some debuging output..
1406
				# at least write some debuging output..
1407
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'Caught exception: %s' % e )
1407
				ud.debug(ud.ADMIN, ud.INFO, 'Caught exception: %s' % e )
1408
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'Continuing without dn..')
1408
				ud.debug(ud.ADMIN, ud.INFO, 'Continuing without dn..')
1409
				self.dn=None
1409
				self.dn=None
1410
				return
1410
				return
1411
1411
 Lines 1418-1425   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1418
				self['lastname']=sn
1418
				self['lastname']=sn
1419
		except Exception, e:					# FIXME: we should NEVER catch all exceptions
1419
		except Exception, e:					# FIXME: we should NEVER catch all exceptions
1420
			# at least write some debuging output..
1420
			# at least write some debuging output..
1421
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'Caught exception: %s' % e )
1421
			ud.debug(ud.ADMIN, ud.INFO, 'Caught exception: %s' % e )
1422
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'Continuing without dn..')
1422
			ud.debug(ud.ADMIN, ud.INFO, 'Continuing without dn..')
1423
			self.dn=None
1423
			self.dn=None
1424
			return
1424
			return
1425
1425
 Lines 1461-1467   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1461
						self['groups']=self.lo.searchDn(filter='(&(cn=*)(|(objectClass=univentionGroup)(objectClass=sambaGroupMapping))(uniqueMember=%s))' % univention.admin.filter.escapeForLdapFilter(self.dn))
1461
						self['groups']=self.lo.searchDn(filter='(&(cn=*)(|(objectClass=univentionGroup)(objectClass=sambaGroupMapping))(uniqueMember=%s))' % univention.admin.filter.escapeForLdapFilter(self.dn))
1462
					else:
1462
					else:
1463
						self.groupsLoaded=0
1463
						self.groupsLoaded=0
1464
						univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'user: open with loadGroups=false for user %s'%self['username'])
1464
						ud.debug(ud.ADMIN, ud.INFO, 'user: open with loadGroups=false for user %s'%self['username'])
1465
					primaryGroupNumber=self.oldattr.get('gidNumber',[''])[0]
1465
					primaryGroupNumber=self.oldattr.get('gidNumber',[''])[0]
1466
					if primaryGroupNumber:
1466
					if primaryGroupNumber:
1467
						primaryGroupResult=self.lo.searchDn('(&(cn=*)(|(objectClass=posixGroup)(objectClass=sambaGroupMapping))(gidNumber='+primaryGroupNumber+'))')
1467
						primaryGroupResult=self.lo.searchDn('(&(cn=*)(|(objectClass=posixGroup)(objectClass=sambaGroupMapping))(gidNumber='+primaryGroupNumber+'))')
 Lines 1477-1483   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1477
							except:
1477
							except:
1478
								primaryGroup = None
1478
								primaryGroup = None
1479
1479
1480
							univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'user: could not find primaryGroup, setting primaryGroup to %s' % primaryGroup)
1480
							ud.debug(ud.ADMIN, ud.INFO, 'user: could not find primaryGroup, setting primaryGroup to %s' % primaryGroup)
1481
1481
1482
							self['primaryGroup']=primaryGroup
1482
							self['primaryGroup']=primaryGroup
1483
							self.newPrimaryGroupDn=primaryGroup
1483
							self.newPrimaryGroupDn=primaryGroup
 Lines 1689-1714   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1689
1689
1690
		# change memberUid if we have a new username
1690
		# change memberUid if we have a new username
1691
		if not old_uid == new_uid and self.exists():
1691
		if not old_uid == new_uid and self.exists():
1692
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: rewrite memberuid after rename')
1692
			ud.debug(ud.ADMIN, ud.INFO, 'users/user: rewrite memberuid after rename')
1693
			for group in new_groups:
1693
			for group in new_groups:
1694
				self.__rewrite_member_uid( group )
1694
				self.__rewrite_member_uid( group )
1695
1695
1696
		group_mod = univention.admin.modules.get('groups/group')
1696
		group_mod = univention.admin.modules.get('groups/group')
1697
1697
1698
		univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: check groups in old_groups')
1698
		ud.debug(ud.ADMIN, ud.INFO, 'users/user: check groups in old_groups')
1699
		for group in old_groups:
1699
		for group in old_groups:
1700
			if group and not case_insensitive_in_list(group, self.info.get('groups', [])) and group.lower() != self['primaryGroup'].lower():
1700
			if group and not case_insensitive_in_list(group, self.info.get('groups', [])) and group.lower() != self['primaryGroup'].lower():
1701
				grpobj = group_mod.object(None, self.lo, self.position, group)
1701
				grpobj = group_mod.object(None, self.lo, self.position, group)
1702
				grpobj.fast_member_remove( [ self.dn ], [ old_uid ] )
1702
				grpobj.fast_member_remove( [ self.dn ], [ old_uid ] )
1703
1703
1704
		univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: check groups in info[groups]')
1704
		ud.debug(ud.ADMIN, ud.INFO, 'users/user: check groups in info[groups]')
1705
		for group in self.info.get('groups', []):
1705
		for group in self.info.get('groups', []):
1706
			if group and not case_insensitive_in_list(group, old_groups):
1706
			if group and not case_insensitive_in_list(group, old_groups):
1707
				grpobj = group_mod.object(None, self.lo, self.position, group)
1707
				grpobj = group_mod.object(None, self.lo, self.position, group)
1708
				grpobj.fast_member_add( [ self.dn ], [ new_uid ] )
1708
				grpobj.fast_member_add( [ self.dn ], [ new_uid ] )
1709
1709
1710
		if univention.admin.baseConfig.is_true("directory/manager/user/primarygroup/update", True):
1710
		if univention.admin.baseConfig.is_true("directory/manager/user/primarygroup/update", True):
1711
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: check primaryGroup')
1711
			ud.debug(ud.ADMIN, ud.INFO, 'users/user: check primaryGroup')
1712
			if not self.exists() and self.info.get('primaryGroup'):
1712
			if not self.exists() and self.info.get('primaryGroup'):
1713
				grpobj = group_mod.object(None, self.lo, self.position, self.info.get('primaryGroup'))
1713
				grpobj = group_mod.object(None, self.lo, self.position, self.info.get('primaryGroup'))
1714
				grpobj.fast_member_add( [ self.dn ], [ new_uid ] )
1714
				grpobj.fast_member_add( [ self.dn ], [ new_uid ] )
 Lines 1727-1733   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1727
				if UIDs:
1727
				if UIDs:
1728
					new_uids.append(UIDs[0])
1728
					new_uids.append(UIDs[0])
1729
					if len(UIDs) > 1:
1729
					if len(UIDs) > 1:
1730
						univention.debug.debug(univention.debug.ADMIN, univention.debug.WARN, 'users/user: A groupmember has multiple UIDs (%s %s)' % (memberDNstr, repr(uid_list)))
1730
						ud.debug(ud.ADMIN, ud.WARN, 'users/user: A groupmember has multiple UIDs (%s %s)' % (memberDNstr, repr(uid_list)))
1731
		self.lo.modify(group, [ ( 'memberUid', uids, new_uids ) ] )
1731
		self.lo.modify(group, [ ( 'memberUid', uids, new_uids ) ] )
1732
1732
1733
	def __primary_group(self):
1733
	def __primary_group(self):
 Lines 1751-1769   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1751
			searchResult=self.lo.search(base=self.oldinfo['primaryGroup'], attr=['gidNumber'])
1751
			searchResult=self.lo.search(base=self.oldinfo['primaryGroup'], attr=['gidNumber'])
1752
			for tmp,number in searchResult:
1752
			for tmp,number in searchResult:
1753
				oldPrimaryGroup = number['gidNumber']
1753
				oldPrimaryGroup = number['gidNumber']
1754
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: set gidNumber by oldinfo')
1754
			ud.debug(ud.ADMIN, ud.INFO, 'users/user: set gidNumber by oldinfo')
1755
			self.lo.modify(self.dn, [('gidNumber',oldPrimaryGroup[0], primaryGroupNumber[0])])
1755
			self.lo.modify(self.dn, [('gidNumber',oldPrimaryGroup[0], primaryGroupNumber[0])])
1756
			if 'samba' in self.options:
1756
			if 'samba' in self.options:
1757
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: set sambaPrimaryGroupSID by oldinfo')
1757
				ud.debug(ud.ADMIN, ud.INFO, 'users/user: set sambaPrimaryGroupSID by oldinfo')
1758
				self.lo.modify(self.dn, [('sambaPrimaryGroupSID',oldPrimaryGroup[0], primaryGroupSambaNumber[0])])
1758
				self.lo.modify(self.dn, [('sambaPrimaryGroupSID',oldPrimaryGroup[0], primaryGroupSambaNumber[0])])
1759
		else:
1759
		else:
1760
			searchResult=self.lo.search(base=self.dn, scope='base', attr=['gidNumber'])
1760
			searchResult=self.lo.search(base=self.dn, scope='base', attr=['gidNumber'])
1761
			for tmp,number in searchResult:
1761
			for tmp,number in searchResult:
1762
				oldNumber = number['gidNumber']
1762
				oldNumber = number['gidNumber']
1763
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: set gidNumber')
1763
			ud.debug(ud.ADMIN, ud.INFO, 'users/user: set gidNumber')
1764
			self.lo.modify(self.dn, [('gidNumber',oldNumber, primaryGroupNumber[0])])
1764
			self.lo.modify(self.dn, [('gidNumber',oldNumber, primaryGroupNumber[0])])
1765
			if 'samba' in self.options:
1765
			if 'samba' in self.options:
1766
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: set sambaPrimaryGroupSID')
1766
				ud.debug(ud.ADMIN, ud.INFO, 'users/user: set sambaPrimaryGroupSID')
1767
				self.lo.modify(self.dn, [('sambaPrimaryGroupSID',oldNumber, primaryGroupSambaNumber[0])])
1767
				self.lo.modify(self.dn, [('sambaPrimaryGroupSID',oldNumber, primaryGroupSambaNumber[0])])
1768
1768
1769
1769
 Lines 1772-1778   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1772
			group_mod = univention.admin.modules.get('groups/group')
1772
			group_mod = univention.admin.modules.get('groups/group')
1773
			grpobj = group_mod.object(None, self.lo, self.position, self.newPrimaryGroupDn)
1773
			grpobj = group_mod.object(None, self.lo, self.position, self.newPrimaryGroupDn)
1774
			grpobj.fast_member_add( [ self.dn ], [ new_uid ] )
1774
			grpobj.fast_member_add( [ self.dn ], [ new_uid ] )
1775
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: adding to new primaryGroup %s (uid=%s)' % (self.newPrimaryGroupDn, new_uid))
1775
			ud.debug(ud.ADMIN, ud.INFO, 'users/user: adding to new primaryGroup %s (uid=%s)' % (self.newPrimaryGroupDn, new_uid))
1776
1776
1777
		self.save()
1777
		self.save()
1778
1778
 Lines 1782-1791   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1782
		return self['username']+'@'+realm
1782
		return self['username']+'@'+realm
1783
1783
1784
	def _ldap_pre_create(self):
1784
	def _ldap_pre_create(self):
1785
		_d=univention.debug.function('admin.handlers.users.user.object._ldap_pre_create')
1785
		_d=ud.function('admin.handlers.users.user.object._ldap_pre_create')
1786
1786
1787
		self.dn='uid=%s,%s' % ( self['username'], self.position.getDn())
1787
		self.dn='uid=%s,%s' % ( self['username'], self.position.getDn())
1788
		univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'users/user: dn was set to %s'%self.dn)
1788
		ud.debug(ud.ADMIN, ud.INFO, 'users/user: dn was set to %s'%self.dn)
1789
		if not self['password']:
1789
		if not self['password']:
1790
			self['password']=self.oldattr.get('password',[''])[0]
1790
			self['password']=self.oldattr.get('password',[''])[0]
1791
			self.modifypassword=0
1791
			self.modifypassword=0
 Lines 1990-2005   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1990
		sambaPwdLastSetValue = ''	# if is filled, it will be added to ml in the end
1990
		sambaPwdLastSetValue = ''	# if is filled, it will be added to ml in the end
1991
1991
1992
		if self.options != self.old_options:
1992
		if self.options != self.old_options:
1993
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'options: %s' % self.options)
1993
			ud.debug(ud.ADMIN, ud.INFO, 'options: %s' % self.options)
1994
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'old_options: %s' % self.old_options)
1994
			ud.debug(ud.ADMIN, ud.INFO, 'old_options: %s' % self.old_options)
1995
			# pki option add / remove
1995
			# pki option add / remove
1996
			if 'pki' in self.options and not 'pki' in self.old_options:
1996
			if 'pki' in self.options and not 'pki' in self.old_options:
1997
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'added pki option')
1997
				ud.debug(ud.ADMIN, ud.INFO, 'added pki option')
1998
				ocs=self.oldattr.get('objectClass', [])
1998
				ocs=self.oldattr.get('objectClass', [])
1999
				if not 'pkiUser' in ocs:
1999
				if not 'pkiUser' in ocs:
2000
					ml.insert(0, ('objectClass', '', 'pkiUser'))
2000
					ml.insert(0, ('objectClass', '', 'pkiUser'))
2001
			if not 'pki' in self.options and 'pki' in self.old_options:
2001
			if not 'pki' in self.options and 'pki' in self.old_options:
2002
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'remove pki option')
2002
				ud.debug(ud.ADMIN, ud.INFO, 'remove pki option')
2003
				ocs=self.oldattr.get('objectClass', [])
2003
				ocs=self.oldattr.get('objectClass', [])
2004
				if 'pkiUser' in ocs:
2004
				if 'pkiUser' in ocs:
2005
					ml.insert(0, ('objectClass', 'pkiUser', ''))
2005
					ml.insert(0, ('objectClass', 'pkiUser', ''))
 Lines 2007-2019   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2007
						ml=self._remove_attr(ml,attr)
2007
						ml=self._remove_attr(ml,attr)
2008
			# ldap_pwd option add / remove
2008
			# ldap_pwd option add / remove
2009
			if 'ldap_pwd' in self.options and not 'ldap_pwd' in self.old_options:
2009
			if 'ldap_pwd' in self.options and not 'ldap_pwd' in self.old_options:
2010
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'added ldap_pwd option')
2010
				ud.debug(ud.ADMIN, ud.INFO, 'added ldap_pwd option')
2011
				ocs=self.oldattr.get('objectClass', [])
2011
				ocs=self.oldattr.get('objectClass', [])
2012
				if not 'simpleSecurityObject' in ocs:
2012
				if not 'simpleSecurityObject' in ocs:
2013
					ml.insert(0, ('objectClass', '', 'simpleSecurityObject'))
2013
					ml.insert(0, ('objectClass', '', 'simpleSecurityObject'))
2014
					ml.insert(0, ('objectClass', '', 'uidObject'))
2014
					ml.insert(0, ('objectClass', '', 'uidObject'))
2015
			if not 'ldap_pwd' in self.options and 'ldap_pwd' in self.old_options:
2015
			if not 'ldap_pwd' in self.options and 'ldap_pwd' in self.old_options:
2016
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'remove ldap_pwd option')
2016
				ud.debug(ud.ADMIN, ud.INFO, 'remove ldap_pwd option')
2017
				ocs=self.oldattr.get('objectClass', [])
2017
				ocs=self.oldattr.get('objectClass', [])
2018
				if 'simpleSecurityObject' in ocs:
2018
				if 'simpleSecurityObject' in ocs:
2019
					ml.insert(0, ('objectClass', 'simpleSecurityObject', ''))
2019
					ml.insert(0, ('objectClass', 'simpleSecurityObject', ''))
 Lines 2114-2120   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2114
2114
2115
						shadowLastChangeValue = str(int(now))
2115
						shadowLastChangeValue = str(int(now))
2116
2116
2117
					univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'shadowMax: %s' % shadowMax)
2117
					ud.debug(ud.ADMIN, ud.INFO, 'shadowMax: %s' % shadowMax)
2118
					old_shadowMax=self.oldattr.get('shadowMax', '')
2118
					old_shadowMax=self.oldattr.get('shadowMax', '')
2119
					if old_shadowMax != shadowMax:
2119
					if old_shadowMax != shadowMax:
2120
						ml.append(('shadowMax',self.oldattr.get('shadowMax', [''])[0], shadowMax))
2120
						ml.append(('shadowMax',self.oldattr.get('shadowMax', [''])[0], shadowMax))
 Lines 2130-2136   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2130
						krb5PasswordEnd=''
2130
						krb5PasswordEnd=''
2131
					else:
2131
					else:
2132
						krb5PasswordEnd="%s" % "20"+expiry[6:8]+expiry[3:5]+expiry[0:2]+"000000Z"
2132
						krb5PasswordEnd="%s" % "20"+expiry[6:8]+expiry[3:5]+expiry[0:2]+"000000Z"
2133
					univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'krb5PasswordEnd: %s' % krb5PasswordEnd)
2133
					ud.debug(ud.ADMIN, ud.INFO, 'krb5PasswordEnd: %s' % krb5PasswordEnd)
2134
					old_krb5PasswordEnd=self.oldattr.get('krb5PasswordEnd', '')
2134
					old_krb5PasswordEnd=self.oldattr.get('krb5PasswordEnd', '')
2135
					if old_krb5PasswordEnd != krb5PasswordEnd:
2135
					if old_krb5PasswordEnd != krb5PasswordEnd:
2136
						ml.append(('krb5PasswordEnd',self.oldattr.get('krb5PasswordEnd', [''])[0], krb5PasswordEnd))
2136
						ml.append(('krb5PasswordEnd',self.oldattr.get('krb5PasswordEnd', [''])[0], krb5PasswordEnd))
 Lines 2271-2277   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2271
				shadowExpire=''
2271
				shadowExpire=''
2272
				if self['userexpiry']:
2272
				if self['userexpiry']:
2273
					shadowExpire="%d" % long(time.mktime(time.strptime(self['userexpiry'],"%d.%m.%y"))/3600/24+1)
2273
					shadowExpire="%d" % long(time.mktime(time.strptime(self['userexpiry'],"%d.%m.%y"))/3600/24+1)
2274
					univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'shadowExpire: %s' % shadowExpire)
2274
					ud.debug(ud.ADMIN, ud.INFO, 'shadowExpire: %s' % shadowExpire)
2275
				old_shadowExpire=self.oldattr.get('shadowExpire', '')
2275
				old_shadowExpire=self.oldattr.get('shadowExpire', '')
2276
				if old_shadowExpire != shadowExpire:
2276
				if old_shadowExpire != shadowExpire:
2277
					ml.append(('shadowExpire',self.oldattr.get('shadowExpire', [''])[0], shadowExpire))
2277
					ml.append(('shadowExpire',self.oldattr.get('shadowExpire', [''])[0], shadowExpire))
 Lines 2279-2285   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2279
				sambaKickoffTime=''
2279
				sambaKickoffTime=''
2280
				if self['userexpiry']:
2280
				if self['userexpiry']:
2281
					sambaKickoffTime="%d" % long(time.mktime(time.strptime(self['userexpiry'],"%d.%m.%y")))
2281
					sambaKickoffTime="%d" % long(time.mktime(time.strptime(self['userexpiry'],"%d.%m.%y")))
2282
					univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'sambaKickoffTime: %s' % sambaKickoffTime)
2282
					ud.debug(ud.ADMIN, ud.INFO, 'sambaKickoffTime: %s' % sambaKickoffTime)
2283
				old_sambaKickoffTime=self.oldattr.get('sambaKickoffTime', '')
2283
				old_sambaKickoffTime=self.oldattr.get('sambaKickoffTime', '')
2284
				if old_sambaKickoffTime != sambaKickoffTime:
2284
				if old_sambaKickoffTime != sambaKickoffTime:
2285
					ml.append(('sambaKickoffTime',self.oldattr.get('sambaKickoffTime', [''])[0], sambaKickoffTime))
2285
					ml.append(('sambaKickoffTime',self.oldattr.get('sambaKickoffTime', [''])[0], sambaKickoffTime))
 Lines 2287-2293   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2287
				krb5ValidEnd=''
2287
				krb5ValidEnd=''
2288
				if self['userexpiry']:
2288
				if self['userexpiry']:
2289
					krb5ValidEnd="%s" % "20"+self['userexpiry'][6:8]+self['userexpiry'][3:5]+self['userexpiry'][0:2]+"000000Z"
2289
					krb5ValidEnd="%s" % "20"+self['userexpiry'][6:8]+self['userexpiry'][3:5]+self['userexpiry'][0:2]+"000000Z"
2290
					univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'krb5ValidEnd: %s' % krb5ValidEnd)
2290
					ud.debug(ud.ADMIN, ud.INFO, 'krb5ValidEnd: %s' % krb5ValidEnd)
2291
				old_krb5ValidEnd=self.oldattr.get('krb5ValidEnd', '')
2291
				old_krb5ValidEnd=self.oldattr.get('krb5ValidEnd', '')
2292
				if old_krb5ValidEnd != krb5ValidEnd:
2292
				if old_krb5ValidEnd != krb5ValidEnd:
2293
					if not self['userexpiry']:
2293
					if not self['userexpiry']:
 Lines 2331-2337   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2331
			if 'kerberos' in self.options:
2331
			if 'kerberos' in self.options:
2332
				expiry=time.strftime("%d.%m.%y",time.gmtime((long(time.time()))))
2332
				expiry=time.strftime("%d.%m.%y",time.gmtime((long(time.time()))))
2333
				krb5PasswordEnd="%s" % "20"+expiry[6:8]+expiry[3:5]+expiry[0:2]+"000000Z"
2333
				krb5PasswordEnd="%s" % "20"+expiry[6:8]+expiry[3:5]+expiry[0:2]+"000000Z"
2334
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'krb5PasswordEnd: %s' % krb5PasswordEnd)
2334
				ud.debug(ud.ADMIN, ud.INFO, 'krb5PasswordEnd: %s' % krb5PasswordEnd)
2335
				old_krb5PasswordEnd=self.oldattr.get('krb5PasswordEnd', '')
2335
				old_krb5PasswordEnd=self.oldattr.get('krb5PasswordEnd', '')
2336
				if old_krb5PasswordEnd != krb5PasswordEnd:
2336
				if old_krb5PasswordEnd != krb5PasswordEnd:
2337
					ml.append(('krb5PasswordEnd',self.oldattr.get('krb5PasswordEnd', [''])[0], krb5PasswordEnd))
2337
					ml.append(('krb5PasswordEnd',self.oldattr.get('krb5PasswordEnd', [''])[0], krb5PasswordEnd))
 Lines 2358-2364   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2358
				now=(long(time.time())/3600/24)
2358
				now=(long(time.time())/3600/24)
2359
				shadowLastChangeValue = str(int(now))
2359
				shadowLastChangeValue = str(int(now))
2360
2360
2361
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'shadowMax: %s' % shadowMax)
2361
				ud.debug(ud.ADMIN, ud.INFO, 'shadowMax: %s' % shadowMax)
2362
				old_shadowMax=self.oldattr.get('shadowMax', [''])[0]
2362
				old_shadowMax=self.oldattr.get('shadowMax', [''])[0]
2363
				if old_shadowMax != shadowMax:
2363
				if old_shadowMax != shadowMax:
2364
					ml.append(('shadowMax', old_shadowMax, shadowMax))
2364
					ml.append(('shadowMax', old_shadowMax, shadowMax))
 Lines 2367-2373   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2367
			if 'samba' in self.options:
2367
			if 'samba' in self.options:
2368
				sambaPwdLastSetValue = str(long(time.time()))
2368
				sambaPwdLastSetValue = str(long(time.time()))
2369
				# transfered into ml below
2369
				# transfered into ml below
2370
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'sambaPwdLastSetValue: %s' % sambaPwdLastSetValue)
2370
				ud.debug(ud.ADMIN, ud.INFO, 'sambaPwdLastSetValue: %s' % sambaPwdLastSetValue)
2371
2371
2372
			# 4. set kerberos attribute
2372
			# 4. set kerberos attribute
2373
			if 'kerberos' in self.options:
2373
			if 'kerberos' in self.options:
 Lines 2376-2382   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2376
				else:
2376
				else:
2377
					expiry=time.strftime("%d.%m.%y",time.gmtime((long(time.time()) + (expiryInterval*3600*24))))
2377
					expiry=time.strftime("%d.%m.%y",time.gmtime((long(time.time()) + (expiryInterval*3600*24))))
2378
					krb5PasswordEnd="%s" % "20"+expiry[6:8]+expiry[3:5]+expiry[0:2]+"000000Z"
2378
					krb5PasswordEnd="%s" % "20"+expiry[6:8]+expiry[3:5]+expiry[0:2]+"000000Z"
2379
				univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'krb5PasswordEnd: %s' % krb5PasswordEnd)
2379
				ud.debug(ud.ADMIN, ud.INFO, 'krb5PasswordEnd: %s' % krb5PasswordEnd)
2380
				old_krb5PasswordEnd=self.oldattr.get('krb5PasswordEnd', [''])[0]
2380
				old_krb5PasswordEnd=self.oldattr.get('krb5PasswordEnd', [''])[0]
2381
				if old_krb5PasswordEnd != krb5PasswordEnd:
2381
				if old_krb5PasswordEnd != krb5PasswordEnd:
2382
					ml.append(('krb5PasswordEnd',old_krb5PasswordEnd, krb5PasswordEnd))
2382
					ml.append(('krb5PasswordEnd',old_krb5PasswordEnd, krb5PasswordEnd))
 Lines 2393-2401   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2393
			else:
2393
			else:
2394
				try:
2394
				try:
2395
					self.alloc.append( ( 'mailPrimaryAddress', self[ 'mailPrimaryAddress' ] ) )
2395
					self.alloc.append( ( 'mailPrimaryAddress', self[ 'mailPrimaryAddress' ] ) )
2396
					univention.debug.debug( univention.debug.ADMIN, univention.debug.INFO, "LOCKING: %s" % self[ 'mailPrimaryAddress' ] )
2396
					ud.debug( ud.ADMIN, ud.INFO, "LOCKING: %s" % self[ 'mailPrimaryAddress' ] )
2397
					univention.admin.allocators.request( self.lo, self.position, 'mailPrimaryAddress', value = self[ 'mailPrimaryAddress' ] )
2397
					univention.admin.allocators.request( self.lo, self.position, 'mailPrimaryAddress', value = self[ 'mailPrimaryAddress' ] )
2398
					univention.debug.debug( univention.debug.ADMIN, univention.debug.INFO, "LOCKING DONE: %s" % self[ 'mailPrimaryAddress' ] )
2398
					ud.debug( ud.ADMIN, ud.INFO, "LOCKING DONE: %s" % self[ 'mailPrimaryAddress' ] )
2399
				except univention.admin.uexceptions.noLock:
2399
				except univention.admin.uexceptions.noLock:
2400
					self.cancel()
2400
					self.cancel()
2401
					raise univention.admin.uexceptions.mailAddressUsed
2401
					raise univention.admin.uexceptions.mailAddressUsed
2402
- 
2403
--
2404
.../univention/admin/handlers/users/user.py        |  120 +++++++++-----------
2402
.../univention/admin/handlers/users/user.py        |  120 +++++++++-----------
2405
1 file changed, 55 insertions(+), 65 deletions(-)
2403
1 file changed, 55 insertions(+), 65 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-67 / +55 lines)
 Lines 1003-1014   def posixDaysToDate(days): Link Here 
1003
	return time.strftime("%Y-%m-%d",time.gmtime(long(days)*3600*24))
1003
	return time.strftime("%Y-%m-%d",time.gmtime(long(days)*3600*24))
1004
1004
1005
def sambaWorkstationsMap(workstations):
1005
def sambaWorkstationsMap(workstations):
1006
	ud.debug(ud.ADMIN, ud.ALL, 'samba: sambaWorkstationMap: in=%s; out=%s' % (workstations,string.join(workstations, ',')))
1006
	tmp = ','.join(workstations)
1007
	return string.join(workstations, ',')
1007
	ud.debug(ud.ADMIN, ud.ALL, 'samba: sambaWorkstationMap: in=%s; out=%s' % (workstations, tmp))
1008
	return tmp
1008
1009
1009
def sambaWorkstationsUnmap(workstations):
1010
def sambaWorkstationsUnmap(workstations):
1010
	ud.debug(ud.ADMIN, ud.ALL, 'samba: sambaWorkstationUnmap: in=%s; out=%s' % (workstations[0],string.split(workstations[0],',')))
1011
	tmp = workstations[0].split(',')
1011
	return string.split(workstations[0],',')
1012
	ud.debug(ud.ADMIN, ud.ALL, 'samba: sambaWorkstationUnmap: in=%s; out=%s' % (workstations[0], tmp))
1013
	return tmp
1012
1014
1013
def logonHoursMap(logontimes):
1015
def logonHoursMap(logontimes):
1014
	"converts the bitfield 001110010110...100 to the respective string"
1016
	"converts the bitfield 001110010110...100 to the respective string"
 Lines 1110-1116   def load_certificate(user_certificate): Link Here 
1110
1112
1111
	def convert_certdate (certdate):
1113
	def convert_certdate (certdate):
1112
		datestring=str(certdate)
1114
		datestring=str(certdate)
1113
		dl=string.split(datestring)
1115
		dl = datestring.split()
1114
		month=[None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1116
		month=[None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1115
		try:
1117
		try:
1116
			dl[0]=month.index(dl[0])
1118
			dl[0]=month.index(dl[0])
 Lines 1134-1177   def load_certificate(user_certificate): Link Here 
1134
	if not serial:
1136
	if not serial:
1135
		return {}
1137
		return {}
1136
1138
1137
1139
	ATTR = {
1138
	value={}
1140
			"C": "Country",
1139
1141
			"ST": "State",
1140
	value['certificateDateNotBefore']=convert_certdate(not_before)
1142
			"L": "Location",
1141
	value['certificateDateNotAfter']=convert_certdate(not_after)
1143
			"O": "Organisation",
1142
	value['certificateVersion']=str(version)
1144
			"OU": "OrganisationalUnit",
1143
	value['certificateSerial']=str(serial)
1145
			"CN": "CommonName",
1144
1146
			"emailAddress": "Mail",
1147
			}[key]
1148
	value = {
1149
			'certificateDateNotBefore': convert_certdate(not_before),
1150
			'certificateDateNotAfter': convert_certdate(not_after),
1151
			'certificateVersion': str(version),
1152
			'certificateSerial': str(serial),
1153
			}
1145
	for i in issuer.split('/'):
1154
	for i in issuer.split('/'):
1146
		if re.match('^C=', i):
1155
		try:
1147
			value['certificateIssuerCountry']=string.split(i, '=')[1]
1156
			key, val = i.split('=', 1)
1148
		elif re.match('^ST=', i):
1157
		except ValueError:
1149
			value['certificateIssuerState']=string.split(i, '=')[1]
1158
			continue
1150
		elif re.match('^L=', i):
1159
		try:
1151
			value['certificateIssuerLocation']=string.split(i, '=')[1]
1160
			attr = "certificateIssuer%s" % ATTR[key]
1152
		elif re.match('^O=', i):
1161
		except KeyError:
1153
			value['certificateIssuerOrganisation']=string.split(i, '=')[1]
1162
			continue
1154
		elif re.match('^OU=', i):
1163
		value[attr] = val
1155
			value['certificateIssuerOrganisationalUnit']=string.split(i, '=')[1]
1156
		elif re.match('^CN=', i):
1157
			value['certificateIssuerCommonName']=string.split(i, '=')[1]
1158
		elif re.match('^emailAddress=', i):
1159
			value['certificateIssuerMail']=string.split(i, '=')[1]
1160
	for i in subject.split('/'):
1164
	for i in subject.split('/'):
1161
		if re.match('^C=', i):
1165
		try:
1162
			value['certificateSubjectCountry']=string.split(i, '=')[1]
1166
			key, val = i.split('=', 1)
1163
		elif re.match('^ST=', i):
1167
		except ValueError:
1164
			value['certificateSubjectState']=string.split(i, '=')[1]
1168
			continue
1165
		elif re.match('^L=', i):
1169
		try:
1166
			value['certificateSubjectLocation']=string.split(i, '=')[1]
1170
			attr = "certificateSubject%s" % ATTR[key]
1167
		elif re.match('^O=', i):
1171
		except KeyError:
1168
			value['certificateSubjectOrganisation']=string.split(i, '=')[1]
1172
			continue
1169
		elif re.match('^OU=', i):
1173
		value[attr] = val
1170
			value['certificateSubjectOrganisationalUnit']=string.split(i, '=')[1]
1171
		elif re.match('^CN=', i):
1172
			value['certificateSubjectCommonName']=string.split(i, '=')[1]
1173
		elif re.match('^emailAddress=', i):
1174
			value['certificateSubjectMail']=string.split(i, '=')[1]
1175
1174
1176
	ud.debug(ud.ADMIN, ud.ERROR, 'value=%s' % value)
1175
	ud.debug(ud.ADMIN, ud.ERROR, 'value=%s' % value)
1177
	return value
1176
	return value
 Lines 1306-1322   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1306
			self['disabled']='all'
1305
			self['disabled']='all'
1307
1306
1308
	def __is_kerberos_disabled(self):
1307
	def __is_kerberos_disabled(self):
1309
		if self['disabled'] in ['all', 'kerberos', 'posix_kerberos', 'windows_kerberos']:
1308
		return self['disabled'] in ('all', 'kerberos', 'posix_kerberos', 'windows_kerberos')
1310
			return True
1309
1311
		return False
1312
	def __is_windows_disabled(self):
1310
	def __is_windows_disabled(self):
1313
		if self['disabled'] in ['all', 'windows', 'windows_posix', 'windows_kerberos']:
1311
		return self['disabled'] in ('all', 'windows', 'windows_posix', 'windows_kerberos')
1314
			return True
1312
1315
		return False
1316
	def __is_posix_disabled(self):
1313
	def __is_posix_disabled(self):
1317
		if self['disabled'] in ( 'all', 'posix', 'posix_kerberos', 'windows_posix' ):
1314
		return self['disabled'] in ('all', 'posix', 'posix_kerberos', 'windows_posix')
1318
			return True
1319
		return False
1320
1315
1321
	def __pwd_is_auth_saslpassthrough(self, password):
1316
	def __pwd_is_auth_saslpassthrough(self, password):
1322
		if password.startswith('{SASL}') and univention.admin.baseConfig.get('directory/manager/web/modules/users/user/auth/saslpassthrough','no').lower() == 'keep':
1317
		if password.startswith('{SASL}') and univention.admin.baseConfig.get('directory/manager/web/modules/users/user/auth/saslpassthrough','no').lower() == 'keep':
 Lines 1494-1502   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1494
			if self['passwordexpiry']:
1489
			if self['passwordexpiry']:
1495
				today=time.strftime('%Y-%m-%d').split('-')
1490
				today=time.strftime('%Y-%m-%d').split('-')
1496
				expiry=self['passwordexpiry'].split('-')
1491
				expiry=self['passwordexpiry'].split('-')
1497
				# expiry.reverse()
1492
				if int(''.join(today)) >= int(''.join(expiry)):
1498
				# today.reverse()
1499
				if int(string.join(today,''))>=int(string.join(expiry,'')):
1500
					self['pwdChangeNextLogin']='1'
1493
					self['pwdChangeNextLogin']='1'
1501
1494
1502
			if 'samba' in self.options:
1495
			if 'samba' in self.options:
 Lines 2546-2565   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2546
	def __passwordInHistory(self, newpassword, pwhistory):
2539
	def __passwordInHistory(self, newpassword, pwhistory):
2547
		# first calc hash for the new pw
2540
		# first calc hash for the new pw
2548
		s = hashlib.sha1( newpassword.encode( 'utf-8' ) )
2541
		s = hashlib.sha1( newpassword.encode( 'utf-8' ) )
2549
		newpwhash = string.upper(s.hexdigest())
2542
		newpwhash = s.hexdigest().upper()
2550
		if not string.find(pwhistory, newpwhash) < 0:
2543
		return pwhistory.find(newpwhash) >= 0
2551
			# password has already been used.
2552
			return 1
2553
		return 0
2554
2544
2555
	def __getPWHistory(self, newpassword, pwhistory, pwhlen):
2545
	def __getPWHistory(self, newpassword, pwhistory, pwhlen):
2556
		# first calc hash for the new pw
2546
		# first calc hash for the new pw
2557
		s = hashlib.sha1( newpassword.encode( 'utf-8' ) )
2547
		s = hashlib.sha1( newpassword.encode( 'utf-8' ) )
2558
		newpwhash = string.upper(s.hexdigest())
2548
		newpwhash = s.hexdigest().upper()
2559
2549
2560
		# split the history
2550
		# split the history
2561
		if len(string.strip(pwhistory)):
2551
		if len(pwhistory.strip()):
2562
			pwlist = string.split(pwhistory, ' ')
2552
			pwlist = pwhistory.split(' ')
2563
		else:
2553
		else:
2564
			pwlist = []
2554
			pwlist = []
2565
2555
 Lines 2583-2595   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2583
					else:
2573
					else:
2584
						pwlist.append(newpwhash)
2574
						pwlist.append(newpwhash)
2585
		# and build the new history
2575
		# and build the new history
2586
		res = string.join(pwlist)
2576
		res = ' '.join(pwlist)
2587
		return res
2577
		return res
2588
2578
2589
	def __getsmbPWHistory(self, newpassword, smbpwhistory, smbpwhlen):
2579
	def __getsmbPWHistory(self, newpassword, smbpwhistory, smbpwhlen):
2590
		# split the history
2580
		# split the history
2591
		if len(string.strip(smbpwhistory)):
2581
		if len(smbpwhistory.strip()):
2592
			pwlist = string.split(smbpwhistory, ' ')
2582
			pwlist = smbpwhistory.split(' ')
2593
		else:
2583
		else:
2594
			pwlist = []
2584
			pwlist = []
2595
2585
 Lines 2632-2638   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2632
					pwlist.append(smbpwhash)
2622
					pwlist.append(smbpwhash)
2633
2623
2634
		# and build the new history
2624
		# and build the new history
2635
		res = string.join(pwlist, '')
2625
		res = ''.join(pwlist)
2636
		return res
2626
		return res
2637
2627
2638
	def __generate_user_sid(self, uidNum):
2628
	def __generate_user_sid(self, uidNum):
2639
- 
2640
--
2641
.../univention/admin/handlers/users/user.py        |   37 +++++++++++++-------
2629
.../univention/admin/handlers/users/user.py        |   37 +++++++++++++-------
2642
1 file changed, 25 insertions(+), 12 deletions(-)
2630
1 file changed, 25 insertions(+), 12 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-14 / +25 lines)
 Lines 1176-1187   def load_certificate(user_certificate): Link Here 
1176
	return value
1176
	return value
1177
1177
1178
def mapHomePostalAddress(old):
1178
def mapHomePostalAddress(old):
1179
	new=[]
1179
	"""Map address to LDAP encoding.
1180
	for i in old:
1180
	>>> mapHomePostalAddress(["a", "b", "c"])
1181
		new.append(string.join(i, '$' ))
1181
	'a$b$c'
1182
	return new
1182
	"""
1183
	return '$'.join(old)
1183
1184
1184
def unmapHomePostalAddress(old):
1185
def unmapHomePostalAddress(old):
1186
	"""Expand LDAP encoded address.
1187
	>>> unmapHomePostalAddress(['foo'])
1188
	[['foo', ' ', ' ']]
1189
	>>> unmapHomePostalAddress(['foo$bar$baz'])
1190
	[['foo', 'bar', 'baz']]
1191
	"""
1185
	new=[]
1192
	new=[]
1186
	for i in old:
1193
	for i in old:
1187
		if '$' in i:
1194
		if '$' in i:
 Lines 1228-1243   mapping.register('displayName', 'displayName', None, univention.admin.mapping.Li Link Here 
1228
mapping.register('birthday', 'univentionBirthday', None, univention.admin.mapping.ListToString)
1235
mapping.register('birthday', 'univentionBirthday', None, univention.admin.mapping.ListToString)
1229
1236
1230
def mapKeyAndValue(old):
1237
def mapKeyAndValue(old):
1231
	lst = []
1238
	"""Map (key, value) list to key=value list.
1232
	for entry in old:
1239
	>>> mapKeyAndValue([("a", "b")])
1233
		lst.append( '%s=%s' % (entry[0], entry[1]) )
1240
	['a=b']
1234
	return lst
1241
	"""
1242
	return ["%s=%s" % tuple(entry) for entry in old]
1235
1243
1236
def unmapKeyAndValue(old):
1244
def unmapKeyAndValue(old):
1237
	lst = []
1245
	"""Map (key=value) list to (key, value) list.
1238
	for entry in old:
1246
	>>> unmapKeyAndValue(["a=b"])
1239
		lst.append( entry.split('=', 1) )
1247
	[('a', 'b')]
1240
	return lst
1248
	"""
1249
	return [tuple(entry.split('=', 1)) for entry in old]
1241
1250
1242
def unmapBase64( value ):
1251
def unmapBase64( value ):
1243
	try:
1252
	try:
 Lines 2786-2788   def identify(dn, attr, canonical=0): Link Here 
2786
			and not '$' in attr.get('uid',[])
2795
			and not '$' in attr.get('uid',[])
2787
		        and not 'univentionHost' in attr.get('objectClass', [])
2796
		        and not 'univentionHost' in attr.get('objectClass', [])
2788
			)
2797
			)
2789
- 
2798
2790
--
2799
if __name__ == '__main__':
2800
	import doctest
2801
	doctest.testmod()
2791
.../univention/admin/handlers/users/user.py        |   85 +++++---------------
2802
.../univention/admin/handlers/users/user.py        |   85 +++++---------------
2792
1 file changed, 18 insertions(+), 67 deletions(-)
2803
1 file changed, 18 insertions(+), 67 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-69 / +18 lines)
 Lines 1013-1089   def sambaWorkstationsUnmap(workstations): Link Here 
1013
	return tmp
1013
	return tmp
1014
1014
1015
def logonHoursMap(logontimes):
1015
def logonHoursMap(logontimes):
1016
	"converts the bitfield 001110010110...100 to the respective string"
1016
	"""Converts array of bits set to an hex-string."""
1017
1017
	octets = [0] * (24 * 7 / 8)
1018
	# convert list of bit numbers to bit-string
1019
	# bitstring = '0' * 168
1020
	bitstring = ''.join( map( lambda x: x in logontimes and '1' or '0', range( 168 ) ) )
1021
1022
	# for idx in logontimes:
1023
	# 	bitstring[ idx ] = '1'
1024
1025
	logontimes = bitstring
1026
1027
	# the order of the bits of each byte has to be reversed. The reason for this is that
1018
	# the order of the bits of each byte has to be reversed. The reason for this is that
1028
	# consecutive bytes mean consecutive 8-hrs-intervals, but the leftmost bit stands for
1019
	# consecutive bytes mean consecutive 8-hrs-intervals, but the MSB stands for
1029
	# the last hour in that interval, the 2nd but leftmost bit for the second-but-last
1020
	# the last hour in that interval, the 2nd leftmost bit for the second-to-last
1030
	# hour and so on. We want to hide this from anybody using this feature.
1021
	# hour and so on. We want to hide this from anybody using this feature.
1031
	# See http://ma.ph-freiburg.de/tng/tng-technical/2003-04/msg00015.html for details.
1022
	# See <http://ma.ph-freiburg.de/tng/tng-technical/2003-04/msg00015.html> for details.
1032
1023
	for hour in logontimes:
1033
	newtimes = ""
1024
		idx, bit = divmod(hour, 8)
1034
	for i in range(0,21):
1025
		octets[idx] |= 1 << bit
1035
		bitlist=list(logontimes[(i*8):(i*8)+8])
1026
	return ''.join(['%02x' % _ for _ in octets])
1036
		bitlist.reverse()
1037
		newtimes+="".join(bitlist)
1038
	logontimes = newtimes
1039
1040
	# create a hexnumber from each 8-bit-segment
1041
	ret=""
1042
	for i in range(0,21):
1043
	        val=0
1044
	        exp=7
1045
	        for j in range((i*8), (i*8)+8):
1046
	                if not (logontimes[j]=="0"):
1047
	                        val+=2**exp
1048
	                exp-=1
1049
		# we now have: 0<=val<=255
1050
	        hx=hex(val)[2:4]
1051
	        if len(hx)==1: hx="0"+hx
1052
	        ret+=hx
1053
1054
	return ret
1055
1027
1056
def logonHoursUnmap(logontimes):
1028
def logonHoursUnmap(logontimes):
1057
	"converts the string to a bit array"
1029
	"""Converts hex-string to an array of bits set."""
1058
1030
	times = logontimes[0].ljust(42, '0')[:42]
1059
	times=logontimes[0][:42]
1031
	assert len(times) == 24 * 7 / 4
1060
	while len(times)<42:
1032
	octets = [int(times[i : i + 2], 16) for i in range(0, len(times), 2)]
1061
		times=times
1033
	assert len(octets) == 24 * 7 / 8
1062
        ret=""
1034
	return [idx * 8 + bit
1063
        for i in range(0,42,2):
1035
			for (idx, value) in enumerate(octets)
1064
                val=int(times[i:i+2],16)
1036
			for bit in range(8)
1065
                ret+=intToBinary(val)
1037
			if value & (1 << bit)]
1066
1067
	# reverse order of the bits in each byte. See above for details
1068
	newtime = ""
1069
	for i in range(0, 21):
1070
		bitlist=list(ret[(i*8):(i*8)+8])
1071
		bitlist.reverse()
1072
		newtime+="".join(bitlist)
1073
1074
	# convert bit-string to list
1075
	return filter( lambda i: newtime[ i ] == '1', range( 168 ) )
1076
1077
def intToBinary(val):
1078
        ret=""
1079
        while val>0:
1080
                ret=str(val&1)+ret
1081
                val=val>>1
1082
        # pad with leading 0s until length is n*8
1083
        if ret=="": ret="0"
1084
        while not (len(ret)%8==0):
1085
                ret="0"+ret
1086
        return ret
1087
1038
1088
def GMTOffset():
1039
def GMTOffset():
1089
	# returns the difference in hours between local time and GMT (is -1 for CET and CEST)
1040
	# returns the difference in hours between local time and GMT (is -1 for CET and CEST)
1090
- 
1091
--
1092
.../univention/admin/handlers/users/user.py        |   89 ++++++++------------
1041
.../univention/admin/handlers/users/user.py        |   89 ++++++++------------
1093
1 file changed, 35 insertions(+), 54 deletions(-)
1042
1 file changed, 35 insertions(+), 54 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-56 / +35 lines)
 Lines 2020-2026   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2020
					return []
2020
					return []
2021
				if pwhistoryPolicy and pwhistoryPolicy.has_key('length') and pwhistoryPolicy['length']:
2021
				if pwhistoryPolicy and pwhistoryPolicy.has_key('length') and pwhistoryPolicy['length']:
2022
					pwhlen = int(pwhistoryPolicy['length'])
2022
					pwhlen = int(pwhistoryPolicy['length'])
2023
					newPWHistory = self.__getPWHistory(self['password'], pwhistory, pwhlen)
2023
					newPWHistory = object.__getPWHistory(self['password'], pwhistory, pwhlen)
2024
					ml.append(('pwhistory', self.oldattr.get('pwhistory', [''])[0], newPWHistory))
2024
					ml.append(('pwhistory', self.oldattr.get('pwhistory', [''])[0], newPWHistory))
2025
			if pwhistoryPolicy != None and pwhistoryPolicy['pwLength'] != None and pwhistoryPolicy['pwLength'] != 0 and self['overridePWLength'] != '1':
2025
			if pwhistoryPolicy != None and pwhistoryPolicy['pwLength'] != None and pwhistoryPolicy['pwLength'] != 0 and self['overridePWLength'] != '1':
2026
					if len(self['password']) < int(pwhistoryPolicy['pwLength']):
2026
					if len(self['password']) < int(pwhistoryPolicy['pwLength']):
 Lines 2502-2540   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2502
		newpwhash = s.hexdigest().upper()
2502
		newpwhash = s.hexdigest().upper()
2503
		return pwhistory.find(newpwhash) >= 0
2503
		return pwhistory.find(newpwhash) >= 0
2504
2504
2505
	def __getPWHistory(self, newpassword, pwhistory, pwhlen):
2505
	@staticmethod
2506
		# first calc hash for the new pw
2506
	def __getPWHistory(newpassword, pwhistory, pwhlen):
2507
		s = hashlib.sha1( newpassword.encode( 'utf-8' ) )
2507
		"""Save history of previopusly used passwords.
2508
		newpwhash = s.hexdigest().upper()
2508
		>>> object.__getPWHistory("a", "b", 0)
2509
2509
		"b"
2510
		# split the history
2510
		>>> object.__getPWHistory("a", "", 1)
2511
		if len(pwhistory.strip()):
2511
		"86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8"
2512
			pwlist = pwhistory.split(' ')
2512
		>>> object.__getPWHistory("a", "b", 1)
2513
		else:
2513
		"86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8"
2514
			pwlist = []
2514
		>>> object.__getPWHistory("a", "b", 2)
2515
2515
		"b 86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8"
2516
		"""
2516
		#this preserves a temporary disabled history
2517
		#this preserves a temporary disabled history
2517
		if pwhlen > 0:
2518
		if pwhlen > 0:
2518
			if len(pwlist) < pwhlen:
2519
			# first calc hash for the new pw
2519
				pwlist.append(newpwhash)
2520
			s = hashlib.sha1(newpassword.encode('utf-8'))
2520
			else:
2521
			newpwhash = s.hexdigest().upper()
2521
				# calc entries to cut out
2522
2522
				cut = 1 + len(pwlist) - pwhlen
2523
			# split the history
2523
				pwlist[0:cut] = []
2524
			pwlist = pwhistory.strip().split(' ')
2524
				if pwhlen > 1:
2525
			# append new hash
2525
					# and append to shortened history
2526
			pwlist.append(newpwhash)
2526
					pwlist.append(newpwhash)
2527
			# strip old hashes
2527
				else:
2528
			pwlist = pwlist[-pwhlen:]
2528
					# or replace the history completely
2529
			# build histroy
2529
					if len(pwlist) > 0:
2530
			pwhistory = ' '.join(pwlist)
2530
						pwlist[0] = newpwhash
2531
		return pwhistory
2531
						# just to be sure...
2532
						pwlist[1:] = []
2533
					else:
2534
						pwlist.append(newpwhash)
2535
		# and build the new history
2536
		res = ' '.join(pwlist)
2537
		return res
2538
2532
2539
	def __getsmbPWHistory(self, newpassword, smbpwhistory, smbpwhlen):
2533
	def __getsmbPWHistory(self, newpassword, smbpwhistory, smbpwhlen):
2540
		# split the history
2534
		# split the history
 Lines 2562-2589   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2562
		pwdhash = hashlib.md5(salt + pwd).hexdigest().upper()
2556
		pwdhash = hashlib.md5(salt + pwd).hexdigest().upper()
2563
		smbpwhash = hexsalt+pwdhash
2557
		smbpwhash = hexsalt+pwdhash
2564
2558
2565
		if len(pwlist) < smbpwhlen:
2559
		# split the history
2566
			#just append
2560
		pwlist = smbpwhistory.strip().split(' ')
2567
			pwlist.append(smbpwhash)
2561
		# append new hash
2568
		else:
2562
		pwlist.append(smbpwhash)
2569
			#calc entries to cut out
2563
		# strip old hashes
2570
			cut = 1 + len(pwlist) - smbpwhlen
2564
		pwlist = pwlist[-smbpwhlen:]
2571
			pwlist[0:cut] = []
2565
		# build history
2572
			if smbpwhlen > 1:
2566
		smbpwhistory = ''.join(pwlist)
2573
				#and append to shortened history
2567
		return smbpwhistory
2574
				pwlist.append(smbpwhash)
2575
			else:
2576
				# or replace the history completely
2577
				if len(pwlist) > 0:
2578
					pwlist[0] = smbpwhash
2579
					# just to be sure...
2580
					pwlist[1:] = []
2581
				else:
2582
					pwlist.append(smbpwhash)
2583
2584
		# and build the new history
2585
		res = ''.join(pwlist)
2586
		return res
2587
2568
2588
	def __generate_user_sid(self, uidNum):
2569
	def __generate_user_sid(self, uidNum):
2589
		# TODO: cleanup function
2570
		# TODO: cleanup function
2590
- 
2591
--
2592
.../modules/univention/admin/password.py           |   54 +++++++++++---------
2571
.../modules/univention/admin/password.py           |   54 +++++++++++---------
2593
1 file changed, 29 insertions(+), 25 deletions(-)
2572
1 file changed, 29 insertions(+), 25 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/password.py (-27 / +29 lines)
 Lines 30-68    Link Here 
30
# /usr/share/common-licenses/AGPL-3; if not, see
30
# /usr/share/common-licenses/AGPL-3; if not, see
31
# <http://www.gnu.org/licenses/>.
31
# <http://www.gnu.org/licenses/>.
32
32
33
import os, heimdal, codecs, types, string, sys
33
import heimdal
34
import smbpasswd
34
import smbpasswd
35
import univention.config_registry
35
from univention.config_registry import ConfigRegistry
36
from crypt import crypt as _crypt
36
37
37
configRegistry=univention.config_registry.ConfigRegistry()
38
configRegistry = ConfigRegistry()
38
configRegistry.load()
39
configRegistry.load()
39
40
40
def crypt(password):
41
def crypt(password):
41
	"""return crypt hash"""
42
	"""return crypt hash"""
42
43
	valid = ['.', '/', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
44
		'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
45
		'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
46
		'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
47
		'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5',
48
		'6', '7', '8', '9' ]
49
	salt = ''
43
	salt = ''
50
	urandom = open("/dev/urandom", "r")
44
	urandom = open("/dev/urandom", "r")
51
	for i in xrange(0, 16): # up to 16 bytes of salt are evaluated by crypt(3), overhead is ignored
45
	for i in xrange(0, 16): # up to 16 bytes of salt are evaluated by crypt(3), overhead is ignored
52
		o = ord(urandom.read(1))
46
		o = ord(urandom.read(1))
53
		while not o < 256 / len(valid) * len(valid): # make sure not to skew the distribution when using modulo
47
		while not o < 256 / len(crypt.VALID) * len(crypt.VALID): # make sure not to skew the distribution when using modulo
54
			o = ord(urandom.read(1))
48
			o = ord(urandom.read(1))
55
		salt = salt + valid[(o % len(valid))]
49
		salt = salt + crypt.VALID[(o % len(crypt.VALID))]
56
	urandom.close()
50
	urandom.close()
57
51
58
	import crypt # UCRV
52
	method = configRegistry.get('password/hashing/method', 'sha-512').upper()
59
	method_id = {'MD5': '1',
53
	method_id = crypt.METHOD.get(method, 6)
60
	             'SHA256': '5',
54
	return _crypt(password.encode('utf-8'), '$%s$%s$' % (method_id, salt, ))
61
	             'SHA-256': '5',
55
crypt.VALID = (
62
	             'SHA512': '6',
56
		'.', '/', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
63
	             'SHA-512': '6',
57
		'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
64
	             }.get(configRegistry.get('password/hashing/method', 'sha-512').upper(), 6)
58
		'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
65
	return crypt.crypt(password.encode('utf-8'), '$%s$%s$' % (method_id, salt, ))
59
		'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
60
		'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5',
61
		'6', '7', '8', '9',
62
		)
63
crypt.METHOD = {
64
		'MD5': '1',
65
		'SHA256': '5',
66
		'SHA-256': '5',
67
		'SHA512': '6',
68
		'SHA-512': '6',
69
		}
66
70
67
def ntlm(password):
71
def ntlm(password):
68
	"""return tuple with NT and LanMan hash"""
72
	"""return tuple with NT and LanMan hash"""
 Lines 77-94   def ntlm(password): Link Here 
77
	return (nt, lm)
81
	return (nt, lm)
78
82
79
def krb5_asn1(principal, password, krb5_context=None):
83
def krb5_asn1(principal, password, krb5_context=None):
80
	list=[]
84
	if isinstance(principal, unicode):
81
	if type(principal) == types.UnicodeType:
82
		principal = str( principal )
85
		principal = str( principal )
83
	if type(password) == types.UnicodeType:
86
	if isinstance(password, unicode):
84
		password = str( password )
87
		password = str( password )
85
	if not krb5_context:
88
	if not krb5_context:
86
		krb5_context = heimdal.context()
89
		krb5_context = heimdal.context()
90
	result = []
87
	for krb5_etype in krb5_context.get_permitted_enctypes():
91
	for krb5_etype in krb5_context.get_permitted_enctypes():
88
		if str(krb5_etype) == 'des3-cbc-md5' and configRegistry.is_false('password/krb5/enctype/des3-cbc-md5', True):
92
		if str(krb5_etype) == 'des3-cbc-md5' and configRegistry.is_false('password/krb5/enctype/des3-cbc-md5', True):
89
			continue
93
			continue
90
		krb5_principal = heimdal.principal(krb5_context, principal)
94
		krb5_principal = heimdal.principal(krb5_context, principal)
91
		krb5_keyblock = heimdal.keyblock(krb5_context, krb5_etype, password, krb5_principal)
95
		krb5_keyblock = heimdal.keyblock(krb5_context, krb5_etype, password, krb5_principal)
92
		krb5_salt = heimdal.salt(krb5_context, krb5_principal)
96
		krb5_salt = heimdal.salt(krb5_context, krb5_principal)
93
		list.append(heimdal.asn1_encode_key(krb5_keyblock, krb5_salt, 0))
97
		result.append(heimdal.asn1_encode_key(krb5_keyblock, krb5_salt, 0))
94
	return list
98
	return result
95
- 
96
--
97
.../modules/univention/admin/handlers/users/user.py           |    9 ++-------
99
.../modules/univention/admin/handlers/users/user.py           |    9 ++-------
98
1 file changed, 2 insertions(+), 7 deletions(-)
100
1 file changed, 2 insertions(+), 7 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-9 / +2 lines)
 Lines 2538-2553   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2538
			pwlist = []
2538
			pwlist = []
2539
2539
2540
		#calculate the password hash & salt
2540
		#calculate the password hash & salt
2541
		salt=''
2542
		urandom = open('/dev/urandom', 'r')
2541
		urandom = open('/dev/urandom', 'r')
2543
		#get 16 bytes from urandom for salting our hash
2542
		#get 16 bytes from urandom for salting our hash
2544
		rand = urandom.read(16)
2543
		salt = urandom.read(16)
2545
		for i in range(0, len(rand)):
2546
			salt = salt + '%.2X' % ord(rand[i])
2547
		#we have to have that in hex
2544
		#we have to have that in hex
2548
		hexsalt = salt
2545
		hexsalt = salt.encode('hex').upper()
2549
		#and binary for calculating the md5
2550
		salt = self.getbytes(salt)
2551
		#we need the ntpwd binary data to
2546
		#we need the ntpwd binary data to
2552
		pwd = self.getbytes(newpassword)
2547
		pwd = self.getbytes(newpassword)
2553
		#calculating hash. sored as a 32byte hex in sambePasswordHistory,
2548
		#calculating hash. sored as a 32byte hex in sambePasswordHistory,
2554
- 
2555
--
2556
.../modules/univention/admin/handlers/users/user.py             |    7 +------
2549
.../modules/univention/admin/handlers/users/user.py             |    7 +------
2557
1 file changed, 1 insertion(+), 6 deletions(-)
2550
1 file changed, 1 insertion(+), 6 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-8 / +1 lines)
 Lines 2544-2550   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2544
		#we have to have that in hex
2544
		#we have to have that in hex
2545
		hexsalt = salt.encode('hex').upper()
2545
		hexsalt = salt.encode('hex').upper()
2546
		#we need the ntpwd binary data to
2546
		#we need the ntpwd binary data to
2547
		pwd = self.getbytes(newpassword)
2547
		pwd = newpassword.decode('hex')
2548
		#calculating hash. sored as a 32byte hex in sambePasswordHistory,
2548
		#calculating hash. sored as a 32byte hex in sambePasswordHistory,
2549
		#syntax like that: [Salt][MD5(Salt+Hash)]
2549
		#syntax like that: [Salt][MD5(Salt+Hash)]
2550
		#	First 16bytes ^		^ last 16bytes.
2550
		#	First 16bytes ^		^ last 16bytes.
 Lines 2597-2607   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2597
2597
2598
		return userSid
2598
		return userSid
2599
2599
2600
	def getbytes(self, string):
2601
		#return byte values of a string (for smbPWHistory)
2602
		bytes = [int(string[i:i+2], 16) for i in xrange(0, len(string), 2)]
2603
		return struct.pack("%iB" % len(bytes), *bytes)
2604
2605
	def cancel(self):
2600
	def cancel(self):
2606
		for i,j in self.alloc:
2601
		for i,j in self.alloc:
2607
			univention.admin.allocators.release(self.lo, self.position, i, j)
2602
			univention.admin.allocators.release(self.lo, self.position, i, j)
2608
- 
2609
--
2610
.../univention/admin/handlers/users/user.py        |   70 +++++++++++---------
2603
.../univention/admin/handlers/users/user.py        |   70 +++++++++++---------
2611
1 file changed, 39 insertions(+), 31 deletions(-)
2604
1 file changed, 39 insertions(+), 31 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-33 / +39 lines)
 Lines 32-42    Link Here 
32
32
33
import hashlib
33
import hashlib
34
import os
34
import os
35
import string
36
import re
35
import re
37
import copy
36
import copy
38
import time
37
import time
39
import types
40
import struct
38
import struct
41
import tempfile
39
import tempfile
42
from M2Crypto import X509
40
from M2Crypto import X509
 Lines 2015-2026   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2015
			pwhistoryPolicy = self.loadPolicyObject('policies/pwhistory')
2013
			pwhistoryPolicy = self.loadPolicyObject('policies/pwhistory')
2016
			if self['overridePWHistory'] != '1':
2014
			if self['overridePWHistory'] != '1':
2017
				#TODO: if checkbox "override pwhistory" is not set
2015
				#TODO: if checkbox "override pwhistory" is not set
2018
				if self.__passwordInHistory(self['password'], pwhistory):
2016
				if object._passwordInHistory(self['password'], pwhistory):
2019
					raise univention.admin.uexceptions.pwalreadyused
2017
					raise univention.admin.uexceptions.pwalreadyused
2020
					return []
2018
					return []
2021
				if pwhistoryPolicy and pwhistoryPolicy.has_key('length') and pwhistoryPolicy['length']:
2019
				if pwhistoryPolicy and pwhistoryPolicy.has_key('length') and pwhistoryPolicy['length']:
2022
					pwhlen = int(pwhistoryPolicy['length'])
2020
					pwhlen = int(pwhistoryPolicy['length'])
2023
					newPWHistory = object.__getPWHistory(self['password'], pwhistory, pwhlen)
2021
					newPWHistory = object._getPWHistory(self['password'], pwhistory, pwhlen)
2024
					ml.append(('pwhistory', self.oldattr.get('pwhistory', [''])[0], newPWHistory))
2022
					ml.append(('pwhistory', self.oldattr.get('pwhistory', [''])[0], newPWHistory))
2025
			if pwhistoryPolicy != None and pwhistoryPolicy['pwLength'] != None and pwhistoryPolicy['pwLength'] != 0 and self['overridePWLength'] != '1':
2023
			if pwhistoryPolicy != None and pwhistoryPolicy['pwLength'] != None and pwhistoryPolicy['pwLength'] != 0 and self['overridePWLength'] != '1':
2026
					if len(self['password']) < int(pwhistoryPolicy['pwLength']):
2024
					if len(self['password']) < int(pwhistoryPolicy['pwLength']):
 Lines 2132-2141   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2132
				sambaPwdLastSetValue = str(long(time.time()))
2130
				sambaPwdLastSetValue = str(long(time.time()))
2133
2131
2134
				smbpwhistoryPolicy = self.loadPolicyObject('policies/pwhistory')
2132
				smbpwhistoryPolicy = self.loadPolicyObject('policies/pwhistory')
2135
				if smbpwhistoryPolicy != None and smbpwhistoryPolicy['length'] != None:
2133
				if smbpwhistoryPolicy and smbpwhistoryPolicy['length'] != None:
2136
					smbpwhlen = int(pwhistoryPolicy['length'])
2134
					smbpwhlen = int(pwhistoryPolicy['length'])
2137
					smbpwhistory=self.oldattr.get('sambaPasswordHistory',[''])[0]
2135
					smbpwhistory=self.oldattr.get('sambaPasswordHistory',[''])[0]
2138
					newsmbPWHistory = self.__getsmbPWHistory(password_nt, smbpwhistory, smbpwhlen)
2136
					newsmbPWHistory = object._getsmbPWHistory(password_nt, smbpwhistory, smbpwhlen)
2139
					ml.append(('sambaPasswordHistory', self.oldattr.get('sambaPasswordHistory', [''])[0], newsmbPWHistory))
2137
					ml.append(('sambaPasswordHistory', self.oldattr.get('sambaPasswordHistory', [''])[0], newsmbPWHistory))
2140
2138
2141
			if 'kerberos' in self.options:
2139
			if 'kerberos' in self.options:
 Lines 2371-2377   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2371
						ml.insert(0, ('objectClass', '', 'automount'))
2369
						ml.insert(0, ('objectClass', '', 'automount'))
2372
2370
2373
					am_host=share['host']
2371
					am_host=share['host']
2374
					if not self['homeSharePath'] or type(self['homeSharePath']) not in [types.StringType, types.UnicodeType]:
2372
					if not self['homeSharePath'] or not isinstance(self['homeSharePath'], basestring):
2375
						raise univention.admin.uexceptions.missingInformation, _('%(homeSharePath)s must be given if %(homeShare)s is given.') % {'homeSharePath' : _('Home share path'), 'homeShare' : _('Home share')}
2373
						raise univention.admin.uexceptions.missingInformation, _('%(homeSharePath)s must be given if %(homeShare)s is given.') % {'homeSharePath' : _('Home share path'), 'homeShare' : _('Home share')}
2376
					else:
2374
					else:
2377
						am_path = os.path.abspath(os.path.join(share['path'], self['homeSharePath']))
2375
						am_path = os.path.abspath(os.path.join(share['path'], self['homeSharePath']))
 Lines 2496-2518   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2496
				self.move_subelements(tmpdn, olddn, subelements, ignore_license)
2494
				self.move_subelements(tmpdn, olddn, subelements, ignore_license)
2497
				raise
2495
				raise
2498
2496
2499
	def __passwordInHistory(self, newpassword, pwhistory):
2497
	@staticmethod
2498
	def _passwordInHistory(newpassword, pwhistory):
2499
		"""Check if new password was already used.
2500
		>>> object._passwordInHistory('a', '')
2501
		False
2502
		>>> object._passwordInHistory('a', 'b')
2503
		False
2504
		>>> object._passwordInHistory('a', 'b 86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8')
2505
		True
2506
		"""
2500
		# first calc hash for the new pw
2507
		# first calc hash for the new pw
2501
		s = hashlib.sha1( newpassword.encode( 'utf-8' ) )
2508
		s = hashlib.sha1(newpassword.encode('utf-8'))
2502
		newpwhash = s.hexdigest().upper()
2509
		newpwhash = s.hexdigest().upper()
2503
		return pwhistory.find(newpwhash) >= 0
2510
		pwlist = pwhistory.strip().split(' ')
2511
		return newpwhash in pwlist
2504
2512
2505
	@staticmethod
2513
	@staticmethod
2506
	def __getPWHistory(newpassword, pwhistory, pwhlen):
2514
	def _getPWHistory(newpassword, pwhistory, pwhlen):
2507
		"""Save history of previopusly used passwords.
2515
		"""Save history of previopusly used passwords.
2508
		>>> object.__getPWHistory("a", "b", 0)
2516
		>>> object._getPWHistory('a', 'b', 0)
2509
		"b"
2517
		'b'
2510
		>>> object.__getPWHistory("a", "", 1)
2518
		>>> object._getPWHistory('a', '', 1)
2511
		"86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8"
2519
		'86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8'
2512
		>>> object.__getPWHistory("a", "b", 1)
2520
		>>> object._getPWHistory('a', 'b', 1)
2513
		"86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8"
2521
		'86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8'
2514
		>>> object.__getPWHistory("a", "b", 2)
2522
		>>> object._getPWHistory('a', 'b', 2)
2515
		"b 86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8"
2523
		'b 86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8'
2516
		"""
2524
		"""
2517
		#this preserves a temporary disabled history
2525
		#this preserves a temporary disabled history
2518
		if pwhlen > 0:
2526
		if pwhlen > 0:
 Lines 2530-2555   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
2530
			pwhistory = ' '.join(pwlist)
2538
			pwhistory = ' '.join(pwlist)
2531
		return pwhistory
2539
		return pwhistory
2532
2540
2533
	def __getsmbPWHistory(self, newpassword, smbpwhistory, smbpwhlen):
2541
	@staticmethod
2534
		# split the history
2542
	def _getsmbPWHistory(self, newpassword, smbpwhistory, smbpwhlen):
2535
		if len(smbpwhistory.strip()):
2543
		"""Save history of previopusly used passwords.
2536
			pwlist = smbpwhistory.split(' ')
2544
		"""
2537
		else:
2538
			pwlist = []
2539
2540
		#calculate the password hash & salt
2545
		#calculate the password hash & salt
2541
		urandom = open('/dev/urandom', 'r')
2546
		urandom = open('/dev/urandom', 'r')
2542
		#get 16 bytes from urandom for salting our hash
2547
		try:
2543
		salt = urandom.read(16)
2548
			#get 16 bytes from urandom for salting our hash
2549
			salt = urandom.read(16)
2550
		finally:
2551
			urandom.close()
2544
		#we have to have that in hex
2552
		#we have to have that in hex
2545
		hexsalt = salt.encode('hex').upper()
2553
		hexsalt = salt.encode('hex').upper()
2546
		#we need the ntpwd binary data to
2554
		#we need the ntpwd binary data to
2547
		pwd = newpassword.decode('hex')
2555
		password = newpassword.decode('hex')
2548
		#calculating hash. sored as a 32byte hex in sambePasswordHistory,
2556
		#calculating hash. sored as a 32byte hex in sambePasswordHistory,
2549
		#syntax like that: [Salt][MD5(Salt+Hash)]
2557
		#syntax like that: [Salt][MD5(Salt+Hash)]
2550
		#	First 16bytes ^		^ last 16bytes.
2558
		#	First 16bytes ^		^ last 16bytes.
2551
		pwdhash = hashlib.md5(salt + pwd).hexdigest().upper()
2559
		pwdhash = hashlib.md5(salt + password).hexdigest().upper()
2552
		smbpwhash = hexsalt+pwdhash
2560
		smbpwhash = hexsalt + pwdhash
2553
2561
2554
		# split the history
2562
		# split the history
2555
		pwlist = smbpwhistory.strip().split(' ')
2563
		pwlist = smbpwhistory.strip().split(' ')
2556
- 
2557
--
2558
.../univention/admin/handlers/users/user.py        |  116 ++++++--------------
2564
.../univention/admin/handlers/users/user.py        |  116 ++++++--------------
2559
1 file changed, 33 insertions(+), 83 deletions(-)
2565
1 file changed, 33 insertions(+), 83 deletions(-)
(-)a/branches/ucs-3.1/ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/users/user.py (-84 / +33 lines)
 Lines 1041-1091   def GMTOffset(): Link Here 
1041
1041
1042
def load_certificate(user_certificate):
1042
def load_certificate(user_certificate):
1043
	"""Import a certificate in DER format"""
1043
	"""Import a certificate in DER format"""
1044
	certificate = base64.decodestring( user_certificate )
1044
	if not user_certificate:
1045
1046
	tempf=tempfile.mktemp()
1047
	fh=open(tempf,'w')
1048
	fh.write( certificate )
1049
	fh.close()
1050
1051
	x509 = X509.load_cert( tempf, format = X509.FORMAT_DER )
1052
	os.unlink( tempf )
1053
	if not x509:
1054
		return {}
1045
		return {}
1055
1046
	try:
1056
	not_after=x509.get_not_after()
1047
		certificate = base64.decodestring( user_certificate )
1057
	not_before=x509.get_not_before()
1048
	except base64.binascii.Error, ex:
1058
1059
	if not not_after or not not_before:
1060
		return {}
1061
1062
	def convert_certdate (certdate):
1063
		datestring=str(certdate)
1064
		dl = datestring.split()
1065
		month=[None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1066
		try:
1067
			dl[0]=month.index(dl[0])
1068
		except:
1069
			return ''
1070
		return "%s-%02d-%02d" % ( dl[ 3 ], int( dl[ 0 ] ), int( dl[ 1 ] ) )
1071
1072
	issuer=str(x509.get_issuer())
1073
	if not issuer:
1074
		return {}
1075
1076
	subject=str(x509.get_subject())
1077
	if not subject:
1078
		return {}
1079
1080
	version=x509.get_version()
1081
	if not version:
1082
		return {}
1049
		return {}
1083
1050
	try:
1084
	serial=x509.get_serial_number()
1051
		x509 = X509.load_cert_string(certificate, X509.FORMAT_DER)
1085
	if not serial:
1052
1053
		values = {
1054
				'certificateDateNotBefore': x509.get_not_before().get_datetime().date().isoformat(),
1055
				'certificateDateNotAfter': x509.get_not_after().get_datetime().date().isoformat(),
1056
				'certificateVersion': str(x509.get_version()),
1057
				'certificateSerial': str(x509.get_serial_number()),
1058
				}
1059
		flags = X509.m2.XN_FLAG_SEP_MULTILINE & ~X509.m2.ASN1_STRFLGS_ESC_MSB | X509.m2.ASN1_STRFLGS_UTF8_CONVERT
1060
		for entity, prefix in (
1061
			(x509.get_issuer(), "certificateIssuer"),
1062
			(x509.get_subject(), "certificateSubject"),
1063
			):
1064
			for key, attr in load_certificate.ATTR.items():
1065
				value = getattr(entity, key)
1066
				values[prefix + attr] = value
1067
	except (X509.X509Error, AttributeError), ex:
1086
		return {}
1068
		return {}
1087
1069
1088
	ATTR = {
1070
	ud.debug(ud.ADMIN, ud.ERROR, 'value=%s' % values)
1071
	return values
1072
load_certificate.ATTR = {
1089
			"C": "Country",
1073
			"C": "Country",
1090
			"ST": "State",
1074
			"ST": "State",
1091
			"L": "Location",
1075
			"L": "Location",
 Lines 1093-1128   def load_certificate(user_certificate): Link Here 
1093
			"OU": "OrganisationalUnit",
1077
			"OU": "OrganisationalUnit",
1094
			"CN": "CommonName",
1078
			"CN": "CommonName",
1095
			"emailAddress": "Mail",
1079
			"emailAddress": "Mail",
1096
			}[key]
1097
	value = {
1098
			'certificateDateNotBefore': convert_certdate(not_before),
1099
			'certificateDateNotAfter': convert_certdate(not_after),
1100
			'certificateVersion': str(version),
1101
			'certificateSerial': str(serial),
1102
			}
1080
			}
1103
	for i in issuer.split('/'):
1104
		try:
1105
			key, val = i.split('=', 1)
1106
		except ValueError:
1107
			continue
1108
		try:
1109
			attr = "certificateIssuer%s" % ATTR[key]
1110
		except KeyError:
1111
			continue
1112
		value[attr] = val
1113
	for i in subject.split('/'):
1114
		try:
1115
			key, val = i.split('=', 1)
1116
		except ValueError:
1117
			continue
1118
		try:
1119
			attr = "certificateSubject%s" % ATTR[key]
1120
		except KeyError:
1121
			continue
1122
		value[attr] = val
1123
1124
	ud.debug(ud.ADMIN, ud.ERROR, 'value=%s' % value)
1125
	return value
1126
1081
1127
def mapHomePostalAddress(old):
1082
def mapHomePostalAddress(old):
1128
	"""Map address to LDAP encoding.
1083
	"""Map address to LDAP encoding.
 Lines 1532-1538   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1532
		self.old_options= copy.deepcopy( self.options )
1487
		self.old_options= copy.deepcopy( self.options )
1533
1488
1534
1489
1535
	def __certificate_clean(self):
1490
	def reload_certificate(self):
1491
		"""Reload user certificate."""
1536
		self.info['certificateSubjectCountry']=''
1492
		self.info['certificateSubjectCountry']=''
1537
		self.info['certificateSubjectState']=''
1493
		self.info['certificateSubjectState']=''
1538
		self.info['certificateSubjectLocation']=''
1494
		self.info['certificateSubjectLocation']=''
 Lines 1551-1569   class object( univention.admin.handlers.simpleLdap, mungeddial.Support ): Link Here 
1551
		self.info['certificateDateNotAfter']=''
1507
		self.info['certificateDateNotAfter']=''
1552
		self.info['certificateVersion']=''
1508
		self.info['certificateVersion']=''
1553
		self.info['certificateSerial']=''
1509
		self.info['certificateSerial']=''
1554
		self.info['userCertificate']=''
1510
		certificate = self.info.get('userCertificate')
1555
1511
		values = load_certificate(certificate)
1556
	def reload_certificate(self):
1512
		if values:
1557
1513
			for key, value in values.items():
1558
		if self.info.get( 'userCertificate' ):
1514
				self.info[key] = value
1559
			values=load_certificate(self.info['userCertificate'])
1560
			if not values:
1561
				self.__certificate_clean()
1562
			else:
1563
				for i in values.keys():
1564
					self.info[i]=values[i]
1565
		else:
1515
		else:
1566
			self.__certificate_clean()
1516
			self.info['userCertificate'] = ''
1567
1517
1568
	def hasChanged(self, key):
1518
	def hasChanged(self, key):
1569
		if key == 'disabled':
1519
		if key == 'disabled':
1570
- 

Return to bug 30722