o
    Û1j^ª  ã                   @   s   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
Zd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZmZmZmZ d dl m!Z!m"Z" d dl#m$Z$ d dl%m&Z&m'Z'm(Z(m)Z) dd„ Z*G dd„ deƒZ+dS )é    N)Údatetime)Úgetpwuid)Ú__version__)ÚSoSComponent)ÚSoSIPParser)ÚSoSMacParser)ÚSoSHostnameParser)ÚSoSKeywordParser)ÚSoSUsernameParser)ÚSoSIPv6Parser)ÚSoSReportArchiveÚSoSReportDirectoryÚSoSCollectorArchiveÚSoSCollectorDirectory)ÚDataDirArchiveÚTarballArchive)ÚInsightsArchive)Úget_human_readableÚimport_moduleÚImporterHelperÚis_executablec              
   C   s²   	 z|  ¡ }W n ttfy$ } ztd|› d�ƒ W Y d }~d S d }~ww |d u rSz| | j| j| jf¡ W d S  tyR } ztd|› d�ƒ W Y d }~d S d }~ww |  |¡ q)NTz3Child process exception when reading input queue: 'ú'z7Child process exception when writing to output queue: ')	ÚgetÚEOFErrorÚOSErrorÚprintÚputÚfiles_obfuscated_countÚtotal_sub_countÚremoved_file_countÚobfuscate_arc_file)ÚarcÚinput_queueÚoutput_queueÚfileÚe© r&   ú6/usr/lib/python3/dist-packages/sos/cleaner/__init__.pyÚ_obfuscate_arc_files*   s6   €þý	ûÿÿ€û
îr(   c                       sT  e Zd ZdZdZdg g g dg dddddg d	d
œZ		dK‡ fdd„	ZdLdd„ZdLdd„ZdLdd„Z	dLdd„Z
edd„ ƒZdd„ Zdd„ Zedd„ ƒZdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ ZdMd/d0„Zd1d2„ Zd3d4„ Zd5d6„ Zd7d8„ Zd9d:„ Zd;d<„ Zd=d>„ Z d?d@„ Z!dAdB„ Z"dCdD„ Z#dEdF„ Z$dGdH„ Z%dIdJ„ Z&‡  Z'S )NÚ
SoSCleanera-  
    This function is designed to obfuscate potentially sensitive information
    from an sos report archive in a consistent and reproducible manner.

    It may either be invoked during the creation of a report by using the
    --clean option in the report command, or may be used on an already existing
    archive by way of 'sos clean'.

    The target of obfuscation are items such as IP addresses, MAC addresses,
    hostnames, usernames, and also keywords provided by users via the
    --keywords and/or --keyword-file options.

    For every collection made in a report the collection is parsed for such
    items, and when items are found SoS will generate an obfuscated replacement
    for it, and in all places that item is found replace the text with the
    obfuscated replacement mapped to it. These mappings are saved locally so
    that future iterations will maintain the same consistent obfuscation
    pairing.

    In the case of IP addresses, support is for IPv4 and IPv6 - effort is made
    to keep network topology intact so that later analysis is as accurate and
    easily understandable as possible. If an IP address is encountered that we
    cannot determine the netmask for, a private IP address from 172.17.0.0/22
    range is used instead.

    For IPv6, note that IPv4-mapped addresses, e.g. ::ffff:10.11.12.13, are
    NOT supported currently, and will remain unobfuscated.

    For hostnames, domains are obfuscated as whole units, leaving the TLD in
    place.

    For instance, 'example.com' may be obfuscated to 'obfuscateddomain0.com'
    and 'foo.example.com' may end up being 'obfuscateddomain1.com'.

    Users will be notified of a 'mapping' file that records all items and the
    obfuscated counterpart mapped to them for ease of reference later on. This
    file should be kept private.
    z6Obfuscate sensitive networking information in a reportÚautoé   Nú /etc/sos/cleaner/default_mappingFÚ Ú	obfuscate)Úarchive_typeÚdomainsÚdisable_parsersÚskip_cleaning_filesÚjobsÚkeywordsÚkeyword_fileÚmap_fileÚ	no_updateÚkeep_binary_filesÚtargetÚ	usernamesÚtreat_certificatesc                    sü  |st ƒ  |||¡ d| _nE|d | _|d | _|d | _|d | _|d | _d| _t| jdƒs6| jj	| j_
d	| j_t d
¡| _t d¡| _tjtj | jd¡dd� |  ¡  |  ¡ | _t d¡ || _| j ¡ | _| jj d¡| _| jjr~tj | jj¡nd}| j|| jj g‰ t!t"t#t$t%t&g}dd„ |D ƒ}| jj'D ]@}	d}
|D ]-}|dd…  (¡ }|	 (¡  )¡ |krÎ|  *d|› �¡ | j +d|	› d�¡ | ,|¡ d}
 nq¡|
sÛ| j +d|	› d�¡ q›‡ fdd„|D ƒ| _-t.t/t0t1t2t3t4g| _5d | _6|  *d| j› �¡ d S )NTÚoptionsÚtmpdirÚsys_tmpÚpolicyÚmanifestFr3   r*   ÚsosÚsos_uiÚcleaner©Úexist_oké?   z/etc/sos/cleanerc                 S   ó   g | ]}|j ‘qS r&   )Ú__name__)Ú.0Úclsr&   r&   r'   Ú
<listcomp>­   s    ÿz'SoSCleaner.__init__.<locals>.<listcomp>é   iúÿÿÿzDisabling parser: zDisabling the 'zP' parser.
Be aware that this may leave sensitive plain-text data in the archive.z&Failing to disable an unknown parser 'z'.c                    s   g | ]	}t ƒ | ˆ Ž ‘qS r&   )Úglobals)rI   Úcls_name©Úparser_argsr&   r'   rK   Ä   s    ÿÿz#Cleaner initialized. From cmdline: )7ÚsuperÚ__init__Úfrom_cmdlineÚoptsr=   r>   r?   r@   ÚhasattrÚthreadsr3   r/   ÚloggingÚ	getLoggerÚsoslogÚui_logÚosÚmakedirsÚpathÚjoinÚreview_parser_valuesÚload_map_fileÚcleaner_mappingÚumaskÚin_placeÚget_preferred_hash_nameÚ	hash_nameÚ
componentsÚadd_sectionÚ
cleaner_mdr6   Údirnamer2   r   r   r   r   r	   r
   r1   ÚlowerÚstripÚlog_infoÚwarningÚremoveÚparsersr   r   r   r   r   r   r   Úarchive_typesÚnested_archive)ÚselfÚparserÚargsÚcmdlinerc   Úhook_commonsÚcleaner_dirÚparser_classesÚparser_namesÚ_parserÚfoundÚpnameÚparser_name©Ú	__class__rO   r'   rR   z   s�   






ÿÿýúÿ
ÿ
÷

ÿ€
þø

ÿzSoSCleaner.__init__c                 C   s   d|rd|› �nd› d|› �S )Nz[cleanerú:r-   z] r&   ©rr   ÚmsgÚcallerr&   r&   r'   Ú_fmt_log_msgØ   s   zSoSCleaner._fmt_log_msgc                 C   ó   | j  |  ||¡¡ d S ©N)rY   Údebugr„   r�   r&   r&   r'   Ú	log_debugÛ   ó   zSoSCleaner.log_debugc                 C   r…   r†   )rY   Úinfor„   r�   r&   r&   r'   rl   Þ   r‰   zSoSCleaner.log_infoc                 C   r…   r†   )rY   Úerrorr„   r�   r&   r&   r'   Ú	log_errorá   r‰   zSoSCleaner.log_errorc                 C   s   |  d¡ | | j¡ d S )NzSoS Cleaner Detailed Help)Ú	set_titleÚadd_textÚ__doc__)rJ   Úsectionr&   r&   r'   Údisplay_helpä   s   
zSoSCleaner.display_helpc                 C   s$  i }d}t j | jj¡rtd| jj› d�ƒ‚t j | jj¡s1| jj|kr/|  d| jj› d�¡ |S t| jjddd��N}zt	 
|¡}W n- t	jyQ   |  d	¡ Y n' tyo } z|  d
| jj› d|› �¡ W Y d}~nd}~ww W d  ƒ |S W d  ƒ |S W d  ƒ |S 1 s‹w   Y  |S )z×Verifies that the map file exists and has usable content.

        If the provided map file does not exist, or it is empty, we will print
        a warning and continue on with cleaning building a fresh map
        r,   zRequested map file z is a directoryzERROR: map file z6 does not exist, will not load any obfuscation matchesÚrúutf-8©ÚencodingzOERROR: Unable to parse map file, json is malformed. Will not load any mappings.zERROR: Could not load 'ú': N)r[   r]   ÚisdirrT   r6   Ú	ExceptionÚexistsrŒ   ÚopenÚjsonÚloadÚJSONDecodeError)rr   Ú_confÚdefault_mapÚmfÚerrr&   r&   r'   r`   é   sD   ÿ÷ÿÿ€ÿü
þ	û
ü	þ
ù	÷	zSoSCleaner.load_map_filec              
   C   s    |   d¡}| j dt› d�¡ | j |¡ | jjsNztdƒ W dS  ty5   | j d¡ |  d¡ Y dS  t	yM } z|  d|¡ W Y d}~dS d}~ww dS )	z�When we are directly running `sos clean`, rather than hooking into
        SoSCleaner via report or collect, print a disclaimer banner
        a…  This command will attempt to obfuscate information that is generally considered to be potentially sensitive. Such information includes IP addresses, MAC addresses, domain names, and any user-provided keywords.

Note that this utility provides a best-effort approach to data obfuscation, but it does not guarantee that such obfuscation provides complete coverage of all such data in the archive, or that any obfuscation is provided to data that does not fit the description above.

Users should review any resulting data and/or archives generated or processed by this utility for remaining sensitive content before being passed to a third party.
z
sos clean (version z)
z-
Press ENTER to continue, or CTRL-C to quit.
z
Exiting on user cancelé‚   é   N)
Ú_fmt_msgrZ   rŠ   r   rT   ÚbatchÚinputÚKeyboardInterruptÚ_exitr˜   )rr   r‚   r%   r&   r&   r'   Úprint_disclaimer  s   
€ÿúzSoSCleaner.print_disclaimerc                 C   s  d|_ | dd¡}|jdddd� |jdd	g d
¢dd� |jddg dd� |jddg ddd� |jdddg ddd� |jdddtdd� |jddg dd d� |jd!d d"d#d$� |jd%d&d'd(d)� |jd*d+d,d-d.d/� |jd0d,d-d1d2d3� |jd4d5g dd6d/� |jd7d8g d9¢d:d;d<� d S )=Nzsos clean|mask TARGET [options]zCleaner/Masking Optionsz7These options control how data obfuscation is performedr9   ÚTARGETz%The directory or archive to obfuscate)ÚmetavarÚhelpz--archive-typer*   )r*   ÚreportÚcollectÚinsightszdata-dirÚtarballz8Specify what kind of archive the target was generated as)ÚdefaultÚchoicesr¬   z	--domainsÚextendz!List of domain names to obfuscate)Úactionr±   r¬   z--disable-parsersr1   zCDisable specific parsers, so that those elements are not obfuscated)r´   r±   Údestr¬   z--skip-cleaning-filesz--skip-masking-filesr2   zBList of files to skip/ignore during cleaning. Globs are supported.z-jz--jobsr+   z&Number of concurrent archives to clean)r±   Útyper¬   z
--keywordsr4   zList of keywords to obfuscatez--keyword-filer5   z&Provide a file a keywords to obfuscate)r±   rµ   r¬   z
--map-filer6   r,   z;Provide a previously generated mapping file for obfuscation)rµ   r±   r¬   z--no-updater7   FÚ
store_truez<Do not update the --map-file with new mappings from this run)rµ   r±   r´   r¬   z--keep-binary-filesr8   zGKeep unprocessable binary files in the archive instead of removing them)r±   r´   rµ   r¬   z--usernamesr:   zList of usernames to obfuscatez--treat-certificatesr.   )r.   Úkeeprn   r;   z”How to treat certificate files [.csr .crt .pem]. Defaults to "obfuscate" after convert the file to text. "Key" certificate files are always removed.)r±   r²   rµ   r¬   )ÚusageÚadd_argument_groupÚadd_argumentÚint)rJ   rs   Ú	clean_grpr&   r&   r'   Úadd_parser_options"  sr   þÿý
ÿþýÿ
þþþ
þý
þ
üzSoSCleaner.add_parser_optionsc                 C   s   || j _dS )z¿For use by report and collect to set the TARGET option appropriately
        so that execute() can be called just as if we were running `sos clean`
        directly from the cmdline.
        N)rT   r9   )rr   r]   r&   r&   r'   Úset_target_path]  s   zSoSCleaner.set_target_pathc                 C   sê   d}| j jdkr*| j j dd¡}| jD ]}|j|kr(|| j j| j| j j| j jƒ}qn| jD ]}| 	| j j¡rF|| j j| j| j j| j jƒ} nq-|sKdS || _
| j |¡ |jrh| j | ¡ ¡ | j |¡ || _| jrs| jj| j_dS dS )z²The target path is not a directory, so inspect it for being an
        archive or an archive of archives.

        In the event the target path is not an archive, abort.
        Nr*   ú-Ú_)rT   r/   Úreplacerp   Ú	type_namer9   r=   r8   r;   Úcheck_is_typeÚmain_archiveÚreport_pathsÚappendÚ	is_nestedr³   Úget_nested_archivesrn   rq   ÚdescriptionÚui_name)rr   Ú_arcÚ
check_typeÚarchiver!   r&   r&   r'   Úinspect_target_archived  s<   

þ€þ
þüÿz!SoSCleaner.inspect_target_archivec                 C   sJ   | j jD ]}t| d¡ƒdk rtd|› d�ƒ‚qdd„ | j jD ƒ| j _dS )zôCheck any values passed to the parsers via the commandline:
        - For the --domains option, ensure that they are valid for the parser
          in question.
        - Convert --skip-cleaning-files from globs to regular expressions.
        Ú.é   zInvalid value 'z0' given: --domains values must be actual domainsc                 S   s   g | ]}t  |¡‘qS r&   )ÚfnmatchÚ	translate)rI   Úpr&   r&   r'   rK   ’  s    z3SoSCleaner.review_parser_values.<locals>.<listcomp>N)rT   r0   ÚlenÚsplitr˜   r2   )rr   Ú_domr&   r&   r'   r_   †  s   
ÿÿÿzSoSCleaner.review_parser_valuesc                 C   s¬  | j j d¡| j _| j j d¡d  d¡d | _| jr|  ¡  g | _tj	 
| j j¡s:| j d| j j› �¡ |  d¡ |  ¡  | jsL| j d¡ |  d¡ g | _| jD ]}|jdkr^|j ¡  qR|  ¡  |  ¡  |  ¡  | js~| jrsd	S | j d
¡ |  d¡ | j dt| jƒ› d�¡ |  ¡ }|  |¡}|  |¡ |  ¡  | jr¬dd„ | jD ƒ}||fS d	}t| jƒdkrº|  ¡ }nH| jd }|j}|   |j¡}|d	urþ|  !| d¡d › d| j"› �¡}	t#tj	 $| j%|	¡ddd��}
|
 &|¡ W d	  ƒ n1 sùw   Y  |  '¡  tj	 $| j%|  !| d¡d ¡¡}t( )||¡ t *|¡}| j d|› �¡ | j d|› d�¡ | j dt+|j,ƒ› �¡ | j dt-|j.ƒj/› d�¡ | j d¡ |  0¡  d	S )a,  SoSCleaner will begin by inspecting the TARGET option to determine
        if it is a directory, archive, or archive of archives.

        In the case of a directory, the default behavior will be to edit the
        data in place. For an archive will we unpack the archive, iterate
        over the contents, and then repack the archive. In the case of an
        archive of archives, such as one from SoSCollector, each archive will
        be unpacked, cleaned, and repacked and the final top-level archive will
        then be repacked as well.
        ú/éÿÿÿÿz.tarr   z*Invalid target: no such file or directory r£   z'No valid archives or directories found
zHostname ParserNz#No reports obfuscated, aborting...
z
Successfully obfuscated z report(s)
c                 S   rG   r&   )Úfinal_archive_path)rI   Úar&   r&   r'   rK   Ê  s    z&SoSCleaner.execute.<locals>.<listcomp>rÐ   Úwr“   r”   z2A mapping of obfuscated elements is available at
	z)
The obfuscated archive is available at
	Ú
z	Size	z	Owner	zdPlease send the obfuscated archive to your support
representative and keep the mapping file private.)1rT   r9   ÚrstriprÖ   Úarc_namerS   r©   rÆ   r[   r]   r™   rZ   r‹   r¨   rÏ   Úcompleted_reportsro   ÚnameÚmappingÚset_initial_countsÚpreload_all_archives_into_mapsÚgenerate_parser_item_regexesÚobfuscate_report_pathsrc   rŠ   rÕ   Úcompile_mapping_dictÚwrite_map_for_archiveÚwrite_map_for_configÚwrite_stats_to_manifestÚrebuild_nested_archiverÚ   Úget_new_checksumÚobfuscate_stringre   rš   r^   r>   ÚwriteÚwrite_cleaner_logÚshutilÚmoveÚstatr   Úst_sizer   Úst_uidÚpw_nameÚcleanup)rr   rs   Ú_mapÚmap_pathÚ	arc_pathsÚ
final_pathÚarc_pathr!   ÚchecksumÚchksum_nameÚcfÚarcstatr&   r&   r'   Úexecute•  s’   ÿ




€

ÿ



ÿÿþþ
ÿ
ÿÿzSoSCleaner.executec                 C   sì   | j d }| j|d� | jD ]%}|j d¡d }|  |j¡}|dur3d|› d| j› �}| jj||d� qt	 
| jj¡D ],\}}}|D ]$}	t	j ||	¡}
|
 | jj¡d }| d¡}| jj|
|d� t	 |
¡ qBq;| jd	d
� | j | jj¡S )zˆHandles repacking the nested tarball, now containing only obfuscated
        copies of the reports, log files, manifest, etc...
        z-obfuscated)rá   rØ   rÙ   Nz
checksums/rÐ   ©rµ   T)rÎ   )rß   Úsetup_archiverà   rÚ   rÖ   rì   re   rÎ   Ú
add_stringr[   Úwalkrq   Úextracted_pathr]   r^   ÚlstripÚadd_filern   rï   ÚfinalizerT   Úcompression_type)rr   rß   rÎ   Úarc_destrü   ÚdnameÚdirnrÁ   ÚfilesÚfilenameÚfnamer&   r&   r'   rë   ø  s&   

€
úz!SoSCleaner.rebuild_nested_archivec                 C   s2   i }| j D ]}i ||j< ||j  | ¡ ¡ q|S )a  Build a dict that contains each parser's map as a key, with the
        contents as that key's value. This will then be written to disk in the
        same directory as the obfuscated report so that sysadmins have a way
        to 'decode' the obfuscation locally
        )ro   Úmap_file_keyÚupdateÚget_map_contents)rr   r÷   rs   r&   r&   r'   rç     s
   

zSoSCleaner.compile_mapping_dictc                 C   sH   t |ddd��}| tj|dd�¡ W d  ƒ |S 1 sw   Y  |S )zjWrite the mapping to a file on disk that is in the same location as
        the final archive(s).
        rÜ   r“   r”   r+   )ÚindentN)rš   rî   r›   Údumps)rr   r÷   r]   r    r&   r&   r'   Úwrite_map_to_file  s   
ÿþzSoSCleaner.write_map_to_filec              
   C   sd   zt j | j|  | j› d�¡¡}|  ||¡W S  ty1 } z|  d|› �¡ W Y d }~d S d }~ww )Nz-private_mapz"Could not write private map file: )	r[   r]   r^   r>   rí   rß   r  r˜   rŒ   )rr   r÷   rø   r¡   r&   r&   r'   rè   %  s   þ€þz SoSCleaner.write_map_for_archivec              
   C   s˜   | j jrH| j jsJtj | j j¡}ztj|dd� |  || j j¡ |  d| j j› �¡ W dS  t	yG } z|  
d|› �¡ W Y d}~dS d}~ww dS dS )z}Write the mapping to the config file so that subsequent runs are
        able to provide the same consistent mapping
        TrD   zWrote mapping to z&Could not update mapping config file: N)rT   r6   r7   r[   r]   ri   r\   r  rˆ   r˜   rŒ   )rr   r÷   rw   r¡   r&   r&   r'   ré   0  s   €ÿøzSoSCleaner.write_map_for_configc                 C   s’   t j | j| j› d�¡}t|ddd��}| j d¡ | j ¡ D ]}| 	|¡ qW d  ƒ n1 s1w   Y  |rG|  
|¡ | jj|dd� dS dS )	z³When invoked via the command line, the logging from SoSCleaner will
        not be added to the archive(s) it processes, so we need to write it
        separately to disk
        z-obfuscation.logrÜ   r“   r”   r   Nzsos_logs/cleaner.logr  )r[   r]   r^   r>   rß   rš   Úsos_log_fileÚseekÚ	readlinesrî   Úobfuscate_filerÎ   r  )rr   rÎ   Úlog_nameÚlogfileÚliner&   r&   r'   rï   ?  s   ÿÿþ
þzSoSCleaner.write_cleaner_logc              
   C   s¤   z6d}t |dƒ�$}t | j¡}	 | |¡}|sn| |¡ q| ¡ d W  d  ƒ W S 1 s/w   Y  W dS  tyQ } z|  d|› �¡ W Y d}~dS d}~ww )zvCalculate a new checksum for the obfuscated archive, as the previous
        checksum will no longer be valid
        i   ÚrbTrÝ   Nz!Could not generate new checksum: )	rš   ÚhashlibÚnewre   Úreadr  Ú	hexdigestr˜   rˆ   )rr   Úarchive_pathÚ	hash_sizeÚ
archive_fpÚdigestÚhashdatar¡   r&   r&   r'   rì   P  s$   

ü
$ù
þ€þzSoSCleaner.get_new_checksumc                 C   s,  z€dt | jƒ› d| jj› d�}| j |¡ | jjr| j d¡ | jjdkr3t	dƒs3d| j_| j d¡ | jjdkr@| j d	¡ n| jjd
krM| j d¡ n| jjdkrY| j d¡ | jD ]}| j d|j
› �¡ |  |¡ q\| jr~|  ¡  |  | j¡ W dS W dS  ty•   | j d¡ t d¡ Y dS w )zØPerform the obfuscation for each archive or sos directory discovered
        during setup.

        Each archive is handled in a separate thread, up to self.opts.jobs will
        be obfuscated concurrently.
        zFound z. total reports to obfuscate, processing up to z" concurrently within one
archive.
zqWARNING: binary files that potentially contain sensitive information will NOT be
removed from the final archive.
r.   Úopensslrn   zgWARNING: No `openssl` command available. Replacing
`--treat-certificates` from `obfuscate` to `remove`.zˆWARNING: certificate files that potentially contain sensitive information will
be CONVERTED to text and OBFUSCATED in the finalarchive.
r¸   zsWARNING: certificate files that potentially contain sensitive information will
be KEPT in the final archive as is.
zpWARNING: certificate files that potentially contain sensitive information will
be REMOVED in the final archive.
zObfuscating zExiting on user cancelr¢   N)rÕ   rÆ   rT   r3   rZ   rŠ   r8   rm   r;   r   r"  Úobfuscate_reportrq   Ú_replace_obfuscated_archivesr§   r[   r¨   )rr   r‚   Úreport_pathr&   r&   r'   ræ   b  sP   ÿÿÿÿÿÿÿÿ
þþz!SoSCleaner.obfuscate_report_pathsc                 C   sV   | j D ]%}t |j¡ | jj}|j d¡d }tj 	||¡}t
 |j|¡ ||_qdS )z±When we have a nested archive, we need to rebuild the original
        archive, which entails replacing the existing archives with their
        obfuscated counterparts
        rØ   rÙ   N)rà   r[   rn   r"  rq   r  rÚ   rÖ   r]   r^   rð   rñ   )rr   rÎ   rµ   r°   Ú	dest_namer&   r&   r'   r)  ›  s   
úz'SoSCleaner._replace_obfuscated_archivesc                 C   s   | j D ]}| ¡  qdS )zéFor the parsers that use prebuilt lists of items, generate those
        regexes now since all the parsers should be preloaded by the archive(s)
        as well as being handed cmdline options and mapping file configuration.
        N)ro   Úgenerate_item_regexes)rr   rs   r&   r&   r'   rå   ¨  s   

ÿz'SoSCleaner.generate_parser_item_regexesc                 C   sB  | j D ]•}d|j_|j ¡  ¡ d  ¡ }| ||¡D ]G}| |¡}|s$q|  	d|› d|› d|j
› �¡ | ¡ D ])}z| |¡ W q7 ty` } z|  	d|› d|› d|› �¡ W Y d	}~q7d	}~ww q| ||¡}	|	r�|  	d|› d
|j
› �¡ |	D ]}
|j |
¡ qx|j| D ]}|j |¡ q†d|j_|j ¡  q| | j ¡ d	S )a*  
        For each archive we've determined we need to operate on, pass it to
        each prepper so that we can extract necessary files and/or items for
        direct regex replacement. Preppers define these methods per parser,
        so it is possible that a single prepper will read the same file for
        different parsers/mappings. This is preferable to the alternative of
        building up monolithic lists of file paths, as we'd still need to
        manipulate these on a per-archive basis.

        :param archive: The archive we are currently using to prepare our
                        mappings with
        :type archive:  ``SoSObfuscationArchive`` subclass

        :param prepper: The individual prepper we're using to source items
        :type prepper:  ``SoSPrepper`` subclass
        Tr   z	Prepping z parser with file z from zFailed to prep z
 map from ú: Nz mapping with items from F)ro   râ   Úinitializingrá   rj   rÖ   rk   Úget_parser_file_listÚget_file_contentrˆ   rË   Ú
splitlinesÚ
parse_liner˜   Úget_items_for_mapÚaddÚregex_itemsÚadd_regex_itemÚgenerate_compiled_regexesÚset_parsers)rr   rÎ   Úprepperrz   r|   Ú_fileÚcontentr  r¡   Ú	map_itemsÚitemÚritemr&   r&   r'   Ú_prepare_archive_with_prepper°  s@   

ÿÿ€ÿýÿz(SoSCleaner._prepare_archive_with_prepperc                 c   s\   � t tjjƒ}g }| ¡ D ]}| td|› �ƒ¡ qt|dd„ d�D ]	}|| jd�V  q"dS )a  
        Discover all locally available preppers so that we can prepare the
        mappings with obfuscation matches in a controlled manner

        :returns: All preppers that can be leveraged locally
        :rtype:   A generator of `SoSPrepper` items
        zsos.cleaner.preppers.c                 S   s   | j S r†   )Úpriority©Úxr&   r&   r'   Ú<lambda>ë  s    z)SoSCleaner.get_preppers.<locals>.<lambda>)Úkey)r<   N)	r   rA   rC   ÚpreppersÚget_modulesr³   r   ÚsortedrT   )rr   ÚhelperÚprepsÚ_prepr9  r&   r&   r'   Úget_preppersß  s   €ÿzSoSCleaner.get_preppersc                 C   sB   |   d¡ |  ¡ D ]}| jD ]}|  ||¡ qq	| j | j¡ dS )a  Before doing the actual obfuscation, if we have multiple archives
        to obfuscate then we need to preload each of them into the mappings
        to ensure that node1 is obfuscated in node2 as well as node2 being
        obfuscated in node1's archive.
        z.Pre-loading all archives into obfuscation mapsN)rl   rK  rÆ   r?  rÅ   r8  ro   )rr   r9  rÎ   r&   r&   r'   rä   î  s   

ÿz)SoSCleaner.preload_all_archives_into_mapsc              
   C   sZ  dd„ }�z†| j  |j¡}t ¡ }| d|¡ |js| ¡  | d¡ d } }}t	 
¡ }t	 
¡ }	g }
t| jjƒD ]}t	jt|||	fd�}| ¡  |
 |¡ q9|t| ¡ ƒtj tj |j¡¡ƒD ]}| |¡ qat| jjƒD ]}| d¡ qo|
D ]}| ¡  qy|	 ¡ s¹z	|	 ¡ \}}}W n ty¨ } z|  d|› d	�¡ W Y d}~nd}~ww ||7 }||7 }||7 }|	 ¡ r„| ¡  z|   |¡ W n t!yá } z| jd
|› �|jd� W Y d}~nd}~ww z|  "|¡ W n t!�y } z| jd|› �|jd� W Y d}~nd}~ww |j#�sX| $¡ }|�rR| d¡ z| %|  &|j¡¡ | '|¡ W n) t!�yQ } z|  (d|j› d|› �¡ | d|› �¡ W Y d}~W dS d}~ww | j) |¡ t ¡ }| d|¡ | d|| ¡ | d|¡ | d|¡ d}|�r�d}|| }| d|› �¡ W dS  t!�y¬ } z| j* +d|j› d|› �¡ W Y d}~dS d}~ww )zßIndividually handle each archive or directory we've discovered by
        running through each file therein.

        Positional arguments:

            :param archive str:      Filepath to the directory or archive
        c                    s2   ‡ fdd„| D ƒ}t |dd„ dd�}dd„ |D ƒS )zc Order files per their sizes, if they are provided relatively
            to base_path
            c              	      s&   g | ]}|t j t j ˆ |¡¡f‘qS r&   )r[   r]   Úgetsizer^   )rI   Úf©Ú	base_pathr&   r'   rK     s    ÿÿzMSoSCleaner.obfuscate_report.<locals>._order_files_by_size.<locals>.<listcomp>c                 S   s   | d S )Nr£   r&   rA  r&   r&   r'   rC    s    zKSoSCleaner.obfuscate_report.<locals>._order_files_by_size.<locals>.<lambda>T)rD  Úreversec                 S   s   g | ]\}}|‘qS r&   r&   )rI   r$   rÁ   r&   r&   r'   rK     s    )rG  )Ú	file_listrO  Úfiles_with_sizesÚfiles_sizes_sortedr&   rN  r'   Ú_order_files_by_size  s   
þ
ÿz9SoSCleaner.obfuscate_report.<locals>._order_files_by_sizeÚ
start_timezBeginning obfuscation...r   )r9   rt   NzXFailed to receive obfuscation stats from child; statistics might be incomplete. Error: 'r   z!Failed to obfuscate directories: ©rƒ   zFailed to obfuscate symlinks: zRe-compressing...zArchive z failed to compress: zFailed to re-compress archive: Úend_timeÚrun_timeÚfiles_obfuscatedÚtotal_substitutionsr-   z! [removed %s unprocessable files]zObfuscation completedzException while processing r-  ),rh   rg   Úarchive_namer   ÚnowÚ	add_fieldÚis_extractedÚextractÚ
report_msgÚmultiprocessingÚQueueÚrangerT   r3   ÚProcessr(   ÚstartrÇ   ÚlistÚ	get_filesr[   r]   ri   Úabspathr  r   r^   Úemptyr   r   rl   Úload_parser_entriesÚobfuscate_directory_namesr˜   Úobfuscate_symlinksrÈ   Úget_compressionÚrename_top_dirrí   Úcompressrˆ   rà   rZ   rŠ   )rr   rÎ   rT  Úarc_mdrU  r   r   r   r"   r#   Ú	processesrÁ   rÔ   r$   ÚfocÚtscÚrfcr%   r¡   ÚmethodrW  Úrmsgr&   r&   r'   r(  ú  sÄ   	
þ
þ
ÿÿ€ÿöÿ€ÿÿ€ÿ

ÿÿÿ€ûÿÿ€ÿzSoSCleaner.obfuscate_reportc                 C   s   | j  |¡ d S r†   )rÅ   r    )rr   r  r&   r&   r'   r  {  s   zSoSCleaner.obfuscate_filec                    s
  | j d|jd� | ¡ D ]v}zW| |j¡d  d¡‰ ‡ fdd„| jD ƒ}|s1|  dˆ › d�¡ W q| jd	ˆ › �|jd� t 	|¡}tj
 |j|  ˆ ¡¡}|  |¡}||ksY||krdt |¡ t ||¡ W q ty‚ } z|   d
|› d|› �¡ W Y d}~qd}~ww dS )aÄ  Iterate over symlinks in the archive and obfuscate their names.
        The content of the link target will have already been cleaned, and this
        second pass over just the names of the links is to ensure we avoid a
        possible race condition dependent on the order in which the link or the
        target get obfuscated.

        :param archive:     The archive being obfuscated
        :type archive:      ``SoSObfuscationArchive``
        zObfuscating symlink namesrV  r£   rØ   c                    s(   g | ]}t ‡ fd d„|jD ƒƒs|‘qS )c                 3   s   � | ]}|  ˆ ¡V  qd S r†   )Úmatch)rI   Ú_skip©Ú_symr&   r'   Ú	<genexpr>‘  s   € z;SoSCleaner.obfuscate_symlinks.<locals>.<listcomp>.<genexpr>)ÚanyÚskip_patterns)rI   Ú_pry  r&   r'   rK   �  s    þÿz1SoSCleaner.obfuscate_symlinks.<locals>.<listcomp>z Skipping obfuscation of symlink z due to skip pattern matchzObfuscating symlink zError obfuscating symlink 'r–   N)rl   r[  Úget_symlinksrÖ   r  r  ro   rˆ   r[   Úreadlinkr]   r^   rí   rn   Úsymlinkr˜   )rr   rÎ   r�  Ú_parsersÚ_targetÚ_ob_sym_nameÚ
_ob_targetr¡   r&   ry  r'   rl  ~  s:   

ÿ
ÿÿ

ÿ

€"€ÿàzSoSCleaner.obfuscate_symlinksc                 C   s¦   |   d|j› �¡ t| ¡ dd�D ]?}t |¡D ]7}tj ||¡}| |j	¡d }tj 
|¡rO|  |¡}||krO| |¡}tj |j	| d¡|¡}t ||¡ qqdS )z˜For all directories that exist within the archive, obfuscate the
        directory name if it contains sensitive strings found during execution
        z'Obfuscating directory names in archive T)rP  rÙ   rØ   N)rl   r[  rG  Úget_directory_listr[   Úlistdirr]   r^   rÖ   r  r—   rí   rÞ   r  Úrename)rr   rÎ   ÚdirpathÚ_nameÚ_dirnameÚ_arc_dirÚ_ob_dirnameÚ_ob_arc_dirr&   r&   r'   rk  ¬  s(   ÿ

ý€ôÿz$SoSCleaner.obfuscate_directory_namesc                 C   sR   | j D ]#}z| |¡}W q ty& } z|  d|› �¡ W Y d }~qd }~ww |S )NzError obfuscating string data: )ro   Úparse_string_for_keysr˜   rl   )rr   Ústring_datars   r¡   r&   r&   r'   rí   Ã  s   
€ÿzSoSCleaner.obfuscate_stringc                 C   sL   | j  d¡}| jD ]}| |j dd¡ ¡ ¡}| dt|jj	 
¡ ƒ¡ q	dS )zLWrite some cleaner-level, non-report-specific stats to the manifest
        ro   ú rÁ   ÚentriesN)rh   rg   ro   rá   rÂ   rj   r]  rÕ   râ   ÚdatasetÚkeys)rr   Ú	parse_secrs   Ú_secr&   r&   r'   rê   Ë  s
   
þz"SoSCleaner.write_stats_to_manifest)NNNFNr†   )F)(rH   Ú
__module__Ú__qualname__r�   ÚdescÚarg_defaultsrR   r„   rˆ   rl   rŒ   Úclassmethodr‘   r`   r©   r¾   r¿   rÏ   r_   r   rë   rç   r  rè   ré   rï   rì   ræ   r)  rå   r?  rK  rä   r(  r  rl  rk  rí   rê   Ú__classcell__r&   r&   r~   r'   r)   @   sl    'óÿ
^




:"c
9/ .r)   ),r  r›   rW   r[   rð   rÒ   ra  r   Úpwdr   Úsos.cleaner.preppersrA   r   Úsos.componentr   Úsos.cleaner.parsers.ip_parserr   Úsos.cleaner.parsers.mac_parserr   Ú#sos.cleaner.parsers.hostname_parserr   Ú"sos.cleaner.parsers.keyword_parserr	   Ú#sos.cleaner.parsers.username_parserr
   Úsos.cleaner.parsers.ipv6_parserr   Úsos.cleaner.archives.sosr   r   r   r   Úsos.cleaner.archives.genericr   r   Úsos.cleaner.archives.insightsr   Úsos.utilitiesr   r   r   r   r(   r)   r&   r&   r&   r'   Ú<module>   s0   
