Exemplo n.º 1
0
 def get_test_connection(cls, hostname=None, *args, **kwargs):
     ucr = ConfigRegistry()
     ucr.load()
     username = ucr.get('tests/domainadmin/account')
     username = username.split(',')[0][len('uid='):]
     password = ucr.get('tests/domainadmin/pwd')
     return cls(hostname, username, password, *args, **kwargs)
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
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()
Exemplo n.º 4
0
def getLDAPServersCommaList(ucr=None):
	# type: (Optional[ConfigRegistry]) -> str
	"""
	Returns a comma-separated string with all configured |LDAP| servers,
	`ldap/server/name` and `ldap/server/addition`.

	:param ConfigRegistry ucr: An optional |UCR| instance.
	:returns: A space separated list of |LDAP| host names.
	:rtype: str
	"""
	if ucr is None:
		ucr = ConfigRegistry()
		ucr.load()

	ldap_servers = ''
	ldaphosts = []
	ldap_server_name = ucr.get('ldap/server/name')
	ldap_server_addition = ucr.get('ldap/server/addition')

	if ldap_server_name:
		ldaphosts.append(ldap_server_name)
	if ldap_server_addition:
		ldaphosts.extend(ldap_server_addition.split())
	if ldaphosts:
		ldap_servers = ','.join(ldaphosts)

	return ldap_servers
Exemplo n.º 5
0
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()
Exemplo n.º 6
0
def getLDAPURIs(ucr=None):
	# type: (Optional[ConfigRegistry]) -> str
	"""
	Returns a space separated list of all configured |LDAP| servers, according to |UCR| variables
	`ldap/server/name` and `ldap/server/addition`.

	:param ConfigRegistry ucr: An optional |UCR| instance.
	:returns: A space separated list of |LDAP| |URI|.
	:rtype: str
	"""
	if ucr is None:
		ucr = ConfigRegistry()
		ucr.load()

	uri_string = ''
	ldaphosts = []
	port = ucr.get('ldap/server/port', '7389')
	ldap_server_name = ucr.get('ldap/server/name')
	ldap_server_addition = ucr.get('ldap/server/addition')

	if ldap_server_name:
		ldaphosts.append(ldap_server_name)
	if ldap_server_addition:
		ldaphosts.extend(ldap_server_addition.split())
	if ldaphosts:
		urilist = ["ldap://%s:%s" % (host, port) for host in ldaphosts]
		uri_string = ' '.join(urilist)

	return uri_string
Exemplo n.º 7
0
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
Exemplo n.º 8
0
def getRootDnConnection(start_tls=2, decode_ignorelist=[], reconnect=True):
    # type: (int, List[str], bool) -> access
    """
	Open a LDAP connection to the local LDAP server with the LDAP root account.

	: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()
    port = int(ucr.get('slapd/port', '7389').split(',')[0])
    host = ucr['hostname'] + '.' + ucr['domainname']
    if ucr.get('ldap/server/type', 'dummy') == 'master':
        bindpw = open('/etc/ldap.secret').read().rstrip('\n')
        binddn = 'cn=admin,{0}'.format(ucr['ldap/base'])
    else:
        bindpw = open('/etc/ldap/rootpw.conf').read().rstrip('\n').replace(
            'rootpw "', '', 1)[:-1]
        binddn = 'cn=update,{0}'.format(ucr['ldap/base'])
    return access(host=host,
                  port=port,
                  base=ucr['ldap/base'],
                  binddn=binddn,
                  bindpw=bindpw,
                  start_tls=start_tls,
                  decode_ignorelist=decode_ignorelist,
                  reconnect=reconnect)
Exemplo n.º 9
0
    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)
Exemplo n.º 10
0
def getMachineConnection(start_tls=2,
                         decode_ignorelist=[],
                         ldap_master=True,
                         secret_file="/etc/machine.secret",
                         reconnect=True,
                         random_server=False):
    # type: (int, List[str], bool, str, bool) -> access
    """
	Open a LDAP connection using the machine 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 ldap_master: Open a connection to the Master if True, to the preferred LDAP server otherwise.
	:param str secret_file: The name of a file containing the password credentials.
	:param bool reconnect: Automatically reconnect if the connection fails.
	:param bool random_server: Choose a random LDAP server from ldap/server/name and ldap/server/addition.
	:return: A LDAP access object.
	:rtype: univention.uldap.access
	"""
    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'))
        servers = [ucr.get('ldap/server/name')]
        servers += ucr.get('ldap/server/addition', '').split()
        if random_server:
            random.shuffle(servers)
        for server in servers:
            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)
            #LDAP server down, try next server
            except ldap.SERVER_DOWN as exc:
                pass
        raise exc
Exemplo n.º 11
0
    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 get_ldap_master_connection(user_dn):
    ucr = ConfigRegistry()
    ucr.load()

    return univention.uldap.access(host=ucr.get('ldap/master'),
                                   port=int(ucr.get('ldap/master/port',
                                                    '7389')),
                                   base=ucr.get('ldap/base'),
                                   binddn=user_dn,
                                   bindpw='univention')
Exemplo n.º 13
0
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
Exemplo n.º 14
0
def getRootDnConnection(start_tls=2, decode_ignorelist=[], reconnect=True):
	ucr = ConfigRegistry()
	ucr.load()
	port = int(ucr.get('slapd/port', '7389').split(',')[0])
	host = ucr['hostname'] + '.' + ucr['domainname']
	if ucr.get('ldap/server/type', 'dummy') == 'master':
		bindpw = open('/etc/ldap.secret').read().rstrip('\n')
		binddn = 'cn=admin,{0}'.format(ucr['ldap/base'])
	else:
		bindpw = open('/etc/ldap/rootpw.conf').read().rstrip('\n').lstrip('rootpw "').rstrip('"')
		binddn = 'cn=update,{0}'.format(ucr['ldap/base'])
	return access(host=host, port=port, base=ucr['ldap/base'], binddn=binddn, bindpw=bindpw, start_tls=start_tls, decode_ignorelist=decode_ignorelist, reconnect=reconnect)
Exemplo n.º 15
0
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()
Exemplo n.º 16
0
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
Exemplo n.º 17
0
	def write_saml_setup_script(cls, adconnection_alias=None):
		from univention.config_registry import ConfigRegistry
		ucr = ConfigRegistry()
		ucr.load()

		ucs_sso_fqdn = ucr.get('ucs/server/sso/fqdn', "%s.%s" % (ucr.get('hostname', 'undefined'), ucr.get('domainname', 'undefined')))
		cert = ""
		try:
			cert_path = SAML_SETUP_SCRIPT_CERT_PATH.format(
				domainname=ucr.get('domainname', 'undefined'),
				adconnection_alias='_{}'.format(adconnection_alias) if adconnection_alias else ''
			)
			with open(ucr.get('saml/idp/certificate/certificate', cert_path), 'rb') as fd:
				raw_cert = fd.read()
		except IOError as exc:
			logger.exception("while reading certificate: %s", exc)
			raise WriteScriptError(_("Error reading identity provider certificate."), adconnection_alias=adconnection_alias)

		try:
			cert = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, raw_cert))
		except OpenSSL.crypto.Error as exc:
			logger.exception("while converting certificate: %s", exc)
			raise WriteScriptError(_("Error converting identity provider certificate."), adconnection_alias=adconnection_alias)

		saml_uri_supplement = ""
		if adconnection_alias != "defaultADconnection":
			saml_uri_supplement = '/%s' % adconnection_alias

		issuer = 'https://{ssohost}/simplesamlphp{supplement}/saml2/idp/metadata.php'.format(ssohost=ucr.get('ucs/server/sso/fqdn', 'ucs-sso.{domain}'.format(domain=ucr.get('domainname'))), supplement=saml_uri_supplement)

		# The raw base64 encoded certificate is required
		cert = cert.replace('-----BEGIN CERTIFICATE-----', '').replace('-----END CERTIFICATE-----', '').replace('\n', '')
		template = '''
@ECHO OFF
ECHO Asking for Azure Administator credentials
powershell Connect-MsolService; Set-MsolDomainAuthentication -DomainName "{domain}" -Authentication Managed; Set-MsolDomainAuthentication -DomainName "{domain}" -FederationBrandName "UCS" -Authentication Federated -ActiveLogOnUri "https://{ucs_sso_fqdn}/simplesamlphp{supplement}/saml2/idp/SSOService.php" -PassiveLogOnUri "https://{ucs_sso_fqdn}/simplesamlphp{supplement}/saml2/idp/SSOService.php" -SigningCertificate "{cert}" -IssuerUri "{issuer}" -LogOffUri "https://{ucs_sso_fqdn}/simplesamlphp{supplement}/saml2/idp/SingleLogoutService.php?ReturnTo=/univention/" -PreferredAuthenticationProtocol SAMLP;  Get-MsolDomain
ECHO Finished single sign-on configuration change
pause
'''.format(domain=cls.get_domain(adconnection_alias), ucs_sso_fqdn=ucs_sso_fqdn, cert=cert, issuer=issuer, supplement=saml_uri_supplement)

		try:
			script_path = SAML_SETUP_SCRIPT_PATH.format(adconnection_alias='_{}'.format(adconnection_alias) if adconnection_alias else '')
			with open(script_path, 'wb') as fd:
				fd.write(template)
			os.chmod(script_path, 0644)
		except IOError as exc:
			logger.exception("while writing powershell script: %s", exc)
			raise WriteScriptError(_("Error writing SAML setup script."), adconnection_alias=adconnection_alias)
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
Exemplo n.º 19
0
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
Exemplo n.º 20
0
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)
Exemplo n.º 21
0
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
Exemplo n.º 22
0
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
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
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)
Exemplo n.º 25
0
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 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))
Exemplo n.º 27
0
	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, reconnect=True):
		"""start_tls = 0 (no); 1 (try); 2 (must)"""
		self.host = host
		self.base = base
		self.binddn = binddn
		self.bindpw = bindpw
		self.start_tls = start_tls
		self.ca_certfile = ca_certfile
		self.reconnect = reconnect

		self.port = int(port) if port else None

		ucr = ConfigRegistry()
		ucr.load()

		if not self.port:  # if no explicit port is given
			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:%d' % (self.host, self.port)
		elif uri:
			self.uri = uri
		else:
			self.uri = "ldap://%s:%d" % (self.host, self.port)

		self.decode_ignorelist = decode_ignorelist or ucr.get('ldap/binaryattributes', 'krb5Key,userCertificate;binary').split(',')

		# 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

		try:
			client_retry_count = int(ucr.get('ldap/client/retry/count', 10))
		except ValueError:
			univention.debug.debug(univention.debug.LDAP, univention.debug.ERROR, "Unable to read ldap/client/retry/count, please reset to an integer value")
			client_retry_count = 10

		self.client_connection_attempt = client_retry_count + 1

		self.__open(ca_certfile)
Exemplo n.º 28
0
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)
Exemplo n.º 29
0
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)
Exemplo n.º 30
0
def createMachinePassword():
	# type: () -> str
	"""
	Returns a $(pwgen) generated password according to the
	requirements in |UCR| variables
	`machine/password/length` and `machine/password/complexity`.

	:returns: A password.
	:rtype: str
	"""
	ucr = ConfigRegistry()
	ucr.load()
	length = ucr.get('machine/password/length', '20')
	compl = ucr.get('machine/password/complexity', 'scn')
	p = subprocess.Popen(["pwgen", "-1", "-" + compl, length], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	(stdout, stderr) = p.communicate()
	if not isinstance(stdout, str):  # Python 3
		return stdout.decode('ASCII', 'replace').strip()
	return stdout.strip()
Exemplo n.º 31
0
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()
Exemplo n.º 32
0
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()
Exemplo n.º 33
0
def handler(dn, new, old):
	# type: (str, dict, dict) -> None
	listener.setuid(0)
	try:
		change = False
		new_has_service = service_name in new.get('univentionService', [])
		old_has_service = service_name in old.get('univentionService', [])
		if new_has_service and not old_has_service:
			try:
				fqdn = b'%s.%s' % (new['cn'][0], new['associatedDomain'][0])
			except (KeyError, IndexError):
				return

			ucr = ConfigRegistry()
			ucr.load()
			old_ucr_value = ucr.get('admin/diary/backend', u'')
			fqdn_set = set(old_ucr_value.split())
			fqdn_set.add(fqdn.decode('utf-8'))
			new_ucr_value = u' '.join(fqdn_set)
			handler_set([u'admin/diary/backend=%s' % (new_ucr_value,)])
			change = True
		elif old_has_service:
			try:
				fqdn = b'%s.%s' % (old['cn'][0], old['associatedDomain'][0])
			except (KeyError, IndexError):
				return

			ucr = ConfigRegistry()
			ucr.load()
			old_ucr_value = ucr.get('admin/diary/backend', u'')
			fqdn_set = set(old_ucr_value.split())
			fqdn_set.discard(fqdn.decode('UTF-8'))
			new_ucr_value = u' '.join(fqdn_set)
			handler_set([u'admin/diary/backend=%s' % (new_ucr_value,)])
			change = True

		if change:
			subprocess.call(['invoke-rc.d', 'rsyslog', 'try-restart'])
	finally:
		listener.unsetuid()
Exemplo n.º 34
0
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 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
Exemplo n.º 36
0
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
Exemplo n.º 37
0
	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 StringIO
Exemplo n.º 38
0
Arquivo: data.py Projeto: B-Rich/smart
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
Exemplo n.º 39
0
# 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')

# Install packages
cmd_install = configRegistry.get('update/commands/install', '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 install')