def getBackupConnection(start_tls=2, decode_ignorelist=[], reconnect=True): ucr = ConfigRegistry() ucr.load() bindpw = open('/etc/ldap-backup.secret').read().rstrip('\n') port = int(ucr.get('ldap/master/port', '7389')) try: return access(host=ucr['ldap/master'], port=port, base=ucr['ldap/base'], binddn='cn=backup,' + ucr['ldap/base'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, reconnect=reconnect) except ldap.SERVER_DOWN: if not ucr['ldap/backup']: raise backup = ucr['ldap/backup'].split(' ')[0] return access(host=backup, port=port, base=ucr['ldap/base'], binddn='cn=backup,' + ucr['ldap/base'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, reconnect=reconnect)
def main(): """Retrive current Univention Directory Notifier transaction ID.""" configRegistry = ConfigRegistry() configRegistry.load() master = configRegistry.get('ldap/master') if not master: print >> sys.stderr, 'Error: ldap/master not set' sys.exit(1) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((master, 6669)) sock.send('Version: 2\nCapabilities: \n\n') sock.recv(100) sock.send('MSGID: 1\nGET_ID\n\n') notifier_result = sock.recv(100) if notifier_result: print "%s" % notifier_result.splitlines()[1] except socket.error, ex: print >> sys.stderr, 'Error: %s' % (ex,) sys.exit(1)
def main(): """Retrive current Univention Directory Notifier transaction ID.""" configRegistry = ConfigRegistry() configRegistry.load() master = configRegistry.get('ldap/master') if not master: print >> sys.stderr, 'Error: ldap/master not set' sys.exit(1) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((master, 6669)) sock.send('Version: 2\nCapabilities: \n\n') sock.recv(100) sock.send('MSGID: 1\nGET_ID\n\n') notifier_result = sock.recv(100) if notifier_result: print "%s" % notifier_result.splitlines()[1] except socket.error, ex: print >> sys.stderr, 'Error: %s' % (ex, ) sys.exit(1)
def fetch_schema_from_local_ldap(): ucr = ConfigRegistry() ucr.load() ldap_uri = 'ldap://%(hostname)s:%(domainname)s' % ucr return __fetch_schema_from_uri(ldap_uri)
def handler(dn, new, old, command): configRegistry = ConfigRegistry() configRegistry.load() interfaces = Interfaces(configRegistry) # dymanic module object filter current_fqdn = "%s.%s" % (configRegistry['hostname'], domainname) current_ip = str(interfaces.get_default_ip_address().ip) new_univentionShareHost = new.get('univentionShareHost', [None])[0] if new and not new_univentionShareHost in (current_fqdn, current_ip): new = {} ## new object is not for this host old_univentionShareHost = old.get('univentionShareHost', [None])[0] if old and not old_univentionShareHost in (current_fqdn, current_ip): old = {} ## old object is not for this host if not (new or old): return # create tmp dir tmpDir = os.path.dirname(tmpFile) listener.setuid(0) try: if not os.path.exists(tmpDir): os.makedirs(tmpDir) except Exception, e: univention.debug.debug( univention.debug.LISTENER, univention.debug.ERROR, "%s: could not create tmp dir %s (%s)" % (name, tmpDir, str(e))) return
def __init__(self, userdn=None, password=None, host='localhost', base=None, start_tls=2, access=None, format=None): self._cached = {} self._modules = {} self._policies = {} self._format = format self._bc = ConfigRegistry() self._bc.load() self.__reverse = {} if not base: self._base = self._bc['ldap/base'] else: self._base = base self._position = ua_ldap.position(self._base) if access: self._access = access else: self._access = ua_ldap.access(host=host, base=self._base, binddn=userdn, bindpw=password, start_tls=start_tls) ua_modules.update()
class UCSResync(object): def __init__(self): self.configRegistry = ConfigRegistry() self.configRegistry.load() self.lo = univention.uldap.getMachineConnection() def _get_listener_dir(self): return self.configRegistry.get('connector/s4/listener/dir', '/var/lib/univention-connector/s4') def _generate_filename(self): directory = self._get_listener_dir() return os.path.join(directory, "%f" % time.time()) def _dump_object_to_file(self, object_data): filename = self._generate_filename() with open(filename, 'wb+') as fd: os.chmod(filename, 0o600) p = pickle.Pickler(fd) p.dump(object_data) p.clear_memo() def _search_ldap_object_orig(self, ucs_dn): return self.lo.get(ucs_dn, attr=['*', '+'], required=True) def resync(self, ucs_dns=None, ldapfilter=None): treated_dns = [] for dn, new in self.search_ldap(ucs_dns, ldapfilter): object_data = (dn, new, {}, None) self._dump_object_to_file(object_data) treated_dns.append(dn) return treated_dns def search_ldap(self, ucs_dns=None, ldapfilter=None): attr = ('*', '+') if ucs_dns: if not ldapfilter: ldapfilter = '(objectClass=*)' ldap_result = [] missing_dns = [] for targetdn in ucs_dns: try: result = self.lo.search(base=targetdn, scope='base', filter=ldapfilter, attr=attr) ldap_result.extend(result) except ldap.NO_SUCH_OBJECT: missing_dns.append(targetdn) if missing_dns: raise ldap.NO_SUCH_OBJECT(1, 'No object: %s' % (missing_dns, ), [r[0] for r in ldap_result]) else: ldap_result = self.lo.search(filter=ldapfilter, attr=attr) return ldap_result
def getAdminConnection( start_tls=2, decode_ignorelist=[], reconnect=True): # type: (int, List[str], bool) -> access """ Open a LDAP connection to the Master LDAP server using the admin credentials. :param int start_tls: Negotiate TLS with server. If `2` is given, the command will require the operation to be successful. :param decode_ignorelist: List of LDAP attribute names which shall be handled as binary attributes. :type decode_ignorelist: list[str] :param bool reconnect: Automatically reconect if the connection fails. :return: A LDAP access object. :rtype: univention.uldap.access """ ucr = ConfigRegistry() ucr.load() bindpw = open('/etc/ldap.secret').read().rstrip('\n') port = int(ucr.get('ldap/master/port', '7389')) return access(host=ucr['ldap/master'], port=port, base=ucr['ldap/base'], binddn='cn=admin,' + ucr['ldap/base'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, reconnect=reconnect)
def __init__(self, listener, name, attrs, ldap_cred, dn, adconnection_alias=None): """ :param listener: listener object or None :param name: str, prepend to log messages :param attrs: {"listener": [attributes, listener, listens, on], ... } :param ldap_cred: {ldapserver: FQDN, binddn: cn=admin,$ldap_base, basedn: $ldap_base, bindpw: s3cr3t} or None :param dn of LDAP object to work on """ self.listener = listener self.attrs = attrs self.udm = UDMHelper(ldap_cred, adconnection_alias) # self.ldap_cred = ldap_cred self.dn = dn self.adconnection_alias = adconnection_alias logger.debug('adconnection_alias=%r', adconnection_alias) if self.listener: self.ucr = self.listener.configRegistry else: # allow use of this class outside listener from univention.config_registry import ConfigRegistry self.ucr = ConfigRegistry() self.ucr.load() self.not_migrated_to_v3 = self.ucr.is_false( 'office365/migrate/adconnectionalias') self.ah = AzureHandler(self.ucr, name, self.adconnection_alias)
def connect(options): print(time.ctime()) ucr = ConfigRegistry() ucr.load() poll_sleep = int(ucr['%s/ad/poll/sleep' % options.configbasename]) ad_init = None while not ad_init: try: ad = univention.connector.ad.ad.main(ucr, options.configbasename, logfilename=options.log_file, debug_level=options.debug) ad.init_ldap_connections() ad.init_group_cache() ad_init = True except ldap.SERVER_DOWN: print("Warning: Can't initialize LDAP-Connections, wait...") sys.stdout.flush() time.sleep(poll_sleep) # log the active mapping with open('/var/log/univention/%s-ad-mapping.log' % options.configbasename, 'w+') as fd: print(repr(univention.connector.Mapping(ad.property)), file=fd) with ad as ad: _connect(ad, poll_sleep, ucr.get('%s/ad/retryrejected' % options.configbasename, 10))
def parse_args(): usage = '%prog [options] [master]' desc = sys.modules[__name__].__doc__ parser = OptionParser(usage=usage, description=desc) parser.add_option('-m', '--master', dest='master', help='LDAP Server address') parser.add_option('-s', '--shema', dest='cmd', action='store_const', const='GET_SCHEMA_ID', default='GET_ID', help='Fetch LDAP Schema ID') (options, args) = parser.parse_args() if not options.master: if args: try: options.master, = args except ValueError: parser.error('incorrect number of arguments') else: from univention.config_registry import ConfigRegistry configRegistry = ConfigRegistry() configRegistry.load() options.master = configRegistry.get('ldap/master') if not options.master: parser.error('ldap/master or --master not set') return options
def getBackupConnection(start_tls=2, decode_ignorelist=[]): ucr = ConfigRegistry() ucr.load() bindpw = open("/etc/ldap-backup.secret").read() if bindpw[-1] == "\n": bindpw = bindpw[0:-1] port = int(ucr.get("ldap/master/port", "7389")) try: lo = access( host=ucr["ldap/master"], port=port, base=ucr["ldap/base"], binddn="cn=backup," + ucr["ldap/base"], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, ) except ldap.SERVER_DOWN, e: if ucr["ldap/backup"]: backup = string.split(ucr["ldap/backup"], " ")[0] lo = access( host=backup, port=port, base=ucr["ldap/base"], binddn="cn=backup," + ucr["ldap/base"], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, ) else: raise ldap.SERVER_DOWN, e
def getBackupConnection(start_tls=2, decode_ignorelist=[]): ucr = ConfigRegistry() ucr.load() bindpw = open('/etc/ldap-backup.secret').read() if bindpw[-1] == '\n': bindpw = bindpw[0:-1] port = int(ucr.get('ldap/master/port', '7389')) try: lo = access(host=ucr['ldap/master'], port=port, base=ucr['ldap/base'], binddn='cn=backup,' + ucr['ldap/base'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist) except ldap.SERVER_DOWN, e: if ucr['ldap/backup']: backup = string.split(ucr['ldap/backup'], ' ')[0] lo = access(host=backup, port=port, base=ucr['ldap/base'], binddn='cn=backup,' + ucr['ldap/base'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist) else: raise ldap.SERVER_DOWN, e
def call_unjoin_script(unjoin_script_name): print('call_unjoin_script(%r)' % (unjoin_script_name,)) ucr = ConfigRegistry() ucr.load() join_script = '/usr/lib/univention-uninstall/%s' % unjoin_script_name return subprocess.call([join_script, '--binddn', ucr.get('tests/domainadmin/account'), '--bindpwdfile', ucr.get('tests/domainadmin/pwdfile')], shell=False)
def __init__(self): """Test Class constructor""" self.username = None self.password = None self.hostname = None self.client = None self.ucr = ConfigRegistry() self.ucr.load() self.ldap_base = self.ucr.get('ldap/base')
def call_join_script(name, fail_on_error=True): # type: (str, bool) -> int """ Calls the given join script (e.g. name='66foobar.inst'). If fail is true, then the function fail() is called if the exitcode is not zero. """ ucr = ConfigRegistry() ucr.load() return call_cmd(['/usr/lib/univention-install/%s' % name, '--binddn', ucr.get('tests/domainadmin/account'), '--bindpwdfile', ucr.get('tests/domainadmin/pwdfile')], fail_on_error=fail_on_error)
def __init__(self, host='localhost', port=None, base='', binddn='', bindpw='', start_tls=2, ca_certfile=None, decode_ignorelist=[], use_ldaps=False, uri=None, follow_referral=False): """start_tls = 0 (no); 1 (try); 2 (must)""" ucr = None self.host = host self.base = base self.binddn = binddn self.bindpw = bindpw self.start_tls = start_tls self.ca_certfile = ca_certfile self.port = port if not self.port: ## if no explicit port is given ucr = ConfigRegistry() ucr.load() self.port = int(ucr.get('ldap/server/port', 7389)) ## take UCR value if use_ldaps and self.port == "7389": ## adjust the standard port for ssl self.port = "7636" # http://www.openldap.org/faq/data/cache/605.html self.protocol = 'ldap' if use_ldaps: self.protocol = 'ldaps' self.uri = 'ldaps://%s:%s" % (self.host, self.port)' elif uri: self.uri = uri else: self.uri = "ldap://%s:%s" % (self.host, self.port) if not decode_ignorelist or decode_ignorelist == []: if not ucr: ucr = ConfigRegistry() ucr.load() self.decode_ignorelist = ucr.get( 'ldap/binaryattributes', 'krb5Key,userCertificate;binary').split(',') else: self.decode_ignorelist = decode_ignorelist # python-ldap does not cache the credentials, so we override the # referral handling if follow_referral is set to true # https://forge.univention.org/bugzilla/show_bug.cgi?id=9139 self.follow_referral = follow_referral self.__open(ca_certfile)
def load(self): # type: () -> None """ call load() of superclass and save original registry values """ ConfigRegistry.load(self) if self.__original_registry is None: self.__original_registry = { regtype: copy.deepcopy(dict(reg)) for (regtype, reg) in self._walk() }
def __init__(self, name, version, container_version=None, app_directory_suffix=None, package_name=None, build_package=True, call_join_scripts=True): self.app_name = name self.app_version = version self.call_join_scripts = call_join_scripts if not app_directory_suffix: self.app_directory_suffix = random_version() else: self.app_directory_suffix = app_directory_suffix self.app_directory = '%s_%s' % (self.app_name, self.app_directory_suffix) if package_name: self.package_name = package_name else: self.package_name = get_app_name() self.package_version = '%s.%s' % (version, get_app_version()) self.ucr = ConfigRegistry() self.ucr.load() if build_package: self.package = DebianPackage(name=self.package_name, version=self.package_version) self.package.build() else: self.package = None self.ini = {} self.ini['ID'] = self.app_name self.ini['Code'] = self.app_name[0:2] self.ini['Name'] = self.app_name self.ini['Version'] = self.app_version self.ini['NotifyVendor'] = False self.ini['Categories'] = 'System services' self.ini['Logo'] = '%s.svg' % self.app_name if self.package: self.ini['DefaultPackages'] = self.package_name self.ini['ServerRole'] = 'domaincontroller_master,domaincontroller_backup,domaincontroller_slave,memberserver' self.scripts = {} if not container_version: self.ucs_version = self.ucr.get('version/version') else: self.ucs_version = container_version self.ini['SupportedUCSVersions'] = '%s-0,%s-0' % (container_version, self.ucr.get('version/version')) self.installed = False self.admin_user = self.ucr.get('tests/domainadmin/account').split(',')[0][len('uid='):] self.admin_pwdfile = self.ucr.get('tests/domainadmin/pwdfile') print repr(self)
def __init__(self): self.configRegistry = ConfigRegistry() self.configRegistry.load() lp = LoadParm() creds = Credentials() creds.guess(lp) self.samdb = SamDB(url='/var/lib/samba/private/sam.ldb', session_info=system_session(), credentials=creds, lp=lp)
def config(): """Test wide Configuration aka UCR Used to get some defaults if not environment variables are given. But if UCR is not avaiable, returns an empty dict... """ try: from univention.config_registry import ConfigRegistry ucr = ConfigRegistry() ucr.load() return dict(ucr) except ImportError: return {}
def postrun(): ucr = ConfigRegistry() ucr.load() if ucr.is_true("dhcpd/autostart", False): if ucr.is_true('dhcpd/restart/listener', False): ud.debug(ud.LISTENER, ud.INFO, 'DHCP: Restarting server') try: listener.run('/etc/init.d/univention-dhcp', ['univention-dhcp', 'restart'], uid=0) except Exception, e: ud.debug(ud.ADMIN, ud.WARN, 'The restart of the DHCP server failed: %s' % str(e)) else: ud.debug(ud.ADMIN, ud.INFO, 'DHCP: the automatic restart of the dhcp server by the listener is disabled. Set dhcpd/restart/listener to true to enable this option.')
def get_query_limit(): ucr = ConfigRegistry() ucr.load() limit = ucr.get('admin/diary/query/limit', '') default_limit = 1000 try: limit = int(limit) except ValueError: limit = default_limit else: if limit < 0: limit = default_limit return limit
def create_udm_adconnection(cls, alias, description=""): ucr = ConfigRegistry() ucr.load() lo, po, mod = cls.init_udm("office365/ad-connection") po = univention.admin.uldap.position( "cn=ad-connections,cn=office365,%s" % ucr["ldap/base"]) adconn = mod.object(co=None, lo=lo, position=po) adconn.open() adconn['name'] = alias adconn['description'] = description dn = adconn.create() return dn
def getAdminConnection(start_tls=2, decode_ignorelist=[], reconnect=True): ucr = ConfigRegistry() ucr.load() bindpw = open('/etc/ldap.secret').read().rstrip('\n') port = int(ucr.get('ldap/master/port', '7389')) return access(host=ucr['ldap/master'], port=port, base=ucr['ldap/base'], binddn='cn=admin,' + ucr['ldap/base'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, reconnect=reconnect)
def __init__(self): """ Test class constructor """ self.UCR = ConfigRegistry() self.client = None self.admin_username = '' self.admin_password = '' self.ldap_master = '' self.gpo_reference = ''
class TransactionalUcr(object): def __init__(self): self.ucr = ConfigRegistry() self.ucr.load() self.changes = {} def set(self, key, value): ''' Set the value of key of UCR. Does not save immediately. commit() is called at the end of inner_run(). If you need to commit changes immediately, you can call commit() at any time. ''' orig_val = self.ucr.get(key) if orig_val == value: # in case it was overwritten previously self.changes.pop(key, None) else: self.changes[key] = value def commit(self): ''' Saves UCR variables previously set by set_ucr_var(). Also commits changes (if done any). Is called automatically *if inner_run() did not raise an exception*. You can call it manually if you need to do it (e.g. in down()). ''' if self.changes: ucr_update(self.ucr, self.changes) # reset (in case it is called multiple) times in a script self.changes.clear() def get(self, key, search_in_changes=True): ''' Retrieve the value of key from ucr. If search_in_changes, it first looks in (not yet committed) values. ''' if search_in_changes: try: return self.changes[key] except KeyError: pass return self.ucr.get(key) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: self.commit()
def getMachineConnection(start_tls=2, decode_ignorelist=[], ldap_master=True, secret_file="/etc/machine.secret", reconnect=True): ucr = ConfigRegistry() ucr.load() bindpw = open(secret_file).read().rstrip('\n') if ldap_master: # Connect to DC Master port = int(ucr.get('ldap/master/port', '7389')) return access(host=ucr['ldap/master'], port=port, base=ucr['ldap/base'], binddn=ucr['ldap/hostdn'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, reconnect=reconnect) else: # Connect to ldap/server/name port = int(ucr.get('ldap/server/port', '7389')) try: return access(host=ucr['ldap/server/name'], port=port, base=ucr['ldap/base'], binddn=ucr['ldap/hostdn'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, reconnect=reconnect) except ldap.SERVER_DOWN as exc: # ldap/server/name is down, try next server if not ucr.get('ldap/server/addition'): raise servers = ucr.get('ldap/server/addition', '') for server in servers.split(): try: return access(host=server, port=port, base=ucr['ldap/base'], binddn=ucr['ldap/hostdn'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, reconnect=reconnect) except ldap.SERVER_DOWN: pass raise exc
def getAdminConnection(start_tls=2, decode_ignorelist=[]): ucr = ConfigRegistry() ucr.load() bindpw = open('/etc/ldap.secret').read() if bindpw[-1] == '\n': bindpw = bindpw[0:-1] port = int(ucr.get('ldap/master/port', '7389')) lo = access(host=ucr['ldap/master'], port=port, base=ucr['ldap/base'], binddn='cn=admin,' + ucr['ldap/base'], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist) return lo
def write_cron_job(configRegistry: ConfigRegistry, cron: str, updateto: str, reboot: str, try_release_update: bool) -> None: with open(CRON_D, 'w') as file: file.write('# cron job for update\n') file.write('PATH=/sbin:/usr/sbin:/usr/bin:/bin\n') if cron == '* * * * * ': return cmd = ['/usr/sbin/jitter 600 true'] if try_release_update: cmd.append( '/usr/share/univention-updater/univention-updater %s %s --silent --noninteractive' % ( 'local' if configRegistry.is_true('local/repository') else 'net', '--updateto=%s' % (quote(updateto), ) if updateto else '', )) cmd.append( '/usr/share/univention-updater/univention-actualise --dist-upgrade --silent' ) if reboot: cmd.append( 'if [ -f /run/univention-updater-reboot ];then ' 'at -f /var/lib/univention-updater/reboot.at -- %s 2>/dev/null;' 'rm -f /run/univention-updater-reboot;' 'fi' % (quote(reboot), )) print('%s\troot\t%s' % (cron, ';'.join(cmd)), file=file)
def _get_ldap_connection(cls, ldap_cred=None): if ldap_cred and not cls.ldap_cred: cls.ldap_cred = ldap_cred if not cls.lo or not cls.po: if cls.ldap_cred: cls.lo = univention.admin.uldap.access( host=cls.ldap_cred["ldapserver"], base=cls.ldap_cred["basedn"], binddn=cls.ldap_cred["binddn"], bindpw=cls.ldap_cred["bindpw"]) ucr = ConfigRegistry() ucr.load() cls.po = univention.admin.uldap.position(ucr["ldap/base"]) else: cls.lo, cls.po = univention.admin.uldap.getAdminConnection() return cls.lo, cls.po
def set_ucs_overview_link(cls): from univention.config_registry import ConfigRegistry ucr = ConfigRegistry() ucr.load() sp_query_string = "?spentityid=urn:federation:MicrosoftOnline" sp_link = "https://{}/simplesamlphp/saml2/idp/SSOService.php{}".format(ucr["ucs/server/sso/fqdn"], sp_query_string) ucr_update(ucr, { "ucs/web/overview/entries/service/office365/description": "Single Sign-On login for Microsoft Office 365", "ucs/web/overview/entries/service/office365/label": "Office 365 Login", "ucs/web/overview/entries/service/office365/link": sp_link, "ucs/web/overview/entries/service/office365/description/de": "Single-Sign-On Link für Microsoft Office 365", "ucs/web/overview/entries/service/office365/label/de": "Office 365 Login", "ucs/web/overview/entries/service/office365/priority": "50", "ucs/web/overview/entries/service/office365/icon": "/office365.png" })
def __fetch_schema_from_uri(ldap_uri): ucr = ConfigRegistry() ucr.load() retry = ucr.get('ldap/client/retry/count', 15) attempts = int(retry) + 1 i = 0 while i < attempts: try: return ldap.schema.subentry.urlfetch(ldap_uri) except ldap.SERVER_DOWN: if i >= (attempts - 1): raise time.sleep(1) i += 1
def __init__( self, host="localhost", port=None, base="", binddn="", bindpw="", start_tls=2, ca_certfile=None, decode_ignorelist=[], use_ldaps=False, uri=None, follow_referral=False, ): """start_tls = 0 (no); 1 (try); 2 (must)""" ucr = None self.host = host self.base = base self.binddn = binddn self.bindpw = bindpw self.start_tls = start_tls self.ca_certfile = ca_certfile self.port = port if not self.port: ## if no explicit port is given ucr = ConfigRegistry() ucr.load() self.port = int(ucr.get("ldap/server/port", 7389)) ## take UCR value if use_ldaps and self.port == "7389": ## adjust the standard port for ssl self.port = "7636" # http://www.openldap.org/faq/data/cache/605.html self.protocol = "ldap" if use_ldaps: self.protocol = "ldaps" self.uri = 'ldaps://%s:%s" % (self.host, self.port)' elif uri: self.uri = uri else: self.uri = "ldap://%s:%s" % (self.host, self.port) if not decode_ignorelist or decode_ignorelist == []: if not ucr: ucr = ConfigRegistry() ucr.load() self.decode_ignorelist = ucr.get("ldap/binaryattributes", "krb5Key,userCertificate;binary").split(",") else: self.decode_ignorelist = decode_ignorelist # python-ldap does not cache the credentials, so we override the # referral handling if follow_referral is set to true # https://forge.univention.org/bugzilla/show_bug.cgi?id=9139 self.follow_referral = follow_referral self.__open(ca_certfile)
def getAdminConnection(start_tls=2, decode_ignorelist=[]): ucr = ConfigRegistry() ucr.load() bindpw = open("/etc/ldap.secret").read() if bindpw[-1] == "\n": bindpw = bindpw[0:-1] port = int(ucr.get("ldap/master/port", "7389")) lo = access( host=ucr["ldap/master"], port=port, base=ucr["ldap/base"], binddn="cn=admin," + ucr["ldap/base"], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, ) return lo
def getMachineConnection(start_tls=2, decode_ignorelist=[], ldap_master=True, secret_file="/etc/machine.secret"): ucr = ConfigRegistry() ucr.load() bindpw = open(secret_file).read() if bindpw[-1] == "\n": bindpw = bindpw[0:-1] if ldap_master: # Connect to DC Master port = int(ucr.get("ldap/master/port", "7389")) lo = access( host=ucr["ldap/master"], port=port, base=ucr["ldap/base"], binddn=ucr["ldap/hostdn"], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, ) else: # Connect to ldap/server/name port = int(ucr.get("ldap/server/port", "7389")) try: lo = access( host=ucr["ldap/server/name"], port=port, base=ucr["ldap/base"], binddn=ucr["ldap/hostdn"], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, ) except ldap.SERVER_DOWN, e: # ldap/server/name is down, try next server if not ucr.get("ldap/server/addition"): raise ldap.SERVER_DOWN, e for server in ucr.get("ldap/server/addition", []): try: lo = access( host=server, port=port, base=ucr["ldap/base"], binddn=ucr["ldap/hostdn"], bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, ) except ldap.SERVER_DOWN, e: pass else: return lo raise ldap.SERVER_DOWN, e
def _load_ucr(self): """Load Univention Config Registry informations.""" self.ucr = ConfigRegistry() self.ucr.load() self.role = self.ucr.get('server/role', '') TestEnvironment.logger.debug('Role=%r' % self.role) version = self.ucr.get('version/version').split('.', 1) major, minor = int(version[0]), int(version[1]) patchlevel = int(self.ucr.get('version/patchlevel')) if (major, minor) < (3, 0): securitylevel = int(self.ucr.get('version/security-patchlevel', 0)) self.ucs_version = UCSVersion((major, minor, patchlevel, securitylevel)) else: erratalevel = int(self.ucr.get('version/erratalevel', 0)) self.ucs_version = UCSVersion((major, minor, patchlevel, erratalevel)) TestEnvironment.logger.debug('Version=%r' % self.ucs_version)
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()
# /usr/share/common-licenses/AGPL-3; if not, see # <http://www.gnu.org/licenses/>. # This file is part of univention-lib and have to contain python2.4 valid code from univention.config_registry import ConfigRegistry from ConfigParser import ConfigParser import os import re import shlex import string import sys # defaults ucr = ConfigRegistry() # global hashes include = set() shares = {} globals = {} printers = {} ucr.load() class Restrictions( dict ): INVALID_USERS = 'invalid users' VALID_USERS = 'valid users' HOSTS_DENY = 'hosts deny' HOSTS_ALLOW = 'hosts allow'
class TestEnvironment(object): """Test environment for running test cases. Handels system data, requirements checks, test output. """ logger = logging.getLogger('test.env') def __init__(self, interactive=True, logfile=None): self.exposure = 'safe' self.interactive = interactive self._load_host() self._load_ucr() self._load_join() self._load_apt() if interactive: self.tags_required = None self.tags_prohibited = None else: self.tags_required = set() self.tags_prohibited = set(('SKIP', 'WIP')) self.log = open(logfile or os.path.devnull, 'a') def _load_host(self): """Load host system informations.""" (_sysname, nodename, _release, _version, machine) = os.uname() self.hostname = nodename self.architecture = machine def _load_ucr(self): """Load Univention Config Registry informations.""" self.ucr = ConfigRegistry() self.ucr.load() self.role = self.ucr.get('server/role', '') TestEnvironment.logger.debug('Role=%r' % self.role) version = self.ucr.get('version/version').split('.', 1) major, minor = int(version[0]), int(version[1]) patchlevel = int(self.ucr.get('version/patchlevel')) if (major, minor) < (3, 0): securitylevel = int(self.ucr.get('version/security-patchlevel', 0)) self.ucs_version = UCSVersion((major, minor, patchlevel, securitylevel)) else: erratalevel = int(self.ucr.get('version/erratalevel', 0)) self.ucs_version = UCSVersion((major, minor, patchlevel, erratalevel)) TestEnvironment.logger.debug('Version=%r' % self.ucs_version) def _load_join(self): """Load join status.""" devnull = open(os.path.devnull, 'w+') try: ret = call(('/usr/sbin/univention-check-join-status',), stdin=devnull, stdout=devnull, stderr=devnull) self.joined = ret == 0 finally: devnull.close() TestEnvironment.logger.debug('Join=%r' % self.joined) def _load_apt(self): """Load package informations.""" self.apt = apt.Cache() def dump(self, stream=sys.stdout): """Dump environment informations.""" print >> stream, 'hostname: %s' % (self.hostname,) print >> stream, 'architecture: %s' % (self.architecture,) print >> stream, 'version: %s' % (self.ucs_version,) print >> stream, 'role: %s' % (self.role,) print >> stream, 'joined: %s' % (self.joined,) print >> stream, 'tags_required: %s' % \ (' '.join(self.tags_required) or '-',) print >> stream, 'tags_prohibited: %s' % \ (' '.join(self.tags_prohibited) or '-',) def tag(self, require=set(), ignore=set(), prohibit=set()): """Update required, ignored, prohibited tags.""" if self.tags_required is not None: self.tags_required -= set(ignore) self.tags_required |= set(require) if self.tags_prohibited is not None: self.tags_prohibited -= set(ignore) self.tags_prohibited |= set(prohibit) TestEnvironment.logger.debug('tags_required=%r tags_prohibited=%r' % \ (self.tags_required, self.tags_prohibited)) def set_exposure(self, exposure): """Set maximum allowed exposure level.""" self.exposure = exposure
def handler(*args, **kw): log.info("kolab.handler(args(%d): %r, kw: %r)" % (len(args), args, kw)) auth = Auth() auth.connect() if len(args) == 4: # moddn dn = args[0] new = utils.normalize(args[1]) old = utils.normalize(args[2]) command = args[4] pass elif len(args) == 3: dn = args[0] new = utils.normalize(args[1]) old = utils.normalize(args[2]) if isinstance(old, dict) and len(old.keys()) > 0: # Two options: # - entry changed # - entry deleted log.info("user %r, old is dict" % (dn)) if isinstance(new, dict) and len(new.keys()) > 0: log.info("Modify entry %r" % (dn)) mailserver_attribute = conf.get('ldap', 'mailserver_attribute').lower() if mailserver_attribute == None: log.error("Mail server attribute is not set") return if old.has_key(mailserver_attribute): log.info("Modified entry %r has mail server attribute %s: %r" % (dn, mailserver_attribute, new[mailserver_attribute])) if not old[mailserver_attribute] == constants.fqdn: # Even though the new mailserver can be us, it is the # *current* mail server that needs to push for the XFER. log.info("The mail server for user %r is set, and it is not me (%r)" % (dn, old[mailserver_attribute])) return else: # If old has no mailserver attribute, but new does, we need to create # the user locally. if new.has_key(mailserver_attribute): if not new[mailserver_attribute] == constants.fqdn: log.info("The mail server for user %r is set (in new, not old), but it is not me (%r)" % (dn, new[mailserver_attribute])) return else: log.info("Entry %r does not have a mail server attribute." % (dn)) return auth._auth._synchronize_callback( change_type = 'modify', previous_dn = None, change_number = None, dn = dn, entry = new ) else: log.info("Delete entry %r" % (dn)) # See if the mailserver_attribute exists mailserver_attribute = conf.get('ldap', 'mailserver_attribute').lower() if mailserver_attribute == None: log.error("Mail server attribute is not set") # TODO: Perhaps, query for IMAP servers. If there is only one, # we know what to do. return if old.has_key(mailserver_attribute): log.info("Deleted entry %r has mail server attribute %s: %r" % (dn, mailserver_attribute, old[mailserver_attribute])) if not old[mailserver_attribute] == constants.fqdn: log.info("The mail server for user %r is set, and it is not me (%r)" % (dn, old[mailserver_attribute])) return else: log.info("Entry deletion notification for %r does not have a mail server attribute specified." % (dn)) cfg = ConfigRegistry() cfg.load() if cfg.is_true('mail/cyrus/mailbox/delete', True): auth._auth._synchronize_callback( change_type = 'delete', previous_dn = None, change_number = None, dn = dn, entry = old ) elif isinstance(new, dict) and len(new.keys()) > 0: # Old is not a dict (or empty), so the entry is just created log.info("Add entry %r" % (dn)) # See if the mailserver_attribute exists mailserver_attribute = conf.get('ldap', 'mailserver_attribute').lower() if mailserver_attribute == None: log.error("Mail server attribute is not set") # TODO: Perhaps, query for IMAP servers. If there is only one, # we know what to do. return if new.has_key(mailserver_attribute): log.info("Added entry %r has mail server attribute %s: %r" % (dn, mailserver_attribute, new[mailserver_attribute])) if not new[mailserver_attribute] == constants.fqdn: log.info("The mail server for user %r is set, and it is not me (%r)" % (dn, new[mailserver_attribute])) return else: log.info("Added entry %r does not have a mail server attribute set." % (dn)) return auth._auth._synchronize_callback( change_type = 'add', previous_dn = None, change_number = None, dn = dn, entry = new ) else: log.info("entry %r changed, but no new or old attributes" % (dn))
if __name__ == '__main__': from optparse import OptionParser parser = OptionParser(usage="%prog [-h|--help] [--direct-resync]") parser.add_option("--direct-resync", action="store_true", dest="direct_resync", default=False, help="Filter the output of univention-ldapsearch through the this module") (options, args) = parser.parse_args() if not options.direct_resync: parser.error("The option --direct-resync is required to run this module directly") import sys sys.exit(1) univention.debug.init("stderr", univention.debug.NO_FLUSH, univention.debug.NO_FUNCTION) from univention.config_registry import ConfigRegistry ucr = ConfigRegistry() ucr.load() univention.debug.set_level(univention.debug.LISTENER, int(ucr.get('listener/debug/level', 2))) import subprocess cmd = ['/usr/bin/univention-ldapsearch', '-xLLL', filter, 'objectClass'] cmd.extend(attributes) p1 = subprocess.Popen(cmd, stdout=subprocess.PIPE) (stdout, stderr) = p1.communicate() from ldif import LDIFParser class ListenerHandler(LDIFParser): def __init__(self,input): LDIFParser.__init__(self,input) def handle(self,dn,entry): handler(dn, entry, {}, 'a')
import ldap from univention.config_registry import ConfigRegistry from ldap.controls import LDAPControl import ldap.modlist as modlist try: from univention.connector.ad import compatible_modstring except ImportError, e: try: from univention.s4connector.s4 import compatible_modstring except ImportError, e: def compatible_modstring(dn): return dn baseConfig = ConfigRegistry() baseConfig.load() def get_rdn(dn): index = dn.find(',') if index == -1: return dn else: return dn[0:index] def get_parent_dn(dn): index = dn.find(',') if index == -1: return None else: return dn[index+1:len(dn)] class LDAPConnection(object):
# cryptographic keys etc. are subject to a license agreement between # you and Univention and not subject to the GNU AGPL V3. # # In the case you use this program under the terms of the GNU AGPL V3, # the program is provided in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License with the Debian GNU/Linux or Univention distribution in file # /usr/share/common-licenses/AGPL-3; if not, see # <http://www.gnu.org/licenses/>. from univention.config_registry import ConfigRegistry configRegistry = ConfigRegistry() configRegistry.load() # Update package cache cmd_update = configRegistry.get('update/commands/update', 'apt-get update') # Show package information cmd_show = configRegistry.get('update/commands/show', 'apt-cache show') # Upgrade only installed packages cmd_upgrade = configRegistry.get('update/commands/upgrade', 'apt-get -o DPkg::Options::=--force-confold -o DPkg::Options::=--force-overwrite -o DPkg::Options::=--force-overwrite-dir --trivial-only=no --assume-yes --quiet=1 -u upgrade') cmd_upgrade_sim = configRegistry.get('update/commands/upgrade/simulate', 'apt-get -o DPkg::Options::=--force-confold -o DPkg::Options::=--force-overwrite -o DPkg::Options::=--force-overwrite-dir --trivial-only=no --assume-yes --quiet=1 -us upgrade') # Upgrade system, may install new packages to satisfy dependencies cmd_dist_upgrade = configRegistry.get('update/commands/distupgrade', 'apt-get -o DPkg::Options::=--force-confold -o DPkg::Options::=--force-overwrite -o DPkg::Options::=--force-overwrite-dir --trivial-only=no --assume-yes --quiet=1 -u dist-upgrade') cmd_dist_upgrade_sim = configRegistry.get('update/commands/distupgrade/simulate', 'apt-get -o DPkg::Options::=--force-confold -o DPkg::Options::=--force-overwrite -o DPkg::Options::=--force-overwrite-dir --trivial-only=no --assume-yes --quiet=1 -us dist-upgrade')