-
Notifications
You must be signed in to change notification settings - Fork 275
/
Unifi.pm
501 lines (373 loc) · 14.5 KB
/
Unifi.pm
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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
389
390
391
392
393
394
395
396
397
398
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
package pf::Switch::Ubiquiti::Unifi;
=head1 NAME
pf::Switch::Ubiquiti::Unifi
=head1 SYNOPSIS
The pf::Switch::Ubiquiti::Unifi module implements an object oriented interface to
manage Unifi controllers
=head1 STATUS
Developed and tested on Unifi controller version 5.4.14 with a UniFi AP-AC-Pro running 3.4.14.3413
=head1 BUGS AND LIMITATIONS
=cut
use strict;
use warnings;
use base ('pf::Switch');
use DateTime;
use DateTime::Format::MySQL;
use pf::security_event qw(security_event_count_reevaluate_access);
use pf::constants::node qw($STATUS_UNREGISTERED);
use pf::file_paths qw($var_dir);
use pf::constants;
use pf::util;
use pf::node;
use pf::util::radius qw(perform_disconnect);
use pf::config qw(
%connection_type_to_str
$MAC
$SSID
$WEBAUTH_WIRELESS
);
use pf::locationlog;
use Try::Tiny;
use JSON::MaybeXS;
use pf::config::cluster;
# The port to reach the Unifi controller API
our $UNIFI_API_PORT = "8443";
sub description { 'Unifi Controller' }
=head1 SUBROUTINES
=cut
# CAPABILITIES
# access technology supported
use pf::SwitchSupports qw(
ExternalPortal
WirelessDot1x
WirelessMacAuth
);
# inline capabilities
sub inlineCapabilities { return ($MAC,$SSID); }
=head2 getVersion
Obtain image version information from switch
=cut
sub getVersion {
my ($self) = @_;
my $oid_sysDescr = '1.3.6.1.2.1.1.1.0';
my $logger = $self->logger;
if ( !$self->connectRead() ) {
return '';
}
$logger->trace("SNMP get_request for sysDescr: $oid_sysDescr");
my $result = $self->{_sessionRead}->get_request( -varbindlist => [$oid_sysDescr] );
my $sysDescr = ( $result->{$oid_sysDescr} || '' );
if ( $sysDescr =~ m/V(\d{1}\.\d{2}\.\d{2})/ ) {
return $1;
} elsif ( $sysDescr =~ m/Version (\d+\.\d+\([^)]+\)[^,\s]*)(,|\s)+/ ) {
return $1;
} else {
return $sysDescr;
}
}
=head2 synchronize_locationlog
Override the Switch method so that the controller IP is inserted as the switch_ip in the locationlog
=cut
sub synchronize_locationlog {
my ( $self, $ifIndex, $vlan, $mac, $voip_status, $connection_type, $connection_sub_type, $user_name, $ssid, $stripped_user_name, $realm, $role, $ifDesc) = @_;
# Set the switch IP to the controller IP so that the locationlog entry has the proper switch_ip entry
$self->{_ip} = $self->returnSwitchIP($self->{_switchMac}) if ($connection_type == $WEBAUTH_WIRELESS);
$self->SUPER::synchronize_locationlog($ifIndex, $vlan, $mac, $voip_status, $connection_type, $connection_sub_type, $user_name, $ssid, $stripped_user_name, $realm, $role, $ifDesc);
}
=head2 returnSwitchIP
return the SwitchIP
=cut
sub returnSwitchIP {
my ($self, $mac) = @_;
if (my $ip = $self->getAccessPointMACIP($mac)) {
return $ip;
}
if (ref($self)) {
if (exists($self->{_controllerIp}) && $self->{_controllerIp} ne '') {
return $self->{_controllerIp};
}
}
return undef;
}
=head2 parseExternalPortalRequest
Parse external portal request using URI and it's parameters then return an hash reference with the appropriate parameters
See L<pf::web::externalportal::handle>
=cut
sub parseExternalPortalRequest {
my ( $self, $r, $req ) = @_;
my $logger = $self->logger;
# Using a hash to contain external portal parameters
my %params = ();
my $client_ip = defined($r->headers_in->{'X-Forwarded-For'}) ? $r->headers_in->{'X-Forwarded-For'} : $r->connection->remote_ip;
%params = (
switch_id => $req->param('ap'),
switch_mac => $req->param('ap'),
switch_ip => $self->returnSwitchIP($req->param('ap')),
client_mac => clean_mac($req->param('id')),
client_ip => $client_ip,
ssid => $req->param('ssid'),
redirect_url => $req->param('url'),
status_code => '200',
synchronize_locationlog => $TRUE,
connection_type => $WEBAUTH_WIRELESS,
);
return \%params;
}
=head2 deauthTechniques
Return the reference to the deauth technique or the default deauth technique.
=cut
sub deauthTechniques {
my ($self, $method, $connection_type) = @_;
my $logger = $self->logger;
my $default = $SNMP::HTTP;
my %tech = (
$SNMP::HTTP => '_deauthenticateMacWithHTTP',
$SNMP::RADIUS => 'deauthenticateMacRadius',
);
if ($connection_type == $WEBAUTH_WIRELESS) {
$method = $SNMP::HTTP;
}
if (!defined($method) || !defined($tech{$method})) {
$method = $default;
}
return $method,$tech{$method};
}
=head2 _connect
Return the connection to the controller
=cut
sub _connect {
my ($self) = @_;
my $logger = $self->logger;
my $controllerIp = $self->{_controllerIp};
my $transport = lc($self->{_wsTransport});
my $username = $self->{_wsUser};
my $password = $self->{_wsPwd};
my $ua = LWP::UserAgent->new();
$ua->cookie_jar({ file => "$var_dir/run/.ubiquiti.cookies.txt" });
$ua->ssl_opts(verify_hostname => 0);
$ua->timeout(10);
my $base_url = "$transport://$controllerIp:$UNIFI_API_PORT";
my $response = $ua->post("$base_url/api/login", Content => '{"username":"'.$username.'", "password":"'.$password.'"}');
unless($response->is_success) {
$logger->error("Can't login on the Unifi controller: ".$response->status_line);
die;
}
return ($ua, $base_url);
}
=head2 _deauthenticateMacWithHTTP
Enable or disable the access of a user (portal vs no portal) using an HTTP webservices call
=cut
sub _deauthenticateMacWithHTTP {
my ( $self, $mac ) = @_;
my $logger = $self->logger;
my $node_info = node_view($mac);
my %site_opts;
my $found = $FALSE;
my $args = {
mac => $mac,
};
my $command;
unless ($node_info->{status} eq $STATUS_UNREGISTERED || security_event_count_reevaluate_access($mac)) {
$command = "authorize-guest";
if($node_info->{unregdate} ne $ZERO_DATE) {
my $now = DateTime->now();
$now->set_time_zone('local');
my $unregdate = DateTime::Format::MySQL->parse_datetime($node_info->{unregdate});
$unregdate->set_time_zone('local');
$args->{minutes} = $now->delta_ms($unregdate)->in_units('minutes');
}
} else {
$command = "unauthorize-guest";
}
$command = "kick-sta" if ($node_info->{last_connection_type} ne $connection_type_to_str{$WEBAUTH_WIRELESS});
$args->{cmd} = $command;
my ($ua, $base_url) = $self->_connect();
my $response = $ua->get("$base_url/api/self/sites");
unless($response->is_success) {
$logger->error("Can't have the site list from the Unifi controller: ".$response->status_line);
return;
}
my $json_data = decode_json($response->decoded_content());
foreach my $entry (@{$json_data->{'data'}}) {
$response = $ua->get("$base_url/api/s/$entry->{'name'}/stat/sta/$mac");
if ($response->is_success) {
$found = $TRUE;
$site_opts{'name'} = $entry->{'name'};
$site_opts{'desc'} = $entry->{'desc'};
$logger->info("Found site: $site_opts{'desc'}");
last;
}
}
tie my %SwitchConfig, 'pfconfig::cached_hash', "config::Switch($host_id)";
my $count = 0;
foreach my $switch_id (keys(%SwitchConfig)) {
my $switch = $SwitchConfig{$switch_id};
# If the other switch is a MAC based entry and an Ubiquiti AP and is part of the same AP group, then we'll send the deauth
if(valid_mac($switch_id) && $switch->{type} eq $self->{_type} && $switch->{group} eq $self->{_group}) {
$count++;
$args->{ap_mac} = $switch_id;
if ($found) {
$response = $ua->post("$base_url/api/s/$site_opts{'name'}/cmd/stamgr", Content => encode_json($args));
if ($response->is_success) {
$logger->trace("Deauth on site: $site_opts{'desc'} for $switch_id");
}
} else {
foreach my $entry (@{$json_data->{'data'}}) {
$response = $ua->post("$base_url/api/s/$entry->{'name'}/cmd/stamgr", Content => encode_json($args));
if ($response->is_success) {
$logger->trace("Deauth on site: $entry->{'desc'} for $switch_id");
}
}
}
}
}
$logger->info("Deauth on $count access points");
unless($response->is_success) {
$logger->error("Can't send request on the Unifi controller: ".$response->status_line);
return;
}
$logger->info("Switched status on the Unifi controller using command $command");
}
=item getAccessPointMACIP
get IP associated to a AP MAC
=cut
sub getAccessPointMACIP {
my ($self, $mac) = @_;
my $logger = $self->logger;
my $cache = $self->cache_distributed;
my $result = $cache->get("Ubiquiti-" .$mac);
return $result if defined($result);
return $FALSE;
}
=item populateAccessPointMACIP
Fetch all the AP on the controller and cache it
=cut
sub populateAccessPointMACIP {
my ($self) = @_;
my $logger = $self->logger;
my $cache = $self->cache_distributed;
my $controllerIp = $self->{_controllerIp};
my $transport = lc($self->{_wsTransport});
my $username = $self->{_wsUser};
my $password = $self->{_wsPwd};
my ($ua, $base_url) = $self->_connect();
my $response = $ua->get("$base_url/api/self/sites");
unless($response->is_success) {
$logger->error("Can't have the site list from the Unifi controller: ".$response->status_line);
return;
}
$response = $ua->get("$base_url/api/self/sites");
my $json_data = decode_json($response->decoded_content());
foreach my $entry (@{$json_data->{'data'}}) {
$response = $ua->get("$base_url/api/s/$entry->{'name'}/stat/device/");
unless($response->is_success) {
$logger->error("Can't have the site list from the Unifi controller: ".$response->status_line);
return;
}
my $json_data_ap = decode_json($response->decoded_content());
my %exists;
foreach my $AP (@{$json_data_ap->{'data'}}) {
$cache->set("Ubiquiti-" . $AP->{'mac'} , $AP->{'ip'} );
$exists{$AP->{'mac'}} = $TRUE;
foreach my $vap (@{$AP->{'vap_table'}}) {
$cache->set("Ubiquiti-" . $vap->{'bssid'}, $AP->{'ip'} ) unless $exists{$vap->{'bssid'}};
$exists{$vap->{'bssid'}} = $TRUE;
}
}
}
}
=item deauthenticateMacDefault
De-authenticate a MAC address from wireless network (including 802.1x).
New implementation using RADIUS Disconnect-Request.
=cut
sub deauthenticateMacRadius {
my ( $self, $mac, $is_dot1x ) = @_;
my $logger = $self->logger;
if ( !$self->isProductionMode() ) {
$logger->info("not in production mode... we won't perform deauthentication");
return 1;
}
$logger->debug("deauthenticate $mac using RADIUS Disconnect-Request deauth method");
return $self->radiusDisconnect($mac);
}
=item radiusDisconnect
Sends a RADIUS Disconnect-Request to the NAS with the MAC as the Calling-Station-Id to disconnect.
Optionally you can provide other attributes as an hashref.
Uses L<pf::util::radius> for the low-level RADIUS stuff.
=cut
# TODO consider whether we should handle retries or not?
sub radiusDisconnect {
my ($self, $mac, $add_attributes_ref) = @_;
my $logger = $self->logger;
# initialize
$add_attributes_ref = {} if (!defined($add_attributes_ref));
if (!defined($self->{'_radiusSecret'})) {
$logger->warn(
"Unable to perform RADIUS Disconnect-Request on $self->{'_ip'}: RADIUS Shared Secret not configured"
);
return;
}
$logger->info("deauthenticating $mac");
# Where should we send the RADIUS Disconnect-Request?
# to network device by default
my $send_disconnect_to = $self->{'_ip'};
# allowing client code to override where we connect with NAS-IP-Address
$send_disconnect_to = $add_attributes_ref->{'NAS-IP-Address'}
if (defined($add_attributes_ref->{'NAS-IP-Address'}));
my $response;
try {
my $locationlog = locationlog_view_open_mac($mac);
my $connection_info = {
nas_ip => $send_disconnect_to,
secret => $self->{'_radiusSecret'},
LocalAddr => $self->deauth_source_ip($send_disconnect_to),
};
# transforming MAC to the expected format 00-11-22-33-CA-FE
$mac = uc($mac);
$mac =~ s/:/-/g;
my $nasID = $locationlog->{'switch_mac'};
$nasID =~ s/://g;
# Standard Attributes
my $attributes_ref = {
'Calling-Station-Id' => $mac,
'NAS-Identifier' => $nasID,
};
# merging additional attributes provided by caller to the standard attributes
$attributes_ref = { %$attributes_ref, %$add_attributes_ref };
$response = perform_disconnect($connection_info, $attributes_ref);
} catch {
chomp;
$logger->warn("Unable to perform RADIUS Disconnect-Request: $_");
$logger->error("Wrong RADIUS secret or unreachable network device...") if ($_ =~ /^Timeout/);
};
return if (!defined($response));
return $TRUE if ( ($response->{'Code'} eq 'Disconnect-ACK') || ($response->{'Code'} eq 'CoA-ACK') );
$logger->warn(
"Unable to perform RADIUS Disconnect-Request."
. ( defined($response->{'Code'}) ? " $response->{'Code'}" : 'no RADIUS code' ) . ' received'
. ( defined($response->{'Error-Cause'}) ? " with Error-Cause: $response->{'Error-Cause'}." : '' )
);
return;
}
=head1 AUTHOR
Inverse inc. <info@inverse.ca>
=head1 COPYRIGHT
Copyright (C) 2005-2021 Inverse inc.
=head1 LICENSE
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.
=cut
1;
# vim: set shiftwidth=4:
# vim: set expandtab:
# vim: set backspace=indent,eol,start: