Project

General

Profile

Download (19.3 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
	Copyright (C) 2010 Ermal Luci <ermal.luci@gmail.com>
4
	Copyright (C) 2010 Scott Ullrich <sullrich@gmail.com>
5
    Copyright (C) 2007 Marcel Wiget <mwiget@mac.com>
6
    All rights reserved.
7
    
8
    Redistribution and use in source and binary forms, with or without
9
    modification, are permitted provided that the following conditions are met:
10
    
11
    1. Redistributions of source code must retain the above copyright notice,
12
       this list of conditions and the following disclaimer.
13
    
14
    2. Redistributions in binary form must reproduce the above copyright
15
       notice, this list of conditions and the following disclaimer in the
16
       documentation and/or other materials provided with the distribution.
17
    
18
    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
19
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
20
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
22
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
    POSSIBILITY OF SUCH DAMAGE.
28

    
29
*/
30

    
31
/*
32
	pfSense_BUILDER_BINARIES:	/usr/local/bin/voucher	/usr/local/bin/minicron
33
	pfSense_MODULE:	captiveportal
34
*/
35

    
36
/* include all configuration functions */
37
if(!function_exists('captiveportal_syslog'))
38
	require_once("captiveportal.inc");
39

    
40
function xmlrpc_sync_voucher_disconnect($dbent, $syncip, $port, $password, $username, $term_cause = "1", $stop_time = null) {
41
	global $g, $config;
42
	require_once("xmlrpc.inc");
43
	if($port == "443") 
44
		$url = "https://{$syncip}";
45
	else 
46
		$url = "http://{$syncip}";
47

    
48
	/* Construct code that is run on remote machine */
49
	$method = 'pfsense.exec_php';
50
	$execcmd  = <<<EOF
51
	require_once('/etc/inc/captiveportal.inc');
52
	require_once('/etc/inc/voucher.inc');
53
	\$radiusservers = captiveportal_get_radius_servers();
54
	captiveportal_disconnect(\$dbent, \$radiusservers, \$term_cause, \$stop_time);
55

    
56
EOF;
57

    
58
	/* assemble xmlrpc payload */
59
	$params = array(
60
		XML_RPC_encode($password),
61
		XML_RPC_encode($execcmd)
62
	);
63

    
64
	log_error("Captive Portal Voucher XMLRPC sync data {$url}:{$port}.");
65
	$msg = new XML_RPC_Message($method, $params);
66
	$cli = new XML_RPC_Client('/xmlrpc.php', $url, $port);
67
	$cli->setCredentials($username, $password);
68
	$resp = $cli->send($msg, "250");
69
	if(!is_object($resp)) {
70
		$error = "A communications error occurred while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} (pfsense.exec_php).";
71
		log_error($error);
72
		file_notice("CaptivePortalVoucherSync", $error, "Communications error occurred", "");
73
		return false;
74
	} elseif($resp->faultCode()) {
75
		$error = "An error code was received while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString();
76
		log_error($error);
77
		file_notice("CaptivePortalVoucherSync", $error, "Error code received", "");
78
		return false;
79
	} else {
80
		log_error("CaptivePortalVoucherSync XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php).");
81
	}
82

    
83
	$toreturn =  XML_RPC_Decode($resp->value());
84

    
85
	return $toreturn;
86
}
87

    
88
function xmlrpc_sync_used_voucher($voucher_received, $syncip, $port, $password, $username) {
89
	global $g, $config;
90
	require_once("xmlrpc.inc");
91
	if($port == "443") 
92
		$url = "https://{$syncip}";
93
	else 
94
		$url = "http://{$syncip}";
95

    
96
	/* Construct code that is run on remote machine */
97
	$method = 'pfsense.exec_php';
98
	$execcmd  = <<<EOF
99
	require_once('/etc/inc/voucher.inc');
100
	\$timeleft = voucher_auth({$voucher_received});
101
	\$toreturn = array();
102
	\$toreturn['timeleft'] = \$timeleft;
103
	\$toreturn['voucher']['roll'] = \$config['voucher']['roll'];
104

    
105
EOF;
106

    
107
	/* assemble xmlrpc payload */
108
	$params = array(
109
		XML_RPC_encode($password),
110
		XML_RPC_encode($execcmd)
111
	);
112

    
113
	log_error("Captive Portal Voucher XMLRPC sync data {$url}:{$port}.");
114
	$msg = new XML_RPC_Message($method, $params);
115
	$cli = new XML_RPC_Client('/xmlrpc.php', $url, $port);
116
	$cli->setCredentials($username, $password);
117
	$resp = $cli->send($msg, "250");
118
	if(!is_object($resp)) {
119
		$error = "A communications error occurred while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} (pfsense.exec_php).";
120
		log_error($error);
121
		file_notice("CaptivePortalVoucherSync", $error, "Communications error occurred", "");
122
		return array("timeleft" => "0");
123
	} elseif($resp->faultCode()) {
124
		$error = "An error code was received while attempting CaptivePortalVoucherSync XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString();
125
		log_error($error);
126
		file_notice("CaptivePortalVoucherSync", $error, "Error code received", "");
127
		return array("timeleft" => "0");
128
	} else {
129
		log_error("CaptivePortalVoucherSync XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php).");
130
	}
131
	$toreturn =  XML_RPC_Decode($resp->value());
132
	if(count($toreturn['voucher']['roll']) <> count($config['voucher']['roll'])) {
133
		$config['voucher']['roll'] = $toreturn['voucher']['roll'];
134
		write_config("Captive Portal Voucher database synchronized with {$url}");
135
		voucher_configure(true);
136
	}
137

    
138
	return $toreturn['timeleft'];
139
}
140

    
141
/* 
142
 * Authenticate a voucher and return the remaining time credit in minutes
143
 * if $test is set, don't mark the voucher as used nor add it to the list
144
 * of active vouchers
145
 * If $test is set, simply test the voucher. Don't change anything
146
 * but return a more verbose error and result message back
147
 */
148
function voucher_auth($voucher_received, $test = 0) {
149
    global $g, $config;
150

    
151
    $voucherlck = lock('voucher', LOCK_EX);
152

    
153
	// XMLRPC Call over to the master Voucher node
154
	$a_voucher = &$config['voucher'];
155
	if(!empty($a_voucher['vouchersyncdbip'])) {
156
		$syncip   = $a_voucher['vouchersyncdbip'];
157
		$syncport = $a_voucher['vouchersyncport'];
158
		$syncpass = $a_voucher['vouchersyncpass'];
159
		$vouchersyncusername = $a_voucher['vouchersyncusername'];
160
		$remote_time_used = xmlrpc_sync_used_voucher($voucher_received, $syncip, $syncport, $syncpass, $vouchersyncusername);
161
	}
162

    
163
	// read rolls into assoc array with rollid as key and minutes as value
164
	$tickets_per_roll = array();
165
	$minutes_per_roll = array();
166
	if (is_array($config['voucher']['roll'])) {
167
		$a_roll = &$config['voucher']['roll'];
168
		foreach ($a_roll as $rollent) {
169
			$tickets_per_roll[$rollent['number']] = $rollent['count'];
170
			$minutes_per_roll[$rollent['number']] = $rollent['minutes'];
171
		}
172
	}
173

    
174
    // split into an array. Useful for multiple vouchers given
175
    $a_vouchers_received = split("[\t\n\r ]+",$voucher_received); 
176
    $error = 0;
177
    $test_result = array();     // used to display for voucher test option in GUI
178
    $total_minutes = 0;
179
    $first_voucher = "";
180
    $first_voucher_roll = 0;
181

    
182
    // go through all received vouchers, check their valid and extract
183
    // Roll# and Ticket# using the external readvoucher binary
184

    
185
    foreach ($a_vouchers_received as $voucher) {
186

    
187
        $v = escapeshellarg($voucher);
188
        if (strlen($voucher) < 3)
189
            continue;   // seems too short to be a voucher!
190

    
191
        $result = exec("/usr/local/bin/voucher -c {$g['varetc_path']}/voucher.cfg -k {$g['varetc_path']}/voucher.public -- $v");
192
        list($status, $roll, $nr) = explode(" ", $result);
193
        if ($status == "OK") {
194
            if (!$first_voucher) {
195
				// store first voucher. Thats the one we give the timecredit
196
                $first_voucher = $voucher;
197
                $first_voucher_roll = $roll;
198
            }
199
            // check if we have this ticket on a registered roll for this ticket 
200
            if ($tickets_per_roll[$roll] && ($nr <= $tickets_per_roll[$roll])) {
201
                // voucher is from a registered roll. 
202
                if (!isset($active_vouchers[$roll]))
203
                    $active_vouchers[$roll] = voucher_read_active_db($roll);
204
                // valid voucher. Store roll# and ticket#
205
                if (!empty($active_vouchers[$roll][$voucher])) {
206
                    list($timestamp,$minutes) = explode(",", $active_vouchers[$roll][$voucher]);
207
                    // we have an already active voucher here.
208
                    $remaining = intval((($timestamp + (60*$minutes)) - time())/60);
209
                    $test_result[] = "$voucher ($roll/$nr) active and good for $remaining Minutes";
210
                    $total_minutes += $remaining;
211
                } else {
212
                    // voucher not used. Check if ticket Id is on the roll (not too high)
213
                    // and if the ticket is marked used.
214
                    // check if voucher already marked as used
215
                    if (!isset($bitstring[$roll]))
216
                        $bitstring[$roll] = voucher_read_used_db($roll);
217
                    $pos = $nr >> 3; // divide by 8 -> octet
218
                    $mask = 1 << ($nr % 8);
219
                    if (ord($bitstring[$roll][$pos]) & $mask) {
220
                        $test_result[] = "$voucher ($roll/$nr) already used and expired";
221
						captiveportal_syslog("$voucher ($roll/$nr) already used and expired");
222
                        $total_minutes = -1;    // voucher expired
223
                        $error++;
224
                    } else {
225
                        // mark bit for this voucher as used
226
                        $bitstring[$roll][$pos] = chr(ord($bitstring[$roll][$pos]) | $mask);
227
                        $test_result[] = "$voucher ($roll/$nr) good for {$minutes_per_roll[$roll]} Minutes";
228
                        $total_minutes += $minutes_per_roll[$roll];
229
                    }
230
                }
231
            } else {
232
                $test_result[] = "$voucher ($roll/$nr): not found on any registererd Roll";
233
		captiveportal_syslog("$voucher ($roll/$nr): not found on any registererd Roll");
234
            }
235
        } else {
236
            // hmm, thats weird ... not what I expected
237
            $test_result[] = "$voucher invalid: $result !!";
238
	    captiveportal_syslog("$voucher invalid: $result !!");
239
            $error++;
240
        }
241
    }
242

    
243
    // if this was a test call, we're done. Return the result.
244
    if ($test) {
245
        if ($error) {
246
            $test_result[] = "Access denied!";
247
        } else {
248
            $test_result[] = "Access granted for $total_minutes Minutes in total.";
249
        }
250
	unlock($voucherlck);
251
        return $test_result;
252
    }
253

    
254
    // if we had an error (one of the vouchers is invalid), return 0.
255
    // Discussion: we could return the time remaining for good vouchers, but then
256
    // the user wouldn't know that he used at least one invalid voucher.
257

    
258
    if ($error) {
259
		unlock($voucherlck);
260
        if ($total_minutes > 0)     // probably not needed, but want to make sure
261
            $total_minutes = 0;     // we only report -1 (expired) or 0 (no access)
262
        return $total_minutes;       // well, at least one voucher had errors. Say NO ACCESS
263
    }
264

    
265
	// If we did a XMLRPC sync earlier check the timeleft
266
	if(!empty($a_voucher['vouchersyncdbip'])) 
267
		if($remote_time_used < $total_minutes) 
268
			$total_minutes = $remote_time_used;
269

    
270
    // All given vouchers were valid and this isn't simply a test.
271
    // Write back the used DB's
272

    
273
	if (is_array($bitstring)) {
274
		foreach ($bitstring as $roll => $used) {
275
			if(is_array($used)) {
276
				foreach($used as $u)
277
					voucher_write_used_db($roll, base64_encode($u));
278
			} else {
279
				voucher_write_used_db($roll, base64_encode($used));
280
			}
281
		}
282
	}
283

    
284
    // Active DB: we only add the first voucher if multiple given
285
    // and give that one all the time credit. This allows the user to logout and
286
    // log in later using just the first voucher. It also keeps username limited
287
    // to one voucher and that voucher shows the correct time credit in 'active vouchers'
288

    
289
    if (!empty($active_vouchers[$first_voucher_roll][$first_voucher])) {
290
        list($timestamp, $minutes) = explode(",", $active_vouchers[$first_voucher_roll][$first_voucher]);
291
    } else {
292
        $timestamp = time();    // new voucher
293
        $minutes = $total_minutes;
294
    }
295

    
296
    $active_vouchers[$first_voucher_roll][$first_voucher] = "$timestamp,$minutes";
297
    voucher_write_active_db($roll, $active_vouchers[$first_voucher_roll]);
298

    
299
    unlock($voucherlck);
300

    
301
    return $total_minutes;
302
}
303

    
304
function voucher_configure($sync = false) {
305
	global $config, $g;
306

    
307
	/* kill any running minicron */
308
	killbypid("{$g['varrun_path']}/vouchercron.pid");
309

    
310
	if (!isset($config['voucher']['enable']))
311
		return 0;
312

    
313
        if ($g['booting'])
314
            echo "Enabling voucher support... ";
315
	if ($sync == true)
316
	    captiveportal_syslog("Writing voucher db from sync data...");
317

    
318
        // start cron if we're asked to save runtime DB periodically
319
        // to XML config if it changed
320
        $croninterval = $config['voucher']['saveinterval'] * 60; // need seconds. Config has minutes
321
        if ($croninterval) {
322
            /* start pruning process (interval defaults to 60 seconds) */
323
            mwexec("/usr/local/bin/minicron $croninterval {$g['varrun_path']}/vouchercron.pid " .
324
                    "/etc/rc.savevoucher");
325
        }
326

    
327
	$voucherlck = lock('voucher', LOCK_EX);
328

    
329
        /* write public key used to verify vouchers */
330
        $pubkey = base64_decode($config['voucher']['publickey']);
331
        $fd = fopen("{$g['varetc_path']}/voucher.public", "w");
332
        if (!$fd) {
333
            captiveportal_syslog("Voucher error: cannot write voucher.public\n");
334
	    unlock($voucherlck);
335
            return 1;
336
        }
337
        fwrite($fd, $pubkey);
338
        fclose($fd);
339
        @chmod("{$g['varetc_path']}/voucher.public", 0600);
340

    
341
        /* write config file used by voucher binary to decode vouchers */
342
        $fd = fopen("{$g['varetc_path']}/voucher.cfg", "w");
343
        if (!$fd) {
344
            printf("Error: cannot write voucher.cfg\n");
345
	    unlock($voucherlck);
346
            return 1;
347
        }
348
        fwrite($fd, "{$config['voucher']['rollbits']},{$config['voucher']['ticketbits']},{$config['voucher']['checksumbits']},{$config['voucher']['magic']},{$config['voucher']['charset']}\n");
349
        fclose($fd);
350
        @chmod("{$g['varetc_path']}/voucher.cfg", 0600);
351
	unlock($voucherlck);
352

    
353
        if (($g['booting'] || $sync == true) && is_array($config['voucher']['roll'])) {
354

    
355
            // create active and used DB per roll on ramdisk from config
356
            $a_roll = &$config['voucher']['roll'];
357
		$voucherlck = lock('voucher', LOCK_EX);
358

    
359
            foreach ($a_roll as $rollent) {
360

    
361
                $roll = $rollent['number'];
362
                voucher_write_used_db($roll, $rollent['used']);
363
                $minutes = $rollent['minutes'];
364
                $active_vouchers = array();
365
                $a_active = &$rollent['active'];
366
                if (is_array($a_active)) {
367
                    foreach ($a_active as $activent) {
368
                        $voucher = $activent['voucher'];
369
                        $timestamp = $activent['timestamp'];
370
                        $minutes = $activent['minutes'];
371
                        // its tempting to check for expired timestamps, but during
372
                        // bootup, we most likely don't have the correct time time.
373
                        $active_vouchers[$voucher] = "$timestamp,$minutes";
374
                    }
375
                }
376
                voucher_write_active_db($roll, $active_vouchers);
377
            }
378

    
379
		unlock($voucherlck);
380
		if ($g['booting'])
381
		    echo "done\n";
382
        }
383

    
384
	return 0;
385
}
386

    
387
/* write bitstring of used vouchers to ramdisk. 
388
 * Bitstring must already be base64_encoded!
389
 */
390
function voucher_write_used_db($roll, $vdb) {
391
	global $g;
392

    
393
	$fd = fopen("{$g['vardb_path']}/voucher_used_$roll.db", "w");
394
	if ($fd) {
395
		fwrite($fd, $vdb . "\n");
396
		fclose($fd);
397
	} else
398
		voucher_log(LOG_ERR, "cant write {$g['vardb_path']}/voucher_used_$roll.db");
399
}
400

    
401
/* return assoc array of active vouchers with activation timestamp
402
 * voucher is index. 
403
 */
404
function voucher_read_active_db($roll) {
405
	global $g;
406

    
407
	$active = array();
408
	$dirty = 0;
409
	$file = "{$g['vardb_path']}/voucher_active_$roll.db";
410
	if (file_exists($file)) {
411
		$fd = fopen($file, "r");
412
		if ($fd) {
413
			while (!feof($fd)) {
414
				$line = trim(fgets($fd));
415
				if ($line) {
416
					list($voucher,$timestamp,$minutes) = explode(",", $line); // voucher,timestamp
417
					if ((($timestamp + (60*$minutes)) - time()) > 0)
418
						$active[$voucher] = "$timestamp,$minutes";
419
					else
420
						$dirty=1;
421
				}
422
			}
423
			fclose($fd);
424
			if ($dirty) // if we found expired entries, lets save our snapshot
425
				voucher_write_active_db($roll, $active);
426
		}
427
	}
428
	return $active;
429
}
430

    
431
/* store array of active vouchers back to DB */
432
function voucher_write_active_db($roll, $active) {
433
    global $g;
434

    
435
    $fd = fopen("{$g['vardb_path']}/voucher_active_$roll.db", "w");
436
    if ($fd) {
437
        foreach($active as $voucher => $value)
438
            fwrite($fd, "$voucher,$value\n");
439
        fclose($fd);
440
    }
441
}
442

    
443
/* return how many vouchers are marked used on a roll */
444
function voucher_used_count($roll) {
445
    global $g;
446

    
447
    $bitstring = voucher_read_used_db($roll);
448
    $max = strlen($bitstring) * 8;
449
    $used = 0;
450
    for ($i = 1; $i <= $max; $i++) {
451
        // check if ticket already used or not. 
452
        $pos = $i >> 3;            // divide by 8 -> octet
453
        $mask = 1 << ($i % 8);  // mask to test bit in octet
454
        if (ord($bitstring[$pos]) & $mask)
455
            $used++;
456
    }   
457
    return $used;
458
}
459

    
460
function voucher_read_used_db($roll) {
461
    global $g;
462

    
463
    $vdb = "";
464
    $file = "{$g['vardb_path']}/voucher_used_$roll.db";
465
    if (file_exists($file)) {
466
        $fd = fopen($file, "r");
467
        if ($fd) {
468
            $vdb = trim(fgets($fd));
469
            fclose($fd);
470
        } else {
471
            voucher_log(LOG_ERR, "cant read {$g['vardb_path']}/voucher_used_$roll.db");
472
        }
473
    }
474
    return base64_decode($vdb);
475
}
476

    
477
function voucher_unlink_db($roll) {
478
    global $g;
479
    @unlink("{$g['vardb_path']}/voucher_used_$roll.db");
480
    @unlink("{$g['vardb_path']}/voucher_active_$roll.db");
481
}
482

    
483
/* we share the log with captiveportal for now */
484
function voucher_log($priority, $message) {
485

    
486
    define_syslog_variables();
487
    $message = trim($message);
488
    openlog("logportalauth", LOG_PID, LOG_LOCAL4);
489
    syslog($priority, "Voucher: " . $message);
490
    closelog();
491
}
492

    
493
/* Save active and used voucher DB into XML config and write it to flash
494
 * Called during reboot -> system_reboot_cleanup() and minicron
495
 */
496
function voucher_save_db_to_config() {
497
    global $config, $g;
498
    
499
    if (!isset($config['voucher']['enable']) || $config['voucher']['saveinterval'] == 0) 
500
        return;   // no vouchers or don't want to save DB's
501

    
502
    $voucherlck = lock('voucher', LOCK_EX);
503

    
504
    // walk all active rolls and save runtime DB's to flash
505
    $a_roll = &$config['voucher']['roll'];
506
    while (list($key, $value) = each($a_roll)) {
507
        $rollent = &$a_roll[$key];
508
        $roll = $rollent['number'];
509
        $bitmask = voucher_read_used_db($roll);
510
        $rollent['used'] = base64_encode($bitmask);
511
        $active_vouchers = voucher_read_active_db($roll);
512
        $db = array();
513
		$dbi = 1;
514
        foreach($active_vouchers as $voucher => $line) {
515
            list($timestamp,$minutes) = explode(",", $line);
516
            $activent['voucher'] = $voucher;
517
            $activent['timestamp'] = $timestamp;
518
            $activent['minutes'] = $minutes;
519
            $db["v{$dbi}"] = $activent;
520
	    $dbi++;
521
        }
522
        $rollent['active'] = $db;
523
    }
524

    
525
    unlock($voucherlck);
526

    
527
    write_config();
528
    return;
529
}
530

    
531
?>
(51-51/61)