summaryrefslogtreecommitdiff
path: root/fail2ban/tests/action_d/test_smtp.py
blob: d9ad0f3a4f56528e671c654de5c9e0937df74d65 (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
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :

# This file is part of Fail2Ban.
#
# Fail2Ban 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; either version 2 of the License, or
# (at your option) any later version.
#
# Fail2Ban 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fail2Ban; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import os
import smtpd
import threading
import unittest
import re
import sys
if sys.version_info >= (3, 3):
	import importlib
else:
	import imp

from ..dummyjail import DummyJail

from ..utils import CONFIG_DIR, asyncserver


class TestSMTPServer(smtpd.SMTPServer):

	def process_message(self, peer, mailfrom, rcpttos, data):
		self.peer = peer
		self.mailfrom = mailfrom
		self.rcpttos = rcpttos
		self.org_data = data
		# replace new line (with tab or space) for possible mime translations (word wrap):
		self.data = re.sub(r"\n[\t ]", " ", data)


class SMTPActionTest(unittest.TestCase):

	def setUp(self):
		"""Call before every test case."""
		super(SMTPActionTest, self).setUp()
		self.jail = DummyJail()
		pythonModule = os.path.join(CONFIG_DIR, "action.d", "smtp.py")
		pythonModuleName = os.path.basename(pythonModule.rstrip(".py"))
		if sys.version_info >= (3, 3):
			customActionModule = importlib.machinery.SourceFileLoader(
				pythonModuleName, pythonModule).load_module()
		else:
			customActionModule = imp.load_source(
				pythonModuleName, pythonModule)

		self.smtpd = TestSMTPServer(("localhost", 0), None)
		port = self.smtpd.socket.getsockname()[1]

		self.action = customActionModule.Action(
			self.jail, "test", host="127.0.0.1:%i" % port)

		## because of bug in loop (see loop in asyncserver.py) use it's loop instead of asyncore.loop:
		self._active = True
		self._loop_thread = threading.Thread(
			target=asyncserver.loop, kwargs={'active': lambda: self._active})
		self._loop_thread.daemon = True
		self._loop_thread.start()

	def tearDown(self):
		"""Call after every test case."""
		self.smtpd.close()
		self._active = False
		self._loop_thread.join()

	def testStart(self):
		self.action.start()
		self.assertEqual(self.smtpd.mailfrom, "fail2ban")
		self.assertEqual(self.smtpd.rcpttos, ["root"])
		self.assertTrue(
			"Subject: [Fail2Ban] %s: started" % self.jail.name
			in self.smtpd.data)

	def testStop(self):
		self.action.stop()
		self.assertEqual(self.smtpd.mailfrom, "fail2ban")
		self.assertEqual(self.smtpd.rcpttos, ["root"])
		self.assertTrue(
			"Subject: [Fail2Ban] %s: stopped" %
				self.jail.name in self.smtpd.data)

	def testBan(self):
		aInfo = {
			'ip': "127.0.0.2",
			'failures': 3,
			'matches': "Test fail 1\n",
			'ipjailmatches': "Test fail 1\nTest Fail2\n",
			'ipmatches': "Test fail 1\nTest Fail2\nTest Fail3\n",
			}

		self.action.ban(aInfo)
		self.assertEqual(self.smtpd.mailfrom, "fail2ban")
		self.assertEqual(self.smtpd.rcpttos, ["root"])
		subject = "Subject: [Fail2Ban] %s: banned %s" % (
			self.jail.name, aInfo['ip'])
		self.assertIn(subject, self.smtpd.data)
		self.assertIn(
			"%i attempts" % aInfo['failures'], self.smtpd.data)

		self.action.matches = "matches"
		self.action.ban(aInfo)
		self.assertIn(aInfo['matches'], self.smtpd.data)

		self.action.matches = "ipjailmatches"
		self.action.ban(aInfo)
		self.assertIn(aInfo['ipjailmatches'], self.smtpd.data)

		self.action.matches = "ipmatches"
		self.action.ban(aInfo)
		self.assertIn(aInfo['ipmatches'], self.smtpd.data)

	def testOptions(self):
		self.action.start()
		self.assertEqual(self.smtpd.mailfrom, "fail2ban")
		self.assertEqual(self.smtpd.rcpttos, ["root"])

		self.action.fromname = "Test"
		self.action.fromaddr = "test@example.com"
		self.action.toaddr = "test@example.com, test2@example.com"
		self.action.start()
		self.assertEqual(self.smtpd.mailfrom, "test@example.com")
		self.assertTrue("From: %s <%s>" %
			(self.action.fromname, self.action.fromaddr) in self.smtpd.data)
		self.assertEqual(set(self.smtpd.rcpttos), set(["test@example.com", "test2@example.com"]))