HEX
Server: Apache
System: Linux scp1.abinfocom.com 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
User: confeduphaar (1010)
PHP: 8.1.33
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //usr/libexec/kcare/python/kcarectl/__pycache__/__init__.cpython-38.pyc
U

n�h0&�@s�ddlmZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlmZddlmZddlmZddlmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)ddlm*Z*m+Z+m,Z,dd	l-m.Z.m/Z/m0Z0m1Z1m2Z2d
Z3dZ4dZ5d
Z6dZ7dZ8dZ9dZ:e�;dej<�Z=e�;d�Z>ej?�@d��r�ej?�Add�ejBdeCd�e"jJ�KejL�dd�ZMdd�ZNdd�ZOdd�ZPdd �ZQd�d!d"�ZRd#d$�ZSd%d&�ZTd'd(�ZUd)d*�ZVd+d,�ZWd-d.�ZXGd/d0�d0eY�ZZGd1d2�d2e*�Z[Gd3d4�d4e*�Z\Gd5d6�d6e*�Z]d7d8�Z^ed9d:��Z_d�d;d<�Z`d=d>�Zad?d@�ZbiZcdAdB�Zdede0je_fegedCd��sz8ddlhZiddljZkeijl�mekjn�eijl�mdD�k�r�eodE��Wneok
�r�Yn8XdFdG�Zpe0jqZrGdHdI�dIes�ZtGdJdK�dKe0jq�Zueue0_qdLdM�ZvejwfdNdO�ZxdPdQ�ZydRdS�ZzGdTdU�dUes�Z{dVdW�Z|dXdY�Z}d�d[d\�Z~d]d^�Zd_d`�Z�d�dadb�Z�dcdd�Z�dedf�Z�dgdh�Z�didj�Z�dkdl�Z�dmdn�Z�dodp�Z�dqdr�Z�dsdt�Z�dudv�Z�dwdx�Z�dydz�Z�d{d|�Z�d}d~�Z�dd��Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�Gd�d��d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�ej�ejwfd�d��Z�d�d��Z�ej�fd�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�dS)��)�print_functionN)�ArgumentParser)�contextmanager)�datetime�)�auth�capabilities�config�config_handlers�	constants�errors�fetch�
http_utils�ipv6_support�kcare�libcare�	log_utils�platform_utils�
process_utils�selinux�server_info�serverid�update_utils�utils)�
KcareError�NotFound�SafeExceptionWrapper)�	HTTPError�URLError�httplib�json_loads_nstr�	urlencode�cZv3)Z12hZ24hZ48h�testz./etc/sysconfig/kcare/freezer.modules.blacklistz/usr/libexec/kcare/kcdoctor.sh)z	latest.v3�	latest.v2z /etc/sysconfig/kcare/sysctl.conf�
z$==BLACKLIST==
(.*)==END BLACKLIST==
z'(kpatch.*|ksplice.*|kpatch_livepatch.*)z/usr/libexec/kcare/python�ignore)�categorycCs@t�}tj�t�r<ttd�}|D]}|�|���q |��|S)N�r)	�set�os�path�isfile�FREEZER_BLACKLIST�open�add�rstrip�close)�result�f�line�r5�./usr/libexec/kcare/python/kcarectl/__init__.py�get_freezer_blacklistQs
r7cCsB|�d�}|r(d�|d||dg�}nd�|d|dg�}|S)N�.r���)�split�join)�ptype�filenameZ
name_partsr5r5r6�_apply_ptype[s

r>cCsJt|tj�t_t|tj�t_t|tj�t_t|tj�t_t|tj�t_dS�N)r>r	�	PATCH_BIN�
PATCH_INFO�BLACKLIST_FILE�FIXUPS_FILE�
PATCH_DONE)r<r5r5r6�apply_ptypeds
rEcCs�t��\}}}d}t|t�r`t|t�s`zd|jt�|j�|jf}Wq�t	t
fk
r\Yq�XnNt|tt
tf�r�t|t�s�d|}n*t|t
�r�|jp�t|j�}|jp�d|j}t��}tjt��|d|dt|dt|��|d�t�|d��t|dd�d	�S)
N�z[Errno %i] %s: '%s'z%srr�__name__�d�attempts)Z
agent_versionZpython_version�distroZdistro_version�error�details�	tracebackrI)�sys�exc_info�
isinstance�OSErrorr�errnor*�strerrorr=�AttributeError�	TypeError�KeyError�IOErrorr�etype�type�innerrLr�
get_distror�VERSIONZget_python_version�getattr�strr;rMZ	format_tb)rX�value�tbZdetails_sanitizedrJr5r5r6� format_exception_without_detailsls,


�racCsvtjr
dSt�t��}t�t�t�	|���}t�
d�d|}t�|t
���}zt�|�Wntk
rpYnXdS)Nz/api/kcarectl-tracez?trace=)r	�UPDATE_FROM_LOCAL�json�dumpsrar�nstr�base64Zurlsafe_b64encodeZbstr�get_patch_server_urlrZhttp_requestrZget_http_auth_stringZurlopen_base�	Exception)ZtraceZ
encoded_trace�urlZrequestr5r5r6�send_exc�srjc	Cs�t��}|dkr t�|d�dSt��t��}|dkrBt�d�t�d�ttjd��&}t�	|�
�d�t�	|�
�d�W5QRX|r�t�|�z
|�Wn*t
k
r�tj�d�t�d�YnXt�d�dS)z�
    Run func in a fork in an own process group
    (will stay alive after kcarectl process death).
    :param func: function to execute
    :return:
    rN�ar�zWait exception)r*�fork�waitpid�setsid�_exitr1r.rZLOG_FILE�dup2�fileno�time�sleeprhr�kcarelog�	exception)�funcrt�pid�fdr5r5r6�
nohup_fork�s(



rzc	Cs�tj�tjd�}tj�|�rtt|d��H}z,t|���}|t	j
t��krRt||��Wnt
k
rhYnXW5QRXt�|t���dS)aCheck the fact that there was a failed patching attempt.
    If anchor file not exists we should create an anchor with
    timestamp and schedule its deletion at $timeout.

    If anchor exists and its timestamp more than $timeout from now
    we should raise an error.
    �.kcareprev.lockr(N)r*r+r;r�PATCH_CACHEr,r.�int�readr	�SUCCESS_TIMEOUTrs�PreviousPatchFailedException�
ValueErrorr�atomic_write�
timestamp_str)Zanchor_filepathZafile�	timestampr5r5r6�touch_anchor�sr�cCsxzt�tj�tjd��Wntk
r.YnXtd|�tj	�
�ztdd�Wn tk
rrt
j�d�YnXdS)z�
    See touch_anchor() for detailed explanation of anchor mechanics.
    See KPT-730 for details about action registration.
    :param state_data: dict with current level, kernel_id etc.
    r{�done��reasonzCannot send update info!N)r*�remover+r;rr|rQ�register_actionr�get_loaded_modules�clear�get_latest_patch_levelrhrrurv��
state_datar5r5r6�
commit_update�s

r�cCs(tjtj�tjd�t�||d�d�dS)N�patchesrF)Zexclude_path)	r�clean_directoryr*r+r;rr|r�get_cache_path)�khashZplevelr5r5r6�clear_cache�sr�cCs>tjpd}d�||g�}tjd|f}|r2||f7}tjj|�S)N�none�-�modules)r	�PREFIXr;rr|r*r+)r��fname�prefixZ
module_dirr2r5r5r6�get_current_level_path�s

r�cCstjt|d�t|�dd�dS)N�latestT)Z
ensure_dir)rr�r�r^)r��patch_levelr5r5r6�save_cache_latest�sr�c	CsXt|d�}tj�|�rTz$tt|d������}t�	||�WSt
tfk
rRYnXdS)Nr�r()r�r*r+r,r}r.r~�stripr�LegacyKernelPatchLevelr�rU)r�Zpath_with_latest�plr5r5r6�get_cache_latest�s
r�c@seZdZdS)�CertificateErrorN)rG�
__module__�__qualname__r5r5r5r6r�
sr�c@seZdZdd�ZdS)�UnknownKernelExceptionc	Cs*t�|d�t��dt��t����dS)N�LNew kernel detected ({0} {1} {2}).
There are no updates for this kernel yet.r)	rh�__init__�formatrr[�platform�releaser�get_kernel_hash��selfr5r5r6r�s
��zUnknownKernelException.__init__N)rGr�r�r�r5r5r5r6r�sr�cs$eZdZ�fdd�Zdd�Z�ZS)�ApplyPatchErrorcsFtt|�j||�||_||_||_||_t��d|_	t
��|_dS�Nr)�superr�r��code�
freezer_style�level�
patch_filerr[rJr�r�)r�r�r�r�r��args�kwargs��	__class__r5r6r�szApplyPatchError.__init__cCs0d�|j|j|j|j|jd�dd�|jD���S)Nz0Unable to apply patch ({0} {1} {2} {3} {4}, {5})�, cSsg|]}t|��qSr5)r^)�.0�ir5r5r6�
<listcomp>)sz+ApplyPatchError.__str__.<locals>.<listcomp>)r�r�r�r�rJr�r;r�r�r5r5r6�__str__"s�zApplyPatchError.__str__�rGr�r�r�r��
__classcell__r5r5r�r6r�s	r�cs$eZdZ�fdd�Zdd�Z�ZS)r�cs"tt|�j||�||_||_dSr?)r�r�r�r��anchor)r�r�r�r�r�r�r5r6r�/sz%PreviousPatchFailedException.__init__cCsd}|�|j|j�S)Nz�It seems, the latest patch, applying at {0}, crashed, and further attempts will be suspended. To force patch applying, remove `{1}` file)r�r�r�)r��messager5r5r6r�4s�z$PreviousPatchFailedException.__str__r�r5r5r�r6r�.sr�c
Cs�t��d�|�}z|t�|�}t�t�|����}t	|d�}|dkrRt�
d�n8|dkrft�
d�n$|dkrzt�
d�nt�
d	�|��|WStk
r�}zt�
||�W5d}~XYnXd
S)Nz"/nagios/register_key.plain?key={0}r�rzKey successfully registeredrzWrong key format or sizerlz!No KernelCare license for that IPzUnknown error {0}r9)r�get_registration_urlr�r�urlopenr�data_as_dictrer~r}�
print_wrapperrr�print_cln_http_error)�keyri�response�resr��er5r5r6�!set_monitoring_key_for_ip_license=s 
r�c
cs>tjrtjtjdd�z
dVW5tjr8tjtjdd�XdS)NT)�shell)r	ZBEFORE_UPDATE_COMMANDr�run_commandZAFTER_UPDATE_COMMANDr5r5r5r6�
execute_hooksQs
r�cCs�t�}|j}|j}t��}|dkrht|�tjt�	�t
��|tt
���|d�}t�d�t�t�|��njt�d�t�t|��t�dt|��t�tj�t�t�	��t�t
���t�|�t�t
���dS)a1
    The output will consist of:
    Ignore output up to the line with "--START--"
    Line 1: show if update is needed:
        0 - updated to latest,
        1 - update available,
        2 - unknown kernel
        3 - kernel doesn't need patches
        4 - no license, cannot determine
    Line 2: licensing message (can be skipped, can be more then one line)
    Line 3: LICENSE: CODE: 1: license present, 2: trial license present, 0: no license
    Line 4: Update mode (True - auto-update, False, no auto update)
    Line 5: Effective kernel version
    Line 6: Real kernel version
    Line 7: Patchset Installed # --> If None, no patchset installed
    Line 8: Uptime (in seconds)

    If *format* is 'json' return the results in JSON format.

    Any other output means error retrieving info
    :return:
    rc)Z
updateCodeZ
autoUpdateZeffectiveKernelZ
realKernelZloadedPatchLevelZuptime�licensez	--START--z	LICENSE: N)�_patch_level_infor��applied_lvlr�license_infor^r	�AUTO_UPDATEr�kcare_unamer�r�r}rZ
get_uptimerr�rcrd)�fmt�pliZupdate_codeZ	loaded_plZlicense_info_resultZresultsr5r5r6�plugin_info]s.
�	


r�cCsbt��}ztdd�}Wn"tk
r8tjr0dndYSX|dkrFdS||krRdSt��r^dSdS)N�infor�r�rrl)r�loaded_patch_levelr�r�r	�IGNORE_UNKNOWN_KERNELrZstatus_gap_passed)�
current_levelZlatest_patch_levelr5r5r6�get_update_status�sr�cCs2t��dd�\}}|dkr*|�d�r*dSdSdS)NrlZ
CloudLinuxz7.�extrarF)rr[�
startswith)rJ�versionr5r5r6�edf_fallback_ptype�sr�cCsl|j|jf}t�||�}t�||j�|_|j�tj	tj
d�|tkrZ|j��dd�t|<|jrh|�
�dS)z�Function remembers IP address of host connected to
    and uses it for later connections.

    Replaces stdlib version of httplib.HTTPConnection.connect
    rNrl)�hostZport�CONNECTION_STICKY_MAP�get�socketZcreate_connectionZtimeout�sockZ
setsockoptZIPPROTO_TCPZTCP_NODELAYZgetpeername�_tunnel_hostZ_tunnel)r�ZaddrZ
resolved_addrr5r5r6�sticky_connect�sr�ZHAS_SNIz0.13z%No pyOpenSSL module with SNI ability.cGsdS)NTr5)r�r5r5r6�dummy_verify_callback�sr�c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�SSLSockcCs||_d|_dSr�)�	_ssl_conn�_makefile_refs)r�r�r5r5r6r��szSSLSock.__init__cGs&|jd7_tj|jf|�ddi�S)Nrr1T)r�r�Z_fileobjectr��r�r�r5r5r6�makefile�szSSLSock.makefilecCs |js|jr|j��d|_dSr?)r�r�r1r�r5r5r6r1�s
z
SSLSock.closecGs|jj|�Sr?)r��sendallr�r5r5r6r��szSSLSock.sendallN)rGr�r�r�r�r1r�r5r5r5r6r��sr�c@seZdZdd�ZdS)�PyOpenSSLHTTPSConnectioncCs�tj�|�tj�tjj�}|�tjjtjj	B�t
jrJ|�tjj
t�n|�tjjt�|��tj�||j�}|��|jp�|j}|�|���|��t
jr�t|��|�t|�|_dSr?)r�HTTPConnection�connect�OpenSSLZSSLZContextZ
SSLv23_METHODZset_optionsZOP_NO_SSLv2ZOP_NO_SSLv3r	�CHECK_SSL_CERTSZ
set_verifyZVERIFY_PEERr�ZVERIFY_NONEZset_default_verify_pathsZ
Connectionr�Zset_connect_stater�r�Zset_tlsext_host_name�encodeZdo_handshake�match_hostnameZget_peer_certificater�)r�ZctxZconnZserver_hostr5r5r6r��sz PyOpenSSLHTTPSConnection.connectN)rGr�r�r�r5r5r5r6r��sr�cCs6tjr&t�||�}t�tj�|dd�S|dk}d|fd|fdfD]�\}}tj	||||d�}|rhd�
|�}t�|t||��d|}d	}	|s�|r�t|�|	kr�|r�d
nd}
t
�d|
�q@zt�tj�|dd�WStk
�r.}z@|s�|�r|jd
k�s|jdk�rt
�d�
|��WY�q@�W5d}~XYq@Xq@dS)NF��
check_license)z	latest.v1r$T)FF)�b64_encoding�secure_boot_info�perf_metricszinfo={0}�?iXzsecure boot infozperf metricsz.Check-in URL param is too large, discarding %s)i�i�i�zCCheck-in request failed with error: {0}, retrying with reduced info)r	rbrZget_kernel_prefixed_urlr
Zwrap_with_cache_keyr�urlopen_authrZencoded_server_infor��stickyfy�lenr�logwarnrr�)r�r�r��moderir�r�r�Z
request_paramZmax_url_lengthZdiscard_info�exr5r5r6�_fetch_patch_level_requests4�
"rc	Cs>t��}tjdk	r$t�|ttj��StD�]}z�t||||�}t�	|j
�t�t�
|�����}tjd�||�dd�|r�|�d�r�t|�}|�dg�}t�|�s�t�d��t�||d|d|d	�WSt�|t|��WStk
r�Yq(tk
�r0}z|jd
k�rtd���W5d}~XYq(Xq(t��dS)Nz;fetch patch level, reason: {0}, kernel latest response: {1}F�Z	print_msg�{rzeLatest KernelCare patchset is incompatible with the current kernecare package version, please upgrader��baseurlr�)i�i�zKC licence is required) rr�r	�PATCH_LEVELr�r}�PATCH_LATESTrr
Zset_config_from_patchserver�headers�update_all_kmod_paramsrrer~r�r�loginfor�r�r r�rZhas_kc_capabilitiesr�CapabilitiesMismatchZKernelPatchLevelrrr�rr�)	r�rr�r�r�r�Zlatest_infoZrequired_capabilitiesrr5r5r6�fetch_patch_level%s4


�"rc
CsB|�t|tj��}tj�d�|��ztj	|ddd�WdSt
k
rbtj�d�|��YdStk
r�}ztj�d�|t
|���W5d}~XYnX|�t|tj�tj�}tj�d�|��ztj	|dd�Wndt
k
�rtj�d�|��YdStk
�r<}ztj�d	�|t
|���W5d}~XYnXdS)
NzProbing patch URL: {0}F�HEAD)r��methodTz{0} is not available: 404zFHEAD request for {0} raised an error, fallback to the GET request: {1}r�z{0} is not available: {1})�file_urlr>r	r@rrur�r�rr�rrh�debugr^rZSIGr)r�r<Zbin_urlrrir5r5r6�probe_patchFs(**rcCsF|tjkr|�tj�}n
|�|�}|�|�}tj||tjt�	|�d�S)N)Zhash_checker)
r�KMOD_BINZkmod_urlr�
cache_pathr
Z	fetch_urlr	�
USE_SIGNATUREZget_hash_checker)r��nameriZdstr5r5r6�fetch_and_verify_kernel_file_s



rc@s>eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�PatchFetcherNcCs
||_dSr?)r�)r�r�r5r5r6r�jszPatchFetcher.__init__cCst|j|�Sr?)rr�)r�rr5r5r6�_fetchmszPatchFetcher._fetchcCsr|j�tj�}|j�tj�}|j�tj�}|j�tj�}tdd�||||fD��opt	j
�|�dkopt	j
�|�dkS)Ncss|]}tj�|�VqdSr?)r*r+r,)r�r+r5r5r6�	<genexpr>wsz0PatchFetcher.is_patch_fetched.<locals>.<genexpr>r)r�rr	rDr@rArr�allr*r+�getsize)r�Zpatch_done_pathZpatch_bin_pathZpatch_info_pathZ
kmod_bin_pathr5r5r6�is_patch_fetchedps��zPatchFetcher.is_patch_fetchedcCs0|jdkrtd��|js|jS|��r6t�d�|jSt�d�t|jtj�r�ztj	|j�
tj�dd�}Wnt
k
r~Yn(X|j�dd�}|r�|j�t�|��|_z|�tj�Wn,t
k
r�td�|jtjp�d���YnX|�tj�|�tj�|��tj|j�tj�d	d
d�t�tj �|jS)Nz+Cannot fetch patch as no patch level is setzUpdates already downloadedzDownloading updatesr)r�KC-Base-UrlzfThe `{0}` patch level is not found for `{1}` patch type. Please select valid patch type or patch level�default��wb�r)!r�r�rrr
rPrr�rr�rr	r@rrr��upgraderrerrr��
PATCH_TYPErArr�extract_blacklistr�rrDr�restore_selinux_contextr|)r��resprr5r5r6�fetch_patch|s>


��
zPatchFetcher.fetch_patchcCsJt|j�tj�d���}|rFt�|�}|rFt�	|j�tj
�|�d��dS)Nr(r)r.r�rr	rAr~�BLACKLIST_RE�searchrr�rB�group)r�ZbufZmor5r5r6r'�s

zPatchFetcher.extract_blacklistc	Cs�|dkrdSzt|tj�}Wntk
r2YdSX|j�dd�}|rV|�t�|��}|�	tj�}t
|d��}tdd�|��D��}W5QRX|D]}t||�q�t
�tj�dS)z�
        Download fixup files for defined patch level
        :param level: download fixups for this patch level (usually it's a level of loaded patch)
        :return: None
        Nr r(cSsg|]}|���qSr5)r�)r��fixupr5r5r6r��sz-PatchFetcher.fetch_fixups.<locals>.<listcomp>)rr	rCrrr�r%rrerr.r)�	readlinesrr(rr|)r�r�r)rZfixups_fnamer3�fixupsr.r5r5r6�fetch_fixups�s zPatchFetcher.fetch_fixups)N)	rGr�r�r�rrr*r'r1r5r5r5r6rhs
(rcCs8t�}t�|j�|jtjkr*t�d�n
t�d�dS)Nrr)	r�rr��msgr��PLI�PATCH_NEED_UPDATErN�exit)r�r5r5r6�kcare_check�s
r6c	Cst�}t|�}zt��}Wntk
r2i}YnXt��}d}|dk	r\t�|d��	d�}t�
�}t|�dg��}t
dd�|D��}t��}|s�t�d�n
t�d�t�d	�|��t�d
�|��|dkr�t�d�|��|dkr�t�d
�|��||dk�rt�d�t�d�dS)NZUnknown�tsz%Y-%m-%dr�css|]}t|�dg��VqdS)r�N)rr�)r�Zrecr5r5r6r�sz$show_generic_info.<locals>.<genexpr>z$KernelCare live patching is disabledz"KernelCare live patching is activez - Last updated on {0}z - Effective kernel version {0}rz* - {0} kernel vulnerabilities live patchedz- - {0} userspace vulnerabilities live patchedz% - This system has no applied patchesz(Type kcarectl --patch-info to learn more)r��_kcare_patch_info_jsonrZlibcare_patch_info_basicrrZ	get_staterZ
fromtimestamp�strftimer�rr��sumr�rr�r�)	r��
kcare_info�libcare_info�stateZ
latest_updateZeffective_versionZkernel_vulnerabilitiesZuserspace_vulnerabilitiesr�r5r5r6�show_generic_info�s4


r>Fc	
Cs�z�tdtjd�}|st�|�tj�}t�t	�
|����}|r�gi}}|�d�D]0}t�
|�}|rvd|krv|�|�qP|�|�qP||d<t�|�}t�|�WnRtk
r�}zt�||j�WY�dSd}~XYntk
r�t�d�YnXd	S)
z�
    Retrieve and output to STDOUT latest patch info, so it is easy to get
    list of CVEs in use. More info at
    https://cloudlinux.atlassian.net/browse/KCARE-952
    :return: None
    r�)r��policy�

�kpatch-namer�rNzNo patches availabler)r�r�
POLICY_REMOTEr�rr	rArrerr�r~r:r��append�updatercrdr�rrr�ri)	�is_jsonr�ri�
patch_infor�r2�chunk�datar�r5r5r6�kcare_latest_patch_info�s,


rIcCs�d|ji}|jdk	r�t|�}g}|�d�D]0}t�|�}|rPd|krP|�|�q*|�|�q*||d<t�	�}|rx|dnd|d<|S)Nr�r@rAr�r��unknown)
r2r��_kcare_patch_infor:rr�rCrDrZread_dumped_kernel_patch_level)r�r2rFr�rGrHZsaved_patch_levelr5r5r6r8s


r8cCsPt��}t�||jtj�}tj�|�s.t	d��t
|d���}|rLt�
d|�}|S)NzvCan't find information due to the absent patch information file. Please, run /usr/bin/kcarectl --update and try again.r(rF)rr�r�r�r	rAr*r+r,rr.r~r+�sub)r�r�rr�r5r5r6rK)s�rKcCsZt�}|s>|jdkr t�|j�|jdkr.dSt�t|��nt�tjt	|�dd��dS)NrT)Z	sort_keys)
r�r�rr�r2r�rKrcrdr8�rEr�r5r5r6rF7s

rFcCs:tjd|g}t�|�}t��}d}t�||�t�||�kS)Nz	file-infozkpatch-build-time)r�
KPATCH_CTLr�check_outputr�_patch_infoZget_patch_value)�new_patch_filer�Znew_patch_infoZcurrent_patch_infoZbuild_time_labelr5r5r6�
is_same_patchCs

rRcCsL|dkrdS|r||krdS||kr(dSt�t��|tj�}t|�sHdSdS)NrFT)rr�r�r	r@rR)�
applied_level�	new_levelrQr5r5r6�kcare_need_updateKsrUcCsptjrltj�t�r t�ttj�s6tj	�
d�t��dStj
dddtgdd�\}}}|dkrltj	�
d�|��dS)	Nz-File {0} does not exist or has no read accessz/sbin/sysctl�-qz-pT��catch_stdoutrz%Unable to load kcare sysctl.conf: {0})r	ZUPDATE_SYSCTL_CONFIGr*r+r,�
SYSCTL_CONFIG�access�R_OKrru�warningr�rr�)r��_r5r5r6�
update_sysctl]sr^c	s�tj�t�sttd���t�ttj�s>tj	�
d�t��dSttd��b}|��}|�
d�|D]$�t�fdd�|D��s`|���q`|D]}|�|d�q�|��W5QRXdS)	z*Update SYSCTL_CONFIG accordingly the editsrkzFile {0} has no read accessNzr+rc3s|]}��|�VqdSr?)r�)r�r(�r4r5r6rysz#edit_sysctl_conf.<locals>.<genexpr>�
)r*r+r,rYr.r1rZr[rrur\r�r/�seek�any�write�truncate)r�rCZsysctl�linesrkr5r_r6�edit_sysctl_confhs
rfcCs&|D]}t�|�rtd�|���qdS)NzDDetected '{0}' kernel module loaded. Please unload that module first)�CONFLICTING_MODULES_RE�matchrr�)r��moduler5r5r6�detect_conflicting_modules�s
rjcCsd�t���S)Nz/lib/modules/{0}/extra/kcare.ko)r�rZget_system_unamer5r5r5r6�get_kcare_kmod_link�srkc
Csdtdd�}t�t��|tj�}tj�|�s.dSt	|d��"}|�
�dd�dkW5QR�SQRXdS)Nr�r��rbi��s~Module signature appended~
)r�rr�r�rrr*r+r,r.r~)r�Z	kmod_fileZvfdr5r5r6�kmod_is_signed�s
rmcs4t�d���dkrdSddg}t�fdd�|D��S)Nz
/proc/keysZ(12ff0613c0f80cfba3b2f8eba71ebc27c5a76170Z(69a6d9eed3f620d5c2e13a1d211c46510a5ad9f5c3s|]}|�kVqdSr?r5)r�r��Zsystem_keysr5r6r�sz'kcare_certs_enrolled.<locals>.<genexpr>)rZtry_to_readrb)Z
kcare_keysr5rnr6�kcare_certs_enrolled�s
�rocKs\d|g}|��D]\}}|�d�||��qtj|dd�\}}}|dkrXtd�||���dS)Nz/sbin/insmodz{0}={1}TrWrzLUnable to load kmod ({0} {1}). Try to run with `--check-compatibility` flag.)�itemsrCr�rr�r)Zkmodr��cmdr�r_r�r]r5r5r6�	load_kmod�srrcCsPt��r,t�dkrtd��t�dkr,td��t��sDt��sDt��rLtd��dS)NFz4Secure boot is enabled. Not supported by KernelCare.z<Secure boot is enabled. No KernelCare certificates enrolled.zWYou are running inside a container. Kernelcare should be executed on host side instead.)rZis_secure_bootrmrroZinside_vz_containerZinside_lxc_containerZinside_docker_containerr5r5r5r6�check_compatibility�s

rscCsPt�d�}tj|dgddd�ddk}|rL|dkrLt�d�|��t�d�dS)	NZmodinfoZkmodlveT�rX�catch_stderrr��freer�z3{0} patch type conflicts with kmodlve kernel moduler)rZfind_cmdr�r�logerrorr�rNr5)r<rqZhas_kmodlver5r5r6�check_patch_type_compatibility�s

rycCsLt�ddd|g�}g}|�d�D]&}|��r |�d�\}}}|�|�q |S)Nz
/sbin/modinfoz-FZparmr`�:)rrOr:r��	partitionrC)�
kcare_link�stdoutZavailable_paramsr4Z
param_namer]r5r5r6�get_kmod_available_params�sr~cCsLtjr
dndtjrdndtjr$tjndttjt�r8tjndtjrDdndd�S)NrrrF)�kpatch_debugZkmsg_outputZkcore_outputZ
kdumps_dirZenable_crashreporter)	r	�KPATCH_DEBUGZKMSG_OUTPUTZKCORE_OUTPUTZKCORE_OUTPUT_SIZErP�
KDUMPS_DIRr^ZENABLE_CRASHREPORTERr5r5r5r6�make_kmod_new_params�s�r�cCsBtjr tj�tj�s t�tj�t���D]\}}t||�q*dSr?)	r	r�r*r+�exists�makedirsr�rp�update_kmod_param)Zparam�valr5r5r6r�src	Cstd}tj�||�}tj�|�s"dSz(t|d��}|�t|��W5QRXWn$tk
rntj	�
d||�YnXdS)Nz/sys/module/kcare/parameters�wz!failed to set %s kmod param to %s)r*r+r;r�r.rcr^rhrrurK)Zkmod_param_nameZparam_valueZparams_rootZ
param_pathr3r5r5r6r��sr�cs�t�}t�||tj�}zt�||�Wntk
r>|}YnXtj	r`t
j�tj	�s`t
�
tj	�t�}t|��t�fdd�|��D��}t|f|�t�dS)Nc3s"|]\}}|�kr||fVqdSr?r5)r��k�v�Zavailable_kmod_paramsr5r6r�sz"load_kcare_kmod.<locals>.<genexpr>)rkrr�rr�shutil�copyrhr	r�r*r+r�r�r�r~�dictrprr�
update_depmod)r�r�r|Z
kcare_fileZkmod_paramsr5r�r6�load_kcare_kmod�s
r�cCsXdg}|dk	r|�d|g�tj|ddd�\}}}|rTtjd�d�|�||�dd�dS)	Nz/sbin/depmodz-aTrtz%Running of `{0}` failed with {1}: {2}� Fr)�extendrr�rrxr�r;)�unamerqr�r]�stderrr5r5r6r��s�r�cCs4tjd|gdd�\}}}|dkr0td�||���dS)Nz/sbin/rmmodTrWrzUnable to unload {0} kmod {1})rr�rr�)�modnamer�r]r5r5r6�unload_kmod
sr�cCsPg}dg|D]<}t�||d�|��}tj�|�rt|�|�d�|��q|S)NZvmlinuxzfixup_{0}.koz	fixup_{0})rr�r�r*r+r�rrrC)r�r�r�Zloaded�mod�modpathr5r5r6�apply_fixupssr�c	Cs@|D]6}zt|�Wqtk
r8tj�d|�YqXqdS)Nz$Exception while unloading module %s.)r�rhrrurv)r0r�r5r5r6�
remove_fixupss
r�cCs�|r
|}n6tjrtj}n(t��|�r2d|tjdfSd|tjdfSdddddd�}|��}||krj||}ntd�||tjd���||tjdfS)	NZfreeze_conflictTr!FZfreeze_noneZ
freeze_all)ZNONEZNOFREEZEZFULLZFREEZEZSMARTz3Unable to detect freezer style ({0}, {1}, {2}, {3}))r	ZPATCH_METHODr7�intersection�upperrr�)�freezerr�rZpatch_method_mapr5r5r6�get_freezer_style"s$�
r�rFcs�|||d��td��t��}t��}t|�t||�}t�||tj�}t	||�d�
|tjt�
�t�|��}	d|k}
|
o�t�||�}|dk	}|o�t|�o�t�|	�}
��||d��|
r�td��dS|�rtd��t|||�}td��t|�td	��t|�|�r"td
��td�d}
|
�s<td��t||�|�rHt�td
��t||||	|�t�t�d�
|t����t��td��t �fdd�tj!d�dS)N)r�Zfuturer�startz{0}-{1}:{2};{3}r)Zcurrent�kmod_changedr�Zfxp�unpatchZunfxp�unloadF�load�patchz5Patch level {0} applied. Effective kernel version {1}�waitcst��Sr?)r�r5r�r5r6�<lambda>}r"zkcare_load.<locals>.<lambda>)rt)"r�rr�r�rjr�r�r	r@r�r�r&rr�Zparse_unameZis_kmod_version_changedrRZkcare_update_effective_versionrDr��kpatch_ctl_unpatchr�r�r�r��kpatch_ctl_patchr^rr
r�rZtouch_status_gap_filerzr)r�r�rr��
use_anchorr�r�r�r��descriptionZkmod_loadedr�Zpatch_loadedZ
same_patchr0r5r�r6�
kcare_loadAsZ


�








r�c	Cs�tjg}t�||tj�}tj�|�r2|�	d|g�|�	dd|g�|�	d|dg�|�
|�tj|dd�\}}}|dkr�t
||||��dS)Nz-br�z-d�-mrTrW)rrNrr�r	rBr*r+r�r�rCrr�r�)	r�r�r�r�r�r�Zblacklist_filer�r]r5r5r6r��s
r�cCsZtjtjdd|dgddd�\}}}|dkrVtjd�||�dd�td	�|t|����dS)
Nr�r�rTrt�4Error unpatching, kpatch_ctl stdout:
{0}
stderr:
{1}Fr�Error unpatching [{0}] {1})	rr�rrNrrxr�rr^)r�r�r}r�r5r5r6r��s�r�cCs8||d<tt���|d<t�tj�tjd�t	|��dS)N�actionr7zkcare.state)
r}rsrr�r*r+r;rr|r^)r�r�r5r5r6r��sr�cCsld}tj�|�sdSt�|�D]H}tj�||dd�}tj�|�sBqt�|�}||krt�|�t|�qdS)Nz/usr/lib/modules/zweak-updateszkcare.ko)	r*r+�isdir�listdirr;�islink�readlink�unlinkr�)�	kmod_linkZmodules_path�entryZ
sym_link_pathZtarget_pathr5r5r6�update_weak_modules�s

r�c

CsBt��}t�}z|�|�Wn4tk
rP}z|s@td�|���W5d}~XYnXt��}t||�}t	���d|k�r|dk	}|r�t
t��||�}tj
tjdd|dgddd�\}	}
}t|�|	dkr�tjd�|
|�d	d
�td�|	t|����tjt�t�dtd
�t�d�t�}tj�|��r,t�|�t|�W5QRXdS)Nz�Unable to retrieve fixups: '{0}'. The unloading of patches has been interrupted. To proceed without fixups, use the --force flag.rr�r�rTrtr�Frr�r)�count�delay) rr�rr1rhrr�r�r�r�r�r�rr�rrNr�rrxr^rZretryrZ	check_exc�UNLOAD_RETRY_DELAYr�rkr*r+r,r�r�)
r��forcer��pf�errr�r�Zneed_unpatchr0r�r}r�r�r5r5r6�kcare_unload�sF��

�
�
r�cCs8t�}|rt|�S|jdkr"|jS|jdk	r4t��SdSr�)r��_kcare_info_jsonr�r2r�rrPrMr5r5r6r;�s

r;cCsRd|ji}|jdk	r>|�t�t����|�t�|�d���|j	|d<t
�|�S)Nr�zkpatch-descriptionzkpatch-state)r2r�rDrr�rrPZparse_patch_descriptionr�r=rcrd)r�r2r5r5r6r��s


r�c@s$eZdZdZdZdZdZdd�ZdS)r3rrrlr�cCs"||_||_||_||_||_dSr?)r�r2�
remote_lvlr�r=)r�r�r2r�r�r=r5r5r6r��s
zPLI.__init__N)rGr�r�r
r4�PATCH_UNAVALIABLE�PATCH_NOT_NEEDEDr�r5r5r5r6r3�s
r3c	Cs�t��}z�tdd�}|rJt||�r6tjdd}}}qxtjdd}}}n.|dkrftjdd}}}ntjd	d}}}t|||||�}Wnltk
r�tj	}t
jr�d
�t
jt
��dt���}nd�t
��dt��t���}t||ddd�}YnX|S)
Nr�r�z*Update available, run 'kcarectl --update'.ZappliedzThe latest patch is applied.rz(This kernel doesn't require any patches.ZunsetzDNo patches applied, but some are available, run 'kcarectl --update'.zuInvalid sticky patch tag {0} for kernel ({1} {2}). Please check /etc/sysconfig/kcare/kcare.conf STICKY_PATCH settingsr�Zunavailable)rr�r�rUr3r4r
r�r�r�r	�STICKY_PATCHr�rr[r�r�r�)Zcurrent_patch_levelZnew_patch_levelr�r2r=r�r5r5r6r��sN

����

��
�r�c	
Csd}zZt��}td|fd|fg�}t��d�|�}t�|�}t�	t�
|����}t|d�WSt
k
r�}zt�||�WY�dSd}~XYnltk
r�}zt�||�WY�dSd}~XYn:tk
�r�}zt�d�|��WY�d	Sd}~XYnXdS)
z�
    Request to tag server from ePortal. See KCARE-947 for more info

    :param tag: String used to tag the server
    :return: 0 on success, -1 on wrong server id, other values otherwise
    N�	server_id�tagz/tag_server.plain?{0}r�������zInternal Error {0}���)r�get_serveridr!rr�r�rr�rr�rer~r}rrr�rrhrx)	r�rir�Zqueryr�r�r�ZueZeer5r5r6�
tag_server1s"
r�cCs�t�d�}t�d�|��t}t����}z:t�	||j
�}t�t�
|�|j
�t�|j
|�|j
}Wn2tk
r�}zt�d�|��W5d}~XYnXtjd|t��gdd�\}}}|r�td�||���W5QRXdS)Nz	doctor.shz#Requesting doctor script from `{0}`z3Kcare doctor error: {0}. Fallback to the local one.ZbashT)ruzScript failed with '{0}' {1})rrgrZlogdebugr��KCDOCTOR�tempfileZNamedTemporaryFiler
Zfetch_signaturerZsave_to_filerr�Zcheck_gpg_signaturerhrxrr�rZget_patch_serverr)Z
doctor_urlZdoctor_filenameZ
doctor_dstZ	signaturer�r�r]r�r5r5r6�kcdoctorLs


"r�cCsDt�d�t��}zt�|�Wntk
r4YdSXt�d�dS)Nz{0}-new-versionFzwA new version of the KernelCare package is available. To continue to get kernel updates, please install the new versionT)	rrgr��EFFECTIVE_LATESTrr�rrr
)rir5r5r6�check_new_kc_version]s�r�c

Cst��}t|�}|tjkp*|tjko*|dk}zt||�}Wn�tjk
r�}z,|dkrX�t	�
t|��t	�
d�tj}W5d}~XYn<t
k
r�}z|r��nt	j�d�|��W5d}~XYnX|tjkr�|}	n@|}	|dk�r|tjkr�t�|d�}	n|tjk�r
|}	ntd��|	S)a�
    Get patch level to apply.
    :param reason: what was the source of request (update, info etc.)
    :param policy: REMOTE -- get latest patch_level from patchserver,
                   LOCAL -- use cached latest,
                   LOCAL_FIRST -- if cached level is None get latest from patchserver, use cache otherwise
    :param mode: constants.UPDATE_MODE_MANUAL, constants.UPDATE_MODE_AUTO or constants.UPDATE_MODE_SMART
    :return: patch_level string
    Nz#Using previously downloaded patcheszUnable to send data: {0}rz9Unknown policy, choose one of: REMOTE, LOCAL, LOCAL_FIRST)rr�r�rrBZPOLICY_LOCAL_FIRSTrrrrrr^ZPOLICY_LOCALrhrur\r�r�r)
r�r?rr�Zcached_levelZconsider_remote_exZremote_levelr�rr�r5r5r6r�js2
$


r�cCs�|dkrdS|dkrdn|t_ttdd�tj�r�tjtjd�tjdkrnt��rntjpXt	}t
dd	d
�|�f�t�
d�|��ntd�|���dS)
N�edfr!rFZprober��r&rv)zfs.enforce_symlinksifownerzfs.symlinkown_gidzfs.enforce_symlinksifowner=1zfs.symlinkown_gid={0}z'{0}' patch type selectedz/'{0}' patch type is unavailable for your kernel)r	r&rrr
�
update_configrZ	is_cpanelZ	FORCE_GID�
CPANEL_GIDrfr�rr
r)r<Zgidr5r5r6�update_patch_type�s
�r�c	
Cstt��ttj�|tjkr"t�ztd||d�}WnXt	k
r�}z:|tj
tjfkrztjrzt
|�}tj�|�WY�
dS�W5d}~XYnXt��}t|�}|��t||d�s�t�d�dSz(tjtjddd�tjtjdd	d�Wn"tk
�r
tj�d
�YnXt��}|tj
k�s(tj�r\t��(|�|�t |||||tjkd�W5QRXt�!|�t"||�dS)ax
    :param mode: constants.UPDATE_MODE_MANUAL, constants.UPDATE_MODE_AUTO or constants.UPDATE_MODE_SMART
    :param policy: REMOTE -- download latest and patches from patchserver,
                   LOCAL -- use cached files,
                   LOCAL_FIRST -- download latest and patches if cached level is None, use cache in other cases
    :param freezer: freezer mode
    rD)r�r?rN)rSrTz%No updates are needed for this kernelr�zkcore*.dump)Zkeep_nZpatternz	kmsg*.logz#Error during crash reporter cleanup)r�)#rZlog_all_parent_processesryr	r&rrBr�r�r��UPDATE_MODE_AUTO�UPDATE_MODE_SMARTr�r^rrur\rr�rr*rUr
rr�r�rhrvr�r�r�r1r�Zdump_kernel_patch_levelr�)	r�rr?r�r�r2r�r�r�r5r5r6�	do_update�s<




"
r�cCs�tttj�ttjptj�ttjp$tj�f�}|dkr<td��tjrHtjS|t	j
krltjp\tj}tjphtj}ntj}tj}|r�|S|r�d|SdS)Nrz�Invalid configuration: conflicting settings STICKY_PATCH, [AUTO_]UPDATE_DELAY or [AUTO_]STICKY_PATCHSET. There should be only one of themzrelease-)r:�boolr	r�ZUPDATE_DELAYZAUTO_UPDATE_DELAYZSTICKY_PATCHSETZAUTO_STICKY_PATCHSETrr�UPDATE_MODE_MANUAL)rr�r�Zpatchsetr5r5r6�
get_sticky�s*���
r�cCs|d|S)Nr8r5)r�r�r5r5r6�	_stickyfysr�c
Cs t|�}|s|S|dkr"t||�St��}|sDtj�d�t�d�zt	�
t��d�
|��}Wn:tk
r�}zt�||j�t�d�W5d}~XYnXt�t�|����}t|d�}|dkr�t|d	|�S|d
kr�|S|dk�r�tj�d�t�d
�tj�d|d�t�d�dS)z�
    Used to add sticky prefix to satisfy KCARE-953
    :param file: name of the file to stickify
    :return: stickified file.
    �KEYzHPatch set to STICKY_PATCH=KEY, but server is not registered with the keyr�z!/sticky_patch.plain?server_id={0}r�Nr�rr�rrlzEServer ID is not recognized. Please check if the server is registeredr9zError: r�r�)r�r�rr�rrur�rNr5rr�rr�r�rr�rirr�rer~r})�filer�sr�r�r�r�r�r5r5r6rs2



rc
Cs�g}|sdS|�d�}|d}|dd�}|�d�}||krLtdt|���|s`|��|��kS|dkrt|�d�n>|�d	�s�|�d	�r�|�t�|��n|�t�|��	d
d��|D]}|�t�|��q�t�
dd
�|�dtj�}	|	�
|�S)zhMatching according to RFC 6125, section 6.4.3

    http://tools.ietf.org/html/rfc6125#section-6.4.3
    Fr8rrN�*z,too many wildcards in certificate DNS name: z[^.]+zxn--z\*z[^.]*z\Az\.z\Z)r:r�r��repr�lowerrCr��re�escape�replace�compiler;Z
IGNORECASErh)
Zdn�hostnameZ
max_wildcardsZpats�piecesZleftmostZ	remainderZ	wildcardsZfragZpatr5r5r6�_dnsname_match4s(

r�c		Csg}t|���D]2}|�|�}|��dkrdd�t|��d�D�}q|sPtd��g}|D]*\}}|dkrXt||�rxdS|�|�qX|s�|�	�j
}t||�r�dS|�|�t|�dkr�td�
|d	�tt|�����n*t|�dkr�td
�
||d���ntd��dS)
NZsubjectAltNamecSsg|]}|���dd��qS)rzr)r�r:)r��itr5r5r6r�lsz"match_hostname.<locals>.<listcomp>�,ztempty or no certificate, match_hostname needs a SSL socket or SSL context with either CERT_OPTIONAL or CERT_REQUIREDZDNSrz(hostname {0} doesn't match either of {1}r�zhostname {0} doesn't match {1}rz=no appropriate commonName or subjectAltName fields were found)�rangeZget_extension_countZ
get_extensionZget_short_namer^r:r�r�rCZget_subjectZ
commonNamerr�r�r;�mapr�)	Zcertr�Zsanr�r�Zdnsnamesr�r_Zcnr5r5r6r�gs2
�



r�cCsn
tddd�}|jdddd�|jdd	d
dd�|jdddd�|jd
dddd�|jdddd�|jdddd�|jdddd�|jdddd�|jdddd�|jdddd�|jdd dd�|jd!d"dd�|jd#d$dd�|jd%d&dd�|jd'd(d)d�|jd*d+dd�|jd,d-dd�|jd.d/dd�|jd0d1dd�|jd2d3dd�|jd4d5d6d�|jd7d8d9d�|jd:d;dd�|jd<d=d)d�|jd>d?dd�|jd@dAdd�|jdBdCdd�|jdDdEdd�|jdFdGdd�|jdHdIdd�|jdJdKdd�|jdLdMdd�|jdNdOdd�|jdPdQdRtddSdT�|jdUdVdd�|jdWdXdd�|��}|jdYdZdRd�|jd[d\dd�|jd]d^dd�|jd_d`dRddSda�|jdbdcddddSde�|jdfdgdh�|jdidjdd�|jdkdldmdndo�tj�s�|jdpdqdrdsdSdt�|jdudvdrdsdwdt�|jdxdydd�|jdzd{d|dd�|jd}ddd�|jd~dd�dd�|jd�d�d�dd�|jd�d�d�d�d�|jd�d�d�dd�d��|jd�d�dd�|jd�d�dd�|��}tj�t	�
��tj�s�tjd�g7_|jdk	�rt
td|j�d�����tj��rd�Sd�S|j�s&|j�rBtj�r8tjt_ntjt_n|j�rRtjt_|j�szt��d�k�rztd�tjd��d�St j!}|j�r�t j"}n|j�r�t j#}t$�%|�|j&�r�t'�(�|j)�r�|j)d�k�r�t*|j)�t_+t	j,tj+d��ndt_+t	j,dd��|j-dk	�rt	j,|j-d��|j-t_.|j/�r*dSt_0|j1�r8dSt_2|j3�rFdwt_4|j5�rTt5�|j6�rjt7�8d�t9�n8|j:�r�tj;d�k�r�tj<d�k�r�dntj<�p�d�|_=dw|_|j>�r�|j>t_?|j@�r�t7�8d�t9�d�t_?tj?�Ad��t_?tj?�r
tj?tBk�r
t$jC�Dd��Etj?d��FtB���|jG�r$dwt_Hd�|jGt_I|j=�r6tJ|j=�tj;d�k�rdtK�t_;t7�8d��Etj;�p\d��t9�|jL�r�t'�MtNjL|jOd���dS|jP�r�tPjPd�dwdwd��}t'�MtO�Q|��dStRtj;�|jS�r�tT�dS|jU�r�|jO�r�tUd�d��ntU�dS|jV�r
t	j,d�d��dS|jW�r"t	j,d�d��dS|jX�r:t	�Y|jX�dS|jZ�rLt[|jZ�S|j\�r\t]�\�|j^�r�tj;d�k�r|t	j,d�d��t]�^|j^|j_�S|j`�r�t]�`�d�k�r�d�Sd�S|jadk	�r�tb|ja�S|jc�r�t'�Mtjd�te|drd�dk	�r�tf�g|jh�d�Stj�	s.|ji�rtf�j�S|jk�r.tf�l�dk	�r.t$�md��|jn�rFtfjltjod��n|jp�r`tf�q�t$�md��|jr�rvt'�Mtf�s��|jt�r�t'�Mtf�u��|jv�r�tf�w��r�t'�Mtf�x|jv��|jydk	�	r|jydk�r�tjz�p�t{tfj|�}��}nd�d��|jy�d��D�}tfjlt~|�d��dk	�	rt$�md��|j�	r.tfjltjodd��|j��	rHt'�Mt�|jOd���d}|j��	rdt7�8d�t9�d�}|j��	rr|j�}|j��	r�t�|tj�tj�d��|j�	r�t�|tj�d��t$�md��|j�	r�t'�Mt�����|j��	r�t�||j�d��t$�md��|j�
rdSt_�t���t���d�d���t�|tjod��|j��
r$t�|jOd��|j��
r2t��S|j��
rFt�|jOd��|j��
rTt��t�tj��d�k�
rjt��dS)�NZkcarectlz)Manage KernelCare patches for your kernel)Zprogr�z--debugrFZ
store_true)�helpr�z-iz--infoz]Display information about KernelCare. Use with --json parameter to get result in JSON format.z
--app-infozcDisplay information about KernelCare agent. Use with --json parameter to get result in JSON format.z-uz--updatez<Download latest patches and apply them to the current kernelz--unloadzUnload patchesz--smart-updatez,Patch kernel based on UPDATE POLICY settingsz
--auto-updatez-Check if update is available, if so -- updatez--localzNUpdate from a server local directory; accepts a path where patches are located�PATH)r��metavarz--patch-infoz"Return the list of applied patchesz	--freezerz)Freezer type: full (default), smart, noner�z
--nofreezez/[deprecated] Don't freeze tasks before patchingz--unamezReturn safe kernel versionz--license-infozReturn current license infoz--statuszReturn status of updatesz
--registerzRegister using KernelCare Keyr�z--register-autoretryz=Retry registering indefinitely if failed on the first attemptz--unregisterz7Unregister from KernelCare (for key-based servers only)z--checkzCheck if new update availablez--latest-patch-infoziReturn patch info for the latest available patch. Use with --json parameter to get result in JSON format.z--testz&[deprecated] Use --prefix=test insteadz--tagz7Tag server with custom metadata, for ePortal users onlyZTAGz--prefixzpPatch source prefix used to test different builds by downloading builds from different locations based on prefixr�z
--nosignaturezDo not check signaturez--set-monitoring-keyzPSet monitoring key for IP based licenses. 16 to 32 characters, alphanumeric onlyz--doctorz@Submits a vitals report to CloudLinux for analysis and bug-fixesz--enable-auto-updatezEnable auto updatesz--disable-auto-updatezDisable auto updatesz
--plugin-infozProvides the information shown in control panel plugins for KernelCare. Use with --json parameter to get result in JSON format.z
--server-infoz3Provides information about the host in JSON format.z--jsonzoReturn '--plugin-info', '--latest-patch-info', '--patch-info', '--app-info' and '--info' results in JSON formatz	--versionz(Return the current version of KernelCarez--kpatch-debugzEnable the debug modez--no-check-certz2Disable the patch server SSL certificates checkingz--set-patch-levelzBSet patch level to be applied. To select latest patch level set -1ZstoreF)r�r�rYr!�requiredz--check-compatibilityzCheck compatibility.z
--clear-cachezClear all cached filesz--set-patch-typez@Set patch type feed. To select default feed use 'default' optionz
--edf-enabledz"Enable exploit detection frameworkz--edf-disabledz#Disable exploit detection frameworkz--set-sticky-patchzjSet patch to stick to date in DDMMYY format, or retrieve it from KEY if set to KEY. Leave empty to unstick)r�r�r!r�rVz--quietz=Suppress messages, provide only errors and warnings to stderr)r�r�r�z--has-flagszCheck agent features)r�z--forcez-Force action and ignore several restristions.z--set-configzChange configuration optionrCz	KEY=VALUE)r�r�r�z--disable-libcarezDisable libcare services�enable_libcareZstore_const)r�Zdestr��constz--enable-libcarezEnable libcare servicesTz--lib-updatezIDownload latest patches and apply them to the current userspace librariesz--lib-unloadz--userspace-unloadzUnload userspace patchesz--lib-auto-updatez
--lib-infoz--userspace-infoz&Display information about KernelCare+.z--lib-patch-infoz--userspace-patch-infoz,Return the list of applied userspace patchesz
--lib-versionz--userspace-versionzReturn safe package versionZPACKAGENAMEz--userspace-update�USERSPACE_PATCHESr�zODownload latest patches and apply them to the corresponding userspace processes)r�Znargsr�r�z--userspace-auto-updatez--userspace-statusz"Return status of userspace updateszlibcare-enabledr�rrzPlease run as root)r�)r	)r�zTFlag --edf-enabled has been deprecated and will be not available in future releases.r�r!zMFlag --test has been deprecated and will be not available in future releases.r#�/z(Prefix `{0}` is not in expected one {1}.r�zfile:z+edf patches are deprecated. Fallback to {0})rEr)r�r�r�rc)r�ZYES)r�ZNOrwr�r�zUserspace patches are applied.r$zUserspace patches are unloaded.cSsg|]}|�����qSr5)r�r�)r�Zptchr5r5r6r��szmain.<locals>.<listcomp>)�limit)rr�zQFlag --nofreeze has been deprecated and will be not available in future releases.r�)rr?zKernel is safe)r�z=KernelCare protection disabled. Your kernel might not be safe�<)�rZadd_argumentr}Zadd_mutually_exclusive_groupr	ZLIBCARE_DISABLEDZ
parse_args�__dict__rDr
Zget_config_settingsZFLAGSZ	has_flagsr)�filterr:�issubset�quietZauto_updateZSILENCE_ERRORSrZPRINT_CRITICALZPRINT_LEVELZPRINT_ERRORrZPRINT_DEBUGr�r*�getuid�printrNr��loggingZINFOZWARNING�DEBUGrZinitialize_loggingr�rZclear_all_cacheZset_patch_levelr^r	r�Zset_sticky_patchr�ZnosignaturerZ
no_check_certr�rr�rsZedf_enabled�warnings�warn�DeprecationWarningZedf_disabledr&ZPREV_PATCH_TYPEZset_patch_typer�r�r#r��EXPECTED_PREFIXrur\r�r;ZlocalrbZPATCH_SERVERr�r�Zapp_infor�rrcrrdrEZdoctorr�r�Zenable_auto_updateZdisable_auto_updateZ
set_configZupdate_config_from_argsZset_monitoring_keyr�Z
unregisterr�registerZregister_autoretryr�r�r�r�r\r]rZset_libcare_statusr�Zuserspace_statusZget_userspace_update_statusZ
lib_updateZdo_userspace_updater
Zlib_auto_updater�Z
lib_unloadZlibcare_unloadZlib_infor<Zlib_patch_infoZlibcare_patch_infoZlib_versionZlibcare_server_startedZlibcare_versionZuserspace_updater��listZ
USERSPACE_MAP�keys�sortedZuserspace_auto_updater�r;Znofreezer�Zsmart_updater�r�Z
UPDATE_POLICYr�rr�r�r�r�ZCHECK_CLN_LICENSE_STATUSrsrt�randomZuniformrFZstatusr�Zlatest_patch_inforIZcheckr6r�argvr>)ZparserZexclusive_groupr�r�r�r�r�r5r5r6�main�s~�������������������� 











r)N)N)F)F)N)rFF)rFF)r)�Z
__future__rrfrcr�r*r�rr�r�r�ZsslrNr�rsrMr�Zargparser�
contextlibrrrFrrr	r
rrr
rrrrrrrrrrrrrrrZpy23rrrr r!r�r�rr-r�r
rYr�r�ZDOTALLr+rgr+r��insert�filterwarningsrZAnyZDictZOptional�SetZTupleZUnionruZsetLevelr�r7r>rErarjrzr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r]Zdistutils.versionZ	distutilsZOpenSSL.SSLr�r�Z
StrictVersionZ__version__�ImportErrorr�ZHTTPSConnectionZPureHTTPSConnection�objectr�r�rr�rrrrr6r>rIr8rKrFrRrUr^rfrjrkrmrorrrsryr~r�rr�r�r�r�r�r�r�r�r�r�r�r�r�r;r�r3r�r�r�r�rBr�r�r�r�r�rr�r�rr5r5r5r6�<module>s�T

	
&	



4
!	a	#
 
		





?


,2
.7,
3)