Project

General

Profile

Download (16.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
    $Id$
4
    part of m0n0wall (http://m0n0.ch/wall)
5

    
6
    Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
7
    All rights reserved.
8

    
9
    Redistribution and use in source and binary forms, with or without
10
    modification, are permitted provided that the following conditions are met:
11

    
12
    1. Redistributions of source code must retain the above copyright notice,
13
       this list of conditions and the following disclaimer.
14

    
15
    2. Redistributions in binary form must reproduce the above copyright
16
       notice, this list of conditions and the following disclaimer in the
17
       documentation and/or other materials provided with the distribution.
18

    
19
    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
20
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
21
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
23
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
    POSSIBILITY OF SUCH DAMAGE.
29
*/
30

    
31
require_once("functions.inc");
32

    
33
header("Expires: 0");
34
header("Cache-Control: no-store, no-cache, must-revalidate");
35
header("Cache-Control: post-check=0, pre-check=0", false);
36
header("Pragma: no-cache");
37

    
38
$orig_host = $_ENV['HTTP_HOST'];
39
$orig_request = $_GET['redirurl'];
40
$clientip = $_SERVER['REMOTE_ADDR'];
41

    
42
if (!$clientip) {
43
    /* not good - bail out */
44
    echo "An error occured.  Please check the system logs for more information.";
45
    log_error("Captive portal could not deterimine clients ip address.");
46
    exit;
47
}
48

    
49
if (isset($config['captiveportal']['httpslogin']))
50
    $ourhostname = $config['captiveportal']['httpsname'] . ":8001";
51
else
52
    $ourhostname = $config['interfaces'][$config['captiveportal']['interface']]['ipaddr'] . ":8000";
53

    
54
if ($orig_host != $ourhostname) {
55
    /* the client thinks it's connected to the desired web server, but instead
56
       it's connected to us. Issue a redirect... */
57

    
58
    if (isset($config['captiveportal']['httpslogin']))
59
        header("Location: https://{$ourhostname}/index.php?redirurl=" . urlencode("http://{$orig_host}{$orig_request}"));
60
    else
61
        header("Location: http://{$ourhostname}/index.php?redirurl=" . urlencode("http://{$orig_host}{$orig_request}"));
62

    
63
    exit;
64
}
65

    
66
if (preg_match("/redirurl=(.*)/", $orig_request, $matches))
67
    $redirurl = urldecode($matches[1]);
68
if ($_POST['redirurl'])
69
    $redirurl = $_POST['redirurl'];
70

    
71
$macfilter = !isset($config['captiveportal']['nomacfilter']);
72

    
73
/* find MAC address for client */
74
$clientmac = arp_get_mac_by_ip($clientip);
75
if (!$clientmac && $macfilter) {
76
    /* unable to find MAC address - shouldn't happen! - bail out */
77
    captiveportal_logportalauth("unauthenticated","noclientmac",$clientip,"ERROR");
78
    echo "An error occured.  Please check the system logs for more information.";
79
    log_error("Captive portal could not deterimine clients MAC address.  Disable MAC address filtering in captive portal if you do not needs this functionality.");
80
    exit;
81
}
82

    
83
/* find out if we need RADIUS + RADIUSMAC or not */
84
if (file_exists("{$g['vardb_path']}/captiveportal_radius.db")) {
85
    $radius_enable = TRUE;
86
    if ($radius_enable && isset($config['captiveportal']['radmac_enable']))
87
        $radmac_enable = TRUE;
88
}
89

    
90
if ($_POST['logout_id']) {
91
    disconnect_client($_POST['logout_id']);
92
    echo <<<EOD
93
<HTML>
94
<HEAD><TITLE>Disconnecting...</TITLE></HEAD>
95
<BODY BGCOLOR="#435370">
96
<SPAN STYLE="color: #ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
97
<B>You have been disconnected.</B>
98
</SPAN>
99
<SCRIPT LANGUAGE="JavaScript">
100
<!--
101
setTimeout('window.close();',5000) ;
102
-->
103
</SCRIPT>
104
</BODY>
105
</HTML>
106

    
107
EOD;
108
/* The $macfilter can be removed safely since we first check if the $clientmac is present, if not we fail */
109
} else if ($clientmac && portal_mac_fixed($clientmac)) {
110
    /* punch hole in ipfw for pass thru mac addresses */
111
    portal_allow($clientip, $clientmac, "unauthenticated");
112
    exit;
113

    
114
} else if ($clientmac && $radmac_enable && portal_mac_radius($clientmac,$clientip)) {
115
    /* radius functions handle everything so we exit here since we're done */
116
    exit;
117

    
118
} else if ($_POST['accept'] && $radius_enable) {
119

    
120
    if ($_POST['auth_user'] && $_POST['auth_pass']) {
121
        $auth_list = radius($_POST['auth_user'],$_POST['auth_pass'],$clientip,$clientmac,"USER LOGIN");
122

    
123
        if ($auth_list['auth_val'] == 1) {
124
            captiveportal_logportalauth($_POST['auth_user'],$clientmac,$clientip,"ERROR",$auth_list['error']);
125
            portal_reply_page($redirurl, "error", $auth_list['error']);
126
        }
127
        else if ($auth_list['auth_val'] == 3) {
128
            captiveportal_logportalauth($_POST['auth_user'],$clientmac,$clientip,"FAILURE",$auth_list['reply_message']);
129
            portal_reply_page($redirurl, "error", $auth_list['reply_message']);
130
        }
131
    } else {
132
        captiveportal_logportalauth($_POST['auth_user'],$clientmac,$clientip,"ERROR");
133
        portal_reply_page($redirurl, "error");
134
    }
135

    
136
} else if ($_POST['accept'] && $config['captiveportal']['auth_method'] == "local") {
137

    
138
    //check against local usermanager
139
    $userdb = &$config['captiveportal']['user'];
140

    
141
    $loginok = false;
142

    
143
    //erase expired accounts
144
    if (is_array($userdb)) {
145
        $moddb = false;
146
        for ($i = 0; $i < count($userdb); $i++) {
147
            if ($userdb[$i]['expirationdate'] && (strtotime("-1 day") > strtotime($userdb[$i]['expirationdate']))) {
148
                unset($userdb[$i]);
149
                $moddb = true;
150
            }
151
        }
152
        if ($moddb)
153
            write_config();
154

    
155
        $userdb = &$config['captiveportal']['user'];
156

    
157
        for ($i = 0; $i < count($userdb); $i++) {
158
            if (($userdb[$i]['name'] == $_POST['auth_user']) && ($userdb[$i]['password'] == md5($_POST['auth_pass']))) {
159
                $loginok = true;
160
                break;
161
            }
162
        }
163
    }
164

    
165
    if ($loginok){
166
        captiveportal_logportalauth($_POST['auth_user'],$clientmac,$clientip,"LOGIN");
167
        portal_allow($clientip, $clientmac,$_POST['auth_user']);
168
    } else {
169
        captiveportal_logportalauth($_POST['auth_user'],$clientmac,$clientip,"FAILURE");
170
        portal_reply_page($redirurl, "error");
171
    }
172
} else if ($_POST['accept'] && $clientip) {
173
    captiveportal_logportalauth("unauthenticated",$clientmac,$clientip,"ACCEPT");
174
    portal_allow($clientip, $clientmac, "unauthenticated");
175
} else {
176
    /* display captive portal page */
177
    portal_reply_page($redirurl, "login");
178
}
179

    
180
exit;
181

    
182
function portal_reply_page($redirurl, $type = null, $message = null) {
183
    global $g, $config;
184

    
185
    /* Get captive portal layout */
186
    if ($type == "login")
187
        $htmltext = file_get_contents("{$g['varetc_path']}/captiveportal.html");
188
    else
189
        $htmltext = file_get_contents("{$g['varetc_path']}/captiveportal-error.html");
190

    
191
    /* substitute other variables */
192
    if (isset($config['captiveportal']['httpslogin']))
193
        $htmltext = str_replace("\$PORTAL_ACTION\$", "https://{$config['captiveportal']['httpsname']}:8001/", $htmltext);
194
    else
195
        $htmltext = str_replace("\$PORTAL_ACTION\$", "http://{$config['interfaces'][$config['captiveportal']['interface']]['ipaddr']}:8000/", $htmltext);
196

    
197
    $htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
198
    $htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
199

    
200
    echo $htmltext;
201
}
202

    
203
function portal_mac_fixed($clientmac) {
204
    global $g ;
205

    
206
    /* open captive portal mac db */
207
    if (file_exists("{$g['vardb_path']}/captiveportal_mac.db")) {
208
        $fd = @fopen("{$g['vardb_path']}/captiveportal_mac.db","r") ;
209
        if (!$fd) {
210
            return FALSE;
211
        }
212
        while (!feof($fd)) {
213
            $mac = trim(fgets($fd)) ;
214
            if(strcasecmp($clientmac, $mac) == 0) {
215
                fclose($fd) ;
216
                return TRUE ;
217
            }
218
        }
219
        fclose($fd) ;
220
    }
221
    return FALSE ;
222
}
223

    
224
function portal_mac_radius($clientmac,$clientip) {
225
    global $config ;
226

    
227
    $radmac_secret = $config['captiveportal']['radmac_secret'];
228

    
229
    /* authentication against the radius server */
230
    $username = mac_format($clientmac);
231
    $auth_list = radius($username,$radmac_secret,$clientip,$clientmac,"MACHINE LOGIN");
232
    if ($auth_list['auth_val'] == 2) {
233
        return TRUE;
234
    }
235
    return FALSE;
236
}
237

    
238
function portal_allow($clientip,$clientmac,$username,$password = null, $attributes = null, $ruleno = null)  {
239

    
240
    global $redirurl, $g, $config, $url_redirection, $type;
241

    
242
    /* See if a ruleno is passed, if not start locking the sessions because this means there isn't one atm */
243
    if ($ruleno == null) {
244
        captiveportal_lock();
245
        $ruleno = captiveportal_get_next_ipfw_ruleno();
246
    }
247

    
248
    /* if the pool is empty, return appropriate message and exit */
249
    if (is_null($ruleno)) {
250
        portal_reply_page($redirurl, "error", "System reached maximum login capacity");
251
        log_error("WARNING!  Captive portal has reached maximum login capacity");
252
        captiveportal_unlock();
253
        exit;
254
    }
255

    
256
    // Ensure we create an array if we are missing attributes
257
    if (!is_array($attributes))
258
        $attributes = array();
259

    
260
    /* read in client database */
261
    $cpdb = captiveportal_read_db();
262

    
263
    $radiusservers = captiveportal_get_radius_servers();
264

    
265
    /* Find an existing session */
266
    for ($i = 0; $i < count($cpdb); $i++) {
267
        /* on the same ip */
268
        if($cpdb[$i][2] == $clientip) {
269
            captiveportal_logportalauth($cpdb[$i][4],$cpdb[$i][3],$cpdb[$i][2],"CONCURRENT LOGIN - REUSING OLD SESSION");
270
            $sessionid = $cpdb[$i][5];
271
            break;
272
        }
273
        elseif ((isset($config['captiveportal']['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
274
            /* on the same username */
275
            if ($cpdb[$i][4] == $username) {
276
                /* This user was already logged in so we disconnect the old one */
277
                captiveportal_disconnect($cpdb[$i],$radiusservers,13);
278
                captiveportal_logportalauth($cpdb[$i][4],$cpdb[$i][3],$cpdb[$i][2],"CONCURRENT LOGIN - TERMINATING OLD SESSION");
279
                unset($cpdb[$i]);
280
                break;
281
            }
282
        }
283
    }
284

    
285
    if (!isset($sessionid)) {
286

    
287
        /* generate unique session ID */
288
        $tod = gettimeofday();
289
        $sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
290

    
291
        /* Add rules for traffic shaping
292
         * We don't need to add extra l3 allow rules since traffic will pass due to the following kernel option
293
         * net.inet.ip.fw.one_pass: 1
294
         */
295
        $peruserbw = isset($config['captiveportal']['peruserbw']);
296

    
297
        $bw_up = isset($attributes['bw_up']) ? trim($attributes['bw_up']) : $config['captiveportal']['bwdefaultup'];
298
        $bw_down = isset($attributes['bw_down']) ? trim($attributes['bw_down']) : $config['captiveportal']['bwdefaultdn'];
299

    
300
        if ($peruserbw && !empty($bw_up) && is_numeric($bw_up)) {
301
            $bw_up_pipeno = $ruleno + 40500;
302
            exec("/sbin/ipfw add $ruleno set 2 pipe $bw_up_pipeno ip from $clientip to any in");
303
            exec("/sbin/ipfw pipe $bw_up_pipeno config bw {$bw_up}Kbit/s queue 100");
304
        } else {
305
            exec("/sbin/ipfw add $ruleno set 2 skipto 50000 ip from $clientip to any in");
306
        }
307
        if ($peruserbw && !empty($bw_down) && is_numeric($bw_down)) {
308
            $bw_down_pipeno = $ruleno + 45500;
309
            exec("/sbin/ipfw add $ruleno set 2 pipe $bw_down_pipeno ip from any to $clientip out");
310
            exec("/sbin/ipfw pipe $bw_down_pipeno config bw {$bw_down}Kbit/s queue 100");
311
        } else {
312
            exec("/sbin/ipfw add $ruleno set 2 skipto 50000 ip from any to $clientip out");
313
        }
314

    
315
        /* add ipfw rules for layer 2 */
316
        if (!isset($config['captiveportal']['nomacfilter'])) {
317
            $l2ruleno = $ruleno + 10000;
318
            exec("/sbin/ipfw add $l2ruleno set 3 deny all from $clientip to any not MAC any $clientmac layer2 in");
319
            exec("/sbin/ipfw add $l2ruleno set 3 deny all from any to $clientip not MAC $clientmac any layer2 out");
320
        }
321

    
322
        /* encode password in Base64 just in case it contains commas */
323
        $bpassword = base64_encode($password);
324
        $cpdb[] = array(time(), $ruleno, $clientip, $clientmac, $username, $sessionid, $bpassword,
325
                $attributes['session_timeout'],
326
                $attributes['idle_timeout'],
327
                $attributes['session_terminate_time']);
328

    
329
        if (isset($config['captiveportal']['radacct_enable']) && isset($radiusservers[0])) {
330
            $acct_val = RADIUS_ACCOUNTING_START($ruleno,
331
                                                            $username,
332
                                                            $sessionid,
333
                                                            $radiusservers[0]['ipaddr'],
334
                                                            $radiusservers[0]['acctport'],
335
                                                            $radiusservers[0]['key'],
336
                                                            $clientip,
337
                                                            $clientmac);
338

    
339
            if(!$type)                                                
340
				log_error("WARNING: \$type has not been set in captiveportal/index.php");                                                            
341
                                                            
342
            if ($acct_val == 1)
343
                captiveportal_logportalauth($username,$clientmac,$clientip,$type,"RADIUS ACCOUNTING FAILED");
344
        }
345

    
346

    
347
    }
348

    
349
    /* rewrite information to database */
350
    captiveportal_write_db($cpdb);
351

    
352
    /* redirect user to desired destination */
353
    if ($url_redirection)
354
        $my_redirurl = $url_redirection;
355
    else if ($config['captiveportal']['redirurl'])
356
        $my_redirurl = $config['captiveportal']['redirurl'];
357
    else
358
        $my_redirurl = $redirurl;
359

    
360
    if(isset($config['captiveportal']['logoutwin_enable'])) {
361

    
362
        if (isset($config['captiveportal']['httpslogin']))
363
            $logouturl = "https://{$config['captiveportal']['httpsname']}:8001/";
364
        else
365
            $logouturl = "http://{$config['interfaces'][$config['captiveportal']['interface']]['ipaddr']}:8000/";
366

    
367
        echo <<<EOD
368
<HTML>
369
<HEAD><TITLE>Redirecting...</TITLE></HEAD>
370
<BODY>
371
<SPAN STYLE="font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
372
<B>Redirecting to <A HREF="{$my_redirurl}">{$my_redirurl}</A>...</B>
373
</SPAN>
374
<SCRIPT LANGUAGE="JavaScript">
375
<!--
376
LogoutWin = window.open('', 'Logout', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=256,height=64');
377
if (LogoutWin) {
378
    LogoutWin.document.write('<HTML>');
379
    LogoutWin.document.write('<HEAD><TITLE>Logout</TITLE></HEAD>') ;
380
    LogoutWin.document.write('<BODY BGCOLOR="#435370">');
381
    LogoutWin.document.write('<DIV ALIGN="center" STYLE="color: #ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">') ;
382
    LogoutWin.document.write('<B>Click the button below to disconnect</B><P>');
383
    LogoutWin.document.write('<FORM METHOD="POST" ACTION="{$logouturl}">');
384
    LogoutWin.document.write('<INPUT NAME="logout_id" TYPE="hidden" VALUE="{$sessionid}">');
385
    LogoutWin.document.write('<INPUT NAME="logout" TYPE="submit" VALUE="Logout">');
386
    LogoutWin.document.write('</FORM>');
387
    LogoutWin.document.write('</DIV></BODY>');
388
    LogoutWin.document.write('</HTML>');
389
    LogoutWin.document.close();
390
}
391

    
392
document.location.href="{$my_redirurl}";
393
-->
394
</SCRIPT>
395
</BODY>
396
</HTML>
397

    
398
EOD;
399
    } else {
400
        header("Location: " . $my_redirurl);
401
    }
402

    
403
    captiveportal_unlock();
404
    return $sessionid;
405
}
406

    
407

    
408

    
409
/* remove a single client by session ID
410
   by Dinesh Nair
411
 */
412
function disconnect_client($sessionid, $logoutReason = "LOGOUT", $term_cause = 1) {
413

    
414
    global $g, $config;
415

    
416
    captiveportal_lock();
417
    /* read database */
418
    $cpdb = captiveportal_read_db();
419

    
420
    $radiusservers = captiveportal_get_radius_servers();
421

    
422
    /* find entry */
423
    for ($i = 0; $i < count($cpdb); $i++) {
424
        if ($cpdb[$i][5] == $sessionid) {
425
            captiveportal_disconnect($cpdb[$i],$radiusservers, $term_cause);
426
            captiveportal_logportalauth($cpdb[$i][4],$cpdb[$i][3],$cpdb[$i][2],$logoutReason);
427
            unset($cpdb[$i]);
428
            break;
429
        }
430
    }
431

    
432
    /* write database */
433
    captiveportal_write_db($cpdb);
434

    
435
    captiveportal_unlock();
436
}
437

    
438
?>
(1-1/3)