postfix mailserver scenarios.pdf

Upload: guillermm

Post on 11-Oct-2015

50 views

Category:

Documents


0 download

TRANSCRIPT

  • Postfix using your distros package man-ager should not prove too difficult. Suseusers can call yast -i postfix, and Debianusers apt-get install postfix. If this worksas expected, you should now have a/etc/postfix/main.cf file. This is themajor config file for your postmaster.

    It is worthwhile taking a look at thisfile before we start modifying settings.The main.cf file is well-documented bymost distributions. It is full of sampleconfigurations, which are tagged as com-ments (#). If a parameter is disabled,Postfix will always have a useful defaulthandy. Some distributions add values oftheir own at the end of main.cf, allowingadmins to locate the most importantparameters at a glance. The downside isthat your modifications might be over-written by entries further down in thefile. The last value applied wins. Thepostconf program provides an alternativeto manual editing (see the Overview ofPostfix Tools box) which helps with theentering of new parameters.

    The first time you run Postfix on amachine, you need to define a few basicsettings for the hostname and networkinterface (see the Postfix Basic Configu-

    ration box). After completing this step,and assuming that your tests have beensuccessful, we can now turn to a fewtypical applications.

    Scenario 1: Plain VanillaOur simplest case assumes that Postfix isrunning in a data center or on a corpora-tion network with a static, routable IPaddress. In this case, the mail servershould work after completing the basicinstallation steps, accepting email mes-sages for its domain, and allowingclients on the local network to send mes-sages to other mail addresses. A serverlike this is extensible. You can add spamand antivirus protection (see Box Virusand Spam Protection with Amavis) orprovide a mail relay for customers.

    The most important question with amail server is whether the server acceptsmail or not. A normal mail serveraccepts email from anywhere in a net-work, assuming that the messages aredestined for a mail address for which theserver is responsible. Only users areallowed to contact the server to sendmail to the Internet, and the server willdeliver mail all over the world.

    An email server is a standard pieceof equipment for enterprises.Email communication is rapidlybecoming the preferred method ofexchanging messages. Even governmentoffices are catching on, with mail serversrapidly gaining a foothold.

    However, mail servers are a complexsubject and beginners often have no realunderstanding of a mail servers poten-tial. Reason enough to look at the PostfixMail Transfer Agent (MTA) [1] in a fewapplication scenarios, especially as it isknown for its simplicity and security.

    After completing an installation to puta Linux distribution on the designatedPostfix machine, the steps for installing

    The Postfix mail server continues togain popularity, above all as it issimple to modify and configure. Nomatter whether you use Postfix as adialup host, in a DMZ, or as a simplerelay, we will be looking at typicalscenarios in production environ-ments. BY PEER HEINLEIN

    Postfix in Practical Scenarios

    Flexible Postman

    31www.linux-magazine.com October 2004

    COVER STORYPostfixwww.photocase.de

    Peer Heinlein has beenan Internet ServiceProvider since 1992.Besides his book onPostfix, Peer has pub-lished two otherbooks on "LPIC-1" andthe "Snort" IntrusionDetection System with Open SourcePress. Peer's company, www.heinlein-support.de, educates and trainsadministrators, and provides consultingand support services all over Europe.

    THE A

    UTHO

    R

  • 32 October 2004 www.linux-magazine.com

    PostfixCOVER STORY

    It is not the servers responsibility todeliver mail from arbitrary addresses andusers to arbitrary destinations.

    If we apply this to a configuration,these distinctions are made by settingthe smtpd_recipient_restrictions parame-ter. We can simply use the default:

    smtpd_recipient_restrictions U= permit_mynetworks,

    reject_unauth_destination

    Relaying is permitted for any IPaddresses in $mynetworks, but other-wise Postfix will refuse any mail notdestined for it; in other words, the serverneeds to be the final destination.

    Scenario 2: As a Backup MXIn contrast to Web servers, it is quiteeasy to designate a backup mail serverthat accepts any messages posted to yourmain mail server while it is down, andputs the messages into temporary stor-age. In smaller networks it is often notworth setting up a Backup MX; othermail servers along the path to your mainmail server will also keep mail for deliv-ery later, when your Postfix server isback up and running. However, there area few situations where a Backup MX canstill prove useful. Knowing where mes-sages will be stored in case of down timegives admins more leeway; at least you

    have some control over the backupserver, and can patch up a workaroundthat will keep your business running.

    There are some environments whereanother type of mail server (such asExchange, Scenario 3) stores messagestemporarily, allowing the Backup MX todeliver incoming messages withoutdelay, despite any problems with themain server. Here, the two servers arepeers, and fail over transparently.

    Backup for ReliabilityIt is easy to set up a backup mail server.All you need is a second Linux machinewith Postfix installed and the minimalconfiguration shown in the PostfixBasic Configuration box. The BackupMX needs a suitable MX entry in yourDNS. Select a higher MX value to reflecta lower priority and allow other mailservers to contact your main mail server(MX 10) first. If this fails, they willchoose the backout machine (MX 20).

    The machine needs to know that it is abackup machine, and expected to storemessages. To configure this, look for theline with smtpd_recipient_restrictions inmain.cf, and add an entry for permit_

    mx_backup, paying attention to theorder of the entries:

    smtpd_recipient_restrictions = Upermit_mynetworks,

    permit_mx_backup,reject_unauth_destination

    You can use any other mail server as abackup machine. Two active serverscould back each other up if an error con-dition occurs. Smaller companies shouldlook to use the providers mail server orcontact a partner to organize a mutualbackup solution.

    postfix flush: Immediately attempts todeliver any mail waiting in the mail queue.mailq: Lists all the messages in the mailqueue with their status.postconf parameter: Shows the current set-tings for this parameter.postconf -e parameter=value: Sets a para-meter in main.cf to the given value.Thisallows for convenient editing of main.cf inshell scripts, and other applications.postconf -n: Displays all the parameters inmain.cf which are not default values.This isvery useful for troubleshooting.postsuper -r: Initiates a requeuefor allmessages; that is it puts the messages backin the queue, resolves all DNS data, andchecks any new address aliases (such as theones in the virtual table).postmap file: Converts a lookup table fromPostfix (for example virtual or transport to aPostfix database format.

    Overview of Postfix Tools

    A few simple steps are all it takes to config-ure a newly installed Postfix machine toallow it to assume the role of a normal mailserver on a LAN.You will typically need tomodify a few parameters in main.cf. Ensurethat the setup program provided by your dis-tribution has entered useful values into/etc/postfix/main.cf.The first place to look isthe end of the file.This is where setup pro-grams tend to add critical parameters, whichwould overwrite any changes you made fur-ther up in the file.Postfix can use variables. If you define$myhostname somewhere in the file, youcan use the variable at other positions.$myhostname has to be a hostname thatDNS can fully resolve to your server name,including the domain (FQDN).$mydomain is not normally set. Postfixchecks $mythostname for the domain in thiscase.$mydestination tells Postfix the mailaddresses for which it is the final destina-tion, that is, the domains for which it shouldaccept messages for delivery to localaccounts this is a critical parameter.Besides localhost and $myhostname, $mydo-

    main is typically added here, as messagesare normally addressed [email protected] rather than [email protected].$mynetworks: Includes the trusted IPaddresses that are permitted to send mes-sages to external addresses (relaying).This istypically 127.0.0.0/8 and the local subnetserved by the mail server.$mynetworks_style: Alternatively, Postfixallows you to use this parameter to definethe network segments allowed to relay.Theserver refers to its own IP address to discoverthe networks, allowing for a flexible configu-ration that can be transferred to otherservers.$mynetworks_style = class

    The value for class reflects the network class,A/B/C, of the network on which the serverresides.The other alternatives are subnet(refers to the servers subnet and is normallythe best choice), and host (for the server IPaddress).Postfix has to reload the configuration frommain.cf when you change it. Depending onthe distribution you use, type either rcpostfixreload or /etc/init.d/postfix reload to do this.

    Postfix Basic Configuration

    01 # Permit DNS queries:02 /usr/sbin/postconf -e

    "disable_dns_lookups = no"03 # Allow immediate mail

    delivery:04 /usr/sbin/postconf -e

    "defer_transports = "05 # Reload configuration:06 /usr/sbin/postfix reload07 # Process mail queue:08 /usr/sbin/postfix flush

    Listing 1: ip-up.local

  • main mail server,and deliver themessages to thatserver when itcomes back up, asif nothing had hap-pened.

    Scenario 3:Relay in theDMZThere are goodreasons for usingPostfix as a mailrelay, and storingmessages on an-other mail server.Environments thatuse MS Exchange

    to support critical Groupware functionson a LAN are just one example; Exchangeis not renowned for its prowess in thebattle against spam, viruses, and hackers.To mitigate the risk, some admins set upa Postfix server at the border to their net-works, allowing Postfix to handleInternet-based mail exchanges, and pass-

    ing incoming mail to the Exchange serveron the local network.

    This removes the need to expose theExchange server on the Internet. At thesame time, Postfix can show its strengthin the fight against the issue of malevo-lent messages.

    Do-It-Yourself RoutingYou can use the same setup if you needto deploy a mail server in your DMZ torelay incoming mail to another mailserver in your secure LAN. It does notmake any difference if this is anExchange server or another Postfixserver. Figure 1 shows this scenario.

    After rebooting, Postfix will acceptmessages although they are notaddressed to its final_destination do-main. The server recognizes that there isanother server with a lower MX value (ahigher priority) and not try to deliver anymessages to local accounts. The serverwill continually attempt to contact the

    33www.linux-magazine.com October 2004

    COVER STORYPostfix

    Figure 1: A relay server in the DMZ protects the mail server proper wherethe mailboxes reside.

    External firewall

    Inner firewall

    DMZ / Green zone

    Internet

    LAN

    Mail server

    Mail serverSMTP/POP3/IMAP

    SMTP-Relay

    Proxy ServerHTTP/FTP

    WWW ServerHTTP

    01 # Disable DNS queries:02 /usr/sbin/postconf -e

    "disable_dns_lookups = yes"03 # Stop SMTP transmissions:04 /usr/sbin/postconf -e

    "defer_transports = smtp"05 # Reload configuration.06 /usr/sbin/postfix reload

    Listing 2: ip-down.local

  • 34 October 2004 www.linux-magazine.com

    PostfixCOVER STORY

    smtpd_recipient_restrictions U= permit_mynetworks,

    permit_mx_backup,reject_unauth_destination

    The server will not look for local useraccounts, but instead honor the trans-port record, sending the messages forthis domain to the 192.168.1.99 IP.

    Instead of using an IP, you could use aDNS hostname, but the square bracketsare mandatory. The brackets have a spe-cial meaning and tell the server to relaythe messages to the named host (identi-fied by querying the DNS A record) andnot to the authoritative mail server forthe domain (identified by querying theDNS MX record as this could be therelay itself).

    Admins have to allow mail to travel inthe opposite direction too, allowing mes-sages to travel from the LAN-based mailserver at 192.168.1.99 to the Postfix relayin the DMZ. The settings will depend onthe LAN-based mail servers software.You will typically find a parameter called

    Relayhost (or sometimes Smarthost)that handles this. Any messages withexternal addresses are sent to this hostfor forwarding; this is the counterpart ofthe transport table if you like. If the LAN-based mail server also runs Postfix, youcan add the following entry to themain.cf file:

    relayhost=[mail.example.com]

    Scenario 4: Without aPermanent ConnectionThe scenarios we have looked at so far,assumed a leased line with static IPs tofacilitate routing to the servers. Noteveryone has a Class C network with a2Mbit or even 34Mbit leased line, or aserver of their own at the data center.Users in home or small business net-works, or in areas without broadband,may still need to resort to a good oldISDN card and dialup access to an Inter-net-by-Call provider. With this kind ofconnection you can expect to be billedfor access and connection time.

    Just a few steps are required to modifythe Postfix configuration. Several optionsare open to the admin, but the easiestway to go is to use a so-called transporttable. The /etc/postfix/transport file tellsPostfix to deliver mail based on a pre-configured IP address, rather than usingthe MX records in the DNS. If the localmail server on your LAN has an IP of192.168.1.99, the following is fine:

    example.com smtp:[192.168.1.99]

    The next thing you need to do is callpostmap /etc/postfix/transport to tellPostfix to convert the file to its nativedatabase format.

    The rest of the Internet does not knowabout this setup, of course. Other mailservers will use the MX record to identifythe DMZ mail server as their target, andsend mail to that server. Postfix acceptsthis incoming mail, as the mail addressincludes the MX record for the domainand permit_mx_backup is specified inthe smtpd_recipient_restrictions:

    Effective spam protection is often a complexmatter, and a whole armory of defensivemethods may be required to provide it.TheAmavis Project [8], which started off life asan antivirus gateway for mail servers, allowsyou to integrate Spam Assassin anextremely complex, and intelligent softwarethat can filter your mail on spam criteria.Although you can install Spam Assassin as astand-alone software without Amavis, thedual approach is preferable. Amavis is quick,and easy to install; it performs well, and han-dles the details of Postfix and Spam Assassinintegration really neatly. Also, if you installthe antivirus program, you get virus check-ing into the bargain.

    Both programs are included by most oftodays modern distros. As there are manyversions around, you should always checkamavisd-new for the latest version.After installing the packages, you shouldhave a amavisd-new daemon running in thebackground. It opens a lightweight SMTPdaemon on port 10024, and uses a virusscanner, and Spam Assassin to check emailson this port. Assuming it does not find any-thing, the daemon uses SMTP to forward themessages to Postfix via port 10025. Figure 7shows the setup.After calling /etc/init.d/amavis to launchAmavis, it makes sense to check the logfile tosee if everything is running as it should be.

    Depending on your distribution, Amavis willlog the results in /var/log/mail or/var/spool/amavis.There are just two steps left with Postfix. Anentry ofcontent_filter=[127.0.0.1]:10024in main.cf tells the server to send new emailmessages to amavis-new.At the same time,Postfix has to open thelocal port 10025 to pick up checked messages.The master.cf file handles this.A suitableentry may already be pre-configured:localhost:10025 inet n - nU- - smtpd -o content_filter=

    The -o content_filter= parameter tells Postfixnot to forward checked mail to amavisd-new, and prevents an infinite loop. Again,you need to restart Postfix to apply thechanges.Some distributions configure Spam Assassinto allow all mail to pass, even messages thathave been identified as spam. Check out thedocumentation and readmes with your dis-tribution for more details (look in/usr/share/doc/packages/amavisd-new forSuse).You can also use the test messages inthis directory to ensure that spam and virusdetection is working as designed. /etc/amav-isd.conf is the place for any fine tuning youmight want to perform.

    Virus and Spam Protection with Amavis

    Figure 7: Every message goes through an additional check performed by Amavis.

    Normal treatmentthrough Postfix

    SMTP, Port 10025 No content filter

    SMTP, Port 25 Content filter

    Input from other mail server

    Amavis

    Port 10024

  • 36 October 2004 www.linux-magazine.com

    PostfixCOVER STORY

    will need to add the changes in Listings 1and 2 to these files; recent versions pro-vide the ip-up.local and ip-down.localfiles for local modifications, however.

    In contrast to sendmail, Postfix cannotcheck whether the queued messageshave been delivered successfully as theconnection is closed by a dial-on-demand timeout if not in use.

    Modem, ISDN, and DSL connectionsin multi-user environments can all bene-fit from traffic shaping to prevent parallelmail transmissions from impacting theWeb surfers experience [2].

    Scenario 5: Postfix and PortForwarding/NATIt is common practice to use an IP suchas 192.168.0.0/24 for local networks andNetwork Address Translation (NAT) or

    masquerading to mapthis private address to theroutable IP assigned tothe dialup host or router.Postfix has no troubletransmitting messages inthis kind of environment,but incoming mail isanother matter. Todaysrouters typically have aport forwarding feature,which is often referred toas Destination NAT.The router opens up apre-configured port andforwards any incomingconnections for this portto the servers running onthe local 192.168.*.* net-work.

    Although this is okayfor many services and will work reliablywith your Web server at home, for exam-ple, it can cause a mail server quiteserious trouble. Here, the router opensup a TCP connection to the mail server,but from Postfixs point of view, the con-nection is from the host at 192.168.0.1and not from a host out on the Internet.

    The IP assigned to the router is typi-cally within the subnet defined in$mynetworks, and thus a trusted IPwhich is allowed to relay to externaladdresses. Thanks to port forwarding, ahome mail server can quickly become anopen relay for spammers and cause theowner no end of surprises. An entry forthe router IP in the proxy_interfaces vari-able will prevent this:

    proxy_interfaces=[ip.of.router]

    Saving MoneyPostfix does not know if theInternet connection is up ordown. It simply attempts toquery DNS for the targetserver, and deliver any mes-sages it has in its queues. Ifyour ISDN connection isconfigured to dial ondemand, every email one ofyour users transmits wouldcause Postfix to dial up anInternet connection. Youcan imagine what thiswould cost in a busy office.

    The idea is to configurePostfix to queue mail locallywhile the connection isdown, and start handlingmessages as soon as theconnection goes up (possi-bly because an Internet user has openeda dial-on-demand connection.

    If the parameter defer_transports=smtp is set in main.cf, Postfix will notimmediately attempt to deliver messagesto external addresses (which wouldmeaning dialing up the provider), butfirst queue them locally. After dialing upthe provider, you can use a script to setthis parameter to zero, reload the config-uration and call postfix flush to flush themessages waiting in the queue. postconf-e provides a convenient way of modify-ing main.cf from the console (see BoxOverview of Postfix Tools).

    The /etc/ppp/ip-up and /etc/ppp/ip-down that most distributions run afterestablishing a connection and discon-necting can be used to automate thisprocess. For some Linux variants, you

    Figure 2: If port forwarding is used, Postfix has to know that the local routeraddress is not trustworthy.

    192.168.0.4

    62.8.206.62

    195.135.220.2

    Target: 192.168.0.1Sender: 192.168.0.1Target: 192.168.0.4

    mail.suse.de

    Sender: 62.8.206.62Target: 195.135.220.2Target: 62.8.206.62

    Sender: 195.135.220.2

    192.168.0.5

    192.168.0.75

    Sender: 192.168.0.4

    192.168.0.1

    Figure 3: Services like DynDNS are popular with users of low-budget DSLaccounts. They cause Postfix a few problems.

    Figure 4: Two additional options in the software configuration, tell KMail touse SMTP-Auth to authenticate.

  • 37www.linux-magazine.com October 2004

    COVER STORYPostfix

    This tells Postfix to handle any connec-tions to these IPs as not belonging to$mynetworks. Also, the server knowsthat it has to treat these IPs as its own forDNS queries, to avoid relaying messagesto itself, from Postfix to the router, andvia port forwarding back to Postfix.

    Scenario 6: Using DynDNSDynDNS and similar services offer freesubdomains for your hosts, and toolsthat flexibly change the IP address regis-tered with DNS. Whenever a client dialsup the Internet, it can automatically setits own DNS entry to the dynamic IPaddress assigned by the provider. Ofcourse, this is a fantastic solution forhome PCs or scratch servers, as you canuse the same name for access despite IPaddress changes.

    Using a DynDNS address to handleyour mail might sound like an attractiveproposition, but you need to be aware ofhow mail servers work. An MTA lookingto deliver a message will first query DNSfor the MX or A records in the domain todiscover the host it needs to send themessage to.

    Of course, this would work fine withDynDNS. The going starts to get moredifficult if your computer happens to bedown for a few hours. Other MTAs willstore your mail as usual, but will send itto the former IP when it becomes avail-able again, instead of querying DNSbefore delivery. Even if the target mailserver had a new IP, and the DynDNS

    entry pointed at the right address, mes-sages stored on other servers while theserver was down would never reach it.

    In an ideal case, these messages wouldbe returned to the sender as undeliver-able a few hours, or days, later. If you areunlucky, the IP might be assigned toanother MTA, which might accept thedelivery, putting your secrets in thehands of a total stranger.

    DynDNS-based mail collection has tobe regarded as a compromise that youshould definitely not rely on.

    Scenario 7: DynDNS as a RelayThere is an answer to the DynDNS issue,assuming you have another mail serverwith a static IP. If you assign highest pri-ority (the lowest MX value) to the MXrecord in your DNS, MTAs will delivermessages to the relay first. An entry inthe transport table tells Postfix to delivermessages to the DynDNS host. This sce-nario is more or less the same asScenario 3 so far. Of course, you needsquare brackets for the /etc/postfix/trans-port entry again:

    test.dyndns.org smtp:U[test.dyndns.org]

    Postfix will relay any messages [email protected] to the DynDNS host.

    If this address is unavailable for alonger period of time, the relay wouldqueue the messages and not resolve theIP number of the target host after doingso. As a workaround, you could call

    postsuper -r ALL

    at regular intervals a cronjob everyhour should do the trick. This tellsPostfix to requeue any outstanding mes-sages. At the same time, the mail serverwould resolve the DNS data, thus honor-ing any changes to the DynDNS addressthat have occurred in the meantime, andallowing it to deliver the messages to theright address.

    This setup works with one or twoexceptions, but it is far from perfect. Thefact that requeuing only occurs once anhour could delay delivery by up to anhour. In this time, a new MTA mightbecome available at the old IP, and yourmail would end up in some strangersmailbox. This kind of issue assumes thatthe DynDNS host is down for a longerperiod of time and would only affectusers with modems or ISDN, rather thanDSL, which is available 24x7 apart froma few seconds per day.

    Of course, there is always the questionas to the usefulness of a DynDNS solu-tion that needs a genuine mail server asa relay to queue its messages. On theother hand, in an environment with mul-tiple mailboxes the DynDNS setupshown here is less trouble than a com-plex fetchmail configuration on theDynDNS host that picks up the messagesfrom the relays mailboxes, if you needto have your mail stored in mailboxes onthe DynDNS host.

    Scenario 8: Postfix and SMTPAuthThe previous scenarios allow users tosend mail via a Postfix mail server, ifthey are in $mynetworks. Things are

    smtpd_sasl_auth_enable = yes

    enables or disables SMTP-Auth no.smtpd_sasl_security_options =noanonymous, noplaintext

    noanonymous prevents anonymous logins,noplaintext prevents clients from transmit-ting the SMTP-Auth password in the clear,which is what the PLAIN and LOGIN authen-tication methods do.This parameter forcesthe client to encrypt the password to pre-vent it from being sniffed. Users need toselect secure settings in their software (forexample CRAM-MD5 or DIGEST-MD5, Figure5).This is not required if logins will be takingplace over secure SSL/TLS connections.

    smtpd_sasl_local_domain = mail

    This parameter stores the value used as arealm by sasldb2. Realms are basically usedto authenticate users from multiple (virtual)server domains, however, both Postfix andmany clients can only handle a single SASLdomain.broken_sasl_auth_clients = yes

    Some older clients, for example MicrosoftOutlook Express 4.x, expect the mail serverauthentication in the following format,AUTH=LOGIN, although this is more typi-cally AUTH LOGIN. Setting this value to yestells Postfix to output the AUTH bannertwice using each of these formats.

    Critical SASL Parameters

    Figure 5: Select MD5 encryption to secure pass-word transmissions.

  • 38 October 2004 www.linux-magazine.com

    PostfixCOVER STORY

    manages a small login database in/etc/sasldb2, which Postfix can access tovalidate users.

    You can add user entries with thesaslpasswd2 tool, and sasldblistusers2lists the existing entries.

    Cyrus-SASL can manage multiple host-names and domains in a single database,allowing multiple user accounts with thesame name but for different domains toco-exist peacefully. Cyrus-SASL uses arealm concept to distinguish betweenaccounts. You can either use the -udomainname parameter to define a spe-cific realm, or saslpasswd2 will simplyuse the hostnames, mail in this case (seeBox Critical SASL Parameters) todefine smtpd_sasl_local_domain.

    To tell Postfix to allow users who haveauthenticated via SMTP-Auth to relay,admins need to add an option forpermit_sasl_authenticated to the smtpd_recipient_restrictions list:

    smtpd_recipient_restrictions= Upermit_mynetworks,

    permit_sasl_authenticated,permit_mx_backup,reject_unauth_destination

    You also need the following parametersin main.cf.

    smtpd_sasl_auth_enable = yessmtpd_sasl_security_options = Unoanonymous, noplaintextsmtpd_sasl_local_domain = mailbroken_sasl_auth_clients = yes

    Refer to the Critical SASL Parametersbox for more details on the individualoptions.

    A small script will take care of every-thing else; transferring the user data tothe SASL database. The -p parametertells saslpasswd2 to read the passwordfrom standard input:

    echo secret | Usaslpasswd2 -p -c tux

    Although SMTP-Auth is quite simple toset up, it does have some drawbacks:The postmaster has to get users to enterthe required credentials into their clientconfigurations (Figures 4 and 6).

    POP before SMTPThe popular POP-before-SMTP method(aka SMTP-after-POP) is an alternative,and it does work with IMAP serversdespite the name. The idea is trivial, butit is still quite difficult to configure. Aftera successful POP3/IMAP login hasoccurred from a specific machine, youcan assume that it is a trustworthy user.The mail server then accepts mail fromauthenticated email clients for a specificinterval (typically 15 minutes).

    more complicated for users from outsideof the local IP range, attempting to con-tact the server from an arbitrary host onthe Internet in order to send email mes-sages. In other words, we need to thinkabout authentication.

    A Mail Address is Not Proofof IDThe idea of using mail addresses forauthentication is a bad one. Mailaddresses can be chosen arbitrarily, andspammers often do just that. Somespammers use the mail addresses of themail servers they exploit to convincethese servers to relay the unsolicitedmail.

    If you are unable to identify clients bystatic IPs or cryptographic techniques,your only option is to use password pro-tection. In contrast to the POP3 or IMAPprotocols, which are used to collectemail messages, SMTP did not originallyspecify a mechanism for checking usernames or passwords for identificationpurposes. This gap was closed sometime later, and modern MTAs and mailclients all support SMTP authentication(SMTP-Auth). A client needs to identifyitself when it requests a mail transfer tobe regarded as trustworthy.

    User Management withCyrus SASLThe Cyrus SASL package [3] brings thisfunctionality to Postfix. The package

    01 ~: # /etc/init.d/pop-before-smtp start02 ~: # ps ax | grep pop-before-smtp03 5022 ? S 0:07 /usr/bin/perl -wT /usr/sbin/pop-before-

    smtp--watchlog=/var/log/mail --logto=/var/log/pop-before-smtp--daemon=/var/run/pop-before-smtp.pid

    04 9367 pts/1 S 0:00 grep pop-before05 ~: # ls -al /etc/postfix/pop*06 -rw-r--r-- 1 root root 12288 Oct 8 11:18 /etc/postfix/pop-before-

    smtp.db

    Listing 3: pop-before-smtp

    Figure 6: No matter whether you have SMTP-Auth with MD5, or SMTP-After-POP the Windows Client,The Bat, can handle both.

  • 39www.linux-magazine.com October 2004

    COVER STORYPostfix

    After configuring the mail software tocheck the mailbox first, before attempt-ing to send messages, there are no othersteps required on the part of the user.Some mail clients use this order bydefault (KMail for example); othersallow you to change the configuration.Older versions of Outlook (Express) arebasically incapable of POP-before-SMTPand you will need a few tricks to getthem to play ball [4].

    This approach has a few drawbacksfor postmasters, and it is slightly contro-versial. For one thing, there is no realway of validating the senders creden-tials. A computer that has been validatedmight be used by multiple users.

    For another, there is always a dangerof a dynamic IP being assigned toanother user within the time slot, andthis user might happen to access themail server that authenticated the pre-vious user (or an attacker might do this on purpose). Still, POP-before-SMTP isuseful in many cases, and can be imple-mented in addition to SMTP-Auth.

    The pop-before-smtp script [5], whichmany current distributions include as aready-to-run package, uses a daemon tocheck the logfiles of a POP3/IMAPserver. When new entries or successfullogins occur, the script extracts the userIP and enters the IP into the /etc/postfix/pop-before-smtp database.

    If Postfix decides to accept mail fromthe authenticated IPs, there is nothing tostop authenticated users from sendingmail. When the time slot has elapsed,pop-before-smtp removes the IP from thedatabase.

    The /etc/pop-before-smtp-conf.pl configfile uses regular expressions to identifyand extract the IP from the logfile entriescreated by POP/IMAP mail servers. Thescript has entries for many common mailserver types.

    The init script supplied with the pack-age loads the daemon when you bootyour machine; follow the steps requiredby your distro to enable the script. Afterrestarting, the script should disappearinto the background and create therequired database (see Listing 3).

    In debug mode the daemon logs anyIPs it has recognized in /var/log/pop-before-smtp (see Listing 4). It will notcreate entries for IP numbers that Postfixhas added to $mynetworks, or that arealready in the database, but simply notethat the IP was known. Debug mode isenabled when the $debug variable in theconfiguration file is set to 1.

    If you see an entry for written ok in thelogfile, you can assume that the scripthas stored the IP in the database. If thisentry is missing, pop-before-smtp is try-ing to tell you that the IP is known froma previous login and authenticated. An

    entry for purging means that the timeslot for this IP has elapsed, and that theIP has been removed from the database.

    A quick look at the logfile after theinstall tells you if login detection is work-ing okay. If pop-before-smtp does notrecognize any IPs, you should check theregular expression in /etc/pop-before-smtp-conf.pl for errors.

    Now, Postfix needs to know how toevaluate the database to answer thequestion as to whether a user is allowedto relay. A smtpd_recipient_restrictionsparameter called check_client_access isused to do this. The parameter expectsthe database for the pop-before-smtpscript as an argument:

    smtpd_recipient_restrictions = Upermit_mynetworks,

    permit_mx_backup,check_sasl_authenticated,check_client_access hash:U/etc/postfix/pop-before-smtp,reject_unauth_destination

    Before you send your server off into theWild, you should definitely check theconfiguration [6]. Databases such asORDB [7] register open relays, and manyservers refuse to accept mail from hostsknown to be on these lists. If you getblacklisted in an open relay database,you might have a hard time getting off ofthe list again. Changing the server IP isoften the only option as running an openrelay means helping the spammers.

    [1] Postfix: http://www.postfix.org/[2] Traffic shaping: http://lartc.org/[3] SASL info and howtos:

    http://www.thecabal.org/~devin/postfix/smtp-auth.txt

    [4] POP-before-SMTP with Outlook:http://www.spinnet.jp/man/pbsmtp/wine/pbs_we_ol98.html

    [5] Script and howto for SMTP-after-POP:http://popbsmtp.sourceforge.net/

    [6] Very useful relay test:http://www.abuse.net/relay.html

    [7] Open Relay Database:http://www.ordb.org/

    [8] Amavis: http://www.amavis.orgPictures courtesy of Open Source Press,"Das Postfix-Buch", ISBN 3-937514-04-X,www.opensourcepress.de

    INFO

    01 /var/log: # tail pop-before-smtp

    02 [...]03 read ts=Mar 22 11:03:29

    ip=62.8.206.15604 read ts=Mar 22 11:17:58

    ip=217.235.18.6605 accepted --- not in

    mynetworks06 written ok07 read ts=Mar 22 11:17:59

    ip=217.235.18.6608 purging ts=Fri Mar 22 10:21:50

    2002 ip=217.224.233.74

    Listing 4: Checking the logfile

    There are two standard formats that mailservers use to store messages.The Mbox for-mat stores all the messages for a specificuser in a single large Mbox file for examplein /var/mail/username. Shell mail programslike mutt or elm access the Mbox filedirectly.The Mbox format is simple andquick, but it can be time-consuming toextract and delete individual messagesfrom a large mail file.Maildir stores each message in a single fileand creates a directory for each user, forexample in /var/mail/username/ Theadvantage that this format provides is itsflexible structure, which also supports theuse of IMAP servers, which create additionalIMAP folders below the Maildir directory,providing the ability to sort messages.Postfix uses the mail_spool_directory para-meter to distinguish between Mbox andMaildir. If the pathname stored in this vari-able ends in a slash, (/)Postfix will storethe messages in Maildir format:mail_spool_directory = /var/mail/If the path name ends in a folder name,without a terminating slash, Postfix will usethe Mbox format instead:mail_spool_directory = /var/mail

    Mbox and Maildir Formats