Project

General

Profile

Download (19.2 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}:{$port}";
93
	else 
94
		$url = "http://{$syncip}:{$port}";
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();
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['timeleft'] < $total_minutes) 
268
			$total_minutes = $remote_time_used['timeleft'];
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() {
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

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

    
325
	$voucherlck = lock('voucher', LOCK_EX);
326

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

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

    
351
        if ($g['booting'] && is_array($config['voucher']['roll'])) {
352

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

    
357
            foreach ($a_roll as $rollent) {
358

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

    
377
		unlock($voucherlck);
378
            echo "done\n";
379
        }
380

    
381
	return 0;
382
}
383

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

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

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

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

    
428
/* store array of active vouchers back to DB */
429
function voucher_write_active_db($roll, $active) {
430
    global $g;
431

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

    
440
/* return how many vouchers are marked used on a roll */
441
function voucher_used_count($roll) {
442
    global $g;
443

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

    
457
function voucher_read_used_db($roll) {
458
    global $g;
459

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

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

    
480
/* we share the log with captiveportal for now */
481
function voucher_log($priority, $message) {
482

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

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

    
499
    $voucherlck = lock('voucher', LOCK_EX);
500

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

    
522
    unlock($voucherlck);
523

    
524
    write_config();
525
    return;
526
}
527

    
528
?>
(51-51/61)