Cyberbe Notes from Blackcat

Nginx and Perl-FastCGI on Ubuntu

Feb 072016

Install:

apt-get update
apt-get upgrade
apt-get install spawn-fcgi fcgiwrap
Nginx config:

#Все скрипты заканчивающиеся на pl и cgi
location ~ \.(pl|cgi)$
{
#Не сжимаем скрипты
gzip off;
try_files $uri =404;
#Передаем скрипты на обработку fcgiwrap
fastcgi_pass unix:/var/run/fcgiwrap.socket;
# Используем стандартные параметры
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_ignore_client_abort off;
}
#Замена апачевской ScriptAlias
location /cgi-bin/ {
gzip off;
try_files $uri =404;
root /var/www/;
fastcgi_pass unix:/var/run/fcgiwrap.socket;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_ignore_client_abort off;
}

Using GeoIP With Nginx On Ubuntu

Feb 072016

1. Download The GeoIP Databases

mkdir /etc/nginx/geoip
cd /etc/nginx/geoip
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz

2. Configure Nginx

http {
geoip_country /etc/nginx/geoip/GeoIP.dat; # the country IP database
geoip_city /etc/nginx/geoip/GeoLiteCity.dat; # the city IP database
[...]
/etc/nginx/fastcgi_params
### SET GEOIP Variables ###
fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;
fastcgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;
fastcgi_param GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3;
fastcgi_param GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name;
fastcgi_param GEOIP_REGION $geoip_region;
fastcgi_param GEOIP_CITY $geoip_city;
fastcgi_param GEOIP_POSTAL_CODE $geoip_postal_code;
fastcgi_param GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code;
fastcgi_param GEOIP_LATITUDE $geoip_latitude;
fastcgi_param GEOIP_LONGITUDE $geoip_longitude;

3. A Short Test

<html>
<body>
<?php
$geoip_country_code = getenv(GEOIP_COUNTRY_CODE);
/*
$geoip_country_code = $_SERVER['GEOIP_COUNTRY_CODE']; // works as well
*/
$geoip_country_code3 = getenv(GEOIP_COUNTRY_CODE3);
$geoip_country_name = getenv(GEOIP_COUNTRY_NAME);
$geoip_city_country_code = getenv(GEOIP_CITY_COUNTRY_CODE);
$geoip_city_country_code3 = getenv(GEOIP_CITY_COUNTRY_CODE3);
$geoip_city_country_name = getenv(GEOIP_CITY_COUNTRY_NAME);
$geoip_region = getenv(GEOIP_REGION);
$geoip_city = getenv(GEOIP_CITY);
$geoip_postal_code = getenv(GEOIP_POSTAL_CODE);
$geoip_city_continent_code = getenv(GEOIP_CITY_CONTINENT_CODE);
$geoip_latitude = getenv(GEOIP_LATITUDE);
$geoip_longitude = getenv(GEOIP_LONGITUDE);
echo 'country_code: '.$geoip_country_code.'<br>';
echo 'country_code3: '.$geoip_country_code3.'<br>';
echo 'country_name: '.$geoip_country_name.'<br>';
echo 'city_country_code: '.$geoip_city_country_code.'<br>';
echo 'city_country_code3: '.$geoip_city_country_code3.'<br>';
echo 'city_country_name: '.$geoip_city_country_name.'<br>';
echo 'region: '.$geoip_region.'<br>';
echo 'city: '.$geoip_city.'<br>';
echo 'postal_code: '.$geoip_postal_code.'<br>';
echo 'city_continent_code: '.$geoip_city_continent_code.'<br>';
echo 'latitude: '.$geoip_latitude.'<br>';
echo 'longitude: '.$geoip_longitude.'<br>';
?>
</body>
</html>

Увеличение максимального размера загружаемых файлов в PHP и Nginx (upload max filesize)

Feb 072016

Итак для увеличения максимального размера загружаемого файла сначала необходимо увеличить значение переменных PHP upload_max_filesize и post_max_size в файле /etc/php5/fpm/php.ini, например:

; Максимально разрешенный размер для загружаемых файлов.
; http://php.net/upload-max-filesize
upload_max_filesize = 30M

; Максимальный размер POST запросов, которые PHP будет обрабатывать.
; http://php.net/post-max-size
post_max_size = 30M

далее в конфигурационном файле nginx /etc/nginx/nginx.conf увеличить значение переменной client_max_body_size, например:
http {
#...
client_max_body_size 30m;
#...
}

Nginx сборка из исходников

Feb 072016

Скачиваем исходники http://nginx.org/ru/download.html

mkdir nginx_build
cd nginx_build
wget http://nginx.org/download/nginx-1.6.3.tar.gz
tar -xvf nginx-1.6.3.tar.gz
Устанавливаем зависимости:

aptitude install build-essential -y
aptitude install libgd-dev -y
aptitude install libpcre++-dev -y
aptitude install libssl-dev -y
aptitude install libgeoip-dev -y
apt-get install libpam0g-dev -y
aptitude install libxml2-dev -y
aptitude install libxslt1-dev -y
apt-get install libperl-dev -y
aptitude install libpcre++-dev -y

Сборка:

./configure --prefix=/etc/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-debug --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_xslt_module --with-ipv6 --with-sha1=/usr/include/openssl --with-md5=/usr/include/openssl --with-http_spdy_module --with-http_image_filter_module

make && make install

Параметры конфигурации:

nginx.conf

geoip_country /etc/nginx/geoip/GeoIP.dat; # the country IP database
geoip_city /etc/nginx/geoip/GeoIPCity.dat; # the city IP database

Aутентификация пользователя через сертификаты

Feb 072016

#!/bin/bash

CONFIG="ca.config"
CRT="ca.crt"

function cert {
openssl req -new -newkey rsa:1024 -nodes -keyout $NAME.key -subj /C=RU/ST=Msk/L=Msk/O=Inc/OU=XXX/CN=YYY/emailAddress=$EMAIL -out $NAME.csr
openssl ca -config $CONFIG -in $NAME.csr -out $NAME.crt -batch
openssl x509 -noout -text -in $NAME.crt
openssl pkcs12 -export -in $NAME.crt -inkey $NAME.key -certfile $CRT -out $NAME.p12 -passout pass:"$NAME"
}

function em {
echo pass: "$NAME"
echo pass: "$NAME" > emailtext
mutt $EMAIL -c admin@email -a $NAME.p12 -s "New Certificate" -x < emailtext
}

NAME="USERNAME"
EMAIL="mail@to.user"
cert
em
sleep 1

Соответственно как можно видеть у меня в скрипте в качестве пароля к сертификату использовалось имя пользователя, можно заменить на вводимый пароль. Плюс у меня в строке с отсылкой сертификата есть -c для отсылки его еще админу, он еще дублем шел ко мне, что бы если что было удобно его юзеру еще разок выслать.

cat ca.config
[ ca ]
default_ca = CA_CLIENT # При подписи сертификатов
# использовать секцию CA_CLIENT

[ CA_CLIENT ]
dir = ./db # Каталог для служебных файлов
certs = $dir/certs # Каталог для сертификатов
new_certs_dir = $dir/newcerts # Каталог для новых сертификатов

database = $dir/index.txt # Файл с базой данных
# подписанных сертификатов
serial = $dir/serial # Файл содержащий серийный номер
# сертификата
# (в шестнадцатиричном формате)
certificate = ./ca.crt # Файл сертификата CA
private_key = ./ca.key # Файл закрытого ключа CA

default_days = 365 # Срок действия подписываемого
# сертификата
default_crl_days = 7 # Срок действия CRL (см. $4)
default_md = md5 # Алгоритм подписи

policy = policy_anything # Название секции с описанием
# политики в отношении данных
# сертификата

[ policy_anything ]
countryName = optional # Код страны - не обязателен
stateOrProvinceName = optional # ......
localityName = optional # ......
organizationName = optional # ......
organizationalUnitName = optional # ......
commonName = supplied # ...... - обязателен
emailAddress = optional # ......

Setting up Munin to work with MongoDB

Feb 072016

Installing Munin MongoDB plugins


# as a root or using sudo
git clone git://github.com/erh/mongo-munin.git ~/mongo-munin
cd ~/mongo-munin

# We copy all the plugins into munin plugins
cp mongo_* /usr/share/munin/plugins/

# We need to activate them now
ln -s /usr/share/munin/plugins/mongo_btree /etc/munin/plugins/
ln -s /usr/share/munin/plugins/mongo_conn /etc/munin/plugins/
ln -s /usr/share/munin/plugins/mongo_lock /etc/munin/plugins/
ln -s /usr/share/munin/plugins/mongo_mem /etc/munin/plugins/
ln -s /usr/share/munin/plugins/mongo_ops /etc/munin/plugins/

cd ~
# We don't need this anymore
rm -rf mongo-munin

# Restarting munin-node...
/etc/init.d/munin-node restart