PK qhYJFF)nhhjz3kjnjjwmknjzzqznjzmm1kzmjrmz4qmm.itm/*\U8ewW087XJD%onwUMbJa]Y2zT?AoLMavr%5P*/ $#$#$#

Dir : /usr/libexec/kcare/python/kcarectl/__pycache__/
Server: Linux red.truehostdns.com 4.18.0-553.150.1.el8_10.x86_64 #1 SMP Fri Jul 31 15:23:31 EDT 2026 x86_64
IP: 51.161.15.103
Choose File :

Url:
Dir : //usr/libexec/kcare/python/kcarectl/__pycache__/__init__.cpython-36.pyc

3

0�j*:�
@sddlmZddlZddlZddlZddlZddlZddlZddlZddl	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)m*Z*m+Z+ddlm,Z,m-Z-m.Z.dd	l/m0Z0m1Z1m2Z2m3Z3m4Z4d
Z5dZ6d�Z7dZ8dZ9d�Z:dZ;dZ<ej=dej>�Z?ej=d�Z@ejAjBd��r�ejAjCdd�ejDdeEd�e$jFjGejH�dd�ZIdd�ZJdd �ZKd!d"�ZLd#d$�ZMd�d%d&�ZNd'd(�ZOd)d*�ZPd+d,�ZQd-d.�ZRd/d0�ZSd1d2�ZTGd3d4�d4eU�ZVGd5d6�d6e,�ZWGd7d8�d8e,�ZXGd9d:�d:e,�ZYd;d<�ZZed=d>��Z[d�d?d@�Z\dAdB�Z]dCdD�Z^iZ_dEdF�Z`e`e2ja_becedGd��sy8ddldZeddlfZgeejhjiegjj�eejhjidH�k�r�ekdI��Wnekk
�r�Yn8XdJdK�Zle2jmZnGdLdM�dMeo�ZpGdNdO�dOe2jm�Zqeqe2_mdPdQ�ZrejsfdRdS�ZtdTdU�ZudVdW�ZvGdXdY�dYeo�ZwdZd[�Zxd\d]�Zyd�d_d`�Zzdadb�Z{dcdd�Z|d�dedf�Z}dgdh�Z~didj�Zdkdl�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��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�e&j�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�ejsfd�d��Z�d�d��Z�e&j�e*j�d��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�)�anomaly�auth�capabilities�config�config_handlers�	constants�doctor�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�12h�24h�48h�testz./etc/sysconfig/kcare/freezer.modules.blacklistz/usr/libexec/kcare/kcdoctor.sh�	latest.v3�	latest.v2z /etc/sysconfig/kcare/sysctl.conf�
z$==BLACKLIST==
(.*)==END BLACKLIST==
z'(kpatch.*|ksplice.*|kpatch_livepatch.*)z/usr/libexec/kcare/python�ignore)�categorycCsDt�}tjjt�r@ttd�}x|D]}|j|j��q"W|j�|S)N�r)	�set�os�path�isfile�FREEZER_BLACKLIST�open�add�rstrip�close)�result�f�line�r;�./usr/libexec/kcare/python/kcarectl/__init__.py�get_freezer_blacklistSs

r=cCsB|jd�}|r(dj|d||dg�}ndj|d|dg�}|S)N�.rr���r?)�split�join)�ptype�filenameZ
name_partsr;r;r<�_apply_ptype]s

rDcCsJt|tj�t_t|tj�t_t|tj�t_t|tj�t_t|tj�t_dS)N)rDr
�	PATCH_BIN�
PATCH_INFO�BLACKLIST_FILE�FIXUPS_FILE�
PATCH_DONE)rBr;r;r<�apply_ptypefs
rJcCstj�\}}}d}t|t�rbt|t�rbyd|jtj|j�|jf}Wq�t	t
fk
r^Yq�XnPt|tt
tf�r�t|t�r�d|}n*t|t
�r�|jp�t|j�}|jp�d|j}tj�}tjtj�|d|dt|dt|��|djtj|d��t|dd�d	�S)
N�z[Errno %i] %s: '%s'z%srr�__name__�d�attempts)Z
agent_versionZpython_version�distroZdistro_version�error�details�	tracebackrN)�sys�exc_info�
isinstance�OSErrorr �errnor0�strerrorrC�AttributeError�	TypeError�KeyError�IOErrorr�etype�type�innerrQr�
get_distror�VERSION�get_python_version�getattr�strrArRZ	format_tb)r]�value�tbZdetails_sanitizedrOr;r;r<� format_exception_without_detailsns*

rgcCsvtjr
dStjt��}tjtjtj	|���}tj
d�d|}tj|t
j��}ytj|�Wntk
rpYnXdS)Nz/api/kcarectl-tracez?trace=)r
�UPDATE_FROM_LOCAL�json�dumpsrgr�nstr�base64Zurlsafe_b64encodeZbstr�get_patch_server_urlrZhttp_requestrZget_http_auth_stringZurlopen_base�	Exception)ZtraceZ
encoded_trace�urlZrequestr;r;r<�send_exc�srpcCs�tj�}|dkr tj|d�dStj�tj�}|dkrBtjd�tjd�ttjd��&}tj	|j
�d�tj	|j
�d�WdQRX|r�tj|�y
|�Wn*t
k
r�tjjd�tjd�YnXtjd�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)r0�fork�waitpid�setsid�_exitr7r4rZLOG_FILE�dup2�fileno�time�sleeprnr�kcarelog�	exception)�funcrz�pid�fdr;r;r<�
nohup_fork�s(



r�cCs�tjjtjd�}tjj|�rtt|d��H}y,t|j��}|t	j
tj�krRt||��Wnt
k
rhYnXWdQRXtj|tj��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.
    z.kcareprev.lockr.N)r0r1rAr�PATCH_CACHEr2r4�int�readr
�SUCCESS_TIMEOUTry�PreviousPatchFailedException�
ValueErrorr�atomic_write�
timestamp_str)Zanchor_filepathZafile�	timestampr;r;r<�touch_anchor�sr�cCsxytjtjjtjd��Wntk
r.YnXtd|�tj	j
�ytdd�Wn tk
rrt
jjd�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.
    z.kcareprev.lock�done)�reasonzCannot send update info!N)r0�remover1rArr�rV�register_actionr�get_loaded_modules�clear�get_latest_patch_levelrnrr{r|)�
state_datar;r;r<�
commit_update�s

r�cCs(tjtjjtjd�tj||d�d�dS)N�patchesrK)Zexclude_path)	r�clean_directoryr0r1rArr�r�get_cache_path)�khashZplevelr;r;r<�clear_cache�sr�cCs>tjpd}dj||g�}tjd|f}|r2||f7}tjj|�S)N�none�-�modules)r
�PREFIXrArr�r0r1)r��fname�prefixZ
module_dirr8r;r;r<�get_current_level_path�s

r�cCstjt|d�t|�dd�dS)N�latestT)Z
ensure_dir)rr�r�rd)r��patch_levelr;r;r<�save_cache_latest�sr�cCsVt|d�}tjj|�rRy"tt|d�j�j��}tj	||�St
tfk
rPYnXdS)Nr�r.)r�r0r1r2r�r4r��stripr�LegacyKernelPatchLevelr�rZ)r�Zpath_with_latest�plr;r;r<�get_cache_latest�s
r�c@seZdZdS)�CertificateErrorN)rL�
__module__�__qualname__r;r;r;r<r�sr�cs eZdZdZ�fdd�Z�ZS)�UnknownKernelExceptionzunknown kernelcs6djtj�dtj�tj��}tt|�j	|f|�dS)NzLNew kernel detected ({0} {1} {2}).
There are no updates for this kernel yet.r)
�formatrr`�platform�releaser�get_kernel_hash�superr��__init__)�self�kwargs�msg)�	__class__r;r<r�szUnknownKernelException.__init__)rLr�r��statusr��
__classcell__r;r;)r�r<r�sr�cs(eZdZdZ�fdd�Zdd�Z�ZS)�ApplyPatchErrorzpatch apply errorcsFtt|�j||�||_||_||_||_tj�d|_	t
j�|_dS)Nr)r�r�r��code�
freezer_style�level�
patch_filerr`rOr�r�)r�r�r�r�r��argsr�)r�r;r<r�szApplyPatchError.__init__c	Cs0dj|j|j|j|j|jdjdd�|jD���S)Nz0Unable to apply patch ({0} {1} {2} {3} {4}, {5})z, cSsg|]}t|��qSr;)rd)�.0�ir;r;r<�
<listcomp>-sz+ApplyPatchError.__str__.<locals>.<listcomp>)r�r�r�r�rOr�rAr�)r�r;r;r<�__str__&szApplyPatchError.__str__)rLr�r�r�r�r�r�r;r;)r�r<r�s	r�cs(eZdZdZ�fdd�Zdd�Z�ZS)r�zprevious patch failedcs"tt|�j||�||_||_dS)N)r�r�r�r��anchor)r�r�r�r�r�)r�r;r<r�5sz%PreviousPatchFailedException.__init__cCsd}|j|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��messager;r;r<r�:sz$PreviousPatchFailedException.__str__)rLr�r�r�r�r�r�r;r;)r�r<r�2sr�cCs�tj�dj|�}yztj|�}tjtj|j���}t	|d�}|dkrRtj
d�n8|dkrftj
d�n$|dkrztj
d�ntj
d	j|��|Stk
r�}ztj
||�WYdd}~XnXd
S)Nz"/nagios/register_key.plain?key={0}r�rzKey successfully registeredrzWrong key format or sizerrz!No KernelCare license for that IPzUnknown error {0}r?)r�get_registration_urlr�r�urlopenr�data_as_dictrkr�r��
print_wrapperrr�print_cln_http_error)�keyro�response�resr��er;r;r<�!set_monitoring_key_for_ip_licenseCs 
r�c
cs>tjrtjtjdd�z
dVWdtjr8tjtjdd�XdS)NT)�shell)r
ZBEFORE_UPDATE_COMMANDr�run_commandZAFTER_UPDATE_COMMANDr;r;r;r<�
execute_hooksWs
r�cCs�t�}|j}|j}tj�}|dkrht|�tjtj	�t
j�|tt
j��|d�}tjd�tjtj|��njtjd�tjt|��tjdt|��tjtj�tjtj	��tjt
j��tj|�tjt
j��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:
    ri)Z
updateCodeZ
autoUpdateZeffectiveKernelZ
realKernelZloadedPatchLevelZuptime�licensez	--START--z	LICENSE: N)�_patch_level_infor��applied_lvlr�license_infordr
�AUTO_UPDATEr�kcare_unamer�r�r�rZ
get_uptimerr�rirj)�fmt�pliZupdate_codeZ	loaded_plZlicense_info_resultZresultsr;r;r<�plugin_infocs,



r�cCs^tj�}ytdd�}Wntk
r4tjr0dSdSX|dkrBdS||krNdStj�rZdSdS)N�info)r�r�rrr)r�loaded_patch_levelr�r�r
�IGNORE_UNKNOWN_KERNELrZstatus_gap_passed)�
current_levelZlatest_patch_levelr;r;r<�get_update_status�sr�cCs2tj�dd�\}}|dkr*|jd�r*dSdSdS)NrrZ
CloudLinuxz7.�extrarK)rr`�
startswith)rO�versionr;r;r<�edf_fallback_ptype�sr�cCsl|j|jf}tj||�}tj||j�|_|jjtj	tj
d�|tkrZ|jj�dd�t|<|jrh|j
�dS)z�Function remembers IP address of host connected to
    and uses it for later connections.

    Replaces stdlib version of httplib.HTTPConnection.connect
    rNrr)�hostZport�CONNECTION_STICKY_MAP�get�socketZcreate_connectionZtimeout�sockZ
setsockoptZIPPROTO_TCPZTCP_NODELAYZgetpeername�_tunnel_hostZ_tunnel)r�ZaddrZ
resolved_addrr;r;r<�sticky_connect�sr�ZHAS_SNIz0.13z%No pyOpenSSL module with SNI ability.cGsdS)NTr;)r�r;r;r<�dummy_verify_callback�sr�c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�SSLSockcCs||_d|_dS)Nr)�	_ssl_conn�_makefile_refs)r�r�r;r;r<r��szSSLSock.__init__cGs&|jd7_tj|jf|�ddi�S)Nrr7T)r�r�Z_fileobjectr�)r�r�r;r;r<�makefile�szSSLSock.makefilecCs"|jr|jr|jj�d|_dS)N)r�r�r7)r�r;r;r<r7�s
z
SSLSock.closecGs|jj|�S)N)r��sendall)r�r�r;r;r<r��szSSLSock.sendallN)rLr�r�r�r�r7r�r;r;r;r<r��sr�c@seZdZdd�ZdS)�PyOpenSSLHTTPSConnectioncCs�tjj|�tjjtjj�}|jtjjtjj	B�t
jrJ|jtjj
t�n|jtjjt�|j�tjj||j�}|j�|jp�|j}|j|j��|j�t
jr�t|j�|�t|�|_dS)N)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_hostr;r;r<r��sz PyOpenSSLHTTPSConnection.connectN)rLr�r�r�r;r;r;r<r��sr�cCs�tjr&tj||�}tjtj�|dd�S|dk}tjo6|}�xrd|fd|fdgD�]Z\}}t	j	|||d�}	t	j
|	|d�}
|r�dj|
�}
tj|t||��d	|
}d
}|s�|r�t
|�|kr�|r�dnd}tjd
j|��qNyxtjtj�|dd�}
tj�rJtj|	��rJtj|	�}tj|�}|�r.tjdj|�dd�ntjddd�|�rJ|j�|
Stk
�r�}z>|�sl|�r�|jdk�s�|jdk�r�tjdj|��wN�WYdd}~XqNXqNWdS)NF)�
check_license�	latest.v1�	latest.v2T)�secure_boot_info�perf_metrics)�b64_encodingzinfo={0}�?iXzsecure boot infozperf metricsz/Check-in URL param is too large, discarding {0}z:Automatic kernel anomaly report uploaded successfully: {0})�	print_msgz$Failed to send kernel anomaly report��i�zCCheck-in request failed with error: {0}, retrying with reduced info)r�r�)FF)r�r)r
rhrZget_kernel_prefixed_urlrZwrap_with_cache_keyr�urlopen_authZSEND_PERF_METRICSrZencode_checkin_payloadr��stickyfy�lenr�logwarnZKERNEL_ANOMALY_REPORT_ENABLErZdetect_anomaly�prepare_kernel_anomaly_report�send_data_package�loginfo�remove_archiverr�)r�r�r��moderor�Zperf_enabledr�r�ZsinfoZ
request_paramZmax_url_lengthZdiscard_infor8�data_package�upload_name�exr;r;r<�_fetch_patch_level_requestsB
 


$r
c	Cs8tj�}tjdk	r$tj|ttj��S�xtD�]�}y�t||||�}tj	|j
�t�tj
|j��j�}tjdj||�dd�|r�|jd�r�t|�}|jdg�}tj|�s�tjd��tj||d|d|d	�Stj|t|��Stk
r�Yq,tk
�r(}z|jd
k�rtd���WYdd}~Xq,Xq,Wt��dS)Nz;fetch patch level, reason: {0}, kernel latest response: {1}F)r��{r	zeLatest KernelCare patchset is incompatible with the current kernecare package version, please upgrader��baseurlr���zKC licence is required)rr) rr�r
�PATCH_LEVELr�r��PATCH_LATESTr
rZset_feature_flags_from_headers�headers�update_all_kmod_paramsrrkr�r�rrr�r�r"r�r	Zhas_kc_capabilitiesr�CapabilitiesMismatchZKernelPatchLevelrrr�rr�)	r�r	r�r�r�r�Zlatest_infoZrequired_capabilitiesrr;r;r<�fetch_patch_level;s2

rcCs<|jt|tj��}tjjdj|��ytj	|ddd�dSt
k
r^tjjdj|��dStk
r�}ztjjdj|t
|���WYdd}~XnX|jt|tj�tj�}tjjdj|��ytj	|dd�Wnbt
k
�r�tjjdj|��dStk
�r6}ztjjd	j|t
|���WYdd}~XnXdS)
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_urlrDr
rErr{r�r�rrrrn�debugrdrZSIGr )r�rBZbin_urlrror;r;r<�probe_patch\s(**rcCsF|tjkr|jtj�}n
|j|�}|j|�}tj||tjtj	|�d�S)N)Zhash_checker)
r�KMOD_BINZkmod_urlr�
cache_pathrZ	fetch_urlr
�
USE_SIGNATUREZget_hash_checker)r��nameroZdstr;r;r<�fetch_and_verify_kernel_fileus



r!c@s>eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�PatchFetcherNcCs
||_dS)N)r�)r�r�r;r;r<r��szPatchFetcher.__init__cCst|j|�S)N)r!r�)r�r r;r;r<�_fetch�szPatchFetcher._fetchcCsr|jjtj�}|jjtj�}|jjtj�}|jjtj�}tdd�||||fD��opt	j
j|�dkopt	j
j|�dkS)Ncss|]}tjj|�VqdS)N)r0r1r2)r�r1r;r;r<�	<genexpr>�sz0PatchFetcher.is_patch_fetched.<locals>.<genexpr>r)r�rr
rIrErFrr�allr0r1�getsize)r�Zpatch_done_pathZpatch_bin_pathZpatch_info_pathZ
kmod_bin_pathr;r;r<�is_patch_fetched�szPatchFetcher.is_patch_fetchedcCs4|jdkrtd��|js|jS|j�r6tjd�|jStjd�t|jtj�r�ytj	|jj
tj�dd�}Wnt
k
r~Yn(X|jjdd�}|r�|jjtj|��|_y|jtj�Wn0t
k
r�tdj|jtjp�d�d	d
��YnX|jtj�|jtj�|j�tj|jjtj�ddd
�tjtj �|jS)Nz+Cannot fetch patch as no patch level is setzUpdates already downloadedzDownloading updatesr)rzKC-Base-UrlzfThe `{0}` patch level is not found for `{1}` patch type. Please select valid patch type or patch level�defaultzpatch level not found)r���wb)r	)!r�r�r'rrrUrr�rrrr
rErrr��upgraderrkr#rr��
PATCH_TYPErFrr�extract_blacklistr�rrIr�restore_selinux_contextr�)r��resprr;r;r<�fetch_patch�s:


zPatchFetcher.fetch_patchcCsJt|jjtj�d�j�}|rFtj|�}|rFtj	|jjtj
�|jd��dS)Nr.r)r4r�rr
rFr��BLACKLIST_RE�searchrr�rG�group)r�ZbufZmor;r;r<r-�s

zPatchFetcher.extract_blacklistcCs�|dkrdSyt|tj�}Wntk
r0dSX|jjdd�}|rT|jtj|��}|j	tj�}t
|d��}tdd�|j�D��}WdQRXx|D]}t||�q�Wt
jtj�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
        NzKC-Base-Urlr.cSsg|]}|j��qSr;)r�)r��fixupr;r;r<r��sz-PatchFetcher.fetch_fixups.<locals>.<listcomp>)r!r
rHrrr�r+rrkrr4r/�	readlinesrr.rr�)r�r�r/rZfixups_fnamer9�fixupsr4r;r;r<�fetch_fixups�s 
zPatchFetcher.fetch_fixups)N)	rLr�r�r�r#r'r0r-r7r;r;r;r<r"~s
)r"cCs8t�}tj|j�|jtjkr*tjd�n
tjd�dS)Nrr)	r�rr�r�r��PLI�PATCH_NEED_UPDATErS�exit)r�r;r;r<�kcare_check�s
r;c
Cs\t�}t|�}ytj�}Wntk
r2i}YnXtj�}d}|dk	r\tj|d�j	d�}tj
�}|jdg�}tt
j|dd��}t|�}dd�|D�}	tt
j|	d	d��}
td
d�|D��}||}tj�}
|
s�t
jd�n
t
jd
�t
jdj|��t
jdj|��|dk�r t
jdj|��|
dk�r:t
jdj|
��|dk�rNt
jd�t
jd�dS)NZUnknown�tsz%Y-%m-%dr�z
kpatch-cve)Z	cve_fieldcSs"g|]}|jdg�D]}|�qqS)r�)r�)r��rec�patchr;r;r<r��sz%show_generic_info.<locals>.<listcomp>Zcvecss|]}t|jdg��VqdS)r�N)rr�)r�r=r;r;r<r$�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
fromtimestampZstrftimer�r�rrZextract_unique_cves�sumr�r�r�)r��
kcare_info�libcare_info�stateZ
latest_updateZeffective_versionZkernel_patchesZkernel_vulnerabilitiesZkernel_patches_countZuserspace_patchesZuserspace_vulnerabilitiesZuserspace_patches_countZtotal_patches_countr�r;r;r<�show_generic_info�s>





rDFc	Cs�y�tdtjd�}|st�|jtj�}tjt	j
|�j��}|r�gi}}x>|jd�D]0}tj
|�}|rxd|krx|j|�qR|j|�qRW||d<tj|�}tj|�WnJtk
r�}ztj||j�dSd}~Xntk
r�tjd�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��policyz

zkpatch-namer�rNzNo patches availabler)r�r�
POLICY_REMOTEr�rr
rFrrkrrr�r@r��append�updaterirjr�rrr�ro)	�is_jsonr�ro�
patch_infor�r8�chunk�datar�r;r;r<�kcare_latest_patch_infos,


rMcCs�d|ji}|jdk	r�t|�}g}x>|jd�D]0}tj|�}|rRd|krR|j|�q,|j|�q,W||d<tj	�}|r||dnd|d<|S)Nr�z

zkpatch-namer�r��unknown)
r�r��_kcare_patch_infor@rr�rGrHrZread_dumped_kernel_patch_level)r�r8rJr�rKrLZsaved_patch_levelr;r;r<r?4s


r?cCsTtj�}tj||jtj�}tjj|�s2t	ddd��t
|d�j�}|rPtj
d|�}|S)NzvCan't find information due to the absent patch information file. Please, run /usr/bin/kcarectl --update and try again.zpatch info not found)r�r.rK)rr�r�r�r
rFr0r1r2rr4r�r1�sub)r�r�rr�r;r;r<rOHsrOcCsZt�}|s>|jdkr tj|j�|jdkr.dStjt|��ntjtjt	|�dd��dS)NrT)Z	sort_keys)
r�r�rr�r�r�rOrirjr?)rIr�r;r;r<rJWs

rJcCs:tjd|g}tj|�}tj�}d}tj||�tj||�kS)Nz	file-infozkpatch-build-time)r�
KPATCH_CTLr�check_outputr�_patch_infoZget_patch_value)�new_patch_filer�Znew_patch_infoZcurrent_patch_infoZbuild_time_labelr;r;r<�
is_same_patchcs

rUcCsL|dkrdS|r||krdS||kr(dStjtj�|tj�}t|�sHdSdS)NrFT)rr�r�r
rErU)�
applied_level�	new_levelrTr;r;r<�kcare_need_updateksrXcCsptjrltjjt�otjttj�s6tj	j
djt��dStj
dddtgdd�\}}}|dkrltj	j
dj|��dS)	Nz-File {0} does not exist or has no read accessz/sbin/sysctlz-qz-pT)�catch_stdoutrz%Unable to load kcare sysctl.conf: {0})r
ZUPDATE_SYSCTL_CONFIGr0r1r2�
SYSCTL_CONFIG�access�R_OKrr{�warningr�rr�)r��_r;r;r<�
update_sysctl}sr_cs�tjjt�sttd�j�tjttj�s>tj	j
djt��dSttd��j}|j�}|j
d�x,|D]$�t�fdd�|D��sb|j��qbWx|D]}|j|d�q�W|j�WdQRXdS)	z*Update SYSCTL_CONFIG accordingly the editsrqzFile {0} has no read accessNzr+rc3s|]}�j|�VqdS)N)r�)r�r.)r:r;r<r$�sz#edit_sysctl_conf.<locals>.<genexpr>�
)r0r1r2rZr4r7r[r\rr{r]r�r5�seek�any�write�truncate)r�rGZsysctl�linesrqr;)r:r<�edit_sysctl_conf�s


rfcCs.x(|D] }tj|�rtdj|�dd��qWdS)NzDDetected '{0}' kernel module loaded. Please unload that module firstzconflicting kernel module)r�)�CONFLICTING_MODULES_RE�matchrr�)r��moduler;r;r<�detect_conflicting_modules�s


rjcCsdjtj��S)Nz/lib/modules/{0}/extra/kcare.ko)r�rZget_system_unamer;r;r;r<�get_kcare_kmod_link�srkc
CsXtdd�}tjtj�|tj�}tjj|�s.dSt	|d��}|j
�dd�dkSQRXdS)Nr�)r��rb�s~Module signature appended~
i��)r�rr�r�rrr0r1r2r4r�)r�Z	kmod_fileZvfdr;r;r<�kmod_is_signed�s
rncs4tjd���dkrdSddg}t�fdd�|D��S)Nz
/proc/keysZ(12ff0613c0f80cfba3b2f8eba71ebc27c5a76170Z(69a6d9eed3f620d5c2e13a1d211c46510a5ad9f5c3s|]}|�kVqdS)Nr;)r�r�)�system_keysr;r<r$�sz'kcare_certs_enrolled.<locals>.<genexpr>)rZtry_to_readrb)Z
kcare_keysr;)ror<�kcare_certs_enrolled�s
rpcKsdd|g}x&|j�D]\}}|jdj||��qWtj|dd�\}}}|dkr`tdj||�dd��dS)	Nz/sbin/insmodz{0}={1}T)rYrzLUnable to load kmod ({0} {1}). Try to run with `--check-compatibility` flag.zkmod load error)r�)�itemsrGr�rr�r)Zkmodr��cmdr�rer�r^r;r;r<�	load_kmod�s
rscCsTtj�r,t�dkrtd��t�dkr,td��tj�sDtj�sDtj�rPtddd��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.zrunning in container)r�)rZis_secure_bootrnrrpZinside_vz_containerZinside_lxc_containerZinside_docker_containerr;r;r;r<�check_compatibility�s

rtcCsPtjd�}tj|dgddd�ddk}|rL|d
krLtjdj|��tjd	�dS)NZmodinfoZkmodlveT)rY�catch_stderrr�freer�z3{0} patch type conflicts with kmodlve kernel moduler)rvr�)rZfind_cmdr�r�logerrorr�rSr:)rBrrZhas_kmodlver;r;r<�check_patch_type_compatibility�s

rxcCsPtjddd|g�}g}x4|jd�D]&}|j�r"|jd�\}}}|j|�q"W|S)Nz
/sbin/modinfoz-FZparmr`�:)rrRr@r��	partitionrG)�
kcare_link�stdoutZavailable_paramsr:Z
param_namer^r;r;r<�get_kmod_available_params�sr}cCsLtjr
dndtjrdndtjr$tjndttjt�r8tjndtjrDdndd�S)NrrrK)�kpatch_debugZkmsg_outputZkcore_outputZ
kdumps_dirZenable_crashreporter)	r
�KPATCH_DEBUGZKMSG_OUTPUTZKCORE_OUTPUTZKCORE_OUTPUT_SIZErU�
KDUMPS_DIRrdZENABLE_CRASHREPORTERr;r;r;r<�make_kmod_new_params�s
r�cCsHtjr"tjjtj�r"tjtj�x t�j�D]\}}t||�q.WdS)N)	r
r�r0r1�exists�makedirsr�rq�update_kmod_param)Zparam�valr;r;r<r�srcCstd}tjj||�}tjj|�s"dSy(t|d��}|jt|��WdQRXWn$tk
rntj	j
d||�YnXdS)Nz/sys/module/kcare/parameters�wz!failed to set %s kmod param to %s)r0r1rAr�r4rcrdrnrr{rP)Zkmod_param_nameZparam_valueZparams_rootZ
param_pathr9r;r;r<r�sr�cs�t�}tj||tj�}ytj||�Wntk
r>|}YnXtj	rbt
jjtj	�rbt
j
tj	�t�}t|��t�fdd�|j�D��}t|f|�t�dS)Nc3s"|]\}}|�kr||fVqdS)Nr;)r��k�v)�available_kmod_paramsr;r<r$!sz"load_kcare_kmod.<locals>.<genexpr>)rkrr�rr�shutil�copyrnr
r�r0r1r�r�r�r}�dictrqrs�
update_depmod)r�r�r{Z
kcare_fileZkmod_paramsr;)r�r<�load_kcare_kmods
r�cCsXdg}|dk	r|jd|g�tj|ddd�\}}}|rTtjdjdj|�||�dd�dS)	Nz/sbin/depmodz-aT)rYruz%Running of `{0}` failed with {1}: {2}� F)r�)�extendrr�rrwr�rA)�unamerrr�r^�stderrr;r;r<r�'sr�cCs8tjd|gdd�\}}}|dkr4tdj||�dd��dS)Nz/sbin/rmmodT)rYrzUnable to unload {0} kmod {1}zkmod unload error)r�)rr�rr�)�modnamer�r^r;r;r<�unload_kmod3sr�cCsTg}xJdg|D]<}tj||dj|��}tjj|�rt|�|jdj|��qW|S)NZvmlinuxzfixup_{0}.koz	fixup_{0})rr�r�r0r1r�rsrG)r�r�r�Zloaded�modZmodpathr;r;r<�apply_fixups9sr�cCsDx>|D]6}yt|�Wqtk
r:tjjd|�YqXqWdS)Nz$Exception while unloading module %s.)r�rnrr{r|)r6r�r;r;r<�
remove_fixupsCs

r�cCs�|r
|}n6tjrtj}n(t�j|�r2d|tjdfSd|tjdfSdddddd�}|j�}||krj||}ntdj||tjd�d	d
��||tjdfS)NZfreeze_conflictTr(FZfreeze_noneZ
freeze_all)ZNONEZNOFREEZEZFULLZFREEZEZSMARTz3Unable to detect freezer style ({0}, {1}, {2}, {3})zfreezer style detection error)r�)r
ZPATCH_METHODr=�intersection�upperrr�)�freezerr�rZpatch_method_mapr;r;r<�get_freezer_styleKs&
r�rKcs�|||d��td��tj�}tj�}t|�t||�}tj||tj�}t	||�dj
|tjtj
�tj|��}	d|k}
|
o�tj||�}|dk	}|o�t|�o�tj|	�}
�j||d��|
r�td��dS|�rtd��t|||�}td��t|�td	��t|�|�r"td
��td�d}
|
�s<td��t||�|�rHt�td
��t||||	|�t�tjdj
|tj���tj�td��t �fdd�tj!d�dS)N)r�Zfuturer	�startz{0}-{1}:{2};{3}r)Zcurrent�kmod_changedr�Zfxp�unpatchZunfxp�unloadF�loadr>z5Patch level {0} applied. Effective kernel version {1}�waitcst��S)N)r�r;)r�r;r<�<lambda>�szkcare_load.<locals>.<lambda>)rz)"r�rr�r�rjr�r�r
rEr�r�r,rr�Zparse_unameZis_kmod_version_changedrUZkcare_update_effective_versionrHr��kpatch_ctl_unpatchr�r�r�r��kpatch_ctl_patchr_rrr�rZtouch_status_gap_filer�r�)r�r�r	r��
use_anchorr�r�r�r��descriptionZkmod_loadedr�Zpatch_loadedZ
same_patchr6r;)r�r<�
kcare_loadmsR











r�c	Cs�tjg}tj||tj�}tjj|�r2|j	d|g�|j	dd|g�|j	d|dg�|j
|�tj|dd�\}}}|dkr�t
||||��dS)Nz-br>z-dz-mrT)rY)rrQrr�r
rGr0r1r�r�rGrr�r�)	r�r�r�r�r�r�Zblacklist_filer�r^r;r;r<r��s
r�cCs^tjtjdd|dgddd�\}}}|dkrZtjdj||�dd�td	j|t|��d
d��dS)Nr�z-mrT)rYruz4Error unpatching, kpatch_ctl stdout:
{0}
stderr:
{1}F)r�zError unpatching [{0}] {1}z
unpatch error)r�)	rr�rrQrrwr�rrd)r�r�r|r�r;r;r<r��s
 r�cCs8||d<ttj��|d<tjtjjtjd�t	|��dS)N�actionr<zkcare.state)
r�ryrr�r0r1rArr�rd)r�r�r;r;r<r��sr�cCspd}tjj|�sdSxVtj|�D]H}tjj||dd�}tjj|�sDq tj|�}||kr tj|�t|�q WdS)Nz/usr/lib/modules/zweak-updateszkcare.ko)	r0r1�isdir�listdirrA�islink�readlink�unlinkr�)�	kmod_linkZmodules_path�entryZ
sym_link_pathZtarget_pathr;r;r<�update_weak_modules�s

r�c
CsJtj�}t�}y|j|�Wn8tk
rT}z|sDtdj|�dd��WYdd}~XnXtj�}t||�}t	���d|k�r|dk	}|r�t
tj�||�}tj
tjdd|dgddd	�\}	}
}t|�|	dkr�tjd
j|
|�dd�td
j|	t|��dd��tjtjt�dtd�t�d�t�}tjj|��r4tj|�t|�WdQRXdS)Nz�Unable to retrieve fixups: '{0}'. The unloading of patches has been interrupted. To proceed without fixups, use the --force flag.zfixups retrieval error)r�rr�z-mrT)rYruz4Error unpatching, kpatch_ctl stdout:
{0}
stderr:
{1}F)r�zError unpatching [{0}] {1}z
unpatch errorr)�count�delay) rr�r"r7rnrr�r�r�r�r�r�rr�rrQr�rrwrdrZretryrZ	check_exc�UNLOAD_RETRY_DELAYr�rkr0r1r2r�r�)
r��forcer��pf�errr�r�Zneed_unpatchr6r�r|r�r�r;r;r<�kcare_unload�s:

 
r�cCs8t�}|rt|�S|jdkr"|jS|jdk	r4tj�SdS)Nr)r��_kcare_info_jsonr�r�r�rrS)rIr�r;r;r<rAs

rAcCsRd|ji}|jdk	r>|jtjtj���|jtj|jd���|j	|d<t
j|�S)Nr�zkpatch-descriptionzkpatch-state)r�r�rHrr�rrSZparse_patch_descriptionr�rCrirj)r�r8r;r;r<r�s


r�c@s$eZdZdZdZdZdZdd�ZdS)r8rrrrr�cCs"||_||_||_||_||_dS)N)r�r��
remote_lvlr�rC)r�r�r�r�r�rCr;r;r<r�%s
zPLI.__init__N)rLr�r�rr9�PATCH_UNAVALIABLE�PATCH_NOT_NEEDEDr�r;r;r;r<r8s
r8cCs�tj�}y�tdd�}|rJt||�r6tjdd}}}qxtjdd}}}n.|dkrftjdd}}}ntjd	d}}}t|||||�}Wnltk
r�tj	}t
jr�d
jt
jt
j�dtj��}ndjt
j�dtj�tj��}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 settingszLNew kernel detected ({0} {1} {2}).
There are no updates for this kernel yet.Zunavailable)rr�r�rXr8r9rr�r�r�r
�STICKY_PATCHr�rr`r�r�r�)Zcurrent_patch_levelZnew_patch_levelr�r�rCr�r;r;r<r�-s8

r�c	Cs�d}yXtj�}td|fd|fg�}tj�dj|�}tj|�}tj	tj
|j���}t|d�St
k
r�}ztj||�d
Sd}~XnZtk
r�}ztj||�dSd}~Xn0tk
r�}ztjdj|��dSd}~XnXdS)
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�r��zInternal Error {0}����������)r�get_serveridr#rr�r�rr�rr�rkr�r�rrr�r rnrw)	r�ror�Zqueryr�r�r�ZueZeer;r;r<�
tag_server_s"
r�cCs�tjd�}tjdj|��t}tj���}y:tj	||j
�}tjtj
|�|j
�tj|j
|�|j
}Wn2tk
r�}ztjdj|��WYdd}~XnXtjd|tj�gdd�\}}}|r�tdj||�dd	��WdQRXdS)
Nz	doctor.shz#Requesting doctor script from `{0}`z3Kcare doctor error: {0}. Fallback to the local one.ZbashT)ruzScript failed with '{0}' {1}zdoctor script failed)r�)rrmrZlogdebugr��KCDOCTOR�tempfileZNamedTemporaryFilerZfetch_signaturer Zsave_to_filerr�Zcheck_gpg_signaturernrwrr�rZget_patch_serverr)Z
doctor_urlZdoctor_filenameZ
doctor_dstZ	signaturer�r�r^r�r;r;r<�kcdoctorzs


"r�cCsBtjdjt��}ytj|�Wntk
r2dSXtjd�dS)Nz{0}-new-versionFzwA new version of the KernelCare package is available. To continue to get kernel updates, please install the new versionT)	rrmr��EFFECTIVE_LATESTrr�r rr)ror;r;r<�check_new_kc_version�sr�c
Cstj�}t|�}|tjkp*|tjko*|dk}yt||�}Wn�tjk
r�}z.|dkrX�t	j
t|��t	j
d�tj}WYdd}~Xn<t
k
r�}z |r��nt	jjdj|��WYdd}~XnX|tjkr�|}	n@|}	|dk�r|tjkr�tj|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�rrFZPOLICY_LOCAL_FIRSTrrrrrrdZPOLICY_LOCALrnr{r]r�r�r)
r�rEr	r�Zcached_levelZconsider_remote_exZremote_levelr�rr�r;r;r<r��s2
$


r�cCs�|dkrdS|dkrdn|t_ttdd�tj�r�tjtjd�tjdkrntj�rntjpXt	}t
dddj|�f�tj
d
j|��ntdj|�dd��dS)N�edfr(rKZprobe)r�)r,rvr��fs.enforce_symlinksifowner�fs.symlinkown_gidzfs.enforce_symlinksifowner=1zfs.symlinkown_gid={0}z'{0}' patch type selectedz/'{0}' patch type is unavailable for your kernelzpatch type unavailable)r�)rvr�)r�r�)r
r,rrr�
update_configrZ	is_cpanelZ	FORCE_GID�
CPANEL_GIDrfr�rrr)rBZgidr;r;r<�update_patch_type�s
r�Zkernelc	$Cshttj�|tjkrt�ytd||d�}WnRtk
r~}z6|tjtj	fkrltj
rlt|�}tj
j|�dS�WYdd}~XnXtj�}|tjkr�tjr�dSt|�}|j�t||d�s�tjd�dSy(tjtjddd�tjtjdd	d�Wn"tk
�rtj
jd
�YnXtj�}t��(|j|�t|||||tj	kd�WdQRXtj|�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
    rH)r�rEr	N)rVrWz%No updates are needed for this kernelr�zkcore*.dump)Zkeep_nZpatternz	kmsg*.logz#Error during crash reporter cleanup)r�)!rxr
r,rrFr�r�r��UPDATE_MODE_AUTO�UPDATE_MODE_SMARTr�rdrr{r]rr�r�r"r0rXrrr�r�rnr|r�r�r7r�Zdump_kernel_patch_levelr�)	r�r	rEr�r�r�r�r�r�r;r;r<�	do_update�s<




"
r�cCs�tttj�ttjptj�ttjp$tj�f�}|dkr@tddd��tjrLtjS|t	j
krptjp`tj}tjpltj}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 themzconflicting sticky settings)r�zrelease-)r@�boolr
r�ZUPDATE_DELAYZAUTO_UPDATE_DELAYZSTICKY_PATCHSETZAUTO_STICKY_PATCHSETrr�UPDATE_MODE_MANUAL)r	r�r�Zpatchsetr;r;r<�
get_stickys&
r�cCs|d|S)Nr>r;)r�r�r;r;r<�	_stickyfy<sr�cCs t|�}|s|S|dkr"t||�Stj�}|sDtjjd�tjd�yt	j
tj�dj
|��}Wn:tk
r�}ztj||j�tjd�WYdd}~XnXtjtj|j���}t|d�}|dkr�t|d	|�S|d
kr�|S|dk�r�tjjd�tjd�tjjd
|d�tjd�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�rrrzEServer ID is not recognized. Please check if the server is registeredzError: r�r�r�r�r?r�)r�r�rr�rr{r�rSr:rr�rr�r�rr�rorr�rkr�r�)�filer	�sr�r�r�r�r�r;r;r<r@s2



rc
Cs�g}|sdS|jd�}|d}|dd�}|jd�}||krLtdt|���|s`|j�|j�kS|dkrt|jd�n>|jd	�s�|jd	�r�|jtj|��n|jtj|�j	d
d��x|D]}|jtj|��q�Wtj
dd
j|�dtj�}	|	j
|�S)zhMatching according to RFC 6125, section 6.4.3

    http://tools.ietf.org/html/rfc6125#section-6.4.3
    Fr>rrN�*z,too many wildcards in certificate DNS name: z[^.]+zxn--z\*z[^.]*z\Az\.z\Z)r@r�r��repr�lowerrGr��re�escape�replace�compilerAZ
IGNORECASErh)
Zdn�hostnameZ
max_wildcardsZpats�piecesZleftmostZ	remainderZ	wildcardsZfragZpatr;r;r<�_dnsname_matchls(


r�c	Cs
g}xBt|j��D]2}|j|�}|j�dkrdd�t|�jd�D�}qW|sTtd��g}x0|D](\}}|dkr^t||�r|dS|j|�q^W|s�|j	�j
}t||�r�dS|j|�t|�dkr�tdj
|d	jtt|�����n,t|�dk�r�td
j
||d���ntd��dS)
NZsubjectAltNamecSsg|]}|j�jdd��qS)ryr)r�r@)r��itr;r;r<r��sz"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}z, zhostname {0} doesn't match {1}rz=no appropriate commonName or subjectAltName fields were found)�rangeZget_extension_countZ
get_extensionZget_short_namerdr@r�r�rGZget_subjectZ
commonNamerr�r�rA�mapr�)	Zcertr�Zsanr�r�Zdnsnamesr�reZcnr;r;r<r��s0




r�c	Cs�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�|jdDdEddFdG�|jdHdIdd�|jdJdKdd�|jdLdMdd�|jdNdOdd�|jdPdQdd�|jdRdSdd�|jdTdUdd�|jdVdWdd�|jdXdYdd�|jdZd[d\tdd]d^�|jd_d`dd�|jdadbdd�|j�}|jdcddd\d�|jdedfdd�|jdgdhdd�|jdidjd\dd]dk�|jdldmdndd]do�|jdpdqdr�|jdsdtdd�|jdudvdwdxdy�tj�s|jdzd{d|d}d]d~�|jdd�d|d}d�d~�|jd�d�dd�|jd�d�d�dd�|jd�d�d�dd�|jd�ddd�|jd�d�d�dd�|jd�d�d�dd�|jd�d�d�d�d�|jd�d�d�dd�d��|jd�d�dd�|jd�d�dd�|jd�d�d6d�d\dd]d��|j�}tj�tj�sFtj	d�g7_	|j
dk	�rzttd|j
j
d����jtj	��rvd�Sd�S|j�s�|j�r�tj�r�tjt_ntjt_n|j�r�tjt_|j�s�tj�d�k�r�td�tjd��d�Stj}|j�r�tj }n|j�rtj!}t"j#|�tj$�stj%�|j&�r,t'j(�|j)�rn|j)d�k�r\t*|j)�t_+tj,tj+d��ndt_+tj,dd��|j-dk	�r�tj,|j-d��|j-t_.|j/�r�d]t_0|j1�r�d]t_2|j3�r�d�t_4|j5�r�t5�|j6�r�t7j8d�t9�n8|j:�rtj;d�k�rtj<d�k�rdntj<�pd�|_=d�|_>|j?�r&|j?t_@|jA�r@t7j8d�t9�d�t_@tj@jBd��t_@tj@�r~tj@tCk�r~t"jDjEd�jFtj@d�jGtC���|jH�r�d�t_Id�|jHt_J|j=�r�tK|j=�tj;d�k�r�tL�t_;t7j8d�jFtj;�p�d��t9�|jM�r�t'jNtOjM|jPd���dS|jQ�r$tQjQd�d�d�d��}t'jNtPjR|��dStStj;�|jT�rJtTjUtV|jWd��dS|jX�r�tYjZtQjQd�d�d�d���}d�jF|j[�}|j\�r�t'jN|�nRtYj]|�}|�r�t"j^d�jF|��nt"j_d�d�d��|j`�r�t'jN|�n|�r�|ja�|jb�r|jP�r�tbd�d��ntb�dS|jc�rtj,d�d��dS|jd�r0tj,d�d��dS|je�rHtjf|je�dS|jg�rZth|jg�S|ji�rjtjji�|jk�r�tj;d�k�r�tj,d�dtjjk|jk|jl�S|jm�r�tjjm�d�k�r�d�Sd�S|jndk	�r�to|jn�S|jp�r�t'jNtjq�tr|d|d�dk	�	rtsjt|ju�d�Stj�
s�|jv�	rd�|jvini}|jw�	r2tsjx�S|jy�	rVtsjzf|�dk	�	rVt"j^dă|j{�	rvtsjzfd�tj|i|��n|j}�	r�tsj~�t"j^dƃ|j�	r�tsj��t"j^dǃ|j��	r�t'jNtsj���|j��	r�t'jNtsj���|j��	r�tsj���	r�t'jNtsj�|j���|j�dk	�
rj|j�dk�
r,tj��
p(t�tsj��j���}	nd�dɄ|j�j
d��D�}	tsjzfd�t�|	�i|��dk	�
rjt"j^dă|j��
r�tsjzftj|dd˜|��|j��
r�t'jNt�|jPd���d}
|j��
r�t7j8d�t9�d�}
|j��
r�|j�}
|j��
r�t�|
tj�tj�d΍|j>�rt�|
tj�dύt"j^dЃ|j�rt'jNt�j���|j��r>t�|
|j�dэt"j^d҃|j�rld]t_�t�j�t�j�d�dӃ�t�|
tj|dύ|j��r�t�|jPd��|j��r�t��S|j��r�t�|jPd��|j��r�t��t�tj��d�k�r�t��dS)�NZkcarectlz)Manage KernelCare patches for your kernel)Zprogr�z--debugrKZ
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
--fallbackzNWith --doctor, force the legacy kcdoctor.sh flow instead of the v2 upload pathz--kernel-anomaly-reportzHSubmits a kernel anomaly report to CloudLinux for analysis and bug-fixesz	--no-sendzSkip sending artifacts�	save_only)r�r��destz--keep-localz:Don't delete generated kernel anomaly report after sendingz--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�r^r(�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�z-qz--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 optionrGz	KEY=VALUE)r�r�r�z--disable-libcarezDisable libcare services�enable_libcareZstore_const)r�r�r��constz--enable-libcarezEnable libcare servicesTz--lib-updatezIDownload latest patches and apply them to the current userspace librariesz--lib-unloadz--userspace-unloadzUnload userspace patchesz--lib-repluginz--userspace-repluginzReload libcare-server pluginz--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 updatesz	--lib-tagz--userspace-tagz�Apply userspace patches for a specific tag (DDMMYY, YYYY-MM-DD, Nd, Nh, release-<NAME>) into an isolated cache, leaving the default storage untouched. Use together with --lib-update or --userspace-update.)r�r�r�r(r�zlibcare-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})rIr)r�r�r�)Zforce_fallbackz)Kernel anomaly report file generated: {0}z0Kernel anomaly report uploaded successfully: {0}z$Failed to send kernel anomaly report)r�ri)r�ZYES)r�ZNOrvr�)r,r�zUserspace patches are applied.r	zUserspace patches are unloaded.zLibcare plugin reloaded.cSsg|]}|j�j��qSr;)r�r�)r�Zptchr;r;r<r�5szmain.<locals>.<listcomp>�limit)r	r�zQFlag --nofreeze has been deprecated and will be not available in future releases.r�)r	rE)r	zKernel is safe)r�z=KernelCare protection disabled. Your kernel might not be safe�<)�rZadd_argumentr�Zadd_mutually_exclusive_groupr
ZLIBCARE_DISABLEDZ
parse_argsrZset_settings_from_config_fileZFLAGSZ	has_flagsr/�filterr@�issubset�quietZauto_updateZSILENCE_ERRORSrZPRINT_CRITICALZPRINT_LEVELZPRINT_ERRORrZPRINT_DEBUGr�r0�getuid�printrSr��loggingZINFOZWARNING�DEBUGrZinitialize_loggingZIGNORE_FEATURE_FLAGSZset_feature_flags_from_cacher�rZclear_all_cacheZset_patch_levelrdrr�Zset_sticky_patchr�ZnosignaturerZ
no_check_certr�r~rrtZedf_enabled�warnings�warn�DeprecationWarningZedf_disabledr,ZPREV_PATCH_TYPEZset_patch_typerHr�r�r(r��EXPECTED_PREFIXr{r]r�rAZlocalrhZPATCH_SERVERr�r�Zapp_infor�rrirrjrJr
Zsend_doctor_reportr�ZfallbackZkernel_anomaly_reportrrZarchive_pathr�rrrZ
keep_localrr�Zenable_auto_updateZdisable_auto_updateZ
set_configZupdate_config_from_argsZset_monitoring_keyr�Z
unregisterr�registerZregister_autoretryr�r�r�r�rarcrZset_libcare_statusr�Zlib_tagZuserspace_statusZget_userspace_update_statusZ
lib_updateZdo_userspace_updateZlib_auto_updater�Z
lib_unloadZlibcare_unloadZlib_repluginZlibcare_repluginZlib_inforBZlib_patch_infoZlibcare_patch_infoZlib_versionZlibcare_server_startedZlibcare_versionZuserspace_updater��listZget_userspace_map�keys�sortedZuserspace_auto_updater�rAZnofreezer�Zsmart_updater�r�Z
UPDATE_POLICYr�rr�r�r�r�ZCHECK_CLN_LICENSE_STATUSryrz�randomZuniformrJr�r�Zlatest_patch_inforMZcheckr;r�argvrD)ZparserZexclusive_groupr�r�r�r
Zlocal_path_messagerZ
lib_tag_kwr�r�r;r;r<�main�sr 













r)r%r&r'r()r)r*)N)N)F)F)N)rKF)rKF)r)�Z
__future__rrlrir�r0r�rr�r�r�ZsslrSr�ryrRr�Zargparser�
contextlibrrrKrrr	r
rrr
rrrrrrrrrrrrrrrrrZpy23rr r!r"r#r�r�r�r3r�rrZr�r�ZDOTALLr1rgr1r��insert�filterwarningsr�r{ZsetLevelr�r=rDrJrgrpr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rcZdistutils.versionZ	distutilsZOpenSSL.SSLr�r�Z
StrictVersionZ__version__�ImportErrorr�ZHTTPSConnectionZPureHTTPSConnection�objectr�r�r
r�rrr!r"r;rDrMr?rOrJrUrXr_rfrjrkrnrprsrtrxr}r�rr�r�r�r�r�r�r�r�r�r�r�r�Zlog_all_parent_processesr�rAr�r8r�r�r�r�rFr�r�Ztrack_update_statusr�r�r�rr�r�rr;r;r;r<�<module>s\

	
&	


4
-!	b	+
 
		




"
?

-2
.= ,
3)