Raspberry PI - Thoughts

Hello all:

Today, I'm gonna let you know my thoughts about my last experience testing a Raspberry PI. If you don't know yet what it means, just take a look at either raspberrypi.org or wikipedia's article.

I bought it just the next day after I received the "Time To Order" notification by email (order confirmation dated on Jun-2012), however I didn't put my hands on it until few weeks ago. My first thought was: this is the coolest thing ever, it's just a 30$ computer able to be a:
  • Media Center
  • Network Storage
  • Web Server
  • Desktop
  • Game emulator
  • Email Server
  • DNS/DHCP Server
  • ...
You can find more things to do with it, following the links listed below:

So far, so well. I'd bought a cheap, cool, low power device which I can do and learn many things, so I put my hands on it and start to install my Raspbian (Debian distro).

After converting this small device in a desktop environment, ngix server and a nagios test environment, I've figured out that I needed to find something else to do with that, since I would like to find a proper task where my little motherboard would provide an useful service. 
The thing was, that although I already knew that it had limited features, I was thinking that even with a Ram of only 256Kb (just 188Kb available), 700Mhz CPU and an Ethernet port of 100Mb, I wouldn't have any problem... I was wrong.

Last week, I've been setting up a web server (wordpress under apache, mysql and php). By default, great news, everything was working as expected. However, after importing the old database and adding some content to the web, I noticed that my PI was almost burned (high use of ram, almost 100%, and the CPU as well).
I've tried to do my best to optimize Apache/mysql to consume less ram (without any joy), so after some attempts without the improvement that I was expecting, I gave up. 

From my point of view, as everybody must know, this little device has its own limitations so, even though we know that there are many things to do with it, we need to keep in mind that this is not a proper computer, so don't forget that the performance is gonna be an issue if you are trying to set up something useful, instead of having it as a small game for fiddling about with it.


As my friend "Joputaman" suggested, maybe its time to take advantage of this little device setting up something really fun, like a FireHero3, to become a fu**ing Guitar Hero StarRock ;)!!!!

Netstat CLI & GUI

According to Wikipedia, netstat is a command line tool that displays network connections (both incoming and outgoing), routing tables, and a number of network interface statistics. It is available on Unix and Windows, although there are some differences about its parameters.

It's a really helpful tool that help us to find out if there is an app or unallowed process trying to establish a connection without our authorization. For instance, is the correct way to figure out if you have a trojan/malware sending private data to internet.

All its parameters you can find just typing into a shell:
 - netstat /? --> Windows
  http://technet.microsoft.com/en-us/library/bb490947.aspx
 - man netstat --> Linux
  http://userpages.umbc.edu/~jack/ifsm498d/netstat.html

As you can see on linux, there are more parameters so it's still more powerful... but don't give up, I'll share some options that you can use into your Windows system:

Netstat by itself only can show us the information ones, so typing:
netstat -o number (number of seconds that you want to refresh the information) we get the current information each number of seconds.

As you already know, on Windows, grep tool doesn't exist, however to filter the great amount of data that some commands offer us you can use the find command:
netstat -ano | find /i "ESTABLISHED" showing only the established connections (for example)



Furthermore, if you don't feel confortable using the command line or you need even more information, you can use TCPView instead. TCPView is a free tool from Windows Sysinternals Suite (quite good tools for windows sysadmins), that show us useful information about which process is transmitting data, wich local port, whois information and so on. Also allow us to finish every process from its own interface and show you current connections (inbound/outbound) using different colors...


I hope that information might be useful.

Regards.

Using CRON to Schedule Tasks

Scheduling task on Linux is very important topic to talk about. Cron and its associated commands are designed to regularly execute tasks/jobs. Cron daemon, checks every minute for any tasks that need to be run, checking its files.
Any user (also root) can edit that file to configure any task, typing:
$ crontab -e

note: root can configure cron tasks for any user, typing:
# crontab -e user

A cron entry is normally made up of six fields, for instance:
30 1 * * * /root/myscript.sh
This cron entry runs myscript everyday at 1:30 am.

All fields and their possible values are followings:

# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,$
# | | | | |
# * * * * * user-name command to be executed


Alternative options consist of only two fields (date option + command):
@reboot
@midnight
@daily
@weekly
@monthly
@annually
@yearly

For instance: if @weekly = 0 0 * * 0 . Script below will be executed every week on Sunday's midnight:
@weekly /root/script_backup.sh

We can let get a little more complex, running followings cron jobs:

25 5-17 * * * /root/script -> that script will be executed at 25 minutes past the hour, every hour from 5am to 5pm

15 9,12,15 * * * /root/script -> that script will be executed at 15 minutes past the hour, only at 9am, 12am and 3pm.

Finally, I'm going to show you some tricks using /:

/20 14,16 * * * /root/script -> That entry run the script every 20 minutes during the hours of 14 and 16 (starting at the top of the hour each time). It's say, that occurs at 20 minutes after the hour but only once an hour.

0 1/2 * * * /root/script -> That script will start at 1am and specifies every other hour: 1am, 3am, 5am, 7am and so on.

Regards.

¿Cómo resolverías... "How would you solve...?"

Tenemos el siguiente esquema:

El Pc0 está conectado a la red 192.168.1.0/24 con ip 192.168.1.10 y gw 192.168.1.254, que le permite salir a internet.
Al mismo tiempo tenemos otro router (R2) conectado al switch, en otro rango de red: 172.16.0.0/16, al cual no podemos llegar ya que no está en nuestro rango.
¿Cómo podíamos conectarnos a la LAN 172.16.0.0/16 si el Pc0 solo dispone de una NIC y no queremos perder la conexión con la red?
nota: no podemos cambiar nada de la infraestructura del esquema (cables, nuevos dispositivos...)


Pc0 is conected to 192.168.1.0/24 with ip address 192.168.1.10 and gw 192.168.1.254, alowing to connect with inet.
At the same time, we have an other router (R2) connected to switch, in a different range: 172.16.0.0/16, which we can't get connection with (different networks).
How do we connect to LAN 172.16.0.0/16 if the Pc0 just has a NIC and we can´t lose our inet connection?
note: we can't change anything of the schema (wires, new devices..)


Solucion: Unicamente tenemos que añadir una segunda ip a nuestra NIC, dentro de la red 172.16.0.0/16. Es muy importante tener en cuenta que un host puede pertenecer a tantas redes como queramos, siempre y cuando esté configurado dentro de ellas. El gateway solo nos sirve para indicar (por ejemplo en este esquema) la salida a internet.
Siempre debemos tener claro que un switch funciona en capa 2 y que puede existir comunicación entre dispositivos sin necesidad de salir por ninguna puerta de enlace.

Servidor Plesk con CentOS 5.6, SpamAssassin, Qmail-scanner y Clamav

La siguiente guía tiene el propósito de explicar paso por paso la instalación de un servidor Plesk bajo CentOS 5.6 configurando spamassassin, qmail-scanner y clamav como principales herramientas para tener un servidor http/mail seguro y funcionando 100%.
Se asume que el lector tiene unos conocimientos básicos sobre linux y se siente cómodo con la CLI.

Lo primero de todo es descargarnos la distro desde centos.org y grabarla en un cd o en mi caso en un usb como explico aquí: http://www.aprendiendounpoquitomas.com/2011/07/installing-centos-6-from-usb.html

Arrancamos e instalamos CentOS 5.6 sin entorno gráfico y con los menos paquetes posibles para evitar incompatibilidades. Una vez terminado este proceso, pasamos a arrancar nuestro nuevo sistema y conectarlo a la red.

Lo primero de todo es comprobar que no tenemos ninguno de estos paquetes instalados; Si los tenemos pasamos a eliminarlos con:
# yum remove http*
# yum remove php*
# yum remove cyrus*
# yum remove mysql*

Una vez eliminados, paso a actualizar el SO con:
# yum update
Queda de más decir que debe estar instalado gcc, make y otros imprescindibles como nano o vim...

- Instalación de PLESK 9.5.4

Ahora es momento de descargarnos el paquete plesk desde su webpage, en mi caso la versión de 64bits. Antes de poderlo descargar os teneis que registrar.
# mkdir /root/plesk
# cd plesk
# wget download1.parallels.com/Plesk/PPP9/CentOS5/parallels_installer_v3.6.0_build100407.15_os_CentOS_5_x86_64

Una vez descargado, le damos permisos de ejecución y lo instalamos:
# chmod +x paralles_installer_v3.6.0........
# ./parallels_installer_v3.6.0.......

En este paquete vienen incluidas distintas versiones, en mi caso instalaremos la versión 9.5.4 (opción 9) y elegiremos las opciones siguientes:

Como podeis ver en la imagen, he instalado:
- Plesk Migration Manager
- Php 5.3
- Qmail
- Additional Languages Pack (Español)
- Plesk Webmails support (Horde o Atmail)
- Additional Mail Services (No instaleis ni el spamassassin ni el antivirus, ya que lo haremos más adelante)

Podeis instalar todo lo que os interese, pero tened en cuenta que el acceso a esas aplicaciones será limitado por la licencia.

Continuar con la instalación y verificar que no os ha dado ningún error grave.
Una vez terminado, el acceso prederminado al CPANEL es:
https://ip_servidor:8443
user: admin
pass: setup

- Instalación de Qmail-Scanner, ClamAV y SpamAssassin

Antes de nada, es necesario añadir el repositorio atomic:
# wget -q -O - http://www.atomicorp.com/installers/atomic.sh | sh

Procedemos a instalar los paquetes necesarios:
# yum install qmail-scanner clamd qgreylist spamassassin dcc pyzor razor-agents

Iniciamos los servicios:
# /etc/init.d/spamassassin restart
# chkconfig spamassassin on
# /etc/init.d/clamd start
# chkconfig clamd on

Creamos el fichero log, necesario para las actualizaciones de clamav y hacemos propietario a qscand, usuario/grupo predefinido de qmail-scanner:
# touch /var/log/clamav/freshclam.log
# chown qscand:qscand /var/log/clamav/freshclam.log

Añadimos a crontab la actualización de clamav para que siempre contemos con las últimas firmas de virus:
# crontab -e
30 0 * * * /usr/bin/freshclam –quiet -l /var/log/clamav/freshclam.log
La linea anterior actualizará el antivirus todos los días a las 0:30 am.
Seguimos con la instalación, ahora reconfigurando qmail-scanner:
# qmail-scanner-reconfigure

Podemos ver y editar la configuración en /etc/qmail-scanner.ini. Es importante no olvidarse de reconfigurar qmail-scanner cada vez que editemos su configuración.

Podemos probar si ha ido bien la instalación de clamav, actualizando su base de datos de virus:
# freshclam -v

Si os da algún problema, verificar que en el archivo /etc/freshclam.conf el propietario de la db es qscand:
# By default when started freshclam drops privileges and switches to the
# "clamav" user. This directive allows you to change the database owner.
# Default: clamav (may depend on installation options)
DatabaseOwner qscand

En mi caso, me gusta tener todos los logs en /var/log así no tengo que gastar tiempo en buscar donde tiene el log la aplicación x, podemos crear links simbólicos a los log de qmail y qmail-scanner con:
# ln -s /usr/local/psa/var/log/maillog /var/log/qmail
# ln -s /var/spool/qscan/qmail-queue.log /var/log/qmail-scanner

Bien, ya está todo instalado y funcionando, ahora voy a explicar brevemente que archivos de configuración son necesarios conocer para poder configurar estas herramientas:
Encontrareis más info en las webs de los diferentes proyectos
- Qmail-Scanner
/etc/qmail-scanner.ini -> Es el archivo de configuración principal. En él entre otras opciones puedes decirle qué puntuación utilizar a parte del required_score de spamassassin para que ponga en quarentena o elimine los correos marcados como spam.

/var/qmail/bin/qmail-scanner-queue.pl -V
Puedes ver que configuración se está usando, tambien editarla pero parcialmente. En mi caso, la salida de ese comando es la siguiente:
qmail-scanner-queue.pl
Version: 2.08st (20100626)
Perl: Summary of my perl5 (revision 5 version 8 subversion 8) configuration:
Settings per domain: enabled
Scanners installed: clamdscan_scanner, spamassassin, perlscan_scanner,
Scanners default: clamdscan_scanner, spamassassin, perlscan_scanner,
Scanner versioning: clamdscan: 0.97.3/13875. spamassassin: 3.2.5. perlscan: 2.08st.
Spamassassin settings:
Mode: fast_spamassassin
sa_timeout = 120 / sa_fault_tolerant = 1 / sa_maxsize = 256000
sa_subject_site = '****SPAM****'
sa_delta_site = 1
sa_quarantine_site = 2
sa_delete_site = 6.2 / sa_reject_site = 0
Operating System: Linux, 2.6.32-4-pve
Hardware: x86_64
http://qmail-scanner.sourceforge.net/

- Spamassassin
/etc/mail/spamassassin/local.cf-->configuración general del spamassassin. En él se define la puntuación requerida para que un email sea marcado como spam, por defecto 5. En este caso qmail-scanner es el encargado de reescribir el asunto del email, por lo tanto se obviará la linea correspondiente.
Una vez terminemos de editar el archivo de configuración, debemos ejecutar:
# spamassassin --lint
para comprobar que no hay ningún error
http://spamassassin.apache.org/

- Clamav
/etc/clamd.conf
/etc/freshclam.conf
Estos dos archivos son los correspondientes a la configuración del antivirus. En ellos podeis configurar desde el path a los log, hasta notificaciones via mail.
http://www.clamav.net/


Hasta aquí llega la explicación, espero que os sirva todo lo posible ya que no hay mucha información y menos en español.
Podeis opinar y escribir vuestras dudas comentando más abajo :)
Proximamente postearé el mismo tuto en inglés

Un buen artículo sobre la lucha contra el spam en plesk y qmail.

Muy bien explicado.
Os linkeo a la fuente:
http://blogofsysadmins.com/como-luchar-contra-el-spam-en-plesk-con-qmail