Lab 7 Electronic Mail

Goal: To build common skills with MTA configuration

Estimated Duration: 90 minutes

System Setup: Ensure that SELinux and packet filtering are enabled. If you feel confident, then try to complete the lab based only on the specifications given below. The next few pages divide this complex project into manageable sequences.
Following that are step-by-step sequence solutions to guide you through the process of configuring and verifying proper operation.

As with other labs, stationX refers to your actual station as denoted by the last octet of your IPv4 address.

Lab Setup: Instructor: Make sure server1.example.com can receive mail to security@example.com from other hosts.

Situation: You have been asked to set up an email infrastructure for your organization. Your tasks include:

• Create myuser1, myuser2, and compliance users, each with the password redhat

• Users should have IMAPs and POP3s access to the server (using a selfsigned certificate) to check their messages

• Install and configure Postfix

• The MTA accepts connections only from hosts within the example.com or cracker.org subnets

• myuser1 wants to send and receive email as myuser1.alias@stationX.example.com

• Any message sent to mylist is distributed to myuser1, myuser2, and student

• All electronic messages should be archived at /var/spool/mail/compliance

• A copy of every message that mentions the organization's top secret project, "RHCE", should be forwarded to security@example.com

Sequence 1: Dovecot Setup

Scenario: Always divide major projects into discrete components. Installing and configuring Dovecot first allows you to use it for testing the MTA configuration in subsequent sequences.

Deliverable: A working infrastructure for mail retrieval via POPs and IMAPs

Instructions:

1. Install Dovecot.

yum -y install dovecot

2. Confirm that your system date and time are correct.

SSL certificates do not work well when created long before or after the actual time. Check your system's date:

date

You should see a reasonable time and date. If not, you should correct the system date and time before creating your SSL certificate.

3. Generate a private key and self-signed digital certificate.

The first step is to actually generate the private key and self-signed certificate. To avoid setting up a PKI infrastructure and certificate authority, use the Makefile that Red Hat provides:

less /etc/pki/tls/certs/Makefile

In the Makefile, notice the target for %.pem. This target generates a private key and places it in a PEM file. The script then generates a self-signed certificate and appends it to the same PEM file holding the private key.

make checks timestamps when determining which files to process, so find and remove the out-of-box dovecot.pem files:

find /etc/ -name dovecot.pem -exec rm {} \;

Make a new dovecot.pem file containing a private key and self-signed certificate:

make -C /etc/pki/tls/certs dovecot.pem
...output truncated...
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]:US
State or Province Name (full name) [Berkshire]:North Carolina
Locality Name (eg, city) [Newbury]:Raleigh
Organization Name (eg, company) [My Company Ltd]:Example, Inc.
Organizational Unit Name (eg, section) []:Enter (leave blank)
Common Name (eg, your name or your
server's hostname) []:stationX.example.com
Email Address []:root@stationX.example.com
make: Leaving directory `/etc/pki/tls/certs'

Double-check the location and permissions of your new dovecot.pem file:

find /etc/pki -name dovecot.pem -ls
7424004 8 -rw------- 1 root root 2145 Feb 18 22:05
/etc/pki/tls/certs/dovecot.pem

The ownership and permissions are appropriate for a new file containing a private key, but it would seem that the dovecot user would be unable to read its private key. However, perusing dovecot.conf finds a comment that the SSL key and cert are loaded before dropping root privileges, so these permissions are OK.

Check /etc/dovecot.conf to see where dovecot expects to find its key and certificate:

grep -e ssl_cert -e ssl_key /etc/dovecot.conf
#ssl_cert_file = /etc/pki/dovecot/certs/dovecot.pem
#ssl_key_file = /etc/pki/dovecot/private/dovecot.pem
#ssl_key_password =

You need to make the settings in dovecot.conf agree with the actual location. You could copy your new dovecot.pem file to both default locations and then adjust ownership and permissions. Alternatively, you can specify the location of the PEM file you just created.

Modify /etc/dovecot.conf to specify:

ssl_cert_file = /etc/pki/tls/certs/dovecot.pem
ssl_key_file = /etc/pki/tls/certs/dovecot.pem

4. Specify the correct imaps and pop3s protocols.

Modify /etc/dovecot.conf to specify only the secure mail retrieval protocols:

protocols = imaps pop3s

5. Test your configuration.

Start dovecot and enable boot-time startup:

service dovecot restart
chkconfig dovecot on

Send a message to root for testing:

echo 'this is a test' | mail -s test root

Wait a few seconds, then check root's email (warning: this will fail):

mutt -f imaps://root@stationX.example.com

You should see a SASL authentication failure. Perusing /etc/dovecot.conf reveals the following comments:

# Note that denying root logins is hardcoded to dovecot binary and can't
# be done even if first_valid_uid is set to 0.

Repeat your test using the student account:

echo 'this is a test' | mail -s test student
mutt -f imaps://student@stationX.example.com

Examine the certificate carefully before accepting it. In particular, check that the hostname is fully-qualified and that the certificate date looks sane. The time is usually expressed in Universal Time Coordinated (UTC), also known as Greenwich Mean Time (GMT).

Sequence 2: Initial MTA Setup

Scenario: This is a complex configuration, so divide it into smaller tasks. For this sequence, concentrate on creating the necessary users and enabling postfix in its default configuration.

Refer to the step-by-step sequence solutions if you need help or wish to compare your solution to the one provided.

Deliverable: User accounts and a Postfix server that starts at boot-time

Instructions:

1. Create the users myuser1, myuser2, and compliance, each with the password redhat.

Add the users and assign passwords:

for NAME in myuser1 myuser2 compliance; do
  useradd $NAME
  echo redhat | passwd --stdin $NAME
done
Changing password for user myuser1.
passwd: all authentication tokens updated successfully.
...output truncated

2. Install Postfix.

Install the specified MTA and a packet sniffer:

yum -y install postfix wireshark

You will use wireshark to observe network traffic.

3. Set Postfix as your preferred MTA using alternatives.

Stop and disable sendmail,

service sendmail stop
chkconfig sendmail off

Select postfix as your preferred MTA:

alternatives --config mta
There are 2 programs which provide 'mta'.

Selection Command
-----------------------------------------------
*+ 1 /usr/sbin/sendmail.sendmail
2 /usr/sbin/sendmail.postfix

Enter to keep the current selection[+], or type selection number: 2enter

4. Start Postfix and enable it for boot-time startup.

service postfix start
chkconfig postfix on

Confirm that postfix will start at the next reboot:

chkconfig --list postfix
postfix 0:off 1:off 2:on 3:on 4:on 5:on 6:off

This is a good time to back up the original Postfix configuration.

cp -a /etc/postfix /tmp/postfix.orig

Sequence 3: Configuring the MTA to receive mail

Scenario: In this sequence you will configure network access and host-based access controls for your MTA.

Ask your instructor for help if you are unclear on the suggested solution.

Deliverable: A mail server that is available on the classroom subnet and has essential hostbased access controls in place.

Instructions:

1. Use Netfilter to limit access to the specified subnets.

Confirm that you are using stateful inspection for your host firewall:

iptables -nvL | grep -i established
62 4904 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 state
RELATED,ESTABLISHED

If your output does not include a rule similar to the one above, then insert that rule into the kernel at this time:

iptables -I INPUT -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT

Add rules allowing new connections to the MTA and save your configuration:

iptables -I INPUT -p tcp --dport 25 -s 192.168.0.0/24 -m state --state NEW -j ACCEPT

iptables -I INPUT -p tcp --dport 25 -s 192.168.1.0/24 -m state --state NEW -j ACCEPT

service iptables save; restorecon -R /etc/sysconfig

2. Configure Postfix to listen on the classroom interface.

Edit /etc/postfix/main.cf to specify the listening interface:

#inet_interfaces = localhost
inet_interfaces = 192.168.0.X

Restart postfix and confirm that it's listening on the proper interface:

service postfix restart
netstat -tulpn | grep master
tcp 0 0 192.168.0.X:25 0.0.0.0:* LISTEN 16179/master

3. 

Test network connectivity from another station. Remote testing is necessary in order to confirm the effectiveness of your firewall rules.

Start the packet sniffer so that you can observe network traffic in case of a problem with your firewall rules:

tshark -ni eth0 -R "tcp.dstport eq 25 or tcp.srcport eq 25"

The above command will show bidirectional traffic between your server and the remote host after the next step. You may use Ctrl-c to break out of tshark at any time. For now, leave it running.

In a third shell, follow the in-kernel connection tracking table. For optimal viewing, arrange your shells so that you can view both tshark and the connection tracking table side-byside. The following command displays the table, where Y is the last octet of your peer's IP address.

watch -n1 'grep 192.168.0.Y /proc/net/ip_conntrack'

Ask one of your peers to telnet to your MTA while you watch the tshark output to confirm that your firewall rules allow traffic. You should see traffic in both directions. You should see the new connection appear in /proc/net/ip_conntrack, as well. Leave tshark running.

Reciprocate by connecting to a peer host. If connectivity is good, you can expect to see an exchange similar to the following, where Y is the peer's station number.

telnet stationY.example.com 25
Trying 192.168.0.Y...
Connected to stationY.example.com (192.168.0.Y).
Escape character is '^]'.

Type Ctrl-] and then quit to exit the telnet session. It is not necessary to test the full SMTP conversation at this point; you merely want to verify two-way communication through your respective firewalls.

4. Add smtpd_client_restrictions to main.cf to supplement firewall rules.

Sometimes an administrator will temporarily disable a firewall during troubleshooting, or perhaps the firewall rules are not as effective as the administrator believes. Therefore it's prudent to add an additional layer of protection.

Review the configuration man page for postconf to familiarize yourself with the proper host-based restrictions. Make sure to use the man page from section 5!

man 5 postconf

Before implementing your changes, check the current configuration. Either look in main.cf or use the following command:

postconf smtpd_client_restrictions
smtpd_client_restrictions = blank

The above output indicates that there is nothing to preserve in the configuration when making changes.

Edit main.cf to include your new restriction. Recall that any line beginning with one or more whitespace characters is considered a continuation of the preceding line.

smtpd_client_restrictions = check_client_access hash:/etc/postfix/access

Now edit /etc/postfix/access, adding the following lines to the bottom:

127.0.0.1 OK
192.168.0.0/24 OK
192.168.1.0/24 OK
0.0.0.0/0 REJECT

The above restrictions allow localhost, example.com, and cracker.org, but reject connections from all networks. Postfix looks for the most specific match in access files, so order within the access file does not matter.

It is a good practice to include IPv6 restrictions despite listening only on the IPv4 address. This ensures that IPv6-to-IPv4 transitional addresses such as ::ffff:192.168.0.X do not slip past an access control mechanism.

Rehash the access file and restart postfix:

postmap /etc/postfix/access
service postfix restart

If your MTA fails to restart, then examine /var/log/messages for errors.

5. Configure the MTA's destination names for incoming mail.

In many deployments, you would need to edit main.cf to modify mydestination, but the specs for this lab require only that your server receive mail addressed to it by the full hostname. It is therefore sufficient to confirm that the current key/value pair specifies the various hostnames for this machine.

postconf mydestination
mydestination = $myhostname, localhost.$mydomain, localhost

Double-check your own hostname:

hostname
stationX.example.com

Make sure the output is a fully-qualified domain name or else your system has a hostname problem that needs to be corrected, possibly with the help of the instructor.

6. Configure the MTA's origin names for outgoing messages.

The specs for this lab do not require domain masquerading. Nevertheless, you should confirm that myorigin is set appropriately:

postconf myorigin
myorigin = $myhostname

You have already verified that your hostname is correct, so no further action is needed.

7. Test SMTP connectivity from another station. Remote testing is necessary in order to confirm the effectiveness of your access controls.

For practice reading the logs, follow the maillog:

tail -f /var/log/maillog

Ask another person in class to send a message to root@stationX.example.com and watch the maillog. If you see messages indicating that mail has been rejected, then look again at /etc/postfix/access or even main.cf in case of typos.

After the maillog shows that a message has been received, check your mail locally using any one of the following commands.

mutt -f /var/spool/mail/root
-OR-
mail
-OR
cat /var/spool/mail/root

Sequence 4: Configuring User-Based Settings

Scenario: In this sequence you will create a distribution list and configure address rewriting. You will also set up the organizational mail archive and test your settings.

Deliverable: Message archival and address rewriting.

Instructions:

1. Set up message archiving.

Search for bcc in man 5 postconf to find the exact syntax for the always_bcc directive.

Edit /etc/postfix/main.cf and add the following line:

always_bcc = compliance

2. Set up inbound aliases. An alias can also be used for distribution lists, which makes this step easy.

Edit /etc/aliases

myuser1.alias: myuser1
mylist: myuser1, myuser2, student

Rehash the aliases by running

service postfix restart
-OR-
newaliases
-OR-
postalias /etc/aliases

3. Set up outbound address rewriting for myuser1.

Begin by searching for "generic" in man 5 postconf. You should find the directive for smtp_generic_maps along with supporting instructions. The instructions provide a reference to man 5 generic, so feel free to explore that page, as well. Specific Examples are provided in /usr/share/doc/postfix-*/README_FILES/ADDRESS_REWRITING_README.

Edit /etc/postfix/main.cf and add the following line:

smtp_generic_maps = hash:/etc/postfix/generic

Edit /etc/postfix/generic and add the following line:

myuser1 myuser1.alias@stationX.example.com

Since postfix is configured to use a hash of this file, you'll need to create one:

# postalias hash:/etc/postfix/generic

This should create a generic.db file, which postfix will use. Note that this file must be regenerated every time generic is updated.

4. Test user-based configuration settings.

Switch to myuser1 and send an email message to mylist at another workstation.

su - myuser1
echo "test message" | mail -vs 'alias test' mylist@stationY.example.com

Ask your peer at stationY to check their incoming messages for verification, then do the same for that person:

mutt -f imaps://myuser1@stationX.example.com

On stationY, the message should be from myuser1.alias@stationX.example.com

On stationX, the message should be from myuser1.alias@stationY.example.com

Sequence 5: Procmail

Scenario: Configure Procmail to capture messages that refer to the organization's secret project, RHCE.

Deliverable: A working Procmail recipe

Instructions:

1. Ensure that Procmail is installed.

rpm -q procmail

Use yum to install Procmail if necessary.

yum -y install procmail

2. Configure Postfix to use Procmail for local delivery. 

Postfix includes hooks to enable its built-in, local delivery agent to run a specified command. Locate this option by searching the man page for mailbox_command:

man 5 postconf

Confirm the location of the procmail binary:

which procmail
/usr/bin/procmail

Edit /etc/postfix/main.cf:

mailbox_command = /usr/bin/procmail

Restart your MTA:

service postfix restart

Confirm that your setting was effective:

postconf mailbox_command
mailbox_command = /usr/bin/procmail

3. Test procmail locally using a simple recipe.

Review the Procmail man pages before creating a simple recipe for local testing.

man procmail
man procmailrc
man procmailex

Create /etc/procmailrc and add a simple recipe to make sure that Procmail is working as you expect:

cat > /etc/procmailrc << EOF
LOGFILE=/var/spool/mail/procmail.log
VERBOSE=yes

:0 c
* ^Subject.*rhce
/var/spool/mail/procmail.test
EOF

The simple file above directs Procmail to log its actions verbosely to /var/spool/mail/procmail.log for testing. Recipes start with the "colon zero" line. This recipe includes the c flag to indicate that procmail should continue processing even after a successful match. The star line (*) indicates a regular expression match filter. Procmail ignores case by default, so the regex matches any message with RHCE in any combination of case within the subject line. The last line is the action and instructs procmail to store the message in the file /var/spool/mail/procmail.test.

It's a continuing recipe as indicated by the c flag, so the message will still go into the intended recipient's mailbox even if it matches the regex and is therefore placed into the indicated file.

Placing the procmail output files in /var/spool/mail is essential since both Postfix and Procmail are in the default targeted policy.

With /etc/procmailrc in place, test the recipe by sending a matching message on your machine.

mail -vs test-RHCE student
This is a test
.
Cc:Enter
Mail Delivery Status Report will be mailed to <root>.

The dot on a line by itself terminates input.

Review the mail log:

tail -f /var/log/maillog

You'll find a line containing the following error:

can't create user output file. Command output:
procmail: Couldn't create "/var/mail/nobody" procmail: [7313] Wed Feb 20:41:02 2007 procmail: Assigning "LOGFILE=/tmp/procmail.log" procmail:
Opening "/tmp/procmail.log" procmail: Error while writing to
"/tmp/procmail.log" procmail

Start with a long listing on /var/mail, then follow up as shown:

ls -ld /var/mail
lrwxrwxrwx 1 root root 10 Nov 26 13:49 /var/mail -> spool/mail
ls -ld /var/spool/mail
drwxrwxr-x 2 root mail 4096 Feb 21 20:58 /var/spool/mail/

Noting that only root and members of the mail group have write access to the mail spool directory, consider:

• You could add the nobody user to the mail group, but that would give wide access to the mail spool. Don't do this.

• You could change procmail to run setgid, in which case it would run as the postfix user. Presumably, postfix is a member of the mail group.

Test this assumption:

grep mail /etc/group
mail:x:12:mail,postfix,exim
ll `which procmail`
-rwxr-xr-x 1 root mail 92452 Jul 12 2006 /usr/bin/procmail

Yes, it's a valid assumption, so try making procmail run setgid so that it will run with the privileges of postfix instead of nobody.

chmod g+s /usr/bin/procmail
ll `which procmail`
-rwxr-sr-x 1 root mail 92452 Jul 12 2006 /usr/bin/procmail
mail -vs test-RHCE student
This is a test
.
Cc:Enter
Mail Delivery Status Report will be mailed to
<root>.
tail /var/log/maillog
...output truncated...
delivered to command: /usr/bin/procmail

Confirm that procmail was able to write the files specified in your recipe:

ll /var/spool/mail/procmail*
-rw------- 1 nobody mail 901 Feb 21 21:14 /var/spool/mail/procmail.log
rw------- 1 nobody mail 995 Feb 21 21:14 /var/spool/mail/procmail.test

Excellent! Check the contents of both files.

less /var/spool/mail/procmail.*

4. Extend your recipe to search the entire message. procmailrc (5) indicates that without a specific flag to instruct Procmail otherwise, it will search only the header of messages. Your specification must search the entire message.

Edit /etc/procmailrc and add two flags to the :0 line. Also remove "^Subject" from the regex so that your expression will match all lines and not just the subject. Your completed recipe should appear as:

:0 cHB
* .*rhce
/var/spool/mail/procmail.test

Test again using three messages. The first will test the header match. The second will test the body match. The third will test a message that should not match.

mail -vs test-RHCE student
This is a test that matches the subject keyword.
.
Cc:Enter
Mail Delivery Status Report will be mailed to <root>.
mail -vs test student
This is a test that should match RHCE in the body.
.
Cc:Enter
Mail Delivery Status Report will be mailed to <root>.
mail -vs test student
This is a test that should not match.
.
Cc:Enter
Mail Delivery Status Report will be mailed to <root>.

Check the contents of /var/spool/mail/procmail.test to ensure that it has the first two test messages. The last message should not be present.

mutt -f /var/spool/mail/procmail.test

5. Extend your recipe to forward matching messages to security@example.com.

Search procmailrc (5) for the second occurence of !. The man page explains that this
forwards the message to the indicated address.

Edit /etc/procmailrc once again to make your change. Your recipe should be:

:0 cHB
* .*rhce
! security@example.com

Test again:

mail -vs test root
This test should match rhce in the body.
.
Cc:Enter
Mail Delivery Status Report will be mailed to <root>.

Check your mail log to see if it forwarded the message to the security email address:

grep security /var/log/maillog

You should see a log message indicating that a message has been sent to security@example.com.

• If not, then review /etc/procmailrc or the mail log for errors and try again.
• If yes, then ask the instructor to check the mail for security to confirm that your message was received.

Once you are satisfied that your recipe is working as specified, then remove the logging and verbose directives from /etc/procmailrc.

6. Challenge: why does each matching message result in three forwards to security?

Review the actual messages and your mail log for the answer. One copy of the messsage is delivered to compliance, which triggers procmail. Another copy is delivered to your recipient, which also triggers procmail.

posted on 2013-12-17 10:39  逝者如斯(乎)  阅读(949)  评论(0编辑  收藏  举报