l#g ddlZddlZddlZddlZddlZddlZddlZddlmZddl m Z m Z ddl m Z ddlmZmZddlmZejZejejzejzZdZGdd eZd Zd"d Zd efdZd edefdZ d edefdZ!d efdZ"eej#Z#eej$Z$e d#dZ%e dZ&e defdZ'e d$deee(ffdZ)e dede(de(de*fdZ+deeee(fee(dffdeeee(fee(dfffd Z, d%dedefd!Z-dS)&N)ProcessPoolExecutor)contextmanagersuppress)chain)TupleUnion)utilsctjgtj|tj|||SN)os setgroupssetgidsetuid)funuidgidargss W/opt/imunify360/venv/lib/python3.11/site-packages/defence360agent/utils/safe_fileops.pydroprs8LIcNNNIcNNN 3:ceZdZdS)UnsafeFileOperationN)__name__ __module__ __qualname__rrrrsDrrctjt|}|jt jkrt dt|zdS)Nz The file belongs to admin user: T)r statstrst_uidr get_min_uidr)filests rcheck_non_admin_filer$sT T  B y5$&&&&! .T :    4rFcfd}|S)NcPtjddfd }|S)N)loopc@Ktj|s std|zt j|}t t|j|g} rt|j}|D]I}tj t|}|j dkr|j dkr|j |j }}nJtd|ptj}|jt#dt$ |||g|Rd{VS)NzNo such file or directory: rz Unsafe file operation under root max_workers)r pathexistsFileNotFoundErrorpathlibPathrreversedparentsrrr st_gidrasyncioget_event_looprun_in_executorrr) filenamer'rr,pathspr#rrr missing_oks rwrapperz$safe.._safe..wrapper)sP7>>(++ J '1H<<))D(4<004&99E / .. N NWSVV__9>>bi1nn!y")CE)*LMMM37133D--#222  r) functoolswraps)rr;r:s` r_safezsafe.._safe(sK   04          :rr)r:r>s` rsafer?'s$B Lrr7cRtj|dSr )r/r0touchr7s r_touchrCLs$ L  """""rdatacTtj||dSr )r/r0 write_textr7rDs r _write_textrHPs& L%%d+++++rcbKtdt||d{VSNT)r:)r?rHrGs rrFrFWs@3&&&&{33HdCC C C C C C CCrc`Ktdt|d{VSrJ)r?rCrBs rrArA[s>.&&&&v..x88 8 8 8 8 8 88rTc#Kd|vrtdt||5}tj|}t j|}tjd|}||ks|j |j kr"td||rTtj |j tj |jvr"td||VddddS#1swxYwYdS)Nwz'w' mode is not permitted/proc/self/fd/{}zUnable to safely read {}z5Unable to sefely read {}. File is not in user homedir)ropenr fstatfilenopwdgetpwnamreadlinkformatr pw_uidr/r0pw_dirr2)r7modeuserrespect_homedirfr#passwd real_paths rsafe_open_filer^cs d{{!"=>>> h   Xahhjj ! !d##K 2 9 9!((** E EFF  ! !ryFM'A'A%*11(;;    V]++<))122&GNN  1sDD99D=D=c/BKtj|i|} |Vtt5tj|ddddS#1swxYwYdS#tt5tj|dddw#1swxYwYwxYw)z Context manager which wraps os.open and close file descriptor at the end :param args: positional arguments for os.open :param kwargs: keyword arguments for os.open N)r rOrOSErrorclose)rkwargsfds ropen_fdrds! $ !& ! !B g     HRLLL                  Xg     HRLLL                s@AAAAB1B BB BB Bnamec/Kt|g|Rdtji|5}tjd|}||krt d|VddddS#1swxYwYdS)a  Context manager to get a directory file descriptor It also checks if a directory doesn't contain a symlink in the path :param name: full directory name :param args: positional arguments for os.open :param kwargs: keyword arguments for os.open flagsrNz%Operations on symlinks are prohibitedN)rdr O_DIRECTORYrTrUr)rerrbdir_fdreals r opendir_fdrks  = = = =BN =f = ={-44V<<== 4<<%&MNN N sAA--A14A1r[c #Kd}t|trtt5t j||}t j||jt jzt j z|dddn #1swxYwYt j |||}t||5}|pt j||_ |V|rGtt5t j||jdddn #1swxYwYnO#|rHtt5t j||jdddw#1swxYwYwwxYwddddS#1swxYwYdS)a Context manager to open file object from file name or from file descriptor File object extended with 'st' attribute that contains os.stat_result of the opened file :param f: file name or file descriptor to open :param dir_fd: directory descriptor, ignored if 'f' is a file descriptor :param flags: flags for os.open, ignored if 'f' is a file descriptor :param mode: mode for built-in open Nri)rXri)rgrirX) isinstancerrr`r rchmodst_modeS_IRUSRS_IWUSRrOr#)r[rirgrXr#fos r open_fobjrus B!S 3 g    6***B H T\1DL@                    GAU6 2 2 2 ad   1r bgajj 1HHH 1g&&11HQRZ0000111111111111111 1g&&11HQRZ00001111111111111111 1 111111111111111111sA BB B :FD%F1D FD F D !F%E1<E$  E1$E( (E1+E( ,E11FFFrirgis_safec#K|r3t|||5}|dfVddddS#1swxYwYdS||fVdS)z If is_safe flag is True, open file descriptor using name and dir_fd If is_safe is False, return name and dir_fd as is )rirgN)rd)rerirgrvrcs r safe_tuplerxs  T& 6 6 6 "d(NNN                  Fls +//srcdstc\|\}}|\}}t|rdn tjz} t||td5} t||| d5} |r|dt j| | t|tr2tj | | j j dddn #1swxYwY|r=t|tr(|r|dtj ||ddddS#1swxYwYdS)Nrrb)rirgrXwbrnr)rm)W_FLAGSr O_EXCLruR_FLAGSshutil copyfileobjrorrprQr#rqunlink) ryrz src_unlink dst_overwriteracecallsrc_f src_dir_fddst_f dst_dir_fdw_flagssrc_fodst_fos r_moversE:E:m:;G  jd   0   *G$   B    vv . . .%%% Bvy/@AAAA B B B B B B B B B B B B B B B  0*UC00 0  IeJ / / / /%000000000000000000s7D!A/C > D! C D!C AD!!D%(D%cKtj|\}}tj|\} } t|5} t| 5} t || t |5} t | | t |5}tj|| }tj }| tdtt|j|j| |||| d{V|r*|r(|r|dtj|| |r>tj| |j|j| tj| |j| dddn #1swxYwYdddn #1swxYwYdddn #1swxYwYddddS#1swxYwYdS)Nrmr)r*)r r,splitrkrxrr~rr4r5r6rrrr r3rchownrprq)ryrzsafe_srcsafe_dstrrrsrc_dirsrc_namedst_dirdst_namerr src_tuple dst_tuplesrc_str's r safe_movers* c**GX c**GX G  B J--B Z*gxB J*gx B *555%''"" A . . .   M M          3( 3  Ihz 2 2 2 2  B HXv}fmJ O O O O HXv~j A A A A=BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBsG&F,>FCE> 2 F>F FF F F,F F,F F, G,F0 0G3F0 4GG G)F)T)NrN)FFTFN).r4r<r r/rRrrconcurrent.futuresr contextlibrr itertoolsrtypingrrdefence360agentr O_RDONLYrO_TRUNCO_CREATO_WRONLYr~r Exceptionrr$r?rrCrHrFrArprr^rdrkintruboolrxrrrrrrsA  222222////////!!!!!! + *rz !BK /     )   """"J#S####,#,S,,,,DsD#DDDD9#9999 RX bi<    S      1 1sCx 1 1 1 1F S # c D    0 uS#Xc4i 00 10 uS#Xc4i 00 10000H  *B*B *B *B*B*B*B*B*Br