Linux snapshots – apt-btrfs-snapshot

Since a couple (half dozen) of years I have been using the beautiful KDE Desktop in the very well made and supported Kubuntu distribution. As technology progresses and the switch on desktop computers from fast spinning disks to solid state disks is being made, I sleep better at night with a SSD… and if even SSDs can eventually fail (as Linus Torvalds knows…), you should always backup or cloud your important data, so I was much more worried by a system messed up with some update/upgrade or my own incompetence than trough hard drive failure.

So it was time to try snapshots in Linux. As always in Unix land there’s more than one way to cook an egg. You can go with LVM + classical File System, ZFS or Btrfs (and surely many other options). I did a new Kubuntu installation with the installer defaults using Btrfs as the file system (wanted to test drive Btrfs anyway) and from here is very simple to implement snapshots.

First thing, make sure that you have the default Btrfs setup

# btrfs subvolume list /
ID 257 gen 97520 top level 5 path @
ID 258 gen 97520 top level 5 path @home

Install apt-btrfs-snapshot

# apt-get install apt-btrfs-snapshot

And check that snapshots are supported

# apt-btrfs-snapshot supported
Supported

Here actually I get an error the first time i ran it

# apt-btrfs-snapshot supported
Traceback (most recent call last):
File "/usr/bin/apt-btrfs-snapshot", line 92, in
apt_btrfs = AptBtrfsSnapshot()
File "/usr/lib/python3/dist-packages/apt_btrfs_snapshot.py", line 113, in __init__
self.fstab = Fstab(fstab)
File "/usr/lib/python3/dist-packages/apt_btrfs_snapshot.py", line 76, in __init__
entry = FstabEntry.from_line(line)
File "/usr/lib/python3/dist-packages/apt_btrfs_snapshot.py", line 49, in from_line
return FstabEntry(*args[0:6])
TypeError: __init__() missing 3 required positional arguments: 'mountpoint', 'fstype', and 'options'

this was caused by unsupported fuse syntax entries in /etc/fstab, just had to change
sshfs#user@host:/path/ /mountpoint fuse options 0 0
to
user@host:/path/ /mountpoint fuse.sshfs options 0 0

and it will work. From now on the system is pretty much autonomous, every time you apt-get upgrade a snapshot will be made for you. Take notice that each snapshot is relative to root only, this means that /home is excluded, we are taking snapshot of the system not user files and configs…

# apt-btrfs-snapshot list
Available snapshots:
@apt-snapshot-2014-12-17_10:27:24
@apt-snapshot-2014-12-18_10:33:50
@apt-snapshot-2014-12-18_19:57:02
@apt-snapshot-2014-12-19_17:17:13

or you can force a new snapshot

# apt-btrfs-snapshot snapshot

to rollback, just issue

# apt-btrfs-snapshot set-default @apt-snapshot-2014-12-18_19:57:02

and reboot, yeah… fuckin awesome!

Note, i noticed some problems in apt-btrfs-snapshot to delete and list some of own snashots. Probably because of updates in btrfs or apt-btrfs-snapshot itself (pretty common after a distribution upgrade). The delete command doesn’t works as expected and btrfs gives also error. The situation is like this:

You see the snapshot in the list:

#btrfs subvolume list /
ID 257 gen 361392 top level 5 path @
ID 258 gen 361392 top level 5 path @home
ID 505 gen 361392 top level 5 path @apt-snapshot-2015-11-12_13:01:23

But when you go to delete it, btrfs spits an awful ERROR: error accessing…

btrfs subvolume delete @apt-snapshot-2015-11-12_13:01:23
Transaction commit: none (default)
ERROR: error accessing '@apt-snapshot-2015-11-12_13:01:23'

But the solution it quite simple, just mount all the btrfs device and delete it by path:

#mount /dev/sda1 /mnt/
# ls /mnt/
drwxr-xr-x 1 root root 78 Nov 12 13:01 ./
drwxr-xr-x 1 root root 244 Ago 4 12:30 ../
drwxr-xr-x 1 root root 244 Ago 4 12:30 @/
drwxr-xr-x 1 root root 244 Ago 4 12:30 @apt-snapshot-2015-11-12_13:01:23/
drwxr-xr-x 1 root root 40 Fev 7 2015 @home/
# btrfs subvol delete /mnt/@apt-snapshot-2015-11-12_13\:01\:23/
Transaction commit: none (default)
Delete subvolume '/mnt/@apt-snapshot-2015-11-12_13:01:23'
# cd /
# umount /mnt

even so, sometimes when you try to manual delete like above you get an

ERROR: cannot delete ‘/mnt/@apt-snapshot-2015-11-12_13:01:23’: Directory not empty

in this situation just dig a bit deeper

#cd /mnt/@apt-snapshot-2015-11-12_13:01:23
# rm -rf *
rm: cannot remove 'var/lib/machines': Operation not permitted
# subvol delete /mnt/@apt-snapshot-2015-11-12_13:01:23/var/lib/machines/
# subvol delete /mnt/@apt-snapshot-2015-11-12_13:01:23/
# cd /
# umount /mnt

You can thank me later

Estoril/Cascais personal tips, favorite places and insights

So Estoril/Cascais 🙂 it’s a perfect spot for a short break or a week vacations. Both as local and an AirBnb host I have been gathering some tips and insights that I’m glad to share with you. Welcome to my personal guide.

For a general institutional view of the area and presentation video take a look at http://estoril-portugal.com done by the good people of the government….

How to arrive

EN6 - Estrada MarginalFrom Lisbon by car,  ignore the A5 motorway and set your GPS to the scenic (and toll free) Estrada Marginal – EN6, take your time, drive slowly and enjoy the beautiful coastal landscape and the feeling of leaving behind the stress of the big city and switch to a much more relaxed mindset.

From Lisbon airport by public transportation, take the subway red line from Aeroporto station, and switch at Alameda station to the green line to Cais do Sodre (it’s the terminal station). You pay 1.90€ per person, 1.40€ for the ticket and 0.50€ for the rechargeable card, so keep the card.

Viva ViagemAlso don’t put more money at the card or else you can’t use afterwards on the train, the money you put in the subway can only be spent at the subway, the money you put in the train can only be used in the train and so on. Remember that is only possible to switch operator with a zero balance…. yeah… typical Portuguese bureaucracy

At Cais do Sodré exit the subway system and go to the upstairs to the train. Charge the card with a 1.80€ zapping (it’s just a marketing word for money) and catch a train to Cascais. All trains from Cais do Sodré go to Estoril/Cascais. Relax and enjoy your trip.

Taxi, personally I would avoid the usage of taxis in Lisbon/Cascais trip. Unfortunately many of the taxi drivers are simply dishonest and some are even rude…. but if you really have to, like arriving very late or travelling with heavy bags, expect around 40€ trip rip-off. A very good alternative is to use Uber instead.

Now that you are here!

Cascais BoardwalkBoth Estoril and Cascais are very safe areas that you can walk around with no worries at all, and my first invitation to you is to go by the sea and walk the waterfront boardwalk from Estoril to Cascais, it’s a leisure walk of 2750m all the way from S.João do Estoril to Cascais, nice views for photos and lots of bars to stop for a coffee on the way. Take your time to scout for the beaches, my favorites are Tamariz and Praia da Duquesa, both have nice yellow sand and calm clean water to swim. Take notice that at peak Summer the beaches can get a bit crowded. The boardwalk ends in the heart of Cascais, a picturesque former fishing village with an aristocratic touch. If your legs can keep up, stroll around in the many pedestrian only streets.

bicas_cascaisIf you want a break from the beach and are the kind of person that enjoy to ride a bicycle, Cascais has a special treat just for you… the town provides bicycles for free (free, no cost, gratis).

  • You must take an ID card.
  • You can pick up them up in 3 spots. At Cascais train station (in front of MacDonalds), at Av. República near the Eco Turism information spot, and at the roundabout before Casa da Guia on N247 heading to Guincho.
  • You can use them everyday (except 25 December and 1 January) from 08h00 to 19h00 on Summer (01 May to 30 September) and from 09h to 17h on Winter (1 October to 30 April). You can only pick up 1h30 half hour before the station closes.
  • You must return the bicycle at the end of the day (no overnight) and in the same pick up station

Take notice, there are some 20 bicicles in each station so at peak Summer they tend to disappear pretty fast (specially from the Cascais train station pick-up spot) so arrive there early.  Also the BICAs, as they are called, are a little heavy and single shifted (but well maintained), they are perfect for a leisure ride but not at all sporty bicycles. Also they don’t come with lockers, so if you plan to leave the bicycle (to enjoy Guincho beach for example) is best to bring your own locker, if you don’t have lockers and you stay with me I can provide for free a couple of lockers to guests.

Now time to enjoy the beautiful bikepath from Cascais to Guincho, around 9Km always by the ocean

guincho_beachAs you progress you will leave the civilization behind and enter at the Cascais-Sintra natural park, eventually you will arrive at the world renowned Guincho beach, one of the best places in the world for kitesurfing or surfing. For the more adventurers there is a surf shop that can rent all the material or provide a surf (or kitesurfing) lesson/experience.

I would recommend the surf lesson. For a first timer most of the kite lesson will be spent on the sand learning all the gear and wind dynamics, on the other hand in the surf lesson most of time is spent in the water with a huge learning board and there are real chances to do a stand-up and snap that cool picture…

Most of the year Guincho beach is pretty windy and kind of uncomfortable to sunbath and swim, but in the real hot days (35ºC and up) normally is the best beach to go.

Beware! The ocean can get a bit tricky at Guincho (particularly in Winter). If you are not a seasoned swimmer and the water is choppy with big waves please don’t take any unnecessary risks.

Looking North Boca do Infernofrom Guincho you can have a glimpse of Cabo da Roca, the western point of continental Europe, it’s also a hot spot to go. but would not advise with the BICAs bicycle, it’s doable… but you will face some sharp climbing with an inadequate bicycle.

So time to come back, please stop at Boca do Inferno (the Hell’s Mouth) viewpoint. There you can have some photos and there are many places for a coffee break or ice-cream.

Casino EstorilThis is a pretty obvious tip, but since you are here, please don’t skip a visit to Casino do Estoril. During World War II, it was reputed to be a gathering spot for espionage agents, dispossessed royals, and wartime adventurers. It was the inspiration for Ian Fleming’s 007 novel Casino Royale. Also, it’s the biggest casino of Europe and besides all the expected gambling, there is always entertainment with shows and live music (some events are free). And why not to try your luck (with just a bit of money)? Who knows you can get rich during the holidays 🙂

There are many places inside the Casino where you can eat, restaurants, buffets and lounges. Some years ago i went to a show with a dinner and it was good but it wasn’t good enough to go to my restaurants list (a bit down), but some say the Chinese food restaurant Mandarin is the best and most authentic in Portugal.

cabo_da_rocaAs referenced before i also invite you also to go to Cabo da Roca. This landmark is the westernmost extent of continental Europe, has a beautiful view of the ocean and Sintra mountains, and very picturesque old lighthouse. You can get there by bus, line 403, from Cascais station.

If you like palaces and gardens (who doesn’t?) is also a very good idea to visit Sintra village – lots of material for a full post – on the same day of Cabo da Roca.

Unfortunatetly at this writing time the bus company website is only in portuguese, but I can help you with timetables and ticket prices.

But in my opinion the perfect way to go from Estoril/Cascais to Cabo da Roca (and Sintra) in the Summer is to rent a scooter, and to enjoy the fresh mountain air and the winding, but calm road. You can easily rent one in Cascais around 30€/day. I also strongly suggest that you install in your smartphone, MEO Drive a very good and FREE GPS app (available for Android and iOS) with detailed off-line (no Internet connection needed) maps of Portugal.

Check out the bar tips bellow and mark on the GPS the amazing Bar Moinho D. Quixote, located 1km before Cabo da Roca.

peninha roadIf you like stunning views, go up to Peninha, in a clear day you can enjoy a breathtaking view, all the way North to Peniche and all the way South to Serra da Arrábida, more than 100kms panorama…. for me simply the best view in the region. You can get there from a dirt road on N247 on the way to Cabo da Roca after Malveira da Serra. Or on narrow but paved road turning left on N9-1 also after leaving Malveira da Serra (this paved road takes you deep inside a pristine forest before climbing up do Peninha).

These are my suggestions for the days off the beach in Cascais/Estoril area, but of course i would very strongly suggest also a day trip to Lisbon, but that deserves a full post on its own.

Where to eat in Estoril/Cascais?

These are my favorite places, based on quality/price, kind of food, location and service around the area. Keep in mind that I haven’t tried all the restaurants, so there should be also other nice options not listed here. Also the order of listing is of no importance of preference.

  • dom_pregoDom Prego
    This is a local favorite, it’s got a very good (and very very cheap) steak with chips. You must ask for “Prego no prato” and choose with or without the egg. For a complete Portuguese experience choose draft beer (the litlle 20cc cup – but always cold and bubbly) to go with the steak. All the other stuff that I tried here didn’t even come close to the steak, so again ask for “Prego no prato” and you can thank me later 🙂
    ps – on top you will get also the free sea view from most of the tables
  • esplanada-santa-martaEsplanada de Santa Marta
    This one is dedicated to all the fish lovers. Located after the Cascais marina on the way to Guincho, you will see just before the old roman bridge some inconspicuous stairs that lead to an esplanade. This place my best advice for you is to stick to the grilled fresh fish. The prices are very reasonable and it has a beautiful sea view and Santa Marta lighthouse, best at sunset.
  • a_tascaA Tasca
    Deep inside Cascais, you will find this gem of typical Portuguese food. It serves daily dishes with seasonal ingredients. So my best advice for you is to ask Lita (the owner) for the daily special. This place is simple, honest, cousy, kind of old style restaurant that everybody enjoys. The prices are a bit higher than the previous two suggestions, but still retains a great price/quality ratio. My personal tip, go there when you are really on empty stomach 🙂
  • CapricciosaCapricciosa
    For all the Italian food lovers, this place offers good pizza and pasta at reasonable prices. It has a very good sea view and a lovely open balcony ideal for Summer dinners. Sometimes, not so good service and sometimes a little bit overcrowded for my taste.

Bars and discos in Estoril/Cascais

  • O Moinho D QuixoteBar Moinho D. Quixote
    On the way to Cabo da Roca, just 150m after the turn off the main road to Cabo da Roca/Azoia sign. It’s difficult to spot so here are the GPS coordinates
    Lat: 38.770783389980174
    Lon: -9.47728380560875
    It’s a lovely spot in Summer with a stuning outside view over Guincho at the outside tables, and very cosy in the Winter with the fireplace that warms up the several typical wood decorated rooms.
  • Quiosque Jardim dos PassarinhosQuiosque do Jardim dos Passarinhos
    This is a local neighborhood coffee terrace kiosk, good for morning coffee and newspaper on the way to the beach. It’s located on Carlos Anjos garden, a small but charming public garden at the end of Avenida Saboia in Monte Estoril. There is a cage with exotic birds thus the name Jardim dos Passarinhos (The Birds Garden).
  • Attic CascaisAttic
    This bar is a classic in Cascais night scene, it’s open everyday until 4am. At the weekends sometimes it has DJs and live music playing. My personal tip, ask for the 10 bottles of beer in the ice bucket for 10 euros (yes… that’s 1 euro for each beer).
  • 2001 rock club2001 Rock Club
    For all the rock and heavy metal lovers, you should go to the 2001 Rock Club – nicknamed the Cathedral of Rock – this place is open since 1973, and thank God little or nothing has changed since then… it’s located under the Autódromo do Estoril stands 🙂 unfortunately the best way is to get there is by taxi. Expect pretty reasonable prices and loud rock until morning.
  • Bauhaus EstorilBauhaus
    This is a pretty normal discotheque that usually i wouldn’t put in these suggestions. But here comes the insider tip, every first Friday of each month this place trows a rock party (expect lot of 80’s and 90’s) that everybody loves. It’s always fully packed and alive. So, if you are staying nearby at one of these special Fridays you should go. It’s located in front of Monte Estoril train station, at the other side of the road. High prices in the drinks are to be expected.
  • jezebelTamariz/Jézebel
    The more fashionable clubs in Estoril/Cascais. They are siblings, as Tamariz club (located in Tamariz beach) is open during the Summer then it closes and the staff moves to Jézebel (in Casino do Estoril) during the Winter. Both are high life clubs with lots of pretty people to see and be seen. Commercial dance hits of the season and some 80s tunes are the common airplay music. Personally I enjoy more Tamariz with lots of outside space, but on weekends you can get some pretty amusing nights on both of them (thats why they are on this guide…). Be prepared to spend some money as they are quite expensive.

Warning, tourist trap! At Cascais center, just near the Cascais bay and town-hall you will find a square called Largo Camões, packed with restaurants, bars and coffee shops. Most of the places during daytime are restaurants, then in the night transform in a bad mix of bars/clubs playing loud music to outside doing the best to get people inside where half dozen of inebriated people drink and dance with the big TVs on sport channels as background…. consider yourself warned.

And that’s all folks, I hope you really have a wonderful time here, relax, enjoy the sun, the sand, the good wine, the good food and the people.

And if you have any tips please use the comments box bellow.

36

36Another year in the bag!

Following the path and rules set on the previous year, not a vintage year at all but overall better than the previous. Looking back a couple of years, it’s unbelievable how fast and how bad things can go bad in life, and when you find yourself in a hole so deep that you can’t even see any light out, it’s tough and slow to get out of it, i guess it’s a process and it takes the time it needs to take.

Some of the highlights this year:

  • Fantastic Thailand trip, fantastic country, fantastic culture, fantastic food, fantastic motorbike rides, fantastic landscapes.
  • Renting out a room in AirBnb has (is) been (being) a very personal enrichment experience.
  • Achieving some financial balance.
  • Overall physical recovery, even the hair is growing stronger again 🙂

In this awakening many things i have learned, most about myself, some about karma and a few about other persons. And the more i learn, the more i realize that there is yet so much space to improve in so many levels…

Goals to this year (and so many things to do…)

  • finish the clean up process (mainly confined to a bad company and partnership)
  • take good care of the body and take even better care of the mind
  • achieve my financial goal
  • focus on the task and divert on the tasks
  • work in the king and warrior archetypes
  • and of course, don’t be late, don’t be late, don’t be late

Hope positively that all pieces of the life puzzle will fit in.

“Nature loves courage. You make the commitment and nature will respond to that commitment by removing impossible obstacles. Dream the impossible dream and the world will not grind you under, it will lift you up. This is the trick. This is what all these teachers and philosophers who really counted, who really touched the alchemical gold, this is what they understood. This is the shamanic dance in the waterfall. This is how magic is done. By hurling yourself into the abyss and discovering its a feather bed.” – Terence McKenna

My Qmail installation guide reloaded

Qmail ReloadedA couple of years ago I posted my Qmail installation guide, and has expected it served me good when was time to reform to the old mail server. But, i made some changes on this iteration and i think is more polished and shiny than ever.

Again, this is to my own reference, but i will be very glad if it also can help someone. On the other hand, if you follow it, and nukes your system or kills every life form on Earth please don’t blame me. You are warned.

The old picture:

mail-system


2 Qmail instances, 1 published MX record that accepts emails from other MTAs, does the RBL checks and forwards the passed emails to the main Qmail instance via artificial smtproutes. The forwarded emails are then checked against virus (by Clamav) and spam (by SpamAssassin) trough qmail-scanner qmail-queue drop in replacement.

Users receive and send email trough the non published MX Qmail instance. They need to smtp-auth to relay email (send email to remote domains). Delivery to local domains doesn’t require smtp-auth.

Identified problems:

1 – One problem is that the main Qmail instance (that has no published MX records), that works with Vpopmail and holds all the accounts information, maildirs and email is somehow vulnerable:

The main weakness of this installation, is that if a clever spammer discovers that mail.domain.com accepts incoming emails for local domains, he can spam down your users bypassing the rbl tests.

also, one has to rememeber that has SPF and A records published, and it’s IP is printed on all outgoing email headers, so it’s not anonymous.

2 – The user debug is somewhat tricky, if there is a smtp-auth client configuration problem. The problem is that the user will be able to send emails to local domains, but will get the dreadful 553 sorry that domain isn’t in my list of allowed rcpthosts (#5.7.1) error.

3 – Qmail-scanner, is a very neat piece of software, but it is fundamentally flawed performance wise because for each and every email it must load the PERL interpreter.

4 – Restarting Qmail every 15m to recognize new or deleted domains is plain dumb.

The new picture:

mail-system-v2


All of the previous mentioned issues have been addressed and polished. The main Qmail instance (mail) will only accept outside authenticated connections for both local and remote deliveries. The external email comes trough the published mx record Qmail instance only, filtered by rbl, then routed to Amavis for virus and spam scans, and finally routed to the main Qmail instance (if virus and spam free). In this scenario you must trust your customers, because as they authenticate and send emails, these will bypass all the virus and spam checks.

Let’s put our hands to work, the first slice is on point 15 of the original guide “Clam Anti Virus, Spam Assassin and Qmail-scanner”, this version will move the virus and spam filter to the other Qmail instance. So follow the original guide until point 15, and then:

1 – Install qfilter

cd /usr/ports/mail/qmail-qfilter/
make install clean

2 – Make a shell script wrapper that will invoke the filters used by qfilter

mkdir -p /var/qmail/qfilter
edit /var/qmail/qfilter/qfilter-wrapper

and put these contents on the file

#!/bin/sh
exec /usr/local/bin/qmail-qfilter /var/qmail/qfilter/smtp-auth-only

save and mark it executable

chmod +x /var/qmail/qfilter/smtp-auth-only

Note:
actually there is only one filter being invoked (smtp-auth-only), but qfilter supports several filters (exec /usr/local/bin/qmail-qfilter /path/to/filter-one –/path/to/filter-two –/path/to/filter-three)

3 – Install the smtp-auth-only filter

This is just a very simple perl script that will test the presence of the environment variable TCPREMOTEINFO, as this variable is only set upon successful smtp-auth. If the mail comes from an authenticated user the script returns 0, else if it’s from a non-authenticated user the script returns 31 signaling a permanent error.

edit /var/qmail/qfilter/smtp-auth-only

the script is very simple

#!/usr/local/bin/perl

if (defined $ENV{'TCPREMOTEINFO'} == false) {
        use Sys::Syslog qw(:DEFAULT :standard);
        openlog("qfilter", 'ndelay,pid', 'mail');
        syslog('info', "No SMTP-Auth - Rejecting Email");
        exit 31;
}

exit 0;

save it and mark it executable

chmod +x /var/qmail/qfilter/smtp-auth-only

4 – Adjust /etc/tcp.smtp to use qfilter

this is my last line now of /etc/tcp.smtp

:allow,MAXLOAD="2000",SPFBEHAVIOR="0",RBLSMTPD="",QMAILQUEUE="/var/qmail/qfilter/qfilter-wrapper"

it accepts connections from everywhere (if cpu load > 20 rejects connections) it bypasses SPF and RBL checks, and it uses qfilter-wrapper as qmailqueue. After

qmailctl cdb

to build the new smtp tcp rules cdb file and reload qmail, the main Qmail instance will only accept authenticated user email. Email routed from mx should match a previous /etc/tcp.smtp rule.

5 – Install Clam Anti Virus, Spam Assassin and Amavis

This step kind of mimics the step 15 on the original guide, with two main differences. We are installing all the filtering software on the MX instance of Qmail. And qmail-scanner as been replaced by Amavis.

So, log in to the MX console and install the software.

cd /usr/ports/security/clamav
make install clean

options selected: ARC, ARJ, DMG_XAR, DOCS, ICONV, LHA, LLVM, TESTS, UNRAR, UNZOO

cd /usr/ports/mail/spamassassin
make install clean

options selected: AS_ROOT, GNUPG, UPDATE_AND_COMPILE, DCC, DKIM, PYZOR, RAZOR, RELAY_COUNTRY

cd /usr/ports/security/amavisd-new
make install clean

options selected: ALTERMIME, ARC, ARJ, BDB, CABS, DOCS, FILE, FREEZE, LHA, LZOP, MSWORD, MYSQL, P7ZIP, RAR, RPM, SPAMASSASSIN, TNEF, UNARJ, ZOO

as always on FreeBSD the installation is easy and a breeze. Now the fun part, configuring and make all this work together…

6 – Configure Clam Anti Virus

First ClamAV and FreshClam (the anti-virus updater daemon). Here’s a comment striped out of /usr/local/etc/clamd.conf

LogSyslog yes
LogFacility LOG_MAIL
LogVerbose yes
ExtendedDetectionInfo yes
PidFile /var/run/clamav/clamd.pid
DatabaseDirectory /var/db/clamav
LocalSocket /var/run/clamav/clamd.sock
FixStaleSocket yes
ReadTimeout 300
CommandReadTimeout 5
User vscan
AllowSupplementaryGroups yes
ScanMail yes

and the comment stripped version of /usr/local/etc/freshclam.conf

DatabaseDirectory /var/db/clamav
LogVerbose yes
LogSyslog yes
LogFacility LOG_MAIL
PidFile /var/run/clamav/freshclam.pid
DatabaseOwner vscan
AllowSupplementaryGroups yes
DatabaseMirror database.clamav.net
NotifyClamd /usr/local/etc/clamd.conf

There are few modifications to the distribution configuration files, mainly 2 things, to run clamd/freshclam daemons as the user ‘vscan’, the same user that will run amavis, and to log via syslog mail facility.

It makes perfect sense to take advantage of syslog and newsyslog automatic maintenance and log rotation. Also, having most of stuff logging to /var/log/mail makes it easy to spot any error message outputted by any of the several components. The downsize, is that in a busy server the log can become a bit messy.

Adjust the ownership on ClamAV directories:

chown -R vscan:vscan /var/db/clamav
chown -R vscan:vscan /var/run/clamav

add the rcvars to /etc/rc.conf
clamav_clamd_enable=”YES”
clamav_freshclam_enable=”YES”

and start both of the daemons

/usr/local/etc/rc.d/clamav-clamd start
/usr/local/etc/rc.d/clamav-freshclam start

7 – Configure Spamassassin

First, as Spamassassin uses the GeoIP database, you should have an updated database on /usr/local/share/GeoIP/GeoIP.dat, to do so automaticaly write this file on /usr/local/etc/periodic/daily/updategeoip

#!/bin/sh

cd /usr/local/share/GeoIP
/usr/local/bin/wget -q http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gzip -d -f GeoIP.dat.gz

exit 0

and mark it executable

chow +x /usr/local/etc/periodic/daily/updategeoip

and run it manually (you should have installed on your system /usr/ports/ftp/wget)

/usr/local/etc/periodic/daily/updategeoip

update and compile Spamassassin rules

sa-update
sa-compile

and make this process automatic, edit /usr/local/etc/periodic/weekly/spamassassin

#! /bin/sh

/usr/local/bin/sa-update && /usr/local/bin/sa-compile

exit 0

mark it executable, and run by hand the first time

chmod +x /usr/local/etc/periodic/weekly/spamassassin

Spamassassin doesn’t need so much configuration, and it pretty much works out of the box, but i made some fine tuning to everything play happy, so there it is the commented striped version of /usr/local/etc/mail/spamassassin/local.cf

use_dcc 1
dcc_home /var/dcc
dcc_path /usr/local/bin/dccproc
dcc_timeout     10
add_header all  DCC _DCCB_: _DCCR_
use_pyzor 1
pyzor_path /usr/local/bin/pyzor
use_razor2 1
razor_config /var/amavis/.razor/razor-agent.conf
score RAZOR2_CHECK 2.500
score PYZOR_CHECK 2.500
score DCC_CHECK 4.000

create the /var/amavis/.razor directory, and set up razor

mkdir /var/amavis/.razor
razor-admin -home=/var/amavis/.razor -create
razor-admin -home=/var/amavis/.razor -discover

and change ownership to the vscan user

chown -R vscan:vscan /var/amavis/.razor

time to set up the rc vars at /etc/rc.conf and start Spamassassin (replace aaa.bbb.ccc.ddd for the allowed IP address to connect)

spamd_enable="YES"
spamd_flags="-A 127.0.0.1,aaa.bbb.ccc.ddd"

and start it

/usr/local/etc/rc.d/sa-spamd start

8 – Configure Amavis

Amavis will be the glue between Qmail and ClamAV and Spamassassin in a dual MTA setup. It will accept routed emails from Qmail (mx instance) on port 10024, fiter, and re-route to the main Qmail for local delivery (email instance).

Here it is the /usr/local/etc/amavisd.conf configuration file. Now some customizations required to amavis work properly:

  • set $mydomain and $myhostname to your host fqdn
  • configure $forward_method = ‘smtp:[aaa.bbb.ccc.ddd]:25’; Set aaa.bbb.ccc.ddd to the IP address of the main Qmail instance (email host) to where the filtered emails are forward. Remember that in the Qmail instance you need a corresponding entry in /etc/tcp.smtp that accepts the forward emails and skips SPF and RBL checks (replace aaa.bbb.ccc.ddd for the incoming IP of Amavis):
    aaa.bbb.ccc.ddd:allow,MAXLOAD=”2000″,SPFBEHAVIOR=”0″,RBLSMTPD=””,QMAILQUEUE=”/var/qmail/bin/qmail-queue”
  • the $max_servers should, as commented, match the width of your MTA pipe /var/qmail/control/concurrencylocal
  • @local_domains_maps = [‘.’]; we accept every incoming email as a local domain email, because by configuration the mx Qmail instance will only accept and forward to Amavis emails to local domains
  • customize $inet_socket_bind, generally the loopback address IP should be fine, but if your are running inside a jail (and if you are following this guide you are) replace the loopback IP for the main jail IP
  • setup @inet_acl list (this is space delimited list of IPs that Amavis will accept email from). If you are running everything in the same jail (Qmail mx instance and Amavis) this is the main jail IP, if Qmail mx is running in other jail or host add the mx Qmail outgoing IP

These are some of the most important things that you should consider to setup Amavis to your own taste, and as pretty neat software everything (or just about everything) is customizable. The configuration file has extensive comments so it’s easy to understand each and every option:

  • In this setup Amavis is logging to syslog mail facility, $DO_SYSLOG = 1; and $SYSLOG_LEVEL = ‘mail.info’; scroll up to find out why. You can change this to a $LOGFILE. Also setup the $log_level
  • Virus, banned and spam (after $sa_kill_level_deflt threshold) emails are plain discarded, bounce only in case of bad headers.
    $final_virus_destiny = D_DISCARD; # (defaults to D_DISCARD)
    $final_banned_destiny = D_DISCARD; # (defaults to D_BOUNCE)
    $final_spam_destiny = D_DISCARD; # (defaults to D_BOUNCE)
    $final_bad_header_destiny = D_BOUNCE; # (defaults to D_PASS), D_BOUNCE suggested
  • you can customize $virus_admin and $spam_admin with a email address to receive reports when virus/spam email is detected, in this case you should also configure the from addresses in $mailfrom_notify_admin, $mailfrom_notify_recip, $mailfrom_notify_spamadmin
  • this configuration example does not notify me of positives, but i keep them in a quarantine dir, so i can do postmortem analysis and recovery,
    $QUARANTINEDIR = ‘/var/virusmails’;
    # Separate quarantine subdirectories virus, spam, banned and badh within
    # the directory $QUARANTINEDIR may be specified by the following settings
    # (the subdirectories need to exist – must be created manually):
    $virus_quarantine_method = ‘local:virus/virus-%i-%n’;
    $spam_quarantine_method = ‘local:spam/spam-%b-%i-%n’;
    $banned_files_quarantine_method = ‘local:banned/banned-%i-%n’;
    $bad_header_quarantine_method = ‘local:badh/badh-%i-%n’;
  • you can also customize the spam score required to each action
    $sa_tag_level_deflt = undef; # always add spam info headers
    $sa_tag2_level_deflt = 5.0; # subject will be re-written with $sa_spam_subject_tag value
    $sa_kill_level_deflt = 10; # email will not be delivered, and we keep a copy in quarantine
    $sa_dsn_cutoff_level = 15; # Since we are using D_DISCARD, this setting will serve no purpose, but if you were using D_BOUNCE, you can use this to set a level at which the sender will no longer be notified

and many more options that you can/should look into. If you are going to quarantine emails you should create the quarantine directories:

mkdir -p /var/virusmails/badh/
mkdir -p /var/virusmails/banned/
mkdir -p /var/virusmails/spam/
mkdir -p /var/virusmails/virus/

chown -R vscan:vscan /var/virusmails

also, it’s not a bad idea to put a line in root cron to delete older (30 days older) quarantined emails:

crontab -e

05 05 * * * /usr/bin/find /var/virusmails/* -type f -mtime +30 -exec /bin/rm -f {} \;

Finally! add the rc var at /etc/rc.conf

amavisd_enable="YES"

and start it

/usr/local/etc/rc.d/amavisd start

9 – Configure Qmail to use Amavis

Just a simple php script run every 10 minutes by cron will take care of this. As a bonus when you add, rename or delete a domain the Qmail mx instance will pick up the changes.

Edit /var/qmail/control/make_smtp_routes and adjust aaa.bbb.ccc.dd with the Amavis listening IP:port ($inet_socket_bind in amavisd.conf):

#! /usr/local/bin/php
<?php

$smtp_route = 'aaa.bbb.ccc.ddd:10024';

$rcpthosts     = file('/var/qmail/control/rcpthosts');
$morercpthosts = file('/var/qmail/control/morercpthosts');

$hosts = array_merge($rcpthosts, $morercpthosts);
$hosts = array_filter($hosts);

$fp = fopen("/var/qmail/control/smtproutes.tmp", "w");
foreach ($hosts as $host)
    fwrite($fp, trim($host).":".$smtp_route."\n");
fclose($fp);

if (md5_file('/var/qmail/control/smtproutes.tmp') == md5_file('/var/qmail/control/smtproutes')) {
    unlink('/var/qmail/control/smtproutes.tmp');
    exit(0);
}

openlog('PHP', LOG_ODELAY|LOG_PID, LOG_MAIL);
syslog(LOG_INFO, "New /var/qmail/control/smtproutes");

rename("/var/qmail/control/smtproutes.tmp", "/var/qmail/control/smtproutes");

syslog(LOG_INFO, "Restarting Qmail");
exec('/root/bin/qmailctl restart');

exit(0);

?>

mark it executable

chown +x /var/qmail/control/make_smtp_routes

and add it to cron

cron -e
*/10 * * * * /var/qmail/control/make_smtp_routes > /dev/null 2>&1

That’s it, this is the end. Now go grab a well deserved beer and behold your brand new system.

Final toughts

The system is cool, addressed the issues of the old system and is maintenance free. But, there is some space to improvements:
– develop an API (work in progress) that allows for administration, domain management and email management of the system. With this piece in place is then easy to integrate and develop admin and control panels that replace the outdated qmailadmin panel and administrative tasks on the command line.
– related with the API, to give domain managers the possibility to fine tune per domain anti-virus, spam, quarantine and notification settings. This also implies a deeper knowledge of Amavis configuration.
– to compile a complete and comprehensive guide that incorporates the original guide and the stuff on this one.

FIN and CLOSED 🙂

Reverse DNS with djbdns on private IP

Preface:

I remember long time ago when i had to mess around with BIND, the old, venerable, security flaws rich history, and of course the not for humans configuration file, name server. I’m so happy that i switched to djbdns and of course the very practical vegadns GUI.

End of preface.

So, in a a scenario where you have a network with private address(es), yes it can be in the same physical machine (like a private IP jail….) you can use tinydns to publish a PTR record for that IP(s) and force dnscache to use your own published PTR record to resolve the private IP to the configured domain/hostname.

First configure tinydns, you can use vegadns as usual, set a new in-addr.arpa domain according to the pretended IP(s) reverse. Ex:

For several 10.1.1.x addresses, configure a 1.1.10.in-addr.arpa domain, if you just want to configure a reverse record for 10.1.1.2 it’s enough to configure a 2.1.1.10.in-addr.arpa (note in both situations the inverted IP). Don’t forget to set the NS records to your own tinydns instance. Then it’s just a matter of configuring the IP PTR record. Let’s say 10.1.1.1 PTR my.domain.com, in vegadns you insert the IP in the hostname and my.domain.com in the address field (it’s a reverse) and choose PTR from the type select.

Now, for the dnscache resolver use this information, and query directly your server bypassing the normal reverse resolve process. Actually is a very simple, just create a file in /etc/dnscache/root/servers/ with the same tinydns logic. Ex: to bypass only for IP 10.1.1.2 create a 2.1.1.10.in-addr.arpa file, for all 10.1.1.x addresses a 1.1.10.in-addr.arpa file and so on. In the newly created file you just have to put the tinydns IP that dnscache will use to do the resolve queries.

You can easily test if everything is ok, with the good old reliable dig command:
dig +noall +answer -x 10.1.1.1