daemon.pm 39.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Radius daemon
# Copyright (C) 2007-2016, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.



package smradius::daemon;


use strict;
use warnings;


# Check if we have Net::Server::PreFork installed
if (!eval {require Net::Server::PreFork; 1;}) {
	print STDERR "You're missing Net::Server::PreFork, try 'apt-get install libnet-server-perl'\n";
	exit 1;
}

# Check Config::IniFiles is instaslled
if (!eval {require Config::IniFiles; 1;}) {
	print STDERR "You're missing Config::IniFiles, try 'apt-get install libconfig-inifiles-perl'\n";
	exit 1;
}

# Check DateTime is installed
if (!eval {require DateTime; 1;}) {
	print STDERR "You're missing DateTime, try 'apt-get install libdatetime-perl'\n";
	exit 1;
}

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Check Crypt::DES is installed
if (!eval {require Crypt::DES; 1;}) {
	print STDERR "You're missing DateTime, try 'apt-get install libcrypt-des-perl'\n";
	exit 1;
}

# Check Crypt::RC4 is installed
if (!eval {require Crypt::RC4; 1;}) {
	print STDERR "You're missing Crypt::RC4, try 'apt-get install libcrypt-rc4-perl'\n";
	exit 1;
}

# Check Digest::MD4 is installed
if (!eval {require Digest::MD4; 1;}) {
	print STDERR "You're missing Digest::MD4, try 'apt-get install libdigest-md4-perl'\n";
	exit 1;
}

# Check Digest::SHA is installed
if (!eval {require Digest::SHA; 1;}) {
	print STDERR "You're missing Digest::SHA, try 'apt-get install libdigest-sha-perl'\n";
	exit 1;
}

69
70
# Check Date::Parse is installed
if (!eval {require Date::Parse; 1;}) {
71
	print STDERR "You're missing TimeDate, try 'apt-get install libtimedate-perl'\n";
72
73
74
	exit 1;
}

75
76
77
78
79
80
81
82
# Check Cache::FastMmap is installed
if (!eval {require Cache::FastMmap; 1;}) {
	print STDERR "You're missing DateTime, try 'apt-get install libcache-fastmmap-perl'\n";
	exit 1;
} else {
	eval {use AWITPT::Cache;};
}

Nigel Kukard's avatar
Nigel Kukard committed
83
84
85
86
87
88
# Check MIME::Lite is installed
if (!eval {require MIME::Lite; 1;}) {
	print STDERR "You're missing MIME::Lite, try 'apt-get install libmime-lite-perl'\n";
	exit 1;
}

89
90
91
92
93
94
95

## no critic (BuiltinFunctions::ProhibitStringyEval)
eval qq{
	use base qw(Net::Server::PreFork);
};
## use critic

96
use Getopt::Long qw( GetOptionsFromArray );
97
98
99
100
use Socket;
use Sys::Syslog;
use Time::HiRes qw( gettimeofday tv_interval );

101
use AWITPT::DB::DBLayer;
102
103
use AWITPT::Util qw( booleanize );

Nigel Kukard's avatar
Nigel Kukard committed
104
use smradius::Radius::Packet;
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
use smradius::version;
use smradius::constants;
use smradius::daemon::request;
use smradius::logging;
use smradius::config;
use smradius::util;
use smradius::attributes;





# Override configuration
sub configure {
	my ($self,$defaults) = @_;
	my $server = $self->{'server'};


	# If we hit a hash, add the config vars to the server
	if (defined($defaults)) {
		foreach my $item (keys %{$defaults}) {
			$server->{$item} = $defaults->{$item};
		}
		return;
	}

	# Set defaults
	my $cfg;
	$cfg->{'config_file'} = "/etc/smradiusd.conf";
	$cfg->{'cache_file'} = '/var/run/smradius/cache';

	$server->{'timeout'} = 120;
	$server->{'background'} = "yes";
	$server->{'pid_file'} = "/var/run/smradius/smradiusd.pid";
	$server->{'log_level'} = 2;
	$server->{'log_file'} = "/var/log/smradius/smradiusd.log";

	$server->{'host'} = "*";
	$server->{'port'} = [ 1812, 1813 ];
	$server->{'proto'} = 'udp';

	$server->{'min_servers'} = 4;
	$server->{'min_spare_servers'} = 4;
	$server->{'max_spare_servers'} = 12;
	$server->{'max_servers'} = 25;
	$server->{'max_requests'} = 1000;

152
153
154
	# Work out runtime arguments
	my @runArgs = @{$server->{'_run_args'}} ? @{$server->{'_run_args'}} : @ARGV;

155
156
157
	# Parse command line params
	my $cmdline;
	%{$cmdline} = ();
158
159
	if (!GetOptionsFromArray(
			\@runArgs,
160
161
162
163
164
			\%{$cmdline},
			"help",
			"config:s",
			"debug",
			"fg",
165
	)) {
Nigel Kukard's avatar
Nigel Kukard committed
166
167
		print(STDERR "ERROR: Error parsing commandline arguments");
		return 1;
168
	}
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388

	# Check for some args
	if ($cmdline->{'help'}) {
		$self->displayHelp();
		exit 0;
	}
	if (defined($cmdline->{'config'}) && $cmdline->{'config'} ne "") {
		$cfg->{'config_file'} = $cmdline->{'config'};
	}

	# Check config file exists
	if (! -f $cfg->{'config_file'}) {
		die("No configuration file '".$cfg->{'config_file'}."' found!\n");
	}

	# Use config file, ignore case
	tie my %inifile, 'Config::IniFiles', (
			-file => $cfg->{'config_file'},
			-nocase => 1
	) or die "Failed to open config file '".$cfg->{'config_file'}."': $!";
	# Copy config
	my %config = %inifile;
	#untie(%inifile);

	# Pull in params for the server
	my @server_params = (
			'log_level','log_file',
#			'port',   - We don't want to override this do we?
			'host',
			'cidr_allow', 'cidr_deny',
			'pid_file',
			'user', 'group',
			'timeout',
			'background',
			'min_servers',
			'min_spare_servers',
			'max_spare_servers',
			'max_servers',
			'max_requests'
	);
	foreach my $param (@server_params) {
		$server->{$param} = $config{'server'}{$param} if (defined($config{'server'}{$param}));
	}

	# Fix up these ...
	if (defined($server->{'cidr_allow'})) {
		my @lst = split(/,\s;/,$server->{'cidr_allow'});
		$server->{'cidr_allow'} = \@lst;
	}
	if (defined($server->{'cidr_deny'})) {
		my @lst = split(/,\s;/,$server->{'cidr_deny'});
		$server->{'cidr_deny'} = \@lst;
	}

	# Override
	if ($cmdline->{'debug'}) {
		$server->{'log_level'} = 4;
		$cfg->{'debug'} = 1;
	}

	# If we set on commandline for foreground, keep in foreground
	if ($cmdline->{'fg'} || (defined($config{'server'}{'background'}) && $config{'server'}{'background'} eq "no" )) {
		$server->{'background'} = undef;
		$server->{'log_file'} = undef;
	} else {
		$server->{'setsid'} = 1;
	}

	# Loop with logging detail
	if (defined($config{'server'}{'log_detail'})) {
		# Lets see what we have to enable
		foreach my $detail (split(/[,\s;]/,$config{'server'}{'log_detail'})) {
			$cfg->{'logging'}{$detail} = 1;
		}
	}

	#
	# System modules
	#
	if (ref($config{'system'}{'modules'}) eq "ARRAY") {
		foreach my $module (@{$config{'system'}{'modules'}}) {
			$module =~ s/\s+//g;
			# Skip comments
			next if ($module =~ /^#/);
			$module = "system/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	} else {
		my @moduleList = split(/\s+/,$config{'system'}{'modules'});
		foreach my $module (@moduleList) {
			# Skip comments
			next if ($module =~ /^#/);
			$module = "system/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	}

	#
	# Feature modules
	#
	if (ref($config{'features'}{'modules'}) eq "ARRAY") {
		foreach my $module (@{$config{'features'}{'modules'}}) {
			$module =~ s/\s+//g;
			# Skip comments
			next if ($module =~ /^#/);
			$module = "features/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	} else {
		my @moduleList = split(/\s+/,$config{'features'}{'modules'});
		foreach my $module (@moduleList) {
			# Skip comments
			next if ($module =~ /^#/);
			$module = "features/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	}

	#
	# Authentication modules
	#
	if (ref($config{'authentication'}{'mechanisms'}) eq "ARRAY") {
		foreach my $module (@{$config{'authentication'}{'mechanisms'}}) {
			$module =~ s/\s+//g;
			# Skip comments
			next if ($module =~ /^#/);
			$module = "authentication/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	} else {
		my @moduleList = split(/\s+/,$config{'authentication'}{'mechanisms'});
		foreach my $module (@moduleList) {
			# Skip comments
			next if ($module =~ /^#/);
			$module = "authentication/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	}

	if (ref($config{'authentication'}{'users'}) eq "ARRAY") {
		foreach my $module (@{$config{'authentication'}{'users'}}) {
			$module =~ s/\s+//g;
			# Skip comments
			next if ($module =~ /^#/);
			$module = "userdb/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	} else {
		my @moduleList = split(/\s+/,$config{'authentication'}{'users'});
		foreach my $module (@moduleList) {
			# Skip comments
			next if ($module =~ /^#/);
			$module = "userdb/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	}

	#
	# Accounting modules
	#
	if (ref($config{'accounting'}{'modules'}) eq "ARRAY") {
		foreach my $module (@{$config{'accounting'}{'modules'}}) {
			$module =~ s/\s+//g;
			# Skip comments
			next if ($module =~ /^#/);
			$module = "accounting/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	} else {
		my @moduleList = split(/\s+/,$config{'accounting'}{'modules'});
		foreach my $module (@moduleList) {
			# Skip comments
			next if ($module =~ /^#/);
			$module = "accounting/$module";
			push(@{$cfg->{'module_list'}},$module);
		}
	}

	#
	# Dictionary configuration
	#
	# Split off dictionaries to load
	if (ref($config{'dictionary'}->{'load'}) eq "ARRAY") {
		foreach my $dict (@{$config{'dictionary'}->{'load'}}) {
			$dict =~ s/\s+//g;
			# Skip comments
			next if ($dict =~ /^#/);
			push(@{$cfg->{'dictionary_list'}},$dict);
		}
	} else {
		my @dictList = split(/\s+/,$config{'dictionary'}->{'load'});
		foreach my $dict (@dictList) {
			# Skip comments
			next if ($dict =~ /^#/);
			push(@{$cfg->{'dictionary_list'}},$dict);
		}
	}

	# Check if the user specified a cache_file in the config
	if (defined($config{'server'}{'cache_file'})) {
		$cfg->{'cache_file'} = $config{'server'}{'cache_file'};
	}


	# Save our config and stuff
	$self->{'config'} = $cfg;
	$self->{'cmdline'} = $cmdline;
	$self->{'inifile'} = \%config;

	return;
}



# Run straight after ->run
sub post_configure_hook {
	my $self = shift;
	my $config = $self->{'config'};


389
	$self->log(LOG_NOTICE,"[SMRADIUS] SMRadius - v$VERSION");
390
391
392
393
394
395
396
397

	# Init config
	$self->log(LOG_INFO,"[SMRADIUS] Initializing configuration...");
	smradius::config::Init($self);
	$self->log(LOG_INFO,"[SMRADIUS] Configuration initialized.");

	# Load dictionaries
	$self->log(LOG_INFO,"[SMRADIUS] Initializing dictionaries...");
Nigel Kukard's avatar
Nigel Kukard committed
398
	my $dict = smradius::Radius::Dictionary->new();
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
	foreach my $df (@{$config->{'dictionary_list'}}) {
		# Load dictionary
		if (!$dict->readfile($df)) {
			$self->log(LOG_WARN,"[SMRADIUS] Failed to load dictionary '$df': $!");
		}
		$self->log(LOG_DEBUG,"[SMRADIUS] Loaded dictionary '$df'.");
	}
	$self->log(LOG_INFO,"[SMRADIUS] Dictionaries initialized.");
	# Store the dictionary
	$self->{'radius'}->{'dictionary'} = $dict;

	$self->log(LOG_INFO,"[SMRADIUS] Initializing modules...");
	# Load modules
	foreach my $module (@{$config->{'module_list'}}) {
		# Split off dir and mod name
		$module =~ /^(\w+)\/(\w+)$/;
		my ($mod_dir,$mod_name) = ($1,$2);

		# Load module
		## no critic (BuiltinFunctions::ProhibitStringyEval)
		my $res = eval qq{
			use smradius::modules::${mod_dir}::${mod_name};
			plugin_register(\$self,\"${mod_name}\",\$smradius::modules::${mod_dir}::${mod_name}::pluginInfo);
		};
		## use critic
		if ($@ || (defined($res) && $res != 0)) {
			$self->log(LOG_WARN,"[SMRADIUS] Error loading module $module ($@)");
		} else {
			$self->log(LOG_DEBUG,"[SMRADIUS] Plugin '$module' loaded.");
		}
	}
	$self->log(LOG_INFO,"[SMRADIUS] Plugins initialized.");

	$self->log(LOG_INFO,"[SMRADIUS] Initializing system modules.");
	# Init caching engine
	AWITPT::Cache::Init($self,{
		'cache_file' => $self->{'config'}{'cache_file'},
		'cache_file_user' => $self->{'server'}->{'user'},
		'cache_file_group' => $self->{'server'}->{'group'}
	});

	$self->log(LOG_INFO,"[SMRADIUS] System modules initialized.");

	return;
}



# Register plugin info
sub plugin_register {
	my ($self,$plugin,$info) = @_;


	# If no info, return
	if (!defined($info)) {
		print(STDERR "WARNING: Plugin info not found for plugin => $plugin\n");
		return -1;
	}

	# Set real module name & save
	$info->{'Module'} = $plugin;
	push(@{$self->{'module_list'}},$info);

	# If we should, init the module
	if (defined($info->{'Init'})) {
		$info->{'Init'}($self);
	}

	return 0;
}



# Initialize child
sub child_init_hook
{
	my $self = shift;
	my $config = $self->{'config'};


	$self->SUPER::child_init_hook();

	$self->log(LOG_INFO,"[SMRADIUS] Starting up caching engine");
	AWITPT::Cache::connect($self);

	# Do we need database support?
	if ($self->{'smradius'}->{'database'}->{'enabled'}) {
		# This is the database connection timestamp, if we connect, it resets to 0
		# if not its used to check if we must kill the child and try a reconnect
		$self->{'client'}->{'dbh_status'} = time();

		# Init core database support
		$self->{'client'}->{'dbh'} = AWITPT::DB::DBILayer::Init($self,'smradius');
		if (defined($self->{'client'}->{'dbh'})) {
			# Check if we succeeded
			if (!($self->{'client'}->{'dbh'}->connect())) {
			# If we succeeded, record OK
				$self->{'client'}->{'dbh_status'} = 0;
			} else {
				$self->log(LOG_WARN,"[SMRADIUS] Failed to connect to database: ".$self->{'client'}->{'dbh'}->Error().
						" ($$)");
			}
		} else {
			$self->log(LOG_WARN,"[SMRADIUS] Failed to Initialize: ".awitpt::db::dbilayer::internalError()." ($$)");
		}
	}

	return;
}



# Destroy the child
sub child_finish_hook {
	my $self = shift;
	my $server = $self->{'server'};

	$self->SUPER::child_finish_hook();

	$self->log(LOG_INFO,"[SMRADIUS] Shutting down caching engine ($$)");
	AWITPT::Cache::disconnect($self);

	return;
}



# Process requests we get
sub process_request {
	my $self = shift;
	my $server = $self->{'server'};
	my $client = $self->{'client'};
	my $log = defined($server->{'config'}{'logging'}{'module_list'});


	# Grab packet
	my $rawPacket = $server->{'udp_data'};

	# Check min size
	if (length($rawPacket) < 18)
	{
		$self->log(LOG_WARN, "[SMRADIUS] Packet too short - Ignoring");
		return;
	}

	# Very first timer ...
	my $timer0 = [gettimeofday];

	# Grab NOW()
	my $now = time();

	# VERIFY SOURCE SERVER
	$self->log(LOG_DEBUG,"[SMRADIUS] Packet From = > ".$server->{'peeraddr'});

	# Check if we got connected, if not ... bypass
	if ($self->{'client'}->{'dbh_status'} > 0) {
		my $action;

		$self->log(LOG_WARN,"[SMRADIUS] Client in BYPASS mode due to DB connection failure!");
		# Check bypass mode
		if (!defined($self->{'inifile'}{'database'}{'bypass_mode'})) {
			$self->log(LOG_ERR,
					"[SMRADIUS] No bypass_mode specified for failed database connections, defaulting to tempfail");
			$action = "tempfail";
		# Check for "tempfail"
		} elsif (lc($self->{'inifile'}{'database'}{'bypass_mode'}) eq "tempfail") {
		# And for "bypass"
		} elsif (lc($self->{'inifile'}{'database'}{'bypass_mode'}) eq "pass") {
		}

		# Check if we need to reconnect or not
		my $timeout = $self->{'inifile'}{'database'}{'bypass_timeout'};
		if (!defined($timeout)) {
			$self->log(LOG_ERR,"[SMRADIUS] No bypass_timeout specified for failed database connections, defaulting to 120s");
			$timeout = 120;
		}
		# Get time left
		my $timepassed = $now - $self->{'client'}->{'dbh_status'};
		# Then check...
		if ($timepassed >= $timeout) {
			$self->log(LOG_WARN,"[SMRADIUS] Client BYPASS timeout exceeded, reconnecting...");
			exit 0;
		} else {
			$self->log(LOG_WARN,"[SMRADIUS] Client still in BYPASS mode, ".( $timeout - $timepassed ).
					"s left till next reconnect");
			return;
		}
	}

	# Setup database handle
	AWITPT::DB::DBLayer::setHandle($self->{'client'}->{'dbh'});


	my $request = smradius::daemon::request->new($self);
	$request->setTimeZone($self->{'smradius'}->{'event_timezone'});

	$request->parsePacket($self->{'radius'}->{'dictionary'},$rawPacket);

	# Check if we need to override the packet timestamp, if we are not using the packet timestamp, set it to when we go the packet
	if (!booleanize($self->{'smradius'}->{'use_packet_timestamp'})) {
		$request->setTimestamp($now);
	}

	# Username should always be defined?
	if (!$request->hasUsername()) {
		$self->log(LOG_NOTICE,"[SMRADIUS] Packet with no username from ".$server->{'peeraddr'});
		return;
	}


	# TODO/FIXME: WIP
	my $pkt = $request->{'packet'};
	my $user = $request->{'user'};
	my $logReason = "UNKNOWN";



	# First thing we do is to make sure the NAS behaves if we using abuse prevention
	if ($self->{'smradius'}->{'use_abuse_prevention'} && defined($user->{'Username'})) {
		my ($res,$val) = cacheGetKeyPair('FloodCheck',$server->{'peeraddr'}."/".$user->{'Username'}."/".$pkt->code);
		if (defined($val)) {
			my $timePeriod = $now - $val;
			if ($pkt->code eq "Access-Request" && $timePeriod < $self->{'smradius'}->{'access_request_abuse_threshold'}) {
				$self->log(LOG_NOTICE,"[SMRADIUS] ABUSE: Server trying too fast. server = ".$server->{'peeraddr'}.", user = ".$user->{'Username'}.
						", code = ".$pkt->code.", timeout = ".($now - $val));
				return;
			} elsif ($pkt->code eq "Accounting-Request" && $timePeriod < $self->{'smradius'}->{'accounting_request_abuse_threshold'}) {
				$self->log(LOG_NOTICE,"[SMRADIUS] ABUSE: Server trying too fast. server = ".$server->{'peeraddr'}.", user = ".$user->{'Username'}.
						", code = ".$pkt->code.", timeout = ".($now - $val));
				return;
			}
		}
		# We give the benefit of the doubt and let a query take 60s. We update to right stamp at end of this function
		cacheStoreKeyPair('FloodCheck',$server->{'peeraddr'}."/".$user->{'Username'}."/".$pkt->code,$now + 60);
	}

	#
	# GRAB & PROCESS CONFIG
	#

	my $configured = 1;

	foreach my $module (@{$self->{'module_list'}}) {
		# Try find config attribute
		if ($module->{'Config_get'}) {

			# Get result from config module
			$self->log(LOG_DEBUG,"[SMRADIUS] CONFIG: Trying plugin '".$module->{'Name'}."' for incoming connection");
			my $res = $module->{'Config_get'}($self,$user,$pkt);

			# Check result
			if (!defined($res)) {
				$self->log(LOG_WARN,"[SMRADIUS] CONFIG: Error with plugin '".$module->{'Name'}."'");
				$logReason = "Config Error";

			# Check if we skipping this plugin
			} elsif ($res == MOD_RES_SKIP) {
				$self->log(LOG_DEBUG,"[SMRADIUS] CONFIG: Skipping '".$module->{'Name'}."'");

			# Check if we got a positive result back
			} elsif ($res == MOD_RES_ACK) {
				$self->log(LOG_DEBUG,"[SMRADIUS] CONFIG: Configuration retrieved from '".$module->{'Name'}."'");
				$logReason = "Config Retrieved";

			# Check if we got a negative result back
			} elsif ($res == MOD_RES_NACK) {
				$self->log(LOG_DEBUG,"[SMRADIUS] CONFIG: Configuration rejection when using '".$module->{'Name'}."'");
				$logReason = "Config Rejected";

				# FIXME/TODO NK WIP
				return;
#				$configured = 0;
#				last;
			}
		}
	}


	#
	# USERNAME TRANSFORM
	#

	# If we have a config attribute to transform username, use it
	if (defined($user->{'ConfigAttributes'}->{'SMRadius-Username-Transform'})) {

		$self->log(LOG_DEBUG,"[SMRADIUS] Attribute 'SMRadius-Username-Transform' exists, transforming username.");

# NK: Not ready for prime time yet
#		# Get clients(NAS) username transform pattern
#		my $transform = shift(@{$user->{'ConfigAttributes'}->{'SMRadius-Username-Transform'}});
#		if ($transform =~ /^(@\S+)=(@\S+)$/i) {
#
#			# Set old and new, prevents warnings
#			my ($old,$new) = ($1,$2);
#
#			# Use client username transform on temp username
#			my $tempUsername = $user->{'Username'};
#			$tempUsername =~ s/$old/$new/;
#
#			# Override username
#			$user->{'Username'} = $tempUsername;
#		} else {
#			$self->log(LOG_DEBUG,"[SMRADIUS] No string replacement possible on pattern '".
#					$transform."', using username '".$user->{'Username'}."'");
#		}
	}


	#
	# FIND USER
	#

	# Get the user timer
	my $timer1 = [gettimeofday];

	# FIXME - need secret
	# FIXME - need acl list

	# Common stuff for multiple codes....
	if ($pkt->code eq "Accounting-Request" || $pkt->code eq "Access-Request") {

		# Loop with modules to try find user
		foreach my $module (@{$self->{'module_list'}}) {

			# Try find user
			if ($module->{'User_find'}) {
				$self->log(LOG_DEBUG,"[SMRADIUS] FIND: Trying plugin '".$module->{'Name'}."' for username '".
						$user->{'Username'}."'");
Nigel Kukard's avatar
Nigel Kukard committed
727
				my ($res,$userDB_Data) = $module->{'User_find'}($self,$user,$pkt);
728
729
730
731
732
733
734
735
736
737
738
739
740
741

				# Check result
				if (!defined($res)) {
					$self->log(LOG_WARN,"[SMRADIUS] FIND: Error with plugin '".$module->{'Name'}."'");
					$logReason = "Error Finding User";

				# Check if we skipping this plugin
				} elsif ($res == MOD_RES_SKIP) {
					$self->log(LOG_DEBUG,"[SMRADIUS] FIND: Skipping '".$module->{'Name'}."'");

				# Check if we got a positive result back
				} elsif ($res == MOD_RES_ACK) {
					$self->log(LOG_DEBUG,"[SMRADIUS] FIND: Username found with '".$module->{'Name'}."'");
					$user->{'_UserDB'} = $module;
Nigel Kukard's avatar
Nigel Kukard committed
742
					$user->{'_UserDB_Data'} = $userDB_Data;
743
744
					# The user ID is supposed to be global unique, on the same level as the username
					$user->{'ID'} = $user->{'_UserDB_Data'}->{'ID'};
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
					last;

				# Or a negative result
				} elsif ($res == MOD_RES_NACK) {
					$self->log(LOG_DEBUG,"[SMRADIUS] FIND: Username not found with '".$module->{'Name'}."'");
					$logReason = "User Not Found";
					last;

				}
			}
		}
	}


	#
	# PROCESS PACKET
	#

	# Process the packet timer
	my $timer2 = [gettimeofday];


	# Is this an accounting request
	if ($pkt->code eq "Accounting-Request") {

		$self->log(LOG_DEBUG,"[SMRADIUS] Accounting Request Packet");

772
773
774
775
776
777
778
779
780
781
		# Add onto logline
		$request->addLogLine(". REQUEST => ");
		foreach my $attrName ($pkt->attributes) {
			$request->addLogLine(
				"%s: '%s'",
				$attrName,
				$pkt->rawattr($attrName)
			);
		}

782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
		#
		# GET USER
		#

		# Get user data
		if (defined($user->{'_UserDB'}) && defined($user->{'_UserDB'}->{'User_get'})) {
			my $res = $user->{'_UserDB'}->{'User_get'}($self,$user,$pkt);

			# Check result
			if ($res) {
				$self->log(LOG_WARN,"[SMRADIUS] GET: Error returned from '".$user->{'_UserDB'}->{'Name'}.
						"' for username '".$user->{'Username'}."'");
			}
		}

		# Loop with modules to try something that handles accounting
		foreach my $module (@{$self->{'module_list'}}) {
			# Try find user
			if ($module->{'Accounting_log'}) {
				$self->log(LOG_DEBUG,"[SMRADIUS] ACCT: Trying plugin '".$module->{'Name'}."'");
				my $res = $module->{'Accounting_log'}($self,$user,$pkt);

				# Check result
				if (!defined($res)) {
					$self->log(LOG_WARN,"[SMRADIUS] ACCT: Error with plugin '".$module->{'Name'}."'");
					$logReason = "Accounting Log Error";

				# Check if we skipping this plugin
				} elsif ($res == MOD_RES_SKIP) {
					$self->log(LOG_DEBUG,"[SMRADIUS] ACCT: Skipping '".$module->{'Name'}."'");

				# Check if we got a positive result back
				} elsif ($res == MOD_RES_ACK) {
					$self->log(LOG_DEBUG,"[SMRADIUS] ACCT: Accounting logged using '".$module->{'Name'}."'");
					$logReason = "Accounting Logged";

				# Check if we got a negative result back
				} elsif ($res == MOD_RES_NACK) {
					$self->log(LOG_DEBUG,"[SMRADIUS] ACCT: Accounting NOT LOGGED using '".$module->{'Name'}."'");
					$logReason = "Accounting NOT Logged";
				}
			}
		}

		# Are we going to POD the user?
		my $PODUser = 0;

		# Loop with modules that have post-accounting hooks
		foreach my $module (@{$self->{'module_list'}}) {
			# Try authenticate
			if ($module->{'Feature_Post-Accounting_hook'}) {
				$self->log(LOG_DEBUG,"[SMRADIUS] POST-ACCT: Trying plugin '".$module->{'Name'}."' for '".
						$user->{'Username'}."'");
				my $res = $module->{'Feature_Post-Accounting_hook'}($self,$user,$pkt);

				# Check result
				if (!defined($res)) {
					$self->log(LOG_WARN,"[SMRADIUS] POST-ACCT: Error with plugin '".$module->{'Name'}."'");
					$logReason = "Post Accounting Error";

				# Check if we skipping this plugin
				} elsif ($res == MOD_RES_SKIP) {
					$self->log(LOG_DEBUG,"[SMRADIUS] POST-ACCT: Skipping '".$module->{'Name'}."'");

				# Check if we got a positive result back
				} elsif ($res == MOD_RES_ACK) {
					$self->log(LOG_DEBUG,"[SMRADIUS] POST-ACCT: Passed post accounting hook by '".$module->{'Name'}."'");
					$logReason = "Post Accounting Success";

				# Or a negative result
				} elsif ($res == MOD_RES_NACK) {
					$self->log(LOG_DEBUG,"[SMRADIUS] POST-ACCT: Failed post accounting hook by '".$module->{'Name'}."'");
					$logReason = "Failed Post Accounting";
					$PODUser = 1;
				}
			}
		}

860
861
862
863
864
865
866
867
868
		# Tell the NAS we got its packet
		my $resp = smradius::Radius::Packet->new($self->{'radius'}->{'dictionary'});
		$resp->set_code('Accounting-Response');
		$resp->set_identifier($pkt->identifier);
		$resp->set_authenticator($pkt->authenticator);
		$server->{'client'}->send(
			auth_resp($resp->pack, getAttributeValue($user->{'ConfigAttributes'},"SMRadius-Config-Secret"))
		);

869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
		# Build a list of our attributes in the packet
		my $acctAttributes;
		foreach my $attr ($pkt->attributes) {
			$acctAttributes->{$attr} = $pkt->rawattr($attr);
		}
		# Loop with attributes we got from the user
		foreach my $attrName (keys %{$user->{'Attributes'}}) {
			# Loop with operators
			foreach my $attrOp (keys %{$user->{'Attributes'}->{$attrName}}) {
				# Grab attribute
				my $attr = $user->{'Attributes'}->{$attrName}->{$attrOp};
				# Check attribute against accounting attributes attributes
				my $res = checkAcctAttribute($self,$user,$acctAttributes,$attr);
				# We don't care if it fails
			}
		}

		# Check if we must POD the user
		if ($PODUser) {
			$self->log(LOG_DEBUG,"[SMRADIUS] POST-ACCT: Trying to disconnect user...");

Nigel Kukard's avatar
Nigel Kukard committed
890
			my $resp = smradius::Radius::Packet->new($self->{'radius'}->{'dictionary'});
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

			$resp->set_code('Disconnect-Request');
			my $id = $$ & 0xff;
			$resp->set_identifier( $id );

			$resp->set_attr('User-Name',$pkt->attr('User-Name'));
			$resp->set_attr('Framed-IP-Address',$pkt->attr('Framed-IP-Address'));
			$resp->set_attr('NAS-IP-Address',$pkt->attr('NAS-IP-Address'));

			# Add onto logline
			$request->addLogLine(". REPLY => ");
			foreach my $attrName ($resp->attributes) {
				$request->addLogLine(
					"%s: '%s'",
					$attrName,
					$resp->rawattr($attrName)
				);
			}

			# Grab packet
			my $response = auth_resp($resp->pack, getAttributeValue($user->{'ConfigAttributes'},"SMRadius-Config-Secret"));

			# Check for POD Servers and send disconnect
			if (defined($user->{'ConfigAttributes'}->{'SMRadius-Config-PODServer'})) {
				$self->log(LOG_DEBUG,"[SMRADIUS] SMRadius-Config-PODServer is defined");

				# Check address format
				foreach my $podServerAttribute (@{$user->{'ConfigAttributes'}->{'SMRadius-Config-PODServer'}}) {
					# Check for valid IP
					if ($podServerAttribute =~ /^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})/) {
						my $podServer = $1;

						# If we have a port, use it, otherwise use default 1700
						my $podServerPort;
						if ($podServerAttribute =~ /:([0-9]+)$/) {
							$podServerPort = $1;
						} else {
							$podServerPort = 1700;
						}

						$self->log(LOG_DEBUG,"[SMRADIUS] POST-ACCT: Trying PODServer => IP: '".$podServer."' Port: '".$podServerPort."'");

						# Create socket to send packet out on
						my $podServerTimeout = "10";  # 10 second timeout
						my $podSock = IO::Socket::INET->new(
								PeerAddr => $podServer,
								PeerPort => $podServerPort,
								Type => SOCK_DGRAM,
								Proto => 'udp',
								TimeOut => $podServerTimeout,
						);

						if (!$podSock) {
							$self->log(LOG_ERR,"[SMRADIUS] POST-ACCT: Failed to create socket to send POD on");
							next;
						}

						# Check if we sent the packet...
						if (!$podSock->send($response)) {
							$self->log(LOG_ERR,"[SMRADIUS] POST-ACCT: Failed to send data on socket");
							next;
						}

						# Once sent, we need to get a response back
						my $sh = IO::Select->new($podSock);
						if (!$sh) {
							$self->log(LOG_ERR,"[SMRADIUS] POST-ACCT: Failed to select data on socket");
							next;
						}

						if (!$sh->can_read($podServerTimeout)) {
							$self->log(LOG_ERR,"[SMRADIUS] POST-ACCT: Failed to receive data on socket");
							next;
						}

						my $data;
						$podSock->recv($data, 65536);
						if (!$data) {
							$self->log(LOG_ERR,"[SMRADIUS] POST-ACCT: Receive data failed");
							$logReason = "POD Failure";
						} else {
							$logReason = "User POD";
						}

						#my @stuff = unpack('C C n a16 a*', $data);
						#$self->log(LOG_DEBUG,"STUFF: ".Dumper(\@stuff));
					} else {
						$self->log(LOG_DEBUG,"[SMRADIUS] Invalid POD Server value: '".$podServerAttribute."'");
					}
				}
			} else {
				$self->log(LOG_DEBUG,"[SMRADIUS] SMRadius-Config-PODServer is not defined");
			}
		}

	# Or maybe a access request
	} elsif ($pkt->code eq "Access-Request") {


		$self->log(LOG_DEBUG,"[SMRADIUS] Access Request Packet");

		# Authentication variables
		my $authenticated = 0;
		my $mechanism;
		# Authorization variables
		my $authorized = 1;


		# If no user is found, bork out ...
		if (!defined($user->{'_UserDB'})) {