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 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 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 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( 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 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(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 __exit__(self, *args): # Terminating Http server self.server.terminate() self.server.join(5) print('Http server is terminated...\n%r' % self.server.is_alive()) handler_unset(['hosts/static/127.0.100.101']) shutil.rmtree(self.cert_basedir)
def remove(self, request): variables = [x for x in [x.get('object') for x in request.options] if x is not None] for var in variables: if self.is_readonly(var): raise UMC_Error(_('The UCR variable %s is read-only and can not be removed!') % (var,)) handler_unset(variables) self.finished(request.id, True)
def remove(self, request): variables = filter(lambda x: x is not None, map(lambda x: x.get('object'), request.options)) for var in variables: if self.is_readonly(var): raise UMC_Error( _('The UCR variable %s is read-only and can not be removed!' ) % (var, )) handler_unset(variables) self.finished(request.id, True)
def remove(self, request): variables = filter(lambda x: x is not None, map(lambda x: x.get('object'), request.options)) for var in variables: if self.is_readonly(var): message = _( 'The UCR variable %s is read-only and can not be removed!' ) % var self.finished(request.id, False, message) return ucr.handler_unset(variables) self.finished(request.id, True)
def remove_adconnection(self, adconnection_alias): aliases = self.get_adconnection_aliases() # Checks if adconnection_alias not in aliases: logger.error('Azure AD connection alias %s is not listed in UCR %s.', adconnection_alias, adconnection_alias_ucrv) return None target_path = os.path.join(ADCONNECTION_CONF_BASEPATH, adconnection_alias) if not os.path.exists(target_path): logger.info('Configuration files for the Azure AD connection in %s do not exist. Removing Azure AD connection anyway...', target_path) UDMHelper.remove_udm_adconnection(adconnection_alias) shutil.rmtree(target_path) ucrv_unset = '%s%s' % (adconnection_alias_ucrv, adconnection_alias) handler_unset([ucrv_unset]) self.listener_restart()
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 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 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 umc_service_active = 'Univention Management Console' in new.get('univentionService', []) umc_service_was_active = 'Univention Management Console' in old.get('univentionService', []) domain_added = 'associatedDomain' in new and 'associatedDomain' not in old and umc_service_active if umc_service_active and (domain_added or not umc_service_was_active): handler_set(['umc/saml/trusted/sp/%s=%s' % (fqdn, fqdn)]) __changed_trusted_sp = True elif umc_service_was_active and not umc_service_active: handler_unset(['umc/saml/trusted/sp/%s' % (fqdn,)]) __changed_trusted_sp = 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 rename_adconnection(self, old_adconnection_alias, new_adconnection_alias): aliases = self.get_adconnection_aliases() if old_adconnection_alias not in aliases: logger.error('Azure AD connection alias %s is not listed in UCR %s.', old_adconnection_alias, adconnection_alias_ucrv) return None if new_adconnection_alias in aliases: logger.error('Azure AD connection alias %s is already configured in UCR %s, cannot rename Azure AD connection %s.', new_adconnection_alias, adconnection_alias_ucrv, old_adconnection_alias) return None new_adconnection_path = os.path.join(ADCONNECTION_CONF_BASEPATH, new_adconnection_alias) if os.path.exists(new_adconnection_path): logger.error('The path for the target Azure AD connection name %s already exists, but no UCR configuration for the Azure AD connection was found.', new_adconnection_path) return None old_adconnection_path = os.path.join(ADCONNECTION_CONF_BASEPATH, old_adconnection_alias) if not os.path.exists(old_adconnection_path): logger.error('The path for the old Azure AD connection %s does not exist.', old_adconnection_path) return None shutil.move(old_adconnection_path, new_adconnection_path) ucrv_set = '{}={}'.format('%s%s' % (adconnection_alias_ucrv, new_adconnection_alias), ucr.get('%s%s' % (adconnection_alias_ucrv, old_adconnection_alias))) handler_set([ucrv_set]) ucrv_unset = '%s%s' % (adconnection_alias_ucrv, old_adconnection_alias) handler_unset([ucrv_unset]) self.listener_restart()
def _settings_set(self, printMode, internetRule, shareMode, period=None, customRule=None): """Defines settings for a room""" if not self._italc.school or not self._italc.room: raise UMC_Error('no room selected') # find AT jobs for the room and execute it to remove current settings jobs = atjobs.list(extended=True) for job in jobs: if job.comments.get(Instance.ATJOB_KEY, False) == self._italc.room: job.rm() subprocess.call(shlex.split(job.command)) roomInfo = _readRoomInfo(self._italc.roomDN) in_exam_mode = roomInfo.get('exam') # for the exam mode, remove current settings before setting new ones if in_exam_mode and roomInfo.get('cmd'): MODULE.info('unsetting room settings for exam (%s): %s' % (roomInfo['exam'], roomInfo['cmd'])) try: subprocess.call(shlex.split(roomInfo['cmd'])) except (OSError, IOError): MODULE.warn( 'Failed to reinitialize current room settings: %s' % roomInfo['cmd']) _updateRoomInfo(self._italc.roomDN, cmd=None) # reset to defaults. No atjob is necessary. if internetRule == 'none' and shareMode == 'all' and printMode == 'default': self._ruleEndAt = None self.reset_smb_connections() self.reload_cups() return # collect new settings vset = {} vappend = {} vunset = [] vunset_now = [] vextract = [] hosts = self._italc.ipAddresses(students_only=True) # print mode if printMode in ('none', 'all'): vextract.append('samba/printmode/hosts/%s' % printMode) vappend[vextract[-1]] = hosts vextract.append('cups/printmode/hosts/%s' % printMode) vappend[vextract[-1]] = hosts vunset.append('samba/printmode/room/%s' % self._italc.room) vset[vunset[-1]] = printMode else: vunset_now.append('samba/printmode/room/%s' % self._italc.room) # share mode if shareMode == 'home': vunset.append('samba/sharemode/room/%s' % self._italc.room) vset[vunset[-1]] = shareMode vextract.append('samba/othershares/hosts/deny') vappend[vextract[-1]] = hosts vextract.append('samba/share/Marktplatz/hosts/deny') vappend[vextract[-1]] = hosts else: vunset_now.append('samba/sharemode/room/%s' % self._italc.room) # internet rule if internetRule != 'none': vextract.append('proxy/filter/room/%s/ip' % self._italc.room) vappend[vextract[-1]] = hosts if internetRule == 'custom': # remove old rules i = 1 while True: var = 'proxy/filter/setting-user/%s/domain/whitelisted/%d' % ( self._username, i) if var in ucr: vunset_now.append(var) i += 1 else: break vunset.append('proxy/filter/room/%s/rule' % self._italc.room) vset[vunset[-1]] = self._username vset['proxy/filter/setting-user/%s/filtertype' % self._username] = 'whitelist-block' i = 1 for domain in (customRule or '').split('\n'): MODULE.info('Setting whitelist entry for domain %s' % domain) if not domain: continue parsed = urlparse.urlsplit(domain) MODULE.info('Setting whitelist entry for domain %s' % str(parsed)) if parsed.netloc: vset[ 'proxy/filter/setting-user/%s/domain/whitelisted/%d' % (self._username, i)] = parsed.netloc i += 1 elif parsed.path: vset[ 'proxy/filter/setting-user/%s/domain/whitelisted/%d' % (self._username, i)] = parsed.path i += 1 else: vunset.append('proxy/filter/room/%s/rule' % self._italc.room) vset[vunset[-1]] = internetRule else: vunset_now.append('proxy/filter/room/%s/ip' % self._italc.room) vunset_now.append('proxy/filter/room/%s/rule' % self._italc.room) # write configuration # remove old values handler_unset(vunset_now) # append values ucr.load() MODULE.info('Merging UCR variables') for key, value in vappend.items(): if ucr.get(key): old = set(ucr[key].split(' ')) MODULE.info('Old value: %s' % old) else: old = set() MODULE.info('Old value empty') new = set(value) MODULE.info('New value: %s' % new) new = old.union(new) MODULE.info('Merged value of %s: %s' % (key, new)) if not new: MODULE.info('Unset variable %s' % key) vunset.append(key) else: vset[key] = ' '.join(new) # Workaround for bug 30450: # if samba/printmode/hosts/none is not set but samba/printmode/hosts/all then all other hosts # are unable to print on samba shares. Solution: set empty value for .../none if no host is on deny list. varname = 'samba/printmode/hosts/none' if varname not in vset: ucr.load() if not ucr.get(varname): vset[varname] = '""' else: # remove empty items ('""') in list vset[varname] = ' '.join( [x for x in vset[varname].split(' ') if x != '""']) if varname in vunset: vunset.remove(varname) # set values ucr_vars = sorted('%s=%s' % x for x in vset.items()) MODULE.info('Writing room rules: %s' % '\n'.join(ucr_vars)) handler_set(ucr_vars) # create at job to remove settings unset_vars = ['-r %s' % quote(x) for x in vunset] MODULE.info('Will remove: %s' % ' '.join(unset_vars)) extract_vars = ['-e %s' % quote(x) for x in vextract] MODULE.info('Will extract: %s' % ' '.join(extract_vars)) cmd = '/usr/share/ucs-school-umc-computerroom/ucs-school-deactivate-rules %s %s %s' % ( ' '.join(unset_vars), ' '.join(extract_vars), ' '.join( quote(x) for x in hosts)) MODULE.info('command for reinitialization is: %s' % (cmd, )) if in_exam_mode: # Command for the exam mode to be executed manually when changing the settings again... _updateRoomInfo(self._italc.roomDN, cmd=cmd) else: starttime = datetime.datetime.now() MODULE.info('Now: %s' % starttime) MODULE.info('Endtime: %s' % period) starttime = starttime.replace(hour=period.hour, minute=period.minute, second=0, microsecond=0) while starttime < datetime.datetime.now( ): # prevent problems due to intra-day limit starttime += datetime.timedelta(days=1) # AT job for the normal case MODULE.info('Remove settings at %s' % (starttime, )) atjobs.add(cmd, starttime, {Instance.ATJOB_KEY: self._italc.room}) self._ruleEndAt = starttime self.reset_smb_connections() self.reload_cups()
def run(opt: Namespace) -> int: os.putenv('PATH', '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin') os.environ['LC_ALL'] = 'C.UTF-8' os.environ['DEBIAN_FRONTEND'] = 'noninteractive' check_failed() remove_temp() pkgdb = None pkgdb_scope = None if opt.silent: # redirect stdout to /dev/null sys.stdout = open("/dev/null", "w") try: if opt.check: # Only probe for packages to add/remove return check(configRegistry, opt.dist_upgrade) if ldap_hostdn: logfile = open(LOGNAME, 'a') logfile.write('***** Starting univention-actualise at %s\n' % time.ctime()) getUpdate() # temporarily disable pkgdb pkgdb_scan = configRegistry.get('pkgdb/scan', getscope=True) if pkgdb_scan: # get value and UCR scope of variable pkgdb/scan pkgdb_scope, pkgdb = pkgdb_scan if pkgdb: # disable pkgdb in UCR scope FORCED handler_set(['pkgdb/scan=no'], {'force': True}) rem_packages = getPackageList(configRegistry, 'remove') for package in rem_packages: # check if the package exists with apt_lock(): res = subprocess.call(shlex.split(cmd_show) + [package], stdout=logfile, stderr=logfile) if res == 0: print("Removing packages: %s" % package) with apt_lock(): res = subprocess.call(shlex.split(cmd_config), stdout=logfile, stderr=logfile) if not res: res = subprocess.call(shlex.split(cmd_remove) + [package], stdout=logfile, stderr=logfile) else: print("The package %s doesn't exist." % package) res = 0 if res != 0: print("E: failed to remove %s" % package, file=sys.stderr) sys.exit(res) add_packages = getPackageList(configRegistry, 'add') for package in add_packages: with apt_lock(): res = subprocess.call(shlex.split(cmd_show) + [package], stdout=logfile, stderr=logfile) if res == 0: print("Installing packages: %s" % package) with apt_lock(): res = subprocess.call(shlex.split(cmd_config), stdout=logfile, stderr=logfile) if not res: res = subprocess.call(shlex.split(cmd_install) + [package], stdout=logfile, stderr=logfile) else: print("The package %s doesn't exist." % package) res = 0 if res != 0: print("E: failed to install %s" % package, file=sys.stderr) sys.exit(res) else: # ldap/hostdn is not set if configRegistry['server/role'] != 'basesystem': print("W: ldap/hostdn is not set - please run univention-join", file=sys.stderr) if opt.dist_upgrade: msg = "Dist-upgrading system" cmd = cmd_dist_upgrade else: msg = "Upgrading system" cmd = cmd_upgrade print(msg) # TODO: use mkstemp and close directly the file descriptor with apt_lock(): tee = Tee([LOGNAME], stdout=not opt.silent) res = tee.call(shlex.split(cmd_config)) if res != 0: print("E: failed to configure packets, see %s for details." % LOGNAME, file=sys.stderr) else: tee = Tee( [LOGNAME], stdout=not opt.silent, filter= '(^Get|^Unpacking|^Preparing|^Setting up|packages upgraded)') res = tee.call(cmd.split(' ')) if res != 0: print("E: failed to upgrade, see %s for details." % LOGNAME, file=sys.stderr) sys.exit(res) finally: if pkgdb: if pkgdb_scope == ConfigRegistry.FORCED: # old value was set in FORCED scope handler_set(['pkgdb/scan=%s' % pkgdb], {'force': True}) else: # old value was set in any other scope ==> remove value in FORCED scope handler_unset(['pkgdb/scan'], {'force': True}) if str(pkgdb).lower() in ("yes", "enable", "enabled", "true", "1"): subprocess.call(('/usr/sbin/univention-pkgdb-scan', ))
def disabled_cronjob(): """Disable cron to avoid race""" handler_set(['%s=%s' % (ucrv, "# disabled")]) yield handler_unset(['%s' % (ucrv, )])