Project

General

Profile

Download (15.8 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_radius($clientmac,$clientip) {
204
    global $config ;
205

    
206
    $radmac_secret = $config['captiveportal']['radmac_secret'];
207

    
208
    /* authentication against the radius server */
209
    $username = mac_format($clientmac);
210
    $auth_list = radius($username,$radmac_secret,$clientip,$clientmac,"MACHINE LOGIN");
211
    if ($auth_list['auth_val'] == 2) {
212
        return TRUE;
213
    }
214
    return FALSE;
215
}
216

    
217
function portal_allow($clientip,$clientmac,$username,$password = null, $attributes = null, $ruleno = null)  {
218

    
219
    global $redirurl, $g, $config, $url_redirection, $type;
220

    
221
    /* See if a ruleno is passed, if not start locking the sessions because this means there isn't one atm */
222
    if ($ruleno == null) {
223
        captiveportal_lock();
224
        $ruleno = captiveportal_get_next_ipfw_ruleno();
225
    }
226

    
227
    /* if the pool is empty, return appropriate message and exit */
228
    if (is_null($ruleno)) {
229
        portal_reply_page($redirurl, "error", "System reached maximum login capacity");
230
        log_error("WARNING!  Captive portal has reached maximum login capacity");
231
        captiveportal_unlock();
232
        exit;
233
    }
234

    
235
    // Ensure we create an array if we are missing attributes
236
    if (!is_array($attributes))
237
        $attributes = array();
238

    
239
    /* read in client database */
240
    $cpdb = captiveportal_read_db();
241

    
242
    $radiusservers = captiveportal_get_radius_servers();
243

    
244
    /* Find an existing session */
245
    for ($i = 0; $i < count($cpdb); $i++) {
246
        /* on the same ip */
247
        if($cpdb[$i][2] == $clientip) {
248
            captiveportal_logportalauth($cpdb[$i][4],$cpdb[$i][3],$cpdb[$i][2],"CONCURRENT LOGIN - REUSING OLD SESSION");
249
            $sessionid = $cpdb[$i][5];
250
            break;
251
        }
252
        elseif ((isset($config['captiveportal']['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
253
            /* on the same username */
254
            if ($cpdb[$i][4] == $username) {
255
                /* This user was already logged in so we disconnect the old one */
256
                captiveportal_disconnect($cpdb[$i],$radiusservers,13);
257
                captiveportal_logportalauth($cpdb[$i][4],$cpdb[$i][3],$cpdb[$i][2],"CONCURRENT LOGIN - TERMINATING OLD SESSION");
258
                unset($cpdb[$i]);
259
                break;
260
            }
261
        }
262
    }
263

    
264
    if (!isset($sessionid)) {
265

    
266
        /* generate unique session ID */
267
        $tod = gettimeofday();
268
        $sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
269

    
270
        /* Add rules for traffic shaping
271
         * We don't need to add extra l3 allow rules since traffic will pass due to the following kernel option
272
         * net.inet.ip.fw.one_pass: 1
273
         */
274
        $peruserbw = isset($config['captiveportal']['peruserbw']);
275

    
276
        $bw_up = isset($attributes['bw_up']) ? trim($attributes['bw_up']) : $config['captiveportal']['bwdefaultup'];
277
        $bw_down = isset($attributes['bw_down']) ? trim($attributes['bw_down']) : $config['captiveportal']['bwdefaultdn'];
278

    
279
        if ($peruserbw && !empty($bw_up) && is_numeric($bw_up)) {
280
            $bw_up_pipeno = $ruleno + 40500;
281
            exec("/sbin/ipfw add $ruleno set 2 pipe $bw_up_pipeno ip from $clientip to any in");
282
            exec("/sbin/ipfw pipe $bw_up_pipeno config bw {$bw_up}Kbit/s queue 100");
283
        } else {
284
            exec("/sbin/ipfw add $ruleno set 2 skipto 50000 ip from $clientip to any in");
285
        }
286
        if ($peruserbw && !empty($bw_down) && is_numeric($bw_down)) {
287
            $bw_down_pipeno = $ruleno + 45500;
288
            exec("/sbin/ipfw add $ruleno set 2 pipe $bw_down_pipeno ip from any to $clientip out");
289
            exec("/sbin/ipfw pipe $bw_down_pipeno config bw {$bw_down}Kbit/s queue 100");
290
        } else {
291
            exec("/sbin/ipfw add $ruleno set 2 skipto 50000 ip from any to $clientip out");
292
        }
293

    
294
        /* add ipfw rules for layer 2 */
295
        if (!isset($config['captiveportal']['nomacfilter'])) {
296
            $l2ruleno = $ruleno + 10000;
297
            exec("/sbin/ipfw add $l2ruleno set 3 deny all from $clientip to any not MAC any $clientmac layer2 in");
298
            exec("/sbin/ipfw add $l2ruleno set 3 deny all from any to $clientip not MAC $clientmac any layer2 out");
299
        }
300

    
301
        /* encode password in Base64 just in case it contains commas */
302
        $bpassword = base64_encode($password);
303
        $cpdb[] = array(time(), $ruleno, $clientip, $clientmac, $username, $sessionid, $bpassword,
304
                $attributes['session_timeout'],
305
                $attributes['idle_timeout'],
306
                $attributes['session_terminate_time']);
307

    
308
        if (isset($config['captiveportal']['radacct_enable']) && isset($radiusservers[0])) {
309
            $acct_val = RADIUS_ACCOUNTING_START($ruleno,
310
                                                            $username,
311
                                                            $sessionid,
312
                                                            $radiusservers[0]['ipaddr'],
313
                                                            $radiusservers[0]['acctport'],
314
                                                            $radiusservers[0]['key'],
315
                                                            $clientip,
316
                                                            $clientmac);
317

    
318
            if ($acct_val == 1)
319
                captiveportal_logportalauth($username,$clientmac,$clientip,$type,"RADIUS ACCOUNTING FAILED");
320
        }
321

    
322

    
323
    }
324

    
325
    /* rewrite information to database */
326
    captiveportal_write_db($cpdb);
327

    
328
    /* redirect user to desired destination */
329
    if ($url_redirection)
330
        $my_redirurl = $url_redirection;
331
    else if ($config['captiveportal']['redirurl'])
332
        $my_redirurl = $config['captiveportal']['redirurl'];
333
    else
334
        $my_redirurl = $redirurl;
335

    
336
    if(isset($config['captiveportal']['logoutwin_enable'])) {
337

    
338
        if (isset($config['captiveportal']['httpslogin']))
339
            $logouturl = "https://{$config['captiveportal']['httpsname']}:8001/";
340
        else
341
            $logouturl = "http://{$config['interfaces'][$config['captiveportal']['interface']]['ipaddr']}:8000/";
342

    
343
        echo <<<EOD
344
<HTML>
345
<HEAD><TITLE>Redirecting...</TITLE></HEAD>
346
<BODY>
347
<SPAN STYLE="font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
348
<B>Redirecting to <A HREF="{$my_redirurl}">{$my_redirurl}</A>...</B>
349
</SPAN>
350
<SCRIPT LANGUAGE="JavaScript">
351
<!--
352
LogoutWin = window.open('', 'Logout', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=256,height=64');
353
if (LogoutWin) {
354
    LogoutWin.document.write('<HTML>');
355
    LogoutWin.document.write('<HEAD><TITLE>Logout</TITLE></HEAD>') ;
356
    LogoutWin.document.write('<BODY BGCOLOR="#435370">');
357
    LogoutWin.document.write('<DIV ALIGN="center" STYLE="color: #ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">') ;
358
    LogoutWin.document.write('<B>Click the button below to disconnect</B><P>');
359
    LogoutWin.document.write('<FORM METHOD="POST" ACTION="{$logouturl}">');
360
    LogoutWin.document.write('<INPUT NAME="logout_id" TYPE="hidden" VALUE="{$sessionid}">');
361
    LogoutWin.document.write('<INPUT NAME="logout" TYPE="submit" VALUE="Logout">');
362
    LogoutWin.document.write('</FORM>');
363
    LogoutWin.document.write('</DIV></BODY>');
364
    LogoutWin.document.write('</HTML>');
365
    LogoutWin.document.close();
366
}
367

    
368
document.location.href="{$my_redirurl}";
369
-->
370
</SCRIPT>
371
</BODY>
372
</HTML>
373

    
374
EOD;
375
    } else {
376
		captiveportal_unlock();
377
        header("Location: " . $my_redirurl);
378
		return $sessionid;
379
    }
380
    captiveportal_unlock();
381
    return $sessionid;
382
}
383

    
384

    
385

    
386
/* remove a single client by session ID
387
   by Dinesh Nair
388
 */
389
function disconnect_client($sessionid, $logoutReason = "LOGOUT", $term_cause = 1) {
390

    
391
    global $g, $config;
392

    
393
    captiveportal_lock();
394
    /* read database */
395
    $cpdb = captiveportal_read_db();
396

    
397
    $radiusservers = captiveportal_get_radius_servers();
398

    
399
    /* find entry */
400
    for ($i = 0; $i < count($cpdb); $i++) {
401
        if ($cpdb[$i][5] == $sessionid) {
402
            captiveportal_disconnect($cpdb[$i],$radiusservers, $term_cause);
403
            captiveportal_logportalauth($cpdb[$i][4],$cpdb[$i][3],$cpdb[$i][2],$logoutReason);
404
            unset($cpdb[$i]);
405
            break;
406
        }
407
    }
408

    
409
    /* write database */
410
    captiveportal_write_db($cpdb);
411

    
412
    captiveportal_unlock();
413
}
414

    
415
?>
(1-1/3)