Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Authors: Simo Sorce <ssorce@redhat.com> # # Copyright (C) 2007-2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #
except ImportError: # Python 2.4 doesn't implement CalledProcessError class CalledProcessError(Exception): """This exception is raised when a process run by check_call() returns a non-zero exit status. The exit status will be stored in the returncode attribute.""" def __init__(self, returncode, cmd): self.returncode = returncode self.cmd = cmd def __str__(self): return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
except Exception: return None
# Use inet_pton() rather than inet_aton() for IP address parsing. We # will use the same function in IPv4/IPv6 conversions + be stricter # and don't allow IP addresses such as '1.1.1' in the same time
allow_network=False, allow_loopback=False, allow_broadcast=False, allow_multicast=False): super(CheckedIPAddress, self).__init__(addr, flags=self.netaddr_ip_flags) self.prefixlen = addr.prefixlen self.defaultnet = addr.defaultnet self.interface = addr.interface return
net = addr addr = net.ip pass else: # netaddr.IPAddress doesn't handle zone indices in textual # IPv6 addresses. Try removing zone index and parse the # address again. raise raise ValueError("netmask and prefix length not allowed here")
raise ValueError("unsupported IP version")
or addr in netaddr.ip.IPV4_6TO4:
if addr.version == 4: family = 'inet' elif addr.version == 6: family = 'inet6'
ipresult = run(['/sbin/ip', '-family', family, '-oneline', 'address', 'show']) lines = ipresult[0].split('\n') for line in lines: fields = line.split() if len(fields) < 4: continue
ifnet = netaddr.IPNetwork(fields[3]) if ifnet == net or (net is None and ifnet.ip == addr): net = ifnet iface = fields[1] break
if iface is None: raise ValueError('No network interface matches the provided IP address and netmask')
return self.interface is not None
""" Format network location (host:port).
If the host part is a literal IPv6 address, it must be enclosed in square brackets (RFC 2732). """ host = '[%s]' % host else:
"""Convert a kerberos realm into the IPA suffix."""
# eval() is a special string one can insert into a template to have the # Python interpreter evaluate the string. This is intended to allow # math to be performed in templates.
txt = open(infilename).read() return template_str(txt, vars)
fd = tempfile.NamedTemporaryFile() fd.write(txt) fd.flush()
return fd
return "'" + string.replace("'", "'\\''") + "'"
nolog=(), env=None, capture_output=True): """ Execute a command and return stdin, stdout and the process return code.
args is a list of arguments for the command
stdin is used if you want to pass input to the command
raiseonerr raises an exception if the return code is not zero
nolog is a tuple of strings that shouldn't be logged, like passwords. Each tuple consists of a string to be replaced by XXXXXXXX.
For example, the command ['/usr/bin/setpasswd', '--password', 'Secret123', 'someuser']
We don't want to log the password so nolog would be set to: ('Secret123',)
The resulting log output would be:
/usr/bin/setpasswd --password XXXXXXXX someuser
If an value isn't found in the list it is silently ignored. """
# We expect a tuple (or list, or other iterable) of nolog strings. # Passing just a single string is bad: strings are also, so this # would result in every individual character of that string being # replaced by XXXXXXXX. # This is a sanity check to prevent that. raise ValueError('nolog must be a tuple of strings.')
# copy default env p_in = subprocess.PIPE
close_fds=True, env=env) except KeyboardInterrupt: p.wait() raise
# The command and its output may include passwords that we don't want # to log. Run through the nolog items. if not isinstance(value, basestring): continue
quoted = urllib2.quote(value) shquoted = shell_quote(value) for nolog_value in (shquoted, value, quoted): if capture_output: stdout = stdout.replace(nolog_value, 'XXXXXXXX') stderr = stderr.replace(nolog_value, 'XXXXXXXX') args = args.replace(nolog_value, 'XXXXXXXX')
raise CalledProcessError(p.returncode, args)
else:
try: mode = os.stat(filename)[stat.ST_MODE] if stat.S_ISDIR(mode): return True else: return False except: return False
if file_exists(dest): os.rename(dest, dest + ".orig") shutil.move(fname, dest)
if file_exists(fname): os.rename(fname, fname + ".orig")
# uses gpg to compress and encrypt a file if type(source) is not StringType or not len(source): raise ValueError('Missing Source File') #stat it so that we get back an exception if it does no t exist os.stat(source)
if type(dest) is not StringType or not len(dest): raise ValueError('Missing Destination File')
if type(password) is not StringType or not len(password): raise ValueError('Missing Password')
#create a tempdir so that we can clean up with easily tempdir = tempfile.mkdtemp('', 'ipa-', workdir) gpgdir = tempdir+"/.gnupg"
try: try: #give gpg a fake dir so that we can leater remove all #the cruft when we clean up the tempdir os.mkdir(gpgdir) args = ['/usr/bin/gpg', '--batch', '--homedir', gpgdir, '--passphrase-fd', '0', '--yes', '--no-tty', '-o', dest, '-c', source] run(args, password) except: raise finally: #job done, clean up shutil.rmtree(tempdir, ignore_errors=True)
if type(source) is not StringType or not len(source): raise ValueError('Missing Source File') #stat it so that we get back an exception if it does no t exist os.stat(source)
if type(dest) is not StringType or not len(dest): raise ValueError('Missing Destination File')
if type(password) is not StringType or not len(password): raise ValueError('Missing Password')
#create a tempdir so that we can clean up with easily tempdir = tempfile.mkdtemp('', 'ipa-', workdir) gpgdir = tempdir+"/.gnupg"
try: try: #give gpg a fake dir so that we can leater remove all #the cruft when we clean up the tempdir os.mkdir(gpgdir) args = ['/usr/bin/gpg', '--batch', '--homedir', gpgdir, '--passphrase-fd', '0', '--yes', '--no-tty', '-o', dest, '-d', source] run(args, password) except: raise finally: #job done, clean up shutil.rmtree(tempdir, ignore_errors=True)
""" Case-insensitive but case-respecting dictionary.
This code is derived from python-ldap's cidict.py module, written by stroeder: http://python-ldap.sourceforge.net/
This version extends 'dict' so it works properly with TurboGears. If you extend UserDict, isinstance(foo, dict) returns false. """
"""This class is a basic timezone wrapper for the offset specified in a Generalized Time. It is dst-ignorant."""
else: raise ValueError()
return self.name
"""Parses are Generalized Time string (as specified in X.680), returning a datetime object. Generalized Times are stored inside the krbPasswordExpiration attribute in LDAP.
This method doesn't attempt to be perfect wrt timezones. If python can't be bothered to implement them, how can we..."""
return None
except ValueError: return None
''' Generates password. Password cannot start or end with a whitespace character. It also cannot be formed by whitespace characters only. Length of password as well as string of characters to be used by generator could be optionaly specified by characters and pwd_len parameters, otherwise default values will be used: characters string will be formed by all printable non-whitespace characters and space, pwd_len will be equal to value of GEN_PWD_LEN. ''' characters=string.digits + string.ascii_letters + string.punctuation + ' ' else: raise ValueError("password cannot be formed by whitespaces only")
rndchar = characters[r.randint(0,upper_bound)]
'''Given text with items separated by whitespace or comma, return a list of those items
The returned list only contains non-empty items. ''' split_re = re.compile('[ ,\t\n]+') items = split_re.split(text) for item in items[:]: if not item: items.remove(item) return items
if default == None: while True: ret = raw_input("%s: " % prompt) if allow_empty or ret.strip(): return ret
if isinstance(default, basestring): while True: ret = raw_input("%s [%s]: " % (prompt, default)) if not ret and (allow_empty or default): return default elif ret.strip(): return ret if isinstance(default, bool): if default: choice = "yes" else: choice = "no" while True: ret = raw_input("%s [%s]: " % (prompt, choice)) if not ret: return default elif ret.lower()[0] == "y": return True elif ret.lower()[0] == "n": return False if isinstance(default, int): while True: try: ret = raw_input("%s [%s]: " % (prompt, default)) if not ret: return default ret = int(ret) except ValueError: pass else: return ret
""" A GSSError exception looks differently in python 2.4 than it does in python 2.5. Deal with it. """
try: major = e[0] minor = e[1] except: major = e[0][0] minor = e[0][1]
return (major, minor)
families = (socket.AF_INET, socket.AF_INET6) success = False
for family in families: try: try: s = socket.socket(family, socket_type) except socket.error: continue
if socket_timeout is not None: s.settimeout(socket_timeout)
s.connect((host, port))
if socket_type == socket.SOCK_DGRAM: s.send('') s.recv(512)
success = True except socket.error, e: pass finally: s.close()
if success: return True
return False
families = (socket.AF_INET, socket.AF_INET6)
host = '' # all available interfaces
for family in families: try: s = socket.socket(family, socket_type) except socket.error, e: if family == families[-1]: # last available family raise e
if socket_timeout is not None: s.settimeout(socket_timeout)
if socket_type == socket.SOCK_STREAM: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try: s.bind((host, port))
if socket_type == socket.SOCK_STREAM: s.listen(1) connection, client_address = s.accept() try: if responder_data: connection.sendall(responder_data) #pylint: disable=E1101 finally: connection.close() elif socket_type == socket.SOCK_DGRAM: data, addr = s.recvfrom(1)
if responder_data: s.sendto(responder_data, addr) finally: s.close()
""" Get base DN of IPA suffix in given LDAP server.
None is returned if the suffix is not found
:param conn: Bound LDAP connection that will be used for searching """ entries = conn.search_ext_s( '', scope=ldap.SCOPE_BASE, attrlist=['defaultnamingcontext', 'namingcontexts'] )
contexts = entries[0][1]['namingcontexts'] if entries[0][1].get('defaultnamingcontext'): # If there is a defaultNamingContext examine that one first default = entries[0][1]['defaultnamingcontext'][0] if default in contexts: contexts.remove(default) contexts.insert(0, entries[0][1]['defaultnamingcontext'][0]) for context in contexts: root_logger.debug("Check if naming context '%s' is for IPA" % context) try: entry = conn.search_s(context, ldap.SCOPE_BASE, "(info=IPA*)") except ldap.NO_SUCH_OBJECT: root_logger.debug("LDAP server did not return info attribute to check for IPA version") continue if len(entry) == 0: root_logger.debug("Info attribute with IPA server version not found") continue info = entry[0][1]['info'][0].lower() if info != IPA_BASEDN_INFO: root_logger.debug("Detected IPA server version (%s) did not match the client (%s)" \ % (info, IPA_BASEDN_INFO)) continue root_logger.debug("Naming context '%s' is a valid IPA context" % context) return context
return None
""" Take a key=value based configuration file, and write new version with certain values replaced or appended
All (key,value) pairs from replacevars and appendvars that were not found in the configuration file, will be added there.
It is responsibility of a caller to ensure that replacevars and appendvars do not overlap.
It is responsibility of a caller to back up file.
returns dictionary of affected keys and their previous values
One have to run restore_context(filepath) afterwards or security context of the file will not be correct after modification """ pattern = re.compile(''' (^ \s* (?P<option> [^\#;]+?) (\s*=\s*) (?P<value> .+?)? (\s*((\#|;).*)?)? $)''', re.VERBOSE) orig_stat = os.stat(filepath) old_values = dict() temp_filename = None with tempfile.NamedTemporaryFile(delete=False) as new_config: temp_filename = new_config.name with open(filepath, 'r') as f: for line in f: new_line = line m = pattern.match(line) if m: option, value = m.group('option', 'value') if option is not None: if replacevars and option in replacevars: # replace value completely new_line = u"%s=%s\n" % (option, replacevars[option]) old_values[option] = value if appendvars and option in appendvars: # append new value unless it is already existing in the original one if not value: new_line = u"%s=%s\n" % (option, appendvars[option]) elif value.find(appendvars[option]) == -1: new_line = u"%s=%s %s\n" % (option, value, appendvars[option]) old_values[option] = value new_config.write(new_line) # Now add all options from replacevars and appendvars that were not found in the file new_vars = replacevars.copy() new_vars.update(appendvars) newvars_view = set(new_vars.keys()) - set(old_values.keys()) append_view = (set(appendvars.keys()) - newvars_view) for item in newvars_view: new_config.write("%s=%s\n" % (item,new_vars[item])) for item in append_view: new_config.write("%s=%s\n" % (item,appendvars[item])) new_config.flush() # Make sure the resulting file is readable by others before installing it os.fchmod(new_config.fileno(), orig_stat.st_mode) os.fchown(new_config.fileno(), orig_stat.st_uid, orig_stat.st_gid)
# At this point new_config is closed but not removed due to 'delete=False' above # Now, install the temporary file as configuration and ensure old version is available as .orig # While .orig file is not used during uninstall, it is left there for administrator. install_file(temp_filename, filepath)
return old_values
""" Take a section-structured key=value based configuration file, and write new version with certain values replaced or appended within the section
All (key,value) pairs from replacevars and appendvars that were not found in the configuration file, will be added there.
It is responsibility of a caller to ensure that replacevars and appendvars do not overlap.
It is responsibility of a caller to back up file.
returns dictionary of affected keys and their previous values
One have to run restore_context(filepath) afterwards or security context of the file will not be correct after modification """ pattern = re.compile(''' (^ \[ (?P<section> .+) \] (\s+((\#|;).*)?)? $)|(^ \s* (?P<option> [^\#;]+?) (\s*=\s*) (?P<value> .+?)? (\s*((\#|;).*)?)? $)''', re.VERBOSE) def add_options(config, replacevars, appendvars, oldvars): # add all options from replacevars and appendvars that were not found in the file new_vars = replacevars.copy() new_vars.update(appendvars) newvars_view = set(new_vars.keys()) - set(oldvars.keys()) append_view = (set(appendvars.keys()) - newvars_view) for item in newvars_view: config.write("%s=%s\n" % (item,new_vars[item])) for item in append_view: config.write("%s=%s\n" % (item,appendvars[item]))
orig_stat = os.stat(filepath) old_values = dict() temp_filename = None with tempfile.NamedTemporaryFile(delete=False) as new_config: temp_filename = new_config.name with open(filepath, 'r') as f: in_section = False finished = False line_idx = 1 for line in f: line_idx = line_idx + 1 new_line = line m = pattern.match(line) if m: sect, option, value = m.group('section', 'option', 'value') if in_section and sect is not None: # End of the searched section, add remaining options add_options(new_config, replacevars, appendvars, old_values) finished = True if sect is not None: # New section is found, check whether it is the one we are looking for in_section = (str(sect).lower() == str(section).lower()) if option is not None and in_section: # Great, this is an option from the section we are loking for if replacevars and option in replacevars: # replace value completely new_line = u"%s=%s\n" % (option, replacevars[option]) old_values[option] = value if appendvars and option in appendvars: # append a new value unless it is already existing in the original one if not value: new_line = u"%s=%s\n" % (option, appendvars[option]) elif value.find(appendvars[option]) == -1: new_line = u"%s=%s %s\n" % (option, value, appendvars[option]) old_values[option] = value new_config.write(new_line) # We have finished parsing the original file. # There are two remaining cases: # 1. Section we were looking for was not found, we need to add it. if not (in_section or finished): new_config.write("[%s]\n" % (section)) # 2. The section is the last one but some options were not found, add them. if in_section or not finished: add_options(new_config, replacevars, appendvars, old_values)
new_config.flush() # Make sure the resulting file is readable by others before installing it os.fchmod(new_config.fileno(), orig_stat.st_mode) os.fchown(new_config.fileno(), orig_stat.st_uid, orig_stat.st_gid)
# At this point new_config is closed but not removed due to 'delete=False' above # Now, install the temporary file as configuration and ensure old version is available as .orig # While .orig file is not used during uninstall, it is left there for administrator. install_file(temp_filename, filepath)
return old_values
""" Take a key=value based configuration file, back up it, and write new version with certain values replaced or appended
All (key,value) pairs from replacevars and appendvars that were not found in the configuration file, will be added there.
It is responsibility of a caller to ensure that replacevars and appendvars do not overlap.
returns dictionary of affected keys and their previous values
One have to run restore_context(filepath) afterwards or security context of the file will not be correct after modification """ # Backup original filepath fstore.backup_file(filepath) old_values = config_replace_variables(filepath, replacevars, appendvars)
return old_values
try: (algolen,) = struct.unpack('>I', data[:4]) if algolen > 0 and algolen <= len(data) - 4: return (data[4:algolen+4], data[algolen+4:], fptype(data).hexdigest().upper()) except struct.error: pass raise ValueError('not a SSH public key')
algo, data, fp = decode_ssh_pubkey(key, fptype=sha1) if algo == 'ssh-rsa': algo = 1 elif algo == 'ssh-dss': algo = 2 else: return return '%d 1 %s' % (algo, fp)
else: return utf8_encode_value(values) |