Saturday, March 28, 2009

Restrict incoming and outgoing mail on #exim4 with #ldap

When I first had to set up an emailserver with Exim4, it took me some time to figure out how to restrict incoming and outgoing mail. This way some accounts were allowed to send mail outside the domain and others could receive mail from the outside world and most could do both.

This turned out to be very useful. I managed to do this with a list including all names. allowed_out and allowed_in. The next step was to figure out how to setup this within the ldap database. Setting up a list, wasn't hard to manage. Finding out the router settings was a lot harder, but I finally found out.

First you'll have to make an ldap entry containing all the users allowed to send mail outside your domain. The ObjectClass for now is inetOrgPerson, better would be something like PosixGroup in combination with memberUid attribute. (I'll change this later)

dn: cn=allowed_out,dc=example,dc=com
cn: allowed_out
objectClass: inetOrgPerson
objectClass: top
o: EXAMPLE
sn: Allowed out
mail: cow@example.com
mail: horse@example.com

Now, you'll have to make a router for your Exim4 config. /etc/exim4/conf.d/router/081_local-config_check_out (whatever filename you like in that dir, but make sure, it's one of the first routers checked)

check_outgoing:
driver = redirect
#don't check local mail
domains = ! +local_domains
#if the sender doens't match the ldap list allowed_out
senders = ! : !{${sg {${lookup ldapm {ldap://127.0.0.1/cn=allowed_out,dc=example,dc=com?mail?sub?}}}{\\s+}{:}}}
# fail sending the mail
allow_fail
# giving the sender next message
data = :fail: You are not allowed the send mail outside this domain. example.com

You can do the exact same thing for incoming mail.

dn: cn=allowed_out,dc=example,dc=com
cn: allowed_in
objectClass: inetOrgPerson
objectClass: top
o: EXAMPLE
sn: Allowed out
mail: cat@example.com
mail: horse@example.com

This time you'll have put some lines in /etc/exim4/conf.d/acl/30_exim4-config_check_rcpt just above the line "acl_check_rcp"

#deny if the mail address is not in the ldap list specified
deny
# but don't check this if the sender is from within the same domain
!hosts = +relay_from_hosts
recipients = !:! {${sg {${lookup ldapm {ldap://127.0.0.1/cn=allowed_in,dc=example,dc=com?mail?sub?}}}{\\s+}{:}}}
message = This email-address isn't allowed to receive mail outside of it's own domain. example.com

That's all, now don't forget to update your Exim4 config and restart the service.

update-exim4.conf
/etc/init.d/exim4 restart


Share/Save/Bookmark

No comments: