3 'j@s$ddlZddlZddlZddlZddlZddlZddlmZddlmZddl m Z ddl Z ddl m Z ddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZmZmZm Z ddl!m"Z"m#Z#ddl$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*ddZ+GdddeZ,dS)N)ProcessPoolExecutor)datetime)getpwuid) __version__) SoSComponent) SoSIPParser) SoSMacParser)SoSHostnameParser)SoSKeywordParser)SoSUsernameParser) SoSIPv6Parser)SoSReportArchiveSoSReportDirectorySoSCollectorArchiveSoSCollectorDirectory)DataDirArchiveTarballArchive)InsightsArchive)get_human_readable import_moduleImporterHelper is_executablecCs |j|S)N)obfuscate_arc_files)arcflistr/usr/lib/python3.6/__init__.pyr*srcsPeZdZdZdZdgggdgdddddgd d ZdKfd d ZdLd dZdMddZdNddZ dOddZ e ddZ ddZ ddZe ddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.ZdPd/d0Zd1d2Zd3d4Zd5d6Zd7d8Zd9d:Zd;d<Zd=d>Z d?d@Z!dAdBZ"dCdDZ#dEdFZ$dGdHZ%dIdJZ&Z'S)Q 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 reportautoNz /etc/sos/cleaner/default_mappingF obfuscate) archive_typedomainsdisable_parsersskip_cleaning_filesjobskeywords keyword_filemap_file no_updatekeep_binary_filestarget usernamestreat_certificatesc s |stj|||d|_n|d|_|d|_|d|_|d|_|d|_d|_t|jdsl|jj |j_ d |j_ t j d |_t j d |_tjtjj|jd dd |j|j|_tjd||_|jj|_|jjjd |_|jjrtjj|jjnd}|j||jj gt!t"t#t$t%t&g}dd|D}x|jj'D]} d} xd|D]\} | ddj(} | j(j)| krH|j*d| |jj+d| d|j,| d} PqHW| s:|jj+d| dq:Wfdd|D|_-t.t/t0t1t2t3t4g|_5d|_6|j*d|jdS)NToptionstmpdirsys_tmppolicymanifestFr&rsosZsos_uicleaner)exist_ok?z/etc/sos/cleanercSsg|] }|jqSr)__name__).0clsrrr sz'SoSCleaner.__init__..zDisabling parser: zDisabling the 'zP' parser. Be aware that this may leave sensitive plain-text data in the archive.z&Failing to disable an unknown parser 'z'.csg|]}t|qSr)globals)r9Zcls_name) parser_argsrrr;sz#Cleaner initialized. From cmdline: i)7super__init__ from_cmdlineoptsr0r1r2r3hasattrZthreadsr&r"loggingZ getLoggersoslogui_logosmakedirspathjoinreview_parser_values load_map_fileZcleaner_mappingumaskin_placeZget_preferred_hash_name hash_nameZ components add_section cleaner_mdr)dirnamer%r rr rr r r$lowerstriplog_infowarningremoveparsersrr rrrrr archive_typesnested_archive) selfparserargsZcmdlinerOZ hook_commons cleaner_dirZparser_classesZ parser_names_parserfoundpnameZ parser_name) __class__)r?rrAhst                 zSoSCleaner.__init__cCsd|rd|ndd|S)Nz[cleaner:r z] r)r\msgcallerrrr _fmt_log_msgszSoSCleaner._fmt_log_msgcCs|jj|j||dS)N)rFdebugrg)r\rerfrrr log_debugszSoSCleaner.log_debugcCs|jj|j||dS)N)rFinforg)r\rerfrrrrVszSoSCleaner.log_infocCs|jj|j||dS)N)rFerrorrg)r\rerfrrr log_errorszSoSCleaner.log_errorcCs|jd|j|jdS)NzSoS Cleaner Detailed Help)Z set_titleZadd_text__doc__)r:Zsectionrrr display_helps zSoSCleaner.display_helpcCsi}d}tjj|jjr,td|jjdtjj|jjs`|jj|kr|jd|jjdnt|jjdddp}yt j |}WnZt j k r|jd Yn<tk r}z |jd |jjd |WYd d }~XnXWd QRX|S) zVerifies 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 z /etc/sos/cleaner/default_mappingzRequested map file z is a directoryzERROR: map file z6 does not exist, will not load any obfuscation matchesrzutf-8)encodingzOERROR: Unable to parse map file, json is malformed. Will not load any mappings.zERROR: Could not load 'z': N) rHrJisdirrCr) ExceptionexistsrlopenjsonloadZJSONDecodeError)r\Z_confZ default_mapmferrrrrrMs  6zSoSCleaner.load_map_filecCs|jd}|jjdtd|jj||jjsy tdWnVtk rh|jjd|jdYn.t k r}z|jd|WYdd}~XnXdS) zWhen we are directly running `sos clean`, rather than hooking into SoSCleaner via report or collect, print a disclaimer banner aThis 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 cancelN) Z_fmt_msgrGrjrrCZbatchinputKeyboardInterrupt_exitrr)r\reerrrprint_disclaimers    zSoSCleaner.print_disclaimerc Cs"d|_|jdd}|jdddd|jdd d d d d d dgdd|jddgdd|jddgddd|jdddgddd|jdddtd d!|jd"dgd#d$d|jd%dd&d'd(|jd)d*d+d,d-|jd.d/d0d1d2d3|jd4d0d1d5d6d7|jd8d9gdd:d3|jd;dgd?d@dAdS)BNzsos clean|mask TARGET [options]zCleaner/Masking Optionsz7These options control how data obfuscation is performedr,ZTARGETz%The directory or archive to obfuscate)metavarhelpz--archive-typerZreportZcollectZinsightszdata-dirtarballz8Specify what kind of archive the target was generated as)defaultchoicesrz --domainsextendz!List of domain names to obfuscate)actionrrz--disable-parsersr$zCDisable specific parsers, so that those elements are not obfuscated)rrdestrz--skip-cleaning-filesz--skip-masking-filesr%zBList of files to skip/ignore during cleaning. Globs are supported.z-jz--jobsrz&Number of concurrent archives to clean)rtyperz --keywordsr'zList of keywords to obfuscatez--keyword-filer(z&Provide a file a keywords to obfuscate)rrrz --map-filer)z /etc/sos/cleaner/default_mappingz;Provide a previously generated mapping file for obfuscation)rrrz --no-updater*F store_truez.N)rCr#lensplitrrr%)r\Z_domrrrrLss zSoSCleaner.review_parser_valuesc Cs|jjjd|j_|jjjddjdd|_|jr>|jg|_tj j |jjst|j j d|jj|j d|j|js|j j d|j dg|_x"|jD]}|jdkr|jjqW|j|j|j|js|jrdS|j jd |j d|j jd t|jd |j}|j|}|j||j|jr`d d |jD}||fSd}t|jdkr~|j}n~|jd}|j}|j |j}|dk r|j!|jddd|j"} t#tj j$|j%| ddd} | j&|WdQRX|j'tj j$|j%|j!|jdd}t(j)||tj*|} |j jd||j jd|d|j jdt+| j,|j jdt-| j.j/d|j jd|j0dS)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. /rzz.tarrz*Invalid target: no such file or directory z'No valid archives or directories found zHostname ParserNz#No reports obfuscated, aborting... z Successfully obfuscated z report(s) cSsg|] }|jqSr)final_archive_path)r9arrrr;sz&SoSCleaner.execute..rwzutf-8)rpz2A mapping of obfuscated elements is available at z) The obfuscated archive is available at  z Size z Owner zcPlease send the obfuscated archive to your support representative and keep the mapping file privaterr)1rCr,rstriprarc_namerBrrrHrJrsrGrkr}rcompleted_reportsrYnamemappingZset_initial_countspreload_all_archives_into_mapsgenerate_parser_item_regexesobfuscate_report_pathsrOrjrcompile_mapping_dictwrite_map_for_archivewrite_map_for_configwrite_stats_to_manifestrebuild_nested_archiverget_new_checksumobfuscate_stringrPrtrKr1writewrite_cleaner_logshutilmovestatrst_sizerst_uidZpw_nameZcleanup) r\r]_mapmap_pathZ arc_pathsZ final_pathZarc_pathrchecksumZ chksum_nameZcfZarcstatrrrexecutesv                   zSoSCleaner.executec Cs|jd}|j|dxT|jD]J}|jjdd }|j|j}|dk rd|d|j}|jj||dqWxnt j |j j D]\\}}}xP|D]H} t j j|| } | j|j j d }|jd}|jj| |dt j| qWq|W|jd d |jj|jjS) zHandles repacking the nested tarball, now containing only obfuscated copies of the reports, log files, manifest, etc... z -obfuscated)rrrzNz checksums/r)rT)rrr)rZ setup_archiverrrrrPrZ add_stringrHwalkr[extracted_pathrJrKlstripadd_filerXrfinalizerCZcompression_type) r\rrZarc_destrZdnameZdirnrfilesfilenameZfnamerrrrs"       z!SoSCleaner.rebuild_nested_archivecCs6i}x,|jD]"}i||j<||jj|jq W|S)aBuild 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 )rYZ map_file_keyupdateZget_map_contents)r\rr]rrrrs   zSoSCleaner.compile_mapping_dictc Cs2t|ddd}|jtj|ddWdQRX|S)zjWrite the mapping to a file on disk that is in the same location as the final archive(s). rzutf-8)rpr)indentN)rtrrudumps)r\rrJrwrrrwrite_map_to_fileszSoSCleaner.write_map_to_filecCs`y*tjj|j|j|jd}|j||Stk rZ}z|jd|dSd}~XnXdS)Nz -private_mapz"Could not write private map file: ) rHrJrKr1rrrrrrl)r\rrrxrrrrs z SoSCleaner.write_map_for_archivecCs|jjr|jj rtjj|jj}y6tj|dd|j||jj|jd|jjWn2t k r}z|j d|WYdd}~XnXdS)z}Write the mapping to the config file so that subsequent runs are able to provide the same consistent mapping T)r6zWrote mapping to z&Could not update mapping config file: N) rCr)r*rHrJrSrIrrirrrl)r\rr_rxrrrrszSoSCleaner.write_map_for_configc Cs~tjj|j|jd}t|ddd0}|jjdx|jjD]}|j |q@WWdQRX|rz|j ||j j |dddS) zWhen 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.logrzutf-8)rprNzsos_logs/cleaner.log)r) rHrJrKr1rrtZ sos_log_fileseek readlinesrobfuscate_filerr)r\rZlog_nameZlogfilelinerrrr*s  zSoSCleaner.write_cleaner_logcCsyRd}t|d:}tj|j}x|j|}|s0P|j|q W|jdSQRXWn2tk r}z|jd|WYdd}~XnXdS)zvCalculate a new checksum for the obfuscated archive, as the previous checksum will no longer be valid irrbrNz!Could not generate new checksum: i) rthashlibnewrPreadrZ hexdigestrrri)r\ archive_pathZ hash_sizeZ archive_fpZdigestZhashdatarxrrrr;s   "zSoSCleaner.get_new_checksumc Cs0ydt|jd|jjd}|jj||jjr>|jjd|jjdkrht d rhd|j_|jjd|jjdkr|jjd n2|jjd kr|jjd n|jjdkr|jjd x,|jD]"}|jjd |j |j |qW|j r|j |j |j Wn,tk r*|jjdtjdYnXdS)zPerform 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. zFound z. total reports to obfuscate, processing up to z! concurrently within one archive zpWARNING: binary files that potentially contain sensitive information will NOT be removed from the final archive r!ZopensslrXzgWARNING: No `openssl` command available. Replacing `--treat-certificates` from `obfuscate` to `remove`.zWARNING: certificate files that potentially contain sensitive information will be CONVERTED to text and OBFUSCATED in the final archive. rzsWARNING: 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 zExiting on user cancelryN)rrrCr&rGrjr+rWr.rrobfuscate_reportr[_replace_obfuscated_archivesr|rHr})r\reZ report_pathrrrrMs:        z!SoSCleaner.obfuscate_report_pathscCsZxT|jD]J}tj|j|jj}|jjdd}tjj ||}t j |j|||_qWdS)zWhen we have a nested archive, we need to rebuild the original archive, which entails replacing the existing archives with their obfuscated counterparts rrzNr) rrHrXrr[rrrrJrKrr)r\rrrZ dest_namerrrrs  z'SoSCleaner._replace_obfuscated_archivescCsx|jD] }|jqWdS)zFor 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)rYZgenerate_item_regexes)r\r]rrrrs z'SoSCleaner.generate_parser_item_regexesc CsDx0|jD]$}|jjjdj}x|j||D]}|j|}|sHq4|jd|d|d|jx^|j D]R}y|j |Wqpt k r}z"|jd|d|d|WYdd}~XqpXqpWq4W|j ||} | r|jd|d |jx| D]} |j j| qWx |j|D]} |j j| qWq W|j|jdS) 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 rz Prepping z parser with file z from zFailed to prep z map from z: Nz mapping with items from )rYrrTrrUZget_parser_file_listZget_file_contentrir splitlinesZ parse_linerrZget_items_for_mapraddZ regex_itemsZadd_regex_item set_parsers) r\rprepperr`rbZ_fileZcontentrrxZ map_itemsitemZritemrrr_prepare_archive_with_preppers* 2  z(SoSCleaner._prepare_archive_with_prepperccsbttjj}g}x$|jD]}|jtd|qWx&t|dddD]}||jdVqHWdS)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 zsos.cleaner.preppers.cSs|jS)N)Zpriority)xrrrsz)SoSCleaner.get_preppers..)key)r/N) rr4r5ZpreppersZ get_modulesrrsortedrC)r\helperZprepsZ_preprrrr get_prepperss  zSoSCleaner.get_prepperscCsJ|jdx,|jD] }x|jD]}|j||q WqW|jj|jdS)aBefore 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)rVrrrrrrY)r\rrrrrrs   z)SoSCleaner.preload_all_archives_into_mapsc;sy~jjj}tj}|jd|js4jjdt j d}}}d_ d_ fddt jjD}tjjdX}|jt|fddt jjD} x*| D]"\} } } || 7}|| 7}|| 7}qWWdQRXjyjWn:tk r8} zjd | jd WYdd} ~ XnXyjWn:tk r} zjd | jd WYdd} ~ XnXjsj}|rjd y jjjj|WnJtk r} z,jd jd| jd| dSd} ~ XnXjjtj}|jd||jd|||jd||jd|d}|rnd}||}jd|Wn>tk r} z j j djd| WYdd} ~ XnXdS)zIndividually 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 start_timezBeginning obfuscation...rNcsg|]}qSrr)r9i)rrrr; sz/SoSCleaner.obfuscate_report..) max_workerscsg|]}|djjqS)N)rCr&)r9r) file_listr\rrr; sz!Failed to obfuscate directories: )rfzFailed to obfuscate symlinks: zRe-compressing...zArchive z failed to compress: zFailed to re-compress archive: end_timeZrun_timeZfiles_obfuscatedZtotal_substitutionsr z! [removed %s unprocessable files]zObfuscation completedzException while processing z: )!rRrQ archive_namerZnow add_fieldZ is_extractedextractZ report_msglistZ get_filesrFrGrangerCr&rmaprZload_parser_entriesobfuscate_directory_namesrrrVobfuscate_symlinksrZget_compressionZrename_top_dirrcompressrirrrj)r\rZarc_mdrZfiles_obfuscated_countZtotal_sub_countZremoved_file_countZ archive_listexecutorZfuturesZfocZtscZrfcrxmethodrZrmsgr)rrr\rrsr              zSoSCleaner.obfuscate_reportcCs|jj|gdS)N)rr)r\rrrrrIszSoSCleaner.obfuscate_filecs|jd|jdx|jD]}y|j|jdjdfdd|jD}|sb|jddw|jd |jdtj |}tj j |j|j }|j |}||ks||krtj |tj||Wqtk r}z|jd |d |WYd d }~XqXqWd S) aIterate 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`` zObfuscating symlink names)rfrzrcs(g|] }tfdd|jDs|qS)c3s|]}|jVqdS)N)match)r9Z_skip)_symrr _sz;SoSCleaner.obfuscate_symlinks...)anyZ skip_patterns)r9Z_p)rrrr;^sz1SoSCleaner.obfuscate_symlinks..z Skipping obfuscation of symlink z due to skip pattern matchzObfuscating symlink zError obfuscating symlink 'z': N)rVrZ get_symlinksrrrrYrirHreadlinkrJrKrrXsymlinkrr)r\rrZ_parsersZ_targetZ _ob_sym_nameZ _ob_targetrxr)rrrLs(        zSoSCleaner.obfuscate_symlinkscCs|jd|jxt|jddD]}x|tj|D]n}tjj||}|j|j d}tjj |r4|j |}||kr4|j |}tjj|j |j d|}tj||q4Wq$WdS)zFor 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)reverserzrNr)rVrrZget_directory_listrHlistdirrJrKrrrqrrrrename)r\rdirpath_nameZ_dirnameZ_arc_dirZ _ob_dirnameZ _ob_arc_dirrrrrzs   z$SoSCleaner.obfuscate_directory_namescCsVxP|jD]F}y|j|}Wqtk rL}z|jd|WYdd}~XqXqW|S)NzError obfuscating string data: )rYZparse_string_for_keysrrrV)r\Z string_datar]rxrrrrs  &zSoSCleaner.obfuscate_stringcCsP|jjd}x>|jD]4}|j|jjddj}|jdt|jj j qWdS)zLWrite some cleaner-level, non-report-specific stats to the manifest rY rZentriesN) rRrQrYrrrTrrrZdatasetkeys)r\Z parse_secr]Z_secrrrrs  z"SoSCleaner.write_stats_to_manifest)NNNFN)N)N)N)N)F)(r8 __module__ __qualname__rmZdescZ arg_defaultsrArgrirVrl classmethodrnrMrrrrrLrrrrrrrrrrrrrrrrrrrr __classcell__rr)rcrr.s`&\      ;"a   6 , j.r)-rrurErHrrconcurrent.futuresrrpwdrZsos.cleaner.preppersr4rZ sos.componentrZsos.cleaner.parsers.ip_parserrZsos.cleaner.parsers.mac_parserrZ#sos.cleaner.parsers.hostname_parserr Z"sos.cleaner.parsers.keyword_parserr Z#sos.cleaner.parsers.username_parserr Zsos.cleaner.parsers.ipv6_parserr Zsos.cleaner.archives.sosr rrrZsos.cleaner.archives.genericrrZsos.cleaner.archives.insightsrZ sos.utilitiesrrrrrrrrrr s.