[
  {
    "path": ".gitignore",
    "content": ".DS_Store\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\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 licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  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\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions 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\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the 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\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\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\nconvey 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    {description}\n    Copyright (C) {year}  {fullname}\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 2 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 along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision 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, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "## Trudy\n\nTrudy is a transparent proxy that can modify and drop traffic for arbitrary TCP connections. Trudy can be used to programmatically modify TCP traffic for proxy-unaware clients. Trudy creates a 2-way \"pipe\" for each connection it proxies. The device you are proxying (the \"client\") connects to Trudy (but doesn't know this) and Trudy connects to the client's intended destination (the \"server\"). Traffic is then passed between these pipes. Users can create Go functions to mangle data between pipes.  [See it in action!](https://asciinema.org/a/7zkywm0biuz1wa64az3tmox8v) For a practical overview, check out [@tsusanka](https://twitter.com/tsusanka)'s very good [blog post](https://blog.susanka.eu/how-to-modify-general-tcp-ip-traffic-on-the-fly-with-trudy) on using Trudy to analyze Telegram's MTProto. \n\nTrudy can also proxy TLS connections. Obviously, you will need a valid certificate or a client that does not validate certificates.\n\nTrudy was designed for monitoring and modifying proxy-unaware devices that use non-HTTP protocols. If you want to monitor, intercept, and modify HTTP traffic, Burp Suite is probably the better option. \n\n## Author\n\nWritten by Kelby Ludwig ([@kelbyludwig](https://twitter.com/kelbyludwig))\n\n### Why I Built This\nI have done security research that involved sitting between a embedded device and a server and modifying some custom binary protocol on the fly. This usually is a slow process that involves sniffing legitimate traffic, and then rebuilding packets programmatically. Trudy enables Burp-like features for generalized TCP traffic.\n\n### Simple Setup\n\n0. Configure a virtual machine (Trudy has been tested on a 64-bit Debian 8 VM) to shove all traffic through Trudy. I personally use a Vagrant VM that sets this up for me. The Vagrant VM is available [here](https://github.com/praetorian-inc/mitm-vm). If you would like to use different `--to-ports` values, you can use Trudy's command line flags to change Trudy's listening ports.\n\n    `iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 8888 -m tcp -j REDIRECT --to-ports 8080`\n\n    `iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 443 -m tcp -j REDIRECT --to-ports 6443`\n\n    `iptables -t nat -A PREROUTING -i eth1 -p tcp -m tcp -j REDIRECT --to-ports 6666`\n\n    `ip route del 0/0`\n\n    `route add default gw 192.168.1.1 dev eth1`\n\n    `sysctl -w net.ipv4.ip_forward=1`\n\n1. Clone the repo on the virtual machine and build the Trudy binary.\n\n    `git clone https://github.com/kelbyludwig/trudy.git`\n\n    `cd trudy`\n\n    `go install`\n\n2. Run the Trudy binary as root. This starts the listeners. If you ran the `iptables` commands above, `iptables` will forward traffic destined for port 443 to port 6443. Trudy listens on this port and expects traffic coming into this port to be TLS. All other TCP connections will be forwarded through port 6666. \n\n    `sudo $GOPATH/bin/trudy`\n\n3. Setup your host machine to use the virtual machine as its router. You should see connections being made in Trudy's console but not notice any traffic issues on the host machine (except TLS errors).\n\n4. In order to manipulate data, just implement whatever functions you might need within the `module` package. The default implementations for these functions are hands-off, so if they do not make sense for your situation, feel free to leave them as they are. More detailed documentation is in the `module` package and the data flow is detailed below.\n\n\n5. To access the interceptor, visit `http://<IP ADDRESS OF VM>:8888/` in your web browser. The only gotcha here is you must visit the interceptor after starting Trudy but before Trudy receives a packet that it wants to intercept. \n\n## Data Flow\n\nModule methods are called in this order. Downward arrows indicate a branch if the `Do*` function returns true.\n\n```\nDeserialize -> Drop -> DoMangle ->  DoIntercept -> DoPrint -> Serialize -> BeforeWriteTo(Server|Client) -> AfterWriteTo(Server|Client)\n                         |         /                |        /\n                         |_> Mangle                 |_> PrettyPrint\n```\n"
  },
  {
    "path": "certificate/the-password-is-password",
    "content": ""
  },
  {
    "path": "certificate/trudy.cer",
    "content": "-----BEGIN CERTIFICAT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MdGQx\nEjAQBgNVBAMTCXRydWR5LmNvbTEqMCgGCSqGSIb3DQEJARYba2VsYnlsdWR3aWcr\ndHJ1ZHlAZ21haWwuY29tggkAiM031r1IUvMwDAYDVR0TBAUwAwEB/zANBgkqhkiG\n9w0BAQUFAAOCAQEAb5w7WDroTd+T1CgZ3/O1YVmon+0tjuPJGud7bh17ElYXkXt5\nBEDBI5LzkFls38bHxy4ZsKoizlEBuNJzLxW3tBTBeDE4kfJDqU52+1pBvSu9uEBH\nLX8gJ0R2FqxYRpmqXi1mORUFWxzbiqvipHTriS0BhM1vWAd5+hHwIXhU24oX5/XG\ncJ1DGeRAqAf8FS4nJ55YZVMSTCNDqmIOMtniRnYzfsVs7HuRrGruWshANjqg1X2l\nwP82E25KOs5JPQN61k+vfLw+XopqjJCT+yGpwHaJk21vhrEJCpPYuzcAjs4uzLPM\nwGBKg8VTkjnYyt/8zL6K6JSyba9ff08kYvjJwA==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "certificate/trudy.key",
    "content": "Bag Attributes\n    localKeyID: B4 DD 83 44 94 4D 94 7F 67 07 A7 D1 53 4E F6 19 B6 9D F4 67 \nKey Attributes: <No Attributes>\n-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAm8f/hkTqg7Y7PJtcEja9IkimoOc2ee+N889WXhEqi0iLC+4q\nGBZ0g2DZSf9/vJR8v1tmiOlRYRvx2o1HLCn6c0uU6Nqg4Cv4IryaJ9w1yfeH9vZH\nbH3YgWO7YU8VsAoDo58rL8oOFAWN4Gq7SPeyT51xqx0iwBEFYfG2AxaS86WWd4kJ\nPMpgqvQ7nJBNF5oWCsg617C2hyivC2K0K+6jW5PdVESMFPc5lM+THKG9CauwwfX5\nnaWVY0VOMtjBmyf+mzDwsZuTGUSNv/Cy55n5nOA9OCfgCLUFlyMc8QCoL8vpRoz5\nZzh2WdQo1TBJ66P2TMwQNXQ7HrtBSiUcY2xoAQIDAQABAoIBAEH+GKZVvY8sfK2x\n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uYTQqs1zbylYyYmSfXhl5mQlni8Yi8OKqQgi08LuGRKo1LF/w71ifz\nxoXsdkWm7kC08sc5eqTFqZF2rt/4f5VqxVF3tXsnDHCVdQlGwO0kZ38CgYEAwIVu\n68ygL8VD6+BEIumILzEHncTJ5Y2vnYOFmhveoJIiKjD+ywWaw7M0tODFU3h9oJ1c\na8D0uRXxfZrQFFVF1kAjAKBkif2xhwCVT+KARVaxNf73G4OKdRmK/ZbZCfxz/7Jh\nFYW2pIIF9HNXOLk3114CL+5HRvQlc1yAEZ2q8H8CgYApxo6ucb035FYBppOdSRDg\nLxlbT1rYjx6lDzKGorjMbRoZqB+MRZcmyQm32C0lQkJP30RGTwWTVXx8/sT/i1Ay\nN3CGZ54WC4gDSN4nUkR1gXNQjgT/RqVqNx4eKCPnTtNvVvBnpI1cikKWOAMkr9yN\nmMV8qy6P2rC5nrpPNEQwPwKBgQCv98Zg5NHtmALzEDN3Lbl6WPg7LmnT1eOUt2hg\naeTdI3Ty14GsE91Xzu73/RKfrtw0+GBHZUDKA9KNGfni++YvZMQZiIEc17NyUAgp\n0j+oIQss7XTzwxHE4qn2C/EpfYSRTHwMbgF48Bd9TgeFI1Z1FcouAT9JDVNF1GCC\nuXhLBQKBgQCJtnlqnnhpbuFiyIW9WVwBUf2ZbAzUv1TD3BRXvV/9sInFOYoMWIC4\n137loBp7Qll3OO52vu0x3jyygvS9YKDQ52hjF19+Zg3/cdvIPq4zNVHpQ6v1XEN6\nlGhlwAxNQ1A48+aD3fBuPUNnruY18ry3nkm29b2JpFvsJfrQFOCIVQ==\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "listener/listener.go",
    "content": "package listener\n\nimport (\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"net\"\n)\n\n//The TrudyListener interface is used to listen for incoming connections and accept them. This is almost\n//the same as the typical Listener interface, except a net.Conn must be returned for Accept. This enables\n//Trudy to grab the original destination IP address from the kernel.\ntype TrudyListener interface {\n\t//TODO: Listen should take two strings: \"tcp\" or \"udp\" and a port to listen on.\n\t//This parameter could create a Listener for both tcp and udp.\n\tListen(string, *net.TCPAddr, *tls.Config)\n\n\t//Accept returns a generic net.Conn and the file descriptor of the socket.\n\tAccept() (int, net.Conn, error)\n\n\t//Close shuts down the listener.\n\tClose() error\n}\n\n//The TCPListener struct implements the TrudyListener interface and handles TCP connections.\ntype TCPListener struct {\n\tListener *net.TCPListener\n}\n\nfunc (tl *TCPListener) Listen(nets string, tcpAddr *net.TCPAddr, _ *tls.Config) {\n\ttcpListener, err := net.ListenTCP(nets, tcpAddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttl.Listener = tcpListener\n}\n\nfunc (tl *TCPListener) Accept() (fd int, conn net.Conn, err error) {\n\tcpointer, err := tl.Listener.AcceptTCP()\n\tif err != nil {\n\t\treturn\n\t}\n\tfile, err := cpointer.File()\n\tif err != nil {\n\t\treturn\n\t}\n\tfd = int(file.Fd())\n\tconn, err = net.FileConn(file)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (tl *TCPListener) Close() error {\n\treturn tl.Listener.Close()\n}\n\n//TLSListener struct implements the TrudyListener interface and handles TCP connections over TLS.\ntype TLSListener struct {\n\tListener *net.TCPListener\n\tConfig   *tls.Config\n}\n\nfunc (tl *TLSListener) Accept() (fd int, conn net.Conn, err error) {\n\tcpointer, err := tl.Listener.AcceptTCP()\n\tif err != nil {\n\t\treturn\n\t}\n\tfile, err := cpointer.File()\n\tif err != nil {\n\t\treturn\n\t}\n\tfd = int(file.Fd())\n\tfconn, err := net.FileConn(file)\n\tif err != nil {\n\t\treturn\n\t}\n\tconn = tls.Server(fconn, tl.Config)\n\treturn\n}\n\nfunc (tl *TLSListener) Listen(nets string, laddr *net.TCPAddr, config *tls.Config) {\n\tif len(config.Certificates) == 0 {\n\t\tpanic(errors.New(\"tls.Listen: no certificates in configuration\"))\n\t}\n\ttcpListener, err := net.ListenTCP(nets, laddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttl.Listener = tcpListener\n\ttl.Config = config\n}\n\nfunc (tl *TLSListener) Close() error {\n\treturn tl.Listener.Close()\n}\n"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/hex\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/praetorian-inc/trudy/listener\"\n\t\"github.com/praetorian-inc/trudy/module\"\n\t\"github.com/praetorian-inc/trudy/pipe\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar connectionCount uint\nvar websocketConn *websocket.Conn\nvar websocketMutex *sync.Mutex\nvar tlsConfig *tls.Config\n\nfunc main() {\n\tvar tcpport string\n\tvar tlsport string\n\n\tvar x509 string\n\tvar key string\n\n\tvar showConnectionAttempts bool\n\n\tflag.StringVar(&tcpport, \"tcp\", \"6666\", \"Listening port for non-TLS connections.\")\n\tflag.StringVar(&tlsport, \"tls\", \"6443\", \"Listening port for TLS connections.\")\n\tflag.StringVar(&x509, \"x509\", \"./certificate/trudy.cer\", \"Path to x509 certificate that will be presented for TLS connection.\")\n\tflag.StringVar(&key, \"key\", \"./certificate/trudy.key\", \"Path to the corresponding private key for the specified x509 certificate\")\n\tflag.BoolVar(&showConnectionAttempts, \"show\", true, \"Show connection open and close messages\")\n\n\tflag.Parse()\n\n\ttcpport = \":\" + tcpport\n\ttlsport = \":\" + tlsport\n\tsetup(tcpport, tlsport, x509, key, showConnectionAttempts)\n}\n\nfunc setup(tcpport, tlsport, x509, key string, show bool) {\n\n\t//Setup non-TLS TCP listener!\n\ttcpAddr, err := net.ResolveTCPAddr(\"tcp\", tcpport)\n\tif err != nil {\n\t\tlog.Printf(\"There appears to be an error with the TCP port you specified. See error below.\\n%v\\n\", err.Error())\n\t\treturn\n\t}\n\ttcpListener := new(listener.TCPListener)\n\n\t//Setup TLS listener!\n\ttrdy, err := tls.LoadX509KeyPair(x509, key)\n\tif err != nil {\n\t\tlog.Printf(\"There appears to be an error with the x509 or key values specified. See error below.\\n%v\\n\", err.Error())\n\t\treturn\n\t}\n\ttlsConfig = &tls.Config{\n\t\tCertificates:       []tls.Certificate{trdy},\n\t\tInsecureSkipVerify: true,\n\t}\n\ttlsAddr, err := net.ResolveTCPAddr(\"tcp\", tlsport)\n\tif err != nil {\n\t\tlog.Printf(\"There appears to be an error with the TLS port specified. See error below.\\n%v\\n\", err.Error())\n\t\treturn\n\t}\n\ttlsListener := new(listener.TLSListener)\n\n\t//All good. Start listening.\n\ttcpListener.Listen(\"tcp\", tcpAddr, &tls.Config{})\n\ttlsListener.Listen(\"tcp\", tlsAddr, tlsConfig)\n\n\tlog.Println(\"[INFO] Trudy lives!\")\n\tlog.Printf(\"[INFO] Listening for TLS connections on port %s\\n\", tlsport)\n\tlog.Printf(\"[INFO] Listening for all other TCP connections on port %s\\n\", tcpport)\n\n\tgo websocketHandler()\n\tgo connectionDispatcher(tlsListener, \"TLS\", show)\n\tconnectionDispatcher(tcpListener, \"TCP\", show)\n\n}\n\nfunc connectionDispatcher(listener listener.TrudyListener, name string, show bool) {\n\tdefer listener.Close()\n\tfor {\n\t\tfd, conn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tp := new(pipe.TrudyPipe)\n\t\tif name == \"TLS\" {\n\t\t\terr = p.New(connectionCount, fd, conn, true)\n\t\t} else {\n\t\t\terr = p.New(connectionCount, fd, conn, false)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"[ERR] Error creating new pipe.\")\n\t\t\tcontinue\n\t\t}\n\t\tif show {\n\t\t\tlog.Printf(\"[INFO] ( %v ) %v Connection accepted!\\n\", connectionCount, name)\n\t\t}\n\t\tgo clientHandler(p, show)\n\t\tgo serverHandler(p)\n\t\tconnectionCount++\n\t}\n}\n\nfunc errHandler(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n//clientHandler manages data that is sent from the client to the server.\nfunc clientHandler(pipe pipe.Pipe, show bool) {\n\tif show {\n\t\tdefer log.Printf(\"[INFO] ( %v ) Closing TCP connection.\\n\", pipe.Id())\n\t}\n\tdefer pipe.Close()\n\n\tbuffer := make([]byte, 65535)\n\n\tfor {\n\t\tbytesRead, clientReadErr := pipe.ReadFromClient(buffer)\n\n\t\tif clientReadErr != io.EOF && clientReadErr != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif clientReadErr != io.EOF && bytesRead == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata := module.Data{FromClient: true,\n\t\t\tBytes:      buffer[:bytesRead],\n\t\t\tTLSConfig:  tlsConfig,\n\t\t\tServerAddr: pipe.ServerInfo(),\n\t\t\tClientAddr: pipe.ClientInfo()}\n\n\t\tdata.Deserialize()\n\n\t\tif data.Drop() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif data.DoMangle() {\n\t\t\tdata.Mangle()\n\t\t\tbytesRead = len(data.Bytes)\n\t\t}\n\n\t\tif data.DoIntercept() {\n\t\t\tif websocketConn == nil {\n\t\t\t\tlog.Printf(\"[ERR] Websocket Connection has not been setup yet! Cannot intercept.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twebsocketMutex.Lock()\n\t\t\tbs := fmt.Sprintf(\"% x\", data.Bytes)\n\t\t\tif err := websocketConn.WriteMessage(websocket.TextMessage, []byte(bs)); err != nil {\n\t\t\t\tlog.Printf(\"[ERR] Failed to write to websocket: %v\\n\", err)\n\t\t\t\twebsocketMutex.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t_, moddedBytes, err := websocketConn.ReadMessage()\n\t\t\twebsocketMutex.Unlock()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[ERR] Failed to read from websocket: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := string(moddedBytes)\n\t\t\tstr = strings.Replace(str, \" \", \"\", -1)\n\t\t\tmoddedBytes, err = hex.DecodeString(str)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[ERR] Failed to decode hexedited data.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdata.Bytes = moddedBytes\n\t\t\tbytesRead = len(moddedBytes)\n\t\t}\n\n\t\tif data.DoPrint() {\n\t\t\tlog.Printf(\"%v -> %v\\n%v\\n\", data.ClientAddr.String(), data.ServerAddr.String(), data.PrettyPrint())\n\t\t}\n\n\t\tdata.Serialize()\n\n\t\tdata.BeforeWriteToServer(pipe)\n\t\tbytesRead = len(data.Bytes)\n\n\t\t_, serverWriteErr := pipe.WriteToServer(data.Bytes[:bytesRead])\n\t\tif serverWriteErr != nil || clientReadErr == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\tdata.AfterWriteToServer(pipe)\n\t}\n}\n\n//serverHandler manages data that is sent from the server to the client.\nfunc serverHandler(pipe pipe.Pipe) {\n\tbuffer := make([]byte, 65535)\n\n\tdefer pipe.Close()\n\n\tfor {\n\t\tbytesRead, serverReadErr := pipe.ReadFromServer(buffer)\n\n\t\tif serverReadErr != io.EOF && serverReadErr != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif serverReadErr != io.EOF && bytesRead == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata := module.Data{FromClient: false,\n\t\t\tBytes:      buffer[:bytesRead],\n\t\t\tTLSConfig:  tlsConfig,\n\t\t\tClientAddr: pipe.ClientInfo(),\n\t\t\tServerAddr: pipe.ServerInfo()}\n\n\t\tdata.Deserialize()\n\n\t\tif data.Drop() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif data.DoMangle() {\n\t\t\tdata.Mangle()\n\t\t\tbytesRead = len(data.Bytes)\n\t\t}\n\n\t\tif data.DoIntercept() {\n\t\t\tif websocketConn == nil {\n\t\t\t\tlog.Printf(\"[ERR] Websocket Connection has not been setup yet! Cannot intercept.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twebsocketMutex.Lock()\n\t\t\tbs := fmt.Sprintf(\"% x\", data.Bytes)\n\t\t\tif err := websocketConn.WriteMessage(websocket.TextMessage, []byte(bs)); err != nil {\n\t\t\t\tlog.Printf(\"[ERR] Failed to write to websocket: %v\\n\", err)\n\t\t\t\twebsocketMutex.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t_, moddedBytes, err := websocketConn.ReadMessage()\n\t\t\twebsocketMutex.Unlock()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[ERR] Failed to read from websocket: %v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := string(moddedBytes)\n\t\t\tstr = strings.Replace(str, \" \", \"\", -1)\n\t\t\tmoddedBytes, err = hex.DecodeString(str)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[ERR] Failed to decode hexedited data.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdata.Bytes = moddedBytes\n\t\t\tbytesRead = len(moddedBytes)\n\t\t}\n\n\t\tif data.DoPrint() {\n\t\t\tlog.Printf(\"%v -> %v\\n%v\\n\", data.ServerAddr.String(), data.ClientAddr.String(), data.PrettyPrint())\n\t\t}\n\n\t\tdata.Serialize()\n\n\t\tdata.BeforeWriteToClient(pipe)\n\t\tbytesRead = len(data.Bytes)\n\n\t\t_, clientWriteErr := pipe.WriteToClient(data.Bytes[:bytesRead])\n\t\tif clientWriteErr != nil || serverReadErr == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\tdata.AfterWriteToClient(pipe)\n\t}\n}\n\nfunc websocketHandler() {\n\twebsocketMutex = &sync.Mutex{}\n\tupgrader := websocket.Upgrader{ReadBufferSize: 65535, WriteBufferSize: 65535}\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tio.WriteString(w, editor)\n\t})\n\thttp.HandleFunc(\"/ws\", func(w http.ResponseWriter, r *http.Request) {\n\t\tvar err error\n\t\twebsocketConn, err = upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ERR] Could not upgrade websocket connection.\")\n\t\t\treturn\n\t\t}\n\t})\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nconst editor string = `<!-- this wonderful page was found here: https://github.com/xem/hex -->\n<body onload='\n// Reset the textarea value\nm.value=\"00\";\n\n// Init the top cell content\nfor(i=0;i<16;i++)\n  t.innerHTML+=(0+i.toString(16)).slice(-2)+\" \";\n'>\n\n<!-- TRUDY SPECIFIC CODE ADDED FOR THIS PROJECT -->\n<h1> ~ Trudy Intercept ~ </h1>\n<script>\n    var url = window.location.href\n    var arr = url.split(\"/\");\n    var ws_url = \"ws://\" + arr[2] + \"/ws\"\n    var socket = new WebSocket(ws_url)\n    socket.onmessage = function (event) {\n\tdocument.getElementById('m').value = event.data\n\tdocument.getElementById('m').oninput()\n\tdocument.getElementById('send').disabled = false\n    }\n    var sender = function() {\n        socket.send(document.getElementById('m').value)\n\tdocument.getElementById('send').disabled = true\n        document.getElementById('m').value = \"00\"\n        document.getElementById('m').oninput()\n    }\n</script>\n<button onclick=\"sender()\" id='send' disabled=true>send</button>\n<!-- END TRUDY SPECIFIC CODE -->\n</body>\n<table border><td><pre><td id=t><tr><td id=l width=80>00000000<td><textarea spellcheck=false id=m oninput='\n// On input, store the length of clean hex before the textarea caret in b\nb=value\n.substr(0,selectionStart)\n.replace(/[^0-9A-F]/ig,\"\")\n.replace(/(..)/g,\"$1 \")\n.length;\n\n// Clean the textarea value\nvalue=value\n.replace(/[^0-9A-F]/ig,\"\")\n.replace(/(..)/g,\"$1 \")\n.replace(/ $/,\"\")\n.toUpperCase();\n\n// Set the height of the textarea according to its length\nstyle.height=(1.5+value.length/47)+\"em\";\n\n// Reset h\nh=\"\";\n\n// Loop on textarea lines\nfor(i=0;i<value.length/48;i++)\n  \n  // Add line number to h\n  h+=(1E7+(16*i).toString(16)).slice(-8)+\" \";\n\n// Write h on the left column\nl.innerHTML=h;\n\n// Reset h\nh=\"\";\n\n// Loop on the hex values\nfor(i=0;i<value.length;i+=3)\n  \n  // Convert them in numbers\n  c=parseInt(value.substr(i,2),16),\n  \n  // Convert in chars (if the charCode is in [64-126] (maybe more later)) or \".\".\n  h=63<c&&127>c?h+String.fromCharCode(c):h+\".\";\n  \n// Write h in the right column (with line breaks every 16 chars)\nr.innerHTML=h.replace(/(.{16})/g,\"$1 \");\n\n// If the caret position is after a space or a line break, place it at the previous index so we can use backspace to erase hex code\nif(value[b]==\" \")\n  b--;\n\n// Put the textarea caret at the right place\nsetSelectionRange(b,b)'\ncols=48></textarea><td width=160 id=r>.</td>\n</table>\n<style>\n*{margin:0;padding:0;vertical-align:top;font:1em/1em courier}\n#m{height:1.5em;resize:none;overflow:hidden}\n#t{padding:0 2px}\n#w{position:absolute;opacity:.001}\n</style>\n`\n"
  },
  {
    "path": "module/module.go",
    "content": "package module\n\nimport (\n\t\"crypto/tls\"\n\t\"encoding/hex\"\n\t\"github.com/praetorian-inc/trudy/pipe\"\n\t\"net\"\n)\n\n//Data is a thin wrapper that provides metadata that may be useful when mangling bytes on the network.\ntype Data struct {\n\tFromClient bool        //FromClient is true is the data sent is coming from the client (the device you are proxying)\n\tBytes      []byte      //Bytes is a byte slice that contians the TCP data\n\tTLSConfig  *tls.Config //TLSConfig is a TLS server config that contains Trudy's TLS server certficiate.\n\tServerAddr net.Addr    //ServerAddr is net.Addr of the server\n\tClientAddr net.Addr    //ClientAddr is the net.Addr of the client (the device you are proxying)\n}\n\n//DoMangle will return true if Data needs to be sent to the Mangle function.\nfunc (input Data) DoMangle() bool {\n\treturn true\n}\n\n//Mangle can modify/replace the Bytes values within the Data struct. This can\n//be empty if no programmatic mangling needs to be done.\nfunc (input *Data) Mangle() {\n\n}\n\n//Drop will return true if the Data needs to be dropped before going through\n//the pipe.\nfunc (input Data) Drop() bool {\n\treturn false\n}\n\n//PrettyPrint returns the string representation of the data. This string will\n//be the value that is logged to the console.\nfunc (input Data) PrettyPrint() string {\n\treturn hex.Dump(input.Bytes)\n}\n\n//DoPrint will return true if the PrettyPrinted version of the Data struct\n//needs to be logged to the console.\nfunc (input Data) DoPrint() bool {\n\treturn true\n}\n\n//DoIntercept returns true if data should be sent to the Trudy interceptor.\nfunc (input Data) DoIntercept() bool {\n\treturn false\n}\n\n//Deserialize should replace the Data struct's Bytes with a deserialized bytes.\n//For example, unpacking a HTTP/2 frame would be deserialization.\nfunc (input *Data) Deserialize() {\n\n}\n\n//Serialize should replace the Data struct's Bytes with the serialized form of\n//the bytes. The serialized bytes will be sent over the wire.\nfunc (input *Data) Serialize() {\n\n}\n\n//BeforeWriteToClient is a function that will be called before data is sent to\n//a client.\nfunc (input *Data) BeforeWriteToClient(p pipe.Pipe) {\n\n}\n\n//AfterWriteToClient is a function that will be called after data is sent to\n//a client.\nfunc (input *Data) AfterWriteToClient(p pipe.Pipe) {\n\n}\n\n//BeforeWriteToServer is a function that will be called before data is sent to\n//a server.\nfunc (input *Data) BeforeWriteToServer(p pipe.Pipe) {\n\n}\n\n//AfterWriteToServer is a function that will be called after data is sent to\n//a server.\nfunc (input *Data) AfterWriteToServer(p pipe.Pipe) {\n\n}\n"
  },
  {
    "path": "module/xmpp.go.trudy",
    "content": "package module\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"encoding/hex\"\n\t\"github.com/praetorian-inc/trudy/pipe\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n)\n\n//Data is a wrapper that provides metadata that may be useful when mangling bytes on the network.\ntype Data struct {\n\tFromClient bool        //FromClient is true is the data sent is coming from the client (the device you are proxying)\n\tBytes      []byte      //Bytes is a byte slice that contians the TCP data\n\tTLSConfig  *tls.Config //TLSConfig is a TLS server config that contains Trudy's TLS server certficiate.\n\tServerAddr net.Addr    //ServerAddr is net.Addr of the server\n\tClientAddr net.Addr    //ClientAddr is the net.Addr of the client (the device you are proxying)\n}\n\nvar startTLSElementSingle string = \"<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\"\nvar startTLSElementDouble string = \"<starttls xmlns=\\\"urn:ietf:params:xml:ns:xmpp-tls\\\"/>\"\nvar proceedElementDouble string = \"<proceed xmlns=\\\"urn:ietf:params:xml:ns:xmpp-tls\\\"/>\"\nvar proceedElementSingle string = \"<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\"\n\n//DoPrint will return true if the PrettyPrinted version of the Data struct\n//needs to be logged to the console.\nfunc (input Data) DoPrint() bool {\n\t//Only print client/server data sent over XMPP Ports.\n\treturn strings.Contains(input.ServerAddr.String(), \":5225\") || strings.Contains(input.ClientAddr.String(), \":5225\")\n}\n\n//AfterWriteToServer is a function that will be called after data is sent to\n//a server.\nfunc (input *Data) AfterWriteToServer(p pipe.Pipe) {\n\n\tif bytes.Contains(input.Bytes, []byte(startTLSElementDouble)) ||\n\t\tbytes.Contains(input.Bytes, []byte(startTLSElementSingle)) {\n\t\t//The client has sent StartTLS response to the server's StartTLS\n\t\t//request. Trudy will now handle that upgrade.\n\n\t\tlog.Printf(\"[INFO] ( %v ) Upgrading client-side connection.\\n\", p.Id())\n\n\t\t//Upgrade the connection and prepare for a ClientHandshake\n\t\ttlsConn := tls.Server(p.ClientConn(), input.TLSConfig)\n\n\t\t//Tell the client to proceed. We will drop the server's real proceed.\n\t\tp.WriteToClient([]byte(proceedElementDouble))\n\t\tlog.Printf(\"[INFO] ( %v ) Sent client a proceed. Now locking own goroutine to allow server-side upgrade.\\n\", p.Id())\n\n\t\t//Lock this pipe until the server-side TLS upgrade has completed.\n\t\tp.Lock() //TODO(kkl): This is kinda hacky. I think a chan will be better here.\n\t\tp.Lock()\n\n\t\t//Once this code has been reached, the server-side TLS\n\t\t//connection has been upgraded. The client-side can now proceed\n\t\t//with a TLS upgrade.\n\t\terr := tlsConn.Handshake()\n\t\tif err != nil {\n\t\t\tp.Close()\n\t\t\treturn\n\t\t}\n\t\t//Update the client-side connection with the new TLS connection\n\t\t//and unlock the pipe.\n\t\tp.SetClientConn(tlsConn)\n\t\tp.Unlock()\n\t\tlog.Printf(\"[INFO] ( %v ) Upgraded client-side connection.\\n\", p.Id())\n\t}\n}\n\n//BeforeWriteToClient is a function that will be called before data is sent to\n//a client.\nfunc (input *Data) BeforeWriteToClient(p pipe.Pipe) {\n\n\tif bytes.Contains(input.Bytes, []byte(proceedElementDouble)) ||\n\t\tbytes.Contains(input.Bytes, []byte(proceedElementSingle)) {\n\n\t\t//We have recieved a proceed from the server. Trudy will\n\t\t//now upgrade the server-side connection.\n\n\t\tlog.Printf(\"[INFO] ( %v ) Upgrading server-side connection.\\n\", p.Id())\n\t\ttlsConfig := tls.Config{InsecureSkipVerify: true}\n\t\ttlsConn := tls.Client(p.ServerConn(), &tlsConfig)\n\t\tp.SetServerConn(tlsConn)\n\n\t\t//Lets drop the proceed message so its not sent to the client. (Since Trudy already sent one)\n\t\tlog.Printf(\"[INFO] ( %v ) Dropping the server's proceed.\\n\", p.Id())\n\t\tinput.Bytes = []byte{}\n\t\tp.Unlock()\n\t\tlog.Printf(\"[INFO] ( %v ) Upgraded server-side connection.\\n\", p.Id())\n\t}\n\n}\n\n//\n//\n// Unmodified module methods. All methods past this point are using the default implementation.\n//\n//\n\n//DoIntercept returns true if data should be sent to the Trudy interceptor.\nfunc (input Data) DoIntercept() bool {\n\treturn false\n}\n\n//Mangle can modify/replace the Bytes values within the Data struct. This can\n//be empty if no programmatic mangling needs to be done.\nfunc (input *Data) Mangle() {\n\n}\n\n//PrettyPrint returns the string representation of the data. This string will\n//be the value that is logged to the console.\nfunc (input Data) PrettyPrint() string {\n\treturn hex.Dump(input.Bytes)\n}\n\n//Deserialize should replace the Data struct's Bytes with a deserialized bytes.\n//For example, unpacking a HTTP/2 frame would be deserialization.\nfunc (input *Data) Deserialize() {\n\n}\n\n//Serialize should replace the Data struct's Bytes with the serialized form of\n//the bytes. The serialized bytes will be sent over the wire.\nfunc (input *Data) Serialize() {\n\n}\n\n//DoMangle will return true if Data needs to be sent to the Mangle function.\nfunc (input Data) DoMangle() bool {\n\treturn false\n}\n\n//Drop will return true if the Data needs to be dropped before going through\n//the pipe.\nfunc (input Data) Drop() bool {\n\treturn false\n}\n\n//AfterWriteToClient is a function that will be called after data is sent to\n//a client.\nfunc (input *Data) AfterWriteToClient(p pipe.Pipe) {\n\n}\n\n//BeforeWriteToServer is a function that will be called before data is sent to\n//a server.\nfunc (input *Data) BeforeWriteToServer(p pipe.Pipe) {\n\n}\n"
  },
  {
    "path": "pipe/pipe.go",
    "content": "//Package pipe defines the data structure used to manipulate, monitor, and create proxied connections.\npackage pipe\n\nimport (\n\t\"crypto/tls\"\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\n//Netfilter/iptables adds a tcp header to identify original destination.\n//Since all traffic is routed through trudy, we need to retrieve the original\n//intended destination (i.e. _not_ trudy)\nconst SO_ORIGINAL_DST = 80\n\n//Pipe is the primary interface that handles connections. Pipe creates a\n//full-duplex pipe that passes data from the client to the server and vice\n//versa. A pipe is compromised of two connections. The client transparently\n//connects to Trudy, and Trudy accepts the connection.  Trudy will then make a\n//connection with the client's intended destination and just pass traffic\n//back-and-forth between the two connections. All modifications and drops to\n//the packet happen to data between the two ends of the pipe.\ntype Pipe interface {\n\n\t//Id returns a unique Pipe identifier\n\tId() uint\n\n\t//ServerInfo returns the net.Addr of the server-end of the pipe.\n\tServerInfo() (addr net.Addr)\n\n\t//ClientInfo returns the net.Addr of the client-end of the pipe.\n\tClientInfo() (addr net.Addr)\n\n\t//ReadFromClient reads data into the buffer from the client-end of the\n\t//pipe. ReadFromClient returns the number of bytes read and an error\n\t//value if an error or EOF occurred. Note: ReadFromClient can read a\n\t//non-zero number of bytes and have a non-nil error value (e.g. EOF).\n\tReadFromClient(buffer []byte) (n int, err error)\n\n\t//WriteToClient writes data to the client-end of the pipe. This is\n\t//typically the proxy-unaware client.\n\tWriteToClient(buffer []byte) (n int, err error)\n\n\t//ReadFromServer reads data into the buffer from the server-end of the\n\t//pipe. The server is the proxy-unaware client's intended destination.\n\t//ReadFromServer returns the number of bytes read and an error value if\n\t//an error or EOF occurred. Note: ReadFromServer can read a non-zero\n\t//number of bytes and have a non-nil error value (e.g. EOF).\n\tReadFromServer(buffer []byte) (n int, err error)\n\n\t//WriteToServer writes buffer to the server-end of the pipe. The server\n\t//is the proxy-unaware client's intended destination.\n\tWriteToServer(buffer []byte) (n int, err error)\n\n\t//ServerConn returns the net.Conn responsible for server-end\n\t//communication.\n\tServerConn() (conn net.Conn)\n\n\t//CilentConn returns the net.Conn responsible for client-end\n\t//communication.\n\tClientConn() (conn net.Conn)\n\n\t//SetServerConn will replace the server-end of the pipe with the supplied\n\t//net.Conn parameter.\n\tSetServerConn(conn net.Conn)\n\n\t//SetClientConn will replace the client-end of the pipe with the supplied\n\t//net.Conn parameter.\n\tSetClientConn(conn net.Conn)\n\n\t//New builds a new Pipe.\n\tNew(pipeID uint, clientConnFD int, clientConn net.Conn, useTLS bool) (err error)\n\n\t//Close closes both connections of the Pipe.\n\tClose()\n\n\t//Lock locks a per-Pipe mutex that can be used in modules for\n\t//synchronization.\n\tLock()\n\n\t//Unlock unlocks a per-Pipe mutex that can be used in modules for\n\t//synchronization.\n\tUnlock()\n\n\t//AddContext adds a key/value pair to the Pipe.\n\tAddContext(key string, value interface{})\n\n\t//GetContext retrieves a value in a Pipe key/value data store.\n\t//GetContext returns the value and a bool indicating success.\n\tGetContext(key string) (value interface{}, ok bool)\n\n\t//DeleteContext removes a key/value pair from the Pipe.\n\tDeleteContext(key string)\n}\n\n//TODO(kkl): I don't think New needs to be part of the Pipe interface.\n//Removing this very specific constructor will allow for other methods\n//of getting trudy as a proxy (e.g. other transparent proxies, or\n//non-transparent proxies like SOCKS).\n\n//TrudyPipe implements the Pipe interface and can be used to proxy TCP connections.\ntype TrudyPipe struct {\n\tid         uint\n\tserverConn net.Conn\n\tclientConn net.Conn\n\tpipeMutex  *sync.Mutex\n\tuserMutex  *sync.Mutex\n\tKV         map[string]interface{}\n}\n\n//Lock locks a mutex stored within TrudyPipe to allow for fine-grained\n//synchronization within a module.\nfunc (t *TrudyPipe) Lock() {\n\tt.userMutex.Lock()\n}\n\n//Unlock unlocks a mutex stored within TrudyPipe to allow for fine-grained\n//synchronization within a module.\nfunc (t *TrudyPipe) Unlock() {\n\tt.userMutex.Unlock()\n}\n\n//AddContext adds a key/value pair to the TrudyPipe. The key/value\n//pair data store is per-TrudyPipe. AddContext is safe for use\n//in multiple goroutines.\nfunc (t *TrudyPipe) AddContext(key string, value interface{}) {\n\tt.pipeMutex.Lock()\n\tt.KV[key] = value\n\tt.pipeMutex.Unlock()\n}\n\n//GetContext retrieves a value in a TrudyPipe key/value data store.\n//GetContext returns the value and a bool indicating success.\nfunc (t *TrudyPipe) GetContext(key string) (retval interface{}, ok bool) {\n\tretval, ok = t.KV[key]\n\treturn\n}\n\n//DeleteContext removes a key/value pair from the TrudyPipe. DeleteContext is\n//safe for use in multiple goroutines.\nfunc (t *TrudyPipe) DeleteContext(key string) {\n\tt.pipeMutex.Lock()\n\tdelete(t.KV, key)\n\tt.pipeMutex.Unlock()\n}\n\n//CilentConn returns the net.Conn responsible for client-end communication.\nfunc (t *TrudyPipe) ClientConn() net.Conn {\n\treturn t.clientConn\n}\n\n//ServerConn returns the net.Conn responsible for server-end communication.\nfunc (t *TrudyPipe) ServerConn() net.Conn {\n\treturn t.serverConn\n}\n\n//SetClientConn will replace the client-end of the pipe with the supplied\n//net.Conn parameter. SetClientConn is safe for use in multiple goroutines.\nfunc (t *TrudyPipe) SetClientConn(c net.Conn) {\n\tt.pipeMutex.Lock()\n\tt.clientConn = c\n\tt.pipeMutex.Unlock()\n}\n\n//SetServerConn will replace the server-end of the pipe with the supplied\n//net.Conn parameter. SetServerConn is safe for use in multiple goroutines.\nfunc (t *TrudyPipe) SetServerConn(s net.Conn) {\n\tt.pipeMutex.Lock()\n\tt.serverConn = s\n\tt.pipeMutex.Unlock()\n}\n\n//Id returns a TrudyPipe identifier\nfunc (t *TrudyPipe) Id() uint {\n\treturn t.id\n}\n\n//ServerInfo returns the net.Addr of the server.\nfunc (t *TrudyPipe) ServerInfo() (addr net.Addr) {\n\taddr = t.serverConn.RemoteAddr()\n\treturn\n}\n\n//ClientInfo returns the net.Addr of the client.\nfunc (t *TrudyPipe) ClientInfo() (addr net.Addr) {\n\taddr = t.clientConn.RemoteAddr()\n\treturn\n}\n\n//Close closes both ends of a TrudyPipe.\nfunc (t *TrudyPipe) Close() {\n\tt.serverConn.Close()\n\tt.clientConn.Close()\n}\n\n//ReadFromClient reads data from the client end of the pipe. This is typically the proxy-unaware client.\nfunc (t *TrudyPipe) ReadFromClient(buffer []byte) (n int, err error) {\n\t//TODO(kkl): Make timeouts configureable.\n\terr = t.clientConn.SetReadDeadline(time.Now().Add(15 * time.Second))\n\tif err != nil {\n\t\treturn\n\t}\n\tn, err = t.clientConn.Read(buffer)\n\treturn\n}\n\n//WriteToClient writes data to the client end of the pipe. This is typically the proxy-unaware client.\nfunc (t *TrudyPipe) WriteToClient(buffer []byte) (n int, err error) {\n\t//TODO(kkl): Make timeouts configureable.\n\terr = t.clientConn.SetWriteDeadline(time.Now().Add(15 * time.Second))\n\tif err != nil {\n\t\treturn\n\t}\n\tn, err = t.clientConn.Write(buffer)\n\treturn\n}\n\n//ReadFromServer reads data from the server end of the pipe. The server is the\n//proxy-unaware client's intended destination.\nfunc (t *TrudyPipe) ReadFromServer(buffer []byte) (n int, err error) {\n\tt.serverConn.SetReadDeadline(time.Now().Add(15 * time.Second))\n\treturn t.serverConn.Read(buffer)\n}\n\n//WriteToServer writes data to the server end of the pipe. The server is the\n//proxy-unaware client's intended destination.\nfunc (t *TrudyPipe) WriteToServer(buffer []byte) (n int, err error) {\n\terr = t.serverConn.SetWriteDeadline(time.Now().Add(15 * time.Second))\n\tif err != nil {\n\t\treturn\n\t}\n\tn, err = t.serverConn.Write(buffer)\n\treturn\n}\n\n//byteToConnString converts the Multiaddr bytestring returned by Getsockopt into a \"host:port\" connection string.\nfunc byteToConnString(multiaddr [16]byte) string {\n\tip := multiaddr[4:8]\n\tipString := net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()\n\tport := multiaddr[2:4]\n\tportUint := int64((uint32(port[0]) << 8) + uint32(port[1]))\n\tportString := strconv.FormatInt(portUint, 10)\n\treturn (ipString + \":\" + portString)\n}\n\n//New builds a new TrudyPipe. New will get the original destination of traffic\n//that was mangled by iptables and get the original destination. New will then\n//open a connection to that original destination and, upon success, will set\n//all the internal values needed for a TrudyPipe.\nfunc (t *TrudyPipe) New(id uint, fd int, clientConn net.Conn, useTLS bool) (err error) {\n\t//TODO(kkl): Make the second argument system-dependent. E.g. If a linux machine: syscall.SOL_IP\n\toriginalAddrBytes, err := syscall.GetsockoptIPv6Mreq(fd, syscall.IPPROTO_IP, SO_ORIGINAL_DST)\n\tif err != nil {\n\t\tlog.Println(\"[DEBUG] Getsockopt failed.\")\n\t\tclientConn.Close()\n\t\treturn err\n\t}\n\n\tvar serverConn net.Conn\n\tif useTLS {\n\t\ttlsconfig := &tls.Config{InsecureSkipVerify: true}\n\t\tserverConn, err = tls.Dial(\"tcp\", byteToConnString(originalAddrBytes.Multiaddr), tlsconfig)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ERR] Unable to connect to destination. Closing connection %v.\\n\", id)\n\t\t\tclientConn.Close()\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tserverConn, err = net.Dial(\"tcp\", byteToConnString(originalAddrBytes.Multiaddr))\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ERR] ( %v ) Unable to connect to destination. Closing pipe.\\n\", id)\n\t\t\tclientConn.Close()\n\t\t\treturn err\n\t\t}\n\t}\n\tt.id = id\n\tt.clientConn = clientConn\n\tt.serverConn = serverConn\n\tt.pipeMutex = new(sync.Mutex)\n\tt.userMutex = new(sync.Mutex)\n\treturn nil\n}\n"
  }
]