quarta-feira, 25 de março de 2009

Meu PostgreSQL não conecta!


Começando do início...


Observação: Apesar de os testes terem sido feitos em ambiente Linux, os comandos (ping, telnet, psql) e arquivos de configuração (postgresql.conf, pg_hba.conf) existem e funcionam também no Windows, Macintosh ou FreeBSD, no respectivo terminal.

Antes de tudo, façamos alguns testes que respondem à algumas perguntas.

A máquina está no ar e é enxergada na rede pelo cliente?


Um simples "ping" pode nos ajudar:
$ ping 10.15.23.15
Se estiver tudo correto, aparecerá o texto abaixo:
rodrigo@asgard:~$ ping 10.15.23.15
PING 10.15.23.15 (10.15.23.15) 56(84) bytes of data.
64 bytes from 10.15.23.15: icmp_seq=1 ttl=64 time=0.044 ms
64 bytes from 10.15.23.15: icmp_seq=2 ttl=64 time=0.034 ms
64 bytes from 10.15.23.15: icmp_seq=3 ttl=64 time=0.034 ms

--- 10.15.23.15 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1999ms
rtt min/avg/max/mdev = 0.034/0.037/0.044/0.006 ms
Caso contrário, será exibido algo como:
rodrigo@asgard:~$ ping 10.15.23.150
PING 10.15.23.150 (10.15.23.150) 56(84) bytes of data.
From 10.15.23.15 icmp_seq=1 Destination Host Unreachable
From 10.15.23.15 icmp_seq=2 Destination Host Unreachable
From 10.15.23.15 icmp_seq=3 Destination Host Unreachable

--- 10.15.23.150 ping statistics ---
6 packets transmitted, 0 received, +3 errors,
100% packet loss, time 5008ms, pipe 3
Se este for o caso, resolva este problema de conexão e configuração de rede antes de continuar.

O servidor está respondendo ao serviço na porta do PostgreSQL?


Se não estiver, qualquer acesso externo ao PostgreSQL é barrado, e a seguinte mensagem será exibida:
psql: could not connect to server: Conexão recusada
Is the server running on host "10.15.23.15" and accepting
TCP/IP connections on port 5432?
Para comprovar isso, podemos fazer um simples teste com o "telnet":
$ telnet 10.15.23.15 5432
rodrigo@asgard:~$ telnet 10.15.23.15 5432
Trying 10.15.23.15...
telnet: Unable to connect to remote host: Connection refused
Este é um problema que ocorre com 5 de cada 4 iniciantes neste banco de dados: a conexão não-local!
Bom, o fato é que a configuração padrão do PostgreSQL faz com que apenas conexões locais (via soquete UNIX) sejam permitidas. O primeiro passo é alterar uma opção no arquivo de configurações postgresql.conf:















VersãoOriginalMudar para
7.X e anteriorestcpip_socket = falsetcpip_socket = true
8.X em diantelisten_addresses = 'localhost'listen_addresses = '*'

Após salvar o arquivo, será preciso reiniciar o SGBD (não basta apenas fazer um "reload").

Agora refaça o teste do "telnet". Terá que aceitar a conexão e aparecer este texto:
rodrigo@asgard:~$ telnet 10.15.23.15 5432
Trying 10.15.23.15...
Connected to 10.15.23.15.
Escape character is '^]'.
Dê um CTRL+C para sair. Se ainda não funcionar, será preciso verificar se firewalls não estão impedindo a conexão entre o cliente e o servidor, na porta do PostgreSQL (padrão: 5432). Resolva essa questão antes de continuar a leitura...

Opa! Metade do serviço está concluída! Agora, outro problema que atormenta quem está começando, este erro ao tentar se conectar:
$ psql -h 10.15.23.15 correios rodrigo
psql: FATAL:  nenhuma entrada no pg_hba.conf para máquina "10.15.22.32",
usuário "rodrigo", banco de dados "correios", SSL desabilitado
Sigamos a dica que o PostgreSQL nos dá! Abra o seguinte arquivo de configuração: pg_hba.conf.

Este arquivo controla: quais hosts têm permissão de conexão, como os clientes se autenticam, quais usuários do PostgreSQL podem ser usados e que bancos de dados eles podem acessar. Os registros podem ter uma das seguintes formas:

local      DATABASE  USER  METHOD  [OPTION]
host DATABASE USER CIDR-ADDRESS METHOD [OPTION]
hostssl DATABASE USER CIDR-ADDRESS METHOD [OPTION]
hostnossl DATABASE USER CIDR-ADDRESS METHOD [OPTION]
Sendo assim, nestas entradas de permissões de acesso ao PostgreSQL, podemos alterar:
  • tipo de conexão ("local", "host")
  • banco de dados ("all": todos)
  • usuário ("all": todos)
  • endereço IP e máscara (estilo CIDR)
  • método ("reject", "trust", "password", "md5", "ident same user")

Importante: o arquivo é lido de cima para baixo, e a primeira entrada que esteja de acordo com a requisição é considerada. Isso é um fato que às vezes confunde os administradores. Os campos podem ser separados por espaços ou tabulações - tanto faz, funcionará de ambas as formas.

Bom, para resolver o problema em questão, precisamos incluir a seguinte linha:

host    correios    rodrigo        10.15.22.32/32        md5
Desta vez, não será preciso reiniciar o PostgreSQL. No Linux, podemos enviar um sinal do tipo HUP das seguintes maneiras:
$ /etc/init.d/postgresql-8.1 reload
$ killall -HUP postmaster
No Windows eu vou ficar devendo, mas deve ser algo como "recarregar o serviço".

Pronto! Simples, não?

Se você quiser, pode fazer com que o PostgreSQL funcione de modo promíscuo, adicionando a seguinte linha:

host    all    all        0.0.0.0/0        trust
Isso faz com que qualquer usuário, de qualquer IP acesse qualquer banco de dados, e sem necessidade de senha!

Se, ao invés de "trust" for usado "reject", todo acesso será fechado.

Lembre-se que, pelo padrão CIDR de endereçamento, diversos IPs podem ser
configurados com uma só linha! Por exemplo, ambas as linhas abaixo fazem
com que toda a subrede do IP 10.15.22.32/22 tenha acesso, por senha, ao
banco "correios":

host    correios    all        10.15.20.0/22        password
host correios all 10.15.22.32 255.255.252.0 password

Uma coisa interessante é restringir o acesso ao usuário "postgres", Senhor de Todo o Cluster, com a inclusão da seguinte linha:

local   all         postgres                          ident sameuser
Com isso, somente acesso local (via "ssh" e instrução "su - postgres") poderá ser feita com este super usuário, que tem permissão para fazer o que quiser em qualquer banco de dados.

sábado, 7 de março de 2009

Setting up Hamachi on Debian GNU/Linux


"LogMeIn Hamachi [1] is a VPN service that easily sets up in 10 minutes, and enables secure remote access to your business network, anywhere there's an Internet connection."

Hamachi is indeed a great tool for easily setting up VPNs! It creates a virtual network interface and all its configurations are made up with almost no need of user intervention.

For Windows users, a "Next-Next-Finish"-like setup executable is provided. Unix/Linux users, however, have no such facilities and should burn some neurons before putting it to work.

In this article I'll show some tips on how to build up the whole scenario on Debian GNU/Linux operating system, including installing Hamachi binaries, setting up required libraries, and deploying automatic initialization scripts.

First of all, you should download Hamachi binaries for Linux [2]. In the given URL, retrieve the most suitable binary for your processor (i.e. choose between an Intel Pentium or "others"). At the time of writing this very document, the current Hamachi release was 0.9.9.9-20.

For instance, I downloaded hamachi-0.9.9.9-20-lnx.tar.gz as my CPU was an AMD Sempron. I'll use this file name as the example from now on. Save the file on a proper Linux directory, say /usr/src.

Then, get into that destiny directory and extract all the zipped file contents using the following commands:

$ cd /usr/src
$ tar xvzf hamachi-0.9.9.9-20-lnx.tar.gz

Convention: Please observe that in the given notation the prefix "$" means a normal user prompt is needed, whereas a "#" prefix needs a root or superuser terminal to input the commands. Also, texts colored in red are user inputs. Its corresponding outputs are styled in blue.

You should note there is now a sub-directory called hamachi-0.9.9.9-20-lnx. Get into it and then switch to a super user account (i.e. "root" or any supercow-powered user).

$ cd hamachi-0.9.9.9-20-lnx
$ su

Although Hamachi can be set per user, in this case I'll set it up for the entire system, I mean, any user can make use of its networking services, and it will be configured for the "hamachi" account (to be created).

# make install

You should expect some output like this:

Copying hamachi into /usr/bin ..
Creating hamachi-init symlink ..
Compiling tuncfg ..
Copying tuncfg into /sbin ..

Hamachi is installed. See README for what to do next.

Perhaps you get stuck into dependencies, like OpenSSH or OpenSSL. If that is the case, install the required packages (e.g. by calling "apt-get install openssl") before proceeding and then try installing hamachi again. A nice try is to use ldd command onto "hamachi" or "tuncfg" binaries in order to have a clue of what file or package needs to be resolved.

Next, run the TUN/TAP device driver [3] configurator:

# ./tuncfg/tuncfg

This time if nothing comes out everything is alright. :)

The next step consists in generating the user crypto identity:

# hamachi-init

You will see the following output in the terminal:

Initializing Hamachi configuration (/root/.hamachi).
Please wait ..
generating 2048-bit RSA keypair .. ok
making /root/.hamachi directory .. ok

saving /root/.hamachi/client.pub .. ok

saving /root/.hamachi/client.pri .. ok

saving /root/.hamachi/state .. ok

Authentication information has been created.

Hamachi can now be started with
'hamachi start' command and then brought online with 'hamachi login'.

Voilà, all the required security keys (private and public) have just been generated on a hidden directory called .hamachi inside the user's home. Note that it is a highly encrypted 2048-bit RSA keypair!

Initialize manually the service by calling the instruction below:

# hamachi start

This single line should appear:

Starting Hamachi hamachi-lnx-0.9.9.9-20 .. ok

Next, it is desirable for you to set a Hamachi nick for the current client by typing:

# hamachi set-nick zangaro

In your case, replace "zangaro" by, say, the identification you usually give your computer.

Now you should put the daemon online and create an account by running this command:

# hamachi login

This simple message is expected:

Logging in ......... ok

If you have no network yet to join, you will need to create yours by typing:

# hamachi create Agajorte

Replace "Agajorte" by the name you will give your new network. A password will be prompted and then the network will be created.

If you are going to join an existing network, just type:

# hamachi join Agajorte

Then, to appear to other users, type this command:

# hamachi go-online Agajorte

Now, to list other members in the network and their respective status, type:

# hamachi list

By default peers' nicknames are not shown in the listing. In order to enable it, you will need to run this command:

# hamachi get-nicks

If you type "hamachi" without any arguments, the outcome is something like this:

Hamachi, a zero-config virtual private networking utility, ver 0.9.9.9-20

version : hamachi-lnx-0.9.9.9-20
pid : 5063
status : logged in
nickname : zangaro

Also, you could have Hamachi usage tips shown by running this command:

# hamachi help

If you successfully came so far, congratulations! We're half way to conclude the process...

You will now need to stop the daemon. Run this command:

# hamachi stop

As every secondary service in the UNIX world, Hamachi daemon could not be initialized using the superuser root account for security reasons. A so-called system user for this service will be created for Hamachi administration tasks. Type the following instruction to add an user called "hamachi" to /etc/passwd.

# adduser --system --disabled-password --no-create-home hamachi

Adding system user `hamachi' (UID 108) ...
Adding new user `hamachi' (UID 108) with group `nogroup' ...
Not creating home directory `/home/hamachi'.
zangaro:/home/rodrigo# id hamachi
uid=108(hamachi) gid=65534(nogroup) grupos=65534(nogroup)

Note that this user has no home directory. He won't need it.

Then, move the Hamachi first initialized configuration directory to /etc/hamachi. In order to let the superuser to still execute Hamachi operations, a symbolic link will be created. Finally, change /etc/hamachi directory and respective ownership to the newly added "hamachi" account. Here are the referenced commands:

# mv /root/.hamachi /etc/hamachi
# ln -s /etc/hamachi /root/.hamachi
# chown hamachi.hamachi /etc/hamachi/ -R

The next step is to develop a Shell Script to start and stop Hamachi daemon. Run this command:

# vi /etc/init.d/hamachi

Then type the instructions below:



#!/bin/bash
#
# hamachi This shell script takes care of starting and stopping hamachi.
# author: Rodrigo HJORT (http://agajorte.blogspot.com)
#
# chkconfig: 345 99 9
# description: hamachi is a zero-configuration VPN
#

PATH=/sbin:/bin:/usr/bin

HAMUSR=hamachi
HAMDIR=/etc/hamachi
HAMBIN=/usr/bin/hamachi

. /lib/lsb/init-functions

[ -f $HAMDIR/client.pri ] || exit 2
[ -f $HAMDIR/client.pub ] || exit 3

[ -f $HAMBIN ] || exit 4

do_start () {
echo "Starting hamachi..."
/sbin/tuncfg
call_daemon start
}

do_status () {
call_daemon
}

do_stop () {
echo "Stopping hamachi..."
killall tuncfg
call_daemon stop
}

call_daemon () {
su $HAMUSR -c "$HAMBIN -c $HAMDIR $1"
}

case "$1" in
start)
do_start
;;
stop)
do_stop
;;
restart)
do_stop
sleep 1
do_start
;;
status)
do_status
;;
*)
echo "Usage: hamachi {start|stop|restart|status}" >&2
exit 1
;;
esac

Give proper execution permissions to the script file by running the following command:

# chmod +x /etc/init.d/hamachi

Now you could perform a simple test by calling:

# /etc/init.d/hamachi

Usage: hamachi {start|stop|restart|status}

Then start the daemon:

# /etc/init.d/hamachi start

Starting hamachi...
Starting Hamachi hamachi-lnx-0.9.9.9-20 .. ok

And then retrieve the service status:

# /etc/init.d/hamachi status

Hamachi, a zero-config virtual private networking utility, ver 0.9.9.9-20

version : hamachi-lnx-0.9.9.9-20
pid : 4997
status : logged in
nickname : zangaro-lin

The most important fact to observe now is that Hamachi service is no longer bound to "root" superuser, but to its proper account: the "hamachi" system user.

# ps aux | grep ^hamachi

hamachi 5063 0.1 0.0 3104 804 ? S 01:42 0:00 /usr/bin/hamachi -c /etc/hamachi start

You could also restart the service by invoking this command:

# /etc/init.d/hamachi restart

Stopping hamachi...
Shutting down .. ok
Starting hamachi...
Starting Hamachi hamachi-lnx-0.9.9.9-20 .. ok

At last, you could stop the service by calling this:

# /etc/init.d/hamachi stop

Stopping hamachi...
Shutting down .. ok

Hold on, there is only one detail left to do!

It will be very interesting to have the service initialized automatically as the system starts, i.e. on Linux boot time. This is a responsibility for System-V, but usually its configuration is distribution-dependent. You should check out your Linux distro on how to do it.

As Debian environment was chosen for the tests, System-V style init script links were installed through update-rc.d command, as shown below:

# update-rc.d hamachi defaults 09 99

Adding system startup for /etc/init.d/hamachi ...
/etc/rc0.d/K99hamachi -> ../init.d/hamachi
/etc/rc1.d/K99hamachi -> ../init.d/hamachi
/etc/rc6.d/K99hamachi -> ../init.d/hamachi
/etc/rc2.d/S09hamachi -> ../init.d/hamachi
/etc/rc3.d/S09hamachi -> ../init.d/hamachi
/etc/rc4.d/S09hamachi -> ../init.d/hamachi
/etc/rc5.d/S09hamachi -> ../init.d/hamachi

Well, unless you care about your uptime or if you are sure about the configuration you made on Sytem-V, you might reboot your Linux to find out whether the entire effort was worthy. Bon courage !

Even if you have another kind of Linux, I hope most of information detailed in the present document are valuable for you. Please don't hesitate in scratching up some comments. :D

References:

[1] Hamachi Official Site, https://secure.logmein.com/products/hamachi/vpn.asp
[2] Hamachi for Linux Binaries, http://files.hamachi.cc/linux/
[3] TUN/TAP device driver, http://hamachi.cc/tuntap