def test_disabled_user_creation_activation(disabled_cronjob, udm, ucr): """Check cron based activation of users/user with accountActivationDate""" now = datetime.now() with open("/etc/timezone", "r") as tzfile: timezone = tzfile.read().strip() ts_later = (now + timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M " + timezone) userdn, username = udm.create_user(accountActivationDate=ts_later) try: udm.verify_udm_object("users/user", userdn, {"disabled": "1"}) except (utils.LDAPObjectNotFound, utils.LDAPUnexpectedObjectFound): utils.fail("User creation failed") except (utils.LDAPObjectValueMissing, utils.LDAPObjectUnexpectedValue): utils.fail( "User is not disabled, despite setting future accountActivationDate" ) # verify that account can't bind with pytest.raises(univention.admin.uexceptions.authFail): lo = univention.admin.uldap.access(binddn=userdn, bindpw="univention") lo.lo.lo.whoami_s() handler_set(['%s=%s' % (ucrv, "*/1 * * * *")]) time.sleep(2 * 60) try: udm.verify_udm_object("users/user", userdn, {"disabled": "0"}) except (utils.LDAPObjectValueMissing, utils.LDAPObjectUnexpectedValue): utils.fail("User is still disabled, after accountActivationDate")
def configure_wizard_for_adconnection(self, adconnection_alias): # configure UCR to let wizard configure this adconnection # TODO: Should be removed in the future, as the wizard should be able to configure # adconnections by itself ucrv_set = '{}={}'.format(adconnection_wizard_ucrv, adconnection_alias) handler_set([ucrv_set]) subprocess.call(['pkill', '-f', '/usr/sbin/univention-management-console-module -m office365'])
def main(): """Get UCR settings from LDAP policy.""" options, host_dn = parse_cmdline() confregfn = os.path.join( confreg.ConfigRegistry.PREFIX, confreg.ConfigRegistry.BASES[confreg.ConfigRegistry.LDAP]) ucr_ldap = confreg.ConfigRegistry(filename=confregfn) ucr_ldap.load() set_list = get_policy(host_dn, options.verbose) if set_list: new_set_list = [] for key, value in set_list.items(): record = '%s=%s' % (key, value) if ucr_ldap.get(key) != value or options.setall: new_set_list.append(record.encode()) if options.simulate or options.verbose: for item in new_set_list: print >> sys.stderr, 'Setting %s' % item if not options.simulate: confreg.handler_set(new_set_list, {'ldap-policy': True}) unset_list = [] for key, value in ucr_ldap.items(): if key not in set_list: unset_list.append(key.encode()) if unset_list: if options.simulate or options.verbose: for item in unset_list: print >> sys.stderr, 'Unsetting %s' % item if not options.simulate: confreg.handler_unset(unset_list, {'ldap-policy': True})
def create_new_adconnection(self, adconnection_alias, make_default=False, description=""): aliases = self.get_adconnection_aliases() if adconnection_alias in aliases: logger.error('Azure AD connection alias %s is already listed in UCR %s.', adconnection_alias, adconnection_alias_ucrv) return None target_path = os.path.join(ADCONNECTION_CONF_BASEPATH, adconnection_alias) if os.path.exists(target_path): logger.error('Path %s already exists, but no UCR configuration for the Azure AD connection was found.', target_path) return None os.mkdir(target_path, 0o700) os.chown(target_path, pwd.getpwnam('listener').pw_uid, 0) for filename in ('cert.fp', 'cert.pem', 'key.pem'): src = os.path.join(ADCONNECTION_CONF_BASEPATH, filename) shutil.copy2(src, target_path) os.chown(os.path.join(target_path, filename), pwd.getpwnam('listener').pw_uid, 0) AzureAuth.uninitialize(adconnection_alias) ucrv = ['{}{}=uninitialized'.format(adconnection_alias_ucrv, adconnection_alias)] if make_default: ucrv.append('{}={}'.format(default_adconnection_alias_ucrv, adconnection_alias)) handler_set(ucrv) UDMHelper.create_udm_adconnection(adconnection_alias, description) self.configure_wizard_for_adconnection(adconnection_alias) self.listener_restart()
def handler(configRegistry, changes): groups = configRegistry.get('dansguardian/groups', 'web-access').split(';') for i in range(len(groups)): ucr.handler_set([ 'dansguardian/current/groupno=%d' % (i + 1), 'dansguardian/current/group=%s' % groups[i] ]) # primary filter group configuration file src = os.path.join(TEMPLATE_PATH, 'dansguardianfX.conf') src_fd = open(src) conf = os.path.join(CONFIG_PATH, 'dansguardianf%d.conf' % (i + 1)) content = ucr.filter(src_fd.read(), configRegistry, srcfiles=[src]) src_fd.close() fd = open(conf, 'w') fd.write(content) fd.close() # several lists for filter groups for entry in os.listdir(os.path.join(TEMPLATE_PATH, 'lists')): abs_filename = os.path.join(TEMPLATE_PATH, 'lists', entry) if os.path.isfile(abs_filename): template = open(abs_filename) conf = os.path.join(CONFIG_PATH, 'lists', '%s-%s' % (groups[i], entry)) content = ucr.filter(template.read(), configRegistry, srcfiles=[abs_filename]) template.close() fd = open(conf, 'w') fd.write(content) fd.close() ucr.handler_unset( ['dansguardian/current/groupno', 'dansguardian/current/group'])
def put( self, request ): message = '' request.status = SUCCESS success = True if isinstance( request.options, ( list, tuple ) ): for _var in request.options: try: var = _var['object'] value = var['value'] or '' key = var['key'] if self.is_readonly( key ): success = False message = _( 'The UCR variable %s is read-only and can not be changed!' ) % key break arg = [ '%s=%s' % ( key.encode(), value.encode() ) ] ucr.handler_set( arg ) # handle descriptions, type, and categories if 'descriptions' in var or 'type' in var or 'categories' in var: self.__create_variable_info( var ) except KeyError: # handle the case that neither key nor value are given for an UCR variable entry request.status = BAD_REQUEST_INVALID_OPTS self.finished(request.id, False, message = _('Invalid UCR variable entry, the properties "key" and "value" need to specified.')) return else: success = False request.status = BAD_REQUEST_INVALID_OPTS self.finished( request.id, success, message )
def handler(dn, new, old): # type: (str, dict, dict) -> None ucr = ConfigRegistry() ucr.load() listener.setuid(0) try: try: fqdn = '%s.%s' % (new['cn'][0].decode('UTF-8'), new['associatedDomain'][0].decode('ASCII')) except (KeyError, IndexError): return change = False if b'univention-saml' in new.get('univentionService', []): handler_set(['ucs/server/saml-idp-server/%s=%s' % (fqdn, fqdn)]) change = True elif b'univention-saml' in old.get('univentionService', []): handler_unset(['ucs/server/saml-idp-server/%s' % (fqdn,)]) change = True if change: path_to_cert = ucr.get('saml/idp/certificate/certificate') path_to_key = ucr.get('saml/idp/certificate/privatekey') if path_to_cert and os.path.exists(path_to_cert) and path_to_key and os.path.exists(path_to_key): subprocess.call(['systemctl', 'restart', 'univention-saml']) finally: listener.unsetuid()
def handler(dn, new, old): ucr = ConfigRegistry() ucr.load() idp_config_objectdn = ucr.get( 'saml/idp/configobject', 'id=default-saml-idp,cn=univention,%s' % ucr.get('ldap/base')) listener.setuid(0) try: if idp_config_objectdn == new['entryDN'][0]: for key in LDAP_UCR_MAPPING.keys(): if key in new: ucr_value = "" if key == 'LdapGetAttributes': ucr_value = "'" + "', '".join(new[key]) + "'" handler_set(['%s=%s' % (LDAP_UCR_MAPPING[key], ucr_value)]) else: handler_unset(['%s' % LDAP_UCR_MAPPING[key]]) else: ud.debug( ud.LISTENER, ud.WARN, 'An IdP config object was modified, but it is not the object the listener is configured for (%s). Ignoring changes. DN of modified object: %s' % (idp_config_objectdn, new['entryDN'])) finally: listener.unsetuid()
def enable_quota_in_kernel(activate): ucr.load() grub_append = ucr.get('grub/append', '') flags = [] option = 'usrquota' match = re.match(r'rootflags=([^\s]*)', grub_append) if match: flags = match.group(1).split(',') if activate and option not in flags: flags.append(option) elif not activate and option in flags: flags.remove(option) flags = ','.join(flags) if flags: flags = 'rootflags=%s' % (flags, ) new_grub_append = grub_append if 'rootflags=' not in grub_append: if flags: new_grub_append = '%s %s' % (grub_append, flags) else: new_grub_append = re.sub(r'rootflags=[^\s]*', flags, grub_append) if new_grub_append != grub_append: MODULE.info('Replacing grub/append from %s to %s' % (grub_append, new_grub_append)) handler_set(['grub/append=%s' % (new_grub_append, )]) status = _('enable') if activate else _('disable') raise QuotaActivationError( _('To %s quota support for the root filesystem the system has to be rebooted.' ) % (status, ))
def save(self): def rule_to_dict(rule): prefix = u'%s/%s' % (u'security/packetfilter', rule.identifier, ) result = {prefix: rule.action, } for (lang, description, ) in rule.description.items(): result[u'%s/%s' % (prefix, lang, )] = description return result config_registry = ucr.ConfigRegistry() config_registry.load() # set global firewall settings bool_to_string = {True: u'true', False: u'false', } global_options = { u'security/packetfilter/defaultpolicy': self.default_policy, u'security/packetfilter/disabled': bool_to_string[self.disabled], u'security/packetfilter/use_packages': bool_to_string[self.use_packages], } ucr.handler_set(global_options) org_dict = {} for (key, value, ) in config_registry.items(): if REGEX_RULE.match(key): org_dict[key] = value new_dict = {} for rule in self.rules.values(): if rule: new_dict = dict(new_dict.items() + rule_to_dict(rule).items()) diff = DictDiffer(new_dict, org_dict) ucr.handler_unset(diff.removed()) changed = [] for key in diff.changed().union(diff.added()): changed.append(u'%s=%s' % (key, new_dict[key])) ucr.handler_set(changed)
def main() -> None: """ Set repository server. """ ucr = ConfigRegistry() ucr.load() hostdn = ucr.get('ldap/hostdn') if not hostdn: # can't query policy without host-dn exit(0) online_server = ucr.get('repository/online/server') mirror_server = ucr.get('repository/mirror/server') fqdn = '%(hostname)s.%(domainname)s' % ucr self_update = '%(version/version)s-%(version/patchlevel)s' % ucr ucr_variables = [] # type: List[str] new_server, policy_update = query_policy(hostdn) policy_update or self_update # FIXME: not used - should be pass to `univention-repository-update --updateto=` if ucr.is_true('local/repository'): # on a repository server if not new_server: ucr_variables.append('repository/online/server?%s' % fqdn) elif new_server != mirror_server and new_server != fqdn: ucr_variables.append('repository/mirror/server=%s' % new_server) else: # without a local repository if new_server and new_server != online_server: ucr_variables.append('repository/online/server=%s' % new_server) if ucr_variables: handler_set(ucr_variables)
def main(): """Get UCR settings from LDAP policy.""" options, host_dn = parse_cmdline() confregfn = os.path.join(confreg.ConfigRegistry.PREFIX, confreg.ConfigRegistry.BASES[confreg.ConfigRegistry.LDAP]) ucr_ldap = confreg.ConfigRegistry(filename=confregfn) ucr_ldap.load() set_list = get_policy(host_dn, options.verbose) if set_list: new_set_list = [] for key, value in set_list.items(): record = '%s=%s' % (key, value) if ucr_ldap.get(key) != value or options.setall: new_set_list.append(record.encode()) if options.simulate or options.verbose: for item in new_set_list: print >> sys.stderr, 'Setting %s' % item if not options.simulate: confreg.handler_set(new_set_list, {'ldap-policy': True}) unset_list = [] for key, value in ucr_ldap.items(): if key not in set_list: unset_list.append(key.encode()) if unset_list: if options.simulate or options.verbose: for item in unset_list: print >> sys.stderr, 'Unsetting %s' % item if not options.simulate: confreg.handler_unset(unset_list, {'ldap-policy': True})
def handler( configRegistry, changes ): groups = configRegistry.get( 'dansguardian/groups', 'web-access' ).split( ';' ) for i in range( len( groups ) ): ucr.handler_set( [ 'dansguardian/current/groupno=%d' % ( i + 1 ), 'dansguardian/current/group=%s' % groups[ i ] ] ) # primary filter group configuration file src = os.path.join( TEMPLATE_PATH, 'dansguardianfX.conf' ) src_fd = open( src ) conf = os.path.join( CONFIG_PATH, 'dansguardianf%d.conf' % ( i + 1 ) ) content = ucr.filter( src_fd.read(), configRegistry, srcfiles = [ src ] ) src_fd.close() fd = open( conf, 'w' ) fd.write( content ) fd.close() # several lists for filter groups for entry in os.listdir( os.path.join( TEMPLATE_PATH, 'lists' ) ): abs_filename = os.path.join( TEMPLATE_PATH, 'lists', entry ) if os.path.isfile( abs_filename ): template = open( abs_filename ) conf = os.path.join( CONFIG_PATH, 'lists', '%s-%s' % (groups[ i ], entry ) ) content = ucr.filter( template.read(), configRegistry, srcfiles = [ abs_filename ] ) template.close() fd = open( conf, 'w' ) fd.write( content ) fd.close() ucr.handler_unset( [ 'dansguardian/current/groupno', 'dansguardian/current/group' ] )
def test_create_modify_move_remove(random_string, suffix, ucr): if suffix: handler_set(['directory/manager/web/modules/users/user/properties/username/syntax=string']) subprocess.call(['service', 'univention-directory-manager-rest', 'restart']) with UDM() as udm: username = random_string() + suffix userdn, user = udm.create_user(username=username) udm.verify_ldap_object(userdn) org_dn = userdn username = random_string() + suffix description = random_string() userdn = udm.modify_object('users/user', dn=userdn, description=description) udm.verify_ldap_object(userdn) assert userdn == org_dn userdn = udm.modify_object('users/user', dn=userdn, username=username) udm.verify_ldap_object(userdn) assert userdn != org_dn org_dn = userdn userdn = udm.move_object('users/user', dn=userdn, position=ucr['ldap/base']) udm.verify_ldap_object(userdn) assert userdn != org_dn udm.remove_object('users/user', dn=userdn) udm.verify_ldap_object(userdn, should_exist=False)
def test_udm_users_ldap_mspolicy(udm, ucr, module): # bugs: [52446] """Test mspolicy password functionality""" from univention.config_registry import handler_set handler_set(['password/quality/mspolicy=true']) attr = {'name': uts.random_username(), 'pwQualityCheck': 'TRUE'} pol_dn = udm.create_object('policies/pwhistory', wait_for_replication=True, check_for_drs_replication=True, wait_for=True, **attr) utils.wait_for_replication_and_postrun() name = "%s_test1" % (uts.random_username()) attr = { 'password': '******', 'username': name, 'lastname': 'test', 'policy_reference': pol_dn } dn = udm.create_object(module, wait_for_replication=True, check_for_drs_replication=True, wait_for=True, **attr) with pytest.raises(udm_test.UCSTestUDM_ModifyUDMObjectFailed): udm.modify_object(module, dn=dn, password='******') with pytest.raises(udm_test.UCSTestUDM_ModifyUDMObjectFailed): udm.modify_object(module, dn=dn, password='******' % (name, )) if module == 'users/user': with pytest.raises(udm_test.UCSTestUDM_ModifyUDMObjectFailed): udm.modify_object(module, dn=dn, password='******')
def create_without_hooks(self, lo, validate): district = self.get_district() if district: ou = OU(name=district) ou.position = ucr.get('ldap/base') ou.create(lo, False) # setting class_share_file_server and home_share_file_server: # 1. set to None # 2. create school # 3. (maybe) create file_servers <- that is why this is necessary # 4. set file_servers # 5. modify school saved_class_share_file_server = self.class_share_file_server saved_home_share_file_server = self.home_share_file_server self.class_share_file_server = None self.home_share_file_server = None try: success = super(School, self).create_without_hooks(lo, validate) if not success: logger.warning('Creating %r failed (maybe it already exists?)! Trying to set it up nonetheless', self) self.modify_without_hooks(lo) # In a single server environment the default DHCP container must # be set to the DHCP container in the school ou. Otherwise newly # imported computers have the DHCP objects in the wrong DHCP container if ucr.is_true('ucsschool/singlemaster', False): if not ucr.get('dhcpd/ldap/base'): handler_set(['dhcpd/ldap/base=cn=dhcp,%s' % (self.dn)]) ucr.load() self.create_default_containers(lo) self.create_default_groups(lo) self.add_host_to_dc_group(lo) if not self.add_domain_controllers(lo): return False if self.dc_name_administrative: self.create_dc_slave(lo, self.dc_name_administrative, administrative=True) dhcp_service = self.get_dhcp_service(self.dc_name_administrative) dhcp_service.create(lo) dhcp_service.add_server(self.dc_name_administrative, lo) finally: logger.debug('Resetting share file servers from None to %r and %r', saved_home_share_file_server, saved_class_share_file_server) self.class_share_file_server = saved_class_share_file_server self.home_share_file_server = saved_home_share_file_server self.class_share_file_server = self.get_class_share_file_server(lo) self.home_share_file_server = self.get_home_share_file_server(lo) logger.debug('Now it is %r and %r - %r should be modified accordingly', self.home_share_file_server, self.class_share_file_server, self) self.modify_without_hooks(lo) # if requested, then create dhcp_dns policy that clears univentionDhcpDomainNameServers at OU level # to prevent problems with "wrong" DHCP DNS policy connected to ldap base if ucr.is_true('ucsschool/import/generate/policy/dhcp/dns/clearou', False): policy = DHCPDNSPolicy(name='dhcp-dns-clear', school=self.name, empty_attributes=['univentionDhcpDomainNameServers']) policy.create(lo) policy.attach(self, lo) return success
def activate_quick_ldif_mode(): with UCSTestConfigRegistry() as ucr: handler_set(['listener/ldap/retries=0', 'replication/ldap/retries=0']) subprocess.check_call( ['systemctl', 'restart', 'univention-directory-listener']) yield ucr subprocess.check_call( ['systemctl', 'restart', 'univention-directory-listener'])
def add_ucs_version_to_appcenter(self, version): if not os.path.exists('/var/www/meta-inf'): os.makedirs('/var/www/meta-inf', 0755) self.meta_inf_created = True if not os.path.exists('/var/www/univention-repository'): os.makedirs('/var/www/univention-repository', 0755) self.univention_repository_created = True os.makedirs('/var/www/univention-repository/%s/maintained/component' % version) os.makedirs('/var/www/meta-inf/%s' % version) if not os.path.exists('/var/www/meta-inf/categories.ini'): f = open('/var/www/meta-inf/categories.ini', 'w') f.write('''[de] Administration=Administration Business=Business Collaboration=Collaboration Education=Schule System services=Systemdienste UCS components=UCS-Komponenten Virtualization=Virtualisierung''') if not os.path.exists('/var/www/meta-inf/app-categories.ini'): with open('/var/www/meta-inf/app-categories.ini', 'w') as f: f.write('[de]\n' 'Backup & Archiving=Backup & Archivierung\n' 'Education=Bildung\n' 'CMS=CMS\n' 'Collaboration & Groupware=Collaboration & Groupware\n' 'CRM & ERP=CRM & ERP\n' 'Desktop=Desktop\n' 'Device Management=Device Management\n' 'File Sync & Share=File Sync & Share\n' 'Identity Management=Identity Management\n' 'Infrastructure=Infrastruktur\n' 'Mail & Messaging=Mail & Messaging\n' 'Office=Office\n' 'Printing=Drucken\n' 'Project Management=Projekt Management\n' 'Security=Sicherheit\n' 'Storage=Speicher\n' 'Telephony=Telefonie\n' 'Virtualization=Virtualisierung\n') with open('/var/www/meta-inf/rating.ini', 'w') as f: f.write('# rating stuff\n') with open('/var/www/meta-inf/license_types.ini', 'w') as f: f.write('# license stuff') handler_set([ 'update/secure_apt=no', 'appcenter/index/verify=false', 'repository/app_center/server=http://%s.%s' % (self.ucr['hostname'], self.ucr['domainname']) ])
def __enter__(self): handler_set(['hosts/static/127.0.100.101=license.univention.de']) subprocess.check_call([ 'univention-certificate', 'new', '-name', 'license.univention.de', '-days', '1', ]) self.server.start() return self
def set_mail_forward_copy_to_self_ucrv(value): handler_set( [ "directory/manager/user/activate_ldap_attribute_mailForwardCopyToSelf={}".format(value), "mail/postfix/activate_unionmap_in_virtual_alias_maps={}".format(value), "mail/postfix/activate_ldap_attribute_mailForwardCopyToSelf_in_virtual_alias_maps={}".format(value) ] ) reload_postfix() restart_postfix()
def test_modlist_cn(self, restart_s4connector_if_present, udm, ucr, form, props, cn): try: with UCSTestConfigRegistry(): handler_set(['directory/manager/usercn/attributes=%s' % (form,)]) # restart udm cli and connector to apply new setting udm.stop_cli_server() restart_s4connector_if_present() self._test_modlist(udm, props, {'cn': [cn]}) finally: udm.stop_cli_server() restart_s4connector_if_present()
def handler( dn, new, old ): if new and 'Software Monitor' in new.get( 'univentionService', () ): listener.setuid( 0 ) ucr.handler_set( ( 'pkgdb/scan=yes', ) ) listener.unsetuid() elif old and 'Software Monitor' in old.get( 'univentionService', () ): if not ldap_info['lo']: ldap_reconnect() if ldap_info['lo'] and not ldap_info['lo'].search(filter='(&%s(univentionService=Software Monitor))' % filter, attr=['univentionService']): listener.setuid( 0 ) ucr.handler_set( ( 'pkgdb/scan=no', ) ) listener.unsetuid()
def activate_lastbind(bindpwdfile, other_server): handler_set(['ldap/overlay/lastbind=true']) subprocess.call(['service', 'slapd', 'restart']) if other_server: subprocess.call([ 'univention-ssh', bindpwdfile, other_server.props.fqdn, 'ucr', 'set', 'ldap/overlay/lastbind=true' ]) subprocess.call([ 'univention-ssh', bindpwdfile, other_server.props.fqdn, 'service', 'slapd', 'restart' ])
def handler(dn, new, old): if new and 'Software Monitor' in new.get('univentionService', ()): listener.setuid(0) ucr.handler_set(('pkgdb/scan=yes', )) listener.unsetuid() elif old and 'Software Monitor' in old.get('univentionService', ()): if not ldap_info['lo']: ldap_reconnect() if ldap_info['lo'] and not ldap_info['lo'].search(filter='(&%s(univentionService=Software Monitor))' % filter, attr=['univentionService']): listener.setuid(0) ucr.handler_set(('pkgdb/scan=no', )) listener.unsetuid()
def handler(dn, new, old): # type: (str, dict, dict) -> None if new and b'Software Monitor' in new.get('univentionService', ()): with SetUID(0): ucr.handler_set(('pkgdb/scan=yes', )) elif old and b'Software Monitor' in old.get('univentionService', ()): if not ldap_info['lo']: ldap_reconnect() if ldap_info['lo'] and not ldap_info['lo'].search( filter='(&%s(univentionService=Software Monitor))' % filter, attr=['univentionService']): with SetUID(0): ucr.handler_set(('pkgdb/scan=no', ))
def update_net(options: Namespace) -> None: """ Copy packages and scripts from remote mirror into local repository """ mirror = UniventionMirror() # update local repository if available urepo.assert_local_repository() # mirror.run calls "apt-mirror", which needs /etc/apt/mirror.conf, which is # only generated with repository/mirror=true if not configRegistry.is_true('repository/mirror', False): print( 'Error: Mirroring for the local repository is disabled. Set the Univention Configuration Registry variable repository/mirror to yes.' ) sys.exit(1) # create mirror_base and symbolic link "univention-repository" if missing destdir = os.path.join( configRegistry.get('repository/mirror/basepath', '/var/lib/univention-repository'), 'mirror') makedirs(destdir) try: os.symlink('.', os.path.join(destdir, 'univention-repository')) except EnvironmentError as e: if e.errno != errno.EEXIST: raise if options.sync: # only update packages of current repositories mirror.run() elif options.errata_only: # trigger update to find new errata repositories handler_commit(['/etc/apt/mirror.list']) mirror.run() elif options.update_to: # trigger update to explicitly mirror until given versions handler_set(['repository/mirror/version/end=%s' % options.update_to]) mirror = UniventionMirror() mirror.run() else: # mirror all future versions handler_commit(['/etc/apt/mirror.list']) nextupdate = mirror.release_update_available() mirror_run = False while nextupdate: handler_set(['repository/mirror/version/end=%s' % nextupdate]) # UCR variable repository/mirror/version/end has change - reinit Mirror object mirror = UniventionMirror() mirror.run() mirror_run = True nextupdate = mirror.release_update_available(nextupdate) if not mirror_run: # sync only mirror.run()
def prepare(options: Namespace) -> None: """ Set local/repository and create directory structure """ if configRegistry.is_false('local/repository', True): handler_set(['local/repository=yes']) configRegistry.load() if configRegistry.is_false('repository/mirror', True): handler_set(['repository/mirror=yes']) configRegistry.load() makedirs(join(options.base, "mirror", "dists"), exist_ok=True) makedirs(join(options.base, "mirror", "pool", "main"), exist_ok=True) makedirs(join(options.base, "skel"), exist_ok=True) makedirs(join(options.base, "var"), exist_ok=True)
def request_new_license(self, email): license = dump_license() if license is None: raise UMC_CommandError(_('Cannot parse License from LDAP')) data = {} data['email'] = email data['licence'] = license data = urllib.urlencode(data) url = 'https://license.univention.de/keyid/conversion/submit' request = urllib2.Request(url, data=data, headers={'User-agent': 'UMC/AppCenter'}) self._request_license(request) # creating a new ucr variable to prevent duplicated registration (Bug #35711) handler_set(['ucs/web/license/requested=true']) return True
def put(self, request): for _var in request.options: var = _var['object'] value = var['value'] or '' key = var['key'] if self.is_readonly(key): raise UMC_Error(_('The UCR variable %s is read-only and can not be changed!') % (key,)) arg = ['%s=%s' % (key.encode(), value.encode())] handler_set(arg) # handle descriptions, type, and categories if 'descriptions' in var or 'type' in var or 'categories' in var: self.__create_variable_info(var) self.finished(request.id, True)
def handler(configRegistry, changes): groups = configRegistry.get('dansguardian/groups', 'defaultgroup').split(';') for i in range(len(groups)): if groups[i] == '': continue ucr.handler_set([ 'dansguardian/current/groupno=%d' % (i + 1), 'dansguardian/current/group=%s' % groups[i] ]) configRegistry.load() # primary filter group configuration file src = os.path.join(TEMPLATE_PATH, 'dansguardianfX.conf') src_fd = open(src) conf = os.path.join(CONFIG_PATH, 'dansguardianf%d.conf' % (i + 1)) content = ucr.filter(src_fd.read(), configRegistry, srcfiles=[src]) src_fd.close() fd = open(conf, 'w') fd.write(content) fd.close() ignore_templates_for_groups = ['bannediplist', 'exceptioniplist'] # several lists for filter groups for entry in os.listdir(os.path.join(TEMPLATE_PATH, 'lists')): if entry not in ignore_templates_for_groups: abs_filename = os.path.join(TEMPLATE_PATH, 'lists', entry) if os.path.isfile(abs_filename): template = open(abs_filename) conf = os.path.join(CONFIG_PATH, 'lists', '%s-%s' % (groups[i], entry)) content = ucr.filter(template.read(), configRegistry, srcfiles=[abs_filename]) template.close() fd = open(conf, 'w') fd.write(content) fd.close() files_written.append(conf) # remove old filter lists for f in glob.iglob(os.path.join(CONFIG_PATH, 'lists', '*-*list')): if f not in files_written and os.path.isfile(f): os.unlink(f) ucr.handler_unset( ['dansguardian/current/groupno', 'dansguardian/current/group'])
def state(self): options = self.azure_response if not options: return progress(message=_('Waiting for authorization to be completed.'), waiting=True) if options['id_token']: try: AzureAuth.parse_id_token(options['id_token'], self.adconnection_alias) AzureAuth.store_tokens(adconnection_alias=self.adconnection_alias, consent_given=True) aa = AzureAuth("office365", self.adconnection_alias) aa.write_saml_setup_script(self.adconnection_alias) aa.set_ucs_overview_link() aa.retrieve_access_token() # not really necessary, but it'll make sure everything worked except AzureError as exc: self.init() raise UMC_Error(str(exc)) options['id_token'] = None if self.adconnection_alias: ucrv_set = '{}{}={}'.format( adconnection_alias_ucrv, self.adconnection_alias, AzureAuth.load_azure_ids(self.adconnection_alias)['adconnection_id'] ) MODULE.process('Setting UCR {}...'.format(ucrv_set)) handler_set([ucrv_set]) return progress(message=_('Successfully authorized. Starting synchronization.')) elif options['error']: self.init() raise UMC_Error(_('Microsoft reported an error condition during authorization. It might help to reauthorize. Error message: {error}: {error_description}').format(**options)) elif AzureAuth.is_initialized(self.adconnection_alias): self.init() try: ah = AzureHandler(ucr, "wizard", self.adconnection_alias) users = ah.list_users() MODULE.process('Retrieved list of users: %r' % users) #except TokenError as exc: # return except AzureError as exc: raise UMC_Error(str(exc)) try: subprocess.call(["systemctl", "restart", "univention-directory-listener.service"]) except (EnvironmentError,): pass return progress(message=_('Successfully initialized'), finished=True) return progress(message=_('Not yet initialized.'))
def handler(dn, new, old): global __changed_trusted_sp listener.setuid(0) try: try: fqdn = '%s.%s' % (new['cn'][0], new['associatedDomain'][0]) except (KeyError, IndexError): return if 'Univention Management Console' in new.get('univentionService', []): handler_set(['umc/saml/trusted/sp/%s=%s' % (fqdn, fqdn)]) __changed_trusted_sp = True elif 'Univention Management Console' in old.get( 'univentionService', []): handler_unset(['umc/saml/trusted/sp/%s' % (fqdn, )]) __changed_trusted_sp = True finally: listener.unsetuid()
def __enter__(self): # type: () -> UMCSeleniumTest self.restart_umc() self._ucr.__enter__() if self.selenium_grid: self.driver = webdriver.Remote( command_executor=os.environ.get( 'SELENIUM_HUB', 'http://jenkins.knut.univention.de:4444/wd/hub'), desired_capabilities={'browserName': self.browser}) else: if self.browser == 'chrome': chrome_options = webdriver.ChromeOptions() chrome_options.add_argument( '--no-sandbox' ) # chrome complains about being executed as root chrome_options.add_argument('ignore-certificate-errors') self.driver = webdriver.Chrome(chrome_options=chrome_options) else: self.driver = webdriver.Firefox() self.ldap_base = self._ucr.get('ldap/base') if self.suppress_notifications: handler_set([ 'umc/web/hooks/suppress_notifications=suppress_notifications' ]) self.account = utils.UCSTestDomainAdminCredentials() self.umcLoginUsername = self.account.username self.umcLoginPassword = self.account.bindpw if not os.path.exists(self.screenshot_path): os.makedirs(self.screenshot_path) self.driver.get(self.base_url + 'univention/login/?lang=%s' % (self.language, )) # FIXME: Workaround for Bug #44718. try: self.driver.execute_script( 'document.cookie = "UMCLang=%s; path=/univention/"' % (self.language, )) except selenium_exceptions.WebDriverException as exc: logger.warn('Setting language cookie failed: %s' % (exc, )) self.set_viewport_size(1200, 800) return self
def handler(dn, new, old): """Called on each change.""" ucr = ConfigRegistry() ucr.load() value = ucr.get('uvmm/managers', '') debug.debug(debug.LISTENER, debug.ALL, "old hosts: %s" % value) tls_allowed_dn_list = value.split() old_host = None if old and service_names & set(old.get('univentionService', [])): try: domain = old['associatedDomain'][0] except KeyError: domain = ucr.get('domainname') old_host = "%s.%s" % (old['cn'][0], domain) if old_host in tls_allowed_dn_list: debug.debug(debug.LISTENER, debug.INFO, "removing host %s" % (old_host, )) tls_allowed_dn_list.remove(old_host) new_host = None if new and service_names & set(new.get('univentionService', [])): try: domain = new['associatedDomain'][0] except KeyError: domain = ucr.get('domainname') new_host = "%s.%s" % (new['cn'][0], domain) debug.debug(debug.LISTENER, debug.INFO, "+uvmm %s" % (new_host, )) if new_host not in tls_allowed_dn_list: debug.debug(debug.LISTENER, debug.INFO, "adding host %s" % (new_host, )) tls_allowed_dn_list.append(new_host) if old_host != new_host: value = ' '.join(tls_allowed_dn_list) debug.debug(debug.LISTENER, debug.ALL, "new hosts: %s" % value) key_value = 'uvmm/managers=%s' % (value, ) listener.setuid(0) try: handler_set([key_value]) global need_restart need_restart = True finally: listener.unsetuid()
def save(self): config_registry = ucr.ConfigRegistry() config_registry.load() org_dict = {} for (key, value, ) in config_registry.items(): if REGEX_RULE.match(key): org_dict[key] = value new_dict = {} for rule in self.rules.values(): if rule: new_dict = dict(new_dict.items() + rule.dict.items()) diff = DictDiffer(new_dict, org_dict) ucr.handler_unset(diff.removed()) changed = [] for key in diff.changed().union(diff.added()): changed.append(u'%s=%s' % (key, new_dict[key])) ucr.handler_set(changed)
def handler(dn, new, old): """Called on each change.""" ucr = ConfigRegistry() ucr.load() value = ucr.get('uvmm/managers','') debug.debug(debug.LISTENER, debug.ALL, "old hosts: %s" % value) tls_allowed_dn_list = value.split() old_host = None if old and service_names & set(old.get('univentionService', [])): try: domain = old['associatedDomain'][0] except KeyError: domain = ucr.get('domainname') old_host = "%s.%s" % (old['cn'][0], domain) if old_host in tls_allowed_dn_list: debug.debug(debug.LISTENER, debug.INFO, "removing host %s" % (old_host,)) tls_allowed_dn_list.remove(old_host) new_host = None if new and service_names & set(new.get('univentionService', [])): try: domain = new['associatedDomain'][0] except KeyError: domain = ucr.get('domainname') new_host = "%s.%s" % (new['cn'][0], domain) debug.debug(debug.LISTENER, debug.INFO, "+uvmm %s" % (new_host,)) if new_host not in tls_allowed_dn_list: debug.debug(debug.LISTENER, debug.INFO, "adding host %s" % (new_host,)) tls_allowed_dn_list.append(new_host) if old_host != new_host: value = ' '.join(tls_allowed_dn_list) debug.debug(debug.LISTENER, debug.ALL, "new hosts: %s" % value) key_value = 'uvmm/managers=%s' % (value,) listener.setuid(0) try: handler_set([key_value]) global need_restart need_restart = True finally: listener.unsetuid()
} univention_openvpn_common.write_rc(3, config.format(**context), fn_serverconf) portold = old.get('univentionOpenvpnPort', [None])[0] portnew = new.get('univentionOpenvpnPort', [None])[0] if portold is not portnew: listener.setuid(0) #ucr = ConfigRegistry() #ucr.load() if portold: ucr.handler_unset(['security/packetfilter/package/univention-openvpn-server/udp/'+portold+'/all']) if portnew and 'univentionOpenvpnActive' in new: ucr.handler_set(['security/packetfilter/package/univention-openvpn-server/udp/'+portnew+'/all=ACCEPT']) listener.unsetuid() ccd = '/etc/openvpn/ccd-' + portnew + '/' fn_ips = '/etc/openvpn/ips-' + portnew fn_ipsv6 = '/etc/openvpn/ipsv6-' + portnew # write new server config flist = univention_openvpn_common.load_rc(3, fn_serverconf) flist = [x for x in flist if not re.search("port", x) and not re.search('push "redirect-gateway', x) and not re.search("duplicate-cn", x) and not re.search("server", x) and not re.search("server-ipv6", x) and not re.search("client-config-dir", x) and not re.search("proto", x) and not re.search("plugin", x)] flist.append("port %s\n" % portnew) network = new.get('univentionOpenvpnNet', [None])[0]