Claudio Borges

Technical blog about Linux, BSD, Mac OS X, Games and etc.

Archive for the ‘Debian’ tag

Using NginX to block a specific HTTP user agent

without comments

Hi Folks, this is my first article in English. My next posts will be in English, I hope everybody is comfortable with that.

I have been working with NginX since version 0.9.7. And this is the first of a plenty of articles about it.

NginX is a powerful web server with a lot of features. It can do amazing things, for example, you can use it for HTTP load balancing or as a forward proxy server and its configuration is pretty easy. As opposed to Apache which has dynamic modules that you can load at your will, NginX is a static binary with built-in modules enabled in compile time.

In this article, I’ll explain how to configure a custom error page and how to block a specific user agent. We’ll use the 480 status code in our error page. The 4xx class of status code is intended for cases in which there seems to be a client error. In fact, they’re making a big mistake by using an outdated browser. We want to offer the best services to our customers, even if we need to force them to update their browser.

Before the main location statement, we need to define the user agent that we want to block and the specific error code:

if ($http_user_agent ~* "MSIE 6.0;") {
    return 480;
}

The if statement above will block just Internet Explorer 6. NginX doesn’t support complex conditions or nested if statements. If you want or need to do that, you need to use regular expressions to have multiple matches or a hack (that I will cover in another post)

The code below will block Internet Explorer version between 6.x and 8.x:

if ($http_user_agent ~* "MSIE ([6-8]{1,}\.\d{0,}\w?\d?);") {
    return 480;
}

PS: You can block any HTTP user agents with GET / POST requests.

If you want to use my error page, click here or you can create a 480.html file in your document root, for example /srv/default/www/. This page will be used when ie6 users try to access our website.

The content is:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Please upgrade your browser</title>
<style type="text/css">
body{text-align:left; font-size:13px; font-family:Tahoma, sans-serif;background:#EEEEEE;}
</style>
</head>
<body>
    <h1>It's time to upgrade your browser</h1>
    <p>You’re using an outdated version of Internet Explorer. Many websites no longer support Internet Explorer 6 and 7. You won't be able to view this website until you upgrade your browser.</p>
    <h2>Internet Explorer 9</h2>
    <span><a href="http://go.microsoft.com/fwlink/?LinkId=398860">Download now</a></span>
    <h3>Not sure?</h3>
    <p>There are many reasons you should upgrade to a newer version of Internet Explorer. Here are just a few:</p>
    <div>
        <ul>
            <li><p>Internet Explorer 9 gives you a faster, safer browsing experience with better privacy protection.</p></li>
            <li><p>It's free and you can download it with just one click if you're using Windows Vista SP2 or higher.</p></li>
        </ul>
    </div>
    <h3>Still have questions?</h3>
    <div>
        <ul>
            <li><p>Visit the <a href="http://go.microsoft.com/fwlink/?LinkId=399116">Internet Explorer Support page</a></p></li>
            <li><p>Visit the <a href="http://support.microsoft.com">Microsoft Support page</a></p></li>
        </ul>
    </div>
</body>
</html>

If you want to see the page preview, click here

The next step is to configure the virtual host to use our error page. So, edit your virtual host file and add the lines:

error_page 480 @480;
location @480 {
    internal;
    try_files /480.html =403;
}

PS: You can put your error pages in another directory. You just need to set a root directive with another directory, ex:

error_page 480 @480;
location @480 {
    internal;
    root /srv/error/www;
    try_files /480.html =403;
}

Now, let’s suppose you want to block offline browsers like wget or libwww-perl. The process is the same, but this time, we will return the 403 error code (Forbidden).

if ($http_user_agent ~* "(wget|libwww-perl)") {
    return 403;
}

My virtual host code is:

server {
    listen 80;
    server_name godaime.claudioborges.org;
    index index.php index.html;
    
    root /srv/default/www;
    
    charset utf-8;
    
    include /etc/nginx/default.d/*.conf;
    
    error_page 480 @480;
    location @480 {
        internal;
        try_files /480.html =403;
    }   

    if ($http_user_agent ~* "MSIE ([5-8]{1,}\.\d{0,}\w?\d?);") {
        return 480;
    }

    if ($http_user_agent ~* "(wget|libwww-perl)") {
        return 403;
    }

    location / {
        try_files $uri $uri/ =404;
    }
    
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_intercept_errors on;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location = /favicon.ico {
        access_log off;
        log_not_found off;
    }   

    access_log /var/log/nginx/access main;
    error_log /var/log/nginx/error.log;
}     

Now you know how to block HTTP user agents. That is all for now folks.

Written by but3k4

July 18th, 2015 at 9:45 pm

Autenticação 802.1x em redes ethernet

without comments

Alguns amigos tiveram dificuldades para autenticar no servidor Radius, isto porque o servidor dhcp somente liberava ip via autenticação, por este motivo resolvi criar este post.

Basicamente você vai utilizar wireless over ethernet, pois o responsável pela autenticação no Radius será o wpa_supplicant. Os procedimentos abaixo são baseados em Debian, caso você utilize outro SO, adapte este documento conforme sua necessidade.

Comece instalando o wpa_supplicant:

apt-get clean
apt-get update
apt-get install -y wpasupplicant

Com o wpa_supplicant instalando, vamos a configuração. Crie o arquivo /etc/wpa_supplicant/wired.conf com o seguinte conteudo:

# /etc/wpa_supplicant/wired.conf
#
ctrl_interface=/var/run/wpa_supplicant
network={
	key_mgmt=WPA-EAP
	eap=PEAP
	pairwise=CCMP TKIP
	group=CCMP TKIP
	identity="claudio@claudioborges.org"
	password="lalalalaxxxxx"
	phase1="peaplabel=0"
	phase2="auth=MSCHAPV2"
}

Obs: Não esqueça de substituir os valores de identify e password por seu usuário e senha.

Para testar se a autenticação está funcionando, inicie o wpa_supplicant em modo debug:

wpa_supplicant -Dwired -ieth0 -d -c/etc/wpa_supplicant/wired.conf

Se tudo correr bem, você será autenticado, caso ocorra algum problema como senha expirada ou algo do gênero, o debug irá lhe mostrar.

Estando tudo certo no passo anterior, vamos deixar a configuração de modo que o serviço seja iniciado de forma automática. Edite o seu /etc/network/interfaces e ajuste os valores a serem utilizados na sua interface:

auto eth0
iface eth0 inet dhcp
   wpa-driver wired
   wpa-conf /etc/wpa_supplicant/wired.conf

E para finalizar, reinicie as interfaces de rede:

/etc/init.d/networking restart

Seguindo os passos acima, você terá sua autenticação over ethernet.

Written by but3k4

June 28th, 2010 at 4:53 pm

Posted in Links

Tagged with , , ,

Configurando um servidor de openvpn parte 2

with 2 comments

Dando continuidade a parte 1 do artigo, vamos configurar o lado do cliente.

Chaves e certificados para a filial

server:~/easy-rsa# ./build-key filial1
Generating a 2048 bit RSA private key
......................+++
..........+++
writing new private key to 'filial1.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [BR]:
State or Province Name (full name) [SP]:
Locality Name (eg, city) [Sao Paulo]:"Sao Paulo"
Organization Name (eg, company) [Personal OpenVPN Client]:
Organizational Unit Name (eg, section) []: POC
Common Name (eg, your name or your server's hostname) []:filial1
Email Address [but3k4@gmail.com]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /root/easy-rsa/openssl.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           : PRINTABLE:'BR'
stateOrProvinceName   : PRINTABLE:'SP'
localityName          : T61STRING:'"Sao Paulo"'
organizationName      : PRINTABLE:'Personal OpenVPN Client'
organizationalUnitName: PRINTABLE:'POC'
commonName            : PRINTABLE:'filial1'
emailAddress          : IA5STRING:'but3k4@gmail.com'
Certificate is to be certified until Aug  9 14:59:05 2018 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
server:~/easy-rsa# 

Com os certificados criados, vamos copiá-los para o /etc/openvpn:

server:~/easy-rsa# mkdir /etc/openvpn/{certs,ccd,keys}
server:~/easy-rsa# cp keys/*.crt /etc/openvpn/certs/
server:~/easy-rsa# cp keys/*.key keys/dh2048.pem /etc/openvpn/keys/

Criando o arquivo de rotas

O arquivo /etc/openvpn/ccd/filial1 é responsável por definir rotas individuais para os clientes, ou seja, sem ele, o servidor nao vai saber que as maquinas de ambos os lados querem se comunicar e com isso a comunicação fica restrita apenas aos servidores.

server:~/easy-rsa# echo "iroute 192.168.1.0 255.255.255.0" > /etc/openvpn/ccd/filial1

Ajustando as permissões de arquivos / diretórios

server:~/easy-rsa# cd /etc/openvpn/
server:/etc/openvpn# chown -R nobody:nogroup keys certs ccd
server:/etc/openvpn# chmod 0400 keys/* certs/* ccd/*

Criando o diretorio de log

Precisamos criar o diretório de log, pois nossa configuração salva estas informações em arquivos específicos

server:/etc/openvpn# mkdir /var/log/openvpn

Startando o openvpn do lado matriz

server:/etc/openvpn# /etc/init.d/openvpn start
Starting virtual private network daemon: openvpn(OK).
server:/etc/openvpn#

Com o lado do servidor ok, vamos criar os arquivos para a filial:

server:/etc/openvpn# mkdir -p filial1/{certs,keys}
server:/etc/openvpn# cp certs/{ca.crt,filial1.crt} filial1/certs/
server:/etc/openvpn# cp keys/{filial1.key,shared.key} filial1/keys/

Criando o arquivo /etc/openvpn/filial1/openvpn.conf:

# /etc/openvpn/openvpn.conf filial configuration file

# diretorio onde esta os arquivos de configuracao / certificados
cd /etc/openvpn

# Especifica que este certificado eh de um cliente
client

# Define o ip do servidor para o cliente conectar
remote	189.47.25.20

# porta usada para os clientes conectarem no servidor
port	1194

# protocolo usado na conexao
proto	udp

# device usado pelo openvpn
dev	tun

# Diz que o certificado foi assinado pelo servidor
ns-cert-type	server

# Habilita conexoes tls
# Ajuda a bloquear ataques DoS e flooding na porta usada pelo openvpn
tls-client

# arquivo de chave compartilhada usado pelo tls-server
# O mesmo adiciona uma camada a mais de seguranca, habilitando controle de conexoes tls
tls-auth	keys/shared.key 1

# Certificado de autoridade
# Tem que ser o mesmo em todos os hosts
# que conectarem a sua vpn
ca	certs/ca.crt

# Certificado e chave privada do servidor
# Cada maquina tem que ter seu certificado e chave
cert	certs/filial1.crt
key	keys/filial1.key

# Habilita ping de 10 em 10 segundos para dizer ao lado da filial que a matriz
# esta no ar, usado para manter a conexao ativa
ping-timer-rem
keepalive 10 120

# Tipo de criptografia usada
cipher	DES-EDE3-CBC

# habilita compressão no link VPN
comp-lzo

# Ativa a opcao de se conectar, caso o cliente nao esteja na internet, ou
# o mesmo tenha perdido a conexao.
resolv-retry	infinite

# Nao especifica uma porta local para o cliente ouvir.
nobind

# usuário e grupo sob o qual o openvpn ira rodar
user	nobody
group	nogroup

# Permite um restart sem fechar a conexão e re-ler as chaves
persist-key
persist-tun

# Log de status das conexoes
status	/var/log/openvpn/openvpn-status.log

# define um arquivo de log, pois o default é o /var/log/syslog
log	/var/log/openvpn/openvpn.log
log-append	/var/log/openvpn/openvpn.log

# Nivel de log
# 0 silencioso, exceto para erros fatais
# 4 razoavel para uso geral
# 5 e 6 podem ajudar a debugar problemas de conexoes
# 9 maximo debug, muito util para tentar descobrir erros caso a vpn nao suba
verb	3

# desabilita mensagens repetitivas, ou seja, erros ou conexoes em sequencia
# acima de 20, ele dropa.
mute	20

Compactando os arquivos para a filial:

server:/etc/openvpn# tar -czpf filial1.tar.gz filial1

Envie o arquivo filial1.tar.gz para o /tmp/ da filial.

Agora do lado da filial, é necessário instalar o openvpn e descompactar os arquivos:

filial1:~# apt-get install -y openvpn

Com o openvpn instalado, edite o arquivo /etc/default/openvpn e descomente a linha #AUTOSTART=”all”. Agora descompacte o arquivo filial1.tar.gz que está no /tmp/:

filial1:~# cd /tmp/
filial1:~# tar xzf filial1.tar.gz
filial1:~# mv filial1/* /etc/openvpn/
filial1:~# rm -rf /tmp/filial1*

Criando o diretorio /var/log/openvpn:

filial1:/etc/openvpn# mkdir /var/log/openvpn

Startando o openvpn do lado filial:

filial1:/etc/openvpn# /etc/init.d/openvpn start
Starting virtual private network daemon: openvpn(OK).
filial1:/etc/openvpn#

Pronto, seu openvpn esta instalado e matriz/filial estao se comunicando. Não esqueça de liberar no fw da matriz a porta 1194 udp de sua interface externa e tudo na interface da vpn que é tun0.

Caso necessite configurar um notebook para acessar o servidor, basta seguir os passos da criação das configurações para a filial, alterando é claro o nome de filial para notebook ou qualquer outro nome.

Abraços.

Written by but3k4

January 29th, 2010 at 10:45 pm

Posted in Linux

Tagged with ,