pax_global_header00006660000000000000000000000064136123761560014524gustar00rootroot0000000000000052 comment=7cfe059c664e06bc7663620024578d85d9e6008c trojan-1.14.1/000077500000000000000000000000001361237615600131055ustar00rootroot00000000000000trojan-1.14.1/.github/000077500000000000000000000000001361237615600144455ustar00rootroot00000000000000trojan-1.14.1/.github/ISSUE_TEMPLATE/000077500000000000000000000000001361237615600166305ustar00rootroot00000000000000trojan-1.14.1/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000016661361237615600213330ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: "[BUG]" labels: bug assignees: GreaterFire --- - [ ] I certify that I acknowledge if I don't follow the format below, or I'm using an old version of trojan, or I apparently fail to provide sufficient information (such as logs, specific numbers), or I don't check this box, my issue will be closed immediately without any notice. **Trojan Version** The version of trojan you are using. **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Logs** If applicable, add logs to help explain your problem. **Environment** Where are you running trojan? What is your proxy set up? **Additional context** Add any other context about the problem here. trojan-1.14.1/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000017141361237615600223600ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project title: "[Feature Request]" labels: enhancement assignees: GreaterFire --- - [ ] I certify that I acknowledge if I don't follow the format below or I don't check this box, my issue will be closed immediately without any notice. **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Is this problem relevant to what trojan should care about?** Trojan is a protocol implementation, not a full-fledged proxy client. Features such as custom routing will not be accepted. **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. trojan-1.14.1/.gitignore000066400000000000000000000010231361237615600150710ustar00rootroot00000000000000# Prerequisites *.d # Compiled Object files *.slo *.lo *.o *.obj # Precompiled Headers *.gch *.pch # Compiled Dynamic libraries *.so *.dylib *.dll # Fortran module files *.mod *.smod # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app trojan # Config files *.json # Key and certificate files *.pem # Systemd service files *.service # Cmake files CMakeCache.txt CMakeFiles CMakeScripts Testing Makefile cmake_install.cmake install_manifest.txt compile_commands.json CTestTestfile.cmake build/ trojan-1.14.1/CMakeLists.txt000066400000000000000000000111611361237615600156450ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.7.2) project(trojan) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/") if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() set(CMAKE_CXX_STANDARD 11) if(MSVC) add_definitions(-D_CRT_SECURE_NO_WARNINGS) else() add_definitions(-Wall -Wextra) endif() add_executable(trojan src/core/authenticator.cpp src/core/config.cpp src/core/log.cpp src/core/service.cpp src/core/version.cpp src/main.cpp src/proto/socks5address.cpp src/proto/trojanrequest.cpp src/proto/udppacket.cpp src/session/clientsession.cpp src/session/forwardsession.cpp src/session/natsession.cpp src/session/serversession.cpp src/session/session.cpp src/session/udpforwardsession.cpp src/ssl/ssldefaults.cpp src/ssl/sslsession.cpp) include_directories(src) set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) target_link_libraries(trojan ${CMAKE_THREAD_LIBS_INIT}) find_package(Boost 1.66.0 REQUIRED COMPONENTS system program_options) include_directories(${Boost_INCLUDE_DIR}) target_link_libraries(trojan ${Boost_LIBRARIES}) if(MSVC) add_definitions(-DBOOST_DATE_TIME_NO_LIB) endif() find_package(OpenSSL 1.1.0 REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(trojan ${OPENSSL_LIBRARIES}) if(OPENSSL_VERSION VERSION_GREATER_EQUAL 1.1.1) option(ENABLE_SSL_KEYLOG "Build with SSL KeyLog support" ON) if(ENABLE_SSL_KEYLOG) add_definitions(-DENABLE_SSL_KEYLOG) endif() option(ENABLE_TLS13_CIPHERSUITES "Build with TLS1.3 ciphersuites support" ON) if(ENABLE_TLS13_CIPHERSUITES) add_definitions(-DENABLE_TLS13_CIPHERSUITES) endif() endif() option(ENABLE_MYSQL "Build with MySQL support" ON) if(ENABLE_MYSQL) find_package(MySQL REQUIRED) include_directories(${MYSQL_INCLUDE_DIR}) target_link_libraries(trojan ${MYSQL_LIBRARIES}) add_definitions(-DENABLE_MYSQL) endif() option(FORCE_TCP_FASTOPEN "Force build with TCP Fast Open support" OFF) if(FORCE_TCP_FASTOPEN) add_definitions(-DTCP_FASTOPEN=23 -DTCP_FASTOPEN_CONNECT=30) endif() if(CMAKE_SYSTEM_NAME STREQUAL Linux) option(ENABLE_NAT "Build with NAT support" ON) if(ENABLE_NAT) add_definitions(-DENABLE_NAT) endif() option(ENABLE_REUSE_PORT "Build with SO_REUSEPORT support" ON) if(ENABLE_REUSE_PORT) add_definitions(-DENABLE_REUSE_PORT) endif() endif() if(APPLE) find_library(CoreFoundation CoreFoundation) find_library(Security Security) target_link_libraries(trojan ${CoreFoundation} ${Security}) endif() if(WIN32) target_link_libraries(trojan wsock32 ws2_32 crypt32) else() set(SYSTEMD_SERVICE AUTO CACHE STRING "Install systemd service") set_property(CACHE SYSTEMD_SERVICE PROPERTY STRINGS AUTO ON OFF) set(SYSTEMD_SERVICE_PATH /lib/systemd/system CACHE PATH "Systemd service path") if(SYSTEMD_SERVICE STREQUAL AUTO) if(EXISTS /usr/lib/systemd/system) set(SYSTEMD_SERVICE ON) set(SYSTEMD_SERVICE_PATH /usr/lib/systemd/system CACHE PATH "Systemd service path" FORCE) elseif(EXISTS /lib/systemd/system) set(SYSTEMD_SERVICE ON) set(SYSTEMD_SERVICE_PATH /lib/systemd/system CACHE PATH "Systemd service path" FORCE) endif() endif() include(GNUInstallDirs) install(TARGETS trojan DESTINATION ${CMAKE_INSTALL_BINDIR}) install(FILES examples/server.json-example DESTINATION ${CMAKE_INSTALL_FULL_SYSCONFDIR}/trojan RENAME config.json) set(DEFAULT_CONFIG ${CMAKE_INSTALL_FULL_SYSCONFDIR}/trojan/config.json CACHE STRING "Default config path") add_definitions(-DDEFAULT_CONFIG="${DEFAULT_CONFIG}") install(FILES docs/trojan.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1) install(DIRECTORY docs/ DESTINATION ${CMAKE_INSTALL_DOCDIR} FILES_MATCHING PATTERN "*.md") install(DIRECTORY examples DESTINATION ${CMAKE_INSTALL_DOCDIR} FILES_MATCHING PATTERN "*.json-example") if(SYSTEMD_SERVICE STREQUAL ON) set(CONFIG_NAME config) configure_file(examples/trojan.service-example trojan.service) set(CONFIG_NAME %i) configure_file(examples/trojan.service-example trojan@.service) install(FILES ${CMAKE_BINARY_DIR}/trojan.service ${CMAKE_BINARY_DIR}/trojan@.service DESTINATION ${SYSTEMD_SERVICE_PATH}) endif() enable_testing() add_test(NAME LinuxSmokeTest-basic COMMAND bash ${CMAKE_SOURCE_DIR}/tests/LinuxSmokeTest/basic.sh ${CMAKE_BINARY_DIR}/trojan) add_test(NAME LinuxSmokeTest-fake-client COMMAND bash ${CMAKE_SOURCE_DIR}/tests/LinuxSmokeTest/fake-client.sh ${CMAKE_BINARY_DIR}/trojan) endif() trojan-1.14.1/CONTRIBUTORS.md000066400000000000000000000031201361237615600153600ustar00rootroot00000000000000# Contributors - [a-wing](https://github.com/a-wing) - Add Debian build instructions in the documentation. - [felixonmars](https://github.com/felixonmars) - Fix incorrect systemd service path in the documentation. - [ffftwo](https://github.com/ffftwo) - Throw an exception when `run_type` is wrong. - [GreaterFire](https://github.com/GreaterFire) - Author of this project. - [JonathanHouten](https://github.com/JonathanHouten) - Fix a parameter type error in the `CertOpenSystemStore` call. - [KCCat](https://github.com/KCCat) - Fix an ambiguity in the documentation. - [klzgrad](https://github.com/klzgrad) - Add Linux smoke test. - [WeidiDeng](https://github.com/WeidiDeng) - Fix incorrect Debian dependency in the documentation. - [wongsyrone](https://github.com/wongsyrone) - Add conditional MySQL compilation. - Remove `SSL_CTX_set_ecdh_auto(native_context, 1)` call in new versions of OpenSSL. - Fix a typo in the documentation. - Add a functionality to log received signals. - Fix a bug that causes trojan to crash if the connection is terminated before a session is established. - Add android log facility. - Refer to `basic_stream_socket` instead of `basic_socket` in SSL sockets. - Cancel async tasks when stopping the service. - Fix fd leak. - Print OpenSSL compile-time version and build flags. - Optimize APIs and other clean-ups. - [xsm1997](https://github.com/xsm1997) - Add `SO_REUSEPORT` support. - Add TLS1.3 ciphersuites support. - [zhangsan946](https://github.com/zhangsan946) - Add macOS keychain support. trojan-1.14.1/LICENSE000066400000000000000000001060051361237615600141140ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} 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 3 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, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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. But first, please read . In addition, as a special exception, the copyright holders give permission to link the code of portions of this program with the OpenSSL library under certain conditions as described in each individual source file, and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than OpenSSL. If you modify file(s) with this exception, you may extend this exception to your version of the file(s), but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. If you delete this exception statement from all source files in the program, then also delete it here. trojan-1.14.1/README.md000066400000000000000000000022161361237615600143650ustar00rootroot00000000000000# trojan [![Build Status](https://dev.azure.com/GreaterFire/Trojan-GFW/_apis/build/status/trojan-gfw.trojan?branchName=master)](https://dev.azure.com/GreaterFire/Trojan-GFW/_build/latest?definitionId=5&branchName=master) An unidentifiable mechanism that helps you bypass GFW. Trojan features multiple protocols over `TLS` to avoid both active/passive detections and ISP `QoS` limitations. Trojan is not a fixed program or protocol. It's an idea, an idea that imitating the most common service, to an extent that it behaves identically, could help you get across the Great FireWall permanently, without being identified ever. We are the GreatER Fire; we ship Trojan Horses. ## Documentations An online documentation can be found [here](https://trojan-gfw.github.io/trojan/). Installation guide on various platforms can be found in the [wiki](https://github.com/trojan-gfw/trojan/wiki/Binary-&-Package-Distributions). ## Dependencies - [CMake](https://cmake.org/) >= 3.7.2 - [Boost](http://www.boost.org/) >= 1.66.0 - [OpenSSL](https://www.openssl.org/) >= 1.1.0 - [libmysqlclient](https://dev.mysql.com/downloads/connector/c/) ## License [GPLv3](LICENSE) trojan-1.14.1/azure-pipelines.yml000066400000000000000000000106741361237615600167540ustar00rootroot00000000000000stages: - stage: Build jobs: - job: Linux pool: vmImage: ubuntu-latest container: image: trojangfw/centos-build:latest steps: - script: | set -euo pipefail echo 'target_link_libraries(trojan dl)' >> CMakeLists.txt cmake -DMYSQL_INCLUDE_DIR=/usr/local/include/mariadb -DMYSQL_LIBRARY=/usr/local/lib/mariadb/libmysqlclient.a -DDEFAULT_CONFIG=config.json -DFORCE_TCP_FASTOPEN=ON -DBoost_USE_STATIC_LIBS=ON . make strip -s trojan - publish: $(System.DefaultWorkingDirectory)/trojan artifact: LinuxBinary - job: macOS pool: vmImage: macOS-latest steps: - script: | set -euo pipefail brew install boost openssl@1.1 cmake -DBoost_USE_STATIC_LIBS=ON -DOPENSSL_INCLUDE_DIR=/usr/local/opt/openssl@1.1/include -DOPENSSL_CRYPTO_LIBRARY=/usr/local/opt/openssl@1.1/lib/libcrypto.a -DOPENSSL_SSL_LIBRARY=/usr/local/opt/openssl@1.1/lib/libssl.a -DDEFAULT_CONFIG=config.json -DENABLE_MYSQL=OFF . make strip -SXTx trojan - publish: $(System.DefaultWorkingDirectory)/trojan artifact: macOSBinary - job: Windows pool: vmImage: windows-latest steps: - bash: | set -euo pipefail curl -LO https://slproweb.com/download/Win64OpenSSL-1_1_1d.exe powershell ".\\Win64OpenSSL-1_1_1d.exe /silent /sp- /suppressmsgboxes /DIR='C:\\Program Files\\OpenSSL-Win64'" cmake -DBoost_USE_STATIC_LIBS=ON -DOPENSSL_ROOT_DIR='C:/Program Files/OpenSSL-Win64' -DOPENSSL_USE_STATIC_LIBS=ON -DENABLE_MYSQL=OFF . cmake --build . --config Release - publish: $(System.DefaultWorkingDirectory)/Release/trojan.exe artifact: WindowsBinary - stage: Test jobs: - job: Linux pool: vmImage: ubuntu-latest steps: - download: current artifact: LinuxBinary - script: | set -uo pipefail BINARY="$PIPELINE_WORKSPACE/LinuxBinary/trojan" chmod +x "$BINARY" mkdir results cp -r "$(tests/LinuxSmokeTest/basic.sh "$BINARY")" results/basic cp -r "$(tests/LinuxSmokeTest/fake-client.sh "$BINARY")" results/fake-client env: PIPELINE_WORKSPACE: $(Pipeline.Workspace) - publish: $(System.DefaultWorkingDirectory)/results artifact: LinuxTest - stage: Package jobs: - job: Linux pool: vmImage: ubuntu-latest steps: - download: current artifact: LinuxBinary - script: | set -euo pipefail BINARY="$PIPELINE_WORKSPACE/LinuxBinary/trojan" chmod +x "$BINARY" mkdir trojan cp "$BINARY" trojan/trojan cp -r examples CONTRIBUTORS.md LICENSE README.md trojan cp examples/server.json-example trojan/config.json tar cf trojan-linux-amd64.tar trojan xz trojan-linux-amd64.tar env: PIPELINE_WORKSPACE: $(Pipeline.Workspace) - publish: $(System.DefaultWorkingDirectory)/trojan-linux-amd64.tar.xz artifact: LinuxRelease - job: macOS pool: vmImage: macOS-latest steps: - download: current artifact: macOSBinary - script: | set -euo pipefail BINARY="$PIPELINE_WORKSPACE/macOSBinary/trojan" chmod +x "$BINARY" mkdir trojan cp "$BINARY" trojan/trojan cp -r examples CONTRIBUTORS.md LICENSE README.md trojan cp examples/client.json-example trojan/config.json rm trojan/examples/nat.json-example trojan/examples/trojan.service-example cat > trojan/start.command <= 3.7.2 - [Boost](http://www.boost.org/) >= 1.66.0 - [OpenSSL](https://www.openssl.org/) >= 1.1.0 - [libmysqlclient](https://dev.mysql.com/downloads/connector/c/) For Debian users, run `sudo apt -y install build-essential cmake libboost-system-dev libboost-program-options-dev libssl-dev default-libmysqlclient-dev` to install all the necessary dependencies. ## Clone Type in ```bash git clone https://github.com/trojan-gfw/trojan.git cd trojan/ ``` to clone the project and go into the directory. ## Build and Install Type in ```bash mkdir build cd build/ cmake .. make ctest sudo make install ``` to build, test, and install trojan. If everything goes well you'll be able to use trojan. The `cmake ..` command can be extended with the following options: - `-DDEFAULT_CONFIG=/path/to/default/config.json`: the default path trojan will look for config (defaults to `${CMAKE_INSTALL_FULL_SYSCONFDIR}/trojan/config.json`). - `ENABLE_MYSQL` - `-DENABLE_MYSQL=ON`: build with MySQL support (default). - `-DENABLE_MYSQL=OFF`: build without MySQL support. - `ENABLE_NAT` (Only on Linux) - `-DENABLE_NAT=ON`: build with NAT support (default). - `-DENABLE_NAT=OFF`: build without NAT support. - `ENABLE_REUSE_PORT` (Only on Linux) - `-DENABLE_REUSE_PORT=ON`: build with `SO_REUSEPORT` support (default). - `-DENABLE_REUSE_PORT=OFF`: build without `SO_REUSEPORT` support. - `ENABLE_SSL_KEYLOG` (OpenSSL >= 1.1.1) - `-DENABLE_SSL_KEYLOG=ON`: build with SSL KeyLog support (default). - `-DENABLE_SSL_KEYLOG=OFF`: build without SSL KeyLog support. - `ENABLE_TLS13_CIPHERSUITES` (OpenSSL >= 1.1.1) - `-DENABLE_TLS13_CIPHERSUITES=ON`: build with TLS1.3 ciphersuites support (default). - `-DENABLE_TLS13_CIPHERSUITES=OFF`: build without TLS1.3 ciphersuites support. - `FORCE_TCP_FASTOPEN` - `-DFORCE_TCP_FASTOPEN=ON`: force build with `TCP_FASTOPEN` support. - `-DFORCE_TCP_FASTOPEN=OFF`: build with `TCP_FASTOPEN` support based on system capabilities (default). - `SYSTEMD_SERVICE` - `-DSYSTEMD_SERVICE=AUTO`: detect systemd automatically and decide whether to install service (default). - `-DSYSTEMD_SERVICE=ON`: install systemd service unconditionally. - `-DSYSTEMD_SERVICE=OFF`: don't install systemd service unconditionally. - `-DSYSTEMD_SERVICE_PATH=/path/to/systemd/system`: the path to which the systemd service will be installed (defaults to `/lib/systemd/system`). After installation, config examples will be installed to `${CMAKE_INSTALL_DOCDIR}/examples/` and a server config will be installed to `${CMAKE_INSTALL_FULL_SYSCONFDIR}/trojan/config.json`. [Homepage](.) | [Prev Page](authenticator) | [Next Page](usage) trojan-1.14.1/docs/config.md000066400000000000000000000230231361237615600156240ustar00rootroot00000000000000# Config In this page, we will look at the config file of trojan. Trojan uses [`JSON`](https://en.wikipedia.org/wiki/JSON) as the format of the config. **Note: all "\\" in the paths under Windows MUST be replaced with "/".** ## A valid client.json ```json { "run_type": "client", "local_addr": "127.0.0.1", "local_port": 1080, "remote_addr": "example.com", "remote_port": 443, "password": [ "password1" ], "log_level": 1, "ssl": { "verify": true, "verify_hostname": true, "cert": "", "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA", "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", "sni": "", "alpn": [ "h2", "http/1.1" ], "reuse_session": true, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } ``` - `run_type`: running trojan as `client` - `local_addr`: a `SOCKS5` server interface will be bound to the specified interface. Feel free to change this to ``0.0.0.0``, ``::1``, ``::`` or other addresses, if you know what you are doing. - `local_port`: a `SOCKS5` interface will be bound to this port - `remote_addr`: server address (hostname) - `remote_port`: server port - `password`: password used for verification (only the first password in the array will be used) - `log_level`: how much log to dump. 0: ALL; 1: INFO; 2: WARN; 3: ERROR; 4: FATAL; 5: OFF. - `ssl`: `SSL` specific configurations - `verify`: whether to verify `SSL` certificate **STRONGLY RECOMMENDED** - `verify_hostname`: whether to verify `SSL` hostname (specified in the `sni` field) **STRONGLY RECOMMENDED** - `cert`: if `verify` is set to `true`, the same certificate used by the server or a collection of `CA` certificates could be provided. If you leave this field blank, `OpenSSL` will try to look for a system `CA` store and will be likely to fail. - `cipher`: a cipher list to send and use - `cipher_tls13`: a cipher list for TLS 1.3 to use - `sni`: the Server Name Indication field in the `SSL` handshake. If left blank, it will be set to `remote_addr`. - `alpn`: a list of `ALPN` protocols to send - `reuse_session`: whether to reuse `SSL` session - `session_ticket`: whether to use session tickets for session resumption - `curves`: `ECC` curves to send and use - `tcp`: `TCP` specific configurations - `no_delay`: whether to disable Nagle's algorithm - `keep_alive`: whether to enable TCP Keep Alive - `reuse_port`: whether to enable TCP port reuse (kernel support required) - `fast_open`: whether to enable TCP Fast Open (kernel support required) - `fast_open_qlen`: the server's limit on the size of the queue of TFO requests that have not yet completed the three-way handshake ## A valid forward.json This forward config is for port forwarding. Everything is the same as the client config, except for `target_addr` and `target_port`, which point to the destination endpoint, and `udp_timeout`, which controls how long (in seconds) a UDP session will last in idle. ```json { "run_type": "forward", "local_addr": "127.0.0.1", "local_port": 5901, "remote_addr": "example.com", "remote_port": 443, "target_addr": "127.0.0.1", "target_port": 5901, "password": [ "password1" ], "udp_timeout": 60, "log_level": 1, "ssl": { "verify": true, "verify_hostname": true, "cert": "", "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA", "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", "sni": "", "alpn": [ "h2", "http/1.1" ], "reuse_session": true, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } ``` ## A valid nat.json The NAT config is for transparent proxy. You'll need to [setup iptables rules](https://github.com/shadowsocks/shadowsocks-libev/tree/v3.3.1#transparent-proxy) to use it. Everything is the same as the client config. ```json { "run_type": "nat", "local_addr": "127.0.0.1", "local_port": 12345, "remote_addr": "example.com", "remote_port": 443, "password": [ "password1" ], "log_level": 1, "ssl": { "verify": true, "verify_hostname": true, "cert": "", "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA", "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", "sni": "", "alpn": [ "h2", "http/1.1" ], "reuse_session": true, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } ``` ## A valid server.json ```json { "run_type": "server", "local_addr": "0.0.0.0", "local_port": 443, "remote_addr": "127.0.0.1", "remote_port": 80, "password": [ "password1", "password2" ], "log_level": 1, "ssl": { "cert": "/path/to/certificate.crt", "key": "/path/to/private.key", "key_password": "", "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384", "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", "prefer_server_cipher": true, "alpn": [ "http/1.1" ], "reuse_session": true, "session_ticket": false, "session_timeout": 600, "plain_http_response": "", "curves": "", "dhparam": "" }, "tcp": { "prefer_ipv4": false, "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 }, "mysql": { "enabled": false, "server_addr": "127.0.0.1", "server_port": 3306, "database": "trojan", "username": "trojan", "password": "" } } ``` - `run_type`: running trojan as `server` - `local_addr`: trojan server will be bound to the specified interface. Feel free to change this to `::` or other addresses, if you know what you are doing. - `local_port`: trojan server will be bound to this port - `remote_addr`: the endpoint address that trojan server will connect to when encountering [other protocols](protocol#other-protocols) - `remote_port`: the endpoint port that trojan server will connect when encountering [other protocols](protocol#other-protocols) - `password`: an array of passwords used for verification - `log_level`: how much log to dump. 0: ALL; 1: INFO; 2: WARN; 3: ERROR; 4: FATAL; 5: OFF. - `ssl`: `SSL` specific configurations - `cert`: server certificate **STRONGLY RECOMMENDED TO BE SIGNED BY A CA** - `key`: private key file for encryption - `key_password`: password of the private key file - `cipher`: a cipher list to use - `cipher_tls13`: a cipher list for TLS 1.3 to use - `prefer_server_cipher`: whether to prefer server cipher list in a connection - `alpn`: a list of `ALPN` protocols to reply - `reuse_session`: whether to reuse `SSL` session - `session_ticket`: whether to use session tickets for session resumption - `session_timeout`: if `reuse_session` is set to `true`, specify `SSL` session timeout - `plain_http_response`: respond to plain http request with this file (raw TCP) - `curves`: `ECC` curves to use - `dhparam`: if left blank, default (RFC 3526) dhparam will be used, otherwise the specified dhparam file will be used - `tcp`: `TCP` specific configurations - `prefer_ipv4`: whether to connect to the IPv4 address when there are both IPv6 and IPv4 addresses for a domain - `no_delay`: whether to disable Nagle's algorithm - `keep_alive`: whether to enable TCP Keep Alive - `reuse_port`: whether to enable TCP port reuse (kernel support required) - `fast_open`: whether to enable TCP Fast Open (kernel support required) - `fast_open_qlen`: the server's limit on the size of the queue of TFO requests that have not yet completed the three-way handshake - `mysql`: see [Authenticator](authenticator) [Homepage](.) | [Prev Page](protocol) | [Next Page](authenticator) trojan-1.14.1/docs/overview.md000066400000000000000000000006751361237615600162350ustar00rootroot00000000000000# Overview On penetrating GFW, people assume that strong encryption and random obfuscation may cheat GFW's filtration mechanism. However, trojan implements the direct opposite: it imitates the most common protocol across the wall, `HTTPS`, to trick GFW into thinking that it is `HTTPS`. The [next page](protocol) introduces the trojan protocol and how it hides itself from active and passive detections. [Homepage](.) | [Next Page](protocol) trojan-1.14.1/docs/protocol.md000066400000000000000000000075451361237615600162330ustar00rootroot00000000000000# The Trojan Protocol We will now show how a trojan server will react to a **valid Trojan Protocol** and **other protocols** (possibly `HTTPS` or any other probes). ## Valid Trojan Protocol When a trojan client connects to a server, it first performs a **real** `TLS` handshake. If the handshake succeeds, all subsequent traffic will be protected by `TLS`; otherwise, the server will close the connection immediately as any `HTTPS` server would. (Trojan now also supports nginx-like response to plain HTTP requests.) Then the client sends the following structure: ``` +-----------------------+---------+----------------+---------+----------+ | hex(SHA224(password)) | CRLF | Trojan Request | CRLF | Payload | +-----------------------+---------+----------------+---------+----------+ | 56 | X'0D0A' | Variable | X'0D0A' | Variable | +-----------------------+---------+----------------+---------+----------+ where Trojan Request is a SOCKS5-like request: +-----+------+----------+----------+ | CMD | ATYP | DST.ADDR | DST.PORT | +-----+------+----------+----------+ | 1 | 1 | Variable | 2 | +-----+------+----------+----------+ where: o CMD o CONNECT X'01' o UDP ASSOCIATE X'03' o ATYP address type of following address o IP V4 address: X'01' o DOMAINNAME: X'03' o IP V6 address: X'04' o DST.ADDR desired destination address o DST.PORT desired destination port in network octet order ``` More information on `SOCKS5` requests can be found [here](https://tools.ietf.org/html/rfc1928). If the connection is a `UDP ASSOCIATE`, then each `UDP` packet has the following format: ``` +------+----------+----------+--------+---------+----------+ | ATYP | DST.ADDR | DST.PORT | Length | CRLF | Payload | +------+----------+----------+--------+---------+----------+ | 1 | Variable | 2 | 2 | X'0D0A' | Variable | +------+----------+----------+--------+---------+----------+ ``` When the server receives the first data packet, it checks if the hashed password is correct and the Trojan Request is valid. If not, the protocol is considered "other protocols" (see next section). Note that the first packet will have payload appended. This avoids length pattern detection and may reduce the number of packets to be sent. If the request is valid, the trojan server connects to the endpoint indicated by the `DST.ADDR` and `DST.PORT` field and opens a direct tunnel between the endpoint and trojan client. (Trojan client is simply a Trojan Protocol-`SOCKS5` converter. There is no detail worth illustrating.) ## Other Protocols Because typically a trojan server is to be assumed to be an `HTTPS` server, the listening socket is always a `TLS` socket. After performing `TLS` handshake, if the trojan server decides that the traffic is "other protocols", it opens a tunnel between a preset endpoint (by default it is `127.0.0.1:80`, the local `HTTP` server) to the client so the preset endpoint takes the control of the decrypted `TLS` traffic. ## Anti-detection ### Active Detection All connection without correct structure and password will be redirected to a preset endpoint, so the trojan server behaves exactly the same as that endpoint (by default `HTTP`) if a suspicious probe connects (or just a fan of you connecting to your blog XD). ### Passive Detection Because the traffic is protected by `TLS` (it is users' responsibility to use a valid certificate), if you are visiting an `HTTP` site, the traffic looks the same as `HTTPS` (there is only one `RTT` after `TLS` handshake); if you are not visiting an `HTTP` site, then the traffic looks the same as `HTTPS` kept alive or `WebSocket`. Because of this, trojan can also bypass ISP `QoS` limitations. For more information, go to [Issue #14](https://github.com/trojan-gfw/trojan/issues/14). [Homepage](.) | [Prev Page](overview) | [Next Page](config) trojan-1.14.1/docs/trojan.1000066400000000000000000000021471361237615600154200ustar00rootroot00000000000000.TH TROJAN 1 "January 2020" "version 1.14.1" .SH NAME trojan \- an unidentifiable mechanism that helps you bypass GFW .SH SYNOPSIS .B trojan [\fB\-htv\fR] [\fB\-l\fR \fILOG\fR] [\fB\-k\fR \fIKEYLOG\fR] [[\fB\-c\fR] \fICONFIG\fR] .SH DESCRIPTION .B trojan is an unidentifiable mechanism that helps you bypass GFW. It will load the config file located in .I CONFIG and start either a proxy client or a proxy server. .SH OPTIONS .TP .BR \-c, " " \-\-config=\fICONFIG\fR Set the config file to be loaded. Default is \fI/etc/trojan/config.json\fR. .TP .BR \-h, " " \-\-help Print help message. .TP .BR \-k, " " \-\-keylog=\fIKEYLOG\fR Set the keylog file to be written. .TP .BR \-l, " " \-\-log=\fILOG\fR Set the log file to be written. If not specified, the log will be outputted to stderr. .TP .BR \-t, " " \-\-test Test the config file, without starting a server. .TP .BR \-v, " " \-\-version Print version and build info. .SH FILES .TP .IR /etc/trojan/config.json The default config file. See for details. .SH SEE ALSO Full documentation at: trojan-1.14.1/docs/usage.md000066400000000000000000000035711361237615600154710ustar00rootroot00000000000000# Usage ``` usage: ./trojan [-htv] [-l LOG] [-k KEYLOG] [[-c] CONFIG] options: -c [ --config ] CONFIG specify config file -h [ --help ] print help message -k [ --keylog ] KEYLOG specify keylog file location (OpenSSL >= 1.1.1) -l [ --log ] LOG specify log file location -t [ --test ] test config file -v [ --version ] print version and build info ``` The default value for CONFIG is where the default config is installed on Linux and other UNIX-like systems and `config.json` on Windows. On Linux and other UNIX-like systems, the behavior of the handlers for the following signals are overridden: - `SIGHUP`: Upon receiving `SIGHUP`, trojan will stop the service, reload the config, and restart the service. All existing connections are dropped. As a side effect, if trojan is left in the background of a shell, it will not exit when the shell exits. - `SIGUSR1`: Upon receiving `SIGUSR1`, trojan will reload the certificate and private key of the `SSL` server. No existing connections are dropped, and the new certificate doesn't affect these connections. Make sure your [config file](config) is valid. Configuring trojan is not trivial: there are several ideas you need to understand and several pitfalls you might fall into. Unless you are an expert, you shouldn't configure a trojan server all by yourself. Here, we will present a list of things you should do before you start a trojan server: - setup an `HTTP` server and make it useful in some sense (to deceive `GFW`). - register a domain name for your server. - Apply for or self-sign (**NOT RECOMMENDED**) an `SSL` certificate. - Correctly write the [config file](config). [Shadowsocks SIP003](https://shadowsocks.org/en/spec/Plugin.html) is supported by trojan, but it is added as an experimental feature and is not standard at all, so it will not be documented here. [Homepage](.) | [Prev Page](build) trojan-1.14.1/examples/000077500000000000000000000000001361237615600147235ustar00rootroot00000000000000trojan-1.14.1/examples/client.json-example000066400000000000000000000021101361237615600205170ustar00rootroot00000000000000{ "run_type": "client", "local_addr": "127.0.0.1", "local_port": 1080, "remote_addr": "example.com", "remote_port": 443, "password": [ "password1" ], "log_level": 1, "ssl": { "verify": true, "verify_hostname": true, "cert": "", "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA", "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", "sni": "", "alpn": [ "h2", "http/1.1" ], "reuse_session": true, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } trojan-1.14.1/examples/forward.json-example000066400000000000000000000022311361237615600207110ustar00rootroot00000000000000{ "run_type": "forward", "local_addr": "127.0.0.1", "local_port": 5901, "remote_addr": "example.com", "remote_port": 443, "target_addr": "127.0.0.1", "target_port": 5901, "password": [ "password1" ], "udp_timeout": 60, "log_level": 1, "ssl": { "verify": true, "verify_hostname": true, "cert": "", "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA", "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", "sni": "", "alpn": [ "h2", "http/1.1" ], "reuse_session": true, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } trojan-1.14.1/examples/nat.json-example000066400000000000000000000021061361237615600200300ustar00rootroot00000000000000{ "run_type": "nat", "local_addr": "127.0.0.1", "local_port": 12345, "remote_addr": "example.com", "remote_port": 443, "password": [ "password1" ], "log_level": 1, "ssl": { "verify": true, "verify_hostname": true, "cert": "", "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA", "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", "sni": "", "alpn": [ "h2", "http/1.1" ], "reuse_session": true, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } trojan-1.14.1/examples/server.json-example000066400000000000000000000025111361237615600205540ustar00rootroot00000000000000{ "run_type": "server", "local_addr": "0.0.0.0", "local_port": 443, "remote_addr": "127.0.0.1", "remote_port": 80, "password": [ "password1", "password2" ], "log_level": 1, "ssl": { "cert": "/path/to/certificate.crt", "key": "/path/to/private.key", "key_password": "", "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384", "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", "prefer_server_cipher": true, "alpn": [ "http/1.1" ], "reuse_session": true, "session_ticket": false, "session_timeout": 600, "plain_http_response": "", "curves": "", "dhparam": "" }, "tcp": { "prefer_ipv4": false, "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 }, "mysql": { "enabled": false, "server_addr": "127.0.0.1", "server_port": 3306, "database": "trojan", "username": "trojan", "password": "" } } trojan-1.14.1/examples/trojan.service-example000066400000000000000000000010431361237615600212310ustar00rootroot00000000000000[Unit] Description=trojan Documentation=man:trojan(1) https://trojan-gfw.github.io/trojan/config https://trojan-gfw.github.io/trojan/ After=network.target network-online.target nss-lookup.target mysql.service mariadb.service mysqld.service [Service] Type=simple StandardError=journal User=nobody AmbientCapabilities=CAP_NET_BIND_SERVICE ExecStart=@CMAKE_INSTALL_FULL_BINDIR@/trojan @CMAKE_INSTALL_FULL_SYSCONFDIR@/trojan/@CONFIG_NAME@.json ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure RestartSec=3s [Install] WantedBy=multi-user.target trojan-1.14.1/src/000077500000000000000000000000001361237615600136745ustar00rootroot00000000000000trojan-1.14.1/src/core/000077500000000000000000000000001361237615600146245ustar00rootroot00000000000000trojan-1.14.1/src/core/authenticator.cpp000066400000000000000000000073021361237615600202040ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "authenticator.h" #include #include using namespace std; #ifdef ENABLE_MYSQL Authenticator::Authenticator(const Config &config) { mysql_init(&con); Log::log_with_date_time("connecting to MySQL server " + config.mysql.server_addr + ':' + to_string(config.mysql.server_port), Log::INFO); if (mysql_real_connect(&con, config.mysql.server_addr.c_str(), config.mysql.username.c_str(), config.mysql.password.c_str(), config.mysql.database.c_str(), config.mysql.server_port, NULL, 0) == NULL) { throw runtime_error(mysql_error(&con)); } bool reconnect = 1; mysql_options(&con, MYSQL_OPT_RECONNECT, &reconnect); Log::log_with_date_time("connected to MySQL server", Log::INFO); } bool Authenticator::auth(const string &password) { if (!is_valid_password(password)) { return false; } if (mysql_query(&con, ("SELECT quota, download + upload FROM users WHERE password = '" + password + '\'').c_str())) { Log::log_with_date_time(mysql_error(&con), Log::ERROR); return false; } MYSQL_RES *res = mysql_store_result(&con); if (res == NULL) { Log::log_with_date_time(mysql_error(&con), Log::ERROR); return false; } MYSQL_ROW row = mysql_fetch_row(res); if (row == NULL) { mysql_free_result(res); return false; } int64_t quota = atoll(row[0]); int64_t used = atoll(row[1]); mysql_free_result(res); if (quota < 0) { return true; } if (used >= quota) { Log::log_with_date_time(password + " ran out of quota", Log::WARN); return false; } return true; } void Authenticator::record(const std::string &password, uint64_t download, uint64_t upload) { if (!is_valid_password(password)) { return; } if (mysql_query(&con, ("UPDATE users SET download = download + " + to_string(download) + ", upload = upload + " + to_string(upload) + " WHERE password = '" + password + '\'').c_str())) { Log::log_with_date_time(mysql_error(&con), Log::ERROR); } } bool Authenticator::is_valid_password(const std::string &password) { if (password.size() != PASSWORD_LENGTH) { return false; } for (size_t i = 0; i < PASSWORD_LENGTH; ++i) { if (!((password[i] >= '0' && password[i] <= '9') || (password[i] >= 'a' && password[i] <= 'f'))) { return false; } } return true; } Authenticator::~Authenticator() { mysql_close(&con); } #else // ENABLE_MYSQL Authenticator::Authenticator(const Config&) {} bool Authenticator::auth(const string&) { return true; } void Authenticator::record(const std::string&, uint64_t, uint64_t) {} bool Authenticator::is_valid_password(const std::string&) { return true; } Authenticator::~Authenticator() {} #endif // ENABLE_MYSQL trojan-1.14.1/src/core/authenticator.h000066400000000000000000000025351361237615600176540ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _AUTHENTICATOR_H_ #define _AUTHENTICATOR_H_ #ifdef ENABLE_MYSQL #include #endif // ENABLE_MYSQL #include "config.h" class Authenticator { private: #ifdef ENABLE_MYSQL MYSQL con; #endif // ENABLE_MYSQL enum { PASSWORD_LENGTH=56 }; bool is_valid_password(const std::string &password); public: Authenticator(const Config &config); bool auth(const std::string &password); void record(const std::string &password, uint64_t download, uint64_t upload); ~Authenticator(); }; #endif // _AUTHENTICATOR_H_ trojan-1.14.1/src/core/config.cpp000066400000000000000000000122541361237615600166010ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "config.h" #include #include #include #include #include using namespace std; using namespace boost::property_tree; void Config::load(const string &filename) { ptree tree; read_json(filename, tree); populate(tree); } void Config::populate(const std::string &JSON) { istringstream s(JSON); ptree tree; read_json(s, tree); populate(tree); } void Config::populate(const ptree &tree) { string rt = tree.get("run_type", string("client")); if (rt == "server") { run_type = SERVER; } else if (rt == "forward") { run_type = FORWARD; } else if (rt == "nat") { run_type = NAT; } else if (rt == "client") { run_type = CLIENT; } else { throw runtime_error("wrong run_type in config file"); } local_addr = tree.get("local_addr", string()); local_port = tree.get("local_port", uint16_t()); remote_addr = tree.get("remote_addr", string()); remote_port = tree.get("remote_port", uint16_t()); target_addr = tree.get("target_addr", string()); target_port = tree.get("target_port", uint16_t()); map().swap(password); for (auto& item: tree.get_child("password")) { string p = item.second.get_value(); password[SHA224(p)] = p; } udp_timeout = tree.get("udp_timeout", 60); log_level = static_cast(tree.get("log_level", 1)); ssl.verify = tree.get("ssl.verify", true); ssl.verify_hostname = tree.get("ssl.verify_hostname", true); ssl.cert = tree.get("ssl.cert", string()); ssl.key = tree.get("ssl.key", string()); ssl.key_password = tree.get("ssl.key_password", string()); ssl.cipher = tree.get("ssl.cipher", string()); ssl.cipher_tls13 = tree.get("ssl.cipher_tls13", string()); ssl.prefer_server_cipher = tree.get("ssl.prefer_server_cipher", true); ssl.sni = tree.get("ssl.sni", string()); ssl.alpn = ""; for (auto& item: tree.get_child("ssl.alpn")) { string proto = item.second.get_value(); ssl.alpn += (char)((unsigned char)(proto.length())); ssl.alpn += proto; } ssl.reuse_session = tree.get("ssl.reuse_session", true); ssl.session_ticket = tree.get("ssl.session_ticket", false); ssl.session_timeout = tree.get("ssl.session_timeout", long(600)); ssl.plain_http_response = tree.get("ssl.plain_http_response", string()); ssl.curves = tree.get("ssl.curves", string()); ssl.dhparam = tree.get("ssl.dhparam", string()); tcp.prefer_ipv4 = tree.get("tcp.prefer_ipv4", false); tcp.no_delay = tree.get("tcp.no_delay", true); tcp.keep_alive = tree.get("tcp.keep_alive", true); tcp.reuse_port = tree.get("tcp.reuse_port", false); tcp.fast_open = tree.get("tcp.fast_open", false); tcp.fast_open_qlen = tree.get("tcp.fast_open_qlen", 20); mysql.enabled = tree.get("mysql.enabled", false); mysql.server_addr = tree.get("mysql.server_addr", string("127.0.0.1")); mysql.server_port = tree.get("mysql.server_port", uint16_t(3306)); mysql.database = tree.get("mysql.database", string("trojan")); mysql.username = tree.get("mysql.username", string("trojan")); mysql.password = tree.get("mysql.password", string()); } bool Config::sip003() { char *JSON = getenv("SS_PLUGIN_OPTIONS"); if (JSON == NULL) { return false; } populate(JSON); switch (run_type) { case SERVER: local_addr = getenv("SS_REMOTE_HOST"); local_port = atoi(getenv("SS_REMOTE_PORT")); break; case CLIENT: case NAT: throw runtime_error("SIP003 with wrong run_type"); break; case FORWARD: remote_addr = getenv("SS_REMOTE_HOST"); remote_port = atoi(getenv("SS_REMOTE_PORT")); local_addr = getenv("SS_LOCAL_HOST"); local_port = atoi(getenv("SS_LOCAL_PORT")); break; } return true; } string Config::SHA224(const string &message) { uint8_t digest[SHA224_DIGEST_LENGTH]; SHA256_CTX ctx; SHA224_Init(&ctx); SHA224_Update(&ctx, message.c_str(), message.length()); SHA224_Final(digest, &ctx); char mdString[(SHA224_DIGEST_LENGTH << 1) + 1]; for (int i = 0; i < SHA224_DIGEST_LENGTH; ++i) { sprintf(mdString + (i << 1), "%02x", (unsigned int)digest[i]); } return string(mdString); } trojan-1.14.1/src/core/config.h000066400000000000000000000047311361237615600162470ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _CONFIG_H_ #define _CONFIG_H_ #include #include #include #include "log.h" class Config { public: enum RunType { SERVER, CLIENT, FORWARD, NAT } run_type; std::string local_addr; uint16_t local_port; std::string remote_addr; uint16_t remote_port; std::string target_addr; uint16_t target_port; std::map password; int udp_timeout; Log::Level log_level; class SSLConfig { public: bool verify; bool verify_hostname; std::string cert; std::string key; std::string key_password; std::string cipher; std::string cipher_tls13; bool prefer_server_cipher; std::string sni; std::string alpn; bool reuse_session; bool session_ticket; long session_timeout; std::string plain_http_response; std::string curves; std::string dhparam; } ssl; class TCPConfig { public: bool prefer_ipv4; bool no_delay; bool keep_alive; bool reuse_port; bool fast_open; int fast_open_qlen; } tcp; class MySQLConfig { public: bool enabled; std::string server_addr; uint16_t server_port; std::string database; std::string username; std::string password; } mysql; void load(const std::string &filename); void populate(const std::string &JSON); bool sip003(); static std::string SHA224(const std::string &message); private: void populate(const boost::property_tree::ptree &tree); }; #endif // _CONFIG_H_ trojan-1.14.1/src/core/log.cpp000066400000000000000000000057661361237615600161270ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "log.h" #include #include #include #include #include #include #ifdef ENABLE_ANDROID_LOG #include #endif // ENABLE_ANDROID_LOG using namespace std; using namespace boost::posix_time; using namespace boost::asio::ip; Log::Level Log::level(INFO); FILE *Log::keylog(NULL); FILE *Log::output_stream(stderr); void Log::log(const string &message, Level level) { if (level >= Log::level) { #ifdef ENABLE_ANDROID_LOG __android_log_print(ANDROID_LOG_ERROR, "trojan", "%s\n", message.c_str()); #else fprintf(output_stream, "%s\n", message.c_str()); fflush(output_stream); #endif // ENABLE_ANDROID_LOG } } void Log::log_with_date_time(const string &message, Level level) { static const char *level_strings[]= {"ALL", "INFO", "WARN", "ERROR", "FATAL", "OFF"}; time_facet *facet = new time_facet("[%Y-%m-%d %H:%M:%S] "); ostringstream stream; stream.imbue(locale(stream.getloc(), facet)); stream << second_clock::local_time(); string level_string = '[' + string(level_strings[level]) + "] "; log(stream.str() + level_string + message, level); } void Log::log_with_endpoint(const tcp::endpoint &endpoint, const string &message, Level level) { log_with_date_time(endpoint.address().to_string() + ':' + to_string(endpoint.port()) + ' ' + message, level); } void Log::redirect(const string &filename) { FILE *fp = fopen(filename.c_str(), "a"); if (fp == NULL) { throw runtime_error(filename + ": " + strerror(errno)); } if (output_stream != stderr) { fclose(output_stream); } output_stream = fp; } void Log::redirect_keylog(const string &filename) { FILE *fp = fopen(filename.c_str(), "a"); if (fp == NULL) { throw runtime_error(filename + ": " + strerror(errno)); } if (keylog != NULL) { fclose(keylog); } keylog = fp; } void Log::reset() { if (output_stream != stderr) { fclose(output_stream); output_stream = stderr; } if (keylog != NULL) { fclose(keylog); keylog = NULL; } } trojan-1.14.1/src/core/log.h000066400000000000000000000031761361237615600155650ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _LOG_H_ #define _LOG_H_ #include #include #include #ifdef ERROR // windows.h #undef ERROR #endif // ERROR class Log { public: enum Level { ALL = 0, INFO = 1, WARN = 2, ERROR = 3, FATAL = 4, OFF = 5 }; static Level level; static FILE *keylog; static void log(const std::string &message, Level level = ALL); static void log_with_date_time(const std::string &message, Level level = ALL); static void log_with_endpoint(const boost::asio::ip::tcp::endpoint &endpoint, const std::string &message, Level level = ALL); static void redirect(const std::string &filename); static void redirect_keylog(const std::string &filename); static void reset(); private: static FILE *output_stream; }; #endif // _LOG_H_ trojan-1.14.1/src/core/service.cpp000066400000000000000000000377261361237615600170070ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "service.h" #include #include #include #include #ifdef _WIN32 #include #include #endif // _WIN32 #ifdef __APPLE__ #include #endif // __APPLE__ #include #include "session/serversession.h" #include "session/clientsession.h" #include "session/forwardsession.h" #include "session/natsession.h" #include "ssl/ssldefaults.h" #include "ssl/sslsession.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; #ifdef ENABLE_REUSE_PORT typedef boost::asio::detail::socket_option::boolean reuse_port; #endif // ENABLE_REUSE_PORT Service::Service(Config &config, bool test) : config(config), socket_acceptor(io_context), ssl_context(context::sslv23), auth(nullptr), udp_socket(io_context) { #ifndef ENABLE_NAT if (config.run_type == Config::NAT) { throw runtime_error("NAT is not supported"); } #endif // ENABLE_NAT if (!test) { tcp::resolver resolver(io_context); tcp::endpoint listen_endpoint = *resolver.resolve(config.local_addr, to_string(config.local_port)).begin(); socket_acceptor.open(listen_endpoint.protocol()); socket_acceptor.set_option(tcp::acceptor::reuse_address(true)); if (config.tcp.reuse_port) { #ifdef ENABLE_REUSE_PORT socket_acceptor.set_option(reuse_port(true)); #else // ENABLE_REUSE_PORT Log::log_with_date_time("SO_REUSEPORT is not supported", Log::WARN); #endif // ENABLE_REUSE_PORT } socket_acceptor.bind(listen_endpoint); socket_acceptor.listen(); if (config.run_type == Config::FORWARD) { auto udp_bind_endpoint = udp::endpoint(listen_endpoint.address(), listen_endpoint.port()); udp_socket.open(udp_bind_endpoint.protocol()); udp_socket.bind(udp_bind_endpoint); } } Log::level = config.log_level; auto native_context = ssl_context.native_handle(); ssl_context.set_options(context::default_workarounds | context::no_sslv2 | context::no_sslv3 | context::single_dh_use); if (config.ssl.curves != "") { SSL_CTX_set1_curves_list(native_context, config.ssl.curves.c_str()); } if (config.run_type == Config::SERVER) { ssl_context.use_certificate_chain_file(config.ssl.cert); ssl_context.set_password_callback([this](size_t, context_base::password_purpose) { return this->config.ssl.key_password; }); ssl_context.use_private_key_file(config.ssl.key, context::pem); if (config.ssl.prefer_server_cipher) { SSL_CTX_set_options(native_context, SSL_OP_CIPHER_SERVER_PREFERENCE); } if (config.ssl.alpn != "") { SSL_CTX_set_alpn_select_cb(native_context, [](SSL*, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *config) -> int { if (SSL_select_next_proto((unsigned char**)out, outlen, (unsigned char*)(((Config*)config)->ssl.alpn.c_str()), ((Config*)config)->ssl.alpn.length(), in, inlen) != OPENSSL_NPN_NEGOTIATED) { return SSL_TLSEXT_ERR_NOACK; } return SSL_TLSEXT_ERR_OK; }, &config); } if (config.ssl.reuse_session) { SSL_CTX_set_timeout(native_context, config.ssl.session_timeout); if (!config.ssl.session_ticket) { SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET); } } else { SSL_CTX_set_session_cache_mode(native_context, SSL_SESS_CACHE_OFF); SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET); } if (config.ssl.plain_http_response != "") { ifstream ifs(config.ssl.plain_http_response, ios::binary); if (!ifs.is_open()) { throw runtime_error(config.ssl.plain_http_response + ": " + strerror(errno)); } plain_http_response = string(istreambuf_iterator(ifs), istreambuf_iterator()); } if (config.ssl.dhparam == "") { ssl_context.use_tmp_dh(boost::asio::const_buffer(SSLDefaults::g_dh2048_sz, SSLDefaults::g_dh2048_sz_size)); } else { ssl_context.use_tmp_dh_file(config.ssl.dhparam); } if (config.mysql.enabled) { #ifdef ENABLE_MYSQL auth = new Authenticator(config); #else // ENABLE_MYSQL Log::log_with_date_time("MySQL is not supported", Log::WARN); #endif // ENABLE_MYSQL } } else { if (config.ssl.sni == "") { config.ssl.sni = config.remote_addr; } if (config.ssl.verify) { ssl_context.set_verify_mode(verify_peer); if (config.ssl.cert == "") { ssl_context.set_default_verify_paths(); #ifdef _WIN32 HCERTSTORE h_store = CertOpenSystemStore(0, _T("ROOT")); if (h_store) { X509_STORE *store = SSL_CTX_get_cert_store(native_context); PCCERT_CONTEXT p_context = NULL; while ((p_context = CertEnumCertificatesInStore(h_store, p_context))) { const unsigned char *encoded_cert = p_context->pbCertEncoded; X509 *x509 = d2i_X509(NULL, &encoded_cert, p_context->cbCertEncoded); if (x509) { X509_STORE_add_cert(store, x509); X509_free(x509); } } CertCloseStore(h_store, 0); } #endif // _WIN32 #ifdef __APPLE__ SecKeychainSearchRef pSecKeychainSearch = NULL; SecKeychainRef pSecKeychain; OSStatus status = noErr; X509 *cert = NULL; // Leopard and above store location status = SecKeychainOpen ("/System/Library/Keychains/SystemRootCertificates.keychain", &pSecKeychain); if (status == noErr) { X509_STORE *store = SSL_CTX_get_cert_store(native_context); status = SecKeychainSearchCreateFromAttributes (pSecKeychain, kSecCertificateItemClass, NULL, &pSecKeychainSearch); for (;;) { SecKeychainItemRef pSecKeychainItem = nil; status = SecKeychainSearchCopyNext (pSecKeychainSearch, &pSecKeychainItem); if (status == errSecItemNotFound) { break; } if (status == noErr) { void *_pCertData; UInt32 _pCertLength; status = SecKeychainItemCopyAttributesAndData (pSecKeychainItem, NULL, NULL, NULL, &_pCertLength, &_pCertData); if (status == noErr && _pCertData != NULL) { unsigned char *ptr; ptr = (unsigned char *)_pCertData; /*required because d2i_X509 is modifying pointer */ cert = d2i_X509 (NULL, (const unsigned char **) &ptr, _pCertLength); if (cert == NULL) { continue; } if (!X509_STORE_add_cert (store, cert)) { X509_free (cert); continue; } X509_free (cert); status = SecKeychainItemFreeAttributesAndData (NULL, _pCertData); } } if (pSecKeychainItem != NULL) { CFRelease (pSecKeychainItem); } } CFRelease (pSecKeychainSearch); CFRelease (pSecKeychain); } #endif // __APPLE__ } else { ssl_context.load_verify_file(config.ssl.cert); } if (config.ssl.verify_hostname) { ssl_context.set_verify_callback(rfc2818_verification(config.ssl.sni)); } X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new(); X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_PARTIAL_CHAIN); SSL_CTX_set1_param(native_context, param); X509_VERIFY_PARAM_free(param); } else { ssl_context.set_verify_mode(verify_none); } if (config.ssl.alpn != "") { SSL_CTX_set_alpn_protos(native_context, (unsigned char*)(config.ssl.alpn.c_str()), config.ssl.alpn.length()); } if (config.ssl.reuse_session) { SSL_CTX_set_session_cache_mode(native_context, SSL_SESS_CACHE_CLIENT); SSLSession::set_callback(native_context); if (!config.ssl.session_ticket) { SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET); } } else { SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET); } } if (config.ssl.cipher != "") { SSL_CTX_set_cipher_list(native_context, config.ssl.cipher.c_str()); } if (config.ssl.cipher_tls13 != "") { #ifdef ENABLE_TLS13_CIPHERSUITES SSL_CTX_set_ciphersuites(native_context, config.ssl.cipher_tls13.c_str()); #else // ENABLE_TLS13_CIPHERSUITES Log::log_with_date_time("TLS1.3 ciphersuites are not supported", Log::WARN); #endif // ENABLE_TLS13_CIPHERSUITES } if (!test) { if (config.tcp.no_delay) { socket_acceptor.set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { socket_acceptor.set_option(boost::asio::socket_base::keep_alive(true)); } if (config.tcp.fast_open) { #ifdef TCP_FASTOPEN using fastopen = boost::asio::detail::socket_option::integer; boost::system::error_code ec; socket_acceptor.set_option(fastopen(config.tcp.fast_open_qlen), ec); #else // TCP_FASTOPEN Log::log_with_date_time("TCP_FASTOPEN is not supported", Log::WARN); #endif // TCP_FASTOPEN #ifndef TCP_FASTOPEN_CONNECT Log::log_with_date_time("TCP_FASTOPEN_CONNECT is not supported", Log::WARN); #endif // TCP_FASTOPEN_CONNECT } } if (Log::keylog) { #ifdef ENABLE_SSL_KEYLOG SSL_CTX_set_keylog_callback(native_context, [](const SSL*, const char *line) { fprintf(Log::keylog, "%s\n", line); fflush(Log::keylog); }); #else // ENABLE_SSL_KEYLOG Log::log_with_date_time("SSL KeyLog is not supported", Log::WARN); #endif // ENABLE_SSL_KEYLOG } } void Service::run() { async_accept(); if (config.run_type == Config::FORWARD) { udp_async_read(); } tcp::endpoint local_endpoint = socket_acceptor.local_endpoint(); string rt; if (config.run_type == Config::SERVER) { rt = "server"; } else if (config.run_type == Config::FORWARD) { rt = "forward"; } else if (config.run_type == Config::NAT) { rt = "nat"; } else { rt = "client"; } Log::log_with_date_time(string("trojan service (") + rt + ") started at " + local_endpoint.address().to_string() + ':' + to_string(local_endpoint.port()), Log::WARN); io_context.run(); Log::log_with_date_time("trojan service stopped", Log::WARN); } void Service::stop() { boost::system::error_code ec; socket_acceptor.cancel(ec); if (udp_socket.is_open()) { udp_socket.cancel(ec); udp_socket.close(ec); } io_context.stop(); } void Service::async_accept() { shared_ptrsession(nullptr); if (config.run_type == Config::SERVER) { session = make_shared(config, io_context, ssl_context, auth, plain_http_response); } else if (config.run_type == Config::FORWARD) { session = make_shared(config, io_context, ssl_context); } else if (config.run_type == Config::NAT) { session = make_shared(config, io_context, ssl_context); } else { session = make_shared(config, io_context, ssl_context); } socket_acceptor.async_accept(session->accept_socket(), [this, session](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { // got cancel signal, stop calling myself return; } if (!error) { boost::system::error_code ec; auto endpoint = session->accept_socket().remote_endpoint(ec); if (!ec) { Log::log_with_endpoint(endpoint, "incoming connection"); session->start(); } } async_accept(); }); } void Service::udp_async_read() { udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { // got cancel signal, stop calling myself return; } if (error) { stop(); throw runtime_error(error.message()); } string data((const char *)udp_read_buf, length); for (auto it = udp_sessions.begin(); it != udp_sessions.end();) { auto next = ++it; --it; if (it->expired()) { udp_sessions.erase(it); } else if (it->lock()->process(udp_recv_endpoint, data)) { udp_async_read(); return; } it = next; } Log::log_with_endpoint(tcp::endpoint(udp_recv_endpoint.address(), udp_recv_endpoint.port()), "new UDP session"); auto session = make_shared(config, io_context, ssl_context, udp_recv_endpoint, [this](const udp::endpoint &endpoint, const string &data) { boost::system::error_code ec; udp_socket.send_to(boost::asio::buffer(data), endpoint, 0, ec); if (ec == boost::asio::error::no_permission) { Log::log_with_endpoint(tcp::endpoint(endpoint.address(), endpoint.port()), "dropped a UDP packet due to firewall policy or rate limit"); } else if (ec) { throw runtime_error(ec.message()); } }); udp_sessions.emplace_back(session); session->start(); session->process(udp_recv_endpoint, data); udp_async_read(); }); } boost::asio::io_context &Service::service() { return io_context; } void Service::reload_cert() { if (config.run_type == Config::SERVER) { Log::log_with_date_time("reloading certificate and private key. . . ", Log::WARN); ssl_context.use_certificate_chain_file(config.ssl.cert); ssl_context.use_private_key_file(config.ssl.key, context::pem); boost::system::error_code ec; socket_acceptor.cancel(ec); async_accept(); Log::log_with_date_time("certificate and private key reloaded", Log::WARN); } else { Log::log_with_date_time("cannot reload certificate and private key: wrong run_type", Log::ERROR); } } Service::~Service() { if (auth) { delete auth; auth = nullptr; } } trojan-1.14.1/src/core/service.h000066400000000000000000000033641361237615600164430ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _SERVICE_H_ #define _SERVICE_H_ #include #include #include #include #include "authenticator.h" #include "session/udpforwardsession.h" class Service { private: enum { MAX_LENGTH = 8192 }; const Config &config; boost::asio::io_context io_context; boost::asio::ip::tcp::acceptor socket_acceptor; boost::asio::ssl::context ssl_context; Authenticator *auth; std::string plain_http_response; boost::asio::ip::udp::socket udp_socket; std::list > udp_sessions; uint8_t udp_read_buf[MAX_LENGTH]; boost::asio::ip::udp::endpoint udp_recv_endpoint; void async_accept(); void udp_async_read(); public: Service(Config &config, bool test = false); void run(); void stop(); boost::asio::io_context &service(); void reload_cert(); ~Service(); }; #endif // _SERVICE_H_ trojan-1.14.1/src/core/version.cpp000066400000000000000000000016741361237615600170250ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "version.h" using namespace std; const string Version::version("1.14.1"); string Version::get_version() { return version; } trojan-1.14.1/src/core/version.h000066400000000000000000000017641361237615600164720ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _VERSION_H_ #define _VERSION_H_ #include class Version { private: const static std::string version; public: static std::string get_version(); }; #endif // _VERSION_H_ trojan-1.14.1/src/main.cpp000066400000000000000000000150151361237615600153260ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include #include #include #include #include #include #ifdef ENABLE_MYSQL #include #endif // ENABLE_MYSQL #include "core/service.h" #include "core/version.h" using namespace std; using namespace boost::asio; namespace po = boost::program_options; #ifndef DEFAULT_CONFIG #define DEFAULT_CONFIG "config.json" #endif // DEFAULT_CONFIG void signal_async_wait(signal_set &sig, Service &service, bool &restart) { sig.async_wait([&](const boost::system::error_code error, int signum) { if (error) { return; } Log::log_with_date_time("got signal: " + to_string(signum), Log::WARN); switch (signum) { case SIGINT: case SIGTERM: service.stop(); break; #ifndef _WIN32 case SIGHUP: restart = true; service.stop(); break; case SIGUSR1: service.reload_cert(); signal_async_wait(sig, service, restart); break; #endif // _WIN32 } }); } int main(int argc, const char *argv[]) { try { Log::log("Welcome to trojan " + Version::get_version(), Log::FATAL); string config_file; string log_file; string keylog_file; bool test; po::options_description desc("options"); desc.add_options() ("config,c", po::value(&config_file)->default_value(DEFAULT_CONFIG)->value_name("CONFIG"), "specify config file") ("help,h", "print help message") ("keylog,k", po::value(&keylog_file)->value_name("KEYLOG"), "specify keylog file location (OpenSSL >= 1.1.1)") ("log,l", po::value(&log_file)->value_name("LOG"), "specify log file location") ("test,t", po::bool_switch(&test), "test config file") ("version,v", "print version and build info") ; po::positional_options_description pd; pd.add("config", 1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(pd).run(), vm); po::notify(vm); if (vm.count("help")) { Log::log(string("usage: ") + argv[0] + " [-htv] [-l LOG] [-k KEYLOG] [[-c] CONFIG]", Log::FATAL); cerr << desc; exit(EXIT_SUCCESS); } if (vm.count("version")) { Log::log(string("Boost ") + BOOST_LIB_VERSION + ", " + OpenSSL_version(OPENSSL_VERSION), Log::FATAL); #ifdef ENABLE_MYSQL Log::log(string(" [Enabled] MySQL Support (") + mysql_get_client_info() + ')', Log::FATAL); #else // ENABLE_MYSQL Log::log("[Disabled] MySQL Support", Log::FATAL); #endif // ENABLE_MYSQL #ifdef TCP_FASTOPEN Log::log(" [Enabled] TCP_FASTOPEN Support", Log::FATAL); #else // TCP_FASTOPEN Log::log("[Disabled] TCP_FASTOPEN Support", Log::FATAL); #endif // TCP_FASTOPEN #ifdef TCP_FASTOPEN_CONNECT Log::log(" [Enabled] TCP_FASTOPEN_CONNECT Support", Log::FATAL); #else // TCP_FASTOPEN_CONNECT Log::log("[Disabled] TCP_FASTOPEN_CONNECT Support", Log::FATAL); #endif // TCP_FASTOPEN_CONNECT #if ENABLE_SSL_KEYLOG Log::log(" [Enabled] SSL KeyLog Support", Log::FATAL); #else // ENABLE_SSL_KEYLOG Log::log("[Disabled] SSL KeyLog Support", Log::FATAL); #endif // ENABLE_SSL_KEYLOG #ifdef ENABLE_NAT Log::log(" [Enabled] NAT Support", Log::FATAL); #else // ENABLE_NAT Log::log("[Disabled] NAT Support", Log::FATAL); #endif // ENABLE_NAT #ifdef ENABLE_TLS13_CIPHERSUITES Log::log(" [Enabled] TLS1.3 Ciphersuites Support", Log::FATAL); #else // ENABLE_TLS13_CIPHERSUITES Log::log("[Disabled] TLS1.3 Ciphersuites Support", Log::FATAL); #endif // ENABLE_TLS13_CIPHERSUITES #ifdef ENABLE_REUSE_PORT Log::log(" [Enabled] TCP Port Reuse Support", Log::FATAL); #else // ENABLE_REUSE_PORT Log::log("[Disabled] TCP Port Reuse Support", Log::FATAL); #endif // ENABLE_REUSE_PORT Log::log("OpenSSL Information", Log::FATAL); if (OpenSSL_version_num() != OPENSSL_VERSION_NUMBER) { Log::log(string("\tCompile-time Version: ") + OPENSSL_VERSION_TEXT, Log::FATAL); } Log::log(string("\tBuild Flags: ") + OpenSSL_version(OPENSSL_CFLAGS), Log::FATAL); exit(EXIT_SUCCESS); } if (vm.count("log")) { Log::redirect(log_file); } if (vm.count("keylog")) { Log::redirect_keylog(keylog_file); } bool restart; Config config; do { restart = false; if (config.sip003()) { Log::log_with_date_time("SIP003 is loaded", Log::WARN); } else { config.load(config_file); } Service service(config, test); if (test) { Log::log("The config file looks good.", Log::OFF); exit(EXIT_SUCCESS); } signal_set sig(service.service()); sig.add(SIGINT); sig.add(SIGTERM); #ifndef _WIN32 sig.add(SIGHUP); sig.add(SIGUSR1); #endif // _WIN32 signal_async_wait(sig, service, restart); service.run(); if (restart) { Log::log_with_date_time("trojan service restarting. . . ", Log::WARN); } } while (restart); Log::reset(); exit(EXIT_SUCCESS); } catch (const exception &e) { Log::log_with_date_time(string("fatal: ") + e.what(), Log::FATAL); Log::log_with_date_time("exiting. . . ", Log::FATAL); exit(EXIT_FAILURE); } } trojan-1.14.1/src/proto/000077500000000000000000000000001361237615600150375ustar00rootroot00000000000000trojan-1.14.1/src/proto/socks5address.cpp000066400000000000000000000072311361237615600203230ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "socks5address.h" #include using namespace std; using namespace boost::asio::ip; bool SOCKS5Address::parse(const string &data, size_t &address_len) { if (data.length() == 0 || (data[0] != IPv4 && data[0] != DOMAINNAME && data[0] != IPv6)) { return false; } address_type = static_cast(data[0]); switch (address_type) { case IPv4: { if (data.length() > 4 + 2) { address = to_string(uint8_t(data[1])) + '.' + to_string(uint8_t(data[2])) + '.' + to_string(uint8_t(data[3])) + '.' + to_string(uint8_t(data[4])); port = (uint8_t(data[5]) << 8) | uint8_t(data[6]); address_len = 1 + 4 + 2; return true; } break; } case DOMAINNAME: { uint8_t domain_len = data[1]; if (domain_len == 0) { // invalid domain len break; } if (data.length() > (unsigned int)(1 + domain_len + 2)) { address = data.substr(2, domain_len); port = (uint8_t(data[domain_len + 2]) << 8) | uint8_t(data[domain_len + 3]); address_len = 1 + 1 + domain_len + 2; return true; } break; } case IPv6: { if (data.length() > 16 + 2) { char t[40]; sprintf(t, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x", uint8_t(data[1]), uint8_t(data[2]), uint8_t(data[3]), uint8_t(data[4]), uint8_t(data[5]), uint8_t(data[6]), uint8_t(data[7]), uint8_t(data[8]), uint8_t(data[9]), uint8_t(data[10]), uint8_t(data[11]), uint8_t(data[12]), uint8_t(data[13]), uint8_t(data[14]), uint8_t(data[15]), uint8_t(data[16])); address = t; port = (uint8_t(data[17]) << 8) | uint8_t(data[18]); address_len = 1 + 16 + 2; return true; } break; } } return false; } string SOCKS5Address::generate(const udp::endpoint &endpoint) { if (endpoint.address().is_unspecified()) { return string("\x01\x00\x00\x00\x00\x00\x00", 7); } string ret; if (endpoint.address().is_v4()) { ret += '\x01'; auto ip = endpoint.address().to_v4().to_bytes(); for (int i = 0; i < 4; ++i) { ret += char(ip[i]); } } if (endpoint.address().is_v6()) { ret += '\x04'; auto ip = endpoint.address().to_v6().to_bytes(); for (int i = 0; i < 16; ++i) { ret += char(ip[i]); } } ret += char(uint8_t(endpoint.port() >> 8)); ret += char(uint8_t(endpoint.port() & 0xFF)); return ret; } trojan-1.14.1/src/proto/socks5address.h000066400000000000000000000024141361237615600177660ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _SOCKS5ADDRESS_H_ #define _SOCKS5ADDRESS_H_ #include #include #include class SOCKS5Address { public: enum AddressType { IPv4 = 1, DOMAINNAME = 3, IPv6 = 4 } address_type; std::string address; uint16_t port; bool parse(const std::string &data, size_t &address_len); static std::string generate(const boost::asio::ip::udp::endpoint &endpoint); }; #endif // _SOCKS5ADDRESS_H_ trojan-1.14.1/src/proto/trojanrequest.cpp000066400000000000000000000037171361237615600204610ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "trojanrequest.h" using namespace std; int TrojanRequest::parse(const string &data) { size_t first = data.find("\r\n"); if (first == string::npos) { return -1; } password = data.substr(0, first); payload = data.substr(first + 2); if (payload.length() == 0 || (payload[0] != CONNECT && payload[0] != UDP_ASSOCIATE)) { return -1; } command = static_cast(payload[0]); size_t address_len; bool is_addr_valid = address.parse(payload.substr(1), address_len); if (!is_addr_valid || payload.length() < address_len + 3 || payload.substr(address_len + 1, 2) != "\r\n") { return -1; } payload = payload.substr(address_len + 3); return data.length(); } std::string TrojanRequest::generate(const std::string &password, const std::string &domainname, uint16_t port, bool tcp) { string ret = password + "\r\n"; if (tcp) { ret += '\x01'; } else { ret += '\x03'; } ret += '\x03'; ret += char(uint8_t(domainname.length())); ret += domainname; ret += char(uint8_t(port >> 8)); ret += char(uint8_t(port & 0xFF)); ret += "\r\n"; return ret; } trojan-1.14.1/src/proto/trojanrequest.h000066400000000000000000000023751361237615600201250ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _TROJANREQUEST_H_ #define _TROJANREQUEST_H_ #include "socks5address.h" class TrojanRequest { public: std::string password; enum Command { CONNECT = 1, UDP_ASSOCIATE = 3 } command; SOCKS5Address address; std::string payload; int parse(const std::string &data); static std::string generate(const std::string &password, const std::string &domainname, uint16_t port, bool tcp); }; #endif // _TROJANREQUEST_H_ trojan-1.14.1/src/proto/udppacket.cpp000066400000000000000000000042701361237615600175260ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "udppacket.h" using namespace std; using namespace boost::asio::ip; bool UDPPacket::parse(const string &data, size_t &udp_packet_len) { if (data.length() <= 0) { return false; } size_t address_len; bool is_addr_valid = address.parse(data, address_len); if (!is_addr_valid || data.length() < address_len + 2) { return false; } length = (uint8_t(data[address_len]) << 8) | uint8_t(data[address_len + 1]); if (data.length() < address_len + 4 + length || data.substr(address_len + 2, 2) != "\r\n") { return false; } payload = data.substr(address_len + 4, length); udp_packet_len = address_len + 4 + length; return true; } string UDPPacket::generate(const udp::endpoint &endpoint, const string &payload) { string ret = SOCKS5Address::generate(endpoint); ret += char(uint8_t(payload.length() >> 8)); ret += char(uint8_t(payload.length() & 0xFF)); ret += "\r\n"; ret += payload; return ret; } string UDPPacket::generate(const string &domainname, uint16_t port, const string &payload) { string ret = "\x03"; ret += char(uint8_t(domainname.length())); ret += domainname; ret += char(uint8_t(port >> 8)); ret += char(uint8_t(port & 0xFF)); ret += char(uint8_t(payload.length() >> 8)); ret += char(uint8_t(payload.length() & 0xFF)); ret += "\r\n"; ret += payload; return ret; } trojan-1.14.1/src/proto/udppacket.h000066400000000000000000000024221361237615600171700ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _UDPPACKET_H_ #define _UDPPACKET_H_ #include "socks5address.h" class UDPPacket { public: SOCKS5Address address; uint16_t length; std::string payload; bool parse(const std::string &data, size_t &udp_packet_len); static std::string generate(const boost::asio::ip::udp::endpoint &endpoint, const std::string &payload); static std::string generate(const std::string &domainname, uint16_t port, const std::string &payload); }; #endif // _UDPPACKET_H_ trojan-1.14.1/src/session/000077500000000000000000000000001361237615600153575ustar00rootroot00000000000000trojan-1.14.1/src/session/clientsession.cpp000066400000000000000000000373731361237615600207620ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "clientsession.h" #include "proto/trojanrequest.h" #include "proto/udppacket.h" #include "ssl/sslsession.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; ClientSession::ClientSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) : Session(config, io_context), status(HANDSHAKE), first_packet_recv(false), in_socket(io_context), out_socket(io_context, ssl_context) {} tcp::socket& ClientSession::accept_socket() { return in_socket; } void ClientSession::start() { boost::system::error_code ec; start_time = time(NULL); in_endpoint = in_socket.remote_endpoint(ec); if (ec) { destroy(); return; } auto ssl = out_socket.native_handle(); if (config.ssl.sni != "") { SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str()); } if (config.ssl.reuse_session) { SSL_SESSION *session = SSLSession::get_session(); if (session) { SSL_set_session(ssl, session); } } in_async_read(); } void ClientSession::in_async_read() { auto self = shared_from_this(); in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { return; } if (error) { destroy(); return; } in_recv(string((const char*)in_read_buf, length)); }); } void ClientSession::in_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } in_sent(); }); } void ClientSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void ClientSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void ClientSession::udp_async_read() { auto self = shared_from_this(); udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this, self](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { return; } if (error) { destroy(); return; } udp_recv(string((const char*)udp_read_buf, length), udp_recv_endpoint); }); } void ClientSession::udp_async_write(const string &data, const udp::endpoint &endpoint) { auto self = shared_from_this(); auto data_copy = make_shared(data); udp_socket.async_send_to(boost::asio::buffer(*data_copy), endpoint, [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } udp_sent(); }); } void ClientSession::in_recv(const string &data) { switch (status) { case HANDSHAKE: { if (data.length() < 2 || data[0] != 5 || data.length() != (unsigned int)(unsigned char)data[1] + 2) { Log::log_with_endpoint(in_endpoint, "unknown protocol", Log::ERROR); destroy(); return; } bool has_method = false; for (int i = 2; i < data[1] + 2; ++i) { if (data[i] == 0) { has_method = true; break; } } if (!has_method) { Log::log_with_endpoint(in_endpoint, "unsupported auth method", Log::ERROR); in_async_write(string("\x05\xff", 2)); status = INVALID; return; } in_async_write(string("\x05\x00", 2)); break; } case REQUEST: { if (data.length() < 7 || data[0] != 5 || data[2] != 0) { Log::log_with_endpoint(in_endpoint, "bad request", Log::ERROR); destroy(); return; } out_write_buf = config.password.cbegin()->first + "\r\n" + data[1] + data.substr(3) + "\r\n"; TrojanRequest req; if (req.parse(out_write_buf) == -1) { Log::log_with_endpoint(in_endpoint, "unsupported command", Log::ERROR); in_async_write(string("\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00", 10)); status = INVALID; return; } is_udp = req.command == TrojanRequest::UDP_ASSOCIATE; if (is_udp) { udp::endpoint bindpoint(in_socket.local_endpoint().address(), 0); boost::system::error_code ec; udp_socket.open(bindpoint.protocol(), ec); if (ec) { destroy(); return; } udp_socket.bind(bindpoint); Log::log_with_endpoint(in_endpoint, "requested UDP associate to " + req.address.address + ':' + to_string(req.address.port) + ", open UDP socket " + udp_socket.local_endpoint().address().to_string() + ':' + to_string(udp_socket.local_endpoint().port()) + " for relay", Log::INFO); in_async_write(string("\x05\x00\x00", 3) + SOCKS5Address::generate(udp_socket.local_endpoint())); } else { Log::log_with_endpoint(in_endpoint, "requested connection to " + req.address.address + ':' + to_string(req.address.port), Log::INFO); in_async_write(string("\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00", 10)); } break; } case CONNECT: { sent_len += data.length(); first_packet_recv = true; out_write_buf += data; break; } case FORWARD: { sent_len += data.length(); out_async_write(data); break; } case UDP_FORWARD: { Log::log_with_endpoint(in_endpoint, "unexpected data from TCP port", Log::ERROR); destroy(); break; } default: break; } } void ClientSession::in_sent() { switch (status) { case HANDSHAKE: { status = REQUEST; in_async_read(); break; } case REQUEST: { status = CONNECT; in_async_read(); if (is_udp) { udp_async_read(); } auto self = shared_from_this(); resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, tcp::resolver::results_type results) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + config.remote_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); Log::log_with_endpoint(in_endpoint, config.remote_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.next_layer().open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.next_layer().set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean; boost::system::error_code ec; out_socket.next_layer().set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed with " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); if (config.ssl.reuse_session) { auto ssl = out_socket.native_handle(); if (!SSL_session_reused(ssl)) { Log::log_with_endpoint(in_endpoint, "SSL session not reused"); } else { Log::log_with_endpoint(in_endpoint, "SSL session reused"); } } boost::system::error_code ec; if (is_udp) { if (!first_packet_recv) { udp_socket.cancel(ec); } status = UDP_FORWARD; } else { if (!first_packet_recv) { in_socket.cancel(ec); } status = FORWARD; } out_async_read(); out_async_write(out_write_buf); }); }); }); break; } case FORWARD: { out_async_read(); break; } case INVALID: { destroy(); break; } default: break; } } void ClientSession::out_recv(const string &data) { if (status == FORWARD) { recv_len += data.length(); in_async_write(data); } else if (status == UDP_FORWARD) { udp_data_buf += data; udp_sent(); } } void ClientSession::out_sent() { if (status == FORWARD) { in_async_read(); } else if (status == UDP_FORWARD) { udp_async_read(); } } void ClientSession::udp_recv(const string &data, const udp::endpoint&) { if (data.length() == 0) { return; } if (data.length() < 3 || data[0] || data[1] || data[2]) { Log::log_with_endpoint(in_endpoint, "bad UDP packet", Log::ERROR); destroy(); return; } SOCKS5Address address; size_t address_len; bool is_addr_valid = address.parse(data.substr(3), address_len); if (!is_addr_valid) { Log::log_with_endpoint(in_endpoint, "bad UDP packet", Log::ERROR); destroy(); return; } size_t length = data.length() - 3 - address_len; Log::log_with_endpoint(in_endpoint, "sent a UDP packet of length " + to_string(length) + " bytes to " + address.address + ':' + to_string(address.port)); string packet = data.substr(3, address_len) + char(uint8_t(length >> 8)) + char(uint8_t(length & 0xFF)) + "\r\n" + data.substr(address_len + 3); sent_len += length; if (status == CONNECT) { first_packet_recv = true; out_write_buf += packet; } else if (status == UDP_FORWARD) { out_async_write(packet); } } void ClientSession::udp_sent() { if (status == UDP_FORWARD) { UDPPacket packet; size_t packet_len; bool is_packet_valid = packet.parse(udp_data_buf, packet_len); if (!is_packet_valid) { if (udp_data_buf.length() > MAX_LENGTH) { Log::log_with_endpoint(in_endpoint, "UDP packet too long", Log::ERROR); destroy(); return; } out_async_read(); return; } Log::log_with_endpoint(in_endpoint, "received a UDP packet of length " + to_string(packet.length) + " bytes from " + packet.address.address + ':' + to_string(packet.address.port)); SOCKS5Address address; size_t address_len; bool is_addr_valid = address.parse(udp_data_buf, address_len); if (!is_addr_valid) { Log::log_with_endpoint(in_endpoint, "udp_sent: invalid UDP packet address", Log::ERROR); destroy(); return; } string reply = string("\x00\x00\x00", 3) + udp_data_buf.substr(0, address_len) + packet.payload; udp_data_buf = udp_data_buf.substr(packet_len); recv_len += packet.length; udp_async_write(reply, udp_recv_endpoint); } } void ClientSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(NULL) - start_time) + " seconds", Log::INFO); boost::system::error_code ec; resolver.cancel(); if (in_socket.is_open()) { in_socket.cancel(ec); in_socket.shutdown(tcp::socket::shutdown_both, ec); in_socket.close(ec); } if (udp_socket.is_open()) { udp_socket.cancel(ec); udp_socket.close(ec); } if (out_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); out_socket.next_layer().cancel(ec); out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); out_socket.next_layer().close(ec); }; out_socket.next_layer().cancel(ec); out_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } } trojan-1.14.1/src/session/clientsession.h000066400000000000000000000040051361237615600204110ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _CLIENTSESSION_H_ #define _CLIENTSESSION_H_ #include "session.h" #include class ClientSession : public Session { private: enum Status { HANDSHAKE, REQUEST, CONNECT, FORWARD, UDP_FORWARD, INVALID, DESTROY } status; bool is_udp; bool first_packet_recv; boost::asio::ip::tcp::socket in_socket; boost::asio::ssl::streamout_socket; void destroy(); void in_async_read(); void in_async_write(const std::string &data); void in_recv(const std::string &data); void in_sent(); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); void udp_async_read(); void udp_async_write(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint); void udp_recv(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint); void udp_sent(); public: ClientSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context); boost::asio::ip::tcp::socket& accept_socket(); void start(); }; #endif // _CLIENTSESSION_H_ trojan-1.14.1/src/session/forwardsession.cpp000066400000000000000000000210321361237615600211310ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "forwardsession.h" #include "proto/trojanrequest.h" #include "ssl/sslsession.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; ForwardSession::ForwardSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) : Session(config, io_context), status(CONNECT), first_packet_recv(false), in_socket(io_context), out_socket(io_context, ssl_context) {} tcp::socket& ForwardSession::accept_socket() { return in_socket; } void ForwardSession::start() { boost::system::error_code ec; start_time = time(NULL); in_endpoint = in_socket.remote_endpoint(ec); if (ec) { destroy(); return; } auto ssl = out_socket.native_handle(); if (config.ssl.sni != "") { SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str()); } if (config.ssl.reuse_session) { SSL_SESSION *session = SSLSession::get_session(); if (session) { SSL_set_session(ssl, session); } } out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, config.target_addr, config.target_port, true); in_async_read(); Log::log_with_endpoint(in_endpoint, "forwarding to " + config.target_addr + ':' + to_string(config.target_port) + " via " + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO); auto self = shared_from_this(); resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, tcp::resolver::results_type results) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + config.remote_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); Log::log_with_endpoint(in_endpoint, config.remote_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.next_layer().open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.next_layer().set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean; boost::system::error_code ec; out_socket.next_layer().set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed with " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); if (config.ssl.reuse_session) { auto ssl = out_socket.native_handle(); if (!SSL_session_reused(ssl)) { Log::log_with_endpoint(in_endpoint, "SSL session not reused"); } else { Log::log_with_endpoint(in_endpoint, "SSL session reused"); } } boost::system::error_code ec; if (!first_packet_recv) { in_socket.cancel(ec); } status = FORWARD; out_async_read(); out_async_write(out_write_buf); }); }); }); } void ForwardSession::in_async_read() { auto self = shared_from_this(); in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { return; } if (error) { destroy(); return; } in_recv(string((const char*)in_read_buf, length)); }); } void ForwardSession::in_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } in_sent(); }); } void ForwardSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void ForwardSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void ForwardSession::in_recv(const string &data) { if (status == CONNECT) { sent_len += data.length(); first_packet_recv = true; out_write_buf += data; } else if (status == FORWARD) { sent_len += data.length(); out_async_write(data); } } void ForwardSession::in_sent() { if (status == FORWARD) { out_async_read(); } } void ForwardSession::out_recv(const string &data) { if (status == FORWARD) { recv_len += data.length(); in_async_write(data); } } void ForwardSession::out_sent() { if (status == FORWARD) { in_async_read(); } } void ForwardSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(NULL) - start_time) + " seconds", Log::INFO); boost::system::error_code ec; resolver.cancel(); if (in_socket.is_open()) { in_socket.cancel(ec); in_socket.shutdown(tcp::socket::shutdown_both, ec); in_socket.close(ec); } if (out_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); out_socket.next_layer().cancel(ec); out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); out_socket.next_layer().close(ec); }; out_socket.next_layer().cancel(ec); out_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } } trojan-1.14.1/src/session/forwardsession.h000066400000000000000000000033001361237615600205740ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _FORWARDSESSION_H_ #define _FORWARDSESSION_H_ #include "session.h" #include class ForwardSession : public Session { private: enum Status { CONNECT, FORWARD, DESTROY } status; bool first_packet_recv; boost::asio::ip::tcp::socket in_socket; boost::asio::ssl::streamout_socket; void destroy(); void in_async_read(); void in_async_write(const std::string &data); void in_recv(const std::string &data); void in_sent(); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); public: ForwardSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context); boost::asio::ip::tcp::socket& accept_socket(); void start(); }; #endif // _FORWARDSESSION_H_ trojan-1.14.1/src/session/natsession.cpp000066400000000000000000000242011361237615600202500ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "natsession.h" #include "proto/trojanrequest.h" #include "ssl/sslsession.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; // These 2 definitions are respectively from linux/netfilter_ipv4.h and // linux/netfilter_ipv6/ip6_tables.h. Including them will 1) cause linux-headers // to be one of trojan's dependencies, which is not good, and 2) prevent trojan // from even compiling. #ifndef SO_ORIGINAL_DST #define SO_ORIGINAL_DST 80 #endif // SO_ORIGINAL_DST #ifndef IP6T_SO_ORIGINAL_DST #define IP6T_SO_ORIGINAL_DST 80 #endif // IP6T_SO_ORIGINAL_DST NATSession::NATSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) : Session(config, io_context), status(CONNECT), first_packet_recv(false), in_socket(io_context), out_socket(io_context, ssl_context) {} tcp::socket& NATSession::accept_socket() { return in_socket; } pair NATSession::get_target_endpoint() { #ifdef ENABLE_NAT int fd = in_socket.native_handle(); // Taken from https://github.com/shadowsocks/shadowsocks-libev/blob/v3.3.1/src/redir.c. sockaddr_storage destaddr; socklen_t socklen = sizeof(destaddr); int error = getsockopt(fd, SOL_IPV6, IP6T_SO_ORIGINAL_DST, &destaddr, &socklen); if (error) { error = getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &destaddr, &socklen); if (error) { return make_pair("", 0); } } char ipstr[INET6_ADDRSTRLEN]; uint16_t port; if (destaddr.ss_family == AF_INET) { sockaddr_in *sa = (sockaddr_in*) &destaddr; inet_ntop(AF_INET, &(sa->sin_addr), ipstr, INET_ADDRSTRLEN); port = ntohs(sa->sin_port); } else { sockaddr_in6 *sa = (sockaddr_in6*) &destaddr; inet_ntop(AF_INET6, &(sa->sin6_addr), ipstr, INET6_ADDRSTRLEN); port = ntohs(sa->sin6_port); } return make_pair(ipstr, port); #else // ENABLE_NAT return make_pair("", 0); #endif // ENABLE_NAT } void NATSession::start() { boost::system::error_code ec; start_time = time(NULL); in_endpoint = in_socket.remote_endpoint(ec); if (ec) { destroy(); return; } auto ssl = out_socket.native_handle(); if (config.ssl.sni != "") { SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str()); } if (config.ssl.reuse_session) { SSL_SESSION *session = SSLSession::get_session(); if (session) { SSL_set_session(ssl, session); } } auto target_endpoint = get_target_endpoint(); string &target_addr = target_endpoint.first; uint16_t target_port = target_endpoint.second; if (target_port == 0) { destroy(); return; } out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, target_addr, target_port, true); in_async_read(); Log::log_with_endpoint(in_endpoint, "forwarding to " + target_addr + ':' + to_string(target_port) + " via " + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO); auto self = shared_from_this(); resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, tcp::resolver::results_type results) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + config.remote_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); Log::log_with_endpoint(in_endpoint, config.remote_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.next_layer().open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.next_layer().set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean; boost::system::error_code ec; out_socket.next_layer().set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed with " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); if (config.ssl.reuse_session) { auto ssl = out_socket.native_handle(); if (!SSL_session_reused(ssl)) { Log::log_with_endpoint(in_endpoint, "SSL session not reused"); } else { Log::log_with_endpoint(in_endpoint, "SSL session reused"); } } boost::system::error_code ec; if (!first_packet_recv) { in_socket.cancel(ec); } status = FORWARD; out_async_read(); out_async_write(out_write_buf); }); }); }); } void NATSession::in_async_read() { auto self = shared_from_this(); in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error == boost::asio::error::operation_aborted) { return; } if (error) { destroy(); return; } in_recv(string((const char*)in_read_buf, length)); }); } void NATSession::in_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } in_sent(); }); } void NATSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void NATSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void NATSession::in_recv(const string &data) { if (status == CONNECT) { sent_len += data.length(); first_packet_recv = true; out_write_buf += data; } else if (status == FORWARD) { sent_len += data.length(); out_async_write(data); } } void NATSession::in_sent() { if (status == FORWARD) { out_async_read(); } } void NATSession::out_recv(const string &data) { if (status == FORWARD) { recv_len += data.length(); in_async_write(data); } } void NATSession::out_sent() { if (status == FORWARD) { in_async_read(); } } void NATSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(NULL) - start_time) + " seconds", Log::INFO); boost::system::error_code ec; resolver.cancel(); if (in_socket.is_open()) { in_socket.cancel(ec); in_socket.shutdown(tcp::socket::shutdown_both, ec); in_socket.close(ec); } if (out_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); out_socket.next_layer().cancel(ec); out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); out_socket.next_layer().close(ec); }; out_socket.next_layer().cancel(ec); out_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } } trojan-1.14.1/src/session/natsession.h000066400000000000000000000033501361237615600177170ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _NATSESSION_H_ #define _NATSESSION_H_ #include "session.h" #include class NATSession : public Session { private: enum Status { CONNECT, FORWARD, DESTROY } status; bool first_packet_recv; boost::asio::ip::tcp::socket in_socket; boost::asio::ssl::streamout_socket; void destroy(); void in_async_read(); void in_async_write(const std::string &data); void in_recv(const std::string &data); void in_sent(); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); std::pair get_target_endpoint(); public: NATSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context); boost::asio::ip::tcp::socket& accept_socket(); void start(); }; #endif // _NATSESSION_H_ trojan-1.14.1/src/session/serversession.cpp000066400000000000000000000336021361237615600210010ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "serversession.h" #include "proto/trojanrequest.h" #include "proto/udppacket.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; ServerSession::ServerSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context, Authenticator *auth, const string &plain_http_response) : Session(config, io_context), status(HANDSHAKE), in_socket(io_context, ssl_context), out_socket(io_context), udp_resolver(io_context), auth(auth), plain_http_response(plain_http_response) {} tcp::socket& ServerSession::accept_socket() { return (tcp::socket&)in_socket.next_layer(); } void ServerSession::start() { boost::system::error_code ec; start_time = time(NULL); in_endpoint = in_socket.next_layer().remote_endpoint(ec); if (ec) { destroy(); return; } auto self = shared_from_this(); in_socket.async_handshake(stream_base::server, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed: " + error.message(), Log::ERROR); if (error.message() == "http request" && plain_http_response != "") { recv_len += plain_http_response.length(); boost::asio::async_write(accept_socket(), boost::asio::buffer(plain_http_response), [this, self](const boost::system::error_code, size_t) { destroy(); }); return; } destroy(); return; } in_async_read(); }); } void ServerSession::in_async_read() { auto self = shared_from_this(); in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } in_recv(string((const char*)in_read_buf, length)); }); } void ServerSession::in_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } in_sent(); }); } void ServerSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void ServerSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void ServerSession::udp_async_read() { auto self = shared_from_this(); udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } udp_recv(string((const char*)udp_read_buf, length), udp_recv_endpoint); }); } void ServerSession::udp_async_write(const string &data, const udp::endpoint &endpoint) { auto self = shared_from_this(); auto data_copy = make_shared(data); udp_socket.async_send_to(boost::asio::buffer(*data_copy), endpoint, [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } udp_sent(); }); } void ServerSession::in_recv(const string &data) { if (status == HANDSHAKE) { TrojanRequest req; bool valid = req.parse(data) != -1; if (valid) { auto password_iterator = config.password.find(req.password); if (password_iterator == config.password.end()) { valid = false; if (auth && auth->auth(req.password)) { valid = true; auth_password = req.password; Log::log_with_endpoint(in_endpoint, "authenticated by authenticator (" + req.password.substr(0, 7) + ')', Log::INFO); } } else { Log::log_with_endpoint(in_endpoint, "authenticated as " + password_iterator->second, Log::INFO); } if (!valid) { Log::log_with_endpoint(in_endpoint, "valid trojan request structure but possibly incorrect password (" + req.password + ')', Log::WARN); } } string query_addr = valid ? req.address.address : config.remote_addr; string query_port = to_string(valid ? req.address.port : config.remote_port); if (valid) { out_write_buf = req.payload; if (req.command == TrojanRequest::UDP_ASSOCIATE) { Log::log_with_endpoint(in_endpoint, "requested UDP associate to " + req.address.address + ':' + to_string(req.address.port), Log::INFO); status = UDP_FORWARD; udp_data_buf = out_write_buf; udp_sent(); return; } else { Log::log_with_endpoint(in_endpoint, "requested connection to " + req.address.address + ':' + to_string(req.address.port), Log::INFO); } } else { Log::log_with_endpoint(in_endpoint, "not trojan request, connecting to " + config.remote_addr + ':' + to_string(config.remote_port), Log::WARN); out_write_buf = data; } sent_len += out_write_buf.length(); auto self = shared_from_this(); resolver.async_resolve(query_addr, query_port, [this, self, query_addr, query_port](const boost::system::error_code error, tcp::resolver::results_type results) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + query_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); if (config.tcp.prefer_ipv4) { for (auto it = results.begin(); it != results.end(); ++it) { const auto &addr = it->endpoint().address(); if (addr.is_v4()) { iterator = it; break; } } } Log::log_with_endpoint(in_endpoint, query_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean; boost::system::error_code ec; out_socket.set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.async_connect(*iterator, [this, self, query_addr, query_port](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + query_addr + ':' + query_port + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); status = FORWARD; out_async_read(); if (!out_write_buf.empty()) { out_async_write(out_write_buf); } else { in_async_read(); } }); }); } else if (status == FORWARD) { sent_len += data.length(); out_async_write(data); } else if (status == UDP_FORWARD) { udp_data_buf += data; udp_sent(); } } void ServerSession::in_sent() { if (status == FORWARD) { out_async_read(); } else if (status == UDP_FORWARD) { udp_async_read(); } } void ServerSession::out_recv(const string &data) { if (status == FORWARD) { recv_len += data.length(); in_async_write(data); } } void ServerSession::out_sent() { if (status == FORWARD) { in_async_read(); } } void ServerSession::udp_recv(const string &data, const udp::endpoint &endpoint) { if (status == UDP_FORWARD) { size_t length = data.length(); Log::log_with_endpoint(in_endpoint, "received a UDP packet of length " + to_string(length) + " bytes from " + endpoint.address().to_string() + ':' + to_string(endpoint.port())); recv_len += length; in_async_write(UDPPacket::generate(endpoint, data)); } } void ServerSession::udp_sent() { if (status == UDP_FORWARD) { UDPPacket packet; size_t packet_len; bool is_packet_valid = packet.parse(udp_data_buf, packet_len); if (!is_packet_valid) { if (udp_data_buf.length() > MAX_LENGTH) { Log::log_with_endpoint(in_endpoint, "UDP packet too long", Log::ERROR); destroy(); return; } in_async_read(); return; } Log::log_with_endpoint(in_endpoint, "sent a UDP packet of length " + to_string(packet.length) + " bytes to " + packet.address.address + ':' + to_string(packet.address.port)); udp_data_buf = udp_data_buf.substr(packet_len); string query_addr = packet.address.address; auto self = shared_from_this(); udp_resolver.async_resolve(query_addr, to_string(packet.address.port), [this, self, packet, query_addr](const boost::system::error_code error, udp::resolver::results_type results) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + query_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); if (config.tcp.prefer_ipv4) { for (auto it = results.begin(); it != results.end(); ++it) { const auto &addr = it->endpoint().address(); if (addr.is_v4()) { iterator = it; break; } } } Log::log_with_endpoint(in_endpoint, query_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); if (!udp_socket.is_open()) { auto protocol = iterator->endpoint().protocol(); boost::system::error_code ec; udp_socket.open(protocol, ec); if (ec) { destroy(); return; } udp_socket.bind(udp::endpoint(protocol, 0)); udp_async_read(); } sent_len += packet.length; udp_async_write(packet.payload, *iterator); }); } } void ServerSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(NULL) - start_time) + " seconds", Log::INFO); if (auth && !auth_password.empty()) { auth->record(auth_password, recv_len, sent_len); } boost::system::error_code ec; resolver.cancel(); udp_resolver.cancel(); if (out_socket.is_open()) { out_socket.cancel(ec); out_socket.shutdown(tcp::socket::shutdown_both, ec); out_socket.close(ec); } if (udp_socket.is_open()) { udp_socket.cancel(ec); udp_socket.close(ec); } if (in_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); in_socket.next_layer().cancel(ec); in_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); in_socket.next_layer().close(ec); }; in_socket.next_layer().cancel(ec); in_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } } trojan-1.14.1/src/session/serversession.h000066400000000000000000000042271361237615600204470ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _SERVERSESSION_H_ #define _SERVERSESSION_H_ #include "session.h" #include #include "core/authenticator.h" class ServerSession : public Session { private: enum Status { HANDSHAKE, FORWARD, UDP_FORWARD, DESTROY } status; boost::asio::ssl::streamin_socket; boost::asio::ip::tcp::socket out_socket; boost::asio::ip::udp::resolver udp_resolver; Authenticator *auth; std::string auth_password; const std::string &plain_http_response; void destroy(); void in_async_read(); void in_async_write(const std::string &data); void in_recv(const std::string &data); void in_sent(); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); void udp_async_read(); void udp_async_write(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint); void udp_recv(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint); void udp_sent(); public: ServerSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context, Authenticator *auth, const std::string &plain_http_response); boost::asio::ip::tcp::socket& accept_socket(); void start(); }; #endif // _SERVERSESSION_H_ trojan-1.14.1/src/session/session.cpp000066400000000000000000000026551361237615600175560ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "session.h" Session::Session(const Config &config, boost::asio::io_context &io_context) : config(config), recv_len(0), sent_len(0), resolver(io_context), udp_socket(io_context), ssl_shutdown_timer(io_context) {} Session::~Session() {} trojan-1.14.1/src/session/session.h000066400000000000000000000035731361237615600172230ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _SESSION_H_ #define _SESSION_H_ #include #include #include #include #include #include "core/config.h" class Session : public std::enable_shared_from_this { protected: enum { MAX_LENGTH = 8192, SSL_SHUTDOWN_TIMEOUT = 30 }; const Config &config; uint8_t in_read_buf[MAX_LENGTH]; uint8_t out_read_buf[MAX_LENGTH]; uint8_t udp_read_buf[MAX_LENGTH]; uint64_t recv_len; uint64_t sent_len; time_t start_time; std::string out_write_buf; std::string udp_data_buf; boost::asio::ip::tcp::resolver resolver; boost::asio::ip::tcp::endpoint in_endpoint; boost::asio::ip::udp::socket udp_socket; boost::asio::ip::udp::endpoint udp_recv_endpoint; boost::asio::steady_timer ssl_shutdown_timer; public: Session(const Config &config, boost::asio::io_context &io_context); virtual boost::asio::ip::tcp::socket& accept_socket() = 0; virtual void start() = 0; virtual ~Session(); }; #endif // _SESSION_H_ trojan-1.14.1/src/session/udpforwardsession.cpp000066400000000000000000000226411361237615600216510ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "udpforwardsession.h" #include #include "ssl/sslsession.h" #include "proto/trojanrequest.h" #include "proto/udppacket.h" using namespace std; using namespace boost::asio::ip; using namespace boost::asio::ssl; UDPForwardSession::UDPForwardSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context, const udp::endpoint &endpoint, const UDPWrite &in_write) : Session(config, io_context), status(CONNECT), in_write(in_write), out_socket(io_context, ssl_context), gc_timer(io_context) { udp_recv_endpoint = endpoint; in_endpoint = tcp::endpoint(endpoint.address(), endpoint.port()); } tcp::socket& UDPForwardSession::accept_socket() { throw logic_error("accept_socket does not exist in UDPForwardSession"); } void UDPForwardSession::start() { timer_async_wait(); start_time = time(NULL); auto ssl = out_socket.native_handle(); if (config.ssl.sni != "") { SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str()); } if (config.ssl.reuse_session) { SSL_SESSION *session = SSLSession::get_session(); if (session) { SSL_set_session(ssl, session); } } out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, config.target_addr, config.target_port, false); Log::log_with_endpoint(in_endpoint, "forwarding UDP packets to " + config.target_addr + ':' + to_string(config.target_port) + " via " + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO); auto self = shared_from_this(); resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, tcp::resolver::results_type results) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot resolve remote server hostname " + config.remote_addr + ": " + error.message(), Log::ERROR); destroy(); return; } auto iterator = results.begin(); Log::log_with_endpoint(in_endpoint, config.remote_addr + " is resolved to " + iterator->endpoint().address().to_string(), Log::ALL); boost::system::error_code ec; out_socket.next_layer().open(iterator->endpoint().protocol(), ec); if (ec) { destroy(); return; } if (config.tcp.no_delay) { out_socket.next_layer().set_option(tcp::no_delay(true)); } if (config.tcp.keep_alive) { out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true)); } #ifdef TCP_FASTOPEN_CONNECT if (config.tcp.fast_open) { using fastopen_connect = boost::asio::detail::socket_option::boolean; boost::system::error_code ec; out_socket.next_layer().set_option(fastopen_connect(true), ec); } #endif // TCP_FASTOPEN_CONNECT out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "cannot establish connection to remote server " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) { if (error) { Log::log_with_endpoint(in_endpoint, "SSL handshake failed with " + config.remote_addr + ':' + to_string(config.remote_port) + ": " + error.message(), Log::ERROR); destroy(); return; } Log::log_with_endpoint(in_endpoint, "tunnel established"); if (config.ssl.reuse_session) { auto ssl = out_socket.native_handle(); if (!SSL_session_reused(ssl)) { Log::log_with_endpoint(in_endpoint, "SSL session not reused"); } else { Log::log_with_endpoint(in_endpoint, "SSL session reused"); } } status = FORWARDING; out_async_read(); out_async_write(out_write_buf); out_write_buf.clear(); }); }); }); } bool UDPForwardSession::process(const udp::endpoint &endpoint, const string &data) { if (endpoint != udp_recv_endpoint) { return false; } in_recv(data); return true; } void UDPForwardSession::out_async_read() { auto self = shared_from_this(); out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) { if (error) { destroy(); return; } out_recv(string((const char*)out_read_buf, length)); }); } void UDPForwardSession::out_async_write(const string &data) { auto self = shared_from_this(); auto data_copy = make_shared(data); boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) { if (error) { destroy(); return; } out_sent(); }); } void UDPForwardSession::timer_async_wait() { gc_timer.expires_after(chrono::seconds(config.udp_timeout)); auto self = shared_from_this(); gc_timer.async_wait([this, self](const boost::system::error_code error) { if (!error) { Log::log_with_endpoint(in_endpoint, "UDP session timeout"); destroy(); } }); } void UDPForwardSession::in_recv(const string &data) { if (status == DESTROY) { return; } gc_timer.cancel(); timer_async_wait(); string packet = UDPPacket::generate(config.target_addr, config.target_port, data); size_t length = data.length(); Log::log_with_endpoint(in_endpoint, "sent a UDP packet of length " + to_string(length) + " bytes to " + config.target_addr + ':' + to_string(config.target_port)); sent_len += length; if (status == FORWARD) { status = FORWARDING; out_async_write(packet); } else { out_write_buf += packet; } } void UDPForwardSession::out_recv(const string &data) { if (status == FORWARD || status == FORWARDING) { gc_timer.cancel(); timer_async_wait(); udp_data_buf += data; for (;;) { UDPPacket packet; size_t packet_len; bool is_packet_valid = packet.parse(udp_data_buf, packet_len); if (!is_packet_valid) { if (udp_data_buf.length() > MAX_LENGTH) { Log::log_with_endpoint(in_endpoint, "UDP packet too long", Log::ERROR); destroy(); return; } break; } Log::log_with_endpoint(in_endpoint, "received a UDP packet of length " + to_string(packet.length) + " bytes from " + packet.address.address + ':' + to_string(packet.address.port)); udp_data_buf = udp_data_buf.substr(packet_len); recv_len += packet.length; in_write(udp_recv_endpoint, packet.payload); } out_async_read(); } } void UDPForwardSession::out_sent() { if (status == FORWARDING) { if (out_write_buf.length() == 0) { status = FORWARD; } else { out_async_write(out_write_buf); out_write_buf.clear(); } } } void UDPForwardSession::destroy() { if (status == DESTROY) { return; } status = DESTROY; Log::log_with_endpoint(in_endpoint, "disconnected, " + to_string(recv_len) + " bytes received, " + to_string(sent_len) + " bytes sent, lasted for " + to_string(time(NULL) - start_time) + " seconds", Log::INFO); resolver.cancel(); gc_timer.cancel(); if (out_socket.next_layer().is_open()) { auto self = shared_from_this(); auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) { if (error == boost::asio::error::operation_aborted) { return; } boost::system::error_code ec; ssl_shutdown_timer.cancel(); out_socket.next_layer().cancel(ec); out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec); out_socket.next_layer().close(ec); }; boost::system::error_code ec; out_socket.next_layer().cancel(ec); out_socket.async_shutdown(ssl_shutdown_cb); ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT)); ssl_shutdown_timer.async_wait(ssl_shutdown_cb); } } trojan-1.14.1/src/session/udpforwardsession.h000066400000000000000000000037201361237615600213130ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _UDPFORWARDSESSION_H_ #define _UDPFORWARDSESSION_H_ #include "session.h" #include #include class UDPForwardSession : public Session { public: typedef std::function UDPWrite; private: enum Status { CONNECT, FORWARD, FORWARDING, DESTROY } status; UDPWrite in_write; boost::asio::ssl::streamout_socket; boost::asio::steady_timer gc_timer; void destroy(); void in_recv(const std::string &data); void out_async_read(); void out_async_write(const std::string &data); void out_recv(const std::string &data); void out_sent(); void timer_async_wait(); public: UDPForwardSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context, const boost::asio::ip::udp::endpoint &endpoint, const UDPWrite &in_write); boost::asio::ip::tcp::socket& accept_socket(); void start(); bool process(const boost::asio::ip::udp::endpoint &endpoint, const std::string &data); }; #endif // _UDPFORWARDSESSION_H_ trojan-1.14.1/src/ssl/000077500000000000000000000000001361237615600144755ustar00rootroot00000000000000trojan-1.14.1/src/ssl/ssldefaults.cpp000066400000000000000000000026351361237615600175400ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "ssldefaults.h" const char SSLDefaults::g_dh2048_sz[] = "-----BEGIN DH PARAMETERS-----\n" "MIIBCAKCAQEA///////////JD9qiIWjCNMTGYouA3BzRKQJOCIpnzHQCC76mOxOb\n" "IlFKCHmONATd75UZs806QxswKwpt8l8UN0/hNW1tUcJF5IW1dmJefsb0TELppjft\n" "awv/XLb0Brft7jhr+1qJn6WunyQRfEsf5kkoZlHs5Fs9wgB8uKFjvwWY2kg2HFXT\n" "mmkWP6j9JM9fg2VdI9yjrZYcYvNWIIVSu57VKQdwlpZtZww1Tkq8mATxdGwIyhgh\n" "fDKQXkYuNs474553LBgOhgObJ4Oi7Aeij7XFXfBvTFLJ3ivL9pVYFxg5lUl86pVq\n" "5RXSJhiY+gUQFXKOWoqsqmj//////////wIBAg==\n" "-----END DH PARAMETERS-----"; const size_t SSLDefaults::g_dh2048_sz_size = sizeof(g_dh2048_sz); trojan-1.14.1/src/ssl/ssldefaults.h000066400000000000000000000017771361237615600172130ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _SSLDEFAULTS_H_ #define _SSLDEFAULTS_H_ #include class SSLDefaults { public: static const char g_dh2048_sz[]; static const size_t g_dh2048_sz_size; }; #endif // _SSLDEFAULTS_H_ trojan-1.14.1/src/ssl/sslsession.cpp000066400000000000000000000026101361237615600174050ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #include "sslsession.h" using namespace std; listSSLSession::sessions; int SSLSession::new_session_cb(SSL*, SSL_SESSION *session) { sessions.push_front(session); return 0; } void SSLSession::remove_session_cb(SSL_CTX*, SSL_SESSION *session) { sessions.remove(session); } SSL_SESSION *SSLSession::get_session() { if (sessions.size() == 0) { return NULL; } return sessions.front(); } void SSLSession::set_callback(SSL_CTX *context) { SSL_CTX_sess_set_new_cb(context, new_session_cb); SSL_CTX_sess_set_remove_cb(context, remove_session_cb); } trojan-1.14.1/src/ssl/sslsession.h000066400000000000000000000023141361237615600170530ustar00rootroot00000000000000/* * This file is part of the trojan project. * Trojan is an unidentifiable mechanism that helps you bypass GFW. * Copyright (C) 2017-2020 The Trojan Authors. * * 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 3 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, see . */ #ifndef _SSLSESSION_H_ #define _SSLSESSION_H_ #include #include class SSLSession { private: static std::listsessions; static int new_session_cb(SSL*, SSL_SESSION *session); static void remove_session_cb(SSL_CTX*, SSL_SESSION *session); public: static SSL_SESSION *get_session(); static void set_callback(SSL_CTX *context); }; #endif // _SSLSESSION_H_ trojan-1.14.1/tests/000077500000000000000000000000001361237615600142475ustar00rootroot00000000000000trojan-1.14.1/tests/.gitignore000066400000000000000000000000461361237615600162370ustar00rootroot00000000000000# Allow config files in tests !*.json trojan-1.14.1/tests/LinuxSmokeTest/000077500000000000000000000000001361237615600172055ustar00rootroot00000000000000trojan-1.14.1/tests/LinuxSmokeTest/README.md000066400000000000000000000002301361237615600204570ustar00rootroot00000000000000# Linux Smoke Test ## Dependencies - curl - netcat - openssl - python3 ## Usage ``` ./basic.sh /path/to/trojan ./fake-client.sh /path/to/trojan ``` trojan-1.14.1/tests/LinuxSmokeTest/basic.sh000077500000000000000000000020031361237615600206200ustar00rootroot00000000000000#!/bin/bash set -eu source "$(dirname "$0")/common.sh" cp server.json client.json forward.json "$TMPDIR" cd "$TMPDIR" exec 2>> test.log yes '' | openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 1 -nodes mkdir true cd true echo true > whoami.txt python3 -m http.server 10081 > server.log 2>&1 & PID1="$!" cd .. mkdir fake cd fake echo fake > whoami.txt python3 -m http.server 10080 > server.log 2>&1 & PID2="$!" cd .. ./trojan -v ./trojan -t server.json ./trojan server.json -l server.log & PID3="$!" ./trojan -t client.json ./trojan client.json -l client.log & PID4="$!" ./trojan -t forward.json ./trojan forward.json -l forward.log & PID5="$!" wait_port 10081 wait_port 10080 wait_port 10443 wait_port 11080 wait_port 20081 WHOAMI=$(curl -v --socks5 127.0.0.1:11080 http://127.0.0.1:10081/whoami.txt) WHOAMI2=$(curl -v http://127.0.0.1:20081/whoami.txt) kill -KILL "$PID1" "$PID2" "$PID3" "$PID4" "$PID5" if [[ "$WHOAMI" = "true" && "$WHOAMI2" = "true" ]]; then exit 0 else exit 1 fi trojan-1.14.1/tests/LinuxSmokeTest/client.json000066400000000000000000000012311361237615600213530ustar00rootroot00000000000000{ "run_type": "client", "local_addr": "127.0.0.1", "local_port": 11080, "remote_addr": "127.0.0.1", "remote_port": 10443, "password": [ "linux-smoke-test-password" ], "log_level": 0, "ssl": { "verify": true, "verify_hostname": false, "cert": "cert.pem", "cipher": "", "cipher_tls13": "", "sni": "", "alpn": [], "reuse_session": false, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } trojan-1.14.1/tests/LinuxSmokeTest/common.sh000066400000000000000000000007521361237615600210350ustar00rootroot00000000000000function check_available() { if ! command -v "$1" > /dev/null; then echo "$1 is required." exit 1 fi } function wait_port() { until nc -z 127.0.0.1 "$1"; do sleep 0.1 done } if [[ "$#" != "1" ]]; then echo "usage: $0 path_to_trojan" exit 1 fi check_available curl check_available nc check_available openssl check_available python3 SCRIPTDIR="$(dirname "$0")" TMPDIR="$(mktemp -d)" echo "$TMPDIR" cp "$1" "$TMPDIR/trojan" cd "$SCRIPTDIR" trojan-1.14.1/tests/LinuxSmokeTest/fake-client.json000066400000000000000000000012161361237615600222620ustar00rootroot00000000000000{ "run_type": "client", "local_addr": "127.0.0.1", "local_port": 11080, "remote_addr": "127.0.0.1", "remote_port": 10443, "password": [ "wrong-password" ], "log_level": 0, "ssl": { "verify": true, "verify_hostname": false, "cert": "cert.pem", "cipher": "", "cipher_tls13": "", "sni": "", "alpn": [], "reuse_session": false, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } trojan-1.14.1/tests/LinuxSmokeTest/fake-client.sh000077500000000000000000000017001361237615600217240ustar00rootroot00000000000000#!/bin/bash set -u source "$(dirname "$0")/common.sh" cp server.json fake-client.json forward.json "$TMPDIR" cd "$TMPDIR" exec 2>> test.log yes '' | openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 1 -nodes mkdir true cd true echo true > whoami.txt python3 -m http.server 10081 > server.log 2>&1 & PID1="$!" cd .. mkdir fake cd fake echo fake > whoami.txt python3 -m http.server 10080 > server.log 2>&1 & PID2="$!" cd .. ./trojan -v ./trojan -t server.json ./trojan server.json -l server.log & PID3="$!" ./trojan -t fake-client.json ./trojan fake-client.json -l fake-client.log & PID4="$!" wait_port 10081 wait_port 10080 wait_port 10443 wait_port 11080 WHOAMI=$(curl -v --socks5 127.0.0.1:11080 http://127.0.0.1:10081/whoami.txt) WHOAMI2=$(curl -v --insecure https://127.0.0.1:10443/whoami.txt) kill -KILL "$PID1" "$PID2" "$PID3" "$PID4" if [[ "$WHOAMI" != "true" && "$WHOAMI2" = "fake" ]]; then exit 0 else exit 1 fi trojan-1.14.1/tests/LinuxSmokeTest/forward.json000066400000000000000000000013531361237615600215460ustar00rootroot00000000000000{ "run_type": "forward", "local_addr": "127.0.0.1", "local_port": 20081, "remote_addr": "127.0.0.1", "remote_port": 10443, "target_addr": "127.0.0.1", "target_port": 10081, "password": [ "linux-smoke-test-password" ], "udp_timeout": 60, "log_level": 0, "ssl": { "verify": true, "verify_hostname": false, "cert": "cert.pem", "cipher": "", "cipher_tls13": "", "sni": "", "alpn": [], "reuse_session": false, "session_ticket": false, "curves": "" }, "tcp": { "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 } } trojan-1.14.1/tests/LinuxSmokeTest/server.json000066400000000000000000000016761361237615600214200ustar00rootroot00000000000000{ "run_type": "server", "local_addr": "127.0.0.1", "local_port": 10443, "remote_addr": "127.0.0.1", "remote_port": 10080, "password": ["linux-smoke-test-password"], "log_level": 0, "ssl": { "cert": "cert.pem", "key": "key.pem", "key_password": "", "cipher": "", "cipher_tls13": "", "prefer_server_cipher": true, "alpn": [], "reuse_session": false, "session_ticket": false, "session_timeout": 600, "plain_http_response": "", "curves": "", "dhparam": "" }, "tcp": { "prefer_ipv4": false, "no_delay": true, "keep_alive": true, "reuse_port": false, "fast_open": false, "fast_open_qlen": 20 }, "mysql": { "enabled": false, "server_addr": "", "server_port": 0, "database": "", "username": "", "password": "" } }