Repository: praetorian-inc/trudy Branch: master Commit: 619d25bba282 Files: 13 Total size: 55.8 KB Directory structure: gitextract_pxbzavi7/ ├── .gitignore ├── LICENSE ├── README.md ├── certificate/ │ ├── the-password-is-password │ ├── trudy.cer │ ├── trudy.key │ ├── trudy.pem │ └── trudy.pfx ├── listener/ │ └── listener.go ├── main.go ├── module/ │ ├── module.go │ └── xmpp.go.trudy └── pipe/ └── pipe.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ ## Trudy Trudy 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. Trudy can also proxy TLS connections. Obviously, you will need a valid certificate or a client that does not validate certificates. Trudy 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. ## Author Written by Kelby Ludwig ([@kelbyludwig](https://twitter.com/kelbyludwig)) ### Why I Built This I 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. ### Simple Setup 0. 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. `iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 8888 -m tcp -j REDIRECT --to-ports 8080` `iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 443 -m tcp -j REDIRECT --to-ports 6443` `iptables -t nat -A PREROUTING -i eth1 -p tcp -m tcp -j REDIRECT --to-ports 6666` `ip route del 0/0` `route add default gw 192.168.1.1 dev eth1` `sysctl -w net.ipv4.ip_forward=1` 1. Clone the repo on the virtual machine and build the Trudy binary. `git clone https://github.com/kelbyludwig/trudy.git` `cd trudy` `go install` 2. 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. `sudo $GOPATH/bin/trudy` 3. 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). 4. 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. 5. To access the interceptor, visit `http://: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. ## Data Flow Module methods are called in this order. Downward arrows indicate a branch if the `Do*` function returns true. ``` Deserialize -> Drop -> DoMangle -> DoIntercept -> DoPrint -> Serialize -> BeforeWriteTo(Server|Client) -> AfterWriteTo(Server|Client) | / | / |_> Mangle |_> PrettyPrint ``` ================================================ FILE: certificate/the-password-is-password ================================================ ================================================ FILE: certificate/trudy.cer ================================================ -----BEGIN CERTIFICATE----- MIIEaDCCA1CgAwIBAgIJAIjNN9a9SFLzMA0GCSqGSIb3DQEBBQUAMH8xCzAJBgNV BAYTAlVTMQswCQYDVQQIEwJUWDEPMA0GA1UEBxMGQXVzdGluMRIwEAYDVQQKEwlU cnVkeSBMdGQxEjAQBgNVBAMTCXRydWR5LmNvbTEqMCgGCSqGSIb3DQEJARYba2Vs YnlsdWR3aWcrdHJ1ZHlAZ21haWwuY29tMB4XDTE1MTIwMTE3MTQwMloXDTE2MTEz MDE3MTQwMlowfzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlRYMQ8wDQYDVQQHEwZB dXN0aW4xEjAQBgNVBAoTCVRydWR5IEx0ZDESMBAGA1UEAxMJdHJ1ZHkuY29tMSow KAYJKoZIhvcNAQkBFhtrZWxieWx1ZHdpZyt0cnVkeUBnbWFpbC5jb20wggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCbx/+GROqDtjs8m1wSNr0iSKag5zZ5 743zz1ZeESqLSIsL7ioYFnSDYNlJ/3+8lHy/W2aI6VFhG/HajUcsKfpzS5To2qDg K/givJon3DXJ94f29kdsfdiBY7thTxWwCgOjnysvyg4UBY3gartI97JPnXGrHSLA EQVh8bYDFpLzpZZ3iQk8ymCq9DuckE0XmhYKyDrXsLaHKK8LYrQr7qNbk91URIwU 9zmUz5Mcob0Jq7DB9fmdpZVjRU4y2MGbJ/6bMPCxm5MZRI2/8LLnmfmc4D04J+AI tQWXIxzxAKgvy+lGjPlnOHZZ1CjVMEnro/ZMzBA1dDseu0FKJRxjbGgBAgMBAAGj geYwgeMwHQYDVR0OBBYEFKylOC1OlwYtFAHBQTfGIzCC/32PMIGzBgNVHSMEgasw gaiAFKylOC1OlwYtFAHBQTfGIzCC/32PoYGEpIGBMH8xCzAJBgNVBAYTAlVTMQsw CQYDVQQIEwJUWDEPMA0GA1UEBxMGQXVzdGluMRIwEAYDVQQKEwlUcnVkeSBMdGQx EjAQBgNVBAMTCXRydWR5LmNvbTEqMCgGCSqGSIb3DQEJARYba2VsYnlsdWR3aWcr dHJ1ZHlAZ21haWwuY29tggkAiM031r1IUvMwDAYDVR0TBAUwAwEB/zANBgkqhkiG 9w0BAQUFAAOCAQEAb5w7WDroTd+T1CgZ3/O1YVmon+0tjuPJGud7bh17ElYXkXt5 BEDBI5LzkFls38bHxy4ZsKoizlEBuNJzLxW3tBTBeDE4kfJDqU52+1pBvSu9uEBH LX8gJ0R2FqxYRpmqXi1mORUFWxzbiqvipHTriS0BhM1vWAd5+hHwIXhU24oX5/XG cJ1DGeRAqAf8FS4nJ55YZVMSTCNDqmIOMtniRnYzfsVs7HuRrGruWshANjqg1X2l wP82E25KOs5JPQN61k+vfLw+XopqjJCT+yGpwHaJk21vhrEJCpPYuzcAjs4uzLPM wGBKg8VTkjnYyt/8zL6K6JSyba9ff08kYvjJwA== -----END CERTIFICATE----- ================================================ FILE: certificate/trudy.key ================================================ Bag Attributes localKeyID: B4 DD 83 44 94 4D 94 7F 67 07 A7 D1 53 4E F6 19 B6 9D F4 67 Key Attributes: -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAm8f/hkTqg7Y7PJtcEja9IkimoOc2ee+N889WXhEqi0iLC+4q GBZ0g2DZSf9/vJR8v1tmiOlRYRvx2o1HLCn6c0uU6Nqg4Cv4IryaJ9w1yfeH9vZH bH3YgWO7YU8VsAoDo58rL8oOFAWN4Gq7SPeyT51xqx0iwBEFYfG2AxaS86WWd4kJ PMpgqvQ7nJBNF5oWCsg617C2hyivC2K0K+6jW5PdVESMFPc5lM+THKG9CauwwfX5 naWVY0VOMtjBmyf+mzDwsZuTGUSNv/Cy55n5nOA9OCfgCLUFlyMc8QCoL8vpRoz5 Zzh2WdQo1TBJ66P2TMwQNXQ7HrtBSiUcY2xoAQIDAQABAoIBAEH+GKZVvY8sfK2x FvD0VW0Xn9cb+7zuGZGGbQ0OcppskdLtAtIPeS5KseIiJYfK04nw+1/Wj033G569 KMBxzBJZm2yFaY9tsQFuKlPmerbjcKrTK/Cu4y/1AuU3LnXT2DTRcecdzpb2v2Kp dEt1+wi1JvkZL6Zzz3btgXCPeJNUEjlan+FPYwI4mzMp2MyTEAvPXojLLcf+anyA 0qelff0Siz1qZS2/6USjZ2+HnF7cAbmSyNEv6SMubE7P065Ok2I9R3SjqnelXGnW ZC0FY2p6zNdi3zOHyUltZAQ2e9Lq7Ghn7OL4xor9+qXJb4Y2kzMNIuopOkBWc1HT C6+C4c0CgYEAzyVfI/nzSWtSVlu3on/qfGMfIkcMafKetofExDF/BlTsgpcQEIZB NAxUFBpcavuYTQqs1zbylYyYmSfXhl5mQlni8Yi8OKqQgi08LuGRKo1LF/w71ifz xoXsdkWm7kC08sc5eqTFqZF2rt/4f5VqxVF3tXsnDHCVdQlGwO0kZ38CgYEAwIVu 68ygL8VD6+BEIumILzEHncTJ5Y2vnYOFmhveoJIiKjD+ywWaw7M0tODFU3h9oJ1c a8D0uRXxfZrQFFVF1kAjAKBkif2xhwCVT+KARVaxNf73G4OKdRmK/ZbZCfxz/7Jh FYW2pIIF9HNXOLk3114CL+5HRvQlc1yAEZ2q8H8CgYApxo6ucb035FYBppOdSRDg LxlbT1rYjx6lDzKGorjMbRoZqB+MRZcmyQm32C0lQkJP30RGTwWTVXx8/sT/i1Ay N3CGZ54WC4gDSN4nUkR1gXNQjgT/RqVqNx4eKCPnTtNvVvBnpI1cikKWOAMkr9yN mMV8qy6P2rC5nrpPNEQwPwKBgQCv98Zg5NHtmALzEDN3Lbl6WPg7LmnT1eOUt2hg aeTdI3Ty14GsE91Xzu73/RKfrtw0+GBHZUDKA9KNGfni++YvZMQZiIEc17NyUAgp 0j+oIQss7XTzwxHE4qn2C/EpfYSRTHwMbgF48Bd9TgeFI1Z1FcouAT9JDVNF1GCC uXhLBQKBgQCJtnlqnnhpbuFiyIW9WVwBUf2ZbAzUv1TD3BRXvV/9sInFOYoMWIC4 137loBp7Qll3OO52vu0x3jyygvS9YKDQ52hjF19+Zg3/cdvIPq4zNVHpQ6v1XEN6 lGhlwAxNQ1A48+aD3fBuPUNnruY18ry3nkm29b2JpFvsJfrQFOCIVQ== -----END RSA PRIVATE KEY----- ================================================ FILE: certificate/trudy.pem ================================================ -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAm8f/hkTqg7Y7PJtcEja9IkimoOc2ee+N889WXhEqi0iLC+4q GBZ0g2DZSf9/vJR8v1tmiOlRYRvx2o1HLCn6c0uU6Nqg4Cv4IryaJ9w1yfeH9vZH bH3YgWO7YU8VsAoDo58rL8oOFAWN4Gq7SPeyT51xqx0iwBEFYfG2AxaS86WWd4kJ PMpgqvQ7nJBNF5oWCsg617C2hyivC2K0K+6jW5PdVESMFPc5lM+THKG9CauwwfX5 naWVY0VOMtjBmyf+mzDwsZuTGUSNv/Cy55n5nOA9OCfgCLUFlyMc8QCoL8vpRoz5 Zzh2WdQo1TBJ66P2TMwQNXQ7HrtBSiUcY2xoAQIDAQABAoIBAEH+GKZVvY8sfK2x FvD0VW0Xn9cb+7zuGZGGbQ0OcppskdLtAtIPeS5KseIiJYfK04nw+1/Wj033G569 KMBxzBJZm2yFaY9tsQFuKlPmerbjcKrTK/Cu4y/1AuU3LnXT2DTRcecdzpb2v2Kp dEt1+wi1JvkZL6Zzz3btgXCPeJNUEjlan+FPYwI4mzMp2MyTEAvPXojLLcf+anyA 0qelff0Siz1qZS2/6USjZ2+HnF7cAbmSyNEv6SMubE7P065Ok2I9R3SjqnelXGnW ZC0FY2p6zNdi3zOHyUltZAQ2e9Lq7Ghn7OL4xor9+qXJb4Y2kzMNIuopOkBWc1HT C6+C4c0CgYEAzyVfI/nzSWtSVlu3on/qfGMfIkcMafKetofExDF/BlTsgpcQEIZB NAxUFBpcavuYTQqs1zbylYyYmSfXhl5mQlni8Yi8OKqQgi08LuGRKo1LF/w71ifz xoXsdkWm7kC08sc5eqTFqZF2rt/4f5VqxVF3tXsnDHCVdQlGwO0kZ38CgYEAwIVu 68ygL8VD6+BEIumILzEHncTJ5Y2vnYOFmhveoJIiKjD+ywWaw7M0tODFU3h9oJ1c a8D0uRXxfZrQFFVF1kAjAKBkif2xhwCVT+KARVaxNf73G4OKdRmK/ZbZCfxz/7Jh FYW2pIIF9HNXOLk3114CL+5HRvQlc1yAEZ2q8H8CgYApxo6ucb035FYBppOdSRDg LxlbT1rYjx6lDzKGorjMbRoZqB+MRZcmyQm32C0lQkJP30RGTwWTVXx8/sT/i1Ay N3CGZ54WC4gDSN4nUkR1gXNQjgT/RqVqNx4eKCPnTtNvVvBnpI1cikKWOAMkr9yN mMV8qy6P2rC5nrpPNEQwPwKBgQCv98Zg5NHtmALzEDN3Lbl6WPg7LmnT1eOUt2hg aeTdI3Ty14GsE91Xzu73/RKfrtw0+GBHZUDKA9KNGfni++YvZMQZiIEc17NyUAgp 0j+oIQss7XTzwxHE4qn2C/EpfYSRTHwMbgF48Bd9TgeFI1Z1FcouAT9JDVNF1GCC uXhLBQKBgQCJtnlqnnhpbuFiyIW9WVwBUf2ZbAzUv1TD3BRXvV/9sInFOYoMWIC4 137loBp7Qll3OO52vu0x3jyygvS9YKDQ52hjF19+Zg3/cdvIPq4zNVHpQ6v1XEN6 lGhlwAxNQ1A48+aD3fBuPUNnruY18ry3nkm29b2JpFvsJfrQFOCIVQ== -----END RSA PRIVATE KEY----- ================================================ FILE: listener/listener.go ================================================ package listener import ( "crypto/tls" "errors" "net" ) //The TrudyListener interface is used to listen for incoming connections and accept them. This is almost //the same as the typical Listener interface, except a net.Conn must be returned for Accept. This enables //Trudy to grab the original destination IP address from the kernel. type TrudyListener interface { //TODO: Listen should take two strings: "tcp" or "udp" and a port to listen on. //This parameter could create a Listener for both tcp and udp. Listen(string, *net.TCPAddr, *tls.Config) //Accept returns a generic net.Conn and the file descriptor of the socket. Accept() (int, net.Conn, error) //Close shuts down the listener. Close() error } //The TCPListener struct implements the TrudyListener interface and handles TCP connections. type TCPListener struct { Listener *net.TCPListener } func (tl *TCPListener) Listen(nets string, tcpAddr *net.TCPAddr, _ *tls.Config) { tcpListener, err := net.ListenTCP(nets, tcpAddr) if err != nil { panic(err) } tl.Listener = tcpListener } func (tl *TCPListener) Accept() (fd int, conn net.Conn, err error) { cpointer, err := tl.Listener.AcceptTCP() if err != nil { return } file, err := cpointer.File() if err != nil { return } fd = int(file.Fd()) conn, err = net.FileConn(file) if err != nil { return } return } func (tl *TCPListener) Close() error { return tl.Listener.Close() } //TLSListener struct implements the TrudyListener interface and handles TCP connections over TLS. type TLSListener struct { Listener *net.TCPListener Config *tls.Config } func (tl *TLSListener) Accept() (fd int, conn net.Conn, err error) { cpointer, err := tl.Listener.AcceptTCP() if err != nil { return } file, err := cpointer.File() if err != nil { return } fd = int(file.Fd()) fconn, err := net.FileConn(file) if err != nil { return } conn = tls.Server(fconn, tl.Config) return } func (tl *TLSListener) Listen(nets string, laddr *net.TCPAddr, config *tls.Config) { if len(config.Certificates) == 0 { panic(errors.New("tls.Listen: no certificates in configuration")) } tcpListener, err := net.ListenTCP(nets, laddr) if err != nil { panic(err) } tl.Listener = tcpListener tl.Config = config } func (tl *TLSListener) Close() error { return tl.Listener.Close() } ================================================ FILE: main.go ================================================ package main import ( "crypto/tls" "encoding/hex" "flag" "fmt" "github.com/gorilla/websocket" "github.com/praetorian-inc/trudy/listener" "github.com/praetorian-inc/trudy/module" "github.com/praetorian-inc/trudy/pipe" "io" "log" "net" "net/http" "strings" "sync" ) var connectionCount uint var websocketConn *websocket.Conn var websocketMutex *sync.Mutex var tlsConfig *tls.Config func main() { var tcpport string var tlsport string var x509 string var key string var showConnectionAttempts bool flag.StringVar(&tcpport, "tcp", "6666", "Listening port for non-TLS connections.") flag.StringVar(&tlsport, "tls", "6443", "Listening port for TLS connections.") flag.StringVar(&x509, "x509", "./certificate/trudy.cer", "Path to x509 certificate that will be presented for TLS connection.") flag.StringVar(&key, "key", "./certificate/trudy.key", "Path to the corresponding private key for the specified x509 certificate") flag.BoolVar(&showConnectionAttempts, "show", true, "Show connection open and close messages") flag.Parse() tcpport = ":" + tcpport tlsport = ":" + tlsport setup(tcpport, tlsport, x509, key, showConnectionAttempts) } func setup(tcpport, tlsport, x509, key string, show bool) { //Setup non-TLS TCP listener! tcpAddr, err := net.ResolveTCPAddr("tcp", tcpport) if err != nil { log.Printf("There appears to be an error with the TCP port you specified. See error below.\n%v\n", err.Error()) return } tcpListener := new(listener.TCPListener) //Setup TLS listener! trdy, err := tls.LoadX509KeyPair(x509, key) if err != nil { log.Printf("There appears to be an error with the x509 or key values specified. See error below.\n%v\n", err.Error()) return } tlsConfig = &tls.Config{ Certificates: []tls.Certificate{trdy}, InsecureSkipVerify: true, } tlsAddr, err := net.ResolveTCPAddr("tcp", tlsport) if err != nil { log.Printf("There appears to be an error with the TLS port specified. See error below.\n%v\n", err.Error()) return } tlsListener := new(listener.TLSListener) //All good. Start listening. tcpListener.Listen("tcp", tcpAddr, &tls.Config{}) tlsListener.Listen("tcp", tlsAddr, tlsConfig) log.Println("[INFO] Trudy lives!") log.Printf("[INFO] Listening for TLS connections on port %s\n", tlsport) log.Printf("[INFO] Listening for all other TCP connections on port %s\n", tcpport) go websocketHandler() go connectionDispatcher(tlsListener, "TLS", show) connectionDispatcher(tcpListener, "TCP", show) } func connectionDispatcher(listener listener.TrudyListener, name string, show bool) { defer listener.Close() for { fd, conn, err := listener.Accept() if err != nil { continue } p := new(pipe.TrudyPipe) if name == "TLS" { err = p.New(connectionCount, fd, conn, true) } else { err = p.New(connectionCount, fd, conn, false) } if err != nil { log.Println("[ERR] Error creating new pipe.") continue } if show { log.Printf("[INFO] ( %v ) %v Connection accepted!\n", connectionCount, name) } go clientHandler(p, show) go serverHandler(p) connectionCount++ } } func errHandler(err error) { if err != nil { panic(err) } } //clientHandler manages data that is sent from the client to the server. func clientHandler(pipe pipe.Pipe, show bool) { if show { defer log.Printf("[INFO] ( %v ) Closing TCP connection.\n", pipe.Id()) } defer pipe.Close() buffer := make([]byte, 65535) for { bytesRead, clientReadErr := pipe.ReadFromClient(buffer) if clientReadErr != io.EOF && clientReadErr != nil { break } if clientReadErr != io.EOF && bytesRead == 0 { continue } data := module.Data{FromClient: true, Bytes: buffer[:bytesRead], TLSConfig: tlsConfig, ServerAddr: pipe.ServerInfo(), ClientAddr: pipe.ClientInfo()} data.Deserialize() if data.Drop() { continue } if data.DoMangle() { data.Mangle() bytesRead = len(data.Bytes) } if data.DoIntercept() { if websocketConn == nil { log.Printf("[ERR] Websocket Connection has not been setup yet! Cannot intercept.") continue } websocketMutex.Lock() bs := fmt.Sprintf("% x", data.Bytes) if err := websocketConn.WriteMessage(websocket.TextMessage, []byte(bs)); err != nil { log.Printf("[ERR] Failed to write to websocket: %v\n", err) websocketMutex.Unlock() continue } _, moddedBytes, err := websocketConn.ReadMessage() websocketMutex.Unlock() if err != nil { log.Printf("[ERR] Failed to read from websocket: %v\n", err) continue } str := string(moddedBytes) str = strings.Replace(str, " ", "", -1) moddedBytes, err = hex.DecodeString(str) if err != nil { log.Printf("[ERR] Failed to decode hexedited data.") continue } data.Bytes = moddedBytes bytesRead = len(moddedBytes) } if data.DoPrint() { log.Printf("%v -> %v\n%v\n", data.ClientAddr.String(), data.ServerAddr.String(), data.PrettyPrint()) } data.Serialize() data.BeforeWriteToServer(pipe) bytesRead = len(data.Bytes) _, serverWriteErr := pipe.WriteToServer(data.Bytes[:bytesRead]) if serverWriteErr != nil || clientReadErr == io.EOF { break } data.AfterWriteToServer(pipe) } } //serverHandler manages data that is sent from the server to the client. func serverHandler(pipe pipe.Pipe) { buffer := make([]byte, 65535) defer pipe.Close() for { bytesRead, serverReadErr := pipe.ReadFromServer(buffer) if serverReadErr != io.EOF && serverReadErr != nil { break } if serverReadErr != io.EOF && bytesRead == 0 { continue } data := module.Data{FromClient: false, Bytes: buffer[:bytesRead], TLSConfig: tlsConfig, ClientAddr: pipe.ClientInfo(), ServerAddr: pipe.ServerInfo()} data.Deserialize() if data.Drop() { continue } if data.DoMangle() { data.Mangle() bytesRead = len(data.Bytes) } if data.DoIntercept() { if websocketConn == nil { log.Printf("[ERR] Websocket Connection has not been setup yet! Cannot intercept.") continue } websocketMutex.Lock() bs := fmt.Sprintf("% x", data.Bytes) if err := websocketConn.WriteMessage(websocket.TextMessage, []byte(bs)); err != nil { log.Printf("[ERR] Failed to write to websocket: %v\n", err) websocketMutex.Unlock() continue } _, moddedBytes, err := websocketConn.ReadMessage() websocketMutex.Unlock() if err != nil { log.Printf("[ERR] Failed to read from websocket: %v\n", err) continue } str := string(moddedBytes) str = strings.Replace(str, " ", "", -1) moddedBytes, err = hex.DecodeString(str) if err != nil { log.Printf("[ERR] Failed to decode hexedited data.") continue } data.Bytes = moddedBytes bytesRead = len(moddedBytes) } if data.DoPrint() { log.Printf("%v -> %v\n%v\n", data.ServerAddr.String(), data.ClientAddr.String(), data.PrettyPrint()) } data.Serialize() data.BeforeWriteToClient(pipe) bytesRead = len(data.Bytes) _, clientWriteErr := pipe.WriteToClient(data.Bytes[:bytesRead]) if clientWriteErr != nil || serverReadErr == io.EOF { break } data.AfterWriteToClient(pipe) } } func websocketHandler() { websocketMutex = &sync.Mutex{} upgrader := websocket.Upgrader{ReadBufferSize: 65535, WriteBufferSize: 65535} http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, editor) }) http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { var err error websocketConn, err = upgrader.Upgrade(w, r, nil) if err != nil { log.Printf("[ERR] Could not upgrade websocket connection.") return } }) err := http.ListenAndServe(":8080", nil) if err != nil { panic(err) } } const editor string = `

~ Trudy Intercept ~

00000000.
` ================================================ FILE: module/module.go ================================================ package module import ( "crypto/tls" "encoding/hex" "github.com/praetorian-inc/trudy/pipe" "net" ) //Data is a thin wrapper that provides metadata that may be useful when mangling bytes on the network. type Data struct { FromClient bool //FromClient is true is the data sent is coming from the client (the device you are proxying) Bytes []byte //Bytes is a byte slice that contians the TCP data TLSConfig *tls.Config //TLSConfig is a TLS server config that contains Trudy's TLS server certficiate. ServerAddr net.Addr //ServerAddr is net.Addr of the server ClientAddr net.Addr //ClientAddr is the net.Addr of the client (the device you are proxying) } //DoMangle will return true if Data needs to be sent to the Mangle function. func (input Data) DoMangle() bool { return true } //Mangle can modify/replace the Bytes values within the Data struct. This can //be empty if no programmatic mangling needs to be done. func (input *Data) Mangle() { } //Drop will return true if the Data needs to be dropped before going through //the pipe. func (input Data) Drop() bool { return false } //PrettyPrint returns the string representation of the data. This string will //be the value that is logged to the console. func (input Data) PrettyPrint() string { return hex.Dump(input.Bytes) } //DoPrint will return true if the PrettyPrinted version of the Data struct //needs to be logged to the console. func (input Data) DoPrint() bool { return true } //DoIntercept returns true if data should be sent to the Trudy interceptor. func (input Data) DoIntercept() bool { return false } //Deserialize should replace the Data struct's Bytes with a deserialized bytes. //For example, unpacking a HTTP/2 frame would be deserialization. func (input *Data) Deserialize() { } //Serialize should replace the Data struct's Bytes with the serialized form of //the bytes. The serialized bytes will be sent over the wire. func (input *Data) Serialize() { } //BeforeWriteToClient is a function that will be called before data is sent to //a client. func (input *Data) BeforeWriteToClient(p pipe.Pipe) { } //AfterWriteToClient is a function that will be called after data is sent to //a client. func (input *Data) AfterWriteToClient(p pipe.Pipe) { } //BeforeWriteToServer is a function that will be called before data is sent to //a server. func (input *Data) BeforeWriteToServer(p pipe.Pipe) { } //AfterWriteToServer is a function that will be called after data is sent to //a server. func (input *Data) AfterWriteToServer(p pipe.Pipe) { } ================================================ FILE: module/xmpp.go.trudy ================================================ package module import ( "bytes" "crypto/tls" "encoding/hex" "github.com/praetorian-inc/trudy/pipe" "log" "net" "strings" ) //Data is a wrapper that provides metadata that may be useful when mangling bytes on the network. type Data struct { FromClient bool //FromClient is true is the data sent is coming from the client (the device you are proxying) Bytes []byte //Bytes is a byte slice that contians the TCP data TLSConfig *tls.Config //TLSConfig is a TLS server config that contains Trudy's TLS server certficiate. ServerAddr net.Addr //ServerAddr is net.Addr of the server ClientAddr net.Addr //ClientAddr is the net.Addr of the client (the device you are proxying) } var startTLSElementSingle string = "" var startTLSElementDouble string = "" var proceedElementDouble string = "" var proceedElementSingle string = "" //DoPrint will return true if the PrettyPrinted version of the Data struct //needs to be logged to the console. func (input Data) DoPrint() bool { //Only print client/server data sent over XMPP Ports. return strings.Contains(input.ServerAddr.String(), ":5225") || strings.Contains(input.ClientAddr.String(), ":5225") } //AfterWriteToServer is a function that will be called after data is sent to //a server. func (input *Data) AfterWriteToServer(p pipe.Pipe) { if bytes.Contains(input.Bytes, []byte(startTLSElementDouble)) || bytes.Contains(input.Bytes, []byte(startTLSElementSingle)) { //The client has sent StartTLS response to the server's StartTLS //request. Trudy will now handle that upgrade. log.Printf("[INFO] ( %v ) Upgrading client-side connection.\n", p.Id()) //Upgrade the connection and prepare for a ClientHandshake tlsConn := tls.Server(p.ClientConn(), input.TLSConfig) //Tell the client to proceed. We will drop the server's real proceed. p.WriteToClient([]byte(proceedElementDouble)) log.Printf("[INFO] ( %v ) Sent client a proceed. Now locking own goroutine to allow server-side upgrade.\n", p.Id()) //Lock this pipe until the server-side TLS upgrade has completed. p.Lock() //TODO(kkl): This is kinda hacky. I think a chan will be better here. p.Lock() //Once this code has been reached, the server-side TLS //connection has been upgraded. The client-side can now proceed //with a TLS upgrade. err := tlsConn.Handshake() if err != nil { p.Close() return } //Update the client-side connection with the new TLS connection //and unlock the pipe. p.SetClientConn(tlsConn) p.Unlock() log.Printf("[INFO] ( %v ) Upgraded client-side connection.\n", p.Id()) } } //BeforeWriteToClient is a function that will be called before data is sent to //a client. func (input *Data) BeforeWriteToClient(p pipe.Pipe) { if bytes.Contains(input.Bytes, []byte(proceedElementDouble)) || bytes.Contains(input.Bytes, []byte(proceedElementSingle)) { //We have recieved a proceed from the server. Trudy will //now upgrade the server-side connection. log.Printf("[INFO] ( %v ) Upgrading server-side connection.\n", p.Id()) tlsConfig := tls.Config{InsecureSkipVerify: true} tlsConn := tls.Client(p.ServerConn(), &tlsConfig) p.SetServerConn(tlsConn) //Lets drop the proceed message so its not sent to the client. (Since Trudy already sent one) log.Printf("[INFO] ( %v ) Dropping the server's proceed.\n", p.Id()) input.Bytes = []byte{} p.Unlock() log.Printf("[INFO] ( %v ) Upgraded server-side connection.\n", p.Id()) } } // // // Unmodified module methods. All methods past this point are using the default implementation. // // //DoIntercept returns true if data should be sent to the Trudy interceptor. func (input Data) DoIntercept() bool { return false } //Mangle can modify/replace the Bytes values within the Data struct. This can //be empty if no programmatic mangling needs to be done. func (input *Data) Mangle() { } //PrettyPrint returns the string representation of the data. This string will //be the value that is logged to the console. func (input Data) PrettyPrint() string { return hex.Dump(input.Bytes) } //Deserialize should replace the Data struct's Bytes with a deserialized bytes. //For example, unpacking a HTTP/2 frame would be deserialization. func (input *Data) Deserialize() { } //Serialize should replace the Data struct's Bytes with the serialized form of //the bytes. The serialized bytes will be sent over the wire. func (input *Data) Serialize() { } //DoMangle will return true if Data needs to be sent to the Mangle function. func (input Data) DoMangle() bool { return false } //Drop will return true if the Data needs to be dropped before going through //the pipe. func (input Data) Drop() bool { return false } //AfterWriteToClient is a function that will be called after data is sent to //a client. func (input *Data) AfterWriteToClient(p pipe.Pipe) { } //BeforeWriteToServer is a function that will be called before data is sent to //a server. func (input *Data) BeforeWriteToServer(p pipe.Pipe) { } ================================================ FILE: pipe/pipe.go ================================================ //Package pipe defines the data structure used to manipulate, monitor, and create proxied connections. package pipe import ( "crypto/tls" "log" "net" "strconv" "sync" "syscall" "time" ) //Netfilter/iptables adds a tcp header to identify original destination. //Since all traffic is routed through trudy, we need to retrieve the original //intended destination (i.e. _not_ trudy) const SO_ORIGINAL_DST = 80 //Pipe is the primary interface that handles connections. Pipe creates a //full-duplex pipe that passes data from the client to the server and vice //versa. A pipe is compromised of two connections. The client transparently //connects to Trudy, and Trudy accepts the connection. Trudy will then make a //connection with the client's intended destination and just pass traffic //back-and-forth between the two connections. All modifications and drops to //the packet happen to data between the two ends of the pipe. type Pipe interface { //Id returns a unique Pipe identifier Id() uint //ServerInfo returns the net.Addr of the server-end of the pipe. ServerInfo() (addr net.Addr) //ClientInfo returns the net.Addr of the client-end of the pipe. ClientInfo() (addr net.Addr) //ReadFromClient reads data into the buffer from the client-end of the //pipe. ReadFromClient returns the number of bytes read and an error //value if an error or EOF occurred. Note: ReadFromClient can read a //non-zero number of bytes and have a non-nil error value (e.g. EOF). ReadFromClient(buffer []byte) (n int, err error) //WriteToClient writes data to the client-end of the pipe. This is //typically the proxy-unaware client. WriteToClient(buffer []byte) (n int, err error) //ReadFromServer reads data into the buffer from the server-end of the //pipe. The server is the proxy-unaware client's intended destination. //ReadFromServer returns the number of bytes read and an error value if //an error or EOF occurred. Note: ReadFromServer can read a non-zero //number of bytes and have a non-nil error value (e.g. EOF). ReadFromServer(buffer []byte) (n int, err error) //WriteToServer writes buffer to the server-end of the pipe. The server //is the proxy-unaware client's intended destination. WriteToServer(buffer []byte) (n int, err error) //ServerConn returns the net.Conn responsible for server-end //communication. ServerConn() (conn net.Conn) //CilentConn returns the net.Conn responsible for client-end //communication. ClientConn() (conn net.Conn) //SetServerConn will replace the server-end of the pipe with the supplied //net.Conn parameter. SetServerConn(conn net.Conn) //SetClientConn will replace the client-end of the pipe with the supplied //net.Conn parameter. SetClientConn(conn net.Conn) //New builds a new Pipe. New(pipeID uint, clientConnFD int, clientConn net.Conn, useTLS bool) (err error) //Close closes both connections of the Pipe. Close() //Lock locks a per-Pipe mutex that can be used in modules for //synchronization. Lock() //Unlock unlocks a per-Pipe mutex that can be used in modules for //synchronization. Unlock() //AddContext adds a key/value pair to the Pipe. AddContext(key string, value interface{}) //GetContext retrieves a value in a Pipe key/value data store. //GetContext returns the value and a bool indicating success. GetContext(key string) (value interface{}, ok bool) //DeleteContext removes a key/value pair from the Pipe. DeleteContext(key string) } //TODO(kkl): I don't think New needs to be part of the Pipe interface. //Removing this very specific constructor will allow for other methods //of getting trudy as a proxy (e.g. other transparent proxies, or //non-transparent proxies like SOCKS). //TrudyPipe implements the Pipe interface and can be used to proxy TCP connections. type TrudyPipe struct { id uint serverConn net.Conn clientConn net.Conn pipeMutex *sync.Mutex userMutex *sync.Mutex KV map[string]interface{} } //Lock locks a mutex stored within TrudyPipe to allow for fine-grained //synchronization within a module. func (t *TrudyPipe) Lock() { t.userMutex.Lock() } //Unlock unlocks a mutex stored within TrudyPipe to allow for fine-grained //synchronization within a module. func (t *TrudyPipe) Unlock() { t.userMutex.Unlock() } //AddContext adds a key/value pair to the TrudyPipe. The key/value //pair data store is per-TrudyPipe. AddContext is safe for use //in multiple goroutines. func (t *TrudyPipe) AddContext(key string, value interface{}) { t.pipeMutex.Lock() t.KV[key] = value t.pipeMutex.Unlock() } //GetContext retrieves a value in a TrudyPipe key/value data store. //GetContext returns the value and a bool indicating success. func (t *TrudyPipe) GetContext(key string) (retval interface{}, ok bool) { retval, ok = t.KV[key] return } //DeleteContext removes a key/value pair from the TrudyPipe. DeleteContext is //safe for use in multiple goroutines. func (t *TrudyPipe) DeleteContext(key string) { t.pipeMutex.Lock() delete(t.KV, key) t.pipeMutex.Unlock() } //CilentConn returns the net.Conn responsible for client-end communication. func (t *TrudyPipe) ClientConn() net.Conn { return t.clientConn } //ServerConn returns the net.Conn responsible for server-end communication. func (t *TrudyPipe) ServerConn() net.Conn { return t.serverConn } //SetClientConn will replace the client-end of the pipe with the supplied //net.Conn parameter. SetClientConn is safe for use in multiple goroutines. func (t *TrudyPipe) SetClientConn(c net.Conn) { t.pipeMutex.Lock() t.clientConn = c t.pipeMutex.Unlock() } //SetServerConn will replace the server-end of the pipe with the supplied //net.Conn parameter. SetServerConn is safe for use in multiple goroutines. func (t *TrudyPipe) SetServerConn(s net.Conn) { t.pipeMutex.Lock() t.serverConn = s t.pipeMutex.Unlock() } //Id returns a TrudyPipe identifier func (t *TrudyPipe) Id() uint { return t.id } //ServerInfo returns the net.Addr of the server. func (t *TrudyPipe) ServerInfo() (addr net.Addr) { addr = t.serverConn.RemoteAddr() return } //ClientInfo returns the net.Addr of the client. func (t *TrudyPipe) ClientInfo() (addr net.Addr) { addr = t.clientConn.RemoteAddr() return } //Close closes both ends of a TrudyPipe. func (t *TrudyPipe) Close() { t.serverConn.Close() t.clientConn.Close() } //ReadFromClient reads data from the client end of the pipe. This is typically the proxy-unaware client. func (t *TrudyPipe) ReadFromClient(buffer []byte) (n int, err error) { //TODO(kkl): Make timeouts configureable. err = t.clientConn.SetReadDeadline(time.Now().Add(15 * time.Second)) if err != nil { return } n, err = t.clientConn.Read(buffer) return } //WriteToClient writes data to the client end of the pipe. This is typically the proxy-unaware client. func (t *TrudyPipe) WriteToClient(buffer []byte) (n int, err error) { //TODO(kkl): Make timeouts configureable. err = t.clientConn.SetWriteDeadline(time.Now().Add(15 * time.Second)) if err != nil { return } n, err = t.clientConn.Write(buffer) return } //ReadFromServer reads data from the server end of the pipe. The server is the //proxy-unaware client's intended destination. func (t *TrudyPipe) ReadFromServer(buffer []byte) (n int, err error) { t.serverConn.SetReadDeadline(time.Now().Add(15 * time.Second)) return t.serverConn.Read(buffer) } //WriteToServer writes data to the server end of the pipe. The server is the //proxy-unaware client's intended destination. func (t *TrudyPipe) WriteToServer(buffer []byte) (n int, err error) { err = t.serverConn.SetWriteDeadline(time.Now().Add(15 * time.Second)) if err != nil { return } n, err = t.serverConn.Write(buffer) return } //byteToConnString converts the Multiaddr bytestring returned by Getsockopt into a "host:port" connection string. func byteToConnString(multiaddr [16]byte) string { ip := multiaddr[4:8] ipString := net.IPv4(ip[0], ip[1], ip[2], ip[3]).String() port := multiaddr[2:4] portUint := int64((uint32(port[0]) << 8) + uint32(port[1])) portString := strconv.FormatInt(portUint, 10) return (ipString + ":" + portString) } //New builds a new TrudyPipe. New will get the original destination of traffic //that was mangled by iptables and get the original destination. New will then //open a connection to that original destination and, upon success, will set //all the internal values needed for a TrudyPipe. func (t *TrudyPipe) New(id uint, fd int, clientConn net.Conn, useTLS bool) (err error) { //TODO(kkl): Make the second argument system-dependent. E.g. If a linux machine: syscall.SOL_IP originalAddrBytes, err := syscall.GetsockoptIPv6Mreq(fd, syscall.IPPROTO_IP, SO_ORIGINAL_DST) if err != nil { log.Println("[DEBUG] Getsockopt failed.") clientConn.Close() return err } var serverConn net.Conn if useTLS { tlsconfig := &tls.Config{InsecureSkipVerify: true} serverConn, err = tls.Dial("tcp", byteToConnString(originalAddrBytes.Multiaddr), tlsconfig) if err != nil { log.Printf("[ERR] Unable to connect to destination. Closing connection %v.\n", id) clientConn.Close() return err } } else { serverConn, err = net.Dial("tcp", byteToConnString(originalAddrBytes.Multiaddr)) if err != nil { log.Printf("[ERR] ( %v ) Unable to connect to destination. Closing pipe.\n", id) clientConn.Close() return err } } t.id = id t.clientConn = clientConn t.serverConn = serverConn t.pipeMutex = new(sync.Mutex) t.userMutex = new(sync.Mutex) return nil }