Skip to content
zhkl0228Public
forked from nginx/nginx

About

The official NGINX Open Source repository.

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

 
 

Latest commit

 

History

8,800 Commits

Folders and files

NGINX Banner

Project Status: Active – The project has reached a stable, usable state and is being actively developed. Community Forum License Code of Conduct

NGINX (pronounced "engine x" or "en-jin-eks") is the world's most popular Web Server, high performance Load Balancer, Reverse Proxy, API Gateway and Content Cache.

NGINX is free and open source software, distributed under the terms of a simplified 2-clause BSD-like license.

Enterprise distributions, commercial support and training are available from F5, Inc.

Important

The goal of this README is to provide a basic, structured introduction to NGINX for novice users. Please refer to the full NGINX documentation for detailed information on installing, building, configuring, debugging, and more. These documentation pages also contain a more detailed Beginners Guide, How-Tos, Development guide, and a complete module and directive reference.

Fork additions: REALITY / MTProxy / JA3 in ngx_stream_ssl_preread_module

This fork extends the upstream ngx_stream_ssl_preread_module (Stream module) with ClientHello inspection that is useful for traffic shaping based on JA3N fingerprints and for terminating the XTLS REALITY protocol's authentication step. All additions live in a single source file, src/stream/ngx_stream_ssl_preread_module.c, and are active only when the ssl_preread directive is enabled inside a stream { ... server { ... } } block.

Directive

ssl_preread on | off [reality=<base64url-encoded-32-byte-private-key>]
                     [mtproxy=<32-hex-char-secret>];

The mtproxy= parameter is optional. Its value is the raw 16-byte MTProxy secret in hex — in an ee… FakeTLS link, the 32 hex characters between the ee prefix and the hex-encoded domain. It enables $ssl_preread_mtproxy (below). Like reality=, it requires an OpenSSL (1.1.0+) or LibreSSL build.

The reality= parameter is optional. When present, its value is a base64url-encoded X25519 private key (32 raw bytes after decoding); this is the same key format used by REALITY's server-side configuration. Without reality=, the module behaves like upstream's ssl_preread but additionally exposes the JA3N and prologue variables described below.

Note

reality= requires nginx to be built with OpenSSL support (any of --with-http_ssl_module, --with-stream_ssl_module, or --with-openssl=PATH). Without OpenSSL, the parameter is rejected at configuration load time with a clear error. See Build notes below.

Exposed variables

Upstream variables (unchanged):

Variable Value
$ssl_preread_protocol TLS version negotiated in ClientHello
$ssl_preread_server_name SNI host name
$ssl_preread_alpn_protocols comma-separated ALPN list

Variables added by this fork:

Variable Value
$ssl_preread_ja3n JA3N fingerprint string (cipher/extension/curve/point-format list with extensions sorted, GREASE values stripped)
$ssl_preread_ja3n_hash MD5 of $ssl_preread_ja3n (32 hex chars)
$ssl_preread_prologue hex dump of the first 32 ClientHello bytes
$ssl_preread_reality_short_id see below — requires OpenSSL build
$ssl_preread_mtproxy see below — requires OpenSSL build

$ssl_preread_reality_short_id semantics

The value is always exactly 16 characters when reality= is configured, so map / if directives can do simple exact-string matches. On a successful decrypt it is the hex ShortId ([0-9a-f]{16}); otherwise it is a readable sentinel naming the reason. Every failure sentinel begins with no-, so a single map rule (~^no-) routes all failures at once, while the suffix still tells you why. Because the sentinels contain non-hex characters, they can never be confused with a real ShortId — including the case where the real ShortId happens to be 0000000000000000.

Configuration / connection state $ssl_preread_reality_short_id
reality= not supplied to ssl_preread variable is absent (not_found)
reality= supplied; decrypt succeeded 16 hex characters — the decrypted ShortId (may be 0000000000000000 if that is the real ShortId)
reality= supplied; no TLS ClientHello (non-TLS, or no preread context) "no-tls----------"
reality= supplied; TLS, but no 32-byte session_id / X25519 key_share (e.g. a TLS 1.2 client) "no-reality------"
reality= supplied; REALITY-shaped ClientHello but GCM decryption failed (wrong key, decoy TLS 1.3 client, or tampering) "no-decrypt------"

Decryption follows the REALITY protocol exactly: ECDH(X25519) with the ClientHello key_share, HKDF-SHA256 with random[:20] as salt and "REALITY" as info, then AES-256-GCM with random[20:32] as nonce and the raw ClientHello (session_id position replaced with 32 zero bytes) as additional authenticated data.

Example: route REALITY traffic to a backend, send others to a decoy

stream {
    map $ssl_preread_reality_short_id $reality_upstream {
        ""                  decoy;                # absent (reality= unset on this server)
        ~^no-               decoy;                # any failure: no-tls / no-reality / no-decrypt
        "0123456789abcdef"  vless_backend_a;
        "fedcba9876543210"  vless_backend_b;
        default             decoy;                # valid ShortId not in our list
    }

    upstream decoy            { server 127.0.0.1:8443; }
    upstream vless_backend_a  { server 10.0.0.10:443; }
    upstream vless_backend_b  { server 10.0.0.11:443; }

    server {
        listen 443;
        ssl_preread on reality=AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8;
        proxy_pass $reality_upstream;
    }
}

Example: log the REALITY outcome (and failure reason)

Because every failure value starts with no-, a single ~^no- rule turns the variable into a coarse ok / fail flag while the raw value keeps the exact reason (no-tls, no-reality, no-decrypt) for the access log:

stream {
    map $ssl_preread_reality_short_id $reality_status {
        ""        not-configured;   # reality= unset on this server
        ~^no-     fail;             # no-tls / no-reality / no-decrypt
        default   ok;               # a real ShortId was decrypted
    }

    log_format reality '$remote_addr $ssl_preread_server_name '
                       'status=$reality_status '
                       'short_id=$ssl_preread_reality_short_id';

    server {
        listen 443;
        ssl_preread on reality=AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8;
        access_log /var/log/nginx/reality.log reality;
        proxy_pass $reality_upstream;   # see the routing example above
    }
}

Sample log lines:

203.0.113.7  www.example.com  status=ok    short_id=0123456789abcdef
198.51.100.4 www.example.com  status=fail  short_id=no-decrypt------
192.0.2.9    -                status=fail  short_id=no-tls----------

$ssl_preread_mtproxy semantics

Tells a real MTProxy FakeTLS client apart from a browser that happens to share its TLS fingerprint (Telegram's FakeTLS ClientHello copies e.g. Safari's, so JA3N alone cannot route it). The client proves it knows the secret by setting ClientHello.random to HMAC-SHA256(secret, record) XOR (28 zero bytes || little-endian unix time), where record is the whole ClientHello record, 5-byte header included, with random replaced by zeros. The module checks exactly that; the timestamp is logged at debug level but not enforced, same as the MTProxy server.

Like $ssl_preread_reality_short_id, the value is always exactly 16 characters when mtproxy= is configured. The success value is a long literal rather than something like ok, so a map rule anchored on it cannot accidentally match an SNI, an ALPN list or another variable when several variables are concatenated into one map key.

Configuration / connection state $ssl_preread_mtproxy
mtproxy= not supplied to ssl_preread variable is absent (not_found)
mtproxy= supplied; digest verified "mtproxy-verified"
no TLS ClientHello (non-TLS, or no preread context) "no-tls----------"
TLS, but not FakeTLS-shaped: ClientHello spread over several records, record header not 16 03 01, record shorter than 255 bytes, extra data after the ClientHello, or legacy_version not 03 03 "no-faketls------"
FakeTLS-shaped, but the HMAC does not match (an ordinary browser, a wrong secret, or tampering) "no-digest-------"

A replayed ClientHello of a real client still verifies; the MTProxy server behind it is expected to deal with that, as it would without nginx in front.

Example: send MTProxy to its backend, same-fingerprint browsers to the site

stream {
    map "$ssl_preread_mtproxy,$ssl_preread_server_name" $name {
        "~^mtproxy-verified,"  mtproxy;
        default                https;
    }

    upstream mtproxy { server 127.0.0.1:44445; }
    upstream https   { server 127.0.0.1:8443; }

    server {
        listen 443;
        ssl_preread on mtproxy=00112233445566778899aabbccddeeff;
        proxy_pass $name;
    }
}

Example: log JA3N for fingerprint analytics

stream {
    log_format ja3 '$remote_addr $ssl_preread_server_name '
                   'ja3n=$ssl_preread_ja3n_hash '
                   'prologue=$ssl_preread_prologue';

    server {
        listen 443;
        ssl_preread on;
        access_log /var/log/nginx/ja3.log ja3;
        proxy_pass real_backend;
    }
}

Build notes

The module splits cleanly into an OpenSSL-free path (JA3N, prologue, SNI, ALPN, ClientHello parsing) and an OpenSSL-dependent path (REALITY decryption). Which features compile in is controlled at auto/configure time by whether any SSL-enabling flag is passed:

Configure flags Compiled features
--with-stream --with-stream_ssl_preread_module JA3N, prologue, SNI, ALPN, ClientHello parsing. reality= parameter on ssl_preread is rejected with a config error; $ssl_preread_reality_short_id is always absent.
Above plus --with-http_ssl_module or --with-stream_ssl_module or --with-openssl=PATH All of the above plus REALITY decryption and $ssl_preread_reality_short_id.

The REALITY path additionally requires OpenSSL 1.1.0 or later for X25519 and HKDF; older OpenSSL versions compile but the decrypt routine short-circuits to a failure.

Implementation detail: REALITY-specific code is gated by #if (NGX_OPENSSL) inside src/stream/ngx_stream_ssl_preread_module.c, mirroring how the rest of the nginx tree (e.g. src/core/ngx_core.h) gates its OpenSSL dependencies.

Table of contents

How it works

NGINX is installed software with binary packages available for all major operating systems and Linux distributions. See Tested OS and Platforms for a full list of compatible systems.

Important

While nearly all popular Linux-based operating systems are distributed with a community version of nginx, we highly advise installation and usage of official packages or sources from this repository. Doing so ensures that you're using the most recent release or source code, including the latest feature-set, fixes and security patches.

Modules

NGINX is comprised of individual modules, each extending core functionality by providing additional, configurable features. See "Modules reference" at the bottom of nginx documentation for a complete list of official modules.

NGINX modules can be built and distributed as static or dynamic modules. Static modules are defined at build-time, compiled, and distributed in the resulting binaries. See Dynamic Modules for more information on how they work, as well as, how to obtain, install, and configure them.

Tip

You can issue the following command to see which static modules your NGINX binaries were built with:

nginx -V

See Configuring the build for information on how to include specific Static modules into your nginx build.

Configurations

NGINX is highly flexible and configurable. Provisioning the software is achieved via text-based config file(s) accepting parameters called "Directives". See Configuration File's Structure for a comprehensive description of how NGINX configuration files work.

Note

The set of directives available to your distribution of NGINX is dependent on which modules have been made available to it.

Runtime

Rather than running in a single, monolithic process, NGINX is architected to scale beyond Operating System process limitations by operating as a collection of processes. They include:

  • A "master" process that maintains worker processes, as well as, reads and evaluates configuration files.
  • One or more "worker" processes that process data (eg. HTTP requests).

The number of worker processes is defined in the configuration file and may be fixed for a given configuration or automatically adjusted to the number of available CPU cores. In most cases, the latter option optimally balances load across available system resources, as NGINX is designed to efficiently distribute work across all worker processes.

Tip

Processes synchronize data through shared memory. For this reason, many NGINX directives require the allocation of shared memory zones. As an example, when configuring rate limiting, connecting clients may need to be tracked in a common memory zone so all worker processes can know how many times a particular client has accessed the server in a span of time.

Downloading and installing

Follow these steps to download and install precompiled NGINX binaries. You may also choose to build NGINX locally from source code.

Stable and Mainline binaries

NGINX binaries are built and distributed in two versions: stable and mainline. Stable binaries are built from stable branches and only contain critical fixes backported from the mainline version. Mainline binaries are built from the master branch and contain the latest features and bugfixes. You'll need to decide which is appropriate for your purposes.

Linux binary installation process

The NGINX binary installation process takes advantage of package managers native to specific Linux distributions. For this reason, first-time installations involve adding the official NGINX package repository to your system's package manager. Follow these steps to download, verify, and install NGINX binaries using the package manager appropriate for your Linux distribution.

Upgrades

Future upgrades to the latest version can be managed using the same package manager without the need to manually download and verify binaries.

FreeBSD installation process

For more information on installing NGINX on FreeBSD system, visit https://nginx.org/en/docs/install.html

Windows executables

Windows executables for mainline and stable releases can be found on the main NGINX download page. Note that the current implementation of NGINX for Windows is at the Proof-of-Concept stage and should only be used for development and testing purposes. For additional information, please see nginx for Windows.

Dynamic modules

NGINX version 1.9.11 added support for Dynamic Modules. Unlike Static modules, dynamically built modules can be downloaded, installed, and configured after the core NGINX binaries have been built. Official dynamic module binaries are available from the same package repository as the core NGINX binaries described in previous steps.

Tip

NGINX JavaScript (njs), is a popular NGINX dynamic module that enables the extension of core NGINX functionality using familiar JavaScript syntax.

Important

If desired, dynamic modules can also be built statically into NGINX at compile time.

Getting started with NGINX

For a gentle introduction to NGINX basics, please see our Beginner’s Guide.

Installing SSL certificates and enabling TLS encryption

See Configuring HTTPS servers for a quick guide on how to enable secure traffic to your NGINX installation.

Load Balancing

For a quick start guide on configuring NGINX as a Load Balancer, please see Using nginx as HTTP load balancer.

Rate limiting

See our Rate Limiting with NGINX blog post for an overview of core concepts for provisioning NGINX as an API Gateway.

Content caching

See A Guide to Caching with NGINX and NGINX Plus blog post for an overview of how to use NGINX as a content cache (e.g. edge server of a content delivery network).

Building from source

The following steps can be used to build NGINX from source code available in this repository.

Installing dependencies

Most Linux distributions will require several dependencies to be installed in order to build NGINX. The following instructions are specific to the apt package manager, widely available on most Ubuntu/Debian distributions and their derivatives.

Tip

It is always a good idea to update your package repository lists prior to installing new packages.

sudo apt update

Installing compiler and make utility

Use the following command to install the GNU C compiler and Make utility.

sudo apt install gcc make

Installing dependency libraries

sudo apt install libpcre3-dev zlib1g-dev

Warning

This is the minimal set of dependency libraries needed to build NGINX with rewriting and gzip capabilities. Other dependencies may be required if you choose to build NGINX with additional modules. Monitor the output of the configure command discussed in the following sections for information on which modules may be missing. For example, if you plan to use SSL certificates to encrypt traffic with TLS, you'll need to install the OpenSSL library. To do so, issue the following command.

sudo apt install libssl-dev

Cloning the NGINX GitHub repository

Using your preferred method, clone the NGINX repository into your development directory. See Cloning a GitHub Repository for additional help.

git clone https://github.com/nginx/nginx.git

Configuring the build

Prior to building NGINX, you must run the configure script with appropriate flags. This will generate a Makefile in your NGINX source root directory that can then be used to compile NGINX with options specified during configuration.

From the NGINX source code repository's root directory:

auto/configure

Important

Configuring the build without any flags will compile NGINX with the default set of options. Please refer to https://nginx.org/en/docs/configure.html for a full list of available build configuration options.

Compiling

The configure script will generate a Makefile in the NGINX source root directory upon successful execution. To compile NGINX into a binary, issue the following command from that same directory:

make

Location of binary and installation

After successful compilation, a binary will be generated at <NGINX_SRC_ROOT_DIR>/objs/nginx. To install this binary, issue the following command from the source root directory:

sudo make install

Important

The binary will be installed into the /usr/local/nginx/ directory.

Running and testing the installed binary

To run the installed binary, issue the following command:

sudo /usr/local/nginx/sbin/nginx

You may test NGINX operation using curl.

curl localhost

The output of which should start with:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>

Asking questions and reporting issues

See our Support guidelines for information on how discuss the codebase, ask troubleshooting questions, and report issues.

Contributing code

Please see the Contributing guide for information on how to contribute code.

Additional help and resources

  • See the NGINX Community Blog for more tips, tricks and HOW-TOs related to NGINX and related projects.
  • Access nginx.org, your go-to source for all documentation, information and software related to the NGINX suite of projects.

Changelog

See our changelog to keep track of updates.

License

2-clause BSD-like license


Additional documentation available at: https://nginx.org/en/docs

About

The official NGINX Open Source repository.

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages