Mostrando entradas con la etiqueta servidores. Mostrar todas las entradas
Mostrando entradas con la etiqueta servidores. Mostrar todas las entradas

miércoles, 30 de diciembre de 2015

Instalar iRedMail en ubuntu 14.04

Vamos a preparar nuestro ubuntu para instalar iRedMail:

  • Instalar Apache+PHP+mysql
  • Instalar Apache2+PHP+mysql
  • Comprobar contenido fichero /etc/hostname
  • archivo hostname
  • Comprobar contenido fichero /etc/hosts
  • [caption id="attachment_177" align="aligncenter" width="300"]archivo hosts archivo hosts[/caption]
  • Descargamos y descomprimimos iRedMail
  • descargar iRedmail
  • Entrar al directorio iRedmail y darle permisos de ejecución al script
  • dar permisos ejecución
  • Una vez comenzada la instalación, no pide un directorio a utilizar como espacio de correo
  • [caption id="attachment_183" align="aligncenter" width="300"]Espacio correo *Si se desea dejar por defecto[/caption]
  • Elegimos servidor web a utiliza, en mi caso apache
  • Servidor web apache
  • Elegimos B.B.D.D, mysql en este ejemplo
  • <img src="http://antoniocarmona.biz/blog/wp-content/uploads/2015/12/8-300x182.png
  • "

  • alt="mysql" width="300" height="182" class="aligncenter size-medium wp-image-185" />

  • Elegimos nombre dominio diferente al del fichero /etc/hosts
  • elegir dominio
  • Elegir pass para la cuenta administrador
  • elegir pass cuenta administrador
  • Instalamos todas las funcionalidades
  • instalar funcionalidades
  • Revisamos configuración y aceptamos para comenzar instalación
  • configuración
  • En la siguiente pantalla nos pedira que si queremos introducir una regla para acceso SSH en nuestro script de iptables
  • SSH+iptables

Y a esperar a que la instalación finalice y reiniciamos y accedemos mediante un navegador con los datos de acceso que nos proporciona el fichero iRedmail.tips y ya podremos acceder al webmail sogo o roundcube

lunes, 9 de septiembre de 2013

Cliente OpenVPN en ubuntu+android


Cliente OpenVPN en ubuntu+android

Primero del todo quisiera remarcar que parte de la información que me dispongo a compartir esta extraída de un proyecto con fines académicos de la Universidad de Tsukuba en Japón.

Bien comencemos con una buena practica, actualizar nuestro PC/laptop:

sudo su

apt-get update && apt-get dist-upgrade

Instalar OpenVPN:

apt-get install openvpn network-manager-openvpn

Una vez finalizado este proceso seguimos el enlace, donde seleccionaremos los servidores con soporte OpenVPN.


server list


Una vez elegido el servidor, nos descargamos su archivo de configuración TCP o UDP, es indiferente.

config fileUDP file 

Editamos el archivo descargado y cortamos lo que hay entre la entre las etiquetas y , lo pegamos en un nuevo documento y lo nombramos como ca.crt.

ca.crt

Ya podemos configurar en nuestro sistema la configuración para la nueva VPN.


conf VPN

importar conf

Una vez importada la configuración de la VPN, utilizamos como nombre y contraseña la clave vpn y donde tambien elegiremos el certificado que anteriormente nombramos como ca.crt.




Ahora es el turno de configurar OpenVPN en android, si cabe es aun más sencillo.

Desde Play Store nos descargamos el sotfware  OpenVPN Connect.

Seguimos el enlace, donde seleccionaremos los servidores con soporte OpenVPN.



server list


Una vez elegido el servidor, nos descargamos su archivo de configuración TCP o UDP, es indiferente.

 config fileUDP file
Dejo un vídeo con todo el proceso para aclarar cualquier duda que pueda surgir.

Una vez instalado en OpenVPN Connect en nuestro smartphone android, lo iniciamos e importamos el archivo ovpn descargado.

import profile

Una vez importado el perfil, ya podemos utilizar el servidor VPN.

conenct VPN


Personalmente no puedo asegurar al 100% la fiabilidad de estos servicios gratuitos, que no se me malinterprete, no estoy diciendo que los servicios de pago/propietarios sean más confiables, no siempre el ratio calidad/precio es directamente proporcional. Tan sólo quiero decir que cualquiera puede publicar su servidor VPN y no se que filtros se le aplican.


Por otra parte he podido probar los protocolos http, https, SMTP e IMAP y funcionan correctamente, en cambio el P2P parece no estar soportado.

lunes, 12 de agosto de 2013

Servidor Email con postfix, dovecot, ispconfig3 ,mysql y squirrelmailen ubuntu 12.04.2


POSTFIX+DOVECOT+MYSL+ISPCONFIG3
+SQUIRRELMAIL en ubuntu server 12.04.2

sudo su


echo "# The primary network interface

auto eth0

iface eth0 inet static

address 192.168.1.103

netmask 255.255.255.0

gateway 192.168.1.1

network 192.168.1.0

dns-nameserves 192.168.1.103 192.168.1.1

dns-search servidor.acl.net" >> /etc/network/interfaces



echo "servidor" > /etc/hostname



echo "127.0.0.1 localhost

192.168.1.103 servidor.acl.net servidor" >/etc/hosts

cp /etc/apt/sources.list /etc/apt/sources.list.bak

nano /etc/apt/sources.list


#deb cdrom:[Ubuntu-Server 12.04 LTS _Precise Pangolin_ - Release amd64 (20120424.1)]/ precise main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://de.archive.ubuntu.com/ubuntu/ precise main restricted
deb-src http://de.archive.ubuntu.com/ubuntu/ precise main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://de.archive.ubuntu.com/ubuntu/ precise-updates main restricted
deb-src http://de.archive.ubuntu.com/ubuntu/ precise-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://de.archive.ubuntu.com/ubuntu/ precise universe
deb-src http://de.archive.ubuntu.com/ubuntu/ precise universe
deb http://de.archive.ubuntu.com/ubuntu/ precise-updates universe
deb-src http://de.archive.ubuntu.com/ubuntu/ precise-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://de.archive.ubuntu.com/ubuntu/ precise multiverse
deb-src http://de.archive.ubuntu.com/ubuntu/ precise multiverse
deb http://de.archive.ubuntu.com/ubuntu/ precise-updates multiverse
deb-src http://de.archive.ubuntu.com/ubuntu/ precise-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://de.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
deb-src http://de.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse

deb http://security.ubuntu.com/ubuntu precise-security main restricted
deb-src http://security.ubuntu.com/ubuntu precise-security main restricted
deb http://security.ubuntu.com/ubuntu precise-security universe
deb-src http://security.ubuntu.com/ubuntu precise-security universe
deb http://security.ubuntu.com/ubuntu precise-security multiverse
deb-src http://security.ubuntu.com/ubuntu precise-security multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu precise partner
# deb-src http://archive.canonical.com/ubuntu precise partner

## Uncomment the following two lines to add software from Ubuntu's
## 'extras' repository.
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
# deb http://extras.ubuntu.com/ubuntu precise main
# deb-src http://extras.ubuntu.com/ubuntu precise main

- Actualizamos para posteriormente reiniciar:

apt-get update

apt-get upgrade

reboot

- Reconfiguramos el interprete de comandos:

dpkg-reconfigure dash

usar /bin/sh->No

- Deshabilitamos apparmor, para evitar problemas:

/etc/init.d/apparmor stop

update-rc.d -f apparmor remove

apt-get remove apparmor apparmor-utils

- Instalamos paquete para mantener actualizada la hora en nuestro sistema:

apt-get install ntpdate

- Instalamos Postfix, Dovecot, MySQL, rkhunter, binutils :

apt-get install postfix postfix-mysql postfix-doc mysql-client mysql-server openssl g
etmail4 rkhunter binutils dovecot-imapd dovecot-pop3d dovecot-mysql dovecot-sieve


New password for the MySQL "root" user:
Repeat password for the MySQL "root" user:
General type of mail configuration:
System mail name:

- Descomentamos /etc/postfix/master.cf las siguientes lineas, de modo que quede lo siguiente:

submission inet n - - - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
# -o milter_macro_daemon_name=ORIGINATING
smtps inet n - - - - smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
# -o milter_macro_daemon_name=ORIGINATING

service postfix restart

- Hacemos que mysql pueda ser accesible desde cualqier ip, para lo cual editamos el arcivo /etc/mysql/my.cnfy comentamos linea, bind-address =127.0.0.1 :

service mysql restart


- Comprobamos que ha funcionado correctamente:

root@servidor:/home/antonio# netstat -tap | grep mysql
tcp 0 0 *:mysql *:* LISTEN 1025/mysqld

- Instalamos Amavisd, SpamAssassin, And Clamav :

apt-get install amavisd-new spamassassin clamav clamav-daemon zoo unzip bzip2 arj nomarch lzop cabextract apt-listchanges libnet-ldap-perl libauthen-sasl-perl clamav-docs daemon libio-string-perl libio-socket-ssl-perl libnet-ident-perl zip libnet-dns-perl

- Detenemos el servicio spamassassin, ya que ispconfig3 carga el filtro Amavisd y a su vez este carga como modulo spamassassin:

/etc/init.d/spamassassin stop

update-rc.d -f spamassassin remove

- Instalamos apache2, phpmyadmin y otros paquetes:

apt-get install apache2 apache2.2-common apache2-doc apache2-mpm-prefork apache2-utils libexpat1 ssl-cert libapache2-mod-php5 php5 php5-common php5-gd php5-mysql php5-imap phpmyadmin php5-cli php5-cgi libapache2-mod-fcgid apache2-suexec php-pear php-auth php5-curl php5-mcrypt mcrypt php5-imagick imagemagick libapache2-mod-suphp libruby libapache2-mod-ruby libapache2-mod-python libapache2-mod-perl2

Web server to reconfigure automatically:
Configure database for phpmyadmin with dbconfig-common?

- Habilitamos los siguientes modulos en apache:

a2enmod suexec rewrite ssl actions include

service apache2 restart

a2enmod dav_fs dav auth_digest

service apache2 restart

- Editamos el archivo /etc/mime.types y comentamos la linea application/x-ruby.

service apache2 restart

- Instalamos el paquete php5-xcache , que es una especie de cache para el código php5:

apt-get install php5-xcache

service apache2 restart

- Instalamos el manejador de procesos php5-fpm y habilitamos el modulo fascgi:

apt-get install libapache2-mod-fastcgi php5-fpm

a2enmod actions fastcgi alias

service apache2 restart

- Instalamos paquete para manejar listas de correo:

apt-get install mailman

root@servidor:/home/antonio# newlist mailman

Enter the email of the person running the list: acl@acl.net
Initial mailman password:
To finish creating your mailing list, you must edit your /etc/aliases (or
equivalent) file by adding the following lines, and possibly running the
`newaliases' program:

## mailman mailing list
mailman: "|/var/lib/mailman/mail/mailman post mailman"
mailman-admin: "|/var/lib/mailman/mail/mailman admin mailman"
mailman-bounces: "|/var/lib/mailman/mail/mailman bounces mailman"
mailman-confirm: "|/var/lib/mailman/mail/mailman confirm mailman"
mailman-join: "|/var/lib/mailman/mail/mailman join mailman"
mailman-leave: "|/var/lib/mailman/mail/mailman leave mailman"
mailman-owner: "|/var/lib/mailman/mail/mailman owner mailman"
mailman-request: "|/var/lib/mailman/mail/mailman request mailman"
mailman-subscribe: "|/var/lib/mailman/mail/mailman subscribe mailman"
mailman-unsubscribe: "|/var/lib/mailman/mail/mailman unsubscribe mailman"

Hit enter to notify mailman owner...

nano /etc/aliases

añadir lineas:
## mailman mailing list
mailman: "|/var/lib/mailman/mail/mailman post mailman"
mailman-admin: "|/var/lib/mailman/mail/mailman admin mailman"
mailman-bounces: "|/var/lib/mailman/mail/mailman bounces mailman"
mailman-confirm: "|/var/lib/mailman/mail/mailman confirm mailman"
mailman-join: "|/var/lib/mailman/mail/mailman join mailman"
mailman-leave: "|/var/lib/mailman/mail/mailman leave mailman"
mailman-owner: "|/var/lib/mailman/mail/mailman owner mailman"
mailman-request: "|/var/lib/mailman/mail/mailman request mailman"
mailman-subscribe: "|/var/lib/mailman/mail/mailman subscribe mailman"
mailman-unsubscribe: "|/var/lib/mailman/mail/mailman unsubscribe mailman"

newaliases

service postfix restart

ln -s /etc/mailman/apache.conf /etc/apache2/conf.d/mailman.conf

service apache2 restart

service mailman start

- Instalamos demonio pureftp y el paquete para aplicar cuotas de disco:

apt-get install pure-ftpd-common pure-ftpd-mysql quota quotatool

- Configurar correctamente el demonio pureftpd:

nano /etc/default/pure-ftpd-common

# STANDALONE_OR_INETD
# valid values are "standalone" and "inetd".
# Any change here overrides the setting in debconf.
STANDALONE_OR_INETD=standalone

# VIRTUALCHROOT:
# whether to use binary with virtualchroot support
# valid values are "true" or "false"
# Any change here overrides the setting in debconf.
VIRTUALCHROOT=true

- Halilitamos soporte TLS para pure-ftp:

echo 1 > /etc/pure-ftpd/conf/TLS

mkdir -p /etc/ssl/private/

openssl req -x509 -nodes -days 7300 -newkey rsa:2048 -keyout /etc/ssl/private/pure-ftpd.pem -out /etc/ssl/private/pure-ftpd.pem

Country Name (2 letter code) [AU]:ES
State or Province Name (full name) [Some-State]:Murcia
Locality Name (eg, city) []:Cehegin
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:mail
Common Name (e.g. server FQDN or YOUR name) []:acl
Email Address []:acl@acl.net

chmod 600 /etc/ssl/private/pure-ftpd.pem

service pure-ftpd-mysql restart

- Modificamos el fichero/etc/fstab para añadir opciones de montaje y se puedan aplicar las cuotas:

# / was on /dev/sda1 during installation
UUID=2213902e-ff7f-4898-aee2-923e1df5b9a3 / ext4 errors=remount-ro,usrjquota=quota.user,grpjquota=quota.group,jqfmt=vfsv00 1

- Volvemos a cargar el sistema de ficheros, chequeamos que la cuota se ha aplicado correctamente y posteriormente iniciamos el servicio para aplicar cuotas:

mount -o remount /

quotacheck -avugm

quotaon -avug

- Instalamos servidor DNS:

apt-get install bind9 dnsutils

- Instalamos Vlogger, Webalizer y Awstats:

apt-get install vlogger webalizer awstats geoip-database libclass-dbi-mysql-perl

nano /etc/cron.d/awstats y comentamos todas las lineas

- Instalamos paquetes para compilar:

apt-get install build-essential autoconf automake1.9 libtool flex bison debhelper binutils-gold

cd /tmp


tar -xvf jailkit-2.14.tar.gz

cd jailkit-2.14

./debian/rules binary

cd ..

dpkg -i jailkit_2.14-1_*.deb

rm -rf jailkit-2.14*

apt-get install fail2ban

- instalamos webmail:

apt-get install squirrelmail

squirrelmail-configure

opcion D y elegimos dovecot

salvamos y salimos.

cd /etc/apache2/conf.d/

ln -s ../../squirrelmail/apache.conf squirrelmail.conf

service apache2 restart

- Editamos archivo /etc/apache2/conf.d/squirrelmail.confe introducimos la siguiente información para que el modulo php sea utilizado en squirrelmail:


Options FollowSymLinks

AddType application/x-httpd-php .php
php_flag magic_quotes_gpc Off
php_flag track_vars On
php_admin_flag allow_url_fopen Off
php_value include_path .
php_admin_value upload_tmp_dir /var/lib/squirrelmail/tmp
php_admin_value open_basedir /usr/share/squirrelmail:/etc/squirrelmail:/var/lib/squirrelmail:/etc/hostname:/etc/mailname:/var/spool/squirrelmail
php_flag register_globals off


DirectoryIndex index.php

# access to configtest is limited by default to prevent information leak

order deny,allow
deny from all
allow from 127.0.0.1

 
- Creamos directorio /var/lib/squirrelmail/tmp y le damos la propiedad al usuario www-data:

mkdir /var/lib/squirrelmail/tmp

chown www-data /var/lib/squirrelmail/tmp

service apache2 restart 
 
- Editamos archivo/etc/apache2/conf.d/squirrelmail.conf y creamos alias para squirrelmail:

Alias /squirrelmail /usr/share/squirrelmail
Alias /webmail /usr/share/squirrelmail

service apache2 reload 
- Instalamos ispconfig3:
cd /tmp  
wget http://prdownloads.sourceforge.net/ispconfig/ISPConfig-3.0.5.2.tar.gz  
tar xfvz ISPConfig-3.0.5.2.tar.gz  
cd ispconfig3_install/install/ 
 
root@servidor:/tmp/ispconfig3_install/install# php -q install.php


--------------------------------------------------------------------------------
_____ ___________ _____ __ _ ____
|_ _/ ___| ___ / __ / _(_) /__
| | `--.| |_/ / | / / ___ _ __ | |_ _ creando una creando VPN__ _ _/ /
| | `--. __/ | | / _ | '_ | _| |/ _` | |_ |
_| |_/__/ / | | __/ (_) | | | | | | | (_| | ___
___/____/_| ____/___/|_| |_|_| |_|__, | ____/
__/ |
|___/
--------------------------------------------------------------------------------


>> Initial configuration

Operating System: 12.04.2 LTS (Precise Pangolin)

Following will be a few questions for primary configuration so be careful.
Default values are in [brackets] and can be accepted with .
Tap in "quit" (without the quotes) to stop the installer.


Select language (en,de) [en]:

Installation mode (standard,expert) [standard]:

Full qualified hostname (FQDN) of the server, eg server1.domain.tld [servidor.acl.com]:

MySQL server hostname [localhost]:

MySQL root username [root]:

MySQL root password []: xxxx

MySQL database to create [dbispconfig]:

MySQL charset [utf8]:

Generating a 4096 bit RSA private key
............................................................................................................................................................................................................................++
..++
writing new private key to 'smtpd.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) [AU]:ES
State or Province Name (full name) [Some-State]:Murcia
Locality Name (eg, city) []:Cehegin
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:mail
Common Name (e.g. server FQDN or YOUR name) []:acl
Email Address []:acl@acl.net
Configuring Jailkit
Configuring Dovecot
Configuring Spamassassin
Configuring Amavisd
Configuring Getmail
Configuring Pureftpd
Configuring BIND
Configuring Apache
Configuring Vlogger
Configuring Apps vhost
Configuring Bastille Firewall
Configuring Fail2ban
Installing ISPConfig
ISPConfig Port [8080]:

Do you want a secure (SSL) connection to the ISPConfig web interface (y,n) [y]:

Generating RSA private key, 4096 bit long modulus
..........................++ creando una creando VPN
.................................................................++
e is 65537 (0x10001)
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) [AU]:ES
State or Province Name (full name) [Some-State]:Murcia
Locality Name (eg, city) []:Cehegin
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:mail
Common Name (e.g. server FQDN or YOUR name) []:acl
Email Address []:acl@acl.net
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
writing RSA key
Configuring DBServer com
Installing ISPConfig crontab
no crontab for root
no crontab for getmail
Restarting services ...

. . . . . . . . . . . . . . . . . . . . . . . . . .


Restarting ftp server: Running: /usr/sbin/pure-ftpd-mysql-virtualchroot -l mysql:/etc/pure-ftpd/db/mysql.conf -l pam -Y 1 -O
 clf:/var/log/pure-ftpd/transfer.log -E -u 1000 -8 UTF-8 -D -A -b -H -B 
Installation completed.

Con esto ya tenemos nuestro mail server totalmente instalado, para posteriormente configurar al menos una zona DNS y crear 
nuevos buzones, nos dirigiremos a ISPCONFIG3:
https://localhost:8080, donde el usuario por defecto es admin y su contraseña sera admin.
Hay dejo un gif con los pasos a repoducir:
Adicionalmente también podéis instalar un software para poder monitorizar el
mail server desde android,yo personalmente lo veo innecesario, ya que creando una creando VPN se
puede hacer exactamente lo mismo, incluso más,
ya que se puede tener acceso a los distintos recursos de nuestro servidor.

- Para hacer unos chequeos:
 root@servidor:/home/antonio# telnet localhost 143 
Trying 127.0.0.1...
Connected to localhost.localdomain.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE STARTTLS AUTH=PLAIN
 AUTH=LOGIN] Dovecot ready. 
a login acl@acl.net contraseña 
a OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY
 THREAD=REFERENCES THREAD=REFS
 MULTIAPPEND UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC
 ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS QUOTA] Logged in 
b select inbox
* FLAGS (Answered Flagged Deleted Seen Draft)
* OK [PERMANENTFLAGS (Answered Flagged Deleted Seen Draft *)] Flags permitted.
* 1 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 1375891119] UIDs valid
* OK [UIDNEXT 3] Predicted next UID
* OK [HIGHESTMODSEQ 1] Highest
b OK [READ-WRITE] Select completed.
c list "" * creando una creando VPN
* LIST (HasNoChildren) "." "Sent"
* LIST (HasNoChildren) "." "Junk"
* LIST (HasNoChildren) "." "Drafts"
* LIST (HasNoChildren) "." "Trash"
* LIST (HasNoChildren) "." "INBOX"
c OK List completed.
d lsub "" *
* LSUB () "." "Sent"
* LSUB () "." "Drafts"
* LSUB () "." "Trash"
* LSUB () "." "Junk"
d OK Lsub completed.
e logout
* BYE Logging out
e OK Logout completed.
root@servidor:/home/antonio# telnet servidor.acl.net 143
Trying 172.16.59.129...
Connected to servidor.acl.net.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE STARTTLS AUTH=PLAIN AUTH=LOGIN] Dovecot ready.
a login acl@acl.net contraseña
a OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS MULTIAPPEND UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS QUOTA] Logged in
b select inbox
* FLAGS (Answered Flagged Deleted Seen Draft)
* OK [PERMANENTFLAGS (Answered Flagged Deleted Seen Draft *)] Flags permitted.
* 1 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 1375891119] UIDs valid
* OK [UIDNEXT 3] Predicted next UID
* OK [HIGHESTMODSEQ 1] Highest
b OK [READ-WRITE] Select completed.
c list "" *
* LIST (HasNoChildren) "." "Sent"
* LIST (HasNoChildren) "." "Junk"
* LIST (HasNoChildren) "." "Drafts"
* LIST (HasNoChildren) "." "Trash"
* LIST (HasNoChildren) "." "INBOX"
c OK List completed.
d lsub "" *
* LSUB () "." "Sent"
* LSUB () "." "Drafts"
* LSUB () "." "Trash"
* LSUB () "." "Junk" e logout
* BYE Logging out
e OK Logout completed.
d OK Lsub completed.
e logout
* BYE Logging out
e OK Logout completed.
Connection closed by foreign host.com

lunes, 29 de julio de 2013

Servidor de dominio en ubuntu server 12.04.2 con samba 4


Servidor de dominio en ubuntu server 12.04.2 con samba 4

Os dejo un tuto sobre como montar un servidor de dominio con samba 4.

A continuación voy a explicar 2 métodos de como hacerlo, mediante apt y compilar el código fuente, personalmente prefiero el segundo método, pero de todas formas hay lo dejo:

Para montar el servidor de dominio en ubuntu 12.04.2, para este ejemplo, necesitaremos el anteriormente mencionado samba 4, bind9 y kerberos aplicable a la siguiente topología:

topologia

Primera opción(compilar fuente).

- Configuración inicial:

sudo su

echo "# The primary network interface
auto eth0
iface eth0 inet static
address 192.168.1.103
netmask 255.255.255.0
gateway 192.168.1.1
network 192.168.1.0
dns-nameserves 192.168.1.103 192.168.1.1
dns-search servidorlocal.test.local
# Secundary network interface
auto eth1
iface eth1 inet dhcp" >> /etc/network/interfaces

echo "servidorlocal" > /etc/hostname

echo "127.0.0.1 localhost
192.168.1.103 servidorlocal servidorlocal.test.local" >/etc/hosts

- Actualizamos nuestro servidor e instalamos los paquetes necesarios:

apt-get update && apt-get dist-upgrade

apt-get install build-essential libacl1-dev python-dev libldap2-dev pkg-config gdb libgnutls-dev libblkid-dev libreadline-dev libattr1-dev python-dnspython libpopt-dev libbsd-dev attr docbook-xsl libcups2-dev git
reboot

- Descargamos samba 4 y lo dejamos en la ruta /usr/src/samba4: 
 git clone git://git.samba.org/samba.git /usr/src/samba4/ 
 - Antes de compilar, se prepara el paquete conforme a nuestras necesidades: 
 cd /usr/src/samba4/  
 ./configure --enable-debug 
 - Se compila el paquete, en este punto paciencia, porque dependiendo de los recursos del equipo, puede tardar más o menos: 
 make 
- Una vez compilado, procedemos al instalar samba 4: 
    make install 
     
     - Añadimos al path la ruta de los ejecutables de samba 4 para lo cual, editamos/creamos el archivo .bashrc e introducimos la siguiente linea:
     
    export PATH="/usr/local/samba/sbin:/usr/local/samba/bin:$PATH"


    - Creamos el dominio:

    samba-tool domain provision --realm test.local --domain TEST --adminpass P$ssword --server-role=dc --use-ntvfs

    - Probamos que samba funciona correctamente: 

    root@servidorlocal:/home/antonio#smbclient -L localhost -U%
      Domain=[TEST] OS=[Unix] Server=[Samba 4.2.0pre1-GIT-44429f9]

      Sharename Type Comment
      --------- ---- -------
      netlogon Disk
      sysvol Disk
      IPC$ IPC IPC Service
      Domain=[TEST] OS=[Unix] Server=[Samba 4.2.0pre1-GIT-44429f9]

      Server Comment
      --------- -------

      Workgroup Master
      --------- -------

      root@servidorlocal:/home/antonio# /usr/local/samba/bin/smbclient //localhost/netlogon -U 'administrator'
        Enter administrator's password:
        Domain=[TEST] OS=[Unix] Server=[Samba 4.2.0pre1-GIT-44429f9]
      - Antes de probar que los DNS funcionan correctamente listar el archivo /usr/local/samba/etc/smb.conf, debiendo quedar:

      # Global parameters
      [global]
      workgroup = TEST
      realm = test.local
      netbios name = SERVIDORLOCAL
      server role = active directory domain controller
      dns forwarder = 192.168.1.1
      allow dns updates = nonsecure and secure
      server services = rpc, nbt, wrepl, ldap, cldap, kdc, drepl, winbind, ntp_signd, kcc, dnsupdate, dns, smb
      dcerpc endpoint servers = epmapper, wkssvc, rpcecho, samr, netlogon, lsarpc, spoolss, drsuapi, dssetup, unixinfo, browser, eventlog6, backupkey, dnsserver, winreg, srvsvc
      [netlogon]
      path = /usr/local/samba/var/locks/sysvol/test.local/scripts
      read only = No
      [sysvol]
      path = /usr/local/samba/var/locks/sysvol
      read only = No

      - Tambien listaremos el contenido del fichero /etc/resolv.conf, donde la salida que obtendremos será al parecido a esto:

        # Dynamic resolv.conf(5) file for glibc resolver(3) generated by r
        esolvconf(8)
        # DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
        nameserver 192.168.1.103
        search test.local
      * Si modificamos/introducimos algún parámetro, sera conveniente reiniciar.

      - - Para comprobar que nuestro servidor DNS funciona, podemos ejecutar:

      r root@servidorlocal:/home/antonio# netstat -tunpe | grep ":53"

            tcp 0 0 127.0.0.1:53699 127.0.0.1:953 TIME_WAIT 0 0

      root@servidorlocal:/home/antonio# host -t SRV _ldap._tcp.test.local.

      _ldap._tcp.test.local has SRV record 0 100 389 servidorlocal.test.local.

      root@servidorlocal:/home/antonio# host -t SRV _kerberos._udp.test.local.

             _kerberos._udp.test.local has SRV record 0 100 88 servidorlocal.test.local.

      root@servidorlocal:/home/antonio# host -t servidorlocal.test.local. 
          
               servidorlocal.test.local has address 192.168.1.103 

       - Para hacer que nuestros clientes modifique sus DNS cuando el servidor los modifica, editamos el archivo /etc/bind/named.conf e introducimos la siguiente linea: 

              tkey-gssapi-keytab "/var/lib/samba/private/dns.keytab";
       
      - Instalamos kerberos: 

      apt-get install krb5-user 

      root@servidorlocal:/home/antonio# kinit administrator@TEST.LOCAL 
        Password for administrator@TEST.LOCAL:
        Warning: Your password will expire in 41 days on Fri Aug 30 15:06:12 2013 
         
        * En caso de nos devuelva una fallo, editar fichero /usr/local/samba/share/setup/krb5.conf:
      [libdefaults]
      default_realm = TEST.LOCAL
      dns_lookup_realm = true
      dns_lookup_kdc = true

      root@servidorlocal:/home/antonio# klist -e
        Ticket cache: FILE:/tmp/krb5cc_0
        Default principal: administrator@TEST.LOCAL
        Valid starting Expires Service principal
        20/07/2013 01:30 20/07/2013 11:30 krbtgt/TEST.LOCAL@TEST.LOCAL
        renew until 21/07/2013 01:30
      -Para hacer que samba 4 se ejecute al inicio, creamos el archivo /etc/init.d/samba4 con el siguiente contenido:

      #! /bin/sh
      ### BEGIN INIT INFO
      # Provides: samba
      # Required-Start: $network $local_fs $remote_fs
      # Required-Stop: $network $local_fs $remote_fs
      # Default-Start: 2 3 4 5
      # Default-Stop: 0 1 6
      # Short-Description: start Samba daemons
      ### END INIT INFO
      #
      # Start/stops the Samba daemon (samba).
      # Adapted from the Samba 3 packages.
      #

      SAMBAPID=/var/run/samba/samba.pid

      # clear conflicting settings from the environment
      unset TMPDIR
      # See if the daemon and the config file are there
      test -x /usr/local/samba/sbin -a -r /usr/local/samba/etc/ || exit 0

      . /lib/lsb/init-functions

      case "$1" in
      start)
      log_daemon_msg "Starting Samba 4 daemon" "samba"
      if ! start-stop-daemon --start --quiet --oknodo --exec /usr/local/samba/sbin/samba -- -D; then
      log_end_msg 1
      exit 1
      fi

      log_end_msg 0
      ;;
      stop)
      log_daemon_msg "Stopping Samba 4 daemon" "samba"

      start-stop-daemon --stop --quiet --name samba $SAMBAPID
      # Wait a little and remove stale PID file
      sleep 1
      if [ -f $SAMBAPID ] && ! ps h `cat $SAMBAPID` > /dev/null
      then
      # Stale PID file (samba was succesfully stopped),
      # remove it (should be removed by samba itself IMHO.)
      rm -f $SAMBAPID
      fi

      log_end_msg 0
      ;;
      restart|force-reload)
      $0 stop
      sleep 1
      $0 start
      ;;
      *)
      echo "Usage: /etc/init.d/samba {start|stop|restart|force-reload}"
      exit 1
      ;;
      esac

      exit 0

      chmod 755 /etc/init.d/samba4

      update-rc.d samba4 defaults


      Segunda opción

      - Primero vamos a configurar nuestro servidor:

      sudo su



      echo "# The primary network interface

      auto eth0

      iface eth0 inet static

      address 192.168.1.103

      netmask 255.255.255.0

      gateway 192.168.1.1

      network 192.168.1.0

      dns-nameserves 192.168.1.103 192.168.1.1

      dns-search servidorlocal.test.local

      # Secundary network interface

      auto eth1

      iface eth1 inet dhcp" >> /etc/network/interfaces



      echo "servidorlocal" > /etc/hostname



      echo "127.0.0.1 localhost
      192.168.1.103 servidorlocal servidorlocal.test.local" > /etc/hosts

      - En segundo lugar actualizamos nuestro servidor:

      apt-get update && apt-get dist-upgrade

      reboot

      - Instalamos samba 4:
      apt-get install samba4
          * En este momento es posible que nos devuelva un error que nos dice algo asi como que samba 4 no se pudo configurar, bien, tendremos que editar el archivo /var/lib/dpkg/status y en el paquete samba4 modificar status: install ok half-configured por install ok installed. Si más tarde necesitamos desinstalar samba 4:
        • Borraremos el archivo/var/lib/dpkg/status.
        • Renombraremos el archivo var/lib/dpkg/status-old a var/lib/dpkg/status-old.bak.
        • Y por último renombramos el archivo var/lib/dpkg/status-old.bak a var/lib/dpkg/status-old.
         - Creamos el dominio:
          
        /usr/share/samba/setup/provision --realm=test.local --domain=TEST --adminpass='P$ssword' --server-role=dc 

        - Donde deberemos obtener la información relacionada con el nuevo dominio creado:

        Server Role: domain controller

        Hostname: servidorlocal

        NetBIOS Domain: TEST

        DNS Domain: test.local

        DOMAIN SID: S-1-5-21-41787111-135949663-3539000777


        - Para comprobar que todos los parámetros del archivo de configuración de samba son correctos:
          
        root@servidorlocal:/home/antonio# testparm

        [global]

        workgroup = TEST

        realm = TEST.LOCAL

        passdb backend = samba4

        idmap config * : backend = tdb



        [netlogon]

        path = /var/lib/samba/sysvol/test.local/scripts

        read only = No



        [sysvol]

        path = /var/lib/samba/sysvol

        read only = No

        - Si todo a ido bien, podemos inciar samba y comprobar que nuestro servidor de dominio funciona correctamente:

        initctl start samba4



        apt-get installsamba4-clients

        root@servidorlocal:/home/antonio#smbclient -L localhost -U%
        Sharename Type Comment

        --------- ---- -------

        netlogon Disk

        sysvol Disk

        IPC$ IPC IPC Service

        - Si obtenemos una salida parecida a la anterior, procedemos a instalar y configurar el servidor DNS:
          apt-get install bind9

          nano /etc/bind/named.conf
        include "/var/lib/samba/private/named.conf"
          nano /etc/apparmor.d/usr.sbin.named

        /var/lib/samba/private/** rkw,
        /var/lib/samba/private/dns/** rkw,
        /usr/lib/x86_64-linux-gnu/samba/bind9/** rm,
        /usr/lib/x86_64-linux-gnu/samba/gensec/** rm,
        /usr/lib/x86_64-linux-gnu/ldb/modules/ldb/** rm,
        /usr/lib/x86_64-linux-gnu/samba/ldb/** rm,

        service bind9 restart
          service apparmor reload
            - Para comprobar que nuestro servidor DNS funciona, podemos ejecutar: 
            root@servidorlocal:/home/antonio#netstat -tunpe | grep ":53" 
             
            tcp 0 0 127.0.0.1:53 699 127.0.0.1:953 TIME_WAIT 0 0
            - Comprobamos que samba 4 y bind9 funcionancorrectamente:

            root@servidorlocal:/home/antonio# host -t SRV _ldap._tcp.test.local. 
             
            _ldap._tcp.test.local has SRV record 0 100 389 servidorlocal.test.local.


            root@servidorlocal:/home/antonio# host -t SRV _kerberos._tcp.test.local. 
             
            _kerberos._tcp.test.local has SRV record 0 100 88 servidorlocal.test.local. 

            root@servidorlocal:/home/antonio# host -t A servidorlocal.test.local.

                            servidorlocal.test.local has address 192.168.1.103



            - Para hacer que nuestros clientes modifique sus DNS cuando el servidor los modifica, editamos el archivo /etc/bind/named.conf e introducimos la siguiente linea:
              tkey-gssapi-keytab "/var/lib/samba/private/dns.keytab";
            - Instalamos kerberos:
            apt-get install krb5-user

            root@servidorlocal:/home/antonio# kinit administrator@TEST.LOCAL 
             
            Password for administrator@TEST.LOCAL:
            Warning: Your password will expire in 41 days on Fri Aug 30 15:06:12 2013

            root@servidorlocal:/home/antonio# klist -e

            Ticket cache: FILE:/tmp/krb5cc_0
            Default principal: administrator@TEST.LOCAL
            Valid starting Expires Service principal
            20/07/2013 01:30 20/07/2013 11:30 krbtgt/TEST.LOCAL@TEST.LOCAL
            renew until 21/07/2013 01:30
             

            Opciones comunes

            - Para probar que todo esto realmente funciona vamos a configurar, a modo de prueba, un cliente, en este caso windows xp:
            1. Entramos en la configuración IP y establecemos los parámetros correctos.
            1. Por último modificamos el nombre del equipo, para que se una al dominio.

              joined

            - Crear recurso compartido, a modo de ejemplo se creara una carpeta:

            mkdir /home/compartido



            nano /usr/local/samba/etc/smb.conf

            [compatido] path = /home/compartido
            comment = Carpeta comun
            read only = yes
            - Para crear nuevos usuarios:

            samba-tool user add “user”


            Conclusión: A titulo personal pienso que este proyecto, si bien tiene muy buena pinta,
            de momento no lo pondría en producción, ya que intuyo que el proyecto esta todavía en pañales,
            aunque a mi no me ha dado ningún pete, pero como dicen en mi tierra, el miedo es libre.
             
            Este tuto no es ni mucho menos un todo, pero si creo que es un buen punto de partida para
            empezar con samba 4.
             
            Para la confeción del este tuto se ha consultado diferentes recursos:
             
            http://www.jadota.com/2013/01/installing-samba4-on-ubuntu-12-04/

            http://www.matrix44.net/cms/notes/gnulinux/samba-4-ad-domain-with-ubuntu-12-04
             
            http://www.darklab.co.uk/2013/01/15/creating-a-samba-4-active-directory-primary-domain-controller-on-ubuntu-12-04-1-server/