*6jdZddlZddlZddlZddlZddlmZmZddlm Z ej e Z ddZ defdZeejfddd Zed Zd ed edefd ZdS)a[fd-based file operations for symlink-attack mitigation. All helpers in this module use O_NOFOLLOW and dir_fd-relative syscalls so that no path-based resolution can be redirected by a concurrent symlink swap. This module is intentionally kept separate from utils/__init__.py to avoid loading these OS-specific helpers into every agent component. N)contextmanagersuppress)Pathreturnc|dfg} |r$|d\}}d}tj|5}|D]}|dr`tj|jtjtjztjz|}|||jfd}ntj |j|dddn #1swxYwY|sN| \}} | 5tj ||d\} }tj | | |"dSdS#t$r |D]\}} | tj |wxYw)uRemove all contents of a directory using fd-relative operations. Every entry is opened with ``O_NOFOLLOW`` so symlinks inside the tree are unlinked rather than followed. The directory referenced by *dir_fd* itself is **not** removed — the caller should ``os.rmdir()`` the parent entry after this call returns. Uses an iterative approach with an explicit stack to avoid hitting Python's recursion limit on adversarial deeply-nested trees. *dir_fd* must be an open ``O_RDONLY | O_DIRECTORY`` descriptor. NF)follow_symlinksdir_fdT)osscandiris_diropennameO_RDONLY O_DIRECTORY O_NOFOLLOWappendunlinkpopclosermdir BaseException) r stack current_fd_pushedentriesentrychild_fdfdr parent_fds Q/opt/imunify360/venv/lib/python3.11/site-packages/defence360agent/utils/fd_ops.py rmtree_fdr$s"d^ E 5!"IMJFJ'' A7$ A AE||E|:: A#%7!JK".82=H#-$$$  h %;<<#t$r1tjd}tj|d |z}YnwxYwd}d }t+d D]}|d tjd d} tj|tjtjztjztjzd|}n#t6$rYwxYwt7d t9|}d}|t|kr3|tj|||dz }|t|k3||tj|||tj||tj |tj!|d }tj"||||d}|dkrtj!||BtGt5tj$||dddn #1swxYwYnd#|dkrtj!||CtGt5tj$||dddw#1swxYwYwwxYwdS)adir_fd-relative implementation of atomic_rewrite. The caller opens the directory with O_NOFOLLOW before any file I/O begins. All file operations use dir_fd so that a concurrent rename of the directory to a symlink cannot redirect writes to a privileged path. r rbr&NFzempty content: %r for file: %s)r r rirdrz .i360editiz.Could not create temporary file (100 attempts)) src_dir_fd dst_dir_fdT)%r r'splitrrrfdopenreadlenFileNotFoundErrorOSErrorerrnoELOOPloggererrorstatS_ISLNKst_modestrerrorS_IMODEumaskrangeurandomhexO_WRONLYO_CREATO_EXCLFileExistsError memoryviewwritechownchmodfsyncrrenamerr)filenamer5uidgidallow_empty_content permissionsr rbasename content_fdf old_contentexcst current_umask tmp_basenametmp_fdviewwrittens r#atomic_rewrite_fdris"'--))KAxW bkBM1&   Yz4 ( ( 0A&&TQ//K 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 $  5        9 # #   DDDD t 5tXFFFu 1&%HHHB|BJ'' Oek2;u{+C+CXNNN,rz22KK  1 1 1HQKKM H] # # #=.0KKK 1L F 3ZZ P P"CCRZ]]%6%6%8%8CCC  W bj(294r}D F E    H NOOO7$D !! rxWXX77 7GD !! ?s HVS# & & & %%%   ,VOOOO Q;; HV     #+,, 7 7 ,v6666 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 Q;; HV     #+,, 7 7 ,v6666 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 $ 4sAB-'&B B-BB- B! B-- C#9 C#CC# BF 8GG A I I$#I$7C N 1NNN 1PO4( P4O8 8P;O8 <P)rN)__doc__rBloggingr rF contextlibrrpathlibr getLogger__name__rDr$intr-rr2r4bytesboolrir#rus0  ////////  8 $ $0000f#: kT"   [ [ [ [[[[[[rt