Mj@ dZddlZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z m Z mZmZmZmZddlmZddlmZdd lmZmZdd lmZd d lmZd d lmZd dlm Z m!Z!m"Z"m#Z#m$Z$ej%dZ&de'fdZ(Gdde Z)eGddZ*GddeZ+Gdde+Z,Gdde+Z-de*fdZ.d/de/de e,e-ffdZ0d/de/d e/ddfd!Z1d0d#Z2d1d%e/d&e'ddfd'Z3d1d%e/d&e'ddfd(Z4d/d%e/deee/ee/ffd)Z5defd*Z6deee/e-ffd+Z7dee/fd,Z8d2d-Z9d2d.Z:dS)3zF This module contains a config parser for cloudlinux-xray-autotracing N) ConfigParser) dataclass)Enum)AnyUnionTupleIteratorListOptional)ClPwd)Feature)cpusersis_panel_feature_supported)CPAPIException) flag_fileSSAError)umask_0set_privilegesis_xray_user_agent_active xray_versionis_kernel_version_supportedzautotracing.configreturnc4ttjS)zACurrently Auto tracing feature is not supported on Shared edition)rr AUTOTRACINGM/opt/cloudlinux/venv/lib64/python3.11/site-packages/ssa/autotracing/config.pyis_autotracing_supportedr (s %g&9 : ::rceZdZdZdZdZdS)Statusz Autotracing statuses enableddisabledN)__name__ __module__ __qualname____doc__ENABLEDDISABLEDrrrr"r"-s$GHHHrr"c2eZdZUdZeed<eed<eed<dS)Userz User container uidnamehomeN)r%r&r'r(int__annotations__strrrrr,r,6s7 HHH III IIIIIrr,cjeZdZdZdZdZd dZd dZdededdfd Z dedefd Z deddfd Z defd Z dS)AutotracingConfigz) Autotracing basic config parser confNrc d tj|jtjtjztjztjz}n#t$rYdSwxYwtj|dd5}tj |}tj |j s!td|jd|j dd|j7|j|jkr'td|jd |jd |j||ddddS#1swxYwYdS) a Read self.config_file, hardened against symlink redirection without a process-wide privilege drop (safe inside the threaded ssa-agent daemon). Uses O_NOFOLLOW so a symlink as the final path component is refused, and an fstat() ownership check (expected_owner_uid) so an intermediate directory symlink that redirects the read to a root/other-user file is refused too. A missing/unreadable file is not an error (matches ConfigParser.read, which silently skips it); a symlink/ownership/type violation IS refused (file is not parsed). O_NONBLOCK + an fstat() S_ISREG regular-file check close the FIFO / special-file DoS: O_NOFOLLOW does NOT reject a FIFO, and a tenant who replaces the path with a writer-less FIFO would otherwise hang the privileged read forever (a blocking syscall raises nothing, so no per-user handler fires). O_NONBLOCK makes the open return immediately and the S_ISREG check refuses FIFOs, sockets, devices and directories before any read. A regular file ignores O_NONBLOCK on read, so the subsequent parse is unaffected. Nzutf-8replace)encodingerrorszRefusing to read z: not a regular file (mode z#o)z: owned by uid z , expected )osopen config_fileO_RDONLY O_NOFOLLOW O_NONBLOCK O_CLOEXECOSErrorfdopenfstatstatS_ISREGst_moderexpected_owner_uidst_uid read_file)selffd config_streamsts r_read_config_filez#AutotracingConfig._read_config_fileMs* )2;+F+VY[Ye+effBB    FF  YrGI > > > *-"B< ++ rp43Cpp`b`jppppqqq&2ryDD[7[7[x(8xxxx_c_vxx NN= ) ) ) * * * * * * * * * * * * * * * * * *s%A A AA6B"D%%D),D)ctj|j}tj|stj|dSdS)zh If subdirectory location for autotracing config file does not exist, create it N)r;pathdirnamer=existsmkdir)rK subdir_paths rcheck_config_dirz"AutotracingConfig.check_config_dirxsP good&677 w~~k** " H[ ! ! ! ! ! " "rkeyvaluec|||j|<|t|jd5}||ddddS#1swxYwYdS)D Set given config item 'key' to given value 'value' wN) main_sectionrVr<r=write)rKrWrX configfiles rset_config_valuez"AutotracingConfig.set_config_values(-T $  $"C ( ( #J JJz " " " # # # # # # # # # # # # # # # # # #sAA!$A!c |nJ#tjttf$r+}t d|j|Yd}~nd}~wwxYw ||j|S#ttjf$rZ}t|ts!t d|j||j |cYd}~Sd}~wwxYw)rZz*Ignoring invalid autotracing config %s: %sNz3Ignoring invalid autotracing config value in %s: %s) rO configparserErrorrBUnicodeDecodeErrorloggerwarningr=r\KeyError isinstance_builtin_defaultsget)rKrWes rget_config_valuez"AutotracingConfig.get_config_values ^  " " $ $ $ $"G-?@ ^ ^ ^ NNGIY[\ ] ] ] ] ] ] ] ] ^ 3)*3/ /,,- 3 3 3a** I$ )--c22 2 2 2 2 2 2! 3s3A!AA"A55C% AC C% C%c2|d|dS)" Set given status statusN)r_)rKrXs r set_statuszAutotracingConfig.set_statuss  h.....rc,|dS)rmrn)rk)rKs r get_statuszAutotracingConfig.get_statuss$$X...rrN) r%r&r'r(r\rHrOrVrr_rkrorqrrrr4r4AsL )*)*)*)*V""""#C######3C3C3333>////// /C//////rr4c"eZdZdZfdZxZS)AdminLevelConfigzAdmin level autotracing configcddi}d|_t||_t||jddS)Nrnr$z/usr/share/clos_ssa/autotracingFdefault_sectionstrict)r=dictrhsuper__init__r\)rKdefaults __class__s rr{zAdminLevelConfig.__init__sMj)<"&h 43DUSSSSSr)r%r&r'r(r{ __classcell__r}s@rrtrtsG((TTTTTTTTTrrtc(eZdZdZdeffd ZxZS)UserLevelConfigzUser level autotracing config configpathcHdti}|d|_ tj|j|_n#t$r d|_YnwxYwt||_ t ||j ddS)Nrnz/.ssa/autotracingFrv) rtrqr=r;rErIrHrBryrhrzr{r\)rKrr|r}s rr{zUserLevelConfig.__init__s.00;;==>(;;;  +&(gj&9&9&@D # # + + +&*D # # # +"&h 43DUSSSSSsAA"!A")r%r&r'r(r2r{r~rs@rrrsU''T3TTTTTTTTTTrrctjtj}t |j|j|jS)z* Get current user and his details )pwdgetpwuidr;getuidr,pw_uidpw_namepw_dir)pw_entrys rwho_am_irs2|BIKK((H !18? C CCr user_homect}|jdkr!|rt|}nAt}n2t rt|j}nt d|S)zF Initialize correct config file instance depending on context rzAuto tracing management is not available. Reason: X-Ray End-User plugin is not enabled, please contact your system administrator for help.)rr-rrtrr/r)r current_user conf_instances rconfig_instancers::L1  /+I66MM-..MM % & & +L,=>>MM]  rrXuserc|r tj|}n&#t$r}td|d|d}~wwxYw t |j|j5t|j |ddddS#1swxYwYdS#t$r}t|j |d}~wwxYwtd5t |ddddS#1swxYwYdS) zUser 'z ' not foundN target_uid target_gid) rgetpwnamrfrrrpw_gidrrroPermissionErrorstrerrorr)rXrpw_datarjs rr_r_s 0 >l4((GG > > >5D55566A = > .7>gnUUU B B//::5AAA B B B B B B B B B B B B B B B B B B . . .1:&&A - .U^^ 0 0    ( ( / / / 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0s^ <7<B(B BBBBB C'B<<C"DD Dsuccessc P t}|j|j}}n%#t$rt jd}}YnwxYw |!t d|||||dSt d|||||t|dS#t$rYdSwxYw)Nunknownz7[audit] operation=%s status=%s uid=%d user=%s target=%sz@[audit] operation=%s status=%s uid=%d user=%s target=%s error=%r) rr-r. Exceptionr;rrdinfor2) operationtargetrnerrorcaller caller_uid caller_names r_audit_autotracingr s9"(*fkK 999"$)++yK 9 = KKI       KKRE            s'AA!B(-B B%$B%Fusernamemode_allcL|r|n|rdnd} td}n#t$r}|j}Yd}~nd}~wwxYw |r|tt t jj|n&#t$r}td|d|d}~wwxYwtd||S)z Enable autotracing. If username is given, the user's config is changed in Admin's mode. Perform some misconfiguration checks before enabling and do not enable if some of them appear all_usersglobalNautotracing_enablefailurernr) misconfiguration_checksrreasonremove_custom_users_configsr_r"r)rXrr)rrrissuerjs renabler*s" NXXx(M XF!!!    *( ' ) ) )-x8888 / QRSSSS +V444 Ls' 8381A.. B8B  Bc|r|n|rdnd} |r|tttjj|n&#t $r}t d|d|d}~wwxYwt d|dS)ze Disable autotracing. If username is given, the user's config is changed in Admin's mode rrNautotracing_disablerr)rr_r"r*rXrr)rrrrjs rdisablerDs " NXXx(M XF  *( ' ) ) ).9999 0&RSTTTT ,f55555s1> A!AA!c td}n#t$r}|j}Yd}~nd}~wwxYw|w tt |dfS#tj$r"}tt||d}~wwxYwt|fS)zk Get status of autotracing. If username is given, the status for a particular user is returned N) rrrrr get_homedirrqNoSuchUserExceptionr2rt)rrrjs rrnrnTs !!!   *"577#6#6x#@#@AALLNNPTT T( * * *3q66"" ) *    ( ( * *E 11s( .).AA66B'B""B'c\ tS#t$rtcYSwxYw)zP Get panel users via cpapi, ignoring exceptions like NotSupported, etc. )rrtuplerrr _panel_usersrhs9yy wws ++c#KtD]M} t|}n#tj$rY6wxYw|t |fVNdS)zT Iterator over all users on the server along with their autotracing configs N)rr rrr)r_homedirs r user_configsrrs.. ww**400HH(    H OH------- ..s!6AAcg}tD]u\}} |tjjkr||C#t $r&}td||Yd}~nd}~wwxYw|S)a3 Get list of disabled users. This is a best-effort daily pass over UNTRUSTED per-tenant config files. Each user's status is read independently and ANY per-user config failure (refusal, OSError, parse error, non-UTF-8 decode, or any other unexpected exception) is logged with the user and the exception, then skipped instead of aborting the whole pass. This closes the DoS prong of F-02: a single tenant who points ``~/.ssa/autotracing`` at a foreign-owned target, or writes a pathological/binary config into their own home dir, can no longer break the daily decision-maker pass for every other user. A user whose config cannot be read is simply not counted as disabled (safe default) and the pass continues; genuine bugs remain diagnosable via the logged exception. zLSkipping user %s in disabled_users pass: cannot read autotracing config (%s)N) rrqr"r*rXappendrrdre)r$ruserconfrjs rdisabled_usersr~s H*nn( ""$$(===)))    NNiksuv w w w HHHH  OsgnUUU L L7>>"2">??LI.:;;;HRW__-=-IJJKKK  L L L L L L L L L L L L L L L  . . .1:&&A - . . .s<CA4C8 CC C C C C4C//C4c4dtdtdtfd}ts |ddts |ddt |d d t jts |d d d S)z(Additional checks for known malfunctionsrfixrc4|d|d}t|dS)Nz . You should z" in order to get Auto Tracing workre)flagr)rrmessages r make_errorz+misconfiguration_checks..make_errors+QQ#QQQi0000rz@Your current server setup is unsupported by Auto Tracing featurez*switch Control Panel or CloudLinux editionz1Your kernel does not support throttling detectionzupdate the kernelNzX-Ray is not installedz install X-RayzSlow Site Analyzer is disabledz enable it) r2rr rrr;rQrr)rs rrrs131S1X1111 $ % % j N 8   ' ( ( j ?    ~~j1?CCC 7>>) $ $Hj9;GGGHHr)N)rN)NFrr);r(loggingr;rrErar dataclassesrenumrtypingrrrr r r clcommon.clpwdr clcommon.constr clcommon.cpapirrclcommon.cpapi.cpapiexceptionsrinternal.constantsrinternal.exceptionsrinternal.utilsrrrrr getLoggerrdboolr r"r,r4rtrrr2rr_rrrrnrrrrrrrrrsL %%%%%%!!!!!!>>>>>>>>>>>>>>>> """""">>>>>>>>999999************  / 0 0;$;;;; T  r/r/r/r/r/ r/r/r/j T T T T T( T T TTTTTT'TTT*D$DDDDse4Do4U.V400C0s0d0000&    <S4D4 6 6c 6D 6T 6 6 6 6 22S2HU3 3E-F$G2222(e .huS/%9:; . . . .S 6 . . . . HHHHHHr