Showing preview only (243K chars total). Download the full file or copy to clipboard to get everything.
Repository: trojan-gfw/trojan
Branch: master
Commit: 3e7bb9aecdc6
Files: 71
Total size: 226.1 KB
Directory structure:
gitextract_1foy4gep/
├── .github/
│ └── ISSUE_TEMPLATE/
│ ├── bug_report.md
│ └── feature_request.md
├── .gitignore
├── .gitpod.Dockerfile
├── .gitpod.yml
├── CMakeLists.txt
├── CONTRIBUTING.md
├── CONTRIBUTORS.md
├── Dockerfile
├── LICENSE
├── README.md
├── SECURITY.md
├── azure-pipelines.yml
├── cmake/
│ └── FindMySQL.cmake
├── docs/
│ ├── README.md
│ ├── _config.yml
│ ├── authenticator.md
│ ├── build.md
│ ├── config.md
│ ├── overview.md
│ ├── protocol.md
│ ├── trojan.1
│ └── usage.md
├── examples/
│ ├── client.json-example
│ ├── forward.json-example
│ ├── nat.json-example
│ ├── server.json-example
│ └── trojan.service-example
├── scripts/
│ └── getcert.py
├── src/
│ ├── core/
│ │ ├── authenticator.cpp
│ │ ├── authenticator.h
│ │ ├── config.cpp
│ │ ├── config.h
│ │ ├── log.cpp
│ │ ├── log.h
│ │ ├── service.cpp
│ │ ├── service.h
│ │ ├── version.cpp
│ │ └── version.h
│ ├── main.cpp
│ ├── proto/
│ │ ├── socks5address.cpp
│ │ ├── socks5address.h
│ │ ├── trojanrequest.cpp
│ │ ├── trojanrequest.h
│ │ ├── udppacket.cpp
│ │ └── udppacket.h
│ ├── session/
│ │ ├── clientsession.cpp
│ │ ├── clientsession.h
│ │ ├── forwardsession.cpp
│ │ ├── forwardsession.h
│ │ ├── natsession.cpp
│ │ ├── natsession.h
│ │ ├── serversession.cpp
│ │ ├── serversession.h
│ │ ├── session.cpp
│ │ ├── session.h
│ │ ├── udpforwardsession.cpp
│ │ └── udpforwardsession.h
│ └── ssl/
│ ├── ssldefaults.cpp
│ ├── ssldefaults.h
│ ├── sslsession.cpp
│ └── sslsession.h
└── tests/
├── .gitignore
└── LinuxSmokeTest/
├── README.md
├── basic.sh
├── client.json
├── common.sh
├── fake-client.json
├── fake-client.sh
├── forward.json
└── server.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: bug
assignees: GreaterFire
---
- [ ] I certify that I have read the contributing guidelines and 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.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: "[Feature Request]"
labels: enhancement
assignees: GreaterFire
---
- [ ] I certify that I have read the contributing guidelines and 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.
================================================
FILE: .gitignore
================================================
# 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/
================================================
FILE: .gitpod.Dockerfile
================================================
FROM gitpod/workspace-full
USER gitpod
RUN sudo apt-get update && \
sudo apt-get install -y \
build-essential \
cmake \
libboost-system-dev \
libboost-program-options-dev \
libssl-dev \
default-libmysqlclient-dev
================================================
FILE: .gitpod.yml
================================================
image:
file: .gitpod.Dockerfile
================================================
FILE: CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.7.2)
project(trojan CXX)
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()
file(GLOB_RECURSE CPP_LIST src/*.cpp)
add_executable(trojan ${CPP_LIST})
target_include_directories(trojan PRIVATE 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)
target_include_directories(trojan PRIVATE ${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)
target_include_directories(trojan PRIVATE ${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)
target_include_directories(trojan PRIVATE ${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)
SET_TESTS_PROPERTIES(LinuxSmokeTest-fake-client PROPERTIES DEPENDS "LinuxSmokeTest-basic")
endif()
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
I want to first thank you for your interests in contributing to the Trojan project. Your contributions are much appreciated. To ensure an effective and efficient communication environment, here are some guidelines you should adhere to when you are considering contributing.
## Issues
Issues in this repository are for bug reports and feature requests, and for these purposes **only**. Irrelevant content, such as usage problems or server configuration issues, should not be discussed here. The developers will, at their discretion, either answer or ignore and close this kind of issues without any notice. The **required** communication language in this repository is English.
If you would like to file a bug report, you **must** use the bug report template and follow the instructions inside it. If you do not do so, or if the problem you reported is not considered by the developers a bug, your issue might be closed immediately.
If you would like to file a feature request, you also **must** use the feature request template and follow the instructions inside it. Note that we are trying to keep this project as small as possible because it is the core of the trojan ecosystem and will be included in other projects. For a feature to be considered, make sure that the feature you request is **really necessary** to be included in this very project. Also, we will not consider adding a dependency to the project unless it is **absolutely necessary**. If you do not do the above, your issue might be closed immediately.
## Pull Requests
Pull requests are very welcomed. However, due to the reasons we just talked about, we will only accept features that are **really necessary** for this project. Bug fixes and security-related fixes have more chances to be reviewed by the developers.
For contributors who make frequent and high-quality contributions, there is a chance that they'll be invited to join our organization.
================================================
FILE: CONTRIBUTORS.md
================================================
# Contributors
- [a-wing](https://github.com/a-wing)
- Add Debian build instructions in the documentation.
- [cybmp3](https://github.com/cybmp3)
- Add MySQL SSL support.
- [du5](https://github.com/du5)
- Update OpenSSL version in Azure Pipelines config.
- [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.
- [karuboniru](https://github.com/karuboniru)
- Make tests serial to avoid a race condition.
- [KCCat](https://github.com/KCCat)
- Fix an ambiguity in the documentation.
- [keur](https://github.com/keur)
- Replace deprecated SHA224 functions with `EVP`.
- [klzgrad](https://github.com/klzgrad)
- Add Linux smoke test.
- [LimiQS](https://github.com/LimiQS)
- Refine the config documentation.
- [MargaretteMoss](https://github.com/MargaretteMoss)
- Add client verification to MySQL SSL connection.
- [PragmaTwice](https://github.com/PragmaTwice)
- List source files automatically in CMakeLists.txt.
- [Qv2ray-dev](https://github.com/Qv2ray-dev)
- Fix Azure Pipelines config.
- Add log callback.
- [WeidiDeng](https://github.com/WeidiDeng)
- Fix incorrect Debian dependency in the documentation.
- [WillyPillow](https://github.com/WillyPillow)
- Add `alpn_port_override` functionality.
- [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.
- Update certificate verification API.
- [xsm1997](https://github.com/xsm1997)
- Add `SO_REUSEPORT` support.
- Add TLS1.3 ciphersuites support.
- [yiailake](https://github.com/yiailake)
- Add support for gitpod.
- [zhangsan946](https://github.com/zhangsan946)
- Add macOS keychain support.
- [zhyncs](https://github.com/zhyncs)
- Fix clang-tidy warnings.
================================================
FILE: Dockerfile
================================================
FROM alpine:3.11
COPY . trojan
RUN apk add --no-cache --virtual .build-deps \
build-base \
cmake \
boost-dev \
openssl-dev \
mariadb-connector-c-dev \
&& (cd trojan && cmake . && make -j $(nproc) && strip -s trojan \
&& mv trojan /usr/local/bin) \
&& rm -rf trojan \
&& apk del .build-deps \
&& apk add --no-cache --virtual .trojan-rundeps \
libstdc++ \
boost-system \
boost-program_options \
mariadb-connector-c
WORKDIR /config
CMD ["trojan", "config.json"]
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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 <http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
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.
================================================
FILE: README.md
================================================
# trojan
[](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).
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md).
## 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)
================================================
FILE: SECURITY.md
================================================
# Security Policy
## Supported Version
The only version that is supported by Trojan-GFW is the latest version.
## Reporting a Vulnerability
To report a vulnerability, please contact GreaterFire@protonmail.com. You can make it secure by encrypting with PGP:
```
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBFnxFxcBEADedizrFWPY6WNjl8r24YSKiqGrAok52LueNmclUwG40PzyOCZG
XXyePaTTPjpBOYT1rG4km8b/zsPsvMuC3WFZU2L4GVV7nxs/sQ/sxKOV1Ptq7xSJ
k+Wmi93dbn1RbyzIJIlEQSiHKQuoz5bc0NkQBGrUFqETWP75MT6txLHRIt1v+GRM
IAvHR0hzhfIMaPogkUApCjOJmRUmuj+v9F5GWj/IglFQCBCqOR/OOYLxH/IaygoV
zwwge+5YS8aAnXFwSkl0Bs6+NzNFB1cDZwnqNvOD9tNN6Y3wCCB2eRZ4uCu5xjR/
D1JYVJlWpIgRP1BpMt2uj28ihnlTD6OYWG8AGOlgWirdF6LutGO5yb9efanafm9o
bfSruUBHgERTAKGitNpJXUxcKMCKvZ5W6j0JJqEnT1dVyHePAo3RBWHScdF1ScZo
LCeGxkqMly8Tvw9uRsX36phroJOvIrb3YHWHW0GDyYvDYHGb+p8+sldSSjGSlmAU
NZRJROs4cJGnn1Ez1VX4SWZkZrPzErpHYmy8HoZ85LlUgg0jngqzaVIRp4NoUb0/
Tq0QkTcsPXOCV1DoY6ZyCcReC2xd8mBOJjn+mi+7EXF48g3NaoktIxSssI+oV9JX
A143yYrxJOXq/Kfu7Qq8iTCfdwE234iItdgysPc8tOYxZEOBDKIMysjzLQARAQAB
tChHcmVhdGVyRmlyZSA8R3JlYXRlckZpcmVAcHJvdG9ubWFpbC5jb20+iQI3BBMB
CAAhBQJZ8RcXAhsDBQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEKHd1IZTOwES
B5sQAM6b8L9TeldziBjF9/mTmGY5rXOzwL/te02ykL0s7SoX6cj3ROxybmgzl38q
sovlBxSQgnkz3Ti69Fk7muCCQmSYyzThpGGGalN84HNhD4UDxd2S9kB1sIEczyZj
U1laiqV2YQjHWAsjyofUpWbz2SdL9KnmIfIdz8bwHMv0DeLDmdL0bmSVq0t/npRw
htyottL0hB2z06ufpq40hzypSKDleM/eIscMfv667/AcjqDzolEXbAqKiqirnjYo
VFzGlWGEd69W6zXqtBxI1gCEGXmjTNw+0fUQbWPlhTJnGcM9ucdBIzBcdhsvAc0X
nDtDYQLbXIzVMTYPatUqqTmdtpZGFsRR7pw7taoZ87TaPm1gsHoWMHOE9vM9XYF9
k6jXCiTD7shyF3EpJn/6W6ErYsui8R3B3P7apvqikq2/oO/aaVj5WcV2ebW/bEns
OMAn0wDwAgGcctsER/WI0zfrS3CI4D+PvM36PnheulL4UxukXkdku0ayyhxDdHiY
9EPL+TgBR2OmDo/06EuUNLDSgbbEM0vgV0BrZNx6Nkh8zXFoUCFkEmKrBgXpr1V8
DXhkVS6XRlx5sm/rxgUfOaF7EJt2LRMtdHY2TYHl+r1jRFV6ZhRFVfQOMOAFhK2x
tXOxB/v13g1WHd/VisE+SYX9r6QmDoz0xiiyTXoZd/ZPyjnzuQINBFnxFxcBEACz
TBFEKzPOMxd41WWV/I+sKmdgpoX1nlC1TxhUXxaRXoBr+sV7sUAnPKa4lQ5PzGHk
FDugdN85NaqI0wVOjr6/VnRcnNB+KuBA/JAb9zdRD4MbV92EpZrdDivtvsGvjsxr
6jip5qBckNLDw19EC0hijstmolHP44Px9W+wMpE0MPx0olfaKHujBRQe+K0ehaT8
Fyf/2a93nG/UjRa0hLdYBwHMR1+Qf7WJsEAkc86fSUNuJMMQZDeacsCBlehqtsxb
XyGEYT5oekxe7EmvCYi9LWvoGPPzYdkvhUUVycZ72OwN9y/I8cy3b8GOFqu9B4E7
qFYp3IJpu8XUS6nCjyce+kZnDk8lUJwVMgWFZAKEk+GuEpAguf4iZ/yrF3A6Tw2Q
QOpzsqnibQhg6Y5valDaEXYy14n20+aT/hGhmBdE0kto37vL43bY4nJEKqLjYkLw
N0wlZ2XjFIqRNVK/JPJepmS2X1CFEJF81XTkuxk9OqjQyTE670iRAwEH8DAZkyjO
WKyhPhIC7OhXtDtuaygISOQraUN5KTXB8G9jEj5hDs9Ej9xsUnnSkVlR/DgYfbkR
ZYbE3Zt8iXnp9Cual5ex546DPLCOmOw3QzUMQnzMdco02sC4pK0Bg9sAUUe5HsA9
JlzArCMn8lR6thG9a1WfOd3uk36YqQz1R0ZrRB0IhwARAQABiQIfBBgBCAAJBQJZ
8RcXAhsMAAoJEKHd1IZTOwESuukQAKlALJErXL0NhUO1ClSUJ+h8Mwx2X39czRWz
sP6vC8Fq11lCEPZip49+rWHCf7QczV/+Trvh4NmlBjuVDPaJDix7Z6kXk7fjIDZE
ig4oRZUoSziM5iIFx8hspKCImqiY9OCOvMyLshzhmY7feUwIcSC7+bM82KaSR6HO
8LG6NKBllW5LoD3KIzlEwRD7wrN9qFJUUihsFCjWN1RIF+OiXjw7wl5qTUST32H3
fPziK6M+ZfC2SuNB5YTTfEqUH+QbKeaqIr6P+s2WtGa8tPbCPi54xJJvx7hwpHzv
fU5mKYHqcW66AKwTFgMeJDYFtkNe/n5zNvYNLQGaxa+i9/NXNug0scd936FTf0An
soHKqs10vBUbRS9MlAdOt2cW+HZDaXtGzXCx+zYDWAVaYg6IbjmoQZGNoHFbAXTW
MIxNgnMtL3Rt8flKvu7beCpNyLWhrF5ZVz8n8+D6gpB3vr4+FPdozlXAdA8QFDsb
PSOs5rvotj3EvYla0dYBFp8DpryLmFMPcmtVat4hHS36VYN8rkweXO2ZUp+UBLxk
kve9N9BjNfOSM8UcZlaW2+azYUYjhVTjyYOE9i/TSVMS/NFboi2L9zvRdhKqKLyI
sqPNFo+QCHzltRQXekccvs2wc6iiuVBOMFErS2ClFOAiHDT9cFU5sidJ19dEoN9h
4wT+LHpX
=Z2PM
-----END PGP PUBLIC KEY BLOCK-----
```
================================================
FILE: azure-pipelines.yml
================================================
stages:
- 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 -DCMAKE_OSX_DEPLOYMENT_TARGET=10.13 .
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_1h.exe
powershell ".\\Win64OpenSSL-1_1_1h.exe /silent /sp- /suppressmsgboxes /DIR='C:\\Program Files\\OpenSSL-Win64'"
cmake -DBoost_INCLUDE_DIR="${BOOST_ROOT_1_72_0}/include" -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 <<EOF
#!/bin/sh
cd "\$(dirname "\$0")"
./trojan
EOF
chmod +x trojan/start.command
zip -r9 trojan-macos.zip trojan
env:
PIPELINE_WORKSPACE: $(Pipeline.Workspace)
- publish: $(System.DefaultWorkingDirectory)/trojan-macos.zip
artifact: macOSRelease
- job: Windows
pool:
vmImage: windows-latest
steps:
- download: current
artifact: WindowsBinary
- bash: |
set -euo pipefail
BINARY="$PIPELINE_WORKSPACE/WindowsBinary/trojan.exe"
mkdir trojan
cp "$BINARY" trojan/trojan.exe
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
7z a -mx=9 trojan-win.zip trojan
env:
PIPELINE_WORKSPACE: $(Pipeline.Workspace)
- publish: $(System.DefaultWorkingDirectory)/trojan-win.zip
artifact: WindowsRelease
================================================
FILE: cmake/FindMySQL.cmake
================================================
# - Find mysqlclient
# Find the native MySQL includes and library
#
# MYSQL_INCLUDE_DIR - where to find mysql.h, etc.
# MYSQL_LIBRARIES - List of libraries when using MySQL.
# MYSQL_FOUND - True if MySQL found.
IF (MYSQL_INCLUDE_DIR)
# Already in cache, be silent
SET(MYSQL_FIND_QUIETLY TRUE)
ENDIF (MYSQL_INCLUDE_DIR)
FIND_PATH(MYSQL_INCLUDE_DIR mysql.h
/usr/local/include/mysql
/usr/include/mysql
)
SET(MYSQL_NAMES mysqlclient mysqlclient_r)
FIND_LIBRARY(MYSQL_LIBRARY
NAMES ${MYSQL_NAMES}
PATHS /usr/lib /usr/local/lib
PATH_SUFFIXES mysql
)
IF (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
SET(MYSQL_FOUND TRUE)
SET( MYSQL_LIBRARIES ${MYSQL_LIBRARY} )
ELSE (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
SET(MYSQL_FOUND FALSE)
SET( MYSQL_LIBRARIES )
ENDIF (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
IF (MYSQL_FOUND)
IF (NOT MYSQL_FIND_QUIETLY)
MESSAGE(STATUS "Found MySQL: ${MYSQL_LIBRARY}")
ENDIF (NOT MYSQL_FIND_QUIETLY)
ELSE (MYSQL_FOUND)
IF (MYSQL_FIND_REQUIRED)
MESSAGE(STATUS "Looked for MySQL libraries named ${MYSQL_NAMES}.")
MESSAGE(FATAL_ERROR "Could NOT find MySQL library")
ENDIF (MYSQL_FIND_REQUIRED)
ENDIF (MYSQL_FOUND)
MARK_AS_ADVANCED(
MYSQL_LIBRARY
MYSQL_INCLUDE_DIR
)
================================================
FILE: docs/README.md
================================================
# Trojan Documentation
Trojan is an unidentifiable mechanism for bypassing GFW. This documentation introduces the trojan protocol, explains its underlying ideas, and provides a guide to it.
## Contents
- [Overview](overview)
- [The Trojan Protocol](protocol)
- [Config](config)
- [Authenticator](authenticator)
- [Build](build)
- [Usage](usage)
================================================
FILE: docs/_config.yml
================================================
theme: jekyll-theme-cayman
show_downloads: true
================================================
FILE: docs/authenticator.md
================================================
# Authenticator
Trojan servers can authenticate users according to not only passwords in the config file but also entries in a MySQL (MariaDB) database. To turn this functionality on, set `enabled` field in the MySQL config to `true` and correctly configure the server address, credentials, and etc. If you would like to connect to the database securely, you can fill the `ca` field indicating the MySQL server's CA file and optionally fill the `key` and `cert` fields indicating the client's private key and certificate:
```json
"mysql": {
"enabled": true,
"server_addr": "127.0.0.1",
"server_port": 3306,
"database": "trojan",
"username": "trojan",
"password": "",
"key": "",
"cert": "",
"ca": ""
}
```
The table has to be named `users`. An example table structure could be:
```sql
CREATE TABLE users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(64) NOT NULL,
password CHAR(56) NOT NULL,
quota BIGINT NOT NULL DEFAULT 0,
download BIGINT UNSIGNED NOT NULL DEFAULT 0,
upload BIGINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (id),
INDEX (password)
);
```
Note that trojan will only read/write the `password`, `quota`, `download`, and `upload` fields. Other fields exist for management convenience. The passwords stored in the table have to be hashed by SHA224 for efficiency and security reasons.
Upon receiving a Trojan Request, **if the server fails to match the password with any passwords set in the config file**, it will query the database for the user. If it succeeds, trojan will check whether `download + upload < quota`; if so, the connection is granted. **A negative `quota` value means infinite quota.** After a connection is closed, trojan will increment `download` and `upload` fields of that user by the amount of data the user has used.
The unit of `quota`, `download`, and `upload` fields is Byte.
[Homepage](.) | [Prev Page](config) | [Next Page](build)
================================================
FILE: docs/build.md
================================================
# Build
We'll only cover the build process on Linux since we will be providing Windows and macOS binaries. Building trojan on every platform is similar.
## Dependencies
Install these dependencies before you build (note that the test has some [additional dependencies](https://github.com/trojan-gfw/trojan/blob/master/tests/LinuxSmokeTest/README.md)):
- [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/)
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)
================================================
FILE: docs/config.md
================================================
# 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. Certificates can be retrieved with [this simple Python script](https://github.com/trojan-gfw/trojan/blob/master/scripts/getcert.py).
- `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 through a trojan connection. 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.
PROTIP: If you simply want to redirect a raw TCP connection, you can use `iptables` or `socat` to do that. The forward mode is not for this purpose.
```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"
],
"alpn_port_override": {
"h2": 81
},
"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": "",
"key": "",
"cert": "",
"ca": ""
}
}
```
- `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**. It's preferred to use the full chain certificate here instead of the certificate alone.
- `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
- `alpn_port_override`: overrides the remote port to the specified value if an `ALPN` is matched. Useful for running NGINX with HTTP/1.1 and HTTP/2 Cleartext on different ports.
- `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)
================================================
FILE: docs/overview.md
================================================
# 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)
================================================
FILE: docs/protocol.md
================================================
# 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)
================================================
FILE: docs/trojan.1
================================================
.TH TROJAN 1 "June 2020" "version 1.16.0"
.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 <https://trojan\-gfw.github.io/trojan/config> for details.
.SH SEE ALSO
Full documentation at: <https://trojan\-gfw.github.io/trojan/>
================================================
FILE: docs/usage.md
================================================
# 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)
================================================
FILE: examples/client.json-example
================================================
{
"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
}
}
================================================
FILE: examples/forward.json-example
================================================
{
"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
}
}
================================================
FILE: examples/nat.json-example
================================================
{
"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
}
}
================================================
FILE: examples/server.json-example
================================================
{
"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"
],
"alpn_port_override": {
"h2": 81
},
"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": "",
"key": "",
"cert": "",
"ca": ""
}
}
================================================
FILE: examples/trojan.service-example
================================================
[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=1s
[Install]
WantedBy=multi-user.target
================================================
FILE: scripts/getcert.py
================================================
#!/usr/bin/env python3
# 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 <http://www.gnu.org/licenses/>.
import socket
import ssl
import sys
def input_with_default(prompt, default):
print('{} [{}]: '.format(prompt, default), file=sys.stderr, end='')
line = input()
return line if line else default
def main(argc, argv):
if argc == 1:
hostname = input_with_default('Enter hostname', 'example.com')
port = int(input_with_default('Enter port number', '443'))
elif argc == 2:
hostname = argv[1]
port = 443
elif argc == 3:
hostname = argv[1]
port = int(argv[2])
else:
print('usage: {} [hostname] [port]'.format(argv[0]), file=sys.stderr)
exit(1)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
with socket.create_connection((hostname, port)) as sock:
with ctx.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssl.DER_cert_to_PEM_cert(ssock.getpeercert(True)), end='')
if __name__ == '__main__':
main(len(sys.argv), sys.argv)
================================================
FILE: src/core/authenticator.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "authenticator.h"
#include <cstdlib>
#include <stdexcept>
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 (!config.mysql.ca.empty()) {
if (!config.mysql.key.empty() && !config.mysql.cert.empty()) {
mysql_ssl_set(&con, config.mysql.key.c_str(), config.mysql.cert.c_str(), config.mysql.ca.c_str(), nullptr, nullptr);
} else {
mysql_ssl_set(&con, nullptr, nullptr, config.mysql.ca.c_str(), nullptr, nullptr);
}
}
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, nullptr, 0) == nullptr) {
throw runtime_error(mysql_error(&con));
}
bool reconnect = true;
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 == nullptr) {
Log::log_with_date_time(mysql_error(&con), Log::ERROR);
return false;
}
MYSQL_ROW row = mysql_fetch_row(res);
if (row == nullptr) {
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 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 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 string&, uint64_t, uint64_t) {}
bool Authenticator::is_valid_password(const string&) { return true; }
Authenticator::~Authenticator() {}
#endif // ENABLE_MYSQL
================================================
FILE: src/core/authenticator.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _AUTHENTICATOR_H_
#define _AUTHENTICATOR_H_
#ifdef ENABLE_MYSQL
#include <mysql.h>
#endif // ENABLE_MYSQL
#include "config.h"
class Authenticator {
private:
#ifdef ENABLE_MYSQL
MYSQL con{};
#endif // ENABLE_MYSQL
enum {
PASSWORD_LENGTH=56
};
static bool is_valid_password(const std::string &password);
public:
explicit 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_
================================================
FILE: src/core/config.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <cstdlib>
#include <sstream>
#include <stdexcept>
#include <boost/property_tree/json_parser.hpp>
#include <openssl/evp.h>
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 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<string, string>().swap(password);
if (tree.get_child_optional("password")) {
for (auto& item: tree.get_child("password")) {
string p = item.second.get_value<string>();
password[SHA224(p)] = p;
}
}
udp_timeout = tree.get("udp_timeout", 60);
log_level = static_cast<Log::Level>(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 = "";
if (tree.get_child_optional("ssl.alpn")) {
for (auto& item: tree.get_child("ssl.alpn")) {
string proto = item.second.get_value<string>();
ssl.alpn += (char)((unsigned char)(proto.length()));
ssl.alpn += proto;
}
}
map<string, uint16_t>().swap(ssl.alpn_port_override);
if (tree.get_child_optional("ssl.alpn_port_override")) {
for (auto& item: tree.get_child("ssl.alpn_port_override")) {
ssl.alpn_port_override[item.first] = item.second.get_value<uint16_t>();
}
}
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());
mysql.key = tree.get("mysql.key", string());
mysql.cert = tree.get("mysql.cert", string());
mysql.ca = tree.get("mysql.ca", string());
}
bool Config::sip003() {
char *JSON = getenv("SS_PLUGIN_OPTIONS");
if (JSON == nullptr) {
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");
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[EVP_MAX_MD_SIZE];
char mdString[(EVP_MAX_MD_SIZE << 1) + 1];
unsigned int digest_len;
EVP_MD_CTX *ctx;
if ((ctx = EVP_MD_CTX_new()) == nullptr) {
throw runtime_error("could not create hash context");
}
if (!EVP_DigestInit_ex(ctx, EVP_sha224(), nullptr)) {
EVP_MD_CTX_free(ctx);
throw runtime_error("could not initialize hash context");
}
if (!EVP_DigestUpdate(ctx, message.c_str(), message.length())) {
EVP_MD_CTX_free(ctx);
throw runtime_error("could not update hash");
}
if (!EVP_DigestFinal_ex(ctx, digest, &digest_len)) {
EVP_MD_CTX_free(ctx);
throw runtime_error("could not output hash");
}
for (unsigned int i = 0; i < digest_len; ++i) {
sprintf(mdString + (i << 1), "%02x", (unsigned int)digest[i]);
}
mdString[digest_len << 1] = '\0';
EVP_MD_CTX_free(ctx);
return string(mdString);
}
================================================
FILE: src/core/config.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _CONFIG_H_
#define _CONFIG_H_
#include <cstdint>
#include <map>
#include <boost/property_tree/ptree.hpp>
#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<std::string, std::string> 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;
std::map<std::string, uint16_t> alpn_port_override;
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;
std::string key;
std::string cert;
std::string ca;
} 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_
================================================
FILE: src/core/log.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "log.h"
#include <cstring>
#include <cerrno>
#include <stdexcept>
#include <sstream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#ifdef ENABLE_ANDROID_LOG
#include <android/log.h>
#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(nullptr);
FILE *Log::output_stream(stderr);
Log::LogCallback Log::log_callback{};
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
if (log_callback) {
log_callback(message, level);
}
}
}
void Log::log_with_date_time(const string &message, Level level) {
static const char *level_strings[]= {"ALL", "INFO", "WARN", "ERROR", "FATAL", "OFF"};
auto *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 == nullptr) {
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 == nullptr) {
throw runtime_error(filename + ": " + strerror(errno));
}
if (keylog != nullptr) {
fclose(keylog);
}
keylog = fp;
}
void Log::set_callback(LogCallback cb) {
log_callback = move(cb);
}
void Log::reset() {
if (output_stream != stderr) {
fclose(output_stream);
output_stream = stderr;
}
if (keylog != nullptr) {
fclose(keylog);
keylog = nullptr;
}
}
================================================
FILE: src/core/log.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _LOG_H_
#define _LOG_H_
#include <cstdio>
#include <string>
#include <boost/asio/ip/tcp.hpp>
#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
};
typedef std::function<void(const std::string &, Level)> LogCallback;
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 set_callback(LogCallback cb);
static void reset();
private:
static FILE *output_stream;
static LogCallback log_callback;
};
#endif // _LOG_H_
================================================
FILE: src/core/service.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "service.h"
#include <cstring>
#include <cerrno>
#include <stdexcept>
#include <fstream>
#ifdef _WIN32
#include <wincrypt.h>
#include <tchar.h>
#endif // _WIN32
#ifdef __APPLE__
#include <Security/Security.h>
#endif // __APPLE__
#include <openssl/opensslv.h>
#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<SOL_SOCKET, SO_REUSEPORT> 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.empty()) {
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.empty()) {
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.empty()) {
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<char>(ifs), istreambuf_iterator<char>());
}
if (config.ssl.dhparam.empty()) {
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.empty()) {
config.ssl.sni = config.remote_addr;
}
if (config.ssl.verify) {
ssl_context.set_verify_mode(verify_peer);
if (config.ssl.cert.empty()) {
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) {
#if BOOST_VERSION >= 107300
ssl_context.set_verify_callback(host_name_verification(config.ssl.sni));
#else
ssl_context.set_verify_callback(rfc2818_verification(config.ssl.sni));
#endif
}
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.empty()) {
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.empty()) {
SSL_CTX_set_cipher_list(native_context, config.ssl.cipher.c_str());
}
if (!config.ssl.cipher_tls13.empty()) {
#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<IPPROTO_TCP, TCP_FASTOPEN>;
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_ptr<Session>session(nullptr);
if (config.run_type == Config::SERVER) {
session = make_shared<ServerSession>(config, io_context, ssl_context, auth, plain_http_response);
} else if (config.run_type == Config::FORWARD) {
session = make_shared<ForwardSession>(config, io_context, ssl_context);
} else if (config.run_type == Config::NAT) {
session = make_shared<NATSession>(config, io_context, ssl_context);
} else {
session = make_shared<ClientSession>(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<UDPForwardSession>(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;
}
}
================================================
FILE: src/core/service.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _SERVICE_H_
#define _SERVICE_H_
#include <list>
#include <boost/version.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/asio/ip/udp.hpp>
#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<std::weak_ptr<UDPForwardSession> > 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:
explicit Service(Config &config, bool test = false);
void run();
void stop();
boost::asio::io_context &service();
void reload_cert();
~Service();
};
#endif // _SERVICE_H_
================================================
FILE: src/core/version.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "version.h"
using namespace std;
const string Version::version("1.16.0");
string Version::get_version() {
return version;
}
================================================
FILE: src/core/version.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _VERSION_H_
#define _VERSION_H_
#include <string>
class Version {
private:
const static std::string version;
public:
static std::string get_version();
};
#endif // _VERSION_H_
================================================
FILE: src/main.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <iostream>
#include <boost/asio/signal_set.hpp>
#include <boost/program_options.hpp>
#include <boost/version.hpp>
#include <openssl/opensslv.h>
#ifdef ENABLE_MYSQL
#include <mysql.h>
#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<string>(&config_file)->default_value(DEFAULT_CONFIG)->value_name("CONFIG"), "specify config file")
("help,h", "print help message")
("keylog,k", po::value<string>(&keylog_file)->value_name("KEYLOG"), "specify keylog file location (OpenSSL >= 1.1.1)")
("log,l", po::value<string>(&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);
}
}
================================================
FILE: src/proto/socks5address.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#include "socks5address.h"
#include <cstdio>
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<AddressType>(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;
}
================================================
FILE: src/proto/socks5address.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _SOCKS5ADDRESS_H_
#define _SOCKS5ADDRESS_H_
#include <cstdint>
#include <string>
#include <boost/asio/ip/udp.hpp>
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_
================================================
FILE: src/proto/trojanrequest.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#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<Command>(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();
}
string TrojanRequest::generate(const string &password, const 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;
}
================================================
FILE: src/proto/trojanrequest.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#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_
================================================
FILE: src/proto/udppacket.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#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;
}
================================================
FILE: src/proto/udppacket.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#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_
================================================
FILE: src/session/clientsession.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#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(nullptr);
in_endpoint = in_socket.remote_endpoint(ec);
if (ec) {
destroy();
return;
}
auto ssl = out_socket.native_handle();
if (!config.ssl.sni.empty()) {
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<string>(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<string>(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<string>(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, const tcp::resolver::results_type& results) {
if (error || results.empty()) {
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<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>;
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(nullptr) - 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);
}
}
================================================
FILE: src/session/clientsession.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _CLIENTSESSION_H_
#define _CLIENTSESSION_H_
#include "session.h"
#include <boost/asio/ssl.hpp>
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::stream<boost::asio::ip::tcp::socket>out_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() override;
void start() override;
};
#endif // _CLIENTSESSION_H_
================================================
FILE: src/session/forwardsession.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#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(nullptr);
in_endpoint = in_socket.remote_endpoint(ec);
if (ec) {
destroy();
return;
}
auto ssl = out_socket.native_handle();
if (!config.ssl.sni.empty()) {
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, const tcp::resolver::results_type& results) {
if (error || results.empty()) {
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<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>;
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<string>(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<string>(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(nullptr) - 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);
}
}
================================================
FILE: src/session/forwardsession.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _FORWARDSESSION_H_
#define _FORWARDSESSION_H_
#include "session.h"
#include <boost/asio/ssl.hpp>
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::stream<boost::asio::ip::tcp::socket>out_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() override;
void start() override;
};
#endif // _FORWARDSESSION_H_
================================================
FILE: src/session/natsession.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#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<string, uint16_t> 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;
memset(&destaddr, 0, sizeof(sockaddr_storage));
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) {
auto *sa = (sockaddr_in*) &destaddr;
inet_ntop(AF_INET, &(sa->sin_addr), ipstr, INET_ADDRSTRLEN);
port = ntohs(sa->sin_port);
} else {
auto *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(nullptr);
in_endpoint = in_socket.remote_endpoint(ec);
if (ec) {
destroy();
return;
}
auto ssl = out_socket.native_handle();
if (!config.ssl.sni.empty()) {
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, const tcp::resolver::results_type& results) {
if (error || results.empty()) {
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<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>;
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<string>(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<string>(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(nullptr) - 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);
}
}
================================================
FILE: src/session/natsession.h
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef _NATSESSION_H_
#define _NATSESSION_H_
#include "session.h"
#include <boost/asio/ssl.hpp>
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::stream<boost::asio::ip::tcp::socket>out_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<std::string, uint16_t> 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() override;
void start() override;
};
#endif // _NATSESSION_H_
================================================
FILE: src/session/serversession.cpp
================================================
/*
* 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 <http://www.gnu.org/licenses/>.
*/
#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(nullptr);
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.empty()) {
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<string>(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<string>(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<string>(data);
udp_socket.async_send_to(boost::asio::buffer(*data_copy), endpoint, [this, self,
gitextract_1foy4gep/
├── .github/
│ └── ISSUE_TEMPLATE/
│ ├── bug_report.md
│ └── feature_request.md
├── .gitignore
├── .gitpod.Dockerfile
├── .gitpod.yml
├── CMakeLists.txt
├── CONTRIBUTING.md
├── CONTRIBUTORS.md
├── Dockerfile
├── LICENSE
├── README.md
├── SECURITY.md
├── azure-pipelines.yml
├── cmake/
│ └── FindMySQL.cmake
├── docs/
│ ├── README.md
│ ├── _config.yml
│ ├── authenticator.md
│ ├── build.md
│ ├── config.md
│ ├── overview.md
│ ├── protocol.md
│ ├── trojan.1
│ └── usage.md
├── examples/
│ ├── client.json-example
│ ├── forward.json-example
│ ├── nat.json-example
│ ├── server.json-example
│ └── trojan.service-example
├── scripts/
│ └── getcert.py
├── src/
│ ├── core/
│ │ ├── authenticator.cpp
│ │ ├── authenticator.h
│ │ ├── config.cpp
│ │ ├── config.h
│ │ ├── log.cpp
│ │ ├── log.h
│ │ ├── service.cpp
│ │ ├── service.h
│ │ ├── version.cpp
│ │ └── version.h
│ ├── main.cpp
│ ├── proto/
│ │ ├── socks5address.cpp
│ │ ├── socks5address.h
│ │ ├── trojanrequest.cpp
│ │ ├── trojanrequest.h
│ │ ├── udppacket.cpp
│ │ └── udppacket.h
│ ├── session/
│ │ ├── clientsession.cpp
│ │ ├── clientsession.h
│ │ ├── forwardsession.cpp
│ │ ├── forwardsession.h
│ │ ├── natsession.cpp
│ │ ├── natsession.h
│ │ ├── serversession.cpp
│ │ ├── serversession.h
│ │ ├── session.cpp
│ │ ├── session.h
│ │ ├── udpforwardsession.cpp
│ │ └── udpforwardsession.h
│ └── ssl/
│ ├── ssldefaults.cpp
│ ├── ssldefaults.h
│ ├── sslsession.cpp
│ └── sslsession.h
└── tests/
├── .gitignore
└── LinuxSmokeTest/
├── README.md
├── basic.sh
├── client.json
├── common.sh
├── fake-client.json
├── fake-client.sh
├── forward.json
└── server.json
SYMBOL INDEX (27 symbols across 24 files)
FILE: scripts/getcert.py
function input_with_default (line 24) | def input_with_default(prompt, default):
function main (line 29) | def main(argc, argv):
FILE: src/core/authenticator.h
function class (line 28) | class Authenticator {
FILE: src/core/config.cpp
function string (line 140) | string Config::SHA224(const string &message) {
FILE: src/core/config.h
function class (line 28) | class Config {
FILE: src/core/log.h
function class (line 31) | class Log {
FILE: src/core/service.h
function class (line 31) | class Service {
FILE: src/core/version.cpp
function string (line 25) | string Version::get_version() {
FILE: src/core/version.h
function class (line 25) | class Version {
FILE: src/main.cpp
function signal_async_wait (line 39) | void signal_async_wait(signal_set &sig, Service &service, bool &restart) {
function main (line 64) | int main(int argc, const char *argv[]) {
FILE: src/proto/socks5address.cpp
function string (line 76) | string SOCKS5Address::generate(const udp::endpoint &endpoint) {
FILE: src/proto/socks5address.h
function class (line 27) | class SOCKS5Address {
FILE: src/proto/trojanrequest.cpp
function string (line 43) | string TrojanRequest::generate(const string &password, const string &dom...
FILE: src/proto/trojanrequest.h
function class (line 25) | class TrojanRequest {
FILE: src/proto/udppacket.cpp
function string (line 42) | string UDPPacket::generate(const udp::endpoint &endpoint, const string &...
function string (line 51) | string UDPPacket::generate(const string &domainname, uint16_t port, cons...
FILE: src/proto/udppacket.h
function class (line 25) | class UDPPacket {
FILE: src/session/clientsession.h
function class (line 26) | class ClientSession : public Session {
FILE: src/session/forwardsession.h
function class (line 26) | class ForwardSession : public Session {
FILE: src/session/natsession.h
function class (line 26) | class NATSession : public Session {
FILE: src/session/serversession.h
function class (line 27) | class ServerSession : public Session {
FILE: src/session/session.h
function class (line 30) | class Session : public std::enable_shared_from_this<Session> {
FILE: src/session/udpforwardsession.h
function class (line 27) | class UDPForwardSession : public Session {
FILE: src/ssl/ssldefaults.h
function class (line 25) | class SSLDefaults {
FILE: src/ssl/sslsession.cpp
function SSL_SESSION (line 34) | SSL_SESSION *SSLSession::get_session() {
FILE: src/ssl/sslsession.h
function class (line 26) | class SSLSession {
Condensed preview — 71 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (243K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/bug_report.md",
"chars": 994,
"preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"[BUG]\"\nlabels: bug\nassignees: GreaterFire\n\n---\n\n-"
},
{
"path": ".github/ISSUE_TEMPLATE/feature_request.md",
"chars": 1016,
"preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: \"[Feature Request]\"\nlabels: enhancement\nassigne"
},
{
"path": ".gitignore",
"chars": 531,
"preview": "# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic"
},
{
"path": ".gitpod.Dockerfile",
"chars": 267,
"preview": "FROM gitpod/workspace-full\n\nUSER gitpod\n\nRUN sudo apt-get update && \\\n sudo apt-get install -y \\\n build-essent"
},
{
"path": ".gitpod.yml",
"chars": 34,
"preview": "image:\n file: .gitpod.Dockerfile\n"
},
{
"path": "CMakeLists.txt",
"chars": 4469,
"preview": "cmake_minimum_required(VERSION 3.7.2)\nproject(trojan CXX)\n\nset(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} \"${CMAKE_SOURCE_DI"
},
{
"path": "CONTRIBUTING.md",
"chars": 1945,
"preview": "# Contributing\n\nI want to first thank you for your interests in contributing to the Trojan project. Your contributions a"
},
{
"path": "CONTRIBUTORS.md",
"chars": 2629,
"preview": "# Contributors\n\n- [a-wing](https://github.com/a-wing)\n - Add Debian build instructions in the documentation.\n- [cybmp"
},
{
"path": "Dockerfile",
"chars": 553,
"preview": "FROM alpine:3.11\n\nCOPY . trojan\nRUN apk add --no-cache --virtual .build-deps \\\n build-base \\\n cmake \\\n "
},
{
"path": "LICENSE",
"chars": 35845,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 1224,
"preview": "# trojan\n\n[ https://trojan-gfw.github.io/trojan/config https://trojan-gfw.gith"
},
{
"path": "scripts/getcert.py",
"chars": 1825,
"preview": "#!/usr/bin/env python3\n\n# This file is part of the trojan project.\n# Trojan is an unidentifiable mechanism that helps yo"
},
{
"path": "src/core/authenticator.cpp",
"chars": 4136,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/authenticator.h",
"chars": 1391,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/config.cpp",
"chars": 6398,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/config.h",
"chars": 2656,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/log.cpp",
"chars": 3265,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/log.h",
"chars": 1818,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/service.cpp",
"chars": 16496,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/service.h",
"chars": 1820,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/version.cpp",
"chars": 956,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/core/version.h",
"chars": 1012,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/main.cpp",
"chars": 6669,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/proto/socks5address.cpp",
"chars": 3737,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/proto/socks5address.h",
"chars": 1292,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/proto/trojanrequest.cpp",
"chars": 1984,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/proto/trojanrequest.h",
"chars": 1277,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/proto/udppacket.cpp",
"chars": 2232,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/proto/udppacket.h",
"chars": 1298,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/clientsession.cpp",
"chars": 16158,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/clientsession.h",
"chars": 2073,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/forwardsession.cpp",
"chars": 8765,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/forwardsession.h",
"chars": 1746,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/natsession.cpp",
"chars": 10441,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/natsession.h",
"chars": 1786,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/serversession.cpp",
"chars": 14750,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/serversession.h",
"chars": 2217,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/session.cpp",
"chars": 1461,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/session.h",
"chars": 1923,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/udpforwardsession.cpp",
"chars": 9686,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/session/udpforwardsession.h",
"chars": 2011,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/ssl/ssldefaults.cpp",
"chars": 1437,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/ssl/ssldefaults.h",
"chars": 1023,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/ssl/sslsession.cpp",
"chars": 1415,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "src/ssl/sslsession.h",
"chars": 1228,
"preview": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Co"
},
{
"path": "tests/.gitignore",
"chars": 38,
"preview": "# Allow config files in tests\n!*.json\n"
},
{
"path": "tests/LinuxSmokeTest/README.md",
"chars": 152,
"preview": "# Linux Smoke Test\n\n## Dependencies\n\n- curl\n- netcat\n- openssl\n- python3\n\n## Usage\n\n```\n./basic.sh /path/to/trojan\n./fak"
},
{
"path": "tests/LinuxSmokeTest/basic.sh",
"chars": 1027,
"preview": "#!/bin/bash\nset -eu\n\nsource \"$(dirname \"$0\")/common.sh\"\n\ncp server.json client.json forward.json \"$TMPDIR\"\ncd \"$TMPDIR\"\n"
},
{
"path": "tests/LinuxSmokeTest/client.json",
"chars": 665,
"preview": "{\n \"run_type\": \"client\",\n \"local_addr\": \"127.0.0.1\",\n \"local_port\": 11080,\n \"remote_addr\": \"127.0.0.1\",\n "
},
{
"path": "tests/LinuxSmokeTest/common.sh",
"chars": 490,
"preview": "function check_available() {\n if ! command -v \"$1\" > /dev/null; then\n echo \"$1 is required.\"\n exit 1\n "
},
{
"path": "tests/LinuxSmokeTest/fake-client.json",
"chars": 654,
"preview": "{\n \"run_type\": \"client\",\n \"local_addr\": \"127.0.0.1\",\n \"local_port\": 11080,\n \"remote_addr\": \"127.0.0.1\",\n "
},
{
"path": "tests/LinuxSmokeTest/fake-client.sh",
"chars": 960,
"preview": "#!/bin/bash\nset -u\n\nsource \"$(dirname \"$0\")/common.sh\"\n\ncp server.json fake-client.json forward.json \"$TMPDIR\"\ncd \"$TMPD"
},
{
"path": "tests/LinuxSmokeTest/forward.json",
"chars": 747,
"preview": "{\n \"run_type\": \"forward\",\n \"local_addr\": \"127.0.0.1\",\n \"local_port\": 20081,\n \"remote_addr\": \"127.0.0.1\",\n "
},
{
"path": "tests/LinuxSmokeTest/server.json",
"chars": 1049,
"preview": "{\n \"run_type\": \"server\",\n \"local_addr\": \"127.0.0.1\",\n \"local_port\": 10443,\n \"remote_addr\": \"127.0.0.1\",\n "
}
]
About this extraction
This page contains the full source code of the trojan-gfw/trojan GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 71 files (226.1 KB), approximately 58.4k tokens, and a symbol index with 27 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.