e7dZddlZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZddlmZdd lmZmZdd lmZdd lmZdd lmZdd lmZddlmZGddZddZdS)zA This module contains classes implementing SSA Manager behaviour N)contextmanager)iglob)is_cl_solo_edition) disable_quota)Tuple)load_validated_parserload_configuration) flag_file)SSAManagerError) ssa_version) AutoTracer) DecisionMakerceZdZdZdZed(dZedefdZ ede fdZ ede fdZ d e de fd Z d)d edejfd Zde ddfdZd(dZd(dZd(dZd(dZd(dZdedefdZdeeeefeffdZedZdedededdfdZ d*dZ!deeeefeffdZ"d*d Z#d*d!Z$d*d"Z%defd#Z&d*d$Z'd*d%Z(d(d&Z)d*d'Z*dS)+Managerz SSA Manager class. ctjd|_d|_d|_d|_t ddf|_tttj f|_ dS)Nmanagerz clos_ssa.ini)php44php51php52php53zphp\d+-imunifyz php-internal)z /opt/alt/php[0-9][0-9]/link/confz+/opt/cpanel/ea-php[0-9][0-9]/root/etc/php.dz$/opt/plesk/php/[0-9].[0-9]/etc/php.dz'/usr/local/php[0-9][0-9]/lib/php.conf.dzM/usr/share/cagefs/.cpanel.multiphp/opt/cpanel/ea-php[0-9][0-9]/root/etc/php.dzA/usr/share/cagefs-skeleton/usr/local/php[0-9][0-9]/lib/php.conf.dz./var/cagefs/*/*/etc/cl.php.d/alt-php[0-9][0-9]c\tj|ddS)N/)pwdgetpwnamsplit)paths B/opt/cloudlinux/venv/lib64/python3.11/site-packages/ssa/manager.pyz"Manager.__init__..6s3< 30B#C#C)ruser) logging getLoggerlogger ini_file_namesubstrings_to_exclude_dir_pathswildcard_ini_locationsdictwildcard_ini_user_locationsOSError ValueError subprocessSubprocessErrorsubprocess_errorsselfs r__init__zManager.__init__%sv' 22 +0 ,' # FCC E E E, ( Z!;" r!returnjson strcddi}|d|Dtj|S)z@ Form a success json response with given kwargs resultsuccessci|]\}}|| Sr9).0kvs r z$Manager.response..Bs===daQ===r!)updateitemsjsondumps)argskwargs raw_responses rresponsezManager.response<sI !), ==fllnn===>>>z,'''r!cJtjtS)z Is SSA enabled )osrisfiler r0s r_enabledzManager._enabledEs w~~i(((r!c ddhS)zK Configuration settings required Request Processor restart requests_duration ignore_listr9r0s r_restart_required_settingsz"Manager._restart_required_settingsLs $]33r!c hdS)N>time correlationdomains_numberrequest_numbercorrelation_coefficientr9r0s rsolo_filtered_settingszManager.solo_filtered_settingsSs*** *r!settingsc6|j|S)z SSA Agent requires restart in case of changing these configuration: - requests_duration - ignore_list )rM intersection)r1rUs r_restart_requiredzManager._restart_requiredXs .;;HEEEr!Fcommandc  tjdd|gdd|}|jd|dn#tj$r}|jdt |jt |jt |j |j|j|j |j d td |jd |jd |j p|j d }~w|j $rS}|jdt |dt |i td|d|d }~wwxYw|S)z Run /sbin/service utility to make given operation with SSA Agent service :command: command to invoke :check_retcode: whether to run with check or not :return: subprocess info about completed process z /sbin/servicez ssa-agentT)capture_outputtextcheckz ssa-agent z succeededz$SSA Agent %s failed with code %s: %s)cmdretcodestdoutstderrextraz SSA Agent z failed with code z: Nz&Failed to run %s command for SSA AgenterrzFailed to run z for SSA Agent: ) r-runr%infoCalledProcessErrorerrorstrr^ returncoder`rar r/)r1rY check_retcoder6es rrun_service_utilityzManager.run_service_utility`s ?^_%0%,%.48d*7 999F K  ='=== > > > >, ^ ^ ^ K  6AE AL!!AH e !"QX??  @ @ @"\QU\\al\\ahFZRSRZ\\^^ ^% ? ? ? K  FG %*CFFO  5 5 5!===!==?? ? ?  s#9=E BC(( E5AEErBct}|| |nO#t$rB}|jddt |itd|d}~wwxYw||r| dd| S) z Change SSA config and restart it. :args: dict to override current option values :return: JSON encoded result of the action z Failed to update SSA config filerdrbz"Failed to update SSA config file: NrestartTrk) r overridewrite_ssa_confr+r%rhrir rXrmrE)r1rBconfigrls r set_configzManager.set_configs '(( L  ! ! # # # # L L L K  @%*CFFO  5 5 5!"Jq"J"JKK K L  ! !$ ' ' D  $ $Yd $ C C C}}s: B=BBct}tdr6fd|D}|S|S)zV Get current SSA config. :return: JSON encoded current config T)skip_jwt_checkc.i|]\}}|jv||Sr9)rT)r:keyvaluer1s rr=z&Manager.get_config..s.zzzjc5SV^b^ySySysESySySyr!)rs)r rr?rE)r1 full_configfiltered_configs` r get_configzManager.get_configsp )** T 2 2 2 9zzzzK.s<111zsE3E ((**111r!r~r)rsversionr agent_status autotracing)r r?rEr rIstatus_ssa_agentr get_stats)r1_configs rrzManager.get_statss11%''--//111}}MM $ =99:..00" ..00    r!dir_pathc.fd|jD}|S)z6 Checking for substrings in a string. c>g|]}tj||Sr9)research)r: substringrs r z+Manager.unused_dir_path..s9222Y)Ix002y222r!)r')r1rress ` runused_dir_pathzManager.unused_dir_paths22222$*N222 r!c#vK|jD]0}t|D]}||rd|fV1|jD]v}t|dD]^}||r |d|}|j|jf|fV=#|jd|Y\xYwwdS)z Generator of existing paths (matching known wildcard locations) for additional ini files Returns tuple of (uid, gid) and path. )rrrr"zhUnable to get information about user owning %s directory (maybe he`s already terminated?), skip updatingN)r(rrr*pw_uidpw_gidr%rf)r1locationr pw_records rexisting_pathszManager.existing_pathss0 3 ' 'H!(OO ' '''11h&&&&& ' 8 I IH!(6"233 I I''11I 0 0 : :I%+Y-=>HHHHH K$$&56>@@@H I I Is 2BB5c#K tj|tj|dVtjdtjddS#tjdtjdwxYw)z Dive into user context by dropping permissions to avoid most of the security issues. Does not cover cagefs case because it also requires nsenter, which is only available with execve() call in our system Nr)rGsetegidseteuid)r1uidgids r _user_contextzManager._user_contextsn  JsOOO JsOOO EEE JqMMM JqMMMMM JqMMM JqMMMMs ,A*Brrini_pathNctj||j}|||5t 5t |d5}|jd|| ddddn #1swxYwYdddn #1swxYwYddddS#1swxYwYdS)zB Enable SSA extension for single ini_path (given) wzGenerating %s file...zextension=clos_ssa.soN) rGrjoinr&rropenr%rfwrite)r1rrrrinis rgenerate_single_inizManager.generate_single_inisw||Hd&899   S ) ) / / / /T3 /#& K  4d ; ; ; II- . . .  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /sYC B01B B0B B0 B !B0$ C0B4 4C7B4 8CC C c |jd|D]\\}}} ||||!#t$r|jd|YHt $r3}|jd|t|Yd}~d}~wwxYw|jddS)zj Place clos_ssa.ini into each existing Additional ini path, including cagefs ones z Generating clos_ssa.ini files...z>Unable to update file %s, possible permission misconfigurationz7Exception on generating clos_ssa.ini: "%s", error: "%s"N Finished!)r%rfrrPermissionError Exceptionrhri)r1rrrrls rrzManager.generate_iniss  ;<<<$($7$7$9$9   JS# ((c8<<<<"      "HIQSSS    !!"[]egjklgmgmnnn  %%%%%sA%B37 B3)B..B3c#K|D]O\\}}}tj|D]2}|j|vr ||ftj||fV3PdS)z Generator function searching for clos_ssa.ini files in all existing Additional ini paths Returns tuple of (uid, gid) and path. N)rrGlistdirr&rr)r1rrrnames rfind_clos_iniszManager.find_clos_inis/s %)$7$7$9$9 ? ? JS# 8,, ? ?%T11Cj"',,x">">>>>>> ? ? ?r!c |jd|D]\\}}} |||5t j|dddn #1swxYwYL#t $r3}|jd|t|Yd}~d}~wwxYw|jddS)z8 Remove all gathered clos_ssa.ini files zRemoving clos_ssa.ini files...Nz5Exception on removing clos_ssa.ini: "%s", error: "%s"r) r%rfrrrGunlinkr exceptionri)r1rrclos_inirls rrzManager.remove_clos_inis;s. 9:::$($7$7$9$9   JS# ''S11((Ih'''(((((((((((((((    %%&]_gilmnioioppp  %%%%%s;A;A/# A;/A3 3A;6A3 7A;; B8)B33B8c|d}|jr|dddS|dddS)ze Start SSA Agent service or restart it if it is accidentally already running rstartTrproNrmrjr1rs rrzManager.start_ssa_agentKsa //99  " D  $ $WD $ A A A A A  $ $Yd $ C C C C Cr!cp|d}|js|dddSdS)z` Stop SSA Agent service or do nothing if it is accidentally not running rstopTrpNrrs rrzManager.stop_ssa_agentVsN //99 & A  $ $V4 $ @ @ @ @ @ A Ar!cZ |ddn#t$rYdSwxYwdS)z: Get SSA Agent status: active or inactive rTrpinactiveactive)rmr r0s rrzManager.status_ssa_agent_sJ   $ $XT $ B B B B   :: xs  ((cttd5 dddn #1swxYwY|jdtddS)zE Create a flag file indicating successful enablement rN Flag file z created)rr r%rfr0s rrzManager.create_flagis)S ! !                   9i999:::::s $((c  tjt|jdtddS#t $r=}|jdtdt|Yd}~dSd}~wwxYw)z: Remove a flag file indicating enablement rz removedz removal failed: N)rGrr r%rfr+rri)r1rls rrzManager.remove_flagqs C Ii K  =)=== > > > > > C C C K  AYAAQAA C C C C C C C C C Cs4O@t & 1 1 1 10000$$    (IeCHos&: ;IIII4^" /s / / / / / / /&&&&$ ?eCHos&: ; ? ? ? ?&&&& D D D DAAAA#;;;; C C C C''''!!!!!!r!rr3Manager instancectS)zk Factory function for appropriate manager initialization :return: appropriate manager instance )rr9r!rinitialize_managerrs 99r!)r3r) rr@r#rGrrr- contextlibrglobrclcommon.lib.cleditionrsecureiortypingr configurationr r internal.constantsr internal.exceptionsr internal.utilsr modules.autotracerrmodules.decision_makerrrrr9r!rrse  %%%%%%555555""""""DDDDDDDD))))))000000''''''******111111i!i!i!i!i!i!i!i!X r!