Usando Linux para muchas cosas y disfrutando de videojuegos, en dispositivos moviles, consolas y pc. Using Linux for many things and enjoying video games, mobile devices, consoles and pc

Servidor subversion con interfaz web Trac

Hoy instalaremos y configuraremos un repositorio subversion con trac, una interfaz web que nos facilitara colaborar en nuestros proyectos de programacion con otras personas en un grupo.
Para esto usaremos un debian o ubuntu server

-Instalamos paquetes que usaremos
apt-get install enscript libapache2-mod-python python-docutils db4.3-util libapache2-svn subversion-tools

-Creamos el directorio para subversion
mkdir -p /var/local/svn/svn.example.com

-Creamos un grupo para desarrollo y agregamos el usuario web a este grupo
addgroup example
adduser www-data example

-Agregamos usuarios al grupo de desarrollo. En mi server el grupo tomo el id 1000
adduser --gid 1000 cabrera

-Colocamos permisos
chmod 2770 /var/local/svn/svn.example.com

-Activamos el repositorio
svnadmin create /var/local/svn/svn.example.com

-Eliminamos passwords para despues crearlos para protocolo https o http
rm /var/local/svn/svn.example.com/conf/passwd
touch /var/local/svn/svn.example.com/conf/passwd

-Damos permiso de escritura al grupo
chmod -R g+w /var/local/svn/svn.example.com

-Cambiamos el dueño y grupo de los files
chown -R www-data:example /var/local/svn/svn.example.com

-Activamos permisos para el repositorio. Ejemplo, dale permiso al grupo example de lectura y escritura
vi /var/local/svn/svn.example.com/conf/authz
example = rw

-Creamos un directorio para los logs
mkdir /var/log/apache2/svn.example.com

-Agregamos a la lista de rotacion de logs de apache
vi /etc/logrotate.d/apache2
/var/log/apache2/svn.example.com {
rotate 6
monthly
compress
missingok
notifempty
}

-Configuramos el directorio virtual de apache
vi /etc/apache2/sites-available/svn.example.com

ServerName svn.example.com

DAV svn
AuthType Basic
AuthName "svn.example.com"
AuthUserFile /var/local/svn/svn.example.com/conf/passwd
AuthzSVNAccessFile /var/local/svn/svn.example.com/conf/authz
SVNPath /var/local/svn/svn.example.com
Require valid-user

CustomLog /var/log/apache2/svn.example.com/access.log combined
ErrorLog /var/log/apache2/svn.example.com/error.log
# Descomente la siguiente linea cuando tenga un certificado web real.
# SSLCertificateKeyFile /etc/apache2/ssl/server.key


-Activamos el sitio virtual
a2ensite svn.example.com

-Creamos los usuarios web
htpasswd /var/local/svn/svn.example.com/conf/passwd cabrera

-Reiniciamos apache
/etc/init.d/apache2 restart

-Creamos un link para poder trabajar localmente
ln -s /usr/bin/svnwrap /usr/local/bin/svn

-Creamos el directorio web para trac
mkdir -p /var/local/trac/trac.example.com

-Activamos permisos
chmod 2770 /var/local/trac/trac.example.com

-Descargamos setuptools, en este caso el de python 2.4, si tiene otra version, cambie el file a descargar o verifique desde la pagina de python

wget -c http://pypi.python.org/packages/2.4/s/setuptools/setuptools-0.6c9-py2.4.egg

-Lo instalamos
sh setuptools-0.6c9-py2.4.egg

-Instalamos trac 0.11
easy_install http://svn.edgewall.org/repos/trac/tags/trac-0.11

-Creamos una instancia de trac
trac-admin /var/local/trac/trac.example.com initenv
Creating a new Trac environment at /var/local/trac/trac.hyette.com

Trac will first ask a few questions about your environment
in order to initalize and prepare the project database.

Please enter the name of your project.
This name will be used in page titles and descriptions.

Project Name [My Project]> Cabrera project

Please specify the connection string for the database to use.
By default, a local SQLite database is created in the environment
directory. It is also possible to use an already existing
PostgreSQL database (check the Trac documentation for the exact
connection string syntax).

Database connection string [sqlite:db/trac.db]>

Please specify the type of version control system,
By default, it will be svn.

If you don't want to use Trac with version control integration,
choose the default here and don't specify a repository directory.
in the next question.

Repository type [svn]>

Please specify the absolute path to the version control
repository, or leave it blank to use Trac without a repository.
You can also set the repository location later.

Path to repository [/path/to/repos]> /var/local/svn/svn.example.com

Creating and Initializing Project
Installing default wiki pages
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracFineGrainedPermissions imported from TracFineGrainedPermissions
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracPermissions imported from TracPermissions
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiProcessors imported from WikiProcessors
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracLogging imported from TracLogging
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracWiki imported from TracWiki
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/InterTrac imported from InterTrac
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracBrowser imported from TracBrowser
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/SandBox imported from SandBox
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/InterMapTxt imported from InterMapTxt
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiMacros imported from WikiMacros
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/PageTemplates imported from PageTemplates
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracWorkflow imported from TracWorkflow
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/InterWiki imported from InterWiki
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/CamelCase imported from CamelCase
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracUnicode imported from TracUnicode
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracInstall imported from TracInstall
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracUpgrade imported from TracUpgrade
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracModPython imported from TracModPython
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiRestructuredTextLinks imported from WikiRestructuredTextLinks
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracEnvironment imported from TracEnvironment
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracTickets imported from TracTickets
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracCgi imported from TracCgi
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiPageNames imported from WikiPageNames
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiRestructuredText imported from WikiRestructuredText
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracIni imported from TracIni
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracInterfaceCustomization imported from TracInterfaceCustomization
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracChangeset imported from TracChangeset
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracRoadmap imported from TracRoadmap
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/RecentChanges imported from RecentChanges
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracReports imported from TracReports
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiFormatting imported from WikiFormatting
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TitleIndex imported from TitleIndex
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracQuery imported from TracQuery
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracNotification imported from TracNotification
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracAdmin imported from TracAdmin
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracPlugins imported from TracPlugins
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracAccessibility imported from TracAccessibility
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracGuide imported from TracGuide
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracImport imported from TracImport
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracNavigation imported from TracNavigation
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiHtml imported from WikiHtml
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracStandalone imported from TracStandalone
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiStart imported from WikiStart
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracRevisionLog imported from TracRevisionLog
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracTicketsCustomFields imported from TracTicketsCustomFields
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracLinks imported from TracLinks
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracSyntaxColoring imported from TracSyntaxColoring
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracSearch imported from TracSearch
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracTimeline imported from TracTimeline
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracBackup imported from TracBackup
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracSupport imported from TracSupport
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiNewPage imported from WikiNewPage
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracFastCgi imported from TracFastCgi
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/WikiDeletePage imported from WikiDeletePage
/usr/lib/python2.4/site-packages/Trac-0.11-py2.4.egg/trac/wiki/default-pages/TracRss imported from TracRss
Indexing repository

---------------------------------------------------------------------
Project environment for 'Cabrera project' created.

You may now configure the environment by editing the file:

/var/local/trac/trac.hyette.com/conf/trac.ini

If you'd like to take this new project environment for a test drive,
try running the Trac standalone web server `tracd`:

tracd --port 8000 /var/local/trac/trac.example.com

Then point your browser to http://localhost:8000/trac.example.com.
There you can also browse the documentation for your installed
version of Trac, including information on further setup (such as
deploying Trac to a real web server).

The latest documentation can also always be found on the project
website:

http://trac.edgewall.org/

Congratulations!

-Activamos permisos al directorio web de trac
chown -R www-data:example /var/local/trac/trac.example.com

-Damos permisos de escritura al grupo
chmod -R g+w /var/local/trac/trac.example.com

-Configuramos trac
vi /var/local/trac/trac.example.com/conf/trac.ini

-Creamos un directorio para logs de trac
mkdir /var/log/apache2/trac.example.com

-Agregamos el site a la rotacion de logs
vi /etc/logrotate.d/apache2
/var/log/apache2/trac.example.com {
rotate 6
monthly
compress
missingok
notifempty
}

-Configuramos el directorio virtual
vi /etc/apache2/sites-available/trac.example.com

ServerName localhost
DocumentRoot /var/local/trac/trac.example.com/
Alias /trac/ /usr/share/trac/htdocs

Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all


SetHandler mod_python
PythonHandler trac.web.modpython_frontend
PythonInterpreter main_interpreter
PythonOption TracEnv /var/local/trac/trac.example.com/
PythonOption TracUriRoot /
AuthType Basic
AuthName "trac.example.com"
# Use the SVN password file.
AuthUserFile /var/local/svn/svn.example.com/conf/passwd
Require valid-user

CustomLog /var/log/apache2/trac.example.com/access.log combined
ErrorLog /var/log/apache2/trac.example.com/error.log
# SSLCertificateKeyFile /etc/apache2/ssl/server.key


-Activamos el directorio virtual de trac
a2ensite trac.example.com

-Configuramos los permisos de trac dentro de su consola administrativa
trac-admin /var/local/trac/trac.example.com

-Reiniciamos apache
/etc/init.d/apache2 restart

-Por ultimo, en caso de que no queramos usar apache podemos manejar nuestro web trac con el server que incluye trac
tracd --port 8000 /var/local/trac/trac.example.com

-Tambien tener en cuenta que para que nos funcione en internet esta solucion, los domains usados, en este caso svn.example y trac.example.com deben estar registrados a nuestro nombre y activos y funcionando en un DNS. Share/Bookmark

Actualizar Openbravo de 2.40Beta a 2.40 Stable

Hace unos días paso de beta a stable la versión 2.40 de OpenBravo, un ERP popular en estos días. En una anterior nota, mostré como instalar y configurar en un servidor Centos 5.2 la beta de OpenBravo, en esta nota veremos como pasar de la beta a la versión stable 2.40. La nota anterior pueden verla en este link.
Todos los pasos siguientes son hechos desde la cuenta root del servidor Centos. De mas esta decir que si es un servidor en producción, antes de hacer esto, saque un backup de su configuración por si algo no sale bien. A mi me funciono sin problemas.

-Descargamos el file para hacer el upgrade del beta a la stable.

wget -c http://internap.dl.sourceforge.net/sourceforge/openbravo/OpenbravoERP_2.40beta-2.40-linux-upgrader.bin

-Colocamos atributos de ejecucion

chmod 755 OpenbravoERP_2.40beta-2.40-linux-upgrader.bin

-Detenemos el servicio de tomcat

service Tomcat5 stop

-Comenzamos el upgrade

./OpenbravoERP_2.40beta-2.40-linux-upgrader.bin

Installation directory

Please specify the directory where Openbravo ERP is installed

[/opt/OpenbravoERP]:

----------------------------------------------------------------------------
Stack: Java home directory

Please specify the directory where the JDK is located

[/usr]: /usr/java/latest

----------------------------------------------------------------------------
Stack: Ant executable

Please specify the location where the Ant executable is located

[/usr/bin/ant]:

Stack: Tomcat directory

Please specify the directory where Tomcat is located.
In case of having Tomcat split into 2 directories, select the one containing the webapps directory

[]: /usr/share/apache-tomcat-5.5.26

Info: Please make sure Tomcat is stopped.
Press [Enter] to continue :
----------------------------------------------------------------------------
Database: PostgreSQL directory

Please specify the directory where the binaries of the PostgreSQL installation are located (psql, pg_restore, vacuumdb)

[/usr/bin]:

----------------------------------------------------------------------------
Setup is now ready to begin installing Openbravo ERP Upgrader on your computer.

Do you want to continue? [Y/n]: y

----------------------------------------------------------------------------
Please wait while Setup installs Openbravo ERP Upgrader on your computer.

Installing
0% ______________ 50% ______________ 100%
#########################################

----------------------------------------------------------------------------
Setup has finished installing Openbravo ERP Upgrader on your computer.

-Listo, ya tenemos la version stable 2.40 de Openbravo y segun el puerto donde lo hayamos configurado es que podremos accederlo, en mi caso es
http://192.168.1.196:8080/openbravo/security/Login_FS.html


Share/Bookmark

Email server con postfix, mailscanner, mailwatch, spamassassin, clamav en Centos 5.2

Esta vez instalaremos y configuraremos un servidor Centos 5.2 para que funcione como servidor de email con antispam/antivirus y una base de usuarios virtuales en una db mysql con las siguientes herramientas:

MTA postfix
PostfixAdmin
MailScanner 4.72.2
MailWatch 1.0.4
Antivirus clamav 0.94
spamassassin
MySQL 5.0

Esta configuración me funciona en varios servidores y asi la he configurado, en Linux una operación se puede hacer de varias formas, así que si alguien tiene una mejor forma, favor decirme y aprendemos todos, jejeje. :-)

email server: 192.168.1.197

-Instalamos webmin

wget -c http://internap.dl.sourceforge.net/sourceforge/webadmin/webmin-1.430-1.noarch.rpm
rpm -vi webmin-1.430-1.noarch.rpm

-Instalamos herramientas para modificar y actualizar su zona horaria y fecha

yum install system-config-date mingetty ethtool

-Verificamos que el firewall este desabilitado por el momento

iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

-Desabilitamos SELinux.

vi /etc/selinux/config

-Modificamos la linea SELINUX
SELINUX=disabled

-Salvamos los cambios y salimos
-Instalamos software que nos hará falta mas tarde

yum install fetchmail wget bzip2 unzip zip nmap openssl lynx fileutils ncftp gcc gcc-c++ bind-utils

-Instalamos y configuramos MySQL
yum install mysql mysql-devel mysql-server
chkconfig --levels 235 mysqld on
service mysqld start

-Verificamos que el mysql este ejecutándose y esperando conexiones

netstat -tap | grep mysql
tcp 0 0 *:mysql *:* LISTEN 2091/mysqld

-En caso de que no este activo, editamos my.cnf y agregamos la siguiente linea en la sección [mysqld] y damos restart al servicio

vi /etc/my.cnf
#skip-networking

service mysqld restart

-Le colocamos password al usuario root de MySQL. OJO, usar una verdadera contraseña y su dominio internet real

mysqladmin -u root password 12345
mysqladmin -h m2.prueba.com -u root password 12345

-Mas software necesitado

yum install rpm-build pcre-devel

-Instalamos Cyrus para la encriptacion en la autenticacion

yum install cyrus-sasl-sql cyrus-sasl-devel

-Eliminamos un paquete de Cyrus que no necesitaremos

yum remove cyrus-sasl-gssapi

-Agregamos el repositorio dag para contar con paquetes que no están en los de centos. Desabilitado para que no se actualice algo que no queremos

vi /etc/yum.repos.d/dag.repo

[dag]
name=Dag RPM Repository for Red Hat Enterprise Linux
baseurl=http://apt.sw.be/redhat/el$releasever/en/$basearch/dag
gpgcheck=1
enabled=0
-Descargamos postfix con soporte para mysql. Podemos buscar la ultima version en http://rpm.pbone.net/ y descargar la versión dependiendo de nuestra version de centos

wget -c ftp://mirror.switch.ch/pool/3/mirror/centos/5.2/centosplus/i386/RPMS/postfix-2.3.3-2.el5.centos.mysql_pgsql.i386.rpm

-Instalamos postgresql debido a dependencia con el rpm de postfix

yum install postgresql
rpm -vi postfix-2.3.3-2.el5.centos.mysql_pgsql.i386.rpm

-Instalamos libtool por dependencia con courier

yum install libtool-ltdl-devel

-Creamos un usuario y grupo bajo el cual ejecutara Courier

groupadd vmail -g 1001
useradd vmail -u 1001 -g 1001

-Agregamos este usuario al file sudoers. Entre columnas damos un TAB

visudo
vmail ALL=(ALL) ALL

-Le colocamos password a la cuenta vmail

passwd vmail

-Cambiamos a esta cuenta para instalar unos paquetes desde ella. El password que nos pide es el de la cuenta vmail, al tratar de instalar con el sudo

su vmail
sudo yum install libtool postgresql-devel gdbm-devel pam-devel expect openldap-devel
sudo yum install gamin-devel openldap-servers

-Creamos un árbol de directorios para compilar algunos rpm que necesitaremos

mkdir $HOME/rpm
mkdir $HOME/rpm/SOURCES
mkdir $HOME/rpm/SPECS
mkdir $HOME/rpm/BUILD
mkdir $HOME/rpm/SRPMS
mkdir $HOME/rpm/RPMS
mkdir $HOME/rpm/RPMS/i386
echo "%_topdir $HOME/rpm" >> $HOME/.rpmmacros

-Creamos un directorio para las descargas

mkdir $HOME/downloads; cd $HOME/downloads

-Descargamos los paquetes de Courier

wget http://surfnet.dl.sourceforge.net/sourceforge/courier/courier-authlib-0.58.tar.bz2
wget http://surfnet.dl.sourceforge.net/sourceforge/courier/courier-imap-4.1.1.tar.bz2
wget http://surfnet.dl.sourceforge.net/sourceforge/courier/maildrop-2.0.2.tar.bz2

-Courier nos permite validar conexiones por postgresql, mysql, LDAP, etc antes que solo /etc/passwd. Pasamos a compilarlo

sudo rpmbuild -ta courier-authlib-0.58.tar.bz2

-Instalamos los siguientes rpm generados

cd $HOME/rpm/RPMS/i386/
sudo rpm --install courier-authlib-0.58-1.i386.rpm
sudo rpm --install courier-authlib-devel-0.58-1.i386.rpm
sudo rpm --install courier-authlib-mysql-0.58-1.i386.rpm

-Colocamos acceso total a los directorios bajo rpm para compilar courier-imap server

sudo chmod -R 777 $HOME/rpm/RPMS/
cd $HOME/downloads
rpmbuild -ta courier-imap-4.1.1.tar.bz2
cd $HOME/vmail/rpm/RPMS/i386/
sudo rpm --install courier-imap-4.1.1-1.4.i386.rpm

-Compilamos maildrop que nos permitirá filtrar mails entrantes y salientes a los directorios correctos

cd $HOME/downloads
sudo rpmbuild -ta maildrop-2.0.2.tar.bz2
cd $HOME/rpm/RPMS/i386
sudo rpm --install maildrop-2.0.2.i386.rpm

-Salimos de la cuenta vmail a root y verificamos que seamos root

exit
whoami
root

-Creamos el file para logs de maildrop

touch /var/log/maildroprc.log
chmod 777 /var/log/maildroprc.log

-Generamos los certificados usados por Postfix (para SMTPS y TLS), Courier (para IMAPS y POP3S) y Apache (para HTTPS)

mkdir /usr/local/ssl; cd /usr/local/ssl

-La llave sera sin password evitando que cuando iniciemos postfix, courier o apache pida el password

openssl genrsa -out mail.yourdomain.com.key 1024
Generating RSA private key, 1024 bit long modulus
.....................++++++
.......................++++++
e is 65537 (0x10001)

chmod 600 mail.yourdomain.com.key

-Generamos la solicitud de certificado

openssl req -new -key mail.yourdomain.com.key -out mail.yourdomain.com.csr
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) [GB]:CO
State or Province Name (full name) [Berkshire]:Cundinamarca
Locality Name (eg, city) [Newbury]:Bogota
Organization Name (eg, company) [My Company Ltd]:Cabrera ltda
Organizational Unit Name (eg, section) []:Soporte Sistemas
Common Name (eg, your name or your server's hostname) []:mail.yourdomain.com
Email Address []:postmaster@yourdomain.com


Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:password
An optional company name []:

-El fichero generado es el necesario para que nos creen un certificado real las Certificate Authority como Verisign o Thawte, en nuestro caso, lo firmaremos nosotros mismos

openssl genrsa -des3 -out ca.key 1024
Generating RSA private key, 1024 bit long modulus
........................................................++++++
...............++++++
e is 65537 (0x10001)
Enter pass phrase for ca.key:
Verifying - Enter pass phrase for ca.key:

-Restringimos sus permisos

chmod 600 ca.key

-Generamos un certificado auto firmado

openssl req -new -x509 -days 365 -key ca.key -out ca.crt
Enter pass phrase for ca.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) [GB]:CO
State or Province Name (full name) [Berkshire]:Cundinamarca
Locality Name (eg, city) [Newbury]:Bogota
Organization Name (eg, company) [My Company Ltd]:Cabrera ltda
Organizational Unit Name (eg, section) []:Sistemas Soporte
Common Name (eg, your name or your server's hostname) []:mail.yourdomain.com
Email Address []:postmaster@yourdomain.com

-Usamos este CA certificado para firmar nuestro certificado

openssl x509 -req -days 365 -CA ca.crt -CAkey ca.key -set_serial 01 -in mail.yourdomain.com.csr -out mail.yourdomain.com.crt

Signature ok
subject=/C=CO/ST=Bogota/L=Cundinamarca/O=Cabrera ltda/OU=Sistemas Soporte/CN=mail.yourdomain.com/emailAddress=postmaster@yourdomain.com
Getting CA Private Key
Enter pass phrase for ca.key:

-Combinamos el server key y el certificado en un unico fichero. Postfix y Apache pueden manejar 2 ficheros pero Courier necesita solo uno. Asi que crearemos un fichero unico para todo. Crearemos el pem en el formato esperado por Courier (key y cert en un unico fichero)

cat mail.yourdomain.com.key mail.yourdomain.com.crt > mail.yourdomain.com.pem
chmod 600 mail.yourdomain.com.pem

-Si todo va bien, debe tener algo parecido

ls -la
total 32
drwxr-xr-x 2 root root 4096 sep 8 17:38 .
drwxr-xr-x 12 root root 4096 sep 8 17:00 ..
-rw-r--r-- 1 root root 1375 sep 8 17:24 ca.crt
-rw------- 1 root root 951 sep 8 17:20 ca.key
-rw-r--r-- 1 root root 993 sep 8 17:30 mail.yourdomain.com.crt
-rw-r--r-- 1 root root 761 sep 8 17:09 mail.yourdomain.com.csr
-rw------- 1 root root 887 sep 8 17:02 mail.yourdomain.com.key
-rw------- 1 root root 1880 sep 8 17:38 mail.yourdomain.com.pem

-Instalamos y configuramos postfixadmin

cd /var/www/html
yum install subversion
svn co https://postfixadmin.svn.sourceforge.net/svnroot/postfixadmin/trunk postfixadmin
cd postfixadmin
chmod 640 *.php
cd admin
chmod 640 *.php
cd ../images/
chmod 640 *.png
cd ../languages/
chmod 640 *.lang
cd ../templates/
chmod 640 *.php
cd ../users/
chmod 640 *.php

-Creamos la db en el server MySQL segun el INSTALL.TXT

mysql -u root -p
CREATE DATABASE postfix;
CREATE USER 'postfix'@'localhost' IDENTIFIED BY 'choose_a_password';
GRANT ALL PRIVILEGES ON `postfix` . * TO 'postfix'@'localhost';
exit

-Configuramos postfixadmin
cd /var/www/html/postfixadmin
yum install php-cli php-ldap php-mysql php-gd php php-pear php-pdo php-common php-devel php5-mbstring php5-imap php-mbstring.i386
yum install php-imap php-odbc php-xml php-xmlrpc curl curl-devel perl-libwww-perl ImageMagick libxml2 libxml2-devel
vi config.inc.php

if (ereg ("config.inc.php", $_SERVER['PHP_SELF']))
{
header ("Location: login.php");
exit;
}
$CONF['configured'] = true;
$CONF['postfix_admin_url'] = 'http://192.168.1.197/postfixadmin';
$CONF['postfix_admin_path'] = dirname(__FILE__);
$CONF['default_language'] = 'en';
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = '192.168.1.198';
$CONF['database_user'] = 'postfix';
$CONF['database_password'] = 'poiuytha';
$CONF['database_name'] = 'postfix';
$CONF['database_prefix'] = '';
$CONF['database_prefix'] = '';
$CONF['database_tables'] = array (
'admin' => 'admin',
'alias' => 'alias',
'alias_domain' => 'alias_domain',
'config' => 'config',
'domain' => 'domain',
'domain_admins' => 'domain_admins',
'fetchmail' => 'fetchmail',
'log' => 'log',
'mailbox' => 'mailbox',
'vacation' => 'vacation',
'vacation_notification' => 'vacation_notification',
);
$CONF['admin_email'] = 'postmaster@yourdomain.com';
$CONF['smtp_server'] = 'localhost';
$CONF['smtp_port'] = '25';
$CONF['encrypt'] = 'md5crypt';
$CONF['min_password_length'] = 8;
$CONF['generate_password'] = 'YES';
$CONF['show_password'] = 'YES';
$CONF['page_size'] = '200';
$CONF['default_aliases'] = array (
'abuse' => 'abuse@yourdomain.com',
'hostmaster' => 'hostmaster@yourdomain.com',
'postmaster' => 'postmaster@yourdomain.com',
'webmaster' => 'webmaster@yourdomain.com'
);
$CONF['domain_path'] = 'NO';
$CONF['domain_in_mailbox'] = 'YES';
$CONF['aliases'] = '10';
$CONF['mailboxes'] = '10';
$CONF['maxquota'] = '100';
$CONF['quota'] = 'YES';
$CONF['quota_multiplier'] = '1024000';
$CONF['transport'] = 'NO';
$CONF['transport_options'] = array (
'virtual', // for virtual accounts
'local', // for system accounts
'relay' // for backup mx
);
$CONF['transport_default'] = 'virtual';
$CONF['vacation'] = 'YES';
$CONF['vacation_domain'] = 'autoreply.yourdomain.com';
$CONF['vacation_control'] ='YES';
$CONF['vacation_control_admin'] = 'YES';
$CONF['alias_control'] = 'YES';
$CONF['alias_control_admin'] = 'NO';
$CONF['special_alias_control'] = 'NO';
$CONF['alias_goto_limit'] = '0';
$CONF['alias_domain'] = 'YES';
$CONF['backup'] = 'YES';
$CONF['sendmail'] = 'YES';
$CONF['logging'] = 'YES';
$CONF['fetchmail'] = 'YES';
$CONF['fetchmail_extra_options'] = 'NO';
$CONF['show_header_text'] = 'NO';
$CONF['header_text'] = ':: Postfix Admin ::';
$CONF['user_footer_link'] = "http://www.yourdomain.com/";
$CONF['show_footer_text'] = 'YES';
$CONF['footer_text'] = 'Return to www.yourdomain.com';
$CONF['footer_link'] = 'http://www.yourdomain.com/';
$CONF['welcome_text'] = <<
Hi,

Welcome to your new account.
EOM;
$CONF['emailcheck_resolve_domain']='YES';
$CONF['show_status']='YES';
$CONF['show_status_key']='YES';
$CONF['show_status_text']=' ';
$CONF['show_undeliverable']='NO';
$CONF['show_undeliverable_color']='tomato';
$CONF['show_undeliverable_exceptions']=array("unixmail.domain.ext","exchangeserver.domain.ext","gmail.com");
$CONF['show_popimap']='YES';
$CONF['show_popimap_color']='darkgrey';
$CONF['show_custom_count']=2;
$CONF['show_custom_domains']=array("subdomain.domain.ext","domain2.ext");
$CONF['show_custom_colors']=array("lightgreen","lightblue");
$CONF['mailbox_postcreation_script']='sudo /usr/local/bin/postfixadmin-mailbox-postcreation.sh';
$CONF['mailbox_postdeletion_script']='sudo /usr/local/bin/postfixadmin-mailbox-postdeletion.sh';
$CONF['domain_postdeletion_script']='sudo /usr/local/bin/postfixadmin-domain-postdeletion.sh';
$CONF['create_mailbox_subdirs_prefix']='INBOX.';
$CONF['theme_logo'] = 'images/logo-default.png';
$CONF['theme_css'] = 'css/default.css';
if (file_exists(dirname(__FILE__) . '/config.local.php')) { # for /
include(dirname(__FILE__) . '/config.local.php');
}

-Habilitamos permisos para apache

chown -R apache.apache /var/www/html/postfixadmin

mv setup.php setup.php-disabled
cp /var/www/html/postfixadmin/ADDITIONS/postfixadmin* /usr/local/bin
cd /usr/local/bin
chown root.root
postfixadmin*
chmod 744 postfixadmin*

-Modificamos o agregamos las siguientes lineas en estos 3 scripts

vi postfixadmin-mailbox-postcreation.sh

basedir=/opt/mail
..
..
maildirmake "$maildir"
chown -R vmail:vmail $maildir

Salvamos y salimos

vi postfixadmin-mailbox-postdeletion.sh

basedir=/opt/mail
trashbase=/opt/deleted
..
..
maildir="${basedir}/${1}"
..
..
mv $maildir $trashdir
chown -R vmail:vmail $trashdir

Salvamos y salimos

vi postfixadmin-domain-postdeletion.sh

basedir=/opt/mail
trashbase=/opt/deleted

Salvamos y salimos

-Accedemos a la interfaz administrativa de postfixadmin. Pero aun no creamos dominios y cuentas:

http://192.168.1.197/postfixadmin/




-Configuramos SASL para SMTP-AUTH

vi /usr/lib/sasl2/smtpd.conf

# smtpd.conf
pwcheck_method: authdaemond
log_level: 3
mech_list: PLAIN LOGIN
authdaemond_path:/var/spool/authdaemon/socket

Salvamos y salimos

chown root.vmail /usr/lib/sasl2/smtpd.conf
chmod 640 /usr/lib/sasl2/smtpd.conf
chmod 755 /var/spool/authdaemon/

-Comenzamos a configurar postfix

cd /etc/postfix

-Modificamos master.cf

vi master.cf

#descomentamos smtps para tener smtp sobre SSL
smtps inet n - n - - smtpd
-o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes

#habilitamos otro puerto para el smtp para los casos cuando los ISP bloquean el puerto 25 SMTP
567 inet n - n - - smtpd

#Modificamos la linea del maildrop
maildrop unix - n n - - pipe
flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#agregamos al final el modulo de vacation
#
# VIRTUAL VACATION
#
vacation unix - n n - - pipe
flags=DRhu user=vacation argv=/var/spool/vacation/vacation.pl -f ${sender} -- ${recipient}

-Salvamos y salimos

-Agregamos el usuario para ejecutar el script de vacation. Por motivos de seguridad, no necesitamos que tenga shell asignado, nadie se logeara por esta cuenta

adduser -d /var/spool/vacation -s /sbin/nologin vacation

-Editamos /etc/passwd y le colocamos un * al campo password del usuario vacation, asi evitamos que alguien coloque un password a esta cuenta para despues usarla.

vi /etc/passwd
vacation:*:1002:1002::/var/spool/vacation:/sbin/nologin
-Copiamos el script y le cambiamos sus privilegios

cp /var/www/html/postfixadmin/VIRTUAL_VACATION/vacation.pl /var/spool/vacation/vacation.pl
chown vacation.vacation /var/spool/vacation/vacation.pl
chmod 700 /var/spool/vacation/vacation.pl

vi /var/spool/vacation/vacation.pl

my $db_type = 'mysql';
my $db_host = '192.168.1.198';
my $db_username = 'postfixadmin';
my $db_password = 'postfixadmin';
my $db_name = 'postfix';
my $vacation_domain = 'autoreply.example.org';
my $smtp_server = 'localhost';
my $syslog = 0;
my $logfile='/var/spool/vacation/vacation.log';
my $log_level = 2;
my $interval = 0;

vi /etc/postfix/transport
autoreply.yourdomain.com vacation

postmap /etc/postfix/transport

-Instalamos por dependencias con perl

yum install links ncftp

-Entramos a webmin para agregar unos modulos perl que necesitamos para vacation

https://192.168.1.197:10000/

-Vamos a Others - Perl. Modulos a instalar (ademas de los que se instalan por default en Centos):

CPAN::Bundle
DBD::mysql
Mail::Sendmail
Email::Valid
MIME::Charset
Log::Log4perl
Log::Dispatch
MIME::EncWords
GetOpt::Std
Net::Server
IO::Multiplex

-Modificamos main.cf

cd /etc/postfix
vi main.cf
myhostname = mail.yourdomain.com
mydomain = yourdomain.com
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost
local_recipient_maps = proxy:unix:passwd.byname $alias_maps
mynetworks = $config_directory/mynetworks
relay_domains = mysql:/etc/postfix/mysql_relay_domains_maps.cf
alias_database = hash:/etc/aliases

-Agregamos al final del fichero

#
# Virtual Mail Mysql settings
#
virtual_alias_maps = hash:/etc/aliases mysql:/etc/postfix/mysql_virtual_alias_maps.cf hash:/etc/aliases
virtual_uid_maps = static:1001
virtual_gid_maps = static:1001
virtual_mailbox_base = /opt/mail
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_mailbox_limit = 51200000
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_minimum_uid = 1001

# Who handles the mail delivery?
# POSTFIX = virtual
# MAILDROP = maildrop
#
#virtual_transport = virtual
virtual_transport = maildrop
maildrop_destination_recipient_limit = 1
# Transport map
transport_maps = hash:/etc/postfix/transport
vacation_destination_recipient_limit = 1
# Additional for quota support
virtual_create_maildirsize = yes
virtual_mailbox_extended = yes
virtual_mailbox_limit_maps = mysql:/etc/postfix/mysql_virtual_mailbox_limit_maps.cf
virtual_mailbox_limit_override = yes
virtual_maildir_limit_message = Sorry, the user's maildir has overdrawn his diskspace quota, please try again later.

###################################################################################
### ENABLE SASL SUPPORT ( SMTP-AUTH )
# smtpd_sasl_auth_enable = yes
# Enable SASL support in postfix
# smtpd_sasl_security_options = noanonymous
# Anonymous logins will not be permitted
# broken_sasl_auth_clients = yes
# Allow RFC-broken mail clients like Outlook Express4 to use SMTP AUTH
# smtpd_sasl_path = smptd
# Tells SASL to get the config from /usr/lib64/sasl2/smptd.conf
# smtpd_sasl_local_domain =
# If the user fails to nominate a domain, don't auto append one
# smtpd_sasl_authenticated_header = yes
# Include the authenticated username in the message headers.
# Having this on will make it easier if a spammer cracks one of your user's weak passwords,
# and starts using SMTP-AUTH to relay spam through your server
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_path = smptd
smtpd_sasl_local_domain =
smtpd_sasl_authenticated_header = yes
smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_non_fqdn_hostname,reject_non_fqdn_sender,reject_non_fqdn_recipient,reject_unauth_destination,reject_unauth_pipelining,reject_invalid_hostname,reject_rbl_client list.dsbl.org,reject_rbl_client bl.spamcop.net,reject_rbl_client sbl-xbl.spamhaus.org
###################################################################################
### ENABLE TLS SUPPORT ( "STARTTLS" ... enables SSL to be negotiated during a SMTP connection )
# smtp_use_tls = no
# dont enable TLS for outbound SMTP connections
# smtpd_use_tls = yes
# announce TLS availability for incoming SMTP connections
# smtpd_tls_auth_only = no :
# TLS is optional, not enforced
# smtpd_tls_key_file :
# specify the private key ( must not be encrypted - ie no password)
# smtpd_tls_cert_file :
# specify the certificate
# smtpd_tls_session_cache_database :
# nominate a server-side TLS session cache. Improves performance.
# smtpd_tls_loglevel = 1 :
# log basic TLS handshake and cert info
# smtpd_tls_received_header = yes
# record some protocol/cipher etc info in the Received header smtp_use_tls = no
smtp_use_tls = no
smtpd_use_tls = yes
smtpd_tls_auth_only = no
smtpd_tls_key_file = /usr/local/ssl/mail.yourdomain.com.key
smtpd_tls_cert_file = /usr/local/ssl/mail.yourdomain.com.crt
smtpd_tls_session_cache_database = btree:/etc/postfix/tls_smtpd_scache
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_client_restrictions = check_client_access hash:/etc/postfix/access
smtpd_client_connection_count_limit = 60

-Creamos los ficheros mysql-virtual

vi /etc/postfix/mysql_virtual_alias_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT goto FROM alias WHERE address='%s' AND active = 1

vi /etc/postfix/mysql_virtual_domains_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s'
#optional query to use when relaying for backup MX
#query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '0' and active = '1'

vi /etc/postfix/mysql_virtual_mailbox_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = 1

vi /etc/postfix/mysql_virtual_mailbox_limit_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT quota FROM mailbox WHERE username='%s'

vi /etc/postfix/mysql_relay_domains_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '1'

-Como estos files contienen datos de conexion a nuestra db, limitamos su acceso por seguridad

chown root.postfix /etc/postfix/mysql_*.cf
chmod 640 /etc/postfix/mysql_*.cf
ls -la /etc/postfix/mysql*
-rw-r----- 1 root postfix 140 sep 15 15:54 /etc/postfix/mysql_relay_domains_maps.cf
-rw-r----- 1 root postfix 134 sep 15 15:48 /etc/postfix/mysql_virtual_alias_maps.cf
-rw-r----- 1 root postfix 261 sep 15 15:51 /etc/postfix/mysql_virtual_domains_maps.cf
-rw-r----- 1 root postfix 123 sep 15 15:53 /etc/postfix/mysql_virtual_mailbox_limit_maps.cf
-rw-r----- 1 root postfix 140 sep 15 15:52 /etc/postfix/mysql_virtual_mailbox_maps.cf

-Colocamos las ip de los servers que haran relay a traves de nuestro server. Los usuarios que tengan cuenta en el server no necesitan tener su ip aqui, ya que ellos se logearan por SMTP-AUTH, por default colocamos localhost para darle permiso a los scripts locales en el server

echo '# Localhost' > /etc/postfix/mynetworks
echo '127.0.0.0/8' >>/etc/postfix/mynetworks
echo '' >>/etc/postfix/mynetworks

-Creacion del directorio de mail para los usuarios. Existen 2 formatos de guardar sus mails, Mbox que es un fichero donde se almacenan todos los mails, uno detras del otro y Maildir que almacena los mails cada uno en un directorio especial. Para este documento usaremos Maildir

mkdir /opt/mail
chown vmail:vmail /opt/mail
chmod 700 /opt/mail
mkdir /opt/deleted
chown vmail:vmail /opt/deleted/
chmod 700 /opt/deleted/

-Configuramos Courier-authlib para manejar Courier-IMAP y Courier-POP3

vi /etc/authlib/authdaemonrc
authmodulelist="authmysql"
authdaemonvar=/usr/var/spool/authdaemon
DEFAULTOPTIONS="wbnochangepass=1,wbusexsender=1,disableshared=1"

vi /etc/authlib/authmysqlrc
MYSQL_SERVER 192.168.1.198
MYSQL_USERNAME root
#password de la cuenta root de mysql
MYSQL_PASSWORD 12345
MYSQL_SOCKET /var/lib/mysql/mysql.sock
MYSQL_PORT 0
MYSQL_OPT 0
MYSQL_DATABASE postfix
MYSQL_USER_TABLE mailbox
MYSQL_CRYPT_PWFIELD password
MYSQL_CLEAR_PWFIELD password
MYSQL_UID_FIELD '1001'
MYSQL_GID_FIELD '1001'
MYSQL_LOGIN_FIELD username
MYSQL_HOME_FIELD '/opt/mail'
MYSQL_NAME_FIELD name
MYSQL_MAILDIR_FIELD CONCAT("/opt/mail/",maildir)
MYSQL_QUOTA_FIELD concat(quota,'S')

-Protegemos el fichero

chmod 400 /etc/authlib/authmysqlrc

-Comenzamos a configurar Maildrop con Maildir+softquota

vi /etc/quotawarnmsg
X-Comment: Rename/Copy this file to quotawarnmsg, and make appropriate changes
X-Comment: See deliverquota man page for more information
From: Mail Delivery System
Reply-To: postmaster@calcom.com.mx
To: Valued Customer:;
Subject: Mail quota warning
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 7bit
Your mailbox on the server is now more than 90% full. So that you can continue to receive mail you need to remove some messages from your mailbox.

vi /etc/postfix/master.cf
maildrop unix - n n - - pipe
flags=DRhu user=vmail argv=/usr/bin/maildrop -w 90 -d ${recipient}
#-w N dara un alerta por mail al usuario cuando su quota de disco este al N porciento lleno
#repitiendose esta alerta todos los dias hasta que libere espacio. El mensaje se toma de
#/etc/quotawarnmsg con los campos "Date:" y "Message-Id:" actualizados

-Salvamos y salimos. Reiniciamos el servicio postfix

chkconfig sendmail off
service sendmail stop
chkconfig postfix on
service postfix restart

vi /etc/maildroprc
logfile "/var/log/maildroprc.log"

-Configuramos Courier-IMAP Courier-POP3

vi /usr/lib/courier-imap/etc/imapd
MAXPERIP=20
IMAP_CAPABILITY="IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA AUTH=CRAM-MD5 AUTH=CRAM-SHA1 AUTH=PLAIN AUTH=LOGIN IDLE"
IMAP_ACL=0
IMAP_CAPABILITY_TLS="$IMAP_CAPABILITY"
IMAP_ENHANCEDIDLE=1
IMAPDSTART=YES

vi /usr/lib/courier-imap/etc/imapd-ssl
IMAPDSSLSTART=YES
IMAPDSTARTTLS=YES
#certificado creado anteriormente
TLS_CERTFILE=/usr/local/ssl/mail.yourdomain.com.pem

vi /usr/lib/courier-imap/etc/pop3d
MAXDAEMONS=40
POP3AUTH="CRAM-MD5 CRAM-SHA1 PLAIN LOGIN"
POP3AUTH_TLS="$POP3AUTH"
POP3DSTART=YES

vi /usr/lib/courier-imap/etc/pop3d-ssl
POP3DSSLSTART=YES
POP3_STARTTLS=YES
TLS_CERTFILE=/usr/local/ssl/mail.yourdomain.com.pem

-Ejecutamos y verificamos que los daemons necesarios estan ok

service mysqld start
service saslauthd start
service saslauthd start
service courier-authlib start
service courier-imap start
service postfix restart

-Modificaciones a postfixadmin
Normalmente para crear los maildir para las cuentas de email necesitaremos algunos comandos, aunque modificarmos el postfixadmin para que haga el trabajo sucio por nosotros.
Este es un ejemplo de como hacerlo manualmente

Creacion del home maildir de una cuenta email:
maildirmake /opt/mail/user1@yourdomain.com

Le creamos una quota de disco, si no esta presente, no hay restriccion de espacio, en este caso son 10MB y fijese en la S que colocamos al final del numero:
maildirmake -q 10971520S /opt/mail/user1@yourdomain.com

Protegemos el directorio
chmod g-r,o-r /opt/mail/user1\@yourdomain.com/
chown -R vmail.vmail /opt/mail/user1\@yourdomain.com/

-Damos permiso a los scripts para crear usuarios y dominios y borrarlos desde postfixadmin

visudo
#comentamos requiretty
#Defaults requiretty
..
..
vmail ALL=(ALL) ALL
apache mail.yourdomain.com=NOPASSWD: /usr/local/bin/postfixadmin-mailbox-postcreation.sh
apache mail.yourdomain.com=NOPASSWD: /usr/local/bin/postfixadmin-mailbox-postdeletion.sh
apache mail.yourdomain.com=NOPASSWD: /usr/local/bin/postfixadmin-domain-postdeletion.sh

service postfix restart

-Manejo de la cola de emails en postfix por linea de comandos

postqueue -p

-Poner un mensaje en HOLD. MESSAGEID es un identificador unico dado por postfix al colocar el mail en cola, para marcar todos los mails escribimos ALL

postsuper -h MESSAGEID

-Eliminar un mail de la cola

postsuper -d MESSAGEID

-Eliminar todos los mails en la cola

postsuper -d ALL

-Verificamos permisos de los files del postfix

postfix check

-Verificamos otros errores

egrep '(reject|warning|error|fatal|panic):' /var/log/maillog

-Verificamos los valores de Courier-authlib. Mostramos las cuentas creadas

vi /etc/authlib/authdaemonrc
DEBUG_LOGIN=2

-Reiniciamos el daemon

service courier-authlib restart

-Listamos las cuentas
/usr/sbin/authenumerate
user2@yourdomain.com 1001 1001 /opt/mail /opt/mail/user2@yourdomain.com/

-Verificamos por linea de comandos una cuenta

/usr/sbin/authtest someuser@yourdomain.com somepassword
Authentication succeeded.

Authenticated: someuser@yourdomain.com (uid 1001, gid 1001)
Home Directory: /opt/mail
Maildir: /opt/mail/someuser@yourdomain.com/
Quota: 10240000S
Encrypted Password: $1$9625a822$9wBt3mVsXm9oMbbO49HVX/
Cleartext Password: somepassword
Options: wbnochangepass=1,wbusexsender=1,disableshared=1

-Cuando estemos seguro de que Courier-authlib este funcionando ok, desabilitamos el modo debug o podemos llenar nuestro disco con mensajes de log

vi /etc/authlib/authdaemonrc
DEBUG_LOGIN=0

service courier-authlib restart

-Verificamos el servicio POP3

telnet localhost pop3
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
user user2@yourdomain.com
+OK Password required.
pass 12345
+OK logged in.
stat
+OK 0 0
quit
+OK Bye-bye.
Connection closed by foreign host.

-Verificamos IMAP

telnet localhost imap
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION STARTTLS] Courier-IMAP ready. Copyright 1998-2005 Double Precision, Inc. See COPYING for distribution information.
a login user2@yourdomain.com 12345
a OK LOGIN Ok.
a examine inbox
* FLAGS (\Draft \Answered \Flagged \Deleted \Seen \Recent)
* OK [PERMANENTFLAGS ()] No permanent flags permitted
* 0 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 1221862032] Ok
* OK [MYRIGHTS "cdilrsw"] ACL
a OK [READ-ONLY] Ok
a logout
* BYE Courier-IMAP server shutting down
a OK LOGOUT completed
Connection closed by foreign host.

-Verificamos Maildrop

maildrop -V9 -d user2@yourdomain.com
maildrop: authlib: groupid=1001
maildrop: authlib: userid=1001
maildrop: authlib: logname=user2@yourdomain.com, home=/opt/mail, mail=/opt/mail/user2@yourdomain.com/
maildrop: Changing to /opt/mail

Ya con postfix funcionando ok, pasaremos a instalar y configurar MailScanner. MailScanner es un software opensource que integra soporte antispam con spamassassin y antivirus con clamav entre otros antivirus.

-Antes de comenzar paramos el servicio postfix

service postfix stop
service saslauthd stop

mkdir /var/spool/postfix/usr
mkdir /var/spool/postfix/usr/var
mkdir /var/spool/postfix/var/
mkdir /var/spool/postfix/var/spool
mv /var/spool/authdaemon/ /var/spool/postfix/var/spool/authdaemon
ln -s /var/spool/postfix/var/spool/authdaemon/ /var/spool/authdaemon

-Reiniciamos postfix y saslauthd

service postfix start
service saslauthd start

-Cambiamos la configuracion del postfix para que trabaje en modo split MTA

vi /etc/postfix/main.cf

header_checks = regexp:/etc/postfix/header_checks

vi /etc/postfix/header_check

/^Received:/ HOLD

-Descargamos MailScanner

cd /home/vmail/downloads/
wget -c http://www.mailscanner.info/files/4/rpm/MailScanner-4.72.2-1.rpm.tar.gz
gunzip -d MailScanner-4.72.2-1.rpm.tar.gz
tar xvf MailScanner-4.72.2-1.rpm.tar
cd MailScanner-4.72.2-1

-Ejecutamos el script de install, OJO, colocamos un . punto antes del /
./install.sh

-Prestamos atencion que se instalen bien HTML-Parser y MIME-tools. Es normal que veamos algunos errores. Pero estos 2 modulos si deben quedar instalados. Ctrl-S para temporalmente la ejecucion para darnos tiempo a anotar algun error o modulo faltante para despues instalarlo y Ctrl-Q continua. Si algun modulo perl da error por falta de otro modulo, tomamos nota y lo instalamos despues al terminar el install.sh y volvemos a ejecutarlo.

-Modificamos los siguientes parametros en MailScanner.conf

cd /etc/MailScanner
vi MailScanner.conf

Run As User = postfix
Run As Group = postfix
Incoming Queue Dir = /var/spool/postfix/hold
Outgoing Queue Dir = /var/spool/postfix/incoming
MTA = postfix
SpamAssassin User State Dir = /var/spool/MailScanner/spamassassin

-Preparamos el directorio bayes
mkdir /etc/MailScanner/bayes
chmod g+rws /etc/MailScanner/bayes
chown root.apache /etc/MailScanner/bayes

-Descargamos e instalamos spamassassin y clamav (antispam-antivirus)

cd /home/vmail/downloads/

-Creamos una cuenta para clamav pero sin home y sin que se pueda logear
adduser -Ms /sbin/nologin clamav

wget -c http://www.mailscanner.info/files/4/install-Clam-SA-latest.tar.gz
gunzip -d install-Clam-SA-latest.tar.gz
tar xvf install-Clam-SA-latest.tar
cd install-Clam-0.94-SA-3.2.5/
./install.sh

-Respondemos y en:
Do you want me to install ClamAV for you [y or n, default is y] ? y

-Habilitamos algunos pluggins de spamassassin
vi /etc/mail/spamassassin/v320.pre

loadplugin Mail::SpamAssassin::Plugin::Check
loadplugin Mail::SpamAssassin::Plugin::HTTPSMismatch
loadplugin Mail::SpamAssassin::Plugin::URIDetail
loadplugin Mail::SpamAssassin::Plugin::Shortcircuit
loadplugin Mail::SpamAssassin::Plugin::Bayes
loadplugin Mail::SpamAssassin::Plugin::BodyEval
loadplugin Mail::SpamAssassin::Plugin::DNSEval
loadplugin Mail::SpamAssassin::Plugin::HTMLEval
loadplugin Mail::SpamAssassin::Plugin::HeaderEval
loadplugin Mail::SpamAssassin::Plugin::MIMEEval
loadplugin Mail::SpamAssassin::Plugin::RelayEval
loadplugin Mail::SpamAssassin::Plugin::URIEval
loadplugin Mail::SpamAssassin::Plugin::WLBLEval
loadplugin Mail::SpamAssassin::Plugin::VBounce
loadplugin Mail::SpamAssassin::Plugin::ImageInfo
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL
loadplugin Mail::SpamAssassin::Plugin::Razor2

vi /etc/mail/spamassassin/v310.pre
loadplugin Mail::SpamAssassin::Plugin::DCC
loadplugin Mail::SpamAssassin::Plugin::Pyzor
loadplugin Mail::SpamAssassin::Plugin::Razor2
loadplugin Mail::SpamAssassin::Plugin::SpamCop
loadplugin Mail::SpamAssassin::Plugin::AWL
loadplugin Mail::SpamAssassin::Plugin::AutoLearnThreshold
loadplugin Mail::SpamAssassin::Plugin::TextCat
loadplugin Mail::SpamAssassin::Plugin::WhiteListSubject
loadplugin Mail::SpamAssassin::Plugin::DomainKeys
loadplugin Mail::SpamAssassin::Plugin::MIMEHeader
loadplugin Mail::SpamAssassin::Plugin::ReplaceTags
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL

vi /etc/mail/spamassassin/init.pre
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL
loadplugin Mail::SpamAssassin::Plugin::Hashcash
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::Razor2

-Activamos el spamassassin y clamav en MailScanner.conf

vi /etc/MailScanner/MailScanner.conf
Use SpamAssassin = yes
Incoming Work User = clamav
Incoming Work Group = clamav
Clamd Socket = /tmp/clamd.socket
Incoming Work Permissions = 0660
Quarantine User = root
Quarantine Group = apache
Quarantine Permissions = 0660
Quarantine Whole Message = yes
Spam Actions = store
Always Looked Up Last = MailWatchLogging
Is Definitely Not Spam = SQLWhitelist
Is Definitely Spam = SQLBlacklist

vi /etc/MailScanner/spam.assassin.prefs.conf
bayes_path /etc/MailScanner/bayes/bayes
bayes_file_mode 0660

-Instalamos y configuramos razor, dcc y pyzor

cd /home/vmail/downloads/
wget -c http://internap.dl.sourceforge.net/sourceforge/razor/razor-agents-sdk-2.07.tar.bz2
wget -c http://internap.dl.sourceforge.net/sourceforge/razor/razor-agents-2.84.tar.bz2
bunzip2 razor-agents-sdk-2.07.tar.bz2
bunzip2 razor-agents-2.84.tar.bz2
tar xvf razor-agents-sdk-2.07.tar
tar xvf razor-agents-2.84.tar

-Verificamos tengamos los siguientes modulos perl instalados:

Time::HiRes
Digest::SHA1
MIME::Base64
Test::Simple
Test::Harness
Getopt::Long
Business::ISBN
GD::Barcode::EAN13
URI::Escape

-Compilamos e instalamos razor

cd razor-agents-sdk-2.07
perl Makefile.PL
make
make test
make install

cd ..
cd razor-agents-2.84
perl Makefile.PL
make
make test
make install

-Creamos el usuario razor para sus reportes, como postfix no puede logearse, primero lo creamos en root y despues lo pasamos al home de postfix

cd /root
razor-admin -create
razor-admin -register
cp -rf .razor/ /var/spool/postfix/
chown -R postfix.postfix /var/spool/postfix/.razor/

cd /home/vmail/downloads/
wget -c http://www.rhyolite.com/dcc/source/dcc.tar.Z
uncompress -d dcc.tar.Z
tar xvf dcc.tar
cd dcc-1.3.97/
./configure
make install

cd ..
wget -c http://internap.dl.sourceforge.net/sourceforge/pyzor/pyzor-0.4.0.tar.bz2
bunzip2 -d pyzor-0.4.0.tar.bz2
tar xvf pyzor-0.4.0.tar
cd pyzor-0.4.0
-Para instalar pyzor necesitamos el modulo gdbm de python, verificamos si lo tenemos instalado
python -c 'import gdbm' && echo 'gdbm found'
gdbm found

python setup.py build
python setup.py install
-Le cambiamos los permisos
chmod -R a+rX /usr/share/doc/pyzor /usr/lib/python2.4/site-packages/pyzor /usr/bin/pyzor /usr/bin/pyzord

pyzor discover
cp -rf .pyzor/ /var/spool/postfix/
chown -R postfix.postfix /var/spool/postfix/.pyzor/

chkconfig postfix off
service postfix stop
chkconfig MailScanner on
service MailScanner start

-Descargamos MailWatch

cd /home/vmail/downloads
wget -c http://internap.dl.sourceforge.net/sourceforge/mailwatch/mailwatch-1.0.4.tar.gz
tar xzvf mailwatch-1.0.4.tar.gz
cd mailwatch-1.0.4
mysql -p < create.sql

vi MailWatch.pm
my($db_user) = 'mailwatch';
my($db_pass) = '%sql_user_password%';
#Comentamos la linea 93
#$dbh->commit;

mv MailWatch.pm /usr/lib/MailScanner/MailScanner/CustomFunctions/

mv -rf mailscanner/ /var/www/html/
mkdir /var/www/html/mailscanner/temp/
chown -R apache:apache /var/www/html/mailscanner/
chmod ug+rwx /var/www/html/mailscanner/images/ /var/www/html/mailscanner/images/cache/
chmod ug+rw /var/www/html/mailscanner/temp/

vi /var/www/html/mailscanner/conf.php.example
define(DB_USER, 'mailwatch');
define(DB_PASS, '%sql_user_password%');
define(QUARANTINE_USE_FLAG, true);

mv /var/www/html/mailscanner/conf.php.example /var/www/html/mailscanner/conf.php
vi SQLBlackWhiteList.pm
my($db_user) = 'mailwatch';
my($db_pass) = '%sql_user_password%';

mv SQLBlackWhiteList.pm /usr/lib/MailScanner/MailScanner/CustomFunctions/

-Creamos el usuario admin para acceder a mailwatch

mysql mailscanner -u mailwatch -p
INSERT INTO users VALUES ('%web_user_username%',md5('%web_user_password%'),'%web_user_name%','A','0','0','0','0','0');
quit;

-Modificamos php.ini

vi /etc/php.ini
short_open_tag ="On"
safe_mode ="Off"
register_globals ="Off"
magic_quotes_gpc ="On"
magic_quotes_runtime ="Off"
auto_start ="0"
allow_url_fopen ="On"
upload_max_filesize ="15M"

-Verificamos haya quedado bien configurado spamassassin. Verificamos si falta algun modulo perl para instalarselo

spamassassin -D -p /etc/MailScanner/spam.assassin.prefs.conf --lint

-Modificamos GeoIP para corregir un bug

vi /var/www/html/mailscanner/geoip_update.php

//Cambiamos
dbquery("LOAD DATA INFILE '".$base.'/'.$file2."' INTO TABLE geoip_country FIELDS TERMINATED BY ',' ENCLOSED BY '\"'");

//por
dbquery("LOAD DATA LOCAL INFILE '".$base.'/'.$file2."' INTO TABLE geoip_country FIELDS TERMINATED BY ',' ENCLOSED BY '\"'");

-Modificamos la cuarentena de MailScanner

vi /etc/cron.daily/clean.quarantine
$days_to_keep = 15;

-Modificamos la cuarentena de MailWatch

cd /home/vmail/downloads/mailwatch-1.0.4
vi tools/db_clean.php
#!/usr/bin/php -q

cp tools/quarantine_maint.php /usr/local/bin/
cp tools/db_clean.php /usr/local/bin/
chmod +x /usr/local/bin/quarantine_maint.php /usr/local/bin/db_clean.php

-En una sola linea ejecutamos lo siguiente
echo "/usr/local/bin/quarantine_maint.php --clean" > /etc/cron.daily/mailwatch_quarantine_maint.sh

echo "/usr/local/bin/db_clean.php" > /etc/cron.daily/mailwatch_db_clean.sh
chmod +x /etc/cron.daily/mailwatch*

-Cola de mensajes

cp mailq.php /usr/local/bin/
crontab -e
0-59 * * * * /usr/local/bin/mailq.php

-Liberar un mail de cuarentena y que no sea chequeado nuevamente con los filtros antispam y antivirus. Debemos agregar un registro a la db mailscanner en la tabla whitelist. Los valores serian:

to_address = default
to_domain = default
from_address = 127.0.0.1

-Modificamos algunos ficheros de MailScanner, OJO, los campos son separados por TAB dentro de estos ficheros

cd /etc/MailScanner/
-En una sola linea ejecutamos el siguiente comando
touch filename.rules filetype.rules filename.rules.allowall.conf filetype.rules.allowall.conf rules/content.scanning.rules

vi filename.rules
From: 127.0.0.1 /etc/MailScanner/filename.rules.allowall.conf
FromOrTo: default /etc/MailScanner/filename.rules.conf

vi filetype.rules
From: 127.0.0.1 /etc/MailScanner/filetype.rules.allowall.conf
FromOrTo: default /etc/MailScanner/filetype.rules.conf

vi filename.rules.allowall.conf
allow .* - -

vi filetype.rules.allowall.conf
allow .* - -

vi rules/content.scanning.rules
From: 127.0.0.1 no
FromOrTo: default yes

-Modificamos los permisos para el directorio de cuarentena
chmod g+rws /var/spool/MailScanner/quarantine/

-Instalamos unrar
cd /home/vmail/downloads/
wget -c http://dag.wieers.com/rpm/packages/unrar/unrar-3.7.4-1.el5.rf.i386.rpm
rpm -vi unrar-3.7.4-1.el5.rf.i386.rpm

-Entrada a MailWatch. Nos logeamos con el usuario administrativo que creamos, en el URL http://192.168.1.197/mailscanner

-Personalizamos MailWatch. Actualizamos las definiciones de spamassassin y GeoIP en Tools/Links y con eso nos queda listo nuestro server. En la medida que nuestro server maneje una buena cantidad de mails, mas de 1000, entre spam y ham (mails buenos) este mejorara su porcentaje de efectividad. Share/Bookmark