403Webshell
Server IP : 162.241.219.206  /  Your IP : 216.73.216.30
Web Server : Apache
System : Linux box5669.bluehost.com 5.14.0-687.15.1.el9_8.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Jun 11 08:51:45 EDT 2026 x86_64
User : signavd5 ( 2863)
PHP Version : 8.3.32
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /usr/libexec/kcare/python/kcarectl/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /usr/libexec/kcare/python/kcarectl/__pycache__/__init__.cpython-39.pyc
a

��;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Z7d
Z8dZ9dZ:dZ;dZ<e�=dej>�Z?e�=d�Z@ejA�Bd��r�ejA�Cdd�ejDdeEd�e$jL�MejN�dd�ZOdd�ZPdd�ZQdd�ZRdd �ZSd�d!d"�ZTd#d$�ZUd%d&�ZVd'd(�ZWd)d*�ZXd+d,�ZYd-d.�ZZGd/d0�d0e[�Z\Gd1d2�d2e,�Z]Gd3d4�d4e,�Z^Gd5d6�d6e,�Z_d7d8�Z`ed9d:��Zad�d;d<�Zbd=d>�Zcd?d@�ZdiZedAdB�Zfefe2jg_heiedCd��sz8ddljZkddllZmekjn�oemjp�ekjn�odD�k�r�eqdE��Wneq�y�Yn80dFdG�Zre2jsZtGdHdI�dIeu�ZvGdJdK�dKe2js�Zwewe2_sdLdM�ZxejyfdNdO�ZzdPdQ�Z{dRdS�Z|GdTdU�dUeu�Z}dVdW�Z~dXdY�Zd�d[d\�Z�d]d^�Z�d_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�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�ejyfd�d��Z�d�d��Z�e&j�e*��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)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�r7�./usr/libexec/kcare/python/kcarectl/__init__.py�get_freezer_blacklistSs
r9cCsB|�d�}|r(d�|d||dg�}nd�|d|dg�}|S)N�.r���)�split�join)�ptype�filenameZ
name_partsr7r7r8�_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>r7r7r8�apply_ptypefs
rGcCs�t��\}}}d}t|t�r^t|t�s^zd|jt�|j�|jf}Wq�t	t
fyZYq�0nNt|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�	tracebackrK)�sys�exc_info�
isinstance�OSErrorr �errnor,�strerrorr?�AttributeError�	TypeError�KeyError�IOErrorr�etype�type�innerrNr�
get_distror�VERSIONZget_python_version�getattr�strr=rOZ	format_tb)rZ�value�tbZdetails_sanitizedrLr7r7r8� format_exception_without_detailsns,


�rccCsttjr
dSt�t��}t�t�t�	|���}t�
d�d|}t�|t
���}zt�|�WntynYn0dS)Nz/api/kcarectl-tracez?trace=)r
�UPDATE_FROM_LOCAL�json�dumpsrcr�nstr�base64Zurlsafe_b64encodeZbstr�get_patch_server_urlrZhttp_requestrZget_http_auth_stringZurlopen_base�	Exception)ZtraceZ
encoded_trace�urlZrequestr7r7r8�send_exc�srlcCs�t��}|dkr t�|d�dSt��t��}|dkrBt�d�t�d�ttjd��0}t�	|�
�d�t�	|�
�d�Wd�n1s�0Y|r�t�|�z
|�Wn(t
y�tj�d�t�d�Yn0t�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�_exitr3r0rZLOG_FILE�dup2�fileno�time�sleeprjr�kcarelog�	exception)�funcrv�pid�fdr7r7r8�
nohup_fork�s(

.

r|c	Cs�tj�tjd�}tj�|�r�t|d��P}z,t|���}|t	j
t��krRt||��Wnt
yfYn0Wd�n1s|0Yt�|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.r0�int�readr
�SUCCESS_TIMEOUTru�PreviousPatchFailedException�
ValueErrorr�atomic_write�
timestamp_str)Zanchor_filepathZafile�	timestampr7r7r8�touch_anchor�s$r�cCstzt�tj�tjd��Wnty,Yn0td|�tj	�
�ztdd�Wntynt
j�d�Yn0dS)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=rr~rS�register_actionr�get_loaded_modules�clear�get_latest_patch_levelrjrrwrx��
state_datar7r7r8�
commit_update�s

r�cCs(tjtj�tjd�t�||d�d�dS)N�patchesrH)Zexclude_path)	r�clean_directoryr,r-r=rr~r�get_cache_path)�khashZplevelr7r7r8�clear_cache�sr�cCs>tjpd}d�||g�}tjd|f}|r2||f7}tjj|�S)N�none�-�modules)r
�PREFIXr=rr~r,r-)r��fname�prefixZ
module_dirr4r7r7r8�get_current_level_path�s

r�cCstjt|d�t|�dd�dS)N�latestT)Z
ensure_dir)rr�r�r`)r��patch_levelr7r7r8�save_cache_latest�sr�c	CsVt|d�}tj�|�rRz$tt|d������}t�	||�WSt
tfyPYn0dS)Nr�r*)r�r,r-r.rr0r��stripr�LegacyKernelPatchLevelr�rW)r�Zpath_with_latest�plr7r7r8�get_cache_latest�s
r�c@seZdZdS)�CertificateErrorN)rI�
__module__�__qualname__r7r7r7r8r�sr�cs eZdZdZ�fdd�Z�ZS)�UnknownKernelExceptionzunknown kernelcs:d�t��dt��t���}tt|�j	|fi|��dS)N�LNew 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__r7r8r�s�zUnknownKernelException.__init__)rIr�r��statusr��
__classcell__r7r7r�r8r�sr�cs(eZdZdZ�fdd�Zdd�Z�ZS)�ApplyPatchErrorzpatch apply errorcsJtt|�j|i|��||_||_||_||_t��d|_	t
��|_dS�Nr)r�r�r��code�
freezer_style�level�
patch_filerr]rLr�r�)r�r�r�r�r��argsr�r�r7r8r�szApplyPatchError.__init__cCs0d�|j|j|j|j|jd�dd�|jD���S)Nz0Unable to apply patch ({0} {1} {2} {3} {4}, {5})�, cSsg|]}t|��qSr7)r`)�.0�ir7r7r8�
<listcomp>-�z+ApplyPatchError.__str__.<locals>.<listcomp>)r�r�r�r�rLr�r=r��r�r7r7r8�__str__&s�zApplyPatchError.__str__�rIr�r�r�r�r�r�r7r7r�r8r�s	r�cs(eZdZdZ�fdd�Zdd�Z�ZS)r�zprevious patch failedcs&tt|�j|i|��||_||_dSrA)r�r�r�r��anchor)r�r�r�r�r�r�r7r8r�5sz%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��messager7r7r8r�:s�z$PreviousPatchFailedException.__str__r�r7r7r�r8r�2sr�c
Cs�t��d�|�}z|t�|�}t�t�|����}t	|d�}|dkrRt�
d�n8|dkrft�
d�n$|dkrzt�
d�nt�
d	�|��|WSty�}zt�
||�WYd}~n
d}~00d
S)Nz"/nagios/register_key.plain?key={0}r�rzKey successfully registeredrzWrong key format or sizernz!No KernelCare license for that IPzUnknown error {0}r;)r�get_registration_urlr�r�urlopenr�data_as_dictrgr�r�
print_wrapperrr�print_cln_http_error)�keyrk�response�resr��er7r7r8�!set_monitoring_key_for_ip_licenseCs 
"r�c
csTtjrtjtjdd�z dVWtjrPtjtjdd�ntjrNtjtjdd�0dS)NT)�shell)r
ZBEFORE_UPDATE_COMMANDr�run_commandZAFTER_UPDATE_COMMANDr7r7r7r8�
execute_hooksWs�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:
    re)Z
updateCodeZ
autoUpdateZeffectiveKernelZ
realKernelZloadedPatchLevelZuptime�licensez	--START--z	LICENSE: N)�_patch_level_infor��applied_lvlr�license_infor`r
�AUTO_UPDATEr�kcare_unamer�r�rrZ
get_uptimerr�rerf)�fmt�pliZupdate_codeZ	loaded_plZlicense_info_resultZresultsr7r7r8�plugin_infocs.
�	


r�cCs`t��}ztdd�}Wn ty6tjr.dndYS0|durDdS||krPdSt��r\dSdS)N�infor�r�rrn)r�loaded_patch_levelr�r�r
�IGNORE_UNKNOWN_KERNELrZstatus_gap_passed)�
current_levelZlatest_patch_levelr7r7r8�get_update_status�sr�cCs2t��dd�\}}|dkr*|�d�r*dSdSdS)NrnZ
CloudLinuxz7.�extrarH)rr]�
startswith)rL�versionr7r7r8�edf_fallback_ptype�sr�cCsl|j|jf}t�||�}t�||j�|_|j�tj	tj
d�|tvrZ|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
    rNrn)�hostZport�CONNECTION_STICKY_MAP�get�socketZcreate_connectionZtimeout�sockZ
setsockoptZIPPROTO_TCPZTCP_NODELAYZgetpeername�_tunnel_hostZ_tunnel)r�ZaddrZ
resolved_addrr7r7r8�sticky_connect�sr�ZHAS_SNIz0.13z%No pyOpenSSL module with SNI ability.cGsdS)NTr7)r�r7r7r8�dummy_verify_callback�sr�c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�SSLSockcCs||_d|_dSr�)�	_ssl_conn�_makefile_refs)r�r�r7r7r8r��szSSLSock.__init__cGs(|jd7_tj|jg|�Rddi�S)Nrr3T)r�r�Z_fileobjectr��r�r�r7r7r8�makefile�szSSLSock.makefilecCs |js|jr|j��d|_dSrA)r�r�r3r�r7r7r8r3�s
z
SSLSock.closecGs|jj|�SrA)r��sendallr�r7r7r8r��szSSLSock.sendallN)rIr�r�r�r�r3r�r7r7r7r8r��sr�c@seZdZdd�ZdS)�PyOpenSSLHTTPSConnectioncCs�tj�|�tj�tjj�}|�tjjtjj	B�t
jrJ|�tjj
t�n|�tjjt�|��tj�||j�}|��|jp�|j}|�|���|��t
jr�t|��|�t|�|_dSrA)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��ctxZconnZserver_hostr7r7r8r��sz PyOpenSSLHTTPSConnection.connectN)rIr�r�r�r7r7r7r8r��sr�cCs�tjr&t�||�}t�tj�|dd�S|dv}tjo6|}d|fd|fdfD�]l\}}t	j	|||d�}	t	j
|	|d�}
|r�d�|
�}
t�|t||��d	|
}d
}|s�|r�t
|�|kr�|r�dnd}t�d
�|��qJz~t�tj�|dd�}
tj�rFt�|	��rFt�|	�}t�|�}|�r*tjd�|�dd�ntjddd�|�rF|��|
WSt�y�}zN|�sl|�r�|jdv�s�|jdk�r�t�d�|��WYd}~qJ�WYd}~qJd}~00qJdS)NF��
check_license)z	latest.v1r&T)FF)�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}�Z	print_msg�$Failed to send kernel anomaly report)i�i�i�zCCheck-in request failed with error: {0}, retrying with reduced info)r
rdrZget_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��moderkrZperf_enabledrrZsinfoZ
request_paramZmax_url_lengthZdiscard_infor4�data_package�upload_name�exr7r7r8�_fetch_patch_level_requestsD




�
$rc	Cs>t��}tjdur$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|��WSty�Yq(t�y0}z"|jd
v�rtd���WYd}~q(d}~00q(t��dS)Nz;fetch patch level, reason: {0}, kernel latest response: {1}Fr�{r	zeLatest 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_LATESTrrZset_feature_flags_from_headers�headers�update_all_kmod_paramsrrgr�r�rr
r�r�r"r�r	Zhas_kc_capabilitiesr�CapabilitiesMismatchZKernelPatchLevelrrr�rr�)	r�rr�r�r�r�Zlatest_infoZrequired_capabilitiesrr7r7r8�fetch_patch_level;s4


�"rc
CsB|�t|tj��}tj�d�|��ztj	|ddd�WdSt
y`tj�d�|��YdSty�}z$tj�d�|t
|���WYd}~n
d}~00|�t|tj�tj�}tj�d�|��ztj	|dd�Wndt
�ytj�d�|��YdSt�y<}z$tj�d	�|t
|���WYd}~n
d}~00dS)
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
rBrrwr�r�rrrrj�debugr`rZSIGr )r�r>Zbin_urlrrkr7r7r8�probe_patch\s(..r cCsF|tjkr|�tj�}n
|�|�}|�|�}tj||tjt�	|�d�S)N)Zhash_checker)
r�KMOD_BINZkmod_urlr�
cache_pathrZ	fetch_urlr
�
USE_SIGNATUREZget_hash_checker)r��namerkZdstr7r7r8�fetch_and_verify_kernel_fileus



r%c@s>eZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�PatchFetcherNcCs
||_dSrA)r�)r�r�r7r7r8r��szPatchFetcher.__init__cCst|j|�SrA)r%r�)r�r$r7r7r8�_fetch�szPatchFetcher._fetchcCsr|j�tj�}|j�tj�}|j�tj�}|j�tj�}tdd�||||fD��opt	j
�|�dkopt	j
�|�dkS)Ncss|]}tj�|�VqdSrA)r,r-r.)r�r-r7r7r8�	<genexpr>�r�z0PatchFetcher.is_patch_fetched.<locals>.<genexpr>r)r�r"r
rFrBrCrr!�allr,r-�getsize)r�Zpatch_done_pathZpatch_bin_pathZpatch_info_pathZ
kmod_bin_pathr7r7r8�is_patch_fetched�s��zPatchFetcher.is_patch_fetchedcCs0|jdurtd��|js|jS|��r6t�d�|jSt�d�t|jtj�r�ztj	|j�
tj�dd�}Wnt
y|Yn(0|j�dd�}|r�|j�t�|��|_z|�tj�Wn.t
y�td�|jtjp�d�d	d
��Yn0|�tj�|�tj�|��tj|j�tj�dd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�defaultzpatch level not found�r�r��wb�r)!r�r�r+rr
rRrr�rrrr
rBrrr��upgraderrgr'rr��
PATCH_TYPErCrr!�extract_blacklistr�r"rFr�restore_selinux_contextr~)r��resprr7r7r8�fetch_patch�s>


��zPatchFetcher.fetch_patchcCsJt|j�tj�d���}|rFt�|�}|rFt�	|j�tj
�|�d��dS)Nr*r)r0r�r"r
rCr��BLACKLIST_RE�searchrr�rD�group)r�ZbufZmor7r7r8r3�s

zPatchFetcher.extract_blacklistcCs�|durdSzt|tj�}Wnty0YdS0|j�dd�}|rT|�t�|��}|�	tj�}t
|d��&}tdd�|��D��}Wd�n1s�0Y|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|]}|���qSr7)r�)r��fixupr7r7r8r��r�z-PatchFetcher.fetch_fixups.<locals>.<listcomp>)r%r
rErrr�r1rrgr"r0r+�	readlinesrr4rr~)r�r�r5rZfixups_fnamer5�fixupsr:r7r7r8�fetch_fixups�s4zPatchFetcher.fetch_fixups)N)	rIr�r�r�r'r+r6r3r=r7r7r7r8r&~s
)r&cCs8t�}t�|j�|jtjkr*t�d�n
t�d�dS)Nrr)	r�rr�r�r��PLI�PATCH_NEED_UPDATErP�exit)r�r7r7r8�kcare_check�s
rAcCsZt�}t|�}zt��}Wnty0i}Yn0t��}d}|durZt�|d��	d�}t�
�}|�dg�}tt
j|dd��}t|�}dd�|D�}	tt
j|	d	d��}
td
d�|D��}||}t��}
|
s�t
�d�n
t
�d
�t
�d�|��t
�d�|��|dk�rt
�d�|��|
dk�r8t
�d�|
��|dk�rLt
�d�t
�d�dS)NZUnknown�tsz%Y-%m-%dr�z
kpatch-cve)Z	cve_fieldcSs"g|]}|�dg�D]}|�qqS)r�)r�)r��rec�patchr7r7r8r��r�z%show_generic_info.<locals>.<listcomp>Zcvecss|]}t|�dg��VqdS)r�N)r	r�)r�rCr7r7r8r(�r�z$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�r�r	rZextract_unique_cves�sumr�r�r�)r��
kcare_info�libcare_info�stateZ
latest_updateZeffective_versionZkernel_patchesZkernel_vulnerabilitiesZkernel_patches_countZuserspace_patchesZuserspace_vulnerabilitiesZuserspace_patches_countZtotal_patches_countr�r7r7r8�show_generic_info�s>





rKFc	
Cs�z�tdtjd�}|st�|�tj�}t�t	�
|����}|r�gi}}|�d�D]0}t�
|�}|rvd|vrv|�|�qP|�|�qP||d<t�|�}t�|�WnNty�}zt�||j�WYd}~dSd}~0ty�t�d�Yn0d	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�NrzNo patches availabler)r�r�
POLICY_REMOTEr�rr
rCrrgrrr�r<r��append�updatererfr�rrr�rk)	�is_jsonr�rk�
patch_infor�r4�chunk�datar�r7r7r8�kcare_latest_patch_infos,


rVcCs�d|ji}|jdur�t|�}g}|�d�D]0}t�|�}|rPd|vrP|�|�q*|�|�q*||d<t�	�}|rx|dnd|d<|S)Nr�rMrNr�r��unknown)
r�r��_kcare_patch_infor<rr�rPrQrZread_dumped_kernel_patch_level)r�r4rSr�rTrUZsaved_patch_levelr7r7r8rE4s


rEcCsTt��}t�||jtj�}tj�|�s2t	ddd��t
|d���}|rPt�
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 foundr.r*rH)rr�r�r�r
rCr,r-r.rr0r�r7�sub)r�r�r"r�r7r7r8rXHs�rXcCsZt�}|s>|jdkr t�|j�|jdur.dSt�t|��nt�tjt	|�dd��dS)NrT)Z	sort_keys)
r�r�rr�r�r�rXrerfrE�rRr�r7r7r8rSWs

rScCs: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_labelr7r7r8�
is_same_patchcs

r_cCsL|dkrdS|r||krdS||kr(dSt�t��|tj�}t|�sHdSdS)NrFT)rr�r�r
rBr_)�
applied_level�	new_levelr^r7r7r8�kcare_need_updateksrbcCsptjrltj�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_OKrrw�warningr�rr�)r��_r7r7r8�
update_sysctl}srkcs�tj�t�sttd���t�ttj�s>tj	�
d�t��dSttd��l}|��}|�
d�|D]$�t�fdd�|D��s`|���q`|D]}|�|d�q�|��Wd�n1s�0YdS)	z*Update SYSCTL_CONFIG accordingly the editsrmzFile {0} has no read accessNzr+rc3s|]}��|�VqdSrA)r�)r�r*�r6r7r8r(�r�z#edit_sysctl_conf.<locals>.<genexpr>�
)r,r-r.rfr0r3rgrhrrwrir�r;�seek�any�write�truncate)r�rPZsysctl�linesrmr7rlr8�edit_sysctl_conf�s
rscCs*|D] }t�|�rtd�|�dd��qdS)NzDDetected '{0}' kernel module loaded. Please unload that module firstzconflicting kernel moduler.)�CONFLICTING_MODULES_RE�matchrr�)r��moduler7r7r8�detect_conflicting_modules�s
�rwcCsd�t���S)Nz/lib/modules/{0}/extra/kcare.ko)r�rZget_system_unamer7r7r7r8�get_kcare_kmod_link�srxcCsptdd�}t�t��|tj�}tj�|�s.dSt	|d��$}|�
�dd�dkWd�S1sb0YdS)Nr�r��rbi��s~Module signature appended~
)r�rr�r�rr!r,r-r.r0r�)r�Z	kmod_fileZvfdr7r7r8�kmod_is_signed�s
rzcs4t�d���durdSddg}t�fdd�|D��S)Nz
/proc/keysZ(12ff0613c0f80cfba3b2f8eba71ebc27c5a76170Z(69a6d9eed3f620d5c2e13a1d211c46510a5ad9f5c3s|]}|�vVqdSrAr7)r�r��Zsystem_keysr7r8r(�r�z'kcare_certs_enrolled.<locals>.<genexpr>)rZtry_to_readro)Z
kcare_keysr7r{r8�kcare_certs_enrolled�s
�r|cKs`d|g}|��D]\}}|�d�||��qtj|dd�\}}}|dkr\td�||�dd��dS)	Nz/sbin/insmodz{0}={1}TrdrzLUnable to load kmod ({0} {1}). Try to run with `--check-compatibility` flag.zkmod load errorr.)�itemsrPr�rr�r)Zkmodr��cmdr�rar�rjr7r7r8�	load_kmod�s
�rcCsTt��r,t�durtd��t�dur,td��t��sDt��sDt��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 containerr.)rZis_secure_bootrzrr|Zinside_vz_containerZinside_lxc_containerZinside_docker_containerr7r7r7r8�check_compatibility�s

�r�cCsPt�d�}tj|dgddd�ddk}|rL|dvrLt�d�|��t�d�dS)	NZmodinfoZkmodlveT�re�catch_stderrr��freer�z3{0} patch type conflicts with kmodlve kernel moduler)rZfind_cmdr�r�logerrorr�rPr@)r>r~Zhas_kmodlver7r7r8�check_patch_type_compatibility�s

r�cCsLt�ddd|g�}g}|�d�D]&}|��r |�d�\}}}|�|�q |S)Nz
/sbin/modinfoz-FZparmrm�:)rr\r<r��	partitionrP)�
kcare_link�stdoutZavailable_paramsr6Z
param_namerjr7r7r8�get_kmod_available_params�sr�cCsLtjr
dndtjrdndtjr$tjndttjt�r8tjndtjrDdndd�S)NrrrH)�kpatch_debugZkmsg_outputZkcore_outputZ
kdumps_dirZenable_crashreporter)	r
�KPATCH_DEBUGZKMSG_OUTPUTZKCORE_OUTPUTZKCORE_OUTPUT_SIZErR�
KDUMPS_DIRr`ZENABLE_CRASHREPORTERr7r7r7r8�make_kmod_new_params�s�r�cCsBtjr tj�tj�s t�tj�t���D]\}}t||�q*dSrA)	r
r�r,r-�exists�makedirsr�r}�update_kmod_param)Zparam�valr7r7r8r�srcCs�d}tj�||�}tj�|�s"dSz<t|d��}|�t|��Wd�n1sR0YWn"ty�tj	�
d||�Yn0dS)Nz/sys/module/kcare/parameters�wz!failed to set %s kmod param to %s)r,r-r=r�r0rpr`rjrrwrM)Zkmod_param_nameZparam_valueZparams_rootZ
param_pathr5r7r7r8r�s0r�cs�t�}t�||tj�}zt�||�Wnty<|}Yn0tj	r^t
j�tj	�s^t
�
tj	�t�}t|��t�fdd�|��D��}t|fi|��t�dS)Nc3s"|]\}}|�vr||fVqdSrAr7)r��k�v�Zavailable_kmod_paramsr7r8r(!r�z"load_kcare_kmod.<locals>.<genexpr>)rxrr�rr!�shutil�copyrjr
r�r,r-r�r�r�r��dictr}r�
update_depmod)r�r�r�Z
kcare_fileZkmod_paramsr7r�r8�load_kcare_kmods
r�cCsXdg}|dur|�d|g�tj|ddd�\}}}|rTtjd�d�|�||�dd�dS)	Nz/sbin/depmodz-aTr�z%Running of `{0}` failed with {1}: {2}� Fr)�extendrr�rr�r�r=)�unamer~r�rj�stderrr7r7r8r�'s�r�cCs8tjd|gdd�\}}}|dkr4td�||�dd��dS)Nz/sbin/rmmodTrdrzUnable to unload {0} kmod {1}zkmod unload errorr.)rr�rr�)�modnamer�rjr7r7r8�unload_kmod3sr�cCsPg}dg|D]<}t�||d�|��}tj�|�rt|�|�d�|��q|S)NZvmlinuxzfixup_{0}.koz	fixup_{0})rr�r�r,r-r�rrP)r�r�r�Zloaded�mod�modpathr7r7r8�apply_fixups9sr�c	Cs>|D]4}zt|�Wqty6tj�d|�Yq0qdS)Nz$Exception while unloading module %s.)r�rjrrwrx)r<r�r7r7r8�
remove_fixupsCs
r�cCs�|r
|}n6tjrtj}n(t��|�r2d|tjdfSd|tjdfSdddddd�}|��}||vrj||}ntd�||tjd�d	d
��||tjdfS)NZfreeze_conflictTr-FZfreeze_noneZ
freeze_all)ZNONEZNOFREEZEZFULLZFREEZEZSMARTz3Unable to detect freezer style ({0}, {1}, {2}, {3})zfreezer style detection errorr.)r
ZPATCH_METHODr9�intersection�upperrr�)�freezerr�rZpatch_method_mapr7r7r8�get_freezer_styleKs*�
�r�rHcs�|||d��td��t��}t��}t|�t||�}t�||tj�}t	||�d�
|tjt�
�t�|��}	d|v}
|
o�t�||�}|du}|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�loadrDz5Patch level {0} applied. Effective kernel version {1}�waitcst��SrA)r�r7r�r7r8�<lambda>�r�zkcare_load.<locals>.<lambda>)rv)"r�rr�r�rwr�r�r
rBr�r�r2rr�Zparse_unameZis_kmod_version_changedr_Zkcare_update_effective_versionrQr��kpatch_ctl_unpatchr�r�r�r��kpatch_ctl_patchrkrr
r�rZtouch_status_gap_filer|r�)r�r�rr��
use_anchorr�r�r�r��descriptionZkmod_loadedr�Zpatch_loadedZ
same_patchr<r7r�r8�
kcare_loadmsT


�








r�c	Cs�tjg}t�||tj�}tj�|�r2|�	d|g�|�	dd|g�|�	d|dg�|�
|�tj|dd�\}}}|dkr�t
||||��dS)Nz-brDz-d�-mrTrd)rr[rr�r
rDr,r-r�r�rPrr�r�)	r�r�r�r�r�r�Zblacklist_filer�rjr7r7r8r��s
r�cCs^tjtjdd|dgddd�\}}}|dkrZtjd�||�dd�td	�|t|��d
d��dS)Nr�r�rTr��4Error unpatching, kpatch_ctl stdout:
{0}
stderr:
{1}Fr�Error unpatching [{0}] {1}�
unpatch errorr.)	rr�rr[rr�r�rr`)r�r�r�r�r7r7r8r��s�r�cCs8||d<tt���|d<t�tj�tjd�t	|��dS)N�actionrBzkcare.state)
rrurr�r,r-r=rr~r`)r�r�r7r7r8r��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_pathr7r7r8�update_weak_modules�s

r�c

Csbt��}t�}z|�|�Wn:tyV}z"|sBtd�|�dd��WYd}~n
d}~00t��}t||�}t	���d|v�r|du}|r�t
t��||�}tj
tjdd|dgddd	�\}	}
}t|�|	dkr�tjd
�|
|�dd�td
�|	t|��dd��tjt�t�dtd�t�d�t�}tj�|��r6t�|�t|�Wd�n1�sT0YdS)Nz�Unable to retrieve fixups: '{0}'. The unloading of patches has been interrupted. To proceed without fixups, use the --force flag.zfixups retrieval errorr.rr�r�rTr�r�Frr�r�r)�count�delay) rr�r&r=rjrr�r�r�r�r�r�rr�rr[r�rr�r`rZretryrZ	check_exc�UNLOAD_RETRY_DELAYr�rxr,r-r.r�r�)
r��forcer��pf�errr�r�Zneed_unpatchr<r�r�r�r�r7r7r8�kcare_unload�sB��

��
r�cCs8t�}|rt|�S|jdkr"|jS|jdur4t��SdSr�)r��_kcare_info_jsonr�r�r�rr]rZr7r7r8rHs

rHcCsRd|ji}|jdur>|�t�t����|�t�|�d���|j	|d<t
�|�S)Nr�zkpatch-descriptionzkpatch-state)r�r�rQrr�rr]Zparse_patch_descriptionr�rJrerf)r�r4r7r7r8r�s


r�c@s$eZdZdZdZdZdZdd�ZdS)r>rrrnr�cCs"||_||_||_||_||_dSrA)r�r��
remote_lvlr�rJ)r�r�r�r�r�rJr7r7r8r�%s
zPLI.__init__N)rIr�r�rr?�PATCH_UNAVALIABLE�PATCH_NOT_NEEDEDr�r7r7r7r8r>s
r>c	Cs�t��}z�tdd�}|rJt||�r6tjdd}}}qxtjdd}}}n.|dkrftjdd}}}ntjd	d}}}t|||||�}Wnjty�tj	}t
jr�d
�t
jt
��dt���}nd�t
��dt��t���}t||ddd�}Yn0|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�rbr>r?rr�r�r�r
�STICKY_PATCHr�rr]r�r�r�)Zcurrent_patch_levelZnew_patch_levelr�r�rJr�r7r7r8r�-sF

����
���r�c	
Cs�d}zZt��}td|fd|fg�}t��d�|�}t�|�}t�	t�
|����}t|d�WSt
y�}zt�||�WYd}~dSd}~0ty�}zt�||�WYd}~dSd}~0t�y�}zt�d�|��WYd}~d	Sd}~00dS)
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�rgr�rrrr�r rjr�)	r�rkr�Zqueryr�r�r�ZueZeer7r7r8�
tag_server_s"
r�cCs�t�d�}t�d�|��t}t����}z:t�	||j
�}t�t�
|�|j
�t�|j
|�|j
}Wn4ty�}zt�d�|��WYd}~n
d}~00tjd|t��gdd�\}}}|r�td�||�dd	��Wd�n1s�0YdS)
Nz	doctor.shz#Requesting doctor script from `{0}`z3Kcare doctor error: {0}. Fallback to the local one.ZbashT)r�zScript failed with '{0}' {1}zdoctor script failedr.)rrirZlogdebugr��KCDOCTOR�tempfileZNamedTemporaryFilerZfetch_signaturer$Zsave_to_filerr�Zcheck_gpg_signaturerjr�rr�rZget_patch_serverr)Z
doctor_urlZdoctor_filenameZ
doctor_dstZ	signaturer�r�rjr�r7r7r8�kcdoctorzs


&r�cCsBt�d�t��}zt�|�Wnty2YdS0t�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)	rrir��EFFECTIVE_LATESTrr�r rr
)rkr7r7r8�check_new_kc_version�s�r�c

Cst��}t|�}|tjkp*|tjko*|du}zt||�}Wn�tjy�}z4|durV�t	�
t|��t	�
d�tj}WYd}~nFd}~0t
y�}z&|r��nt	j�d�|��WYd}~n
d}~00|tjkr�|}	n@|}	|du�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�rrOZPOLICY_LOCAL_FIRSTrrrrr
r`ZPOLICY_LOCALrjrwrir�r�r)
r�rLrr�Zcached_levelZconsider_remote_exZremote_levelr�rr�r7r7r8r��s2
(


r�cCs�|dkrdS|dkrdn|t_ttdd�tj�r�tjtjd�tjdvrnt��rntjpXt	}t
dd	d
�|�f�t�
d�|��ntd�|�d
d��dS)N�edfr-rHZprober��r2r�)zfs.enforce_symlinksifownerzfs.symlinkown_gidzfs.enforce_symlinksifowner=1zfs.symlinkown_gid={0}z'{0}' patch type selectedz/'{0}' patch type is unavailable for your kernelzpatch type unavailabler.)r
r2r rr�
update_configrZ	is_cpanelZ	FORCE_GID�
CPANEL_GIDrsr�rr
r)r>�gidr7r7r8�update_patch_type�s
�r�Zkernelc	
Cs�ttj�|tjkrt�ztd||d�}Wn^ty�}zF|tjtj	fvrttj
rtt|�}tj
�|�WYd}~dS�WYd}~n
d}~00t��}|tjkr�tjs�dSt|�}|��t||d�s�t�d�dSz(tjtjddd�tjtjdd	d�Wn t�ytj
�d
�Yn0t��}t��2|�|�t|||||tj	kd�Wd�n1�sd0Yt�|�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
    rQ)r�rLrN)r`raz%No updates are needed for this kernelr�zkcore*.dump)Zkeep_n�patternz	kmsg*.logz#Error during crash reporter cleanup)r�)!r�r
r2rrOr�r�r��UPDATE_MODE_AUTO�UPDATE_MODE_SMARTr�r`rrwrirr�r�r&r6rbr
rr�r�rjrxr�r�r=r�Zdump_kernel_patch_levelr�)	r�rrLr�r�r�r�r�r�r7r7r8�	do_update�s<




8
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 settingsr.zrelease-)rG�boolr
r�ZUPDATE_DELAYZAUTO_UPDATE_DELAYZSTICKY_PATCHSETZAUTO_STICKY_PATCHSETrr�UPDATE_MODE_MANUAL)rr�r�Zpatchsetr7r7r8�
get_stickys,���
r�cCs|d|S)Nr:r7)r�r�r7r7r8�	_stickyfy<sr�c
Cs"t|�}|s|S|dkr"t||�St��}|sDtj�d�t�d�zt	�
t��d�
|��}Wn<ty�}z$t�||j�t�d�WYd}~n
d}~00t�t�|����}t|d�}|dkr�t|d	|�S|d
kr�|S|dk�rtj�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�rrnzEServer ID is not recognized. Please check if the server is registeredr;zError: r�r�)r�r�rr�rrwr�rPr@rr�rr�r�rr�rkrr�rgr�r)�filer�sr�r�r�r�r�r7r7r8r@s2

 

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
    Fr:rrN�*z,too many wildcards in certificate DNS name: z[^.]+zxn--z\*z[^.]*z\Az\.z\Z)r<r�r��repr�lowerrPr��re�escape�replace�compiler=�
IGNORECASEru)
Zdn�hostnameZ
max_wildcardsZpats�piecesZleftmostZ	remainderZ	wildcardsZfragZpatr7r7r8�_dnsname_matchls(

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)r�r)r�r<)r��itr7r7r8r��r�z"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�rPZget_subjectZ
commonNamer	r�r�r=�mapr�)	Zcertr�Zsanr�r�Zdnsnamesr�raZcnr7r7r8r��s2
�



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�|��}|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��|��}t��tj�sFtj	d�g7_	|j
du�rzttd|j
�
d�����tj	��rvd�Sd�S|j�s�|j�r�tj�r�tjt_ntjt_n|j�r�tjt_|j�s�t��d�k�r�td�tjd��d�Stj}|j�r�tj }n|j�rtj!}t"�#|�tj$�st�%�|j&�r,t'�(�|j)�rn|j)d�k�r\t*|j)�t_+tj,tj+d��ndt_+tj,dd��|j-du�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�t7�8d�t9�n8|j:�rtj;d�k�rtj<d�k�rdntj<�pd�|_=d�|_>|j?�r&|j?t_@|jA�r@t7�8d�t9�d�t_@tj@�Bd��t_@tj@�r~tj@tCv�r~t"jD�Ed��Ftj@d��GtC���|jH�r�d�t_Id�|jHt_J|j=�r�tK|j=�tj;d�k�r�tL�t_;t7�8d��Ftj;�p�d��t9�|jM�r�t'�NtOjM|jPd���dS|jQ�r$tQjQd�d�d�d��}t'�NtP�R|��dStStj;�|jT�rJtTjUtV|jWd��dS|jX�r�tY�ZtQjQd�d�d�d���}d��F|j[�}|j\�r�t'�N|�nRtY�]|�}|�r�t"�^d��F|��nt"j_d�d�d��|j`�r�t'�N|�n|�r�|�a�|jb�r|jP�r�tbd�d��ntb�dS|jc�rtj,d�d��dS|jd�r0tj,d�d��dS|je�rHt�f|je�dS|jg�rZth|jg�S|ji�rjtj�i�|jk�r�tj;d�k�r�tj,d�dtj�k|jk|jl�S|jm�r�tj�m�d�k�r�d�Sd�S|jndu�r�to|jn�S|jp�r�t'�Ntjq�tr|d|d�du�	rts�t|ju�d�Stj�
s�|jv�	rd�|jvini}|jw�	r2ts�x�S|jy�	rZtsjzfi|��du�	rZt"�^dġ|j{�	rztsjzfd�tj|i|��n|j}�	r�ts�~�t"�^dơ|j�	r�ts���t"�^dǡ|j��	r�t'�Nts����|j��	r�t'�Nts����|j��	r�ts����	r�t'�Nts��|j���|j�du�
rn|j�dk�
r0tj��
p,t�ts�������}	nd�dɄ|j��
d��D�}	tsjzfd�t�|	�i|��du�
rnt"�^dġ|j��
r�tsjzftj|dd˜|��|j��
r�t'�Nt�|jPd���d}
|j��
r�t7�8d�t9�d�}
|j��
r�|j�}
|j��
r�t�|
tj�tj�d΍|j>�rt�|
tj�dύt"�^dС|j�r"t'�Nt�����|j��rBt�|
|j�dэt"�^dҡ|j�rpd]t_�t���t���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--debugrHZ
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-rrcz--quietz=Suppress messages, provide only errors and warnings to stderr)r�r�rz--has-flagszCheck agent features)r�z--forcez-Force action and ignore several restristions.z--set-configzChange configuration optionrPz	KEY=VALUE)r�r�r�z--disable-libcarezDisable libcare services�enable_libcareZstore_const)r�rr��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_PATCHESrzODownload latest patches and apply them to the corresponding userspace processes)r�Znargsrr�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-rzlibcare-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})rRr)r�rr)Zforce_fallbackz)Kernel anomaly report file generated: {0}z0Kernel anomaly report uploaded successfully: {0}rrre)r�ZYES)r�ZNOr�r�r�r�zUserspace patches are applied.rzUserspace patches are unloaded.zLibcare plugin reloaded.cSsg|]}|�����qSr7)r�r�)r�Zptchr7r7r8r�5r�zmain.<locals>.<listcomp>�limit)rrzQFlag --nofreeze has been deprecated and will be not available in future releases.r�)rrLr0zKernel is safe)r�z=KernelCare protection disabled. Your kernel might not be safe�<)�rZadd_argumentrZadd_mutually_exclusive_groupr
ZLIBCARE_DISABLEDZ
parse_argsrZset_settings_from_config_file�FLAGSZ	has_flagsr+�filterr<�issubset�quietZauto_updateZSILENCE_ERRORSrZPRINT_CRITICALZPRINT_LEVELZPRINT_ERRORrZPRINT_DEBUGr�r,�getuid�printrPr��logging�INFOZWARNING�DEBUGrZinitialize_loggingZIGNORE_FEATURE_FLAGSZset_feature_flags_from_cacher�rZclear_all_cacheZset_patch_levelr`rr�Zset_sticky_patchr�Znosignaturer#Z
no_check_certr�r�r�r�Zedf_enabled�warnings�warn�DeprecationWarningZedf_disabledr2ZPREV_PATCH_TYPEZset_patch_typerQr�r�r%r��EXPECTED_PREFIXrwrir�r=ZlocalrdZPATCH_SERVERr�r�Zapp_infor�rrerrfrGr
Zsend_doctor_reportr�ZfallbackZkernel_anomaly_reportrrZarchive_pathr�rr
r
Z
keep_localrr�Zenable_auto_updateZdisable_auto_updateZ
set_configZupdate_config_from_argsZset_monitoring_keyr�Z
unregisterr�registerZregister_autoretryr�r�r�r�r^r_rZset_libcare_statusrZlib_tagZuserspace_statusZget_userspace_update_statusZ
lib_updateZdo_userspace_updateZlib_auto_updater�Z
lib_unloadZlibcare_unloadZlib_repluginZlibcare_repluginZlib_inforIZlib_patch_infoZlibcare_patch_infoZlib_versionZlibcare_server_startedZlibcare_versionZuserspace_updater�listZget_userspace_map�keys�sortedZuserspace_auto_updater�rHZnofreezer�Zsmart_updater�r�Z
UPDATE_POLICYr�rr�r�r�r�ZCHECK_CLN_LICENSE_STATUSrurv�randomZuniformrSr�r�Zlatest_patch_inforVZcheckrAr	�argvrK)ZparserZexclusive_groupr�r�r�rZlocal_path_messagerZ
lib_tag_kwrr�r7r7r8�main�s����������������
�
�
������
 




�








r)N)N)F)F)N)rHF)rHF)r)�Z
__future__rrhrerr,r�rr�r�r�ZsslrPr�rurOrZargparser�
contextlibrrrHrrr	r
rrr
rrrrrrrrrrrrrrrrrZpy23rr r!r"r#r�r�rr/r�rrfr�r��DOTALLr7rtr-r��insert�filterwarningsr�Any�Dict�Optional�Set�Tuple�UnionrwZsetLevelrr9r@rGrcrlr|r�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
StrictVersion�__version__�ImportErrorr�ZHTTPSConnectionZPureHTTPSConnection�objectr�r�rr�rr r%r&rArKrVrErXrSr_rbrkrsrwrxrzr|rr�r�r�r�rr�r�r�r�r�r�r�r�r�r�r�r�Zlog_all_parent_processesr�rHr�r>r�r�r�r�rOr�r�Ztrack_update_statusr�r�r�rr�r�rr7r7r7r8�<module>s\

	
&	



4
-!	b	+
 
		




"
?

-2
.= ,
3)

Youez - 2016 - github.com/yon3zu
LinuXploit