summaryrefslogtreecommitdiffstats
path: root/pykolab/setup/setup_mta.py
blob: bc250a8a6882a001be4ae046cf33eefc16feed2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# -*- coding: utf-8 -*-
# Copyright 2010-2012 Kolab Systems AG (http://www.kolabsys.com)
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 or, at your option, any later version
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

from augeas import Augeas
from Cheetah.Template import Template
import os
import shutil
import subprocess

import components

import pykolab

from pykolab import utils
from pykolab.constants import *
from pykolab.translate import _

log = pykolab.getLogger('pykolab.setup')
conf = pykolab.getConf()

def __init__():
    components.register('mta', execute, description=description(), after=['ldap'])

def description():
    return _("Setup MTA.")

def execute(*args, **kw):

    group_filter = conf.get('ldap','kolab_group_filter')
    if group_filter == None:
        group_filter = conf.get('ldap','group_filter')

    user_filter = conf.get('ldap','kolab_user_filter')
    if user_filter == None:
        user_filter = conf.get('ldap','user_filter')

    resource_filter = conf.get('ldap', 'resource_filter')

    files = {
            "/etc/postfix/ldap/local_recipient_maps.cf": """
server_host = localhost
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(|%(kolab_user_filter)s%(kolab_group_filter)s%(resource_filter)s))
result_attribute = mail
""" % {
                        "base_dn": conf.get('ldap', 'base_dn'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                        "kolab_user_filter": user_filter,
                        "kolab_group_filter": group_filter,
                        "resource_filter": resource_filter,
                    },
            "/etc/postfix/ldap/mydestination.cf": """
server_host = localhost
server_port = 389
version = 3
search_base = %(domain_base_dn)s
scope = sub

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = %(domain_filter)s
result_attribute = %(domain_name_attribute)s
""" % {
                        "domain_base_dn": conf.get('ldap', 'domain_base_dn'),
                        "domain_filter": conf.get('ldap', 'domain_filter').replace('*', '%s'),
                        "domain_name_attribute": conf.get('ldap', 'domain_name_attribute'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/mailenabled_distgroups.cf": """
server_host = localhost
server_port = 389
version = 3
search_base = %(group_base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

# This finds the mail enabled distribution group LDAP entry
query_filter = (&(mail=%%s)(objectClass=kolabgroupofuniquenames)(objectclass=groupofuniquenames))
# From this type of group, get all uniqueMember DNs
special_result_attribute = uniqueMember
# Only from those DNs, get the mail
result_attribute =
leaf_result_attribute = mail
""" % {
                        "group_base_dn": conf.get('ldap', 'group_base_dn'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/mailenabled_dynamic_distgroups.cf": """
server_host = localhost
server_port = 389
version = 3
search_base = %(group_base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

# This finds the mail enabled dynamic distribution group LDAP entry
query_filter = (&(mail=%%s)(objectClass=kolabgroupofuniquenames)(objectClass=groupOfURLs))
# From this type of group, get all memberURL searches/references
special_result_attribute = memberURL
# Only from those DNs, get the mail
result_attribute =
leaf_result_attribute = mail
""" % {
                        "group_base_dn": conf.get('ldap', 'group_base_dn'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/transport_maps.cf": """
server_host = localhost
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mailAlternateAddress=%%s)(alias=%%s)(mail=%%s))(objectclass=kolabinetorgperson))
result_attribute = mail
result_format = lmtp:unix:/var/lib/imap/socket/lmtp
""" % {
                        "base_dn": conf.get('ldap', 'base_dn'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
            "/etc/postfix/ldap/virtual_alias_maps.cf": """
server_host = localhost
server_port = 389
version = 3
search_base = %(base_dn)s
scope = sub

domain = ldap:/etc/postfix/ldap/mydestination.cf

bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s

query_filter = (&(|(mail=%%s)(alias=%%s))(objectclass=kolabinetorgperson))
result_attribute = mail
""" % {
                        "base_dn": conf.get('ldap', 'base_dn'),
                        "service_bind_dn": conf.get('ldap', 'service_bind_dn'),
                        "service_bind_pw": conf.get('ldap', 'service_bind_pw'),
                    },
        }

    if not os.path.isdir('/etc/postfix/ldap'):
        os.mkdir('/etc/postfix/ldap/', 0770)

    for filename in files.keys():
        fp = open(filename, 'w')
        fp.write(files[filename])
        fp.close()

    postfix_main_settings = {
            "inet_interfaces": "all",
            "local_recipient_maps": "ldap:/etc/postfix/ldap/local_recipient_maps.cf",
            "mydestination": "ldap:/etc/postfix/ldap/mydestination.cf",
            "transport_maps": "ldap:/etc/postfix/ldap/transport_maps.cf",
            "virtual_alias_maps": "$alias_maps, ldap:/etc/postfix/ldap/virtual_alias_maps.cf, ldap:/etc/postfix/ldap/mailenabled_distgroups.cf, ldap:/etc/postfix/ldap/mailenabled_dynamic_distgroups.cf",
            "smtpd_tls_auth_only": "yes",
            "smtpd_tls_cert_file": "/etc/pki/tls/private/localhost.pem",
            "smtpd_tls_key_file": "/etc/pki/tls/private/localhost.pem",
            "smtpd_recipient_restrictions": "permit_mynetworks, reject_unauth_pipelining, reject_rbl_client zen.spamhaus.org, reject_non_fqdn_recipient, reject_invalid_helo_hostname, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service unix:private/recipient_policy_incoming, permit",
            "smtpd_sender_restrictions": "permit_mynetworks, check_policy_service unix:private/sender_policy_incoming",
            "submission_recipient_restrictions": "check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject",
            "submission_sender_restrictions": "reject_non_fqdn_sender, check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject",
            "submission_data_restrictions": "check_policy_service unix:private/submission_policy",
            "content_filter": "smtp-amavis:[127.0.0.1]:10024"

        }

    if not os.path.isfile('/etc/postfix/main.cf'):
        if os.path.isfile('/usr/share/postfix/main.cf.debian'):
    shutil.copy(
        '/usr/share/postfix/main.cf.debian',
        '/etc/postfix/main.cf'
    )

    myaugeas = Augeas()

    setting_base = '/files/etc/postfix/main.cf/'

    for setting_key in postfix_main_settings.keys():
        setting = os.path.join(setting_base,setting_key)
        current_value = myaugeas.get(setting)

        if current_value == None:
            insert_paths = myaugeas.match('/files/etc/postfix/main.cf/*')
            insert_path = insert_paths[(len(insert_paths)-1)]
            myaugeas.insert(insert_path, setting_key, False)

        log.debug(_("Setting key %r to %r") % (setting_key, postfix_main_settings[setting_key]), level=8)
        myaugeas.set(setting, postfix_main_settings[setting_key])

    myaugeas.save()

    postfix_master_settings = {
        }

    template_file = None

    if os.path.isfile('/etc/kolab/templates/master.cf.tpl'):
        template_file = '/etc/kolab/templates/master.cf.tpl'
    elif os.path.isfile('/usr/share/kolab/templates/master.cf.tpl'):
        template_file = '/usr/share/kolab/templates/master.cf.tpl'
    elif os.path.isfile(os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'master.cf.tpl'))):
        template_file = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'master.cf.tpl'))

    if not template_file == None:
        fp = open(template_file, 'r')
        template_definition = fp.read()
        fp.close()

        t = Template(template_definition, searchList=[postfix_master_settings])
        fp = open('/etc/postfix/master.cf', 'w')
        fp.write(t.__str__())
        fp.close()

    else:
        log.error(_("Could not write out Postfix configuration file /etc/postfix/master.cf"))
        return

    if os.path.isfile('/etc/pki/tls/certs/make-dummy-cert') and not os.path.isfile('/etc/pki/tls/private/localhost.pem'):
        subprocess.call(['/etc/pki/tls/certs/make-dummy-cert', '/etc/pki/tls/private/localhost.pem'])

    amavisd_settings = {
            'ldap_server': 'localhost',
            'ldap_bind_dn': conf.get('ldap', 'service_bind_dn'),
            'ldap_bind_pw': conf.get('ldap', 'service_bind_pw'),
            'primary_domain': conf.get('kolab', 'primary_domain'),
            'ldap_filter': "(|(mail=%m)(alias=%m))",
            'ldap_base_dn': conf.get('ldap', 'base_dn'),
        }

    template_file = None

    # On RPM installations, Amavis configuration is contained within a single file.
    if os.path.isfile("/etc/amavsid/amavisd.conf"):
        if os.path.isfile('/etc/kolab/templates/amavisd.conf.tpl'):
            template_file = '/etc/kolab/templates/amavisd.conf.tpl'
        elif os.path.isfile('/usr/share/kolab/templates/amavisd.conf.tpl'):
            template_file = '/usr/share/kolab/templates/amavisd.conf.tpl'
        elif os.path.isfile(os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'amavisd.conf.tpl'))):
            template_file = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'amavisd.conf.tpl'))

        if not template_file == None:
            fp = open(template_file, 'r')
            template_definition = fp.read()
            fp.close()

            t = Template(template_definition, searchList=[amavisd_settings])
            fp = open('/etc/amavisd/amavisd.conf', 'w')
            fp.write(t.__str__())
            fp.close()

        else:
            log.error(_("Could not write out Amavis configuration file /etc/amavisd/amavisd.conf"))
            return

    # On APT installations, /etc/amavis/conf.d/ is a directory with many more files.
    # 
    # Somebody could work on enhancement request #1080 to configure LDAP lookups,
    # while really it isn't required.
    else:
        log.info(_("Not writing out any configuration for Amavis."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'restart', 'postfix.service'])
        subprocess.call(['systemctl', 'restart', 'amavisd.service'])
        subprocess.call(['systemctl', 'restart', 'clamd.amavisd.service'])
        subprocess.call(['systemctl', 'restart', 'wallace.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['service', 'postfix', 'restart'])
        subprocess.call(['service', 'amavisd', 'restart'])
        subprocess.call(['service', 'clamd.amavisd', 'restart'])
        subprocess.call(['service', 'wallace', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','postfix','restart'])
        subprocess.call(['/usr/sbin/service','amavis','restart'])
        subprocess.call(['/usr/sbin/service','clamav-daemon','restart'])
        subprocess.call(['/usr/sbin/service','wallace','restart'])
    else:
        log.error(_("Could not start the postfix, clamav and amavisd services services."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['systemctl', 'enable', 'postfix.service'])
        subprocess.call(['systemctl', 'enable', 'amavisd.service'])
        subprocess.call(['systemctl', 'enable', 'clamd.amavisd.service'])
        subprocess.call(['systemctl', 'enable', 'wallace.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['chkconfig', 'postfix', 'on'])
        subprocess.call(['chkconfig', 'amavisd', 'on'])
        subprocess.call(['chkconfig', 'clamd.amavisd', 'on'])
        subprocess.call(['chkconfig', 'wallace', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'postfix', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'amavis', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'clamav-daemon', 'defaults'])
        subprocess.call(['/usr/sbin/update-rc.d', 'wallace', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "postfix, clamav and amavisd services."))