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

Last change on this file since 10725 was 10725, checked in by rick, 14 years ago

Laad ook de wleiden.yaml zodat hier de portal_url in gezet kan worden.

Related-To: nodefactory#154

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 11.1 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 10725 2012-05-08 18:11:40Z 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 stored_mac.has_key(ip) and active_mac[ip] == stored_mac[ip]:
154 # previous record found
155 # Stored v.s. Active happy
156 continue
157 else:
158 self.delete(ip)
159 deleted_entries =+ 1
160 return deleted_entries
161
162
163# Call from crontab
164if sys.argv[1:]:
165 if sys.argv[1] == 'cleanup':
166 fw = PacketFilterControl()
167 fw.cleanup()
168 sys.exit(0)
169
170### BEGIN STANDALONE/CGI PARSING ###
171#
172# Query String Dictionaries
173qs_post = None
174qs = None
175header = []
176if not os.environ.has_key('REQUEST_METHOD'):
177 # a) We are not wrapped around in a HTTP server, so this _is_ the
178 # HTTP server, so act like one.
179 class TimeoutException(Exception):
180 """ Helper for alarm signal handling"""
181 pass
182
183 def handler(signum, frame):
184 """ Helper for alarm signal handling"""
185 raise TimeoutException
186
187
188 # Parse the HTTP/1.1 Content-Header (partially)
189 signal.signal(signal.SIGALRM,handler)
190 us = None
191 method = None
192 hostname = None
193 content_length = None
194 remote_host = None
195 while True:
196 try:
197 signal.alarm(1)
198 line = sys.stdin.readline().strip()
199 if not line:
200 break
201 header.append(line)
202 signal.alarm(0)
203 if line.startswith('GET '):
204 us = urlparse.urlsplit(line.split()[1])
205 method = 'GET'
206 elif line.startswith('POST '):
207 method = 'POST'
208 us = urlparse.urlsplit(line.split()[1])
209 elif line.startswith('Host: '):
210 hostname = line.split()[1]
211 elif line.startswith('Content-Length: '):
212 content_length = int(line.split()[1])
213 except TimeoutException:
214 break
215
216 # Capture Portal, make sure to redirect all to portal
217 if hostname != cfg['portalroot']:
218 print "HTTP/1.1 302 Moved Temponary\r\n",
219 print "Location: http://%(portalroot)s/\r\n" % cfg,
220 sys.exit(0)
221
222
223 # Handle potential POST
224 if method == 'POST' and content_length:
225 body = sys.stdin.read(content_length)
226 qs_post = urlparse.parse_qs(body)
227
228 # Parse Query String
229 if us and us.path == "/wlportal" and us.query:
230 qs = urlparse.parse_qs(us.query)
231
232 remote_host = os.environ['REMOTEHOST']
233else:
234 # b) CGI Script: Parse the CGI Variables if present
235 if os.environ['REQUEST_METHOD'] == "POST":
236 content_length = int(os.environ['CONTENT_LENGTH'])
237 body = sys.stdin.read(content_length)
238 qs_post = urlparse.parse_qs(body)
239
240 if os.environ.has_key('QUERY_STRING'):
241 qs = urlparse.parse_qs(os.environ['QUERY_STRING'])
242
243 remote_host = os.environ['REMOTE_ADDR']
244#
245### END STANDALONE/CGI PARSING ###
246
247
248# Helpers for HTML 'templates'
249content = cfg.copy()
250content.update(extra_header='')
251
252# IP or MAC on the whitelist does not need to authenticate, used for devices
253# which need to connect to the internet, but has no 'buttons' to press OK.
254#
255# This assumes that devices will re-connect if they are not able to connect
256# to their original host, as we do not preserve the original URI.
257remote_mac = get_mac(remote_host)
258if cfg['autologin'] or remote_host in cfg['whitelist'] or remote_mac in cfg['whitelist']:
259 qs_post = { 'action' : 'login' }
260
261try:
262 fw = PacketFilterControl()
263
264 # Put authenticate use and process response
265 if qs and qs.has_key('action'):
266 if 'flush' in qs['action']:
267 retval = fw.flush()
268 content['status_msg'] += "# [INFO] Deleted %s entries\n" % retval
269 elif 'update' in qs['action']:
270 tech_footer = "# [INFO] Update timestamp of all entries\n"
271 fw.update()
272 content['status_msg'] += fw.get_log()
273 elif 'cleanup' in qs['action']:
274 retval = fw.cleanup(cfg['expire_time'])
275 content['status_msg'] += "# [INFO] Deleted %s entries\n" % retval
276 elif qs_post and qs_post.has_key('action'):
277 if 'login' in qs_post['action']:
278 if fw.add(remote_host):
279 content['extra_header'] = "Refresh: %(refresh_delay)s; url=%(portal_url)s\r" % content
280 content['status_msg'] = "Sucessfully Logged In! || " +\
281 """ Will redirect you in %(refresh_delay)s seconds to <a href="%(portal_url)s">%(portal_url)s</a> """ % content
282 log_registered_host(remote_mac, remote_host)
283 else:
284 content['status_msg'] = "ERROR! Already Logged On"
285 elif 'logout' in qs_post['action']:
286 fw.delete(remote_host)
287 content['status_msg'] = "Succesfully logged out!"
288
289except Exception, e:
290 content['tech_footer'] += traceback.format_exc()
291 content['status_msg'] = "<div class='error'>Internal error!<pre>%s</pre></div>" % traceback.format_exc()
292 pass
293
294 # Present Main Screen
295print """\
296HTTP/1.1 200 OK\r
297Content-Type: text/html\r
298%(extra_header)s
299""" % content
300
301try:
302 tmpl_file = cfg['tmpl_autologin'] if cfg['autologin'] else cfg['tmpl_login']
303 page = open(tmpl_file,'r').read()
304except IOError:
305 page = """
306<html><head></head><body>
307<h2>%(status_msg)s</h2>
308
309<h3>Wireless Leiden - Internet Portal</h3>
310<form action="http://%(portalroot)s/wlportal/" method="POST">
311<input name="action" type="hidden" value="login" />
312<input type="submit" value="OK, agreed" />
313</form>
314
315<h3>More options</h3>
316<form action="http://%(portalroot)s/wlportal/" method="POST">
317<input name="action" type="hidden" value="logout" />
318<input type="submit" value="Cancel and/or Logout" />
319</form>
320<hr /><em>Technical Details:</em><pre>
321%(tech_footer)s
322</pre>
323</body></html>
324"""
325
326print Template(page).render(content)
Note: See TracBrowser for help on using the repository browser.