Skip to content


linux下安装rabbitmq及php-amqplib

补发丢失的贴子。

linux下安装rabbitmq及php-amqplib

一.linux 安装 git

yum 自带git 版本太低了
git version 1.7.1

yum remove git
yum -y install curl-devel expat-devel gettext-devel openssl-devel zlib-devel gcc perl-ExtUtils-MakeMaker
https://github.com/git/git/archive/v2.21.0.tar.gz
tar zxvf v2.21.0.tar.gz
cd git-2.21.0/
make configure
./configure –prefix=/usr/local/git –with-iconv=/usr/local/
make
make install

/usr/local/git/bin/git –version
git version 2.21.0

ln -s /usr/local/git/bin/git /usr/bin/git

git clone –no-checkout ‘https://github.com/php-amqplib/php-amqplib.git’ ‘/opt/php-5.4.45_phar/lib/composer/vendor/php-amqplib/php-amqplib’

SSL connect error fatal: unable to access ‘https://github.com/php-amqplib/php-amqplib.git/’: SSL connect error
git config –global http.sslversion tlsv1 vi /etc/hosts 192.30.255.112 github.com

二.安装composer

Composer 需要 PHP 5.3.2+ openssl 1.0.1+才能运行。

openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013
php编译时不能带–with-curlwrappers 和–disable-phar

php查看编译参数
php -i |grep configure
Configure Command => ‘./configure’ ‘–prefix=/opt/php-5.4.45’ ‘–with-config-file-path=/opt/php-5.4.45/etc’ ‘–with-mysql=/opt/mysql’ ‘–with-mysqli=/opt/mysql/bin/mysql_config’ ‘–with-iconv-dir=/usr/local’ ‘–with-freetype-dir’ ‘–with-jpeg-dir’ ‘–with-png-dir’ ‘–with-zlib’ ‘–with-libxml-dir=/usr’ ‘–disable-rpath’ ‘–enable-bcmath’ ‘–enable-shmop’ ‘–enable-sysvsem’ ‘–enable-inline-optimization’ ‘–with-curl’ ‘–with-curlwrappers’ ‘–enable-mbregex’ ‘–enable-cgi’ ‘–enable-fpm’ ‘–enable-mbstring’ ‘–with-mcrypt’ ‘–with-gd’ ‘–enable-gd-native-ttf’ ‘–with-openssl’ ‘–with-mhash’ ‘–enable-pcntl’ ‘–enable-sockets’ ‘–with-xmlrpc’ ‘–enable-zip’ ‘–enable-soap’ ‘–enable-xml’ ‘–disable-debug’ ‘–disable-ipv6’ ‘–without-pear’ ‘–disable-phar’ ‘–enable-ftp’ ‘–with-pdo-mysql=/opt/mysql’

–disable-phar 错误

Some settings on your machine make Composer unable to work properly.
Make sure that you fix the issues listed below and run this script again:

The phar extension is missing.
Install it or recompile php without –disable-phar

–with-curlwrappers 错误
PHP was compiled with –with-curlwrappers which will cause issues with HTTP authentication and GitHub. Recompile it without this flag if possible

git 没安装错误
sh: git: command not found

wget https://getcomposer.org/composer.phar ln -s /opt/php/bin/php /usr/bin/php php composer.phar
这将返回给你一个可执行的命令列表。

或者安装成全局方式
mv composer.phar /usr/bin/composer chmod +x /usr/bin/composer composer
创建一个composer.json
{ “require”: { “monolog/monolog”: “1.0.*”, “php-amqplib/php-amqplib”: “>=2.6.1” } }

创建国内镜像
composer clearcache composer config -g repo.packagist composer https://packagist.phpcomposer.com

建议不要用root运行,
运行时compose会在当前用户下创建一个可写的cache目录/home//.compose
sudo -uandychu composer config -g repo.packagist composer https://packagist.phpcomposer.com
会composer.json中添加
“repositories”: { “packagist”: { “type”: “composer”, “url”: “https://packagist.phpcomposer.com” } }

命令行下
php composer.phar install
或者全局方式
composer up

Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals

  • Installing php-amqplib/php-amqplib (v2.8.1): Downloading (failed)
    Downloading (failed)
    Downloading (failed) Failed to download php-amqplib/php-amqplib from dist: Th
    e “https://api.github.com/repos/php-amqplib/php-amqplib/zipball/84449ffd3f5a7466
    bbee3946facb3746ff11f075″ file could not be downloaded: SSL operation failed wit
    h code 1. OpenSSL Error messages:
    error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
    Failed to enable crypto
    failed to open stream: operation failed
    Now trying to download from source
  • Installing php-amqplib/php-amqplib (v2.8.1): Cloning 84449ffd3f from cache
    Writing lock file
    Generating autoload files

vi php.ini
将/opt/php-5.4.45_phar/lib/composer 放入include_path和 open_basedir

reload php

三.linux 安装 Erlang


yum install ncurses ncurses-base ncurses-devel ncurses-libs ncurses-static ncurses-term ocaml-curses ocaml-curses-devel -y
wget http://erlang.org/download/otp_src_21.2.tar.gz
tar zxvf otp_src_21.2.tar.gz
cd otp_src_21.2
./configure –with-ssl -enable-threads -enable-smmp-support -enable-kernel-poll –enable-hipe –without-javac
make
make install
/usr/local/bin/erl
Erlang/OTP 21 [erts-10.2] [source] [64-bit] [smp:40:40] [ds:40:40:10] [async-threads:1] [hipe]

Eshell V10.2 (abort with ^G)
1> halt().

四.linux 安装 rabbitmq

http://www.rabbitmq.com/download.html
wget https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.7.11/rabbitmq-server-generic-unix-3.7.11.tar.xz tar xvf rabbitmq-server-generic-unix-3.7.11.tar.xz mv rabbitmq_server-3.7.11 /opt/ cd /opt ln -s rabbitmq_server-3.7.11 rabbitmq cd /opt/rabbitmq/sbin ./rabbitmq-server &


## ##
## ## RabbitMQ 3.7.11. Copyright (C) 2007-2019 Pivotal Software, Inc.
########## Licensed under the MPL. See http://www.rabbitmq.com/
###### ##
########## Logs: /opt/rabbitmq/var/log/rabbitmq/[email protected]
/opt/rabbitmq/var/log/rabbitmq/rabbit@c1gstudio_upgrade.log

          Starting broker...

completed with 0 plugins.

[bin]# ./rabbitmqctl status
Status of node rabbit@c1gstudio …
[{pid,28884},
{running_applications,
[{rabbit,”RabbitMQ”,”3.7.11″},
{mnesia,”MNESIA CXC 138 12″,”4.15.5″},
{os_mon,”CPO CXC 138 46″,”2.4.7″},
{sysmon_handler,”Rate-limiting system_monitor event handler”,”1.1.0″},
{rabbit_common,
“Modules shared by rabbitmq-server and rabbitmq-erlang-client”,
“3.7.11”},
{ranch,”Socket acceptor pool for TCP protocols.”,”1.7.1″},
{ssl,”Erlang/OTP SSL application”,”9.1″},
{public_key,”Public key infrastructure”,”1.6.4″},
{asn1,”The Erlang ASN1 compiler version 5.0.8″,”5.0.8″},
{inets,”INETS CXC 138 49″,”7.0.3″},
{recon,”Diagnostic tools for production use”,”2.3.6″},
{xmerl,”XML parser”,”1.3.18″},
{jsx,”a streaming, evented json parsing toolkit”,”2.9.0″},
{crypto,”CRYPTO”,”4.4″},
{lager,”Erlang logging framework”,”3.6.5″},
{goldrush,”Erlang event stream processor”,”0.1.9″},
{compiler,”ERTS CXC 138 10″,”7.3″},
{syntax_tools,”Syntax tools”,”2.1.6″},
{sasl,”SASL CXC 138 11″,”3.3″},
{stdlib,”ERTS CXC 138 10″,”3.7″},
{kernel,”ERTS CXC 138 10″,”6.2″}]},
{os,{unix,linux}},
{erlang_version,
“Erlang/OTP 21 [erts-10.2] [source] [64-bit] [smp:40:40] [ds:40:40:10] [async-threads:640] [hipe]\n”},
{memory,
[{connection_readers,0},
{connection_writers,0},
{connection_channels,0},
{connection_other,0},
{queue_procs,0},
{queue_slave_procs,0},
{plugins,10044},
{other_proc,33404336},
{metrics,197308},
{mgmt_db,0},
{mnesia,73360},
{other_ets,2314472},
{binary,150240},
{msg_index,29488},
{code,20364814},
{atom,1082561},
{other_system,30248961},
{allocated_unused,50253824},
{reserved_unallocated,0},
{strategy,rss},
{total,[{erlang,87875584},{rss,113528832},{allocated,138129408}]}]},
{alarms,[]},
{listeners,[{clustering,25672,”::”},{amqp,5672,”0.0.0.0″}]},
{vm_memory_calculation_strategy,rss},
{vm_memory_high_watermark,0.4},
{vm_memory_limit,13413631590},
{disk_free_limit,50000000},
{disk_free,322518425600},
{file_descriptors,
[{total_limit,51100},
{total_used,2},
{sockets_limit,45988},
{sockets_used,0}]},
{processes,[{limit,1048576},{used,253}]},
{run_queue,1},
{uptime,128},
{kernel,{net_ticktime,60}}]

启动服务: ./rabbitmq-server &

查看服务状态:./rabbitmqctl status

关闭服务:./rabbitmqctl stop

启动管理 ./rabbitmq-plugins enable rabbitmq_management

查看mq用户:./rabbitmqctl list_users

查看用户权限:./rabbitmqctl list_user_permissions guest

新增用户: ./rabbitmqctl add_user admin 123456
./rabbitmqctl add_user admin tEneYxJm
./rabbitmqctl add_user yjsworker 7G2hMuXf

设为管理员
./rabbitmqctl set_user_tags admin administrator

编辑配置文件

cd /opt/rabbitmq/etc/rabbitmq
wget https://raw.githubusercontent.com/rabbitmq/rabbitmq-server/master/docs/rabbitmq.conf.example
cp rabbitmq.conf.example rabbitmq.conf

vi rabbitmq.conf
listeners.tcp.local = 192.168.0.37:5672
management.tcp.port = 15672
management.tcp.ip = 192.168.0.37

management.http_log_dir = /var/log/nginx/access.log

management.tcp.port = 15672
management.tcp.ip = 192.168.0.37

五.开机启动

vi /etc/rc.local /opt/rabbitmq/sbin/rabbitmq-server &

六.iptables


iptables -A INPUT -s 192.168.0.0/24 -p tcp -m tcp –dport 5672 -j ACCEPT
iptables -A INPUT -s 192.168.0.40/32 -p tcp -m tcp –dport 15672 -j ACCEPT
/etc/init.d/iptables save

七.nginx配置

vi /opt/nginx/conf/nginx.conf

server
{
listen 80;
server_name admin.c1gstudio.com;
index index.html index.htm index.php;
root /opt/htdocs/www;

    include manageip.conf;
    deny    all;

     location /rabbit/ {
      proxy_pass        http://192.168.0.37:15672/;
      proxy_set_header  Host        $host;
      proxy_set_header  X-Real-IP   $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
     }            

     location / {
      proxy_pass        http://192.168.0.37:80/;
      proxy_set_header  Host        $host;
      proxy_set_header  X-Real-IP   $remote_addr;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
      #proxy_set_header X-Forwarded-For $remote_addr;
      proxy_redirect    off;
     }            

         access_log  /opt/nginx/logs/access.log  access;
 }

八.测试

打开send.php文件:

<?php

require_once DIR . ‘/vendor/autoload.php’;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

// RabbitMQ 默认端口5672, 默认账号密码: guest / guest
// $host = ‘localhost’;
$host = ‘192.168.99.100’;
$port = ‘5672’;
$username = ‘guest’;
$password = ‘guest’;

// $connection = new AMQPStreamConnection(‘localhost’, 5672, ‘guest’, ‘guest’);
$connection = new AMQPStreamConnection($host, $port, $username, $password);
$channel = $connection->channel();
$channel->queue_declare(‘hello’, false, false, false, false);

$msg = new AMQPMessage(‘Hello World!’);
$channel->basic_publish($msg, ”, ‘hello’);
echo ” [x] Sent ‘Hello World!’\n”;

$channel->close();
$connection->close();

打开 receive.php 文件:

<?php
// file: receive.php
require_once DIR . ‘/vendor/autoload.php’;
use PhpAmqpLib\Connection\AMQPStreamConnection;

// RabbitMQ 默认端口5672, 默认账号密码: guest / guest
// $host = ‘localhost’;
// $host = ‘5672’;
$host = ‘192.168.99.100’;
$port = ‘5672’;
$username = ‘guest’;
$password = ‘guest’;

$connection = new AMQPStreamConnection($host, $port, $username, $password);
$channel = $connection->channel();

$queueName = ‘hello-test’;
$channel->queue_declare($queueName, false, false, false, false);

echo ‘ [*] Waiting for messages. To exit press CTRL+C’, “\n”;

$callback = function($msg) {
echo ” [x] Received: {“, $msg->body, “}\n”;
};

$channel->basic_consume($queueName, ”, false, true, false, false, $callback);

while(count($channel->callbacks)) {
$channel->wait();
}

发送和结束队列消息
先执行receive.php.
再执行send.php文件,来发送消息:

$ php send.php
[x] Sent: {18-02-10 02:35:15: Hello World!}
$ php send.php
[x] Sent: {18-02-10 02:35:34: Hello World!}

https://docs.phpcomposer.com/01-basic-usage.htmlhttp://www.rabbitmq.com/tutorials/tutorial-one-php.html

php-amqplib amqp-ext 性能对比

https://blog.forma-pro.com/php-amqp-clients-benchmark-them-all-8a4e6adb1a6b

RabbitMQ的用户角色分类:
none、management、policymaker、monitoring、administrator

RabbitMQ各类角色描述:
none
不能访问 management plugin

management
用户可以通过AMQP做的任何事外加:
列出自己可以通过AMQP登入的virtual hosts
查看自己的virtual hosts中的queues, exchanges 和 bindings
查看和关闭自己的channels 和 connections
查看有关自己的virtual hosts的“全局”的统计信息,包含其他用户在这些virtual hosts中的活动。

policymaker
management可以做的任何事外加:
查看、创建和删除自己的virtual hosts所属的policies和parameters

monitoring
management可以做的任何事外加:
列出所有virtual hosts,包括他们不能登录的virtual hosts
查看其他用户的connections和channels
查看节点级别的数据如clustering和memory使用情况
查看真正的关于所有virtual hosts的全局的统计信息

administrator
policymaker和monitoring可以做的任何事外加:
创建和删除virtual hosts
查看、创建和删除users
查看创建和删除permissions
关闭其他用户的connections

创建用户并设置角色:
可以创建管理员用户,负责整个MQ的运维,例如:
$sudo rabbitmqctl add_user user_admin passwd_admin
赋予其administrator角色:
$sudo rabbitmqctl set_user_tags user_admin administrator

可以创建RabbitMQ监控用户,负责整个MQ的监控,例如:
$sudo rabbitmqctl add_user user_monitoring passwd_monitor
赋予其monitoring角色:
$sudo rabbitmqctl set_user_tags user_monitoring monitoring

可以创建某个项目的专用用户,只能访问项目自己的virtual hosts
$sudo rabbitmqctl add_user user_proj passwd_proj
赋予其monitoring角色:
$sudo rabbitmqctl set_user_tags user_proj management

创建和赋角色完成后查看并确认:
$sudo rabbitmqctl list_users

RabbitMQ 权限控制
默认virtual host:”/”
默认用户:guest
guest具有”/”上的全部权限,仅能有localhost访问RabbitMQ包括Plugin,建议删除或更改密码。可通过将配置文件中loopback_users置孔来取消其本地访问的限制:
[{rabbit, [{loopback_users, []}]}]

用户仅能对其所能访问的virtual hosts中的资源进行操作。这里的资源指的是virtual hosts中的exchanges、queues等,操作包括对资源进行配置、写、读。配置权限可创建、删除、资源并修改资源的行为,写权限可向资源发送消息,读权限从资源获取消息。比如:
exchange和queue的declare与delete分别需要exchange和queue上的配置权限
exchange的bind与unbind需要exchange的读写权限
queue的bind与unbind需要queue写权限exchange的读权限
发消息(publish)需exchange的写权限
获取或清除(get、consume、purge)消息需queue的读权限

对何种资源具有配置、写、读的权限通过正则表达式来匹配,具体命令如下:
set_permissions [-p ]
其中, 的位置分别用正则表达式来匹配特定的资源,如’^(amq.gen.*|amq.default)$’可以匹配server生成的和默认的exchange,’^$’不匹配任何资源

需要注意的是RabbitMQ会缓存每个connection或channel的权限验证结果、因此权限发生变化后需要重连才能生效。

为用户赋权:
$sudo rabbitmqctl set_permissions -p /vhost1 user_admin ‘.’ ‘.’ ‘.*’
该命令使用户user_admin具有/vhost1这个virtual host中所有资源的配置、写、读权限以便管理其中的资源

按用户查看权限:

$sudo rabbitmqctl list_user_permissions user_admin

按服务器查看权限

$sudo rabbitmqctl list_permissions -p /vhost1

Fatal error: Uncaught exception ‘PhpAmqpLib\Exception\AMQPProtocolConnectionException’ with message ‘UNEXPECTED_FRAME – expected content header for class 60, got non content header frame instead’ in /opt/php-5.4.45/lib/composer/vendor/php-amqplib/php-amqplib/PhpAmqpLib/Connection/AbstractConnection.php:715 Stack trace: #0 [internal function]: PhpAmqpLib\Connection\AbstractConnection->connection_close(Object(PhpAmqpLib\Wire\AMQPReader)) #1 /opt/php-5.4.45/lib/composer/vendor/php-amqplib/php-amqplib/PhpAmqpLib/Channel/AbstractChannel.php(211): call_user_func(Array, Object(PhpAmqpLib\Wire\AMQPReader)) #2 /opt/php-5.4.45/lib/composer/vendor/php-amqplib/php-amqplib/PhpAmqpLib/Channel/AbstractChannel.php(369): PhpAmqpLib\Channel\AbstractChannel->dispatch(‘10,50’, ‘\x01\xF9]UNEXPECTED_F…’, NULL) #3 /opt/php-5.4.45/lib/composer/vendor/php-amqplib/php-amqplib/PhpAmqpLib/Connection/AbstractConnection.php(644): PhpAmqpLib\Channel\AbstractChannel->wait() #4 /opt/php-5.4.45/lib/composer/vendor/php-amqplib/php-amqplib/PhpAmqpLib/Chan in /opt/php-5.4.45/lib/composer/vendor/php-amqplib/php-amqplib/PhpAmqpLib/Connection/AbstractConnection.php on line 715

后续安装参考
https://help.aliyun.com/document_detail/53100.html?spm=a2c4g.11186623.0.0.503b522f7G2rRn

Posted in 消息rabbitmq.

Tagged with , .


nginx自适应https的反向代理

方式一,写死地址,用变量

最简洁

map $scheme $online_proxy_www {
default 39.156.66.10;
}

proxy_pass $scheme://$online_proxy_www:$server_port;

方式二,写两个upstream,再用proxy_pass覆盖法

缺点需要维护2个upsteam

upstream online_proxy_www {
server 39.156.66.10:80;
}
upstream online_proxy_www_https {
server 39.156.66.10:443;
}

proxy_pass $scheme://online_proxy_www;

自适应https

if ( $scheme = https) {
proxy_pass $scheme://online_proxy_www_https;
}

方式三,upstream backup法

最简单,缺点会多一次请求,多个错误日志

upstream online_proxy_www {
server 39.156.66.10:80;39.156.66.10
server 39.156.66.10:443 backup;
}
proxy_pass $scheme://online_proxy_www;

==========================

nginx.conf示例

upstream online_proxy_www {
    server   39.156.66.10:80;
    #server   39.156.66.10:443 backup;
}
upstream online_proxy_www_https {
    server   39.156.66.10:443;
}


server
{
    listen       80;
    listen       443 ssl;
    server_name  blog.c1gstudio.com;
    index index.html index.htm index.php;
    root  /opt/htdocs/www;
    access_log  /var/log/nginx/blog.c1gstudio.com.log  access ;

    include ssl.conf;

    location /
    {
        proxy_set_header Host  $host;
        proxy_set_header X-Forwarded-For $proxypass_forwarded_for;
        proxy_pass $scheme://$online_proxy_www:$server_port;

        add_header      X-Cache   C1GPROXY1;
    }


}

Posted in Nginx.

Tagged with , .


部分贴子丢失

服务商自动升级了DB,导致乱码而丢失了部分贴子.

Posted in 技术.


openresty+lua实现WAF应用防火墙

1.#基础包安装

yum -y install readline-devel pcre-devel zlib zlib-devel gcc

2.升级openssl

#yum -y openssl-devel

openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013

wget –no-check-certificate https://www.openssl.org/source/openssl-1.1.1l.tar.gz
tar -zxvf openssl-1.1.1l.tar.gz
cd openssl-1.1.1l
./config shared zlib
make && make install

#ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key

备份当前Openssl
mv /usr/bin/openssl /usr/bin/openssl.old
mv /usr/lib64/openssl /usr/lib64/openssl.old

使用新版Openssl
ln -s /usr/local/bin/openssl /usr/bin/openssl
ln -s /usr/local/include/openssl/ /usr/include/openssl
ln -s /usr/local/lib64/libssl.so.1.1 /usr/lib64/libssl.so.1.1
ln -s /usr/local/lib64/libcrypto.so.1.1 /usr/lib64/libcrypto.so.1.1

更新动态链接库数据
echo “/usr/local/lib/” >> /etc/ld.so.conf
ldconfig

openssl version
openssl: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory
ln -s /usr/local/lib64/libssl.so.1.1 /usr/lib64/libssl.so.1.1
ln -s /usr/local/lib64/libcrypto.so.1.1 /usr/lib64/libcrypto.so.1.1

openssl version
OpenSSL 1.1.1l 24 Aug 2021

3.安装pcre

pcre没找到,编辑时加上–with-pcre=../pcre-8.30 \
0.10/src/ngx_stream_lua_regex.c:205: undefined reference to `pcre_jit_stack_alloc’
collect2: ld returned 1 exit status

#wget -nv http://downloads.sourceforge.net/project/pcre/pcre/8.30/pcre-8.30.tar.gz -O pcre-8.30.tar.gz

wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.30.tar.gz
tar xzvf pcre-8.30.tar.gz
cd pcre-8.30
./configure –enable-utf8 –enable-unicode-properties
make
make install
ln -s /lib64/libpcre.so.0.0.1 /lib64/libpcre.so.1

4.下载ngx_cache_purge清缓组件

wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
tar zxvf ngx_cache_purge-2.3.tar.gz

5.安装openresty

wget https://openresty.org/download/openresty-1.19.9.1.tar.gz
tar zxvf openresty-1.19.9.1.tar.gz
cd openresty-1.19.9.1

伪装openresty为xcdn
sed -i ‘s/”openresty/”xcdn/g’ bundle/nginx-1.19.9/src/core/nginx.h
sed -i “s#Server: openresty#Server: xcdn#” bundle/nginx-1.19.9/src/http/ngx_http_header_filter_module.c
sed -i “s#\”


openresty<\/center>\”#\”


xcdn<\/center>\”#” bundle/nginx-1.19.9/src//http/ngx_http_special_response.c

./configure –user=www –group=website –prefix=/opt/openresty-1.19.9.1 \
–with-http_ssl_module –with-http_v2_module –with-http_realip_module –with-http_addition_module \
–with-http_geoip_module \
–with-http_gzip_static_module \
–with-http_auth_request_module \
–with-http_secure_link_module \
–with-http_degradation_module \
–with-http_stub_status_module \
–add-module=../ngx_cache_purge-2.3 \
–with-pcre=../pcre-8.30 \
–with-cc-opt=”-I /usr/local/include/openssl/ ” \
–with-ld-opt=”-L/usr/local/lib64″

gmake
gmake install

复制原配置文件
cd /opt/nginx/conf/
cp -ar ssl webip.conf geo.*.conf GeoIP.dat manageip.conf fcgi.conf htpasswd nginx.conf /opt/openresty-1.19.9.1/nginx/conf/

4.下载和配置 ngx_lua_waf

nginx下常见的开源 waf 有 mod_security、naxsi、ngx_lua_waf 这三个,ngx_lua_waf 性能高和易用性强,基本上零配置,而且常见的攻击类型都能防御,是比较省心的选择。

其git 地址为 https://github.com/loveshell/ngx_lua_waf
wget --no-check-certificate https://github.com/loveshell/ngx_lua_waf/archive/master.zip
unzip master.zip
mv ngx_lua_waf-master /opt/openresty-1.19.9.1/nginx/conf/waf
chown -R www:website /opt/openresty-1.19.9.1/nginx/conf
chown -R www:website /opt/openresty-1.19.9.1/nginx/logs
chmod 775 /opt/openresty-1.19.9.1/nginx/conf
chmod 775 /opt/openresty-1.19.9.1/nginx/conf/waf
chmod 775 /opt/openresty-1.19.9.1/nginx/conf/waf/wafconf
chmod 664 /opt/openresty-1.19.9.1/nginx/conf/.

mkdir -p /opt/openresty-1.19.9.1/nginx/logs/hack
chown www:website /opt/openresty-1.19.9.1/nginx/logs/hack
chmod -R 775 /opt/openresty-1.19.9.1/nginx/logs/hack

测试配置文件
/opt/openresty-1.19.9.1/nginx/sbin/nginx -t

注意和tengine的不兼容配置
注释掉server_info和#server_tag
[emerg] unknown directive “server_info” in /opt/openresty-1.19.9.1/nginx/conf/nginx.conf:49

#server_info off;

#server_tag off;

在http段增加清除server头
more_clear_headers "Server";

去除dso段

limit_req_zone 不支持多个key
ginx: [emerg] invalid number of arguments in “limit_req_zone” directive in /opt/openresty-1.19.9.1/nginx/conf/nginx.conf:90

#limit_req_zone $binary_remote_addr $uri zone=two:30m rate=20r/s;

5.配置ngx_lua_waf

https://github.com/loveshell/ngx_lua_waf在nginx.conf的http段添加

lua_package_path "/opt/openresty-1.19.9.1/lualib/?.lua;/opt/nginx/conf/waf/?.lua";
lua_shared_dict limit 10m;
init_by_lua_file  /opt/openresty-1.19.9.1/nginx/conf/waf/init.lua; 
access_by_lua_file /opt/openresty-1.19.9.1/nginx/conf/waf/waf.lua;

配置config.lua里的waf规则目录(一般在waf/conf/目录下)

RulePath = "/opt/nginx/conf/waf/wafconf/"

然后重启nginx即可
部署完毕可以尝试如下命令:

curl http://xxxx/test.php?id=../etc/passwd
日志文件名称格式如下:虚拟主机名_sec.log

配置时一些错误
nginx: [alert] failed to load the ‘resty.core’ module (https://github.com/openresty/lua-resty-core); ensure you are using an OpenResty release from https://openresty.org/en/download.html (reason: module ‘resty.core’ not found:
no field package.preload[‘resty.core’]
no file ‘/opt/nginx/conf/waf/resty/core.lua’
no file ‘/opt/openresty-1.19.9.1/lualib/resty/resty/core.lua’
no file ‘/opt/openresty-1.19.9.1/site/lualib/resty/core.so’
no file ‘/opt/openresty-1.19.9.1/lualib/resty/core.so’
no file ‘./resty/core.so’
no file ‘/usr/local/lib/lua/5.1/resty/core.so’
no file ‘/opt/openresty-1.19.9.1/luajit/lib/lua/5.1/resty/core.so’
no file ‘/usr/local/lib/lua/5.1/loadall.so’
no file ‘/opt/openresty-1.19.9.1/site/lualib/resty.so’
no file ‘/opt/openresty-1.19.9.1/lualib/resty.so’
no file ‘./resty.so’
no file ‘/usr/local/lib/lua/5.1/resty.so’
no file ‘/opt/openresty-1.19.9.1/luajit/lib/lua/5.1/resty.so’
no file ‘/usr/local/lib/lua/5.1/loadall.so’) in /opt/openresty-1.19.9.1/nginx/conf/nginx.conf:214

将/opt/openresty-1.19.9.1/lualib/?.lua; 加进lua_package_path
lua_package_path “/opt/openresty-1.19.9.1/lualib/?.lua;/opt/nginx/conf/waf/?.lua”;

user-agent中去除|bench,允许NetworkBench访问
“Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.77.34.5 Safari/537.36; NetworkBench/79.0.3917.0-8710402-0” “(HTTrack|harvest|audit|dirbuster|pangolin|nmap|sqln|-scan|hydra|Parser|libwww|BBBike|sqlmap|w3af|owasp|Nikto|fimap|havij|PycURL|zmeu|BabyKrokodil|netsparker|httperf|bench| SF/)”

user-agent中去除|PycURL,允许监控访问

openresty编辑说明
–help this message

–prefix=PATH set the installation prefix (default to /usr/local/openresty)

–with-debug enable debug logging

–with-no-pool-patch enable the no-pool patch for debugging memory issues

-jN pass -jN option to make while building LuaJIT 2.1

–without-http_echo_module disable ngx_http_echo_module
–without-http_xss_module disable ngx_http_xss_module
–without-http_coolkit_module disable ngx_http_coolkit_module
–without-http_set_misc_module disable ngx_http_set_misc_module
–without-http_form_input_module disable ngx_http_form_input_module
–without-http_encrypted_session_module
disable ngx_http_encrypted_session_module
–without-http_srcache_module disable ngx_http_srcache_module
–without-http_lua_module disable ngx_http_lua_module
–without-http_lua_upstream_module disable ngx_http_lua_upstream_module
–without-http_headers_more_module disable ngx_http_headers_more_module
–without-http_array_var_module disable ngx_http_array_var_module
–without-http_memc_module disable ngx_http_memc_module
–without-http_redis2_module disable ngx_http_redis2_module
–without-http_redis_module disable ngx_http_redis_module
–without-http_rds_json_module disable ngx_http_rds_json_module
–without-http_rds_csv_module disable ngx_http_rds_csv_module
–without-stream_lua_module disable ngx_stream_lua_module
–without-ngx_devel_kit_module disable ngx_devel_kit_module
–without-stream disable TCP/UDP proxy module
–without-http_ssl_module disable ngx_http_ssl_module
–without-stream_ssl_module disable ngx_stream_ssl_module

–with-http_iconv_module enable ngx_http_iconv_module
–with-http_drizzle_module enable ngx_http_drizzle_module
–with-http_postgres_module enable ngx_http_postgres_module

–without-lua_cjson disable the lua-cjson library
–without-lua_tablepool disable the lua-tablepool library (and by consequence, the
lua-resty-shell library)
–without-lua_redis_parser disable the lua-redis-parser library
–without-lua_rds_parser disable the lua-rds-parser library
–without-lua_resty_dns disable the lua-resty-dns library
–without-lua_resty_memcached disable the lua-resty-memcached library
–without-lua_resty_redis disable the lua-resty-redis library
–without-lua_resty_mysql disable the lua-resty-mysql library
–without-lua_resty_upload disable the lua-resty-upload library
–without-lua_resty_upstream_healthcheck
disable the lua-resty-upstream-healthcheck library
–without-lua_resty_string disable the lua-resty-string library
–without-lua_resty_websocket disable the lua-resty-websocket library
–without-lua_resty_limit_traffic disable the lua-resty-limit-traffic library
–without-lua_resty_lock disable the lua-resty-lock library
–without-lua_resty_lrucache disable the lua-resty-lrucache library
–without-lua_resty_signal disable the lua-resty-signal library (and by consequence,
the lua-resty-shell library)
–without-lua_resty_shell disable the lua-resty-shell library
–without-lua_resty_core disable the lua-resty-core library

–with-luajit=DIR use the external LuaJIT 2.1 installation specified by DIR
–with-luajit-xcflags=FLAGS Specify extra C compiler flags for LuaJIT 2.1
–with-luajit-ldflags=FLAGS Specify extra C linker flags for LuaJIT 2.1
–without-luajit-lua52 Turns off the LuaJIT extensions from Lua 5.2 that may break
backward compatibility
–without-luajit-gc64 Turns off the LuaJIT GC64 mode (which is enabled by default
on x86_64)

–with-libdrizzle=DIR specify the libdrizzle 1.0 (or drizzle) installation prefix
–with-libpq=DIR specify the libpq (or postgresql) installation prefix
–with-pg_config=PATH specify the path of the pg_config utility

Options directly inherited from nginx

–sbin-path=PATH set nginx binary pathname
–modules-path=PATH set modules path
–conf-path=PATH set nginx.conf pathname
–error-log-path=PATH set error log pathname
–pid-path=PATH set nginx.pid pathname
–lock-path=PATH set nginx.lock pathname

–user=USER set non-privileged user for
worker processes
–group=GROUP set non-privileged group for
worker processes

–build=NAME set build name
–builddir=DIR set build directory

–with-select_module enable select module
–without-select_module disable select module
–with-poll_module enable poll module
–without-poll_module disable poll module

–with-threads enable thread pool support

–with-file-aio enable file AIO support

–with-http_ssl_module enable ngx_http_ssl_module (default on)
–with-http_v2_module enable ngx_http_v2_module
–with-http_realip_module enable ngx_http_realip_module
–with-http_addition_module enable ngx_http_addition_module
–with-http_xslt_module enable ngx_http_xslt_module
–with-http_xslt_module=dynamic enable dynamic ngx_http_xslt_module
–with-http_image_filter_module enable ngx_http_image_filter_module
–with-http_image_filter_module=dynamic
enable dynamic ngx_http_image_filter_module
–with-http_geoip_module enable ngx_http_geoip_module
–with-http_geoip_module=dynamic enable dynamic ngx_http_geoip_module
–with-http_sub_module enable ngx_http_sub_module
–with-http_dav_module enable ngx_http_dav_module
–with-http_flv_module enable ngx_http_flv_module
–with-http_mp4_module enable ngx_http_mp4_module
–with-http_gunzip_module enable ngx_http_gunzip_module
–with-http_gzip_static_module enable ngx_http_gzip_static_module
–with-http_auth_request_module enable ngx_http_auth_request_module
–with-http_random_index_module enable ngx_http_random_index_module
–with-http_secure_link_module enable ngx_http_secure_link_module
–with-http_degradation_module enable ngx_http_degradation_module
–with-http_slice_module enable ngx_http_slice_module
–with-http_stub_status_module enable ngx_http_stub_status_module

–without-http_charset_module disable ngx_http_charset_module
–without-http_gzip_module disable ngx_http_gzip_module
–without-http_ssi_module disable ngx_http_ssi_module
–without-http_userid_module disable ngx_http_userid_module
–without-http_access_module disable ngx_http_access_module
–without-http_auth_basic_module disable ngx_http_auth_basic_module
–without-http_mirror_module disable ngx_http_mirror_module
–without-http_autoindex_module disable ngx_http_autoindex_module
–without-http_geo_module disable ngx_http_geo_module
–without-http_map_module disable ngx_http_map_module
–without-http_split_clients_module disable ngx_http_split_clients_module
–without-http_referer_module disable ngx_http_referer_module
–without-http_rewrite_module disable ngx_http_rewrite_module
–without-http_proxy_module disable ngx_http_proxy_module
–without-http_fastcgi_module disable ngx_http_fastcgi_module
–without-http_uwsgi_module disable ngx_http_uwsgi_module
–without-http_scgi_module disable ngx_http_scgi_module
–without-http_grpc_module disable ngx_http_grpc_module
–without-http_memcached_module disable ngx_http_memcached_module
–without-http_limit_conn_module disable ngx_http_limit_conn_module
–without-http_limit_req_module disable ngx_http_limit_req_module
–without-http_empty_gif_module disable ngx_http_empty_gif_module
–without-http_browser_module disable ngx_http_browser_module
–without-http_upstream_hash_module
disable ngx_http_upstream_hash_module
–without-http_upstream_ip_hash_module
disable ngx_http_upstream_ip_hash_module
–without-http_upstream_least_conn_module
disable ngx_http_upstream_least_conn_module
–without-http_upstream_random_module
disable ngx_http_upstream_random_module
–without-http_upstream_keepalive_module
disable ngx_http_upstream_keepalive_module
–without-http_upstream_zone_module
disable ngx_http_upstream_zone_module

–with-http_perl_module enable ngx_http_perl_module
–with-http_perl_module=dynamic enable dynamic ngx_http_perl_module
–with-perl_modules_path=PATH set Perl modules path
–with-perl=PATH set perl binary pathname

–http-log-path=PATH set http access log pathname
–http-client-body-temp-path=PATH set path to store
http client request body temporary files
–http-proxy-temp-path=PATH set path to store
http proxy temporary files
–http-fastcgi-temp-path=PATH set path to store
http fastcgi temporary files
–http-uwsgi-temp-path=PATH set path to store
http uwsgi temporary files
–http-scgi-temp-path=PATH set path to store
http scgi temporary files

–without-http disable HTTP server
–without-http-cache disable HTTP cache

–with-mail enable POP3/IMAP4/SMTP proxy module
–with-mail=dynamic enable dynamic POP3/IMAP4/SMTP proxy module
–with-mail_ssl_module enable ngx_mail_ssl_module
–without-mail_pop3_module disable ngx_mail_pop3_module
–without-mail_imap_module disable ngx_mail_imap_module
–without-mail_smtp_module disable ngx_mail_smtp_module

–with-stream enable TCP/UDP proxy module (default on)
–with-stream=dynamic enable dynamic TCP/UDP proxy module
–with-stream_ssl_module enable ngx_stream_ssl_module (default on)
–with-stream_realip_module enable ngx_stream_realip_module
–with-stream_geoip_module enable ngx_stream_geoip_module
–with-stream_geoip_module=dynamic enable dynamic ngx_stream_geoip_module
–with-stream_ssl_preread_module enable ngx_stream_ssl_preread_module
–without-stream_limit_conn_module disable ngx_stream_limit_conn_module
–without-stream_access_module disable ngx_stream_access_module
–without-stream_geo_module disable ngx_stream_geo_module
–without-stream_map_module disable ngx_stream_map_module
–without-stream_split_clients_module
disable ngx_stream_split_clients_module
–without-stream_return_module disable ngx_stream_return_module
–without-stream_upstream_hash_module
disable ngx_stream_upstream_hash_module
–without-stream_upstream_least_conn_module
disable ngx_stream_upstream_least_conn_module
–without-stream_upstream_random_module
disable ngx_stream_upstream_random_module
–without-stream_upstream_zone_module
disable ngx_stream_upstream_zone_module

–with-google_perftools_module enable ngx_google_perftools_module
–with-cpp_test_module enable ngx_cpp_test_module

–add-module=PATH enable external module
–add-dynamic-module=PATH enable dynamic external module

–with-compat dynamic modules compatibility

–with-cc=PATH set C compiler pathname
–with-cpp=PATH set C preprocessor pathname
–with-cc-opt=OPTIONS set additional C compiler options
–with-ld-opt=OPTIONS set additional linker options
–with-cpu-opt=CPU build for the specified CPU, valid values:
pentium, pentiumpro, pentium3, pentium4,
athlon, opteron, sparc32, sparc64, ppc64

–without-pcre disable PCRE library usage
–with-pcre force PCRE library usage
–with-pcre=DIR set path to PCRE library sources
–with-pcre-opt=OPTIONS set additional build options for PCRE
–with-pcre-jit build PCRE with JIT compilation support

–with-zlib=DIR set path to zlib library sources
–with-zlib-opt=OPTIONS set additional build options for zlib
–with-zlib-asm=CPU use zlib assembler sources optimized
for the specified CPU, valid values:
pentium, pentiumpro

–with-libatomic force libatomic_ops library usage
–with-libatomic=DIR set path to libatomic_ops library sources

–with-openssl=DIR set path to OpenSSL library sources
–with-openssl-opt=OPTIONS set additional build options for OpenSSL

–dry-run dry running the configure, for testing only
–platform=PLATFORM forcibly specify a platform name, for testing only

参考:
接入层限流之OpenResty提供的Lua限流模块lua-resty-limit-tra
https://www.jianshu.com/p/687e63118d84

又拍云张聪:OpenResty 动态流控的几种姿势
https://www.cnblogs.com/upyun/p/10307741.html

Posted in Nginx.

Tagged with , .


升级安装Tenginer2.3.3+lua+ngx_lua支持WAF防护功能

1、安装或升级autoconf

安装jemalloc是可能出现autoconf版本不够高
configure.ac:2: error: Autoconf version 2.68 or higher is required
configure.ac:2: the top level
autom4te: /usr/bin/m4 failed with exit status: 63
Error 0 in autoconf

升级autoconf
yum -y install autogen autoconf
Package autoconf-2.63-5.1.el6.noarch already installed and latest version
Nothing to do

查询当前autoconf版本
rpm -qf /usr/bin/autoconf
autoconf-2.63-5.1.el6.noarch

下载并编译
wget ftp://ftp.gnu.org/gnu/autoconf/autoconf-2.68.tar.gz
tar zxvf autoconf-2.68.tar.gz
cd autoconf-2.68
./configure –prefix=/usr/

卸载当前版本
rpm -e –nodeps autoconf-2.63

安装
make && make install

查看版本
autoconf -V
autoconf (GNU Autoconf) 2.68
cd ..

2、jemalloc安装

github 地址 :https://github.com/jemalloc/jemalloc/tree/master
编译安装jemalloc

wget –no-check-certificate https://github.com/jemalloc/jemalloc/releases/download/5.2.1/jemalloc-5.2.1.tar.bz2

wget -O jemalloc-5.2.1.tar.gz https://github.com/jemalloc/jemalloc/archive/refs/tags/5.2.1.tar.gz
tar -xf jemalloc-5.2.1.tar.gz && cd jemalloc-5.2.1
./autogen.sh

make -j8
make install

如果/usr/local/lib 没在ldconfig中
echo ‘/usr/local/lib’ > /etc/ld.so.conf.d/local.conf
ldconfig
cd ..

3、lua安装

curl -R -O http://www.lua.org/ftp/lua-5.4.3.tar.gz
tar zxf lua-5.4.3.tar.gz
cd lua-5.4.3
make linux
make install
cd ..

4、安装luajit

然后从https://github.com/openresty/luajit2下载安装
https://github.com/openresty/luajit2/archive/refs/heads/v2.1-agentzh.zip
unzip luajit2-2.1-agentzh.zip
cd luajit2-2.1-agentzh
make && make install
cd ..

5、安装tengine

tengine 编译说明
–prefix= 指向安装目录
–sbin-path 指向(执行)程序文件(nginx)
–conf-path= 指向配置文件(nginx.conf)
–error-log-path= 指向错误日志目录
–pid-path= 指向pid文件(nginx.pid)
–lock-path= 指向lock文件(nginx.lock)(安装文件锁定,防止安装文件被别人利用,或自己误操作。)
–user= 指定程序运行时的非特权用户
–group= 指定程序运行时的非特权用户组
–builddir= 指向编译目录
–with-rtsig_module 启用rtsig模块支持(实时信号)
–with-select_module 启用select模块支持(一种轮询模式,不推荐在高载环境下使用)禁用:–without-select_module
–with-poll_module 启用poll模块支持(功能与select相同,与select特性相同,为一种轮询模式,不推荐在高载环境下使用)
–with-file-aio 启用file aio支持(一种APL文件传输格式)
–with-ipv6 启用ipv6支持
–with-http_ssl_module 启用ngx_http_ssl_module支持(使支持https请求,需已安装openssl)
–with-http_realip_module 启用ngx_http_realip_module支持(这个模块允许从请求标头更改客户端的IP地址值,默认为关)
–with-http_addition_module 启用ngx_http_addition_module支持(作为一个输出过滤器,支持不完全缓冲,分部分响应请求)
–with-http_xslt_module 启用ngx_http_xslt_module支持(过滤转换XML请求)
–with-http_image_filter_module 启用ngx_http_image_filter_module支持(传输JPEG/GIF/PNG 图片的一个过滤器)(默认为不启用。gd库要用到)
–with-http_geoip_module 启用ngx_http_geoip_module支持(该模块创建基于与MaxMind GeoIP二进制文件相配的客户端IP地址的ngx_http_geoip_module变量)
–with-http_sub_module 启用ngx_http_sub_module支持(允许用一些其他文本替换nginx响应中的一些文本)
–with-http_dav_module 启用ngx_http_dav_module支持(增加PUT,DELETE,MKCOL:创建集合,COPY和MOVE方法)默认情况下为关闭,需编译开启
–with-http_flv_module 启用ngx_http_flv_module支持(提供寻求内存使用基于时间的偏移量文件)
–with-http_gzip_static_module 启用ngx_http_gzip_static_module支持(在线实时压缩输出数据流)
–with-http_random_index_module 启用ngx_http_random_index_module支持(从目录中随机挑选一个目录索引)
–with-http_secure_link_module 启用ngx_http_secure_link_module支持(计算和检查要求所需的安全链接网址)
–with-http_degradation_module 启用ngx_http_degradation_module支持(允许在内存不足的情况下返回204或444码)
–with-http_stub_status_module 启用ngx_http_stub_status_module支持(获取nginx自上次启动以来的工作状态)
–without-http_charset_module 禁用ngx_http_charset_module支持(重新编码web页面,但只能是一个方向–服务器端到客户端,并且只有一个字节的编码可以被重新编码)
–without-http_gzip_module 禁用ngx_http_gzip_module支持(该模块同-with-http_gzip_static_module功能一样)
–without-http_ssi_module 禁用ngx_http_ssi_module支持(该模块提供了一个在输入端处理处理服务器包含文件(SSI)的过滤器,目前支持SSI命令的列表是不完整的)
–without-http_userid_module 禁用ngx_http_userid_module支持(该模块用来处理用来确定客户端后续请求的cookies)
–without-http_access_module 禁用ngx_http_access_module支持(该模块提供了一个简单的基于主机的访问控制。允许/拒绝基于ip地址)
–without-http_auth_basic_module禁用ngx_http_auth_basic_module(该模块是可以使用用户名和密码基于http基本认证方法来保护你的站点或其部分内容)
–without-http_autoindex_module 禁用disable ngx_http_autoindex_module支持(该模块用于自动生成目录列表,只在ngx_http_index_module模块未找到索引文件时发出请求。)
–without-http_geo_module 禁用ngx_http_geo_module支持(创建一些变量,其值依赖于客户端的IP地址)
–without-http_map_module 禁用ngx_http_map_module支持(使用任意的键/值对设置配置变量)
–without-http_split_clients_module 禁用ngx_http_split_clients_module支持(该模块用来基于某些条件划分用户。条件如:ip地址、报头、cookies等等)
–without-http_referer_module 禁用disable ngx_http_referer_module支持(该模块用来过滤请求,拒绝报头中Referer值不正确的请求)
–without-http_rewrite_module 禁用ngx_http_rewrite_module支持(该模块允许使用正则表达式改变URI,并且根据变量来转向以及选择配置。如果在server级 别设置该选项,那么他们将在 location之前生效。如果在location还有更进一步的重写规则,location部分的规则依然会被执行。如果这个URI重写是因为 location部分的规则造成的,那么 location部分会再次被执行作为新的URI。 这个循环会执行10次,然后Nginx会返回一个500错误。)
–without-http_proxy_module 禁用ngx_http_proxy_module支持(有关代理服务器)
–without-http_fastcgi_module 禁用ngx_http_fastcgi_module支持(该模块允许Nginx 与FastCGI 进程交互,并通过传递参数来控制FastCGI 进程工作。 )FastCGI一个常驻型的公共网关接口。
–without-http_uwsgi_module 禁用ngx_http_uwsgi_module支持(该模块用来医用uwsgi协议,uWSGI服务器相关)
–without-http_scgi_module 禁用ngx_http_scgi_module支持(该模块用来启用SCGI协议支持,SCGI协议是CGI协议的替代。它是一种应用程序与HTTP服务接口标准。它有些像FastCGI但他的设计 更容易实现。)
–without-http_memcached_module 禁用ngx_http_memcached_module支持(该模块用来提供简单的缓存,以提高系统效率)
-without-http_limit_zone_module 禁用ngx_http_limit_zone_module支持(该模块可以针对条件,进行会话的并发连接数控制)
–without-http_limit_req_module 禁用ngx_http_limit_req_module支持(该模块允许你对于一个地址进行请求数量的限制用一个给定的session或一个特定的事件)
–without-http_empty_gif_module 禁用ngx_http_empty_gif_module支持(该模块在内存中常驻了一个1*1的透明GIF图像,可以被非常快速的调用)
–without-http_browser_module 禁用ngx_http_browser_module支持(该模块用来创建依赖于请求报头的值。如果浏览器为modern ,则$modern_browser等于modern_browser_value指令分配的值;如 果浏览器为old,则$ancient_browser等于 ancient_browser_value指令分配的值;如果浏览器为 MSIE中的任意版本,则 $msie等于1)
–without-http_upstream_ip_hash_module 禁用ngx_http_upstream_ip_hash_module支持(该模块用于简单的负载均衡)
–with-http_perl_module 启用ngx_http_perl_module支持(该模块使nginx可以直接使用perl或通过ssi调用perl)
–with-perl_modules_path= 设定perl模块路径
–with-perl= 设定perl库文件路径
–http-log-path= 设定access log路径
–http-client-body-temp-path= 设定http客户端请求临时文件路径
–http-proxy-temp-path= 设定http代理临时文件路径
–http-fastcgi-temp-path= 设定http fastcgi临时文件路径
–http-uwsgi-temp-path= 设定http uwsgi临时文件路径
–http-scgi-temp-path= 设定http scgi临时文件路径
-without-http 禁用http server功能
–without-http-cache 禁用http cache功能
–with-mail 启用POP3/IMAP4/SMTP代理模块支持
–with-mail_ssl_module 启用ngx_mail_ssl_module支持
–without-mail_pop3_module 禁用pop3协议(POP3即邮局协议的第3个版本,它是规定个人计算机如何连接到互联网上的邮件服务器进行收发邮件的协议。是因特网电子邮件的第一个离 线协议标 准,POP3协议允许用户从服务器上把邮件存储到本地主机上,同时根据客户端的操作删除或保存在邮件服务器上的邮件。POP3协议是TCP/IP协议族中 的一员,主要用于 支持使用客户端远程管理在服务器上的电子邮件)
–without-mail_imap_module 禁用imap协议(一种邮件获取协议。它的主要作用是邮件客户端可以通过这种协议从邮件服务器上获取邮件的信息,下载邮件等。IMAP协议运行在 TCP/IP协议之上, 使用的端口是143。它与POP3协议的主要区别是用户可以不用把所有的邮件全部下载,可以通过客户端直接对服务器上的邮件进行操作。)
–without-mail_smtp_module 禁用smtp协议(SMTP即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。SMTP协议属于 TCP/IP协议族,它帮助每台计算机在发送或中转信件时找到下一个目的地。)
–with-google_perftools_module 启用ngx_google_perftools_module支持(调试用,剖析程序性能瓶颈)
–with-cpp_test_module 启用ngx_cpp_test_module支持
–add-module= 启用外部模块支持
–with-cc= 指向C编译器路径
–with-cpp= 指向C预处理路径
–with-cc-opt= 设置C编译器参数(PCRE库,需要指定–with-cc-opt=”-I /usr/local/include”,如果使用select()函数则需要同时增加文件描述符数量,可以通过–with-cc- opt=”-D FD_SETSIZE=2048”指定。)
–with-ld-opt= 设置连接文件参数。(PCRE库,需要指定–with-ld-opt=”-L /usr/local/lib”。)
–with-cpu-opt= 指定编译的CPU,可用的值为: pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64
–without-pcre 禁用pcre库
–with-pcre 启用pcre库
–with-pcre= 指向pcre库文件目录
–with-pcre-opt= 在编译时为pcre库设置附加参数
–with-md5= 指向md5库文件目录(消息摘要算法第五版,用以提供消息的完整性保护)
–with-md5-opt= 在编译时为md5库设置附加参数
–with-md5-asm 使用md5汇编源
–with-sha1= 指向sha1库目录(数字签名算法,主要用于数字签名)
–with-sha1-opt= 在编译时为sha1库设置附加参数
–with-sha1-asm 使用sha1汇编源
–with-zlib= 指向zlib库目录
–with-zlib-opt= 在编译时为zlib设置附加参数
–with-zlib-asm= 为指定的CPU使用zlib汇编源进行优化,CPU类型为pentium, pentiumpro
–with-libatomic 为原子内存的更新操作的实现提供一个架构
–with-libatomic= 指向libatomic_ops安装目录
–with-openssl= 指向openssl安装目录
–with-openssl-opt 在编译时为openssl设置附加参数
–with-debug 启用debug日志

wget http://tengine.taobao.org/download/tengine-2.3.3.tar.gz
tar zxvf tengine-2.3.3.tar.gz
cd tengine-2.3.3

./configure –user=www –group=website –prefix=/opt/tengine-2.3.3 \
–with-http_ssl_module –with-http_v2_module –with-http_realip_module –with-http_addition_module \
–with-http_geoip_module \
–with-http_gzip_static_module \
–with-http_auth_request_module \
–with-http_secure_link_module \
–with-http_degradation_module \
–with-http_stub_status_module \
–add-module=modules/ngx_http_concat_module \
–add-module=modules/ngx_http_footer_filter_module \
–add-module=modules/ngx_http_proxy_connect_module \
–add-module=modules/ngx_http_reqstat_module \
–add-module=modules/ngx_http_sysguard_module \
–add-module=modules/ngx_http_trim_filter_module \
–add-module=modules/ngx_http_upstream_check_module \
–add-module=modules/ngx_http_upstream_consistent_hash_module \
–add-module=modules/ngx_http_upstream_dynamic_module \
–add-module=modules/ngx_http_upstream_dyups_module \
–add-module=modules/ngx_http_upstream_session_sticky_module \
–add-module=modules/ngx_http_upstream_vnswrr_module \
–add-module=modules/ngx_http_user_agent_module \
–add-module=modules/ngx_multi_upstream_module \
–with-jemalloc \
–with-http_lua_module \
–with-luajit-lib=/usr/local/lib/ –with-luajit-inc=/usr/local/include/luajit-2.1/ –with-ld-opt=-Wl,-rpath,/usr/local/lib

make -j4
make install

cd /opt/tengine-2.3.3/
sbin/nginx -V
Tengine version: Tengine/2.3.3
nginx version: nginx/1.18.0
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-23) (GCC)
built with OpenSSL 1.0.2u 20 Dec 2019
TLS SNI support enabled
configure arguments: –user=www –group=website –prefix=/opt/tengine-2.3.3 –with-http_ssl_module –with-http_v2_module –with-http_realip_module –with-http_addition_module –with-http_geoip_module –with-http_gzip_static_module –with-http_auth_request_module –with-http_secure_link_module –with-http_degradation_module –with-http_stub_status_module –add-module=modules/ngx_http_concat_module –add-module=modules/ngx_http_footer_filter_module –add-module=modules/ngx_http_proxy_connect_module –add-module=modules/ngx_http_reqstat_module –add-module=modules/ngx_http_sysguard_module –add-module=modules/ngx_http_trim_filter_module –add-module=modules/ngx_http_upstream_check_module –add-module=modules/ngx_http_upstream_consistent_hash_module –add-module=modules/ngx_http_upstream_dynamic_module –add-module=modules/ngx_http_upstream_dyups_module –add-module=modules/ngx_http_upstream_session_sticky_module –add-module=modules/ngx_http_upstream_vnswrr_module –add-module=modules/ngx_http_user_agent_module –add-module=modules/ngx_multi_upstream_module –with-jemalloc –with-http_lua_module –with-luajit-lib=/usr/local/lib/ –with-luajit-inc=/usr/local/include/luajit-2.1/ –with-ld-opt=-Wl,-rpath,/usr/local/lib

查看安装的模块

sbin/nginx -m
Tengine version: Tengine/2.3.3
nginx version: nginx/1.18.0
nginx: loaded modules:
nginx: ngx_core_module (static)
nginx: ngx_errlog_module (static)
nginx: ngx_conf_module (static)
nginx: ngx_openssl_module (static)
nginx: ngx_regex_module (static)
nginx: ngx_events_module (static)
nginx: ngx_event_core_module (static)
nginx: ngx_epoll_module (static)
nginx: ngx_procs_module (static)
nginx: ngx_proc_core_module (static)
nginx: ngx_http_module (static)
nginx: ngx_http_core_module (static)
nginx: ngx_http_log_module (static)
nginx: ngx_http_upstream_module (static)
nginx: ngx_http_v2_module (static)
nginx: ngx_http_static_module (static)
nginx: ngx_http_gzip_static_module (static)
nginx: ngx_http_autoindex_module (static)
nginx: ngx_http_index_module (static)
nginx: ngx_http_mirror_module (static)
nginx: ngx_http_try_files_module (static)
nginx: ngx_http_auth_request_module (static)
nginx: ngx_http_auth_basic_module (static)
nginx: ngx_http_access_module (static)
nginx: ngx_http_limit_conn_module (static)
nginx: ngx_http_limit_req_module (static)
nginx: ngx_http_realip_module (static)
nginx: ngx_http_geo_module (static)
nginx: ngx_http_geoip_module (static)
nginx: ngx_http_map_module (static)
nginx: ngx_http_split_clients_module (static)
nginx: ngx_http_referer_module (static)
nginx: ngx_http_rewrite_module (static)
nginx: ngx_http_ssl_module (static)
nginx: ngx_http_proxy_module (static)
nginx: ngx_http_fastcgi_module (static)
nginx: ngx_http_uwsgi_module (static)
nginx: ngx_http_scgi_module (static)
nginx: ngx_http_grpc_module (static)
nginx: ngx_http_memcached_module (static)
nginx: ngx_http_empty_gif_module (static)
nginx: ngx_http_browser_module (static)
nginx: ngx_http_secure_link_module (static)
nginx: ngx_http_degradation_module (static)
nginx: ngx_http_upstream_hash_module (static)
nginx: ngx_http_upstream_ip_hash_module (static)
nginx: ngx_http_upstream_least_conn_module (static)
nginx: ngx_http_upstream_random_module (static)
nginx: ngx_http_upstream_keepalive_module (static)
nginx: ngx_http_upstream_zone_module (static)
nginx: ngx_http_stub_status_module (static)
nginx: ngx_http_proxy_connect_module (static)
nginx: ngx_http_reqstat_module (static)
nginx: ngx_http_sysguard_module (static)
nginx: ngx_http_upstream_check_module (static)
nginx: ngx_http_upstream_consistent_hash_module (static)
nginx: ngx_http_upstream_dynamic_module (static)
nginx: ngx_http_dyups_module (static)
nginx: ngx_http_upstream_vnswrr_module (static)
nginx: ngx_http_user_agent_module (static)
nginx: ngx_http_multi_upstream_module (static)
nginx: ngx_http_write_filter_module (static)
nginx: ngx_http_header_filter_module (static)
nginx: ngx_http_chunked_filter_module (static)
nginx: ngx_http_v2_filter_module (static)
nginx: ngx_http_range_header_filter_module (static)
nginx: ngx_http_gzip_filter_module (static)
nginx: ngx_http_postpone_filter_module (static)
nginx: ngx_http_ssi_filter_module (static)
nginx: ngx_http_charset_filter_module (static)
nginx: ngx_http_addition_filter_module (static)
nginx: ngx_http_userid_filter_module (static)
nginx: ngx_http_headers_filter_module (static)
nginx: ngx_http_concat_module (static)
nginx: ngx_http_footer_filter_module (static)
nginx: ngx_http_trim_filter_module (static)
nginx: ngx_http_upstream_session_sticky_module (static)
nginx: ngx_http_lua_module (static)
nginx: ngx_http_copy_filter_module (static)
nginx: ngx_http_range_body_filter_module (static)
nginx: ngx_http_not_modified_filter_module (static)
nginx: the configuration file /opt/tengine-2.3.3/conf/nginx.conf syntax is ok
nginx: configuration file /opt/tengine-2.3.3/conf/nginx.conf test is successful

cd /opt/nginx/conf
cp -ar ssl ssl.conf webip.conf geo.*.conf GeoIP.dat manageip.conf fcgi.conf htpasswd nginx.conf /opt/tengine-2.3.3/conf/
/opt/tengine-2.3.3/sbin/nginx -t -c /opt/tengine-2.3.3/conf/nginx.conf

chown www:website /opt/tengine-2.3.3/logs/
chown www:website /opt/nginx/conf/

删除旧的nginx软链接,给tengine增加软链接
rm /opt/nginx
ln -s /opt/tengine-2.3.3 /opt/nginx

关闭tengine
/opt/nginx/sbin/nginx -s quit
启动tengine
/opt/nginx/sbin/nginx
重启tengine
/opt/nginx/sbin/nginx -s reload

6、下载和配置 ngx_lua_waf

nginx下常见的开源 waf 有 mod_security、naxsi、ngx_lua_waf 这三个,ngx_lua_waf 性能高和易用性强,基本上零配置,而且常见的攻击类型都能防御,是比较省心的选择。

其git 地址为 https://github.com/loveshell/ngx_lua_waf
wget –no-check-certificate https://github.com/loveshell/ngx_lua_waf/archive/master.zip
unzip master.zip
mv ngx_lua_waf-master /opt/tengine-2.3.3/conf/waf
chgrp -R website waf
chmod -R 0775 waf

mkdir -p /opt/nginx/logs/hack
chown www:website /opt/nginx/logs/hack
chmod -R 775 /opt/nginx/logs/hack

在nginx.conf的http段添加
lua_package_path “/opt/nginx/conf/waf/?.lua”;
lua_shared_dict limit 10m;
init_by_lua_file /opt/nginx/conf/waf/init.lua;
access_by_lua_file /opt/nginx/conf/waf/waf.lua;
配置config.lua里的waf规则目录(一般在waf/conf/目录下)

RulePath = "/opt/nginx/conf/waf/wafconf/"

然后重启nginx即可
部署完毕可以尝试如下命令:

curl http://xxxx/test.php?id=../etc/passwd
日志文件名称格式如下:虚拟主机名_sec.log

Posted in Nginx.

Tagged with , , .


ngx_cache_puage更新缓存404错误

在清除缓存时部分成功部分失败,有时通过浏览器可以但用程序就失败.

location ~ /purge(/.*)
{
	#设置只允许指定的IP或IP段才可以清除URL缓存。
	allow            127.0.0.1;
	allow            192.168.0.0/16;
	include manageip.conf;
	deny            all;
	proxy_cache_purge    cache_www   $host$1$is_args$args;
	error_page 405 =200 /purge$1; #处理squidclient purge的时候出现的405错误
}    
if ( $request_method = "PURGE" ) {
	rewrite ^(.*)$ /purge$1 last;
}
模拟测试
curl -H "Host:blog.c1gstudio.com" -H "User-Agent: c1gtest"  -X PURGE http://blog.c1gstudio.com/static/image/common/qrcode.png
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>openresty</center>
</body>
</html>

去掉权限,并输出url,发现没有$1的输出
location ~ /purge(/.*)
{
#设置只允许指定的IP或IP段才可以清除URL缓存。
allow 127.0.0.1;
allow 192.168.0.0/16;
echo cache_bbs $host$1$is_args$args;
error_page 405 =200 /purge$1; #处理squidclient purge的时候出现的405错误
}

curl -H “Host:blog.c1gstudio.com” -H “User-Agent: c1gtest” -X PURGE http://blog.c1gstudio.com/static/image/common/qrcode.png
cache_bbs: blog.c1gstudio.com

可能是$1被其它脚本占用,重新定义一个 $purgeurl变量
location ~ /purge(?<purgeurl>/.*)
{
	#设置只允许指定的IP或IP段才可以清除URL缓存。
	allow        127.0.0.1;
	allow        192.168.0.0/16;
	echo    cache_bbs   $host$purgeurl$is_args$args;
	error_page 405 =200 /purge$1; #处理squidclient purge的时候出现的405错误
}    

测试可以输出
curl -H "Host:blog.c1gstudio.com" -H "User-Agent: c1gtest"  -X PURGE http://blog.c1gstudio.com/static/image/common/qrcode.png
cache_bbs: blog.c1gstudio.com/static/image/common/qrcode.png
最后修改并测试成功
location ~ /purge(?<purgeurl>/.*)
{
	#设置只允许指定的IP或IP段才可以清除URL缓存。
	allow        127.0.0.1;
	allow        192.168.0.0/16;
	include manageip.conf;
	deny            all;
	proxy_cache_purge    cache_bbs   $host$purgeurl$is_args$args;
	error_page 405 =200 /purge$purgeurl; #处理squidclient purge的时候出现的405错误
}    
if ( $request_method = "PURGE" ) {
	rewrite ^(.*)$ /purge$1 last;
}      

curl -H "Host:blog.c1gstudio.com" -H "User-Agent: c1gtest"  -X PURGE http://blog.c1gstudio.com/static/image/common/qrcode.png
<html>
<head><title>Successful purge</title></head>
<body bgcolor="white">
<center><h1>Successful purge</h1>
<br>Key : blog.c1gstudio.com/static/image/common/qrcode.png
<br>Path: /dev/shm/nginx/proxy_cache_bbs/1/92/9a7ee4d7167bc0ead33f4ccdb4439921
</center>
<hr><center>openresty/1.19.9.1</center>
</body>
</html>

Posted in Nginx.

Tagged with .


nginx用map获取X-Forwarded-For中的客户端ipv4/ipv6地址

网上搜搜连个像样的取ipv6代码也没有,这里写一个.如果有合法的http_x_forwarder_for就取第一或最后一个,没有则取直连IP.


$ForwardedFirstIp 容易伪造,但可以做流量控制用
$ForwardedLastIp 在前端代理可信情况下,可以做IP限制用

http
{

#获取左边第一个
map $http_x_forwarded_for $ForwardedFirstIp {
    default $remote_addr;
    ~^(?P<firstAddr>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+|[0-9a-fA-F]+:[0-9a-fA-F:]+:[0-9a-fA-F\.]+),?.*$ $firstAddr;
}



#获取右边第一个
map $http_x_forwarded_for $ForwardedLastIp {
    default $remote_addr;
    ~,?(?P<lastAddr>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+|[0-9a-fA-F]+:[0-9a-fA-F:]+:[0-9a-fA-F\.]+)$ $lastAddr;
}

}

支持ipv4;

支持ipv6缩写如 1080::8:800:200C:417A
支持正常ipv6如 2409:8907:a125:2e4d:c5d:9d59:c2d5:a13a
支技ipv4映射地址如 0:0:0:0:0:ffff:192.168.56.10
但不支持::简写回环等如 ::1 , ::192.168.56.10

2022/1/4更新
更严谨的正则语法
支持::1回环,支持 ::192.168.56.10
格式不正确返回空
没有forwared时取remote_addr

map $http_x_forwarded_for $ForwardedFirstIp {
    "" $remote_addr;
    "~(?<firstAddr>([0-9]{1,3}\.){3}[0-9]{1,3}|[0-9a-fA-F]{0,4}:[0-9a-fA-F:]{0,30}:[0-9a-fA-F\.]{1,15}),?.*$" $firstAddr;
}
map $http_x_forwarded_for $ForwardedLastIp {
    "" $remote_addr;
    "~,?\s?(?<lastAddr>([0-9]{1,3}\.){3}[0-9]{1,3}|[0-9a-fA-F]{0,4}:[0-9a-fA-F:]{0,30}:[0-9a-fA-F\.]{1,15})$" $lastAddr;
}

2022/1/13更新

支持[]包含的ipv6块



    map $http_x_forwarded_for $ForwardedFirstIp {
        default $remote_addr;
        "~\[?(?<firstAddr>([0-9]{1,3}\.){3}[0-9]{1,3}|[0-9a-fA-F]{0,4}:[0-9a-fA-F:]{0,30}:[0-9a-fA-F\.]{1,15})\]?,?.*$" $firstAddr;
    }
    map $http_x_forwarded_for $ForwardedLastIp {
        default $remote_addr;
        "~,?\s?\[?(?<lastAddr>([0-9]{1,3}\.){3}[0-9]{1,3}|[0-9a-fA-F]{0,4}:[0-9a-fA-F:]{0,30}:[0-9a-fA-F\.]{1,15})\]?$" $lastAddr;
    }

Posted in Nginx.


nginx resolver 拒绝服务漏洞CVE-2021-23017

之前有过一个 nginx resolver 拒绝服务漏洞(CVE-2016-0742),现在又出了一个.

如果没用resolver 参数,那没影响,可以升到最新nginx-1.21.0  来解决.

Changes with nginx 1.21.0                                        25 May 2021

    *) Security: 1-byte memory overwrite might occur during DNS server
       response processing if the "resolver" directive was used, allowing an
       attacker who is able to forge UDP packets from the DNS server to
       cause worker process crash or, potentially, arbitrary code execution
       (CVE-2021-23017).

概述

ngx_resolver_copy()在处理DNS响应时出现一个off-by-one错误,利用该漏洞网络攻击者可以在堆分配的缓冲区中写一个点字符(.’, 0x2E)导致超出范围。 所有配置解析器语法的(resolver xxxx)Nginx实例可以通过DNS响应(响应来自Nginx的DNS请求)来触发该漏洞。 特制数据包允许使用0x2E覆盖下一个堆块元数据的最低有效字节,利用该漏洞攻击者,可以实现Ddos拒绝服务,甚至可能实现远程代码执行。

由于Nginx中缺乏DNS欺骗缓解措施,并且在检查DNS事务ID之前调用了易受攻击的功能,因此远程攻击者可能能够通向中毒服务器注入受毒的DNS响应来利用此漏洞。

漏洞影响

严重等级: 高

漏洞向量: 远程/DNS

确认的受影响版本: 0.6.18-1.20.0

确认的修补版本: 1.21.0,1.20.1

供应商: F5,Inc.

状态: 公开

CVE: CVE-2021-23017

CWE: 193

CVSS得分: 8.1

CVSS向量:CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H/E:U/RL:O/RC:C

漏洞分析

当Nginx配置中设置resolver时,Nginx DNS解析器(core/ngx_resolver.c)用于通过DNS解析多个模块的主机名。

Nginx中通过ngx_resolver_copy()调用来验证和解压缩DNS响应中包含的每个DNS域名,接收网络数据包作为输入和指向正在处理的名称的指针,并在成功后返回指向包含未压缩名称的新分配缓冲区的指针。调用整体上分两步完成的,

1)计算未压缩的域名大小的长度len并验证输入包的合法性,丢弃包含大于128个指针或包含超出输入缓冲区边界的域名。

2)分配输出缓冲区,并将未压缩的域名复制到其中。

第1部分中的大小计算与第2部分中的未压缩的域名之间的不匹配,导致一个len的一个off-by-one错误,导致允许以一个字节为单位写一个点字符超出name->data的边界。

当压缩名称的最后一部分包含一个指向NUL字节的指针时,就会发生计算错误。 尽管计算步骤仅考虑标签之间的点,但每次处理标签并且接着的字符为非NUL时,解压缩步骤都会写入一个点字符。当标签后跟指向NUL字节的指针时,解压缩过程将:

// 1) copy the label to the output buffer,

ngx_strlow(dst, src, n);

dst += n;

src += n;

// 2) read next character,

n = *src++;

// 3) as its a pointer, its not NUL,

if (n != 0) {

// 4) so a dot character that was not accounted for is written out of bounds

*dst++ = ‘.’;

}

// 5) Afterwards, the pointer is followed,

if (n & 0xc0) {

n = ((n & 0x3f) << 8) + *src;

src = &buf[n];

n = *src++;

}

// 6) and a NULL byte is found, signaling the end of the function

if (n == 0) {

name->len = dst – name->data;

return NGX_OK;

}

如果计算的大小恰好与堆块大小对齐,则超出范围的点字符将覆盖下一个堆块长度的元数据中的最低有效字节。这可能会直接导致下一个堆块的大小写入,但还会覆盖3个标志,从而导致 PREV_INUSE被清除并 IS_MMAPPED被设置。

==7863== Invalid write of size 1

==7863== at 0x137C2E: ngx_resolver_copy (ngx_resolver.c:4018)

==7863== by 0x13D12B: ngx_resolver_process_a (ngx_resolver.c:2470)

==7863== by 0x13D12B: ngx_resolver_process_response (ngx_resolver.c:1844)

==7863== by 0x13D46A: ngx_resolver_udp_read (ngx_resolver.c:1574)

==7863== by 0x14AB19: ngx_epoll_process_events (ngx_epoll_module.c:901)

==7863== by 0x1414D4: ngx_process_events_and_timers (ngx_event.c:247)

==7863== by 0x148E57: ngx_worker_process_cycle (ngx_process_cycle.c:719)

==7863== by 0x1474DA: ngx_spawn_process (ngx_process.c:199)

==7863== by 0x1480A8: ngx_start_worker_processes (ngx_process_cycle.c:344)

==7863== by 0x14952D: ngx_master_process_cycle (ngx_process_cycle.c:130)

==7863== by 0x12237F: main (Nginx.c:383)

==7863== Address 0x4bbcfb8 is 0 bytes after a block of size 24 alloc’d

==7863== at 0x483E77F: malloc (vg_replace_malloc.c:307)

==7863== by 0x1448C4: ngx_alloc (ngx_alloc.c:22)

==7863== by 0x137AE4: ngx_resolver_alloc (ngx_resolver.c:4119)

==7863== by 0x137B26: ngx_resolver_copy (ngx_resolver.c:3994)

==7863== by 0x13D12B: ngx_resolver_process_a (ngx_resolver.c:2470)

==7863== by 0x13D12B: ngx_resolver_process_response (ngx_resolver.c:1844)

==7863== by 0x13D46A: ngx_resolver_udp_read (ngx_resolver.c:1574)

==7863== by 0x14AB19: ngx_epoll_process_events (ngx_epoll_module.c:901)

==7863== by 0x1414D4: ngx_process_events_and_timers (ngx_event.c:247)

==7863== by 0x148E57: ngx_worker_process_cycle (ngx_process_cycle.c:719)

==7863== by 0x1474DA: ngx_spawn_process (ngx_process.c:199)

==7863== by 0x1480A8: ngx_start_worker_processes (ngx_process_cycle.c:344)

==7863== by 0x14952D: ngx_master_process_cycle (ngx_process_cycle.c:130)

虽然目前还没有Poc出来,理论上该漏洞可以被用来进行远程代码执行。

攻击向量分析

DNS响应可以通过多种方式触发漏洞。

首先,Nginx必须发送了DNS请求,并且必须等待响应。 然后,可以在DNS响应的多个部分进行投毒:

DNS问题QNAME,

DNS回答名称,

DNS会回答RDATA以获得CNAME和SRV响应,

通过使用多个中毒的QNAME,NAME或RDATA值制作响应,可以在处理响应时多次击中易受攻击的函数,从而有效地执行多次脱机写入。

此外,当攻击者提供中毒的CNAME时,它将以递归方式解决,从而在执行过程中触发了额外的OOB写操作 ngx_resolve_name_locked() 调用ngx_strlow()(ngx_resolver.c:594)和其他OOB读取期间 ngx_resolver_dup()(ngx_resolver.c:790)和 ngx_crc32_short()(ngx_resolver.c:596)。

用于“example.net”请求的DNS响应示例负载,其中包含被污染的CNAME:

稍微不同的有效负载(poc.py中的有效负载)填充了足够的字节以覆盖 next_chunk.mchunk_size带点的最低有效字节:

24字节的标签导致分配了24字节的缓冲区,该缓冲区填充有24字节+一个超出范围的点字符。

漏洞修复和解决

通过向域名解析时,在域名末尾写入的伪造的点字符分配一个额外的字节可以缓解此问题。

受漏洞影响的配置

daemon off;

http{

access_log logs/access.log;

server{

listen 8080;

location / {

resolver 127.0.0.1:1053;

set $dns example.net;

proxy_pass $dns;

}

}

}

events {

worker_connections 1024;

}

https://baijiahao.baidu.com/s?id=1700787515121182676&wfr=spider&for=pc

Posted in 安全通告.


CVE-2021-3156:Sudo 堆缓冲区溢出漏洞通告

0x01漏洞简述

2021年01月27日,360CERT监测发现RedHat发布了sudo 缓冲区/栈溢出漏洞的风险通告,该漏洞编号为CVE-2021-3156,漏洞等级:高危,漏洞评分:7.0

攻击者在取得服务器基础权限的情况下,可以利用sudo基于堆的缓冲区溢出漏洞,获得root权限。

目前debain已经修复该漏洞,centos依然受到影响

对此,360CERT建议广大用户及时将sudo升级到最新版本。与此同时,请做好资产自查以及预防工作,以免遭受黑客攻击。

0x02风险等级

360CERT对该漏洞的评定结果如下

评定方式等级
威胁等级高危
影响面广泛
360CERT评分7.0

0x03漏洞详情

CVE-2021-3156: 缓冲区溢出漏洞

sudo解析命令行参数的方式中发现了基于堆的缓冲区溢出。任何本地用户(普通用户和系统用户,sudoer和非sudoers)都可以利用此漏洞,而无需进行身份验证,攻击者不需要知道用户的密码。成功利用此漏洞可以获得root权限。

用户可以使用如下方法进行自查:

以非root用户登录系统,并使用命令sudoedit -s /

– 如果响应一个以sudoedit:开头的报错,那么表明存在漏洞。

– 如果响应一个以usage:开头的报错,那么表明补丁已经生效。

0x04影响版本

– sudo:sudo: 1.8.2 – 1.8.31p2

– sudo:sudo: 1.9.0 – 1.9.5p1

0x05修复建议

通用修补建议

下载升级sudo软件包,下载链接为:

sudo软件包下载地址

https://www.sudo.ws/dist/

临时修补建议

对于无法立即更新的用户,建议使用systemtap进行以下临时缓解:

1. 安装所需的systemtap软件包和依赖项:

systemtap yum-utils kernel-devel-"$(uname -r)"

对于RHEL 7,使用命令安装 kernel debuginfo:debuginfo-install -y kernel-"$(uname -r)"。对于RHEL 8,使用命令安装 sudo debuginfo:debuginfo-install sudo

2. 创建以下systemtap脚本(将文件命名为sudoedit-block.stap):

probe process("/usr/bin/sudo").function("main") {
command = cmdline_args(0,0,"");
if (strpos(command, "edit") >= 0) {
raise(9);
}
}

3. 使用以下命令安装脚本:(使用root权限)

# nohup stap -g sudoedit-block.stap &

该脚本将使得易受攻击的sudoedit二进制文件停止工作。sudo命令仍将照常工作。上述更改在重启后失效,必须在每次重启后重新应用。

4. 一旦安装了补丁程序,就可以通过取消systemtap进程来删除systemtap脚本。例如,通过使用:

# kill -s SIGTERM 7590 (其中7590是systemtap进程的PID)

0x06时间线

2021-01-27  RedHat官方发布通告

2021-01-27  360CERT发布通告

0x07参考链接

1、 RedHat官方通告

https://access.redhat.com/security/cve/CVE-2021-3156

2、 CVE-2021-3156: Heap-Based Buffer Overflow in Sudo (Baron Samedit)

https://blog.qualys.com/vulnerabilities-research/2021/01/26/cve-2021-3156-heap-based-buffer-overflow-in-sudo-baron-samedit

来源:https://my.oschina.net/u/4600927/blog/4927558

rpm升级来修复

下载系统安装包
centos 5 https://github.com/sudo-project/sudo/releases/download/SUDO_1_9_5p2/sudo-1.9.5-3.el5.x86_64.rpm
centos 6 https://github.com/sudo-project/sudo/releases/download/SUDO_1_9_5p2/sudo-1.9.5-3.el6.x86_64.rpm
centos 7 https://github.com/sudo-project/sudo/releases/download/SUDO_1_9_5p2/sudo-1.9.5-3.el7.x86_64.rpm
ubuntu 16.04 https://github.com/sudo-project/sudo/releases/download/SUDO_1_9_5p2/sudo_1.9.5-3_ubu1604_amd64.deb
ubuntu 18.04 https://github.com/sudo-project/sudo/releases/download/SUDO_1_9_5p2/sudo-ldap_1.9.5-3_ubu1804_amd64.deb
ubuntu 20.04 https://github.com/sudo-project/sudo/releases/download/SUDO_1_9_5p2/sudo_1.9.5-3_ubu2004_amd64.deb
其他看官网 https://www.sudo.ws/download.html

cd /root/src/packages/
wget -N –no-check-certificate https://github.com/sudo-project/sudo/releases/download/SUDO_1_9_5p2/sudo-1.9.5-3.el6.x86_64.rpm && top
ll sudo-1.9.5-3.el6.x86_64.rpm
rpm -Uvh sudo-1.9.5-3.el6.x86_64.rpm
sudo -V
Sudo version 1.9.5p2

漏洞验证-修复完成
sudoedit -s ” perl -e ‘print “A” x 65536’
usage: sudoedit [-AknS] [-r role] [-t type] [-C num] [-D
directory] [-g group] [-h host] [-p prompt]
[-R directory] [-T timeout] [-u user] file ..

Posted in 安全通告.


Dnsmasq: 多个高危漏洞风险通告

报告编号:B6-2021-012102

报告来源:360CERT

报告作者:360CERT

更新日期:2021-01-21

0x01事件简述

2021年01月21日,360CERT监测发现JSOF发布了DNSpooq的风险通告,事件等级:高危,事件评分:8.1

DNSpooqJSOF命名的本次披露的漏洞的统称,该报告主要围绕dnsmasq的漏洞展开。总计包含2处高危漏洞,2处中危漏洞,3处低危漏洞。

dnsmasq中存在多个高危漏洞,影响DNS服务正常的提供,并导致DNS缓存投毒引发以下后果

1. 域名劫持(网站访问劫持、数据窃取)

2. 流量劫持(网站内容劫持、数据窃取、分布式拒绝服务)

对此,360CERT建议广大用户好资产自查以及预防工作,以免遭受黑客攻击。

0x02风险等级

360CERT对该事件的评定结果如下

评定方式等级
威胁等级高危
影响面广泛
360CERT评分8.1

0x03漏洞详情

漏洞编号漏洞评分漏洞类型漏洞后果
CVE-2020-256818.1启用DNSSEC时,堆的缓冲区溢出远程代码执行
CVE-2020-256828.1启用DNSSEC时,缓冲区溢出远程代码执行
CVE-2020-256835.9启用DNSSEC时,堆缓冲区溢出拒绝服务
CVE-2020-256875.9启用DNSSEC时,堆缓存区溢出拒绝服务
CVE-2020-256844逻辑错误拒绝服务
CVE-2020-256854逻辑错误DNS 缓存投毒
CVE-2020-256864逻辑错误DNS 缓存投毒

0x04影响版本

dnsmasq:dnsmsaq: <2.83

0x05修复建议

通用修补建议

发行版

升级dnsmasq2.83以上 请根据发行版包管理器及时安装并重启dnsmasq,请根据具体情况选择命令。

# 更新软件包
yum update dnsmasq
apt upgrade dnsmasq
# 重启服务
systemctl restart dnsmasq

临时修补建议

网络侧

-禁止从外部网络访问dsnmasq

-设置--dns-forward-max=参数为小于 150 的值

-可以在理解DNSSEC功能的情况下,临时禁用该功能

-可以通过启用一些DNS安全传输的策略(DNS Over TLS, DoH, DoT)

参考命令

命令仅提供参考,具体需要结合服务器的实际情况进行配置

# iptables
sudo iptables -A INPUT -p udp --dport 53 -j DROP 
sudo iptables -A FORWARD -p udp --dport 53 -j DROP 
# firewall-cmd
sudo firewall-cmd --remove-port=53/udp --permanent

0x06相关空间测绘数据

360安全大脑-Quake网络空间测绘系统通过对全网资产测绘,发现dnsmasq具体分布如下图所示。

0x07产品侧解决方案

360城市级网络安全监测服务

360CERT的安全分析人员利用360安全大脑的QUAKE资产测绘平台(quake.360.cn),通过资产测绘技术的方式,对该漏洞进行监测。可联系相关产品区域负责人或(quake#360.cn)获取对应产品。

360安全分析响应平台

360安全大脑的安全分析响应平台通过网络流量检测、多传感器数据融合关联分析手段,对该类漏洞的利用进行实时检测和阻断,请用户联系相关产品区域负责人或(shaoyulong#360.cn)获取对应产品。

0x08时间线

2021-01-21 360CERT发布通告

2021-01-21 JSOF 披露 DNSpooq 报告

0x09参考链接

1、 DNSpooq-Technical-WP.pdf

2、 DNSpooq

0x0a特制报告下载链接

一直以来,360CERT对全球重要网络安全事件进行快速通报、应急响应。为更好地为政企用户提供最新漏洞以及信息安全事件的安全通告服务,现360CERT正式推出安全通告特制版报告,以便用户做资料留存、传阅研究与查询验证。 用户可直接通过以下链接进行特制报告的下载。Dnsmasq: 多个高危漏洞风险通告

若有订阅意向与定制需求请发送邮件至 g-cert-report#360.cn ,并附上您的 公司名、姓名、手机号、地区、邮箱地址。

Posted in 安全通告.