zٳZ\ddlZddlZddlZddlZddlZddlmZmZddlm Z ddl m Z ddl m Z ddlmZmZmZmZmZddlmZddlmZmZmZdd lmZmZmZdd lmZm Z dd l!m"Z"dd l#m$Z$m%Z%dd l&m'Z'ddl(m)Z)ej*e+Z,dZ-dZ.dZ/dZ0dZ1GddeZ2GddeZ3GddZ4dZ5e4Z6dZ7dee8fdZ9GddeZ:Gd d!eZ;Gd"d#eZ<Gd$d%e<Z=Gd&d'e<Z>Gd(d)eZ?dS)*N)ABCabstractmethod) ContextVar)chain)Path)DictListOptionalSetTuple)Core) AbstractPanelModsecVendorsErrorPanelException)apache_modulesapache_runninglitespeed_running)async_lru_cachefinally_happened)files)RBL_WHITELIST_FILEModsec)$get_shared_disabled_modsec_rules_ids) ModSecLockapachenginx litespeed openlitespeedz/imunify360-{ruleset_suffix}-{webserver}-{panel}ceZdZdZdS)ModsecImunifyVendorNotInstalledz: Raises when there is no imunify vendor installed N__name__ __module__ __qualname____doc__M/opt/imunify360/venv/lib/python3.11/site-packages/im360/subsys/panels/base.pyr r * Dr'r ceZdZdZdS)ModsecNotInstalledVendorsz: Raises when there is no vendors installed at all Nr!r&r'r(r+r+2r)r'r+c(eZdZeZdZdS) _ModSecLockercJtjfd}|S)NcKj4d{V|i|d{Vcdddd{VS#1d{VswxYwYdSN)LOCK)argskwargscoroselfs r(wrapperz'_ModSecLocker.__call__..wrapper>sy 3 3 3 3 3 3 3 3!T42622222222 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3s 2 <<) functoolswraps)r5r4r6s`` r(__call__z_ModSecLocker.__call__=s>    3 3 3 3 3   3r'N)r"r#r$rr1r9r&r'r(r-r-:s. :<tjSr0)r-r1lockedr&r'r(is_modsec_lockedr<Fs   $ $ & &&r'cfd}|S)z.Skip the call if ModSecurity is not installed.cK|d{VstddS|g|Ri|d{VS)NzModSecurity is not installed)installed_modsecloggerwarning)clsr2r3funcs r(r6z-skip_if_not_installed_modsec..wrapperPsw))++++++++  NN9 : : : FT#/////////////r'r&)rCr6s` r(skip_if_not_installed_modsecrDMs#00000 Nr'returncxKd}t|ddd{V}|td|S)Nc^KtrtStrtSdSr0)r LITESPEEDrAPACHEr&r'r(get_web_serverz'_get_web_server..get_web_serverZs2         Mtr') max_triesdelayz&Couldn't detect any Web Server running)rr@rA)rJresults r(_get_web_serverrPYsZ$NbJJJ J J J J J JF ~?@@@ Mr'ceZdZedefdZdefdZdeefdZ deefdZ de fdZ de efdZdZd S) PanelInterfacerEc KdSr0r&r5s r(_get_all_admin_emailsz$PanelInterface._get_all_admin_emailsh  r'cK |d{VS#tj$rt$rD}tdt|Yd}~nd}~wwxYwgS)z- Return admin contact emails Nz2Something went wrong while getting admin email: {})rUasyncioCancelledError Exceptionr@rAformatstr)r5es r(get_admin_emailszPanelInterface.get_admin_emailsls 3355555555 5%        NNDKKFF           sA;:A66A;ctS)z+ Return panel's http ports setrTs r( http_portszPanelInterface.http_ports| uu r'ctS)z, Return panel's https ports r`rTs r( https_portszPanelInterface.https_portsrcr'cdS)NFr&rTs r(remoteip_supportedz!PanelInterface.remoteip_supportedsur'c.Ktd{VSr0rPrTs r(rJzPanelInterface.get_web_servers$$&&&&&&&&&r'ctSr0)dictrTs r(get_webshield_protected_portsz,PanelInterface.get_webshield_protected_portss vv r'N)r"r#r$rlistrUr^r intrbreboolrgr r\rJrlr&r'r(rRrRgs T   ^  CH SX D'hsm''''r'rRceZdZUdZdZeddZeeed<e e dZ e d0d Z e d0d Ze d Ze d Ze d0d Ze e dZe e defdZe e defdZe e d1dZe e dededefdZe dedefdZe defdZe defdZe dZe e dZe dZe e dZ e e dZ!e e defdZ"e e defdZ#e e d e$eeffd!Z%e d"Z&e de'efd#Z(e e)d$%de'e*fd&Z+e d'Z,e de-efd(Z.e defd)Z/e de-efd*Z0e e d+Z1e defd,Z2e d-e*d.e*de3fd/Z4dS)2ModSecurityInterfaceNzi360-app-based-excludes.confinstalling_settingsF)defaultinstalling_settings_varc KdS)zR Check if ModSecurity installed and enabled :return: bool Nr&rBs r(r?z%ModSecurityInterface.installed_modsecs  r'Tc KdSr0r&r5 reload_wafds r(_install_settingsz&ModSecurityInterface._install_settingsrVr'cRK|jd} ||d{V|j||d{VdS#|j||d{VwxYw)zJ Install ModSecurity vendors and patch ModSecurity config T)ryN)rtrarzreset"invalidate_installed_vendors_cache)r5rytokens r(install_settingsz%ModSecurityInterface.install_settingss ,0066 <(([(AA A A A A A A A  ( . .u 5 5 599;; ; ; ; ; ; ; ; ; ;  ( . .u 5 5 599;; ; ; ; ; ; ; ; ;s A006B&c KdS)zK Reset ModSecurity settings to values chosen by Imunify360 Nr&rTs r(reset_modsec_directivesz,ModSecurityInterface.reset_modsec_directives r'c KdS)zK Reset ModSecurity rulesets to values chosen by Imunify360 Nr&rTs r(reset_modsec_rulesetsz*ModSecurityInterface.reset_modsec_rulesetsrr'c KdS)zi Uninstall previously installedModSecurity vendors and revert ModSecurity config Nr&rxs r(revert_settingsz$ModSecurityInterface.revert_settings r'cdS)z` Detects Comodo ModSecurity Rule Set installed as Plugin :return: bool: Nr&rvs r( detect_cwafz ModSecurityInterface.detect_cwaf  r'rEc KdS)z/Return a list of installed ModSecurity vendors.Nr&rvs r(modsec_vendor_listz'ModSecurityInterface.modsec_vendor_list  r'c KdS)z-Return a list of enabled ModSecurity vendors.Nr&rvs r(enabled_modsec_vendor_listz/ModSecurityInterface.enabled_modsec_vendor_listrr'c KdS)zl Example: >>> modsec_interface.modsec_get_directive("SecRuleEngine") 'Off' Nr&)rBdirective_namerss r(modsec_get_directivez)ModSecurityInterface.modsec_get_directiverr'vendorfilenamecKt)z&Return path to a specified vendor file)NotImplementedError)rBrrs r(build_vendor_file_pathz+ModSecurityInterface.build_vendor_file_paths"!r'c>K||dd{VS)z-Return path to Imunify360 vendor VERSION fileVERSIONN)r)rBrs r(build_version_file_pathz,ModSecurityInterface.build_version_file_paths0// BBBBBBBBBr'c>K |d{V}n.#t$r!}tt|d}~wwxYw|st dt d|Dd}|#t dd||S)zA Return a name of Imunify360 ModSecurity vendor. NzNo vendors installedc3XK|]%}|tj!|V&dSr0) startswithr PRODUCT).0vs r( z.s5 H H1Q\\$,-G-G HQ H H H H H Hr'z7Imunify360 vendor is not installed, all vendors are :%s )rrrr\r+nextr join)rBinstalled_vendorsr]names r(get_i360_vendor_namez)ModSecurityInterface.get_i360_vendor_names  -&)&<&<&>&> > > > > > >   - - -$SVV,, , -! D+,BCC C H H) H H H$   <1I*++  s A AA cK|d{V}||d{V} |5}|cdddS#1swxYwYdS#t $r'}t d|d}~wwxYw)zH Return a version of the Imunify360 ModSecurity vendor. Nz)Cannot read Imunify360 vendor version: {})rropenreadstripOSErrorrr[)rBr version_fileferrs r(get_i360_vendor_versionz,ModSecurityInterface.get_i360_vendor_version s //11111111 88@@@@@@@@  ""$$ (vvxx~~'' ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (   $;BB3GG  s;B &B3 B BB BB B>"B99B>c"Kt|jdr|jt|jdr|jt|jdr|jdSdS)N cache_clear)hasattrrr_get_release_info_from_filerrvs r(r}z7ModSecurityInterface.invalidate_installed_vendors_caches 3)= 9 9 1  " . . 0 0 0 32M B B :  + 7 7 9 9 9 31= A A 9  * 6 6 8 8 8 8 8 9 9r'c KdS)a :param list updates: [ { "groups": [ "cpanel", "litespeed" ], ... "name": "imunify360-litespeed-meta", "url": "https://files.imunify360.com/.../meta_imunify360_litespeed.yaml" }, { "groups": [ "cpanel", "apache", "litespeed" ], ... "name": "imunify360-rules-meta", "url": "https://files.imunify360.com/.../meta_imunify360_rules.yaml" }] Nr&rvs r(_apply_modsec_files_updatez/ModSecurityInterface._apply_modsec_files_update"s 2 r'crK|d{V|d{VdSr0)rr}rvs r(apply_modsec_files_updatez.ModSecurityInterface.apply_modsec_files_update=sT,,.........4466666666666r'cdS)zR Returns path to ModSecurity audit log file :return: srt: Nr&rvs r(get_audit_log_pathz'ModSecurityInterface.get_audit_log_pathBrr'cdS)ze Returns path to ModSecurity audit log dir for concurrent mode :return: srt: Nr&rvs r(get_audit_logdir_pathz*ModSecurityInterface.get_audit_logdir_pathKrr'cdS)a Disable mod_security rules on global level. Rebuild httpd conf and restart httpd server is caller method responsibility. :param list rule_list: list of rules to disable :return: True if config was changed, False otherwise Nr&rB rule_lists r(write_global_disabled_rulesz0ModSecurityInterface.write_global_disabled_rulesTsr'c KdS)z Disable mod_security rules on global level This method should be idempotent :param list rule_list: list of rules to disable :return: True if config was changed, False otherwise Nr&rs r(sync_global_disabled_rulesz/ModSecurityInterface.sync_global_disabled_rules_rr'domain_rules_mapc KdS)z Disable mod_security rules on domain level for each domain specified in a map. This method should be idempotent. Nr&)rBrs r(sync_disabled_rules_for_domainsz4ModSecurityInterface.sync_disabled_rules_for_domainsirr'cd}d}dt|tD}|r6|dt |}|S)Nz SecRuleRemoveById {rules_list} modsecurity_rules 'SecRuleRemoveById {rules_list}' c,h|]}t|Sr&)r\)rid_s r( zFModSecurityInterface.generate_disabled_rules_config..}s.    HH   r'r) rules_list)rrr[rsorted)rBrtplcontent rules_idss r(generate_disabled_rules_configz3ModSecurityInterface.generate_disabled_rules_configss{  466     IjjCHHVI5F5F,G,GjHHGr'cK |d{V}||td{VS#t$r&}td|Yd}~dSd}~wwxYw)zQReturn RBL whitelist path. Return None on modsec vendor errors. Nz;Can't get RBL whitelist path. ModSecurity ruleset error: %s)rrrrr@rA)rBrr]s r(get_rbl_whitelist_pathz+ModSecurityInterface.get_rbl_whitelist_paths  3355555555F33FK|d{V}|r~ d|d|d|dd|ddkzS#t$r&}td |Yd}~dSd}~wwxYwdS) Nz,{vendor}-{modsec3}{ruleset_type}-{webserver}r ruleset_type webserverzmodsec3-modsec_version)rrrmodsec3z?Release file with info about ruleset is broken: %s is not found)rr[lowerKeyErrorr@rA)rB release_dictrs r(#get_modsec_vendor_from_release_filez8ModSecurityInterface.get_modsec_vendor_from_release_files <<>>>>>>>>   ELL'1!-n!=*;7&,7G*HA*MN M %''     ' ttttt  4sA A** B4BBcdSr0r&rvs r(get_modsec_active_conf_filesz1ModSecurityInterface.get_modsec_active_conf_files r'cdSr0r&rvs r(get_modsec_engine_modez+ModSecurityInterface.get_modsec_engine_moderr'cdSr0r&rvs r(get_modsec_vendor_updatesz.ModSecurityInterface.get_modsec_vendor_updatesrr'cdSr0r&rvs r( _get_conf_dirz"ModSecurityInterface._get_conf_dirs  r'ct|}tj||jS)z Return rules config path if WAF Rules Set configurator is supported for this hosting panel, raise NotImplementedError otherwise )rospathrAPP_BASED_EXCLUDE_CONF_NAME)rBconf_dirs r(get_app_specific_waf_configz0ModSecurityInterface.get_app_specific_waf_configs. $$&&w||Hc&EFFFr'enabled_users_domainsdisabled_users_domainsc"KtS)zu Disable/enable extra modsecurity rules for specific domains. Return set of updated domains. r`)rBrrs r((apply_myimunify_modsec_rules_for_domainsz=ModSecurityInterface.apply_myimunify_modsec_rules_for_domainssuu r')Tr0)5r"r#r$REBUILD_HTTPDCONF_CMDrrrtro__annotations__ classmethodrr?rzrDrrrrrrmrrrr\rrrrrr}rrrrrrrrrr rrrkrrr rrrrrrarr&r'r(rqrqsm "@0: u111Z-  ^[    ^ " < < <"! <  ^   ^    ^   ^[     ^[     ^[    ^[ "#"""""^["C3C4CCC[C3[. c   [ 99[9  ^[ 277[7  ^[   ^[  t   ^[  D   ^[  #CI   ^[ [( Xd^   [ _Q(4. [[( T#Y   [  s   [  $s)   [   ^[ GCGGG[G'+EI [r'rqc:eZdZedZedZdS)ModSecSettingInterfacec KdS)z9 Installs and enabled ModSecurity Vendor Nr&rTs r(applyzModSecSettingInterface.applys r'c KdS)z Removes and disables ModSecurity Vendor :param kwargs: previous_value: values that was applied before Nr&)r5r3s r(revertzModSecSettingInterface.revertrr'N)r"r#r$rrrr&r'r(rrsH  ^   ^   r'rceZdZeZdZedeefdZ e dZ e dZ e dZ dZdZd S) FilesVendorcF||_||_dS)a :param dict item: e.g. { "groups": [ "cpanel", "apache" "configserver" ], "obsoletes": [ "imunify360_rules", "comodo_apache", ], "url": "https://files.imunify360.com/.../meta_imunify360_apache.yaml" } N)_item _vendor_id vendor_id)r5items r(__init__zFilesVendor.__init__s " **r'rEc.Ktd{VSr0rirvs r(rPzFilesVendor._get_web_server$$&&&&&&&&&r'c KdSr0r&rTs r(rzFilesVendor.apply rVr'c KdSr0r&r&r'r(_remove_vendorzFilesVendor._remove_vendorrVr'cdSr0r&rTs r(rzFilesVendor._vendor_idrr'cK|d{Vr<|d{Vtd|jdSdS)z9 Removes and disables ModSecurity vendor NzSuccessfully removed vendor %r.) _is_installedrr@inforrTs r(rzFilesVendor.reverts|##%% % % % % % % K%%'' ' ' ' ' ' ' ' KK94> J J J J J K Kr'cVK|jd{V}|j|vSr0)modsec_interfacerr)r5rs r(rzFilesVendor._is_installeds;"&"7"J"J"L"LLLLLLL~!222r'N)r"r#r$rqrr rr r\rPrrrrrrr&r'r(rrs++++('hsm'''['  ^   ^   ^ KKK33333r'rc eZdZGddeZ dZeZeZ e dZ e e dZ e e dZe deefdZe defd Ze d Zed ZdS) FilesVendorListceZdZdZdS)'FilesVendorList.CompatiblityCheckFailedz; >>> e.args[0] {conflicting items} Nr!r&r'r(CompatiblityCheckFailedr$s  r'rNc|K|jd{V|d{VdSr0)rr}install_or_updatervs r(rzFilesVendorList.apply3sW"EEGGGGGGGGG##%%%%%%%%%%%r'cdSr0r&)rBrs r(vendor_fit_panelz FilesVendorList.vendor_fit_panel8s  r'c KdSr0r&)rBrs r(_get_compatible_namez$FilesVendorList._get_compatible_name=s  r'rEc.Ktd{VSr0rirvs r(rPzFilesVendorList._get_web_serverBr r'c4Ktjtj}|jd{V} ||d{Vn3#|j$r&}td|Yd}~dSd}~wwxYw tfd| D}n,#t$rtdYdSwxYw| |d|d<| |}| D]J}| |}|j|vr*|j|jkr|d{VK|d{VdS) z Installs and enabled ModSecurity vendor list. Returns True if ModSecurity vendor was installed, False otherwise. NzNo vendor can be installed: %sFc34K|]}|dk|VdS)rNr&)ricompatible_names r(rz4FilesVendorList.install_or_update..Vs:AfI,H,H,H,H,H,Hr'zVendor %s not found in indexurl local_pathT)rIndexMODSECrrrrr@rAritems StopIteration localfilepath files_vendorrrr) rBindexrr]rvendor_to_installr#rr$s @r(rz!FilesVendorList.install_or_updateFs  EL))"%"6"I"I"K"KKKKKKK $'$<$<=N$O$OOOOOOOOO*    NN;Q ? ? ?55555   ;;==DD    NN9? K K K55 #00e==\,,T22 ! !A  ##A 000K#4#>>>hhjj       %%'''''''''ts*A B(B  B-C%C)(C)cKtjtj}|D]D}||r-||d{VEdS)z> Removes and disables ModSecurity vendor list N)rr'r(r)rr,r)rB_r-rs r(rzFilesVendorList.revertks  EL))KKMM 6 6D##D)) 6&&t,,33555555555 6 6r'c>tjSr0)rRULESETrr&r'r(get_ruleset_suffixz"FilesVendorList.get_ruleset_suffixus~##%%%r')r"r#r$ RuntimeErrorr config_keyrr,rqrrrrrrr r\rProrr staticmethodr3r&r'r(rr#sA     ,   JL+&&[&^[^['hsm'''['""""["H66[6&&\&&&r'rceZdZUdZdZeedfed<ede fdZ ede e fdZ dZd Zd S) RemoteIPInterfacezThis class implements panel-specific methods for activating and deactivating mod_remoteip or similar functionality. Concrete panel implementation may or may not derive from this class as a means of signaling of support for this functionality.)s mod_remoteipsremoteip_module._REMOTEIP_MODULE_NAMESrEc KdS)z/Checks if remoteip feature is already activatedFr&rTs r(remoteip_activatedz$RemoteIPInterface.remoteip_activateds ur'c KdS)zActivates/ installs remoteip feature. Returns a path to installation log file or None if no log file is produced.Nr&rTs r(remoteip_installz"RemoteIPInterface.remoteip_installs tr'c KdSr0r&rTs r(remoteip_customize_loggingz,RemoteIPInterface.remoteip_customize_loggings tr'cxKtd{VsdStfd|jDS)NTc3 K|]}|vV dSr0r&)rrmoduless r(rz9RemoteIPInterface._is_loaded_to_apache..s'KKt47?KKKKKKr')ranyr9)r5rBs @r(_is_loaded_to_apachez&RemoteIPInterface._is_loaded_to_apachesW&(((((((( 4KKKKt/JKKKKKKr'N)r"r#r$r%r9r bytesrrror;r r\r=r?rDr&r'r(r8r8zsBB 1E%*- $^ ^LLLLLr'r8)@rXr7rloggingrabcrr contextvarsr itertoolsrpathlibrtypingrr r r r defence360agent.contracts.configr "defence360agent.subsys.panels.baserrr!defence360agent.subsys.web_serverrrrdefence360agent.utilsrrim360rim360.contracts.configrr"im360.subsys.shared_disabled_rulesr im360.utilsr getLoggerr"r@rINGINXrH OPENLITESPEEDMODSEC_NAME_TEMPLATEr r+r-r<use_modsec_lockrDr\rPrRrqrrrr8r&r'r(rYs  ########""""""33333333333333111111  DCCCCCCC========#"""""  8 $ $    I     &8        2           ''' -//    x}    (((((](((VIIIII3IIIX      S   "1313131313(131313hT&T&T&T&T&,T&T&T&n L L L L L L L L L Lr'