Debian Codegraph @

ipapython/ipautil.py

raw
1 # Authors: Simo Sorce <[email protected]>
2 #
3 # Copyright (C) 2007-2016 Red Hat, Inc.
4 # see file 'COPYING' for use and warranty information
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 from __future__ import print_function
21
22 import codecs
23 import logging
24 import string
25 import tempfile
26 import subprocess
27 import random
28 import math
29 import os
30 import sys
31 import errno
32 import copy
33 import shutil
34 import socket
35 import re
36 import datetime
37 import netaddr
38 import time
39 import textwrap
40 import io
41 from contextlib import contextmanager
42 from configparser import RawConfigParser, ParsingError
43 import locale
44 import collections
45 import urllib
46
47 import six
48 from six.moves import input
49
50 try:
51 import ifaddr
52 except ImportError:
53 ifaddr = None
54
55 from ipapython.dn import DN
56 from ipaplatform.paths import paths
57 from ipaplatform.constants import User, Group
58
59
60 logger = logging.getLogger(__name__)
61
62 # only for OTP password that is manually retyped by user
63 TMP_PWD_ENTROPY_BITS = 128
64
65
66 PROTOCOL_NAMES = {
67 socket.SOCK_STREAM: 'tcp',
68 socket.SOCK_DGRAM: 'udp'
69 }
70
71 InterfaceDetails = collections.namedtuple(
72 'InterfaceDetails', [
73 'name', # interface name
74 'ifnet' # network details of interface
75 ])
76
77
78 class UnsafeIPAddress(netaddr.IPAddress):
79 """Any valid IP address with or without netmask."""
80
81 # Use inet_pton() rather than inet_aton() for IP address parsing. We
82 # will use the same function in IPv4/IPv6 conversions + be stricter
83 # and don't allow IP addresses such as '1.1.1' in the same time
84 netaddr_ip_flags = netaddr.INET_PTON
85
86 def __init__(self, addr):
87 if isinstance(addr, UnsafeIPAddress):
88 self._net = addr._net
89 super(UnsafeIPAddress, self).__init__(addr,
90 flags=self.netaddr_ip_flags)
91 return
92
93 elif isinstance(addr, netaddr.IPAddress):
94 self._net = None # no information about netmask
95 super(UnsafeIPAddress, self).__init__(addr,
96 flags=self.netaddr_ip_flags)
97 return
98
99 elif isinstance(addr, netaddr.IPNetwork):
100 self._net = addr
101 super(UnsafeIPAddress, self).__init__(self._net.ip,
102 flags=self.netaddr_ip_flags)
103 return
104
105 # option of last resort: parse it as string
106 self._net = None
107 addr = str(addr)
108 try:
109 try:
110 addr = netaddr.IPAddress(addr, flags=self.netaddr_ip_flags)
111 except netaddr.AddrFormatError:
112 # netaddr.IPAddress doesn't handle zone indices in textual
113 # IPv6 addresses. Try removing zone index and parse the
114 # address again.
115 addr, sep, _foo = addr.partition('%')
116 if sep != '%':
117 raise
118 addr = netaddr.IPAddress(addr, flags=self.netaddr_ip_flags)
119 if addr.version != 6:
120 raise
121 except ValueError:
122 self._net = netaddr.IPNetwork(addr, flags=0)
123 addr = self._net.ip
124 super(UnsafeIPAddress, self).__init__(addr,
125 flags=self.netaddr_ip_flags)
126
127 def __getstate__(self):
128 state = {
129 '_net': self._net,
130 'super_state': super(UnsafeIPAddress, self).__getstate__(),
131 }
132 return state
133
134 def __setstate__(self, state):
135 super(UnsafeIPAddress, self).__setstate__(state['super_state'])
136 self._net = state['_net']
137
138
139 class CheckedIPAddress(UnsafeIPAddress):
140 """IPv4 or IPv6 address with additional constraints.
141
142 Reserved or link-local addresses are never accepted.
143 """
144 def __init__(self, addr, parse_netmask=True,
145 allow_loopback=False, allow_multicast=False):
146 try:
147 super(CheckedIPAddress, self).__init__(addr)
148 except netaddr.core.AddrFormatError as e:
149 raise ValueError(e)
150
151 if isinstance(addr, CheckedIPAddress):
152 self.prefixlen = addr.prefixlen
153 return
154
155 if not parse_netmask and self._net:
156 raise ValueError(
157 "netmask and prefix length not allowed here: {}".format(addr))
158
159 if self.version not in (4, 6):
160 raise ValueError("unsupported IP version {}".format(self.version))
161
162 if not allow_loopback and self.is_loopback():
163 raise ValueError("cannot use loopback IP address {}".format(addr))
164 if (not self.is_loopback() and self.is_reserved()) \
165 or self in netaddr.ip.IPV4_6TO4:
166 raise ValueError(
167 "cannot use IANA reserved IP address {}".format(addr))
168
169 if self.is_link_local():
170 raise ValueError(
171 "cannot use link-local IP address {}".format(addr))
172 if not allow_multicast and self.is_multicast():
173 raise ValueError("cannot use multicast IP address {}".format(addr))
174
175 if self._net is None:
176 if self.version == 4:
177 self._net = netaddr.IPNetwork(
178 netaddr.cidr_abbrev_to_verbose(str(self)))
179 elif self.version == 6:
180 self._net = netaddr.IPNetwork(str(self) + '/64')
181
182 self.prefixlen = self._net.prefixlen
183
184 def __getstate__(self):
185 state = {
186 'prefixlen': self.prefixlen,
187 'super_state': super(CheckedIPAddress, self).__getstate__(),
188 }
189 return state
190
191 def __setstate__(self, state):
192 super(CheckedIPAddress, self).__setstate__(state['super_state'])
193 self.prefixlen = state['prefixlen']
194
195 def is_network_addr(self):
196 return self == self._net.network
197
198 def is_broadcast_addr(self):
199 return self.version == 4 and self == self._net.broadcast
200
201 def get_matching_interface(self):
202 """Find matching local interface for address
203 :return: InterfaceDetails named tuple or None if no interface has
204 this address
205 """
206 if ifaddr is None:
207 raise ImportError("ifaddr")
208 logger.debug("Searching for an interface of IP address: %s", self)
209
210 if self.version == 4:
211 family_ips = (
212 (ip.ip, ip.network_prefix, ip.nice_name)
213 for ips in [a.ips for a in ifaddr.get_adapters()]
214 for ip in ips if not isinstance(ip.ip, tuple)
215 )
216 elif self.version == 6:
217 family_ips = (
218 (ip.ip[0], ip.network_prefix, ip.nice_name)
219 for ips in [a.ips for a in ifaddr.get_adapters()]
220 for ip in ips if isinstance(ip.ip, tuple)
221 )
222 else:
223 raise ValueError(
224 "Unsupported address family ({})".format(self.version)
225 )
226
227 for ip, prefix, ifname in family_ips:
228 ifaddrmask = "{ip}/{prefix}".format(ip=ip, prefix=prefix)
229 logger.debug(
230 "Testing local IP address: %s (interface: %s)",
231 ifaddrmask, ifname)
232 ifnet = netaddr.IPNetwork(ifaddrmask)
233
234 if ifnet.ip == self:
235 return InterfaceDetails(ifname, ifnet)
236
237 return None
238
239 def set_ip_net(self, ifnet):
240 """Set IP Network details for this address. IPNetwork is valid only
241 locally, so this should be set only for local IP addresses
242
243 :param ifnet: netaddr.IPNetwork object with information about IP
244 network where particula address belongs locally
245 """
246 assert isinstance(ifnet, netaddr.IPNetwork)
247 self._net = ifnet
248
249
250 class CheckedIPAddressLoopback(CheckedIPAddress):
251 """IPv4 or IPv6 address with additional constraints with
252 possibility to use a loopback IP.
253 Reserved or link-local addresses are never accepted.
254 """
255 def __init__(self, addr, parse_netmask=True, allow_multicast=False):
256
257 super(CheckedIPAddressLoopback, self).__init__(
258 addr, parse_netmask=parse_netmask,
259 allow_multicast=allow_multicast,
260 allow_loopback=True)
261
262 if self.is_loopback():
263 # print is being used instead of a logger, because at this
264 # moment, in execution process, there is no logger configured
265 print("WARNING: You are using a loopback IP: {}".format(addr),
266 file=sys.stderr)
267
268
269 class IPAddressDoTForwarder(str):
270 """IPv4 or IPv6 address with added hostname as needed for DNS over TLS
271 configuration. Example: 1.2.3.4#dns.hostname.test
272 """
273 def __init__(self, addr):
274 addr_split = addr.split("#")
275 if len(addr_split) != 2 or not valid_ip(addr_split[0]):
276 raise ValueError(
277 "DoT forwarder must be in the format "
278 "of '1.2.3.4#dns.example.test'."
279 )
280
281
282 def valid_ip(addr):
283 return netaddr.valid_ipv4(addr) or netaddr.valid_ipv6(addr)
284
285 def format_netloc(host, port=None):
286 """
287 Format network location (host:port).
288
289 If the host part is a literal IPv6 address, it must be enclosed in square
290 brackets (RFC 2732).
291 """
292 host = str(host)
293 try:
294 socket.inet_pton(socket.AF_INET6, host)
295 host = '[%s]' % host
296 except socket.error:
297 pass
298 if port is None:
299 return host
300 else:
301 return '%s:%s' % (host, str(port))
302
303 def realm_to_suffix(realm_name):
304 'Convert a kerberos realm to a IPA suffix.'
305 s = realm_name.split(".")
306 suffix_dn = DN(*[('dc', x.lower()) for x in s])
307 return suffix_dn
308
309 def suffix_to_realm(suffix_dn):
310 'Convert a IPA suffix to a kerberos realm.'
311 assert isinstance(suffix_dn, DN)
312 realm = '.'.join([x.value for x in suffix_dn])
313 return realm
314
315 def template_str(txt, vars):
316 val = string.Template(txt).substitute(vars)
317
318 # eval() is a special string one can insert into a template to have the
319 # Python interpreter evaluate the string. This is intended to allow
320 # math to be performed in templates.
321 pattern = re.compile(r'(eval\s*\(([^()]*)\))')
322 val = pattern.sub(lambda x: str(eval(x.group(2))), val)
323
324 return val
325
326 def template_file(infilename, vars):
327 """Read a file and perform template substitutions"""
328 with open(infilename) as f:
329 return template_str(f.read(), vars)
330
331 def copy_template_file(infilename, outfilename, vars):
332 """Copy a file, performing template substitutions"""
333 txt = template_file(infilename, vars)
334 with open(outfilename, 'w') as file:
335 file.write(txt)
336
337
338 def write_tmp_file(txt):
339 fd = tempfile.NamedTemporaryFile('w+')
340 fd.write(txt)
341 fd.flush()
342
343 return fd
344
345
346 def flush_sync(f):
347 """Flush and fsync file to disk
348
349 :param f: a file object with fileno and name
350 """
351 # flush file buffer to file descriptor
352 f.flush()
353 # flush Kernel buffer to disk
354 os.fsync(f.fileno())
355 # sync metadata in directory
356 dirname = os.path.dirname(os.path.abspath(f.name))
357 dirfd = os.open(dirname, os.O_RDONLY | os.O_DIRECTORY)
358 try:
359 os.fsync(dirfd)
360 finally:
361 os.close(dirfd)
362
363
364 def shell_quote(string):
365 if isinstance(string, str):
366 return "'" + string.replace("'", "'\\''") + "'"
367 else:
368 return b"'" + string.replace(b"'", b"'\\''") + b"'"
369
370
371 class _RunResult(collections.namedtuple('_RunResult',
372 'output error_output returncode')):
373 """Result of ipautil.run"""
374
375
376 class CalledProcessError(subprocess.CalledProcessError):
377 """CalledProcessError with stderr
378
379 Hold stderr of failed call and print it in repr() to simplify debugging.
380 """
381 def __init__(self, returncode, cmd, output=None, stderr=None):
382 super(CalledProcessError, self).__init__(returncode, cmd, output)
383 self.stderr = stderr
384
385 def __str__(self):
386 args = [
387 self.__class__.__name__, '('
388 'Command {!s} '.format(self.cmd),
389 'returned non-zero exit status {!r}'.format(self.returncode)
390 ]
391 if self.stderr is not None:
392 args.append(': {!r}'.format(self.stderr))
393 args.append(')')
394 return ''.join(args)
395
396 __repr__ = __str__
397
398
399 def run(args, stdin=None, raiseonerr=True, nolog=(), env=None,
400 capture_output=False, skip_output=False, cwd=None,
401 runas=None, suplementary_groups=(),
402 capture_error=False, encoding=None, redirect_output=False,
403 umask=None, nolog_output=False, nolog_error=False):
404 """
405 Execute an external command.
406
407 :param args: List of arguments for the command
408 :param stdin: Optional input to the command
409 :param raiseonerr: If True, raises an exception if the return code is
410 not zero
411 :param nolog: Tuple of strings that shouldn't be logged, like passwords.
412 Each tuple consists of a string to be replaced by XXXXXXXX.
413
414 Example:
415 We have a command
416 ['/usr/bin/setpasswd', '--password', 'Secret123', 'someuser']
417 and we don't want to log the password so nolog would be set to:
418 ('Secret123',)
419 The resulting log output would be:
420
421 /usr/bin/setpasswd --password XXXXXXXX someuser
422
423 If a value isn't found in the list it is silently ignored.
424 :param env: Dictionary of environment variables passed to the command.
425 When None, current environment is copied
426 :param capture_output: Capture stdout
427 :param skip_output: Redirect the output to /dev/null and do not log it
428 :param cwd: Current working directory
429 :param runas: Name or User object of a user that the command should be
430 run as. The spawned process will have both real and effective UID and
431 GID set.
432 :param suplementary_groups: List of group names or Group object that will
433 be used as suplementary groups for subporcess. The option runas must
434 be specified together with this option.
435 :param capture_error: Capture stderr
436 :param nolog_output: do not log stdout even if it is being captured
437 :param nolog_error: do not log stderr even if it is being captured
438 :param encoding: For Python 3, the encoding to use for output,
439 error_output, and (if it's not bytes) stdin.
440 If None, the current encoding according to locale is used.
441 :param redirect_output: Redirect (error) output to standard (error) output.
442 :param umask: Set file-creation mask before running the command.
443
444 :return: An object with these attributes:
445
446 `returncode`: The process' exit status
447
448 `output` and `error_output`: captured output, as strings. Under
449 Python 3, these are encoded with the given `encoding`.
450 None unless `capture_output` or `capture_error`, respectively, are
451 given
452
453 `raw_output`, `raw_error_output`: captured output, as bytes.
454
455 `output_log` and `error_log`: The captured output, as strings, with any
456 unencodable characters discarded. These should only be used
457 for logging or error messages.
458
459 If skip_output is given, all output-related attributes on the result
460 (that is, all except `returncode`) are None.
461
462 For backwards compatibility, the return value can also be used as a
463 (output, error_output, returncode) triple.
464 """
465 assert isinstance(suplementary_groups, (tuple, list))
466 p_in = None
467 p_out = None
468 p_err = None
469
470 if isinstance(nolog, str):
471 # We expect a tuple (or list, or other iterable) of nolog strings.
472 # Passing just a single string is bad: strings are iterable, so this
473 # would result in every individual character of that string being
474 # replaced by XXXXXXXX.
475 # This is a sanity check to prevent that.
476 raise ValueError('nolog must be a tuple of strings.')
477
478 if skip_output and (capture_output or capture_error):
479 raise ValueError('skip_output is incompatible with '
480 'capture_output or capture_error')
481
482 if redirect_output and (capture_output or capture_error):
483 raise ValueError('redirect_output is incompatible with '
484 'capture_output or capture_error')
485
486 if skip_output and redirect_output:
487 raise ValueError('skip_output is incompatible with redirect_output')
488
489 if env is None:
490 # copy default env
491 env = copy.deepcopy(os.environ)
492 env["PATH"] = "/bin:/sbin:/usr/kerberos/bin:/usr/kerberos/sbin:/usr/bin:/usr/sbin"
493 if stdin:
494 p_in = subprocess.PIPE
495 if skip_output:
496 p_out = p_err = open(os.devnull, 'w')
497 elif redirect_output:
498 p_out = sys.stdout
499 p_err = sys.stderr
500 else:
501 p_out = subprocess.PIPE
502 p_err = subprocess.PIPE
503
504 if encoding is None:
505 encoding = locale.getpreferredencoding()
506
507 if six.PY3 and isinstance(stdin, str):
508 stdin = stdin.encode(encoding)
509
510 arg_string = nolog_replace(repr(args), nolog)
511 logger.debug('Starting external process')
512 logger.debug('args=%s', arg_string)
513
514 if runas is not None:
515 runas = User(runas)
516 suplementary_groups = [Group(group) for group in suplementary_groups]
517 suplementary_gids = [group.gid for group in suplementary_groups]
518
519 logger.debug(
520 'runas=%s (UID %d, GID %s)', runas, runas.uid, runas.pgid
521 )
522 if suplementary_groups:
523 for group in suplementary_groups:
524 logger.debug(
525 'supplementary_group=%s (GID %d)', group, group.gid
526 )
527
528 if runas is not None or umask is not None:
529 # preexec function is not supported in WSGI environment
530 def preexec_fn():
531 if runas is not None:
532 os.setgroups(suplementary_gids)
533 os.setregid(runas.pgid, runas.pgid)
534 os.setreuid(runas.uid, runas.uid)
535
536 if umask is not None:
537 os.umask(umask)
538 else:
539 preexec_fn = None
540
541 try:
542 # pylint: disable=subprocess-popen-preexec-fn
543 p = subprocess.Popen(args, stdin=p_in, stdout=p_out, stderr=p_err,
544 close_fds=True, env=env, cwd=cwd,
545 preexec_fn=preexec_fn)
546 stdout, stderr = p.communicate(stdin)
547 except KeyboardInterrupt:
548 logger.debug('Process interrupted')
549 p.wait()
550 raise
551 except BaseException:
552 logger.debug('Process execution failed')
553 raise
554 finally:
555 if skip_output:
556 p_out.close()
557
558 logger.debug('Process finished, return code=%s', p.returncode)
559
560 # The command and its output may include passwords that we don't want
561 # to log. Replace those.
562 if skip_output or redirect_output:
563 output_log = None
564 error_log = None
565 else:
566 if six.PY3:
567 output_log = stdout.decode(locale.getpreferredencoding(),
568 errors='replace')
569 else:
570 output_log = stdout
571
572 if six.PY3:
573 error_log = stderr.decode(locale.getpreferredencoding(),
574 errors='replace')
575 else:
576 error_log = stderr
577
578 output_log = nolog_replace(output_log, nolog)
579 if nolog_output:
580 logger.debug('stdout=<REDACTED>')
581 else:
582 logger.debug('stdout=%s', output_log)
583
584 error_log = nolog_replace(error_log, nolog)
585 if nolog_error:
586 logger.debug('stderr=<REDACTED>')
587 else:
588 logger.debug('stderr=%s', error_log)
589
590 if capture_output:
591 if six.PY2:
592 output = stdout
593 else:
594 output = stdout.decode(encoding)
595 else:
596 output = None
597
598 if capture_error:
599 if six.PY2:
600 error_output = stderr
601 else:
602 error_output = stderr.decode(encoding)
603 else:
604 error_output = None
605
606 if p.returncode != 0 and raiseonerr:
607 raise CalledProcessError(
608 p.returncode, arg_string, output_log, error_log
609 )
610
611 result = _RunResult(output, error_output, p.returncode)
612 result.raw_output = stdout
613 result.raw_error_output = stderr
614 result.output_log = output_log
615 result.error_log = error_log
616 return result
617
618
619 def nolog_replace(string, nolog):
620 """Replace occurences of strings given in `nolog` with XXXXXXXX"""
621 for value in nolog:
622 if not value or not isinstance(value, str):
623 continue
624
625 quoted = urllib.parse.quote(value)
626 shquoted = shell_quote(value)
627 for nolog_value in (shquoted, value, quoted):
628 string = string.replace(nolog_value, 'XXXXXXXX')
629 return string
630
631
632 def install_file(fname, dest):
633 # SELinux: use copy to keep the right context
634 if os.path.isfile(dest):
635 os.rename(dest, dest + ".orig")
636 shutil.copy(fname, dest)
637 os.remove(fname)
638
639
640 def backup_file(fname):
641 if os.path.isfile(fname):
642 os.rename(fname, fname + ".orig")
643
644
645 class CIDict(dict):
646 """
647 Case-insensitive but case-respecting dictionary.
648
649 This code is derived from python-ldap's cidict.py module,
650 written by stroeder: http://python-ldap.sourceforge.net/
651
652 This version extends 'dict' so it works properly with TurboGears.
653 If you extend UserDict, isinstance(foo, dict) returns false.
654 """
655
656 def __init__(self, default=None, **kwargs):
657 super(CIDict, self).__init__()
658 self._keys = {} # mapping of lowercased keys to proper case
659 if default:
660 self.update(default)
661 if kwargs:
662 self.update(kwargs)
663
664 def __getitem__(self, key):
665 return super(CIDict, self).__getitem__(key.lower())
666
667 def __setitem__(self, key, value, seen_keys=None):
668 """cidict[key] = value
669
670 The ``seen_keys`` argument is used by ``update()`` to keep track of
671 duplicate keys. It should be an initially empty set that is
672 passed to all calls to __setitem__ that should not set duplicate keys.
673 """
674 lower_key = key.lower()
675 if seen_keys is not None:
676 if lower_key in seen_keys:
677 raise ValueError('Duplicate key in update: %s' % key)
678 seen_keys.add(lower_key)
679 self._keys[lower_key] = key
680 return super(CIDict, self).__setitem__(lower_key, value)
681
682 def __delitem__(self, key):
683 lower_key = key.lower()
684 del self._keys[lower_key]
685 return super(CIDict, self).__delitem__(lower_key)
686
687 def update(self, new=None, **kwargs):
688 """Update self from dict/iterable new and kwargs
689
690 Functions like ``dict.update()``.
691
692 Neither ``new`` nor ``kwargs`` may contain two keys that only differ in
693 case, as this situation would result in loss of data.
694 """
695 seen = set()
696 if new:
697 try:
698 keys = new.keys
699 except AttributeError:
700 self.update(dict(new))
701 else:
702 for key in keys():
703 # pylint: disable=unnecessary-dunder-call
704 self.__setitem__(key, new[key], seen)
705 seen = set()
706 for key, value in kwargs.items():
707 # pylint: disable=unnecessary-dunder-call
708 self.__setitem__(key, value, seen)
709
710 def __contains__(self, key):
711 return super(CIDict, self).__contains__(key.lower())
712
713 if six.PY2:
714 def has_key(self, key):
715 # pylint: disable=no-member
716 return super(CIDict, self).has_key(key.lower()) # noqa
717 # pylint: enable=no-member
718
719 def get(self, key, failobj=None):
720 try:
721 return self[key]
722 except KeyError:
723 return failobj
724
725 def __iter__(self):
726 return six.itervalues(self._keys)
727
728 def keys(self):
729 if six.PY2:
730 return list(self.iterkeys())
731 else:
732 return self.iterkeys()
733
734 def items(self):
735 if six.PY2:
736 return list(self.iteritems())
737 else:
738 return self.iteritems()
739
740 def values(self):
741 if six.PY2:
742 return list(self.itervalues())
743 else:
744 return self.itervalues()
745
746 def copy(self):
747 """Returns a shallow copy of this CIDict"""
748 return CIDict(list(self.items()))
749
750 def iteritems(self):
751 return ((k, self[k]) for k in six.itervalues(self._keys))
752
753 def iterkeys(self):
754 return six.itervalues(self._keys)
755
756 def itervalues(self):
757 return (v for k, v in six.iteritems(self))
758
759 def setdefault(self, key, value=None):
760 try:
761 return self[key]
762 except KeyError:
763 self[key] = value
764 return value
765
766 def pop(self, key, *args):
767 try:
768 value = self[key]
769 del self[key]
770 return value
771 except KeyError:
772 if len(args) == 1:
773 return args[0]
774 raise
775
776 def popitem(self):
777 (lower_key, value) = super(CIDict, self).popitem()
778 key = self._keys[lower_key]
779 del self._keys[lower_key]
780
781 return (key, value)
782
783 def clear(self):
784 self._keys.clear()
785 return super(CIDict, self).clear()
786
787 def viewitems(self):
788 raise NotImplementedError('CIDict.viewitems is not implemented')
789
790 def viewkeys(self):
791 raise NotImplementedError('CIDict.viewkeys is not implemented')
792
793 def viewvvalues(self):
794 raise NotImplementedError('CIDict.viewvvalues is not implemented')
795
796
797 class GeneralizedTimeZone(datetime.tzinfo):
798 """This class is a basic timezone wrapper for the offset specified
799 in a Generalized Time. It is dst-ignorant."""
800 def __init__(self,offsetstr="Z"):
801 super(GeneralizedTimeZone, self).__init__()
802
803 self.name = offsetstr
804 self.houroffset = 0
805 self.minoffset = 0
806
807 if offsetstr == "Z":
808 self.houroffset = 0
809 self.minoffset = 0
810 else:
811 if (len(offsetstr) >= 3) and re.match(r'[-+]\d\d', offsetstr):
812 self.houroffset = int(offsetstr[0:3])
813 offsetstr = offsetstr[3:]
814 if (len(offsetstr) >= 2) and re.match(r'\d\d', offsetstr):
815 self.minoffset = int(offsetstr[0:2])
816 offsetstr = offsetstr[2:]
817 if len(offsetstr) > 0:
818 raise ValueError()
819 if self.houroffset < 0:
820 self.minoffset *= -1
821
822 def utcoffset(self, dt):
823 return datetime.timedelta(hours=self.houroffset, minutes=self.minoffset)
824
825 def dst(self):
826 return datetime.timedelta(0)
827
828 def tzname(self):
829 return self.name
830
831
832 def parse_generalized_time(timestr):
833 """Parses are Generalized Time string (as specified in X.680),
834 returning a datetime object. Generalized Times are stored inside
835 the krbPasswordExpiration attribute in LDAP.
836
837 This method doesn't attempt to be perfect wrt timezones. If python
838 can't be bothered to implement them, how can we..."""
839
840 if len(timestr) < 8:
841 return None
842 try:
843 date = timestr[:8]
844 time = timestr[8:]
845
846 year = int(date[:4])
847 month = int(date[4:6])
848 day = int(date[6:8])
849
850 hour = min = sec = msec = 0
851 tzone = None
852
853 if (len(time) >= 2) and re.match(r'\d', time[0]):
854 hour = int(time[:2])
855 time = time[2:]
856 if len(time) >= 2 and (time[0] == "," or time[0] == "."):
857 hour_fraction = "."
858 time = time[1:]
859 while (len(time) > 0) and re.match(r'\d', time[0]):
860 hour_fraction += time[0]
861 time = time[1:]
862 total_secs = int(float(hour_fraction) * 3600)
863 min, sec = divmod(total_secs, 60)
864
865 if (len(time) >= 2) and re.match(r'\d', time[0]):
866 min = int(time[:2])
867 time = time[2:]
868 if len(time) >= 2 and (time[0] == "," or time[0] == "."):
869 min_fraction = "."
870 time = time[1:]
871 while (len(time) > 0) and re.match(r'\d', time[0]):
872 min_fraction += time[0]
873 time = time[1:]
874 sec = int(float(min_fraction) * 60)
875
876 if (len(time) >= 2) and re.match(r'\d', time[0]):
877 sec = int(time[:2])
878 time = time[2:]
879 if len(time) >= 2 and (time[0] == "," or time[0] == "."):
880 sec_fraction = "."
881 time = time[1:]
882 while (len(time) > 0) and re.match(r'\d', time[0]):
883 sec_fraction += time[0]
884 time = time[1:]
885 msec = int(float(sec_fraction) * 1000000)
886
887 if (len(time) > 0):
888 tzone = GeneralizedTimeZone(time)
889
890 return datetime.datetime(year, month, day, hour, min, sec, msec, tzone)
891
892 except ValueError:
893 return None
894
895
896 def ipa_generate_password(entropy_bits=256, uppercase=1, lowercase=1, digits=1,
897 special=1, min_len=0):
898 """
899 Generate token containing at least `entropy_bits` bits and with the given
900 character restraints.
901
902 :param entropy_bits:
903 The minimal number of entropy bits attacker has to guess:
904 128 bits entropy: secure
905 256 bits of entropy: secure enough if you care about quantum
906 computers
907
908 Integer values specify minimal number of characters from given
909 character class and length.
910 Value None prevents given character from appearing in the token.
911
912 Example:
913 TokenGenerator(uppercase=3, lowercase=3, digits=0, special=None)
914
915 At least 3 upper and 3 lower case ASCII chars, may contain digits,
916 no special chars.
917 """
918 special_chars = '!$%&()*+,-./:;<>?@[]^_{|}~'
919 pwd_charsets = {
920 'uppercase': {
921 'chars': string.ascii_uppercase,
922 'entropy': math.log(len(string.ascii_uppercase), 2)
923 },
924 'lowercase': {
925 'chars': string.ascii_lowercase,
926 'entropy': math.log(len(string.ascii_lowercase), 2)
927 },
928 'digits': {
929 'chars': string.digits,
930 'entropy': math.log(len(string.digits), 2)
931 },
932 'special': {
933 'chars': special_chars,
934 'entropy': math.log(len(special_chars), 2)
935 },
936 }
937 req_classes = dict(
938 uppercase=uppercase,
939 lowercase=lowercase,
940 digits=digits,
941 special=special
942 )
943 # 'all' class is used when adding entropy to too-short tokens
944 # it contains characters from all allowed classes
945 pwd_charsets['all'] = {
946 'chars': ''.join([
947 charclass['chars'] for charclass_name, charclass
948 in pwd_charsets.items()
949 if req_classes[charclass_name] is not None
950 ])
951 }
952 pwd_charsets['all']['entropy'] = math.log(
953 len(pwd_charsets['all']['chars']), 2)
954 rnd = random.SystemRandom()
955
956 todo_entropy = entropy_bits
957 password = u''
958 # Generate required character classes:
959 # The order of generated characters is fixed to comply with check in
960 # NSS function sftk_newPinCheck() in nss/lib/softoken/fipstokn.c.
961 for charclass_name in ['digits', 'uppercase', 'lowercase', 'special']:
962 charclass = pwd_charsets[charclass_name]
963 todo_characters = req_classes[charclass_name]
964 if todo_characters is None:
965 continue
966 while todo_characters > 0:
967 password += rnd.choice(charclass['chars'])
968 todo_entropy -= charclass['entropy']
969 todo_characters -= 1
970
971 # required character classes do not provide sufficient entropy
972 # or does not fulfill minimal length constraint
973 allchars = pwd_charsets['all']
974 while todo_entropy > 0 or len(password) < min_len:
975 password += rnd.choice(allchars['chars'])
976 todo_entropy -= allchars['entropy']
977
978 return password
979
980
981 def user_input(prompt, default = None, allow_empty = True):
982 if default is None:
983 while True:
984 try:
985 ret = input("%s: " % prompt)
986 if allow_empty or ret.strip():
987 return ret.strip()
988 except EOFError:
989 if allow_empty:
990 return ''
991 raise RuntimeError("Failed to get user input")
992
993 if isinstance(default, str):
994 while True:
995 try:
996 ret = input("%s [%s]: " % (prompt, default))
997 if not ret and (allow_empty or default):
998 return default
999 elif ret.strip():
1000 return ret.strip()
1001 except EOFError:
1002 return default
1003
1004 if isinstance(default, bool):
1005 choice = "yes" if default else "no"
1006 while True:
1007 try:
1008 ret = input("%s [%s]: " % (prompt, choice))
1009 ret = ret.strip()
1010 if not ret:
1011 return default
1012 elif ret.lower()[0] == "y":
1013 return True
1014 elif ret.lower()[0] == "n":
1015 return False
1016 except EOFError:
1017 return default
1018
1019 if isinstance(default, int):
1020 while True:
1021 try:
1022 ret = input("%s [%s]: " % (prompt, default))
1023 ret = ret.strip()
1024 if not ret:
1025 return default
1026 ret = int(ret)
1027 except ValueError:
1028 pass
1029 except EOFError:
1030 return default
1031 else:
1032 return ret
1033
1034 return None
1035
1036
1037 def host_port_open(host, port, socket_type=socket.SOCK_STREAM,
1038 socket_timeout=None, log_errors=False,
1039 log_level=logging.DEBUG):
1040 """
1041 host: either hostname or IP address;
1042 if hostname is provided, port MUST be open on ALL resolved IPs
1043
1044 returns True is port is open, False otherwise
1045 """
1046 port_open = True
1047
1048 # port has to be open on ALL resolved IPs
1049 for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type):
1050 af, socktype, proto, _canonname, sa = res
1051 s = None
1052 try:
1053 s = socket.socket(af, socktype, proto)
1054
1055 if socket_timeout is not None:
1056 s.settimeout(socket_timeout)
1057
1058 s.connect(sa)
1059
1060 if socket_type == socket.SOCK_DGRAM:
1061 s.send(b'')
1062 s.recv(512)
1063 except socket.error:
1064 port_open = False
1065 if log_errors:
1066 msg = ('Failed to connect to port %(port)s %(proto)s on '
1067 '%(addr)s' % dict(port=port,
1068 proto=PROTOCOL_NAMES[socket_type],
1069 addr=sa[0]))
1070 logger.log(log_level, msg)
1071 finally:
1072 if s is not None:
1073 s.close()
1074
1075 return port_open
1076
1077
1078 def check_port_bindable(port, socket_type=socket.SOCK_STREAM):
1079 """Check if a port is free and not bound by any other application
1080
1081 :param port: port number
1082 :param socket_type: type (SOCK_STREAM for TCP, SOCK_DGRAM for UDP)
1083
1084 Returns True if the port is free, False otherwise
1085 """
1086 if socket_type == socket.SOCK_STREAM:
1087 proto = 'TCP'
1088 elif socket_type == socket.SOCK_DGRAM:
1089 proto = 'UDP'
1090 else:
1091 raise ValueError(socket_type)
1092
1093 # Detect dual stack or IPv4 single stack
1094 try:
1095 s = socket.socket(socket.AF_INET6, socket_type)
1096 anyaddr = '::'
1097 logger.debug(
1098 "check_port_bindable: Checking IPv4/IPv6 dual stack and %s",
1099 proto
1100 )
1101 except socket.error:
1102 s = socket.socket(socket.AF_INET, socket_type)
1103 anyaddr = ''
1104 logger.debug("check_port_bindable: Checking IPv4 only and %s", proto)
1105
1106 # Attempt to bind
1107 try:
1108 if socket_type == socket.SOCK_STREAM:
1109 # reuse TCP sockets in TIME_WAIT state
1110 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1111 s.bind((anyaddr, port))
1112 except socket.error as e:
1113 logger.debug(
1114 "check_port_bindable: failed to bind to port %i/%s: %s",
1115 port, proto, e
1116 )
1117 return False
1118 else:
1119 logger.debug(
1120 "check_port_bindable: bind success: %i/%s", port, proto
1121 )
1122 return True
1123 finally:
1124 s.close()
1125
1126
1127 def config_replace_variables(filepath, replacevars=dict(), appendvars=dict(),
1128 removevars=None):
1129 """
1130 Take a key=value based configuration file, and write new version
1131 with certain values replaced, appended, or removed.
1132
1133 All (key,value) pairs from replacevars and appendvars that were not found
1134 in the configuration file, will be added there.
1135
1136 All entries in set removevars are removed.
1137
1138 It is responsibility of a caller to ensure that replacevars and
1139 appendvars do not overlap.
1140
1141 It is responsibility of a caller to back up file.
1142
1143 returns dictionary of affected keys and their previous values
1144
1145 One have to run restore_context(filepath) afterwards or
1146 security context of the file will not be correct after modification
1147 """
1148 pattern = re.compile(r'''
1149 (^
1150 \s*
1151 (?P<option> [^\#;]+?)
1152 (\s*=\s*)
1153 (?P<value> .+?)?
1154 (\s*((\#|;).*)?)?
1155 $)''', re.VERBOSE)
1156 orig_stat = os.stat(filepath)
1157 old_values = dict()
1158 temp_filename = None
1159 with tempfile.NamedTemporaryFile(mode="w", delete=False) as new_config:
1160 temp_filename = new_config.name
1161 with open(filepath, 'r') as f:
1162 for line in f:
1163 new_line = line
1164 m = pattern.match(line)
1165 if m:
1166 option, value = m.group('option', 'value')
1167 if option is not None:
1168 if replacevars and option in replacevars:
1169 # replace value completely
1170 new_line = u"%s=%s\n" % (option, replacevars[option])
1171 old_values[option] = value
1172 if appendvars and option in appendvars:
1173 # append new value unless it is already existing in the original one
1174 if not value:
1175 new_line = u"%s=%s\n" % (option, appendvars[option])
1176 elif value.find(appendvars[option]) == -1:
1177 new_line = u"%s=%s %s\n" % (option, value, appendvars[option])
1178 old_values[option] = value
1179 if removevars and option in removevars:
1180 old_values[option] = value
1181 new_line = None
1182 if new_line is not None:
1183 new_config.write(new_line)
1184 # Now add all options from replacevars and appendvars that were not found in the file
1185 new_vars = replacevars.copy()
1186 new_vars.update(appendvars)
1187 newvars_view = set(new_vars.keys()) - set(old_values.keys())
1188 append_view = (set(appendvars.keys()) - newvars_view)
1189 for item in newvars_view:
1190 new_config.write("%s=%s\n" % (item,new_vars[item]))
1191 for item in append_view:
1192 new_config.write("%s=%s\n" % (item,appendvars[item]))
1193 new_config.flush()
1194 # Make sure the resulting file is readable by others before installing it
1195 os.fchmod(new_config.fileno(), orig_stat.st_mode)
1196 os.fchown(new_config.fileno(), orig_stat.st_uid, orig_stat.st_gid)
1197
1198 # At this point new_config is closed but not removed due to 'delete=False' above
1199 # Now, install the temporary file as configuration and ensure old version is available as .orig
1200 # While .orig file is not used during uninstall, it is left there for administrator.
1201 install_file(temp_filename, filepath)
1202
1203 return old_values
1204
1205 def inifile_replace_variables(filepath, section, replacevars=dict(), appendvars=dict()):
1206 """
1207 Take a section-structured key=value based configuration file, and write new version
1208 with certain values replaced or appended within the section
1209
1210 All (key,value) pairs from replacevars and appendvars that were not found
1211 in the configuration file, will be added there.
1212
1213 It is responsibility of a caller to ensure that replacevars and
1214 appendvars do not overlap.
1215
1216 It is responsibility of a caller to back up file.
1217
1218 returns dictionary of affected keys and their previous values
1219
1220 One have to run restore_context(filepath) afterwards or
1221 security context of the file will not be correct after modification
1222 """
1223 pattern = re.compile(r'''
1224 (^
1225 \[
1226 (?P<section> .+) \]
1227 (\s+((\#|;).*)?)?
1228 $)|(^
1229 \s*
1230 (?P<option> [^\#;]+?)
1231 (\s*=\s*)
1232 (?P<value> .+?)?
1233 (\s*((\#|;).*)?)?
1234 $)''', re.VERBOSE)
1235 def add_options(config, replacevars, appendvars, oldvars):
1236 # add all options from replacevars and appendvars that were not found in the file
1237 new_vars = replacevars.copy()
1238 new_vars.update(appendvars)
1239 newvars_view = set(new_vars.keys()) - set(oldvars.keys())
1240 append_view = (set(appendvars.keys()) - newvars_view)
1241 for item in newvars_view:
1242 config.write("%s=%s\n" % (item,new_vars[item]))
1243 for item in append_view:
1244 config.write("%s=%s\n" % (item,appendvars[item]))
1245
1246 orig_stat = os.stat(filepath)
1247 old_values = dict()
1248 temp_filename = None
1249 with tempfile.NamedTemporaryFile(mode='w', delete=False) as new_config:
1250 temp_filename = new_config.name
1251 with open(filepath, 'r') as f:
1252 in_section = False
1253 finished = False
1254 line_idx = 1
1255 for line in f:
1256 line_idx = line_idx + 1
1257 new_line = line
1258 m = pattern.match(line)
1259 if m:
1260 sect, option, value = m.group('section', 'option', 'value')
1261 if in_section and sect is not None:
1262 # End of the searched section, add remaining options
1263 add_options(new_config, replacevars, appendvars, old_values)
1264 finished = True
1265 if sect is not None:
1266 # New section is found, check whether it is the one we are looking for
1267 in_section = (str(sect).lower() == str(section).lower())
1268 if option is not None and in_section:
1269 # Great, this is an option from the section we are loking for
1270 if replacevars and option in replacevars:
1271 # replace value completely
1272 new_line = u"%s=%s\n" % (option, replacevars[option])
1273 old_values[option] = value
1274 if appendvars and option in appendvars:
1275 # append a new value unless it is already existing in the original one
1276 if not value:
1277 new_line = u"%s=%s\n" % (option, appendvars[option])
1278 elif value.find(appendvars[option]) == -1:
1279 new_line = u"%s=%s %s\n" % (option, value, appendvars[option])
1280 old_values[option] = value
1281 new_config.write(new_line)
1282 # We have finished parsing the original file.
1283 # There are two remaining cases:
1284 # 1. Section we were looking for was not found, we need to add it.
1285 if not (in_section or finished):
1286 new_config.write("[%s]\n" % (section))
1287 # 2. The section is the last one but some options were not found, add them.
1288 if in_section or not finished:
1289 add_options(new_config, replacevars, appendvars, old_values)
1290
1291 new_config.flush()
1292 # Make sure the resulting file is readable by others before installing it
1293 os.fchmod(new_config.fileno(), orig_stat.st_mode)
1294 os.fchown(new_config.fileno(), orig_stat.st_uid, orig_stat.st_gid)
1295
1296 # At this point new_config is closed but not removed due to 'delete=False' above
1297 # Now, install the temporary file as configuration and ensure old version is available as .orig
1298 # While .orig file is not used during uninstall, it is left there for administrator.
1299 install_file(temp_filename, filepath)
1300
1301 return old_values
1302
1303 def backup_config_and_replace_variables(
1304 fstore, filepath, replacevars=dict(), appendvars=dict()):
1305 """
1306 Take a key=value based configuration file, back up it, and
1307 write new version with certain values replaced or appended
1308
1309 All (key,value) pairs from replacevars and appendvars that
1310 were not found in the configuration file, will be added there.
1311 The file must exist before this function is called.
1312
1313 It is responsibility of a caller to ensure that replacevars and
1314 appendvars do not overlap.
1315
1316 returns dictionary of affected keys and their previous values
1317
1318 One have to run restore_context(filepath) afterwards or
1319 security context of the file will not be correct after modification
1320 """
1321 # Backup original filepath
1322 fstore.backup_file(filepath)
1323 old_values = config_replace_variables(filepath, replacevars, appendvars)
1324
1325 return old_values
1326
1327
1328 def wait_for_open_ports(host, ports, timeout=0):
1329 """
1330 Wait until the specified port(s) on the remote host are open. Timeout
1331 in seconds may be specified to limit the wait. If the timeout is
1332 exceeded, socket.timeout exception is raised.
1333 """
1334 timeout = float(timeout)
1335 if not isinstance(ports, (tuple, list)):
1336 ports = [ports]
1337
1338 logger.debug('wait_for_open_ports: %s %s timeout %d', host, ports, timeout)
1339 op_timeout = time.time() + timeout
1340
1341 for port in ports:
1342 logger.debug('waiting for port: %s', port)
1343 log_error = True
1344 while True:
1345 port_open = host_port_open(host, port, log_errors=log_error)
1346 log_error = False # Log only first err so that the log is readable
1347
1348 if port_open:
1349 logger.debug('SUCCESS: port: %s', port)
1350 break
1351 if timeout and time.time() > op_timeout: # timeout exceeded
1352 raise socket.timeout("Timeout exceeded")
1353 time.sleep(1)
1354
1355
1356 def wait_for_open_socket(socket_name, timeout=0):
1357 """
1358 Wait until the specified socket on the local host is open. Timeout
1359 in seconds may be specified to limit the wait.
1360 """
1361 timeout = float(timeout)
1362 op_timeout = time.time() + timeout
1363
1364 while True:
1365 try:
1366 s = socket.socket(socket.AF_UNIX)
1367 s.connect(socket_name)
1368 s.close()
1369 break
1370 except socket.error as e:
1371 if e.errno in (2,111): # 111: Connection refused, 2: File not found
1372 if timeout and time.time() > op_timeout: # timeout exceeded
1373 raise e
1374 time.sleep(1)
1375 else:
1376 raise e
1377
1378
1379 def dn_attribute_property(private_name):
1380 '''
1381 Create a property for a dn attribute which assures the attribute
1382 is a DN or None. If the value is not None the setter converts it to
1383 a DN. The getter assures it's either None or a DN instance.
1384
1385 The private_name parameter is the class internal attribute the property
1386 shadows.
1387
1388 For example if a class has an attribute called base_dn, then:
1389
1390 base_dn = dn_attribute_property('_base_dn')
1391
1392 Thus the class with have an attriubte called base_dn which can only
1393 ever be None or a DN instance. The actual value is stored in _base_dn.
1394 '''
1395
1396 def setter(self, value):
1397 if value is not None:
1398 value = DN(value)
1399 setattr(self, private_name, value)
1400
1401 def getter(self):
1402 value = getattr(self, private_name)
1403 if value is not None:
1404 assert isinstance(value, DN)
1405 return value
1406
1407 return property(getter, setter)
1408
1409 def posixify(string):
1410 """
1411 Convert a string to a more strict alpha-numeric representation.
1412
1413 - Alpha-numeric, underscore, dot and dash characters are accepted
1414 - Space is converted to underscore
1415 - Other characters are omitted
1416 - Leading dash is stripped
1417
1418 Note: This mapping is not one-to-one and may map different input to the
1419 same result. When using posixify, make sure the you do not map two different
1420 entities to one unintentionally.
1421 """
1422
1423 def valid_char(char):
1424 return char.isalnum() or char in ('_', '.', '-')
1425
1426 # First replace space characters
1427 replaced = string.replace(' ','_')
1428 omitted = ''.join(filter(valid_char, replaced))
1429
1430 # Leading dash is not allowed
1431 return omitted.lstrip('-')
1432
1433 @contextmanager
1434 def private_ccache(path=None):
1435
1436 if path is None:
1437 dir_path = tempfile.mkdtemp(prefix='krbcc')
1438 path = os.path.join(dir_path, 'ccache')
1439 else:
1440 dir_path = None
1441
1442 original_value = os.environ.get('KRB5CCNAME', None)
1443
1444 os.environ['KRB5CCNAME'] = path
1445
1446 try:
1447 yield path
1448 finally:
1449 if original_value is not None:
1450 os.environ['KRB5CCNAME'] = original_value
1451 else:
1452 os.environ.pop('KRB5CCNAME', None)
1453
1454 if os.path.exists(path):
1455 os.remove(path)
1456 if dir_path is not None:
1457 try:
1458 os.rmdir(dir_path)
1459 except OSError:
1460 pass
1461
1462
1463 @contextmanager
1464 def private_krb5_config(realm, server, dir="/run/ipa"):
1465 """Generate override krb5 config file for a trusted domain DC access
1466 Provide a context where environment variable KRB5_CONFIG is set
1467 with the overlay on top of paths.KRB5_CONF. Overlay's file path
1468 is passed to the context in case it is needed for something else
1469
1470 :param realm: realm of the trusted AD domain
1471 :param server: server to override KDC to
1472 :param dir: path where to create a temporary krb5.conf overlay
1473 """
1474 cfg = paths.KRB5_CONF
1475 tcfg = None
1476 if server:
1477 content = textwrap.dedent(u"""
1478 [realms]
1479 %s = {
1480 kdc = %s
1481 }
1482 """) % (
1483 realm.upper(),
1484 server,
1485 )
1486
1487 (fd, tcfg) = tempfile.mkstemp(dir=dir, prefix="krb5conf", text=True)
1488
1489 with io.open(fd, mode='w', encoding='utf-8') as o:
1490 o.write(content)
1491 cfg = ":".join([tcfg, cfg])
1492
1493 original_value = os.environ.get('KRB5_CONFIG', None)
1494
1495 os.environ['KRB5_CONFIG'] = cfg
1496
1497 try:
1498 yield tcfg
1499 except GeneratorExit:
1500 pass
1501 finally:
1502 if original_value is not None:
1503 os.environ['KRB5_CONFIG'] = original_value
1504 else:
1505 os.environ.pop('KRB5_CONFIG', None)
1506
1507 if tcfg is not None and os.path.exists(tcfg):
1508 os.remove(tcfg)
1509
1510
1511 if six.PY2:
1512 def fsdecode(value):
1513 """
1514 Decode argument using the file system encoding, as returned by
1515 `sys.getfilesystemencoding()`.
1516 """
1517 if isinstance(value, bytes):
1518 return value.decode(sys.getfilesystemencoding())
1519 elif isinstance(value, str):
1520 return value
1521 else:
1522 raise TypeError("expect {0} or {1}, not {2}".format(
1523 bytes.__name__,
1524 str.__name__,
1525 type(value).__name__))
1526 else:
1527 fsdecode = os.fsdecode
1528
1529
1530 def unescape_seq(seq, *args):
1531 """
1532 unescape (remove '\\') all occurences of sequence in input strings.
1533
1534 :param seq: sequence to unescape
1535 :param args: input string to process
1536
1537 :returns: tuple of strings with unescaped sequences
1538 """
1539 unescape_re = re.compile(r'\\{}'.format(seq))
1540
1541 return tuple(re.sub(unescape_re, seq, a) for a in args)
1542
1543
1544 def escape_seq(seq, *args):
1545 """
1546 escape (prepend '\\') all occurences of sequence in input strings
1547
1548 :param seq: sequence to escape
1549 :param args: input string to process
1550
1551 :returns: tuple of strings with escaped sequences
1552 """
1553
1554 return tuple(a.replace(seq, u'\\{}'.format(seq)) for a in args)
1555
1556
1557 def decode_json(data):
1558 """Decode JSON bytes to string with proper encoding
1559
1560 Only for supporting Py 3.5
1561
1562 Py 3.6 supports bytes as parameter for json.load, we can drop this when
1563 there is no need for python 3.5 anymore
1564
1565 Code from:
1566 https://bugs.python.org/file43513/json_detect_encoding_3.patch
1567
1568 :param data: JSON bytes
1569 :return: return JSON string
1570 """
1571
1572 def detect_encoding(b):
1573 bstartswith = b.startswith
1574 if bstartswith((codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE)):
1575 return 'utf-32'
1576 if bstartswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
1577 return 'utf-16'
1578 if bstartswith(codecs.BOM_UTF8):
1579 return 'utf-8-sig'
1580
1581 if len(b) >= 4:
1582 if not b[0]:
1583 # 00 00 -- -- - utf-32-be
1584 # 00 XX -- -- - utf-16-be
1585 return 'utf-16-be' if b[1] else 'utf-32-be'
1586 if not b[1]:
1587 # XX 00 00 00 - utf-32-le
1588 # XX 00 XX XX - utf-16-le
1589 return 'utf-16-le' if b[2] or b[3] else 'utf-32-le'
1590 elif len(b) == 2:
1591 if not b[0]:
1592 # 00 XX - utf-16-be
1593 return 'utf-16-be'
1594 if not b[1]:
1595 # XX 00 - utf-16-le
1596 return 'utf-16-le'
1597 # default
1598 return 'utf-8'
1599
1600 if isinstance(data, str):
1601 return data
1602
1603 return data.decode(detect_encoding(data), 'surrogatepass')
1604
1605
1606 class APIVersion(tuple):
1607 """API version parser and handler
1608
1609 The class is used to parse ipapython.version.API_VERSION and plugin
1610 versions.
1611 """
1612 __slots__ = ()
1613
1614 def __new__(cls, version):
1615 major, dot, minor = version.partition(u'.')
1616 major = int(major)
1617 minor = int(minor) if dot else 0
1618 return tuple.__new__(cls, (major, minor))
1619
1620 def __str__(self):
1621 return '{}.{}'.format(*self)
1622
1623 def __repr__(self):
1624 return "<APIVersion('{}.{}')>".format(*self)
1625
1626 def __getnewargs__(self):
1627 return (str(self),)
1628
1629 @property
1630 def major(self):
1631 return self[0]
1632
1633 @property
1634 def minor(self):
1635 return self[1]
1636
1637
1638 def remove_keytab(keytab_path):
1639 """
1640 Remove Kerberos keytab and issue a warning if the procedure fails
1641
1642 :param keytab_path: path to the keytab file
1643 """
1644 try:
1645 logger.debug("Removing service keytab: %s", keytab_path)
1646 os.remove(keytab_path)
1647 except OSError as e:
1648 if e.errno != errno.ENOENT:
1649 logger.warning("Failed to remove Kerberos keytab '%s': %s",
1650 keytab_path, e)
1651 logger.warning("You may have to remove it manually")
1652
1653
1654 def remove_ccache(ccache_path=None, run_as=None):
1655 """
1656 remove Kerberos credential cache, essentially a wrapper around kdestroy.
1657
1658 :param ccache_path: path to the ccache file
1659 :param run_as: run kdestroy as this user
1660 """
1661 logger.debug("Removing service credentials cache")
1662 kdestroy_cmd = [paths.KDESTROY]
1663 if ccache_path is not None:
1664 logger.debug("Ccache path: '%s'", ccache_path)
1665 kdestroy_cmd.extend(['-c', ccache_path])
1666
1667 try:
1668 run(kdestroy_cmd, runas=run_as, env={})
1669 except CalledProcessError as e:
1670 logger.warning(
1671 "Failed to clear Kerberos credentials cache: %s", e)
1672
1673
1674 def remove_file(filename, only_if_empty=False):
1675 """Remove a file and log any exceptions raised.
1676
1677 :only_if_empty: only remove the file if empty. Default False.
1678 """
1679 if only_if_empty and os.path.exists(filename):
1680 file_stat = os.stat(filename)
1681 if file_stat.st_size > 0:
1682 logger.debug('%s is not empty.', filename)
1683 return
1684 try:
1685 os.unlink(filename)
1686 except Exception as e:
1687 # ignore missing file
1688 if getattr(e, 'errno', None) != errno.ENOENT:
1689 logger.error('Error removing %s: %s', filename, str(e))
1690
1691
1692 def remove_directory(dir):
1693 """Remove an empty directory."""
1694 try:
1695 os.rmdir(dir)
1696 except OSError as e:
1697 if e.errno not in {errno.ENOENT, errno.ENOTEMPTY}:
1698 logger.error("Failed to remove directory %s", dir)
1699
1700
1701 def rmtree(path):
1702 """
1703 Remove a directory structure and log any exceptions raised.
1704 """
1705 try:
1706 if os.path.exists(path):
1707 shutil.rmtree(path)
1708 except Exception as e:
1709 logger.error('Error removing %s: %s', path, str(e))
1710
1711
1712 def datetime_from_utctimestamp(t, units=1):
1713 """
1714 Convert a timestamp or a time.struct_time to a datetime.datetime
1715 object down to seconds, with UTC timezone
1716
1717 The conversion is safe for year 2038 problem
1718
1719 :param t: int or float timestamp in (milli)seconds since UNIX epoch
1720 or time.struct_time
1721 :param units: normalizing factor for the timestamp
1722 (1 for seconds, 1000 for milliseconds)
1723 defaults to 1
1724 :return: datetime.datetime object in UTC timezone
1725 """
1726 if isinstance(t, time.struct_time):
1727 v = int(time.mktime(t))
1728 elif isinstance(t, (float, int)):
1729 v = int(t)
1730 else:
1731 raise TypeError(t)
1732 epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
1733 return epoch + datetime.timedelta(seconds=v // units)
1734
1735
1736 class Sleeper:
1737 """Helper for time.sleep() loop with timeout
1738
1739 A sleeper object sleeps *sleep* seconds when it is called. Close to its
1740 deadline it sleeps shorter to not oversleep the *timeout* deadline. A
1741 sleeper object is *True* and returns *True* before it reaches *timeout*
1742 deadline. After its deadline a sleeper raises the exception object/class
1743 in *raises*. If *raises* is not given, it returns False instead.
1744
1745 sleep = Sleeper(sleep=1, timeout=60, raises=TimeoutError)
1746 while True:
1747 do_something()
1748 sleep()
1749
1750 sleep = Sleeper(sleep=0.5, timeout=60)
1751 while True:
1752 do_something
1753 if not sleep():
1754 log.info("timeout")
1755 break
1756
1757 longsleep = Sleeper(sleep=1, timeout=sys.maxsize)
1758 """
1759 multiplier = 2
1760
1761 def __init__(self, *, sleep, timeout, raises=None):
1762 if timeout <= 0:
1763 raise ValueError(f"invalid timeout {timeout}")
1764 if sleep < 0.01:
1765 raise ValueError(f"sleep duration {sleep} is too short.")
1766
1767 self.timeout = timeout
1768 self.sleep = sleep
1769 self.raises = raises
1770
1771 self.deadline = time.monotonic() + self.timeout
1772
1773 def __bool__(self):
1774 return time.monotonic() < self.deadline
1775
1776 def __call__(self):
1777 now = time.monotonic()
1778 if now >= self.deadline:
1779 if self.raises is not None:
1780 raise self.raises
1781 else:
1782 return False
1783 # don't sleep over deadline
1784 dur = min(self.deadline - now, self.sleep)
1785 time.sleep(dur)
1786 return True
1787
1788
1789 def get_config_debug(context):
1790 """A simplified version of ipalib/config in order to determine if the
1791 API should be bootstrapped in debug mode or not.
1792
1793 A number of daemons setup logging, then bootstrap the API in order
1794 to capture the startup. This presents a chicken-and-egg problem
1795 over debug output.
1796
1797 Debug is rather spammy and probably shouldn't be enabled by default
1798 but if some problem is occuring during startup we want a way to
1799 see that.
1800
1801 So use this limited function to pluck out the debug value out of
1802 the system context config file (in_tree is not supported, another
1803 chicken-and-egg).
1804
1805 This isn't more generalized for two reasons:
1806 1. There is currently only a need for 'debug'
1807 2. Type conversion. They will all be strings.
1808 """
1809 CONFIG_SECTION = 'global' # duplicated from ipalib.constants
1810 config_file = os.path.join('/', 'etc', 'ipa', '%s.conf' % context)
1811
1812 parser = RawConfigParser()
1813 try:
1814 parser.read(config_file)
1815 except ParsingError:
1816 return False
1817
1818 if not parser.has_section(CONFIG_SECTION):
1819 return False
1820
1821 if not parser.has_option(CONFIG_SECTION, 'debug'):
1822 return False
1823
1824 return parser.get(CONFIG_SECTION, 'debug').lower() == 'true'
1825
1826
1827 @contextmanager
1828 def log_level_override():
1829 """The PKI python libraries log to info() which ends up polluting
1830 the ipa server installation output. Switch the log level
1831 prior to calling any PKI library functions and then restore
1832 the value in order to suppress the output. Lines like:
1833
1834 INFO Connecting to https://localhost:8443
1835 INFO Getting PKI server info from /pki/v2/info
1836
1837 This won't affect what is logged to files.
1838 """
1839 stream_handlers = [
1840 (handler, handler.level) for handler in logging.root.handlers
1841 if type(handler) is logging.StreamHandler
1842 ]
1843 for (handler, _level) in stream_handlers:
1844 handler.setLevel(logging.ERROR)
1845 try:
1846 yield
1847 except Exception as e:
1848 raise e
1849 finally:
1850 for (handler, orig_level) in stream_handlers:
1851 handler.setLevel(orig_level)