source: hybrid/branches/releng-9.0/nanobsd/files/usr/local/www/wlportal/index.cgi@ 10794

Last change on this file since 10794 was 10794, checked in by rick, 13 years ago

Houdt rekening met clients die af-en-toe disconnecten, je ziet hiervan
tijdelijk geen MAC.

Related-To: nodefactory:ticket:161

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 11.4 KB
Line 
1#!/usr/bin/env python
2#
3# Wrap me around tcpserver or inetd, example usage for tcpserver (debug):
4# tcpserver -HRl localhost 172.31.255.1 /root/wlportal.py
5#
6# Or put me in a CGI script in for example thttpd server:
7#
8# = Usage =
9# This is a wrapper script which does very basic HTML parsing and altering of
10# pfctl tables rules to build a basic Captive Portal, with basic sanity
11# checking. The ACL is IP based (this is a poor mans solution, layer2
12# ACL would be much better), so don't take security very seriously.
13#
14# To get traffic by default to the portal iI requires a few special rules in
15# pfctl to work properly:
16# no rdr on { $captive_ifs } proto tcp from <wlportal> to !$wl_net port 80
17# rdr on { $captive_ifs } proto tcp from $wl_net to !$wl_net port 80 -> 127.0.0.1 port 8082
18#
19# Enties older than 5 minutes not being used will be removed if the (hidden)
20# argument action=cleanup is given as GET variable. So having this in cron (would fix it):
21# */5 * * * * /usr/bin/fetch -q http://172.31.255.1/wlportal?action=cleanup
22#
23# XXX: The whitelist entries first needs to contact the wlportal.py to get
24# added to the whitelist, this may cause issues during initial setup and hence
25# it might be advised to create a block of static whitelist IP addresses which
26# get added during boot and will never disappear.
27#
28# State : v0.6.0
29# Version : $Id: index.cgi 10794 2012-05-12 16:30:11Z rick $
30# Author : Rick van der Zwet <info@rickvanderzwet.nl>
31# Licence : BSDLike http://wirelessleiden.nl/LICENSE
32import cgitb
33cgitb.enable(logdir="/tmp")
34
35
36import os
37import signal
38import subprocess
39import socket
40import sys
41import time
42import traceback
43import urlparse
44import yaml
45
46from jinja2 import Template
47
48# XXX: Make me dynamic for example put me in the conf file
49cfg = {
50 'autologin' : False,
51 'cmd_arp' : '/usr/sbin/arp',
52 'pfctl' : '/sbin/pfctl',
53 'portal_sponsor': 'Sponsor van Stichting Wireless Leiden',
54 'portal_url' : 'http://wirelessleiden.nl/welkom?connected_to=%s' % socket.gethostname(),
55 'portalroot' : '172.31.255.1',
56 'refresh_delay' : 3,
57 'tmpl_autologin': '/usr/local/etc/wlportal/autologin.tmpl',
58 'tmpl_login' : '/usr/local/etc/wlportal/login.tmpl',
59 'whitelist' : [],
60 'config_files' : ['/usr/local/etc/wlportal/config.yaml','/etc/wleiden.yaml'],
61 'expire_time' : None,
62 'accessdb' : '/var/db/clients',
63 'net_status' : '/tmp/network.status',
64}
65
66
67# No failback if config does not exist, to really make sure the user knows if
68# the config file failed to parse properly or is non-existing
69for config_file in cfg['config_files']:
70 if os.path.isfile(config_file):
71 cfg.update(yaml.load(open(config_file)))
72
73internet_up = True
74if os.path.isfile(cfg['net_status']):
75 internet_up = 'internet=up' in open(cfg['net_status'], 'r').read().lower()
76
77if not internet_up:
78 cfg['warning_msg'] = "<b>Internet Problemen</b>: De laatste 15 minuten zijn er problemen met de (internet) verbinding geconstateerd, de gebruikers ervaring kan dus niet optimaal zijn. Onze excuses voor het eventuele ongemak. Bij aanhoudende problemen kunt u contact opnemen met gebruikers@lijst.wirelessleiden.nl"
79
80def log_registered_host(remote_mac, remote_host):
81 """
82 Write statistics file, used for (nagios) monitoring purposes
83 """
84 with open(cfg['accessdb'],"a") as fh:
85 epoch = int(time.time())
86 fh.write("%s %s %s \n" % (epoch, remote_mac, remote_host) )
87
88class MACnotFound(Exception):
89 pass
90
91def get_mac(ipaddr):
92 """ Find out the MAC for a certain IP address """
93 try:
94 return subprocess.check_output(['/usr/sbin/arp', '-n' ,ipaddr], shell=False).split()[3][1:-1]
95 except subprocess.CalledProcessError:
96 raise MACnotFound
97
98def get_active_MACs():
99 """ Return dictionary with active IPs as keys """
100 output = subprocess.check_output(['/usr/sbin/arp', '-n' ,'-a'], shell=False)
101 db = {}
102 for line in output.strip().split('\n'):
103 i = line.split()
104 mac = i[3][1:-1]
105 ip = i[5]
106 db[ip] = mac
107 return db
108
109
110class PacketFilterControl():
111 """ Manage an Packet Filter using pfctl and table wlportal"""
112 def add(self, ipaddr):
113 """ Add Allow Entry in Firewall"""
114 output = subprocess.Popen([cfg['pfctl'],'-t','wlportal', '-T', 'add', ipaddr], stderr=subprocess.PIPE).communicate()[1]
115 is_added = '1/1 addresses added.' in output
116 return is_added
117 def delete(self, ipaddr):
118 """ Delete one Allow Entry to Firewall"""
119 output = subprocess.Popen([cfg['pfctl'],'-t','wlportal', '-T', 'delete', ipaddr], stderr=subprocess.PIPE).communicate()[1]
120 def flush(self):
121 """ Delete all Allow Entries from Firewall"""
122 output = subprocess.Popen([cfg['pfctl'],'-t','wlportal', '-T', 'flush'], stderr=subprocess.PIPE).communicate()[1]
123 #0 addresses deleted.
124 return int(output.strip().split('\n')[-1].split()[0])
125 def cleanup(self, expire_time=None):
126 """ Delete obsolete entries and expired entries from the Firewall"""
127 deleted_entries = 0
128 # Delete entries older than certain time
129 if expire_time:
130 output = subprocess.Popen([cfg['pfctl'],'-t','wlportal', '-T', 'expire', expire_time], stdout=subprocess.PIPE).communicate()[0]
131 # 0/0 addresses expired.
132 deleted_entries += int(output.strip.split()[-1].split('/')[0])
133
134 # Delete entries which the MAC<>IP mapping does no longer hold. The
135 # ``rogue'' clients, commonly seen when DHCP scope is small and IPs get
136 # re-used frequently, are wipped and require an re-connect.
137 stored_mac = {}
138 if os.path.isfile(cfg['accessdb']):
139 for line in open(cfg['accessdb'],'r'):
140 (epoch, mac, ipaddr) = line.split()
141 stored_mac[ipaddr] = mac
142 # Live configuration
143 active_mac = get_active_MACs()
144 # Process all active ip addresses from firewall and compare changes
145 output = subprocess.Popen([cfg['pfctl'],'-t','wlportal', '-T', 'show'], stdout=subprocess.PIPE).communicate()[0]
146 for ip in output.split():
147 if ip in cfg['whitelist']:
148 # IP is whitelisted
149 continue
150 elif active_mac.has_key(ip) and active_mac[ip] in cfg['whitelist']:
151 # MAC is whitelisted
152 continue
153 elif not active_mac.has_key(ip) and stored_mac.has_key(ip):
154 # In-active connection - Keep entry with normal expire time, as user
155 # might come back (temponary disconnect).
156 continue
157 elif active_mac.has_key(ip) and stored_mac.has_key(ip) and active_mac[ip] == stored_mac[ip]:
158 # Active connection - previous record found - Stored v.s. Active happy
159 continue
160 else:
161 self.delete(ip)
162 deleted_entries =+ 1
163 return deleted_entries
164
165
166# Call from crontab
167if sys.argv[1:]:
168 if sys.argv[1] == 'cleanup':
169 fw = PacketFilterControl()
170 fw.cleanup()
171 sys.exit(0)
172
173### BEGIN STANDALONE/CGI PARSING ###
174#
175# Query String Dictionaries
176qs_post = None
177qs = None
178header = []
179if not os.environ.has_key('REQUEST_METHOD'):
180 # a) We are not wrapped around in a HTTP server, so this _is_ the
181 # HTTP server, so act like one.
182 class TimeoutException(Exception):
183 """ Helper for alarm signal handling"""
184 pass
185
186 def handler(signum, frame):
187 """ Helper for alarm signal handling"""
188 raise TimeoutException
189
190
191 # Parse the HTTP/1.1 Content-Header (partially)
192 signal.signal(signal.SIGALRM,handler)
193 us = None
194 method = None
195 hostname = None
196 content_length = None
197 remote_host = None
198 while True:
199 try:
200 signal.alarm(1)
201 line = sys.stdin.readline().strip()
202 if not line:
203 break
204 header.append(line)
205 signal.alarm(0)
206 if line.startswith('GET '):
207 us = urlparse.urlsplit(line.split()[1])
208 method = 'GET'
209 elif line.startswith('POST '):
210 method = 'POST'
211 us = urlparse.urlsplit(line.split()[1])
212 elif line.startswith('Host: '):
213 hostname = line.split()[1]
214 elif line.startswith('Content-Length: '):
215 content_length = int(line.split()[1])
216 except TimeoutException:
217 break
218
219 # Capture Portal, make sure to redirect all to portal
220 if hostname != cfg['portalroot']:
221 print "HTTP/1.1 302 Moved Temponary\r\n",
222 print "Location: http://%(portalroot)s/\r\n" % cfg,
223 sys.exit(0)
224
225
226 # Handle potential POST
227 if method == 'POST' and content_length:
228 body = sys.stdin.read(content_length)
229 qs_post = urlparse.parse_qs(body)
230
231 # Parse Query String
232 if us and us.path == "/wlportal" and us.query:
233 qs = urlparse.parse_qs(us.query)
234
235 remote_host = os.environ['REMOTEHOST']
236else:
237 # b) CGI Script: Parse the CGI Variables if present
238 if os.environ['REQUEST_METHOD'] == "POST":
239 content_length = int(os.environ['CONTENT_LENGTH'])
240 body = sys.stdin.read(content_length)
241 qs_post = urlparse.parse_qs(body)
242
243 if os.environ.has_key('QUERY_STRING'):
244 qs = urlparse.parse_qs(os.environ['QUERY_STRING'])
245
246 remote_host = os.environ['REMOTE_ADDR']
247#
248### END STANDALONE/CGI PARSING ###
249
250
251# Helpers for HTML 'templates'
252content = cfg.copy()
253content.update(extra_header='')
254
255# IP or MAC on the whitelist does not need to authenticate, used for devices
256# which need to connect to the internet, but has no 'buttons' to press OK.
257#
258# This assumes that devices will re-connect if they are not able to connect
259# to their original host, as we do not preserve the original URI.
260remote_mac = get_mac(remote_host)
261if cfg['autologin'] or remote_host in cfg['whitelist'] or remote_mac in cfg['whitelist']:
262 qs_post = { 'action' : 'login' }
263
264try:
265 fw = PacketFilterControl()
266
267 # Put authenticate use and process response
268 if qs and qs.has_key('action'):
269 if 'flush' in qs['action']:
270 retval = fw.flush()
271 content['status_msg'] += "# [INFO] Deleted %s entries\n" % retval
272 elif 'update' in qs['action']:
273 tech_footer = "# [INFO] Update timestamp of all entries\n"
274 fw.update()
275 content['status_msg'] += fw.get_log()
276 elif 'cleanup' in qs['action']:
277 retval = fw.cleanup(cfg['expire_time'])
278 content['status_msg'] += "# [INFO] Deleted %s entries\n" % retval
279 elif qs_post and qs_post.has_key('action'):
280 if 'login' in qs_post['action']:
281 if fw.add(remote_host):
282 content['extra_header'] = "Refresh: %(refresh_delay)s; url=%(portal_url)s\r" % content
283 content['status_msg'] = "Sucessfully Logged In! || " +\
284 """ Will redirect you in %(refresh_delay)s seconds to <a href="%(portal_url)s">%(portal_url)s</a> """ % content
285 log_registered_host(remote_mac, remote_host)
286 else:
287 content['status_msg'] = "ERROR! Already Logged On"
288 elif 'logout' in qs_post['action']:
289 fw.delete(remote_host)
290 content['status_msg'] = "Succesfully logged out!"
291
292except Exception, e:
293 content['tech_footer'] += traceback.format_exc()
294 content['status_msg'] = "<div class='error'>Internal error!<pre>%s</pre></div>" % traceback.format_exc()
295 pass
296
297 # Present Main Screen
298print """\
299HTTP/1.1 200 OK\r
300Content-Type: text/html\r
301%(extra_header)s
302""" % content
303
304try:
305 tmpl_file = cfg['tmpl_autologin'] if cfg['autologin'] else cfg['tmpl_login']
306 page = open(tmpl_file,'r').read()
307except IOError:
308 page = """
309<html><head></head><body>
310<h2>%(status_msg)s</h2>
311
312<h3>Wireless Leiden - Internet Portal</h3>
313<form action="http://%(portalroot)s/wlportal/" method="POST">
314<input name="action" type="hidden" value="login" />
315<input type="submit" value="OK, agreed" />
316</form>
317
318<h3>More options</h3>
319<form action="http://%(portalroot)s/wlportal/" method="POST">
320<input name="action" type="hidden" value="logout" />
321<input type="submit" value="Cancel and/or Logout" />
322</form>
323<hr /><em>Technical Details:</em><pre>
324%(tech_footer)s
325</pre>
326</body></html>
327"""
328
329print Template(page).render(content)
Note: See TracBrowser for help on using the repository browser.