gjdZddlmZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z ddl mZmZmZmZmZdd lmZmZmZmZmZmZmZmZmZmZmZmZdd l m!Z!dd l"m#Z#dd l$m%Z%m&Z&dd l'm(Z(m)Z)m*Z*ddl+m,Z,m-Z-m.Z.m/Z/ddl0m1Z1m2Z2m3Z3m4Z4ddl5m6Z6Gdde%Z7Gdde%Z8edGddZ9Gdde%Z:Gdde%Z;dS)u  This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program.  If not, see . Copyright © 2019 Cloud Linux Software Inc. This software is also available under ImunifyAV commercial license, see ) annotationsN) dataclass) attrgetter)Path)time)DictIterableListSetcast) BooleanFieldCase CharFieldCheck Expression FloatFieldForeignKeyField IntegerFieldPrimaryKeyFieldSQL TextFieldfn model_to_dict)UserType)Modelinstance) FilenameField ScanPathFieldapply_order_by)execute_iterable_expressionget_abspath_from_user_dirget_results_iterable_expressionsplit_for_chunk)FAILED_TO_CLEANUPMalwareHitStatusMalwareScanResourceTypeMalwareScanType) get_crontabcbeZdZdZGddZedZedZedZ ede d e j e je je je je je jfg Zedd Zedd Zedd Zedd Zede d ejjejjfg ZedZ e! de j e je jfd ddZ"d S) MalwareScanzRepresents a batch of files scanned for malware Usually a single AI-BOLIT execution. See :class:`.MalwareScanType` for possible kinds of scans. c eZdZejZdZdS)MalwareScan.Meta malware_scansN__name__ __module__ __qualname__rdbdatabasedb_tableJ/opt/imunify360/venv/lib/python3.11/site-packages/imav/malwarelib/model.pyMetar-Ns;"r7r9T) primary_keyFnullz type in {}r< constraintsrr<defaultNresource_type in {})typespathsc v||j|j|j|j|j|j|j|j d|j |j | |j|k |j|k}|r-| |j |}| |j|j|j|jtj||}|t'|||}|dt+|fS)N scan_typeT clear_limit)selecttotal_resourcespathscanidstarted completederrortotal_malicioustypealias resource_typewherein_group_byorder_byr+desclimitoffsetr countlistdicts) clssincetorYrZrWrCrDquerys r8 ondemand_listzMalwareScan.ondemand_listsd" JJ#    #{++!  U38<<&& ' ' U3;%' ( ( U3;"$ % % "  5KK U 3 344E NN#SXsz3;  Xk)..00 1 1 U5\\ VF^^   "8S%88E{{t{,,d5;;==.A.AAAr7N)#r0r1r2__doc__r9rrLrrMrNrformatr( ON_DEMANDREALTIMEMALWARE_RESPONSE BACKGROUNDRESCANUSERRESCAN_OUTDATEDrQrJrrKrrOrPr'DBvalueFILErS initiator classmethodrbr6r7r8r+r+Gs ######## Y4 ( ( (Fl&&&G $'''I 9  E##'1'0'8'2'.','7        D&#lq999O =dB / / /D I4 . . .E"lq999OI  E%,,/28/4:       M t$$$I /B  %  &   /B/B/B/B[/B/B/Br7r+c eZdZdZGddZeZeedddZ e dZ e dZ e dZe dZedd Ze d Ze d Zed Ze ej Zed Ze ded ejjejjfg Z e d Z!e d Z"e d Z#e d Z$e d Z%e&dZ'GddZ(e) ddZ-e)dddZ.e)d>dZ/e)d?dZ0e)d@dZ1e)dAd!Z2e)d"Z3e) dBd#Z4e)dd$d%Z5e)dCd(Z6e)d)Z7d*Z8e)dDdEd,Z9e)d-Z:e)dAd.Z;e)dAd/Ze)d2Z?e)d3Z@eAdFd9ZBd:ZCd;ZDdS)G MalwareHitz*Represents a malicious or suspicious file.c eZdZejZdZdS)MalwareHit.Meta malware_hitsNr/r6r7r8r9rus;!r7r9FhitsCASCADE)r< related_name on_deleter;r?T)r@rBr=cTtt|j}t|Src)r str orig_filer)selfr}s r8orig_file_pathzMalwareHit.orig_file_pathsdn-- Ir7c$eZdZedZdS)MalwareHit.OrderByc ttjtjdftjdftjdftjdftjdffdfS)Nrd) rrsstatusr&CLEANUP_PENDINGCLEANUP_STARTEDFOUND CLEANUP_DONECLEANUP_REMOVEDr6r7r8rzMalwareHit.OrderBy.statussb%)91=)91=)/3)6:)91=     r7N)r0r1r2 staticmethodrr6r7r8OrderByrs-       r7rrNc  ||tt} |p t}d|}tj|ktj|kz}||z}||t d|f|j|zzz}||tj|kz}||tj |kz}| |tj | zz}|}| "|tj | z}| |||}| t!| t|}||}d|D}||fS)Nz%{}%zCAST(orig_file AS TEXT) LIKE ?c6g|]}|Sr6)as_dict.0rows r8 z)MalwareHit._hits_list..7s 333C#++--333r7)rIr+joinrrerMruserrsrLridrUrTrYrZr _hits_num)r^clausesr_r`rYrZsearch by_scan_idrrW by_statusidskwargsrwpatternrM full_clausesmax_count_clausesordered max_countresults r8 _hits_listzMalwareHit._hits_list s{ zz#{++00== \466--''&%/K4G24MN(   C07*7"$ $L   JOt3 3L  ! K.*< >vFF  $Xz7CCGMM"344 337333&  r7cH|j|g|Ri|Src)r is_suspicious)r^argsrs r8suspicious_listzMalwareHit.suspicious_list;s0s~c//11CDCCCFCCCr7cx|r&|r$|tj|ktj|kzz}|||j|kz}|t j|jt|}|t|t|}| Src) r+rMrrIrCOUNTrrrTr rsscalar)r^rr_r`rrWqs r8rzMalwareHit._hits_num?s  R   +u4#r) G   sx4' 'G JJrx'' ( ( - -k : : @ @ I I  xQ77Axxzzr7c||jtj|jz|||Src)rrnot_inr&CLEANUP malicious)r^r_r`rs r8 malicious_numzMalwareHit.malicious_numNs?}} Z  /7 8 83= H       r7)ignore_cleanedc|j}|r'||jtjz}|j|g|Ri|Src)rrrr&rr)r^rrrrs r8malicious_listzMalwareHit.malicious_listWsR-  C sz(()9)ABB BGs~g7777777r7cFd|D}d}t|||||S)Ncg|] }|j Sr6rrs r8rz)MalwareHit.set_status..`s'''3'''r7cd|i}|||d<|jdi||j|S)Nr cleaned_atr6)updaterTrrU)rr^rrfields_to_updates r8 expressionz)MalwareHit.set_status..expressionbsU&  %1; .3:11 01177 3HH Hr7r!)r^rwrrrs r8 set_statuszMalwareHit.set_status^sF''$''' I I I+ c6:   r7 to_deleter\cFd|D}fd}t||S)Ncg|] }|j Sr6rrs r8rz/MalwareHit.delete_instances..qs111SV111r7cj|Src)deleterTrrU)rr^s r8rz/MalwareHit.delete_instances..expressionss+::<<%%cfjjoo66 6r7r)r^rrs` r8delete_instanceszMalwareHit.delete_instancesosA11y111  7 7 7 7 7+:yAAAr7 to_updatec|D]V}|D]?\}}|D]\}}t||||j@WdSrc)itemssetattrsave)r^rdatarnew_fields_datafieldrns r8update_instanceszMalwareHit.update_instancesxs  D-1ZZ\\  )/$3$9$9$;$;44LE5HeU3333    r7returnrc`|jtjg|jz}|Src)rrUr&rr)r^rs r8 is_infectedzMalwareHit.is_infecteds: JNN$*   m   r7c|jSrc)rr^s r8rzMalwareHit.is_suspiciouss  ~r7c Tfd}tt||||dS)Nc|j}|||j|z}nSr(||jt jz}n)r'||jt jz}|5t|tr|g}||j |z}| |Src) rrrUrrr&r RESTORABLE isinstancer|rrIrT) chunk_of_idsr^rrcleanuprestores r8rz/MalwareHit.malicious_select..expressionsmG'36::l333 G3:,,-=-EFFF G3:>>*:*EFFFdC((" 6D38<<---::<<%%g.. .r7T)exec_expr_with_empty_iterr\r#)r^rrrrrrs `` r8malicious_selectzMalwareHit.malicious_selectsS / / / / / / +Cdd      r7)statusesc2fd}t||S)Ncj|}r|jz}|Src)r}rUrrIrT)filesrr^rs r8rz'MalwareHit.get_hits..expressionsTm''..G 43:>>(333::<<%%g.. .r7)r#)r^rrrs` ` r8get_hitszMalwareHit.get_hitss4 / / / / / / /z5AAAr7 hits_infor cxd|D}d|D}d|Dtttj|tj|}fd|D}|S)Ncg|] }|j Sr6rKrentrys r8rz*MalwareHit.get_db_hits..s333333r7cg|] }|j Sr6app_namers r8rz*MalwareHit.get_db_hits..s6665666r7c*g|]}|j|jfSr6rKrrs r8rz*MalwareHit.get_db_hits..s!JJJuuz5>2JJJr7c4g|]}|j|jfv|Sr6r}r)rhit paths_appss r8rz*MalwareHit.get_db_hits..s3   CM3<#@J#N#NC#N#N#Nr7)r\rsrIrTr}rUr)r^rrDappsrwrs @r8 get_db_hitszMalwareHit.get_db_hitss3333366I666JJ JJJ       U:'++E22 3 3 U:&**400 1 1           r7c.fd}t||S)Ncj|Src)rrTr}rU)rr^s r8rz*MalwareHit.delete_hits..expressions/::<<%%cm&7&7&>&>?? ?r7r)r^rrs` r8 delete_hitszMalwareHit.delete_hitss3 @ @ @ @ @+:u===r7cjt||Src)rQget_pk_exprr~s r8refreshzMalwareHit.refreshs"Dzz~~dmmoo...r7Iterable[MalwareHit]cLfd}tt||S)Nc}r3tt}|jd|DS)Ncg|] }|j Sr6rrrs r8rz?MalwareHit.refresh_hits..expression..s*B*B*Bc36*B*B*Br7)rIr+rrTrrU)rwrar^include_scan_infos r8rz+MalwareHit.refresh_hits..expressionsiJJLLE  G 3 4499+FF;;svzz*B*BT*B*B*BCCDD Dr7r)r^rwrrs` ` r8 refresh_hitszMalwareHit.refresh_hitssC E E E E E E 3JEEFFFr7c||jtjjkSrc)rIrTrSr'rmrnrs r8db_hitszMalwareHit.db_hitss4zz||!!  !8!;!A A   r7cv||jtjkS)z,Return db hits that are in queue for cleanup)rrTrr&rrs r8db_hits_pending_cleanupz"MalwareHit.db_hits_pending_cleanup2{{}}"" J*: :   r7cv||jtjkS)z3Return db hits for which the cleanup is in progress)rrTrr&rrs r8db_hits_under_cleanupz MalwareHit.db_hits_under_cleanupr r7cv||jtjkS)z3Return db hits for which the restore is in progressrrTrr&CLEANUP_RESTORE_STARTEDrs r8db_hits_under_restorationz$MalwareHit.db_hits_under_restorations2{{}}"" J*B B   r7c<d|D}d|D}d|D||j||j|}fd|DS)z Return db hits for which the cleanup is in progress specified by the provided set of MalwareDatabaseHitInfo ch|] }|j Sr6rrhit_infos r8 z6MalwareHit.db_hits_under_cleanup_in..s???hHM???r7ch|] }|j Sr6rrs r8rz6MalwareHit.db_hits_under_cleanup_in..sGGGh)GGGr7c*h|]}|j|jfSr6rrs r8rz6MalwareHit.db_hits_under_cleanup_in..s/   3;X]H- .   r7c4g|]}|j|jfv|Sr6r)rrpath_app_name_sets r8rz7MalwareHit.db_hits_under_cleanup_in..s8    s|,0AAA AAAr7)r rTr}rUr)r^ hit_info_setpath_set app_name_setrars @r8db_hits_under_cleanup_inz#MalwareHit.db_hits_under_cleanup_ins@?,???GG,GGG   ?K     % % ' ' U3=$$X.. / / U3<##L11 2 2          r7cv||jtjkSrc)rrTrr&CLEANUP_RESTORE_PENDINGrs r8db_hits_pending_cleanup_restorez*MalwareHit.db_hits_pending_cleanup_restore0{{}}"" J*B B   r7cv||jtjkSrcr rs r8db_hits_under_cleanup_restorez(MalwareHit.db_hits_under_cleanup_restorer r7 hit_list_listList['MalwareHit'] attributer|Dict[str, List['MalwareHit']]ctdtj|Dt |}dtj|t |DS)Nc3K|]}|VdSrcr6rs r8 z0MalwareHit.group_by_attribute..s" I ISS I I I I I Ir7)keyc4i|]\}}|t|Sr6)r\)r attr_valuerws r8 z1MalwareHit.group_by_attribute..s4    D T    r7)sorted itertoolschain from_iterablergroupby)r%r#hit_lists r8group_by_attributezMalwareHit.group_by_attributes I IIO99-HH I I I9%%     $-$5y))%%%    r7cid|jd|jd|jd|jjd|jd|jjd|jd|jd |jd |j d |j d |j d |j did|j d|jd|j|j|j|jt$jjkrQt+t,t,jt,jt,jt,j|jkt,j|jkt,j|jkt,j |j kt,j|jkt,j|jkt,j|jkt,jdt,jdt,jd ngdS)Nrusernamefilecreatedscan_idrFrSrQhashsizerrr extra_datadb_namerdb_hostF)db_portsnippet table_fields) rrr}rLrM scanid_idrQrSr:r;rrrr=rr>r?r@r'rmrnr\MalwareHistoryrI table_name table_field table_row_infrTrKr9is_nullr]rs r8rzMalwareHit.as_dict$s , $',  ,  DN,  t{* , t~ , ) ,  T/,  DI,  DI,  DI,  ,  dk,  $/,  ",  t|,  !, " t|#, $||,%)@)C)III)"))&1&2&4 U&/4=@&.$,>&.$,>&.$,>&+t~=&48JJ&.$+=&199%@@&2::5AA&4<r?r=r@propertyrrrqrrrrrrrrrrrrrrrrrrr rrrr"rr4rrKr6r7r8rsrssc44""""""""   B _%f F I5 ! ! !E 9% D 5)))I 9% D %777I 9$   D 9$   D %%%IY/5 6 6 6F&&&JI  E%,,/28/4:       Myd###HiT"""GiT"""GiT"""GiT"""G X"   ,!,!,![,!\DD[DDH   [    [ 278888[8    [ BBB[B   [    [ [9>   [ .)-BBBB[B   [ >>[> ///GGGG[G  [    [    [    [   [ .  [   [     \  - - - ^NNNNNr7rsT)frozenceZdZUdZded<ded<ded<ded<ded<d ed <ded <ded <d ed <ded<edZedZdS)MalwareHitAlternatezA Used as a replacement for MalwareHit for file hits only r|rLr}NonerrLrintr;r:rQrMboolrc |||d|d|d|d|d|ddd|ddd|ddd  S) NrLrr;r:rwrmatchesrM suspicious) rLr}rrLrr;r:rQrMrr6)r^rLfilenamers r8createzMalwareHitAlternate.createosssw-ffffa+6l1ok2v,q/,77    r7cNttj|jSrc)rosfsdecoder}rs r8rz"MalwareHitAlternate.orig_file_path~sBK//000r7N) r0r1r2rd__annotations__rqrYrNrr6r7r8rQrQ]sKKKNNNNNNJJJ III III III IIINNNOOO   [  11X111r7rQcJeZdZdZGddZdZeZeZ ede dgZ e dd Z ed Zefd Zefd Ze dddZeddZedZxZS)MalwareIgnorePathz+A path that must be excluded from all scansc$eZdZejZdZdZdS)MalwareIgnorePath.Metamalware_ignore_path)))rKrSTN)r0r1r2rr3r4r5indexesr6r7r8r9ras;(6r7r9NFzresource_type in ('file','db')r=c8ttSrcrSrr6r7r8zMalwareIgnorePath.s#dff++r7r?ct||j}||_dSrc)r\rIrWrKr]CACHE)r^rs r8 _update_cachezMalwareIgnorePath._update_caches>SZZ\\**3844::<<== r7c Rd|_tt|jdi|S)Nr6)rhsuperr_rY)r^rrJs r8rYzMalwareIgnorePath.creates. 3u&,,3==f===r7c`d|_tt|Src)rhrkr_r)r^rJs r8rzMalwareIgnorePath.deletes' &,,33555r7rSr|c \||j} || |j|k} || |j|k} |-| |j|} || |j|k} || |} || |} |t||| } |t|} | |j t| dz|jt| kz|jtt|kz} | d} | d| DfS)N/TrGc,g|]}t|Sr6rrs r8rz:MalwareIgnorePath.paths_count_and_list..s - - -C]3   - - -r7)rIrWrKrT added_datecontainsrSrZrYr r" startswithr|r)r[) r^rYrZrrSrr_r`rWr user_homers r8paths_count_and_listz&MalwareIgnorePath.paths_count_and_lists JJLL ! !#( + +  %/00A >",--A  ))&1122A  $)]:;;A    A  A  xa00A  1$77I$$S^^c%9::8s9~~-/8s;t#4#45557A GGG--  - -1 - - -  r7r List[str]c:|j|i|\}}d|DS)Ncg|] }|d Srr6rs r8rz/MalwareIgnorePath.path_list..s111F 111r7)rt)r^rr_ path_lists r8ryzMalwareIgnorePath.path_lists1/s/@@@ 911y1111r7cK|j|t|}|jD]C}tjdd{Vt|d}||ks ||jvrdSDdS)zChecks whether path stored in MalwareIgnorePath cache or if it's belongs to path from cache or if it matches patters from cache :param str check_path: path to check :return: bool: is ignored according MalwareIgnorePath NrrKTF)rhrirasynciosleepparents)r^ check_pathrKp ignored_paths r8is_path_ignoredz!MalwareIgnorePath.is_path_ignoreds 9       J  A-"" " " " " " " "& ??L $$,$,*F*Ftt+Gur7)NNNNNNNN)rSr|)rru)r0r1r2rdr9rhrrrrKrrSrrprqrirYrrtryr __classcell__)rJs@r8r_r_s5577777777 E   B 9;;DI 'G!H!H IM52E2EFFFJ[>>>>[>6666[6!  & & & & [& P222[2[r7r_c eZdZdZGddZedZedZede d e j j e jj fge jj ZedZedZedZedZedZedd ZedZedZedZedZedZedZedZe dd Zed Z eddZ!eddZ"d S)rCz:Records every event related to :class:`MalwareHit` recordsc eZdZejZdZdS)MalwareHistory.Metamalware_historyNr/r6r7r8r9rs;$r7r9Fr;TrB)r<r>r@c8ttSrcrer6r7r8rfzMalwareHistory. sS[[r7r?Nc|j|k|j|kz}|r/||j|td|fzz}|r||j|kz}|||| } |t|t| } t| } | d| fS)Nz(INSTR(path, ?))TrG)ctimeeventrqr file_userrIrTrYrZr]r rCr\r[) r^r_r`rYrZrrrWrra list_results r8 get_historyzMalwareHistory.get_historys9%#)r/:    **622& 22 G  - s}, ,G ""7++11%88??GGMMOO  "8^UCCE5kk {{t{,,k99r7c |jd|ddp tj|ddp tj|ddpt jjd| dS)NrpcauserS)rprrSr6) insertpoprROOTr(MANUALr'rornexecute)r^rs r8 save_eventzMalwareHistory.save_event.s  jjd33Dx}**Wd++E/E **_d;;2&+1      ')))))r7rw List[dict]c tj5t|dt |jjzD])}||* ddddS#1swxYwYdS)Ni) chunk_size) rr3atomicr$len_metacolumns insert_manyr)r^rw hits_chunks r8 save_eventszMalwareHistory.save_events8s [   ! ! 6 6 .CI,=(>(>!> 6 6  ++335555 6  6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6sABB BrDr\r_rSc>||jtj|j||jtkz|j|kz |j Src) rIrKrrrTrUrr%rrVtuples)r^rDr_s r8get_failed_cleanup_events_countz.MalwareHistory.get_failed_cleanup_events_countDs{ JJsx , , U U##9 1139%' Xch   VXX r7)NNN)rwr)rDr\r_rS)#r0r1r2rdr9rrKrrrrer'rmrnrorSrrrp file_ownerrrrr>r?r=rDrErFr9rqrrrrr6r7r8rCrCs:DD%%%%%%%% =e $ $ $Dyd###HI  E%,,/28/4:    (,2   M I5 ! ! !E I5 ! ! !E u%%%I&&&J u%%%I Le-@-@ A A AEiT"""GiT"""GiT"""G%%%J)&&&K Ld+++MiT"""GHL:::[:&[ 6 6 6[ 6    [    r7rC)rse*#""""" !!!!!!22222222222222                            .-----55555511111111   544444pBpBpBpBpB%pBpBpBf`N`N`N`N`N`N`N`NF  $"1"1"1"1"1"1"1"1J````````Fi i i i i Ui i i i i r7