-
Notifications
You must be signed in to change notification settings - Fork 11
/
Smart.class.php
672 lines (599 loc) · 18.6 KB
/
Smart.class.php
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
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
<?php
// vim: :set filetype=php tabstop=4 shiftwidth=4 autoindent smartindent:
namespace FreePBX\modules\Firewall;
class Smart {
private $db; // DB handle
private $chansip = false; // This machine uses chansip
private $pjsip = false; // This machine uses pjsip
private $iax = false; // This machine uses IAX
private $firewall;
public function __construct($db = false) {
if (!$db || !($db instanceof \PDO)) {
throw new \Exception("Need a PDO Database handle");
}
$this->db = $db;
$this->chansip = false;
$this->pjsip = false;
$driver = \FreePBX::Config()->get('ASTSIPDRIVER');
switch ($driver) {
case 'both':
$this->chansip = true;
$this->pjsip = true;
break;
case 'chan_pjsip':
$this->pjsip = true;
break;
case 'chan_sip':
$this->chansip = true;
break;
default:
throw new \Exception("Crazy driver setting $driver");
}
$this->iax = $this->usesIax();
}
public function getSettings() {
$retarr = array("ssf" => true, "period" => 60, "responsive" => false);
$retarr['rprotocols'] = array();
if ($this->chansip) {
$retarr['rprotocols'] = array_merge($retarr['rprotocols'], array("chansip" => array("state" => true, "descr" => _("Legacy SIP (chan_sip)"))));
}
if ($this->pjsip) {
$retarr['rprotocols'] = array_merge($retarr['rprotocols'], array("pjsip" => array("state" => true, "descr" => _("SIP Protocol (pjsip)"))));
}
if ($this->iax) {
$retarr['rprotocols'] = array_merge($retarr['rprotocols'], array("iax" => array("state" => false, "descr" => _("IAX Protocol"))));
}
if ($this->getFirewallObj()->getConfig("responsivefw")) {
$retarr['responsive'] = true;
foreach ($retarr['rprotocols'] as $id => $null) {
$retarr['rprotocols'][$id]['state'] = $this->getFirewallObj()->getConfig($id, "rfw");
}
$retarr['fail2banbypass'] = $this->getFirewallObj()->getConfig("fail2banbypass");
}
//responsive firewall
$retarr['fpbxratelimit']['TIER1'] = $this->getFirewallObj()->getConfig('TIER1','fpbxratelimit');
$retarr['fpbxratelimit']['TIER2'] = $this->getFirewallObj()->getConfig('TIER2','fpbxratelimit');
$retarr['fpbxratelimit']['TIER3'] = $this->getFirewallObj()->getConfig('TIER3','fpbxratelimit');
$retarr['fpbxrfw']['TIERA'] = $this->getFirewallObj()->getConfig('TIERA','fpbxrfw');
$retarr['fpbxrfw']['TIERB'] = $this->getFirewallObj()->getConfig('TIERB','fpbxrfw');
$retarr['fpbxrfw']['TIERC'] = $this->getFirewallObj()->getConfig('TIERC','fpbxrfw');
return $retarr;
}
private function usesIax() {
// Does this machine have any IAX devices?
$sql = "SELECT `id` FROM `iax` LIMIT 1";
$q = $this->db->query($sql);
$rows = $q->fetchAll(\PDO::FETCH_ASSOC);
return (!empty($rows));
}
public function getAllPorts() {
// Returns ALL ports.
$retarr = array(
'signalling' => $this->getVoipPorts(),
'rtp' => $this->getRTPPorts(),
'udptl' => $this->getUDPTLports(),
'known' => $this->getKnown(),
'registrations' => $this->getRegistrations(),
);
return $retarr;
}
public function getVoipPorts() {
$ports = $this->getSipPorts();
if ($this->iax) {
$ports['udp'][] = $this->getIaxPort();
}
return $ports;
}
public function getRTPPorts() {
// These are always open to the world, on every interface.
// The only limitation is that we don't let people be dumb, and we'll
// never return less than 1024, or more than 65000. As RTP runs on
// UDP, it's not THAT critical, but better to be safe than sorry.
//
// Yes. This are just random ranges that I made up as 'reasonable'.
//
$s = \FreePBX::Sipsettings();
$sipsettings = $s->genConfig();
$ports = $sipsettings['rtp_additional.conf']['general'];
$start = (int) $ports['rtpstart'];
$end = (int) $ports['rtpend'];
if ($start < 1024) {
$start = 1024;
}
if ($end > 65535) {
$end = 65535;
}
// Make sure start and end are the right way round...
if ($end < $start) {
return array("start" => $end, "end" => $start);
} else {
return array("start" => $start, "end" => $end);
}
}
public function getUDPTLports() {
exec("grep -i \"^udptlstart\" /etc/asterisk/udptl_custom.conf | sed -r 's/.+=//g'", $out, $ret);
if (isset($out[0])) {
$start = (int) $out[0];
} else {
$start = 0;
}
exec("grep -i \"^udptlend\" /etc/asterisk/udptl_custom.conf | sed -r 's/.+=//g'", $outend, $ret);
if (isset($outend[0])) {
$end = (int) $outend[0];
} else {
$end = 0;
}
if ($start < 1024) {
//Either not configured or port is wrong. Use defaults.
$start = 4000;
}
if ($end > 65535 || $end < 1024) {
$end = 4999;
}
// Make sure start and end are the right way round...
if ($end < $start) {
return array("start" => $end, "end" => $start);
} else {
return array("start" => $start, "end" => $end);
}
}
public function getIaxPort() {
$sql = "SELECT `keyword`, `data` FROM `iaxsettings` WHERE `keyword` LIKE 'bind%'";
$q = $this->db->query($sql);
$iax = $q->fetchAll(\PDO::FETCH_ASSOC);
$bindport = 4569;
$bindaddr = "0.0.0.0";
foreach ($iax as $res) {
if (empty($res['data'])) {
continue;
}
if ($res['keyword'] == "bindport") {
$bindport = $res['data'];
} elseif ($res['keyword'] == "bindaddr") {
$bindaddr = $res['data'];
}
}
return array("dest" => $bindaddr, "dport" => $bindport, "name" => "iax");
}
public function getSipPorts() {
// Returns an array of ports or ranges used by SIP or PJSIP.
$udp = array();
$tcp = array();
$ss = \FreePBX::Sipsettings();
$allBinds = $ss->getBinds(true);
// Do we want chansip settings?
if ($this->chansip) {
$udpport = 5060;
$tlsport = false;
$tcpport = false;
if (isset($allBinds['sip']) && is_array($allBinds['sip'])) {
$sip = array_shift($allBinds['sip']);
if (isset($sip['udp']) && (int) $sip['udp'] > 1024) {
$udpport = (int) $sip['udp'];
}
if (isset($sip['tls']) && (int) $sip['tls'] > 1024) {
$tlsport = (int) $sip['tls'];
}
if (isset($sip['tcp']) && (int) $sip['tcp'] > 1024) {
$tcpport = (int) $sip['tcp'];
}
}
$udp[] = array("dest" => "::", "dport" => $udpport, "name" => "chansip");
// Are we listening for TCP connections?
if ($tcpport) {
$tcp[] = array("dest" => "::", "dport" => $tcpport, "name" => "chansip");
}
// Or TLS?
if ($tlsport) {
$tcp[] = array("dest" => "::", "dport" => $tlsport, "name" => "chansip");
}
}
// Do we have pjsip?
if ($this->pjsip) {
// Woo. What are our settings?
// ss->getBinds should always return correct information.
// But be paranoid.
if (!isset($allBinds['pjsip']) || !is_array($allBinds['pjsip'])) {
$pjbinds = array();
} else {
$pjbinds = $allBinds['pjsip'];
}
foreach ($pjbinds as $allports) {
foreach ($allports as $protocol => $port) {
// Ignore protocol if we weren't given a port
if ((int) $port < 1024) {
continue;
}
// If it's not udp, it's tcp.
if ($protocol == "udp") {
$udp[] = array("dest" => "::", "dport" => $port, "name" => "pjsip");
} else {
$tcp[] = array("dest" => "::", "dport" => $port, "name" => "pjsip");
}
}
}
}
$retarr = array("udp" => $udp, "tcp" => $tcp);
return $retarr;
}
public function getKnown() {
// Figure out who our known entities are.
$discovered = array();
if ($this->chansip) {
// Trunks and extens are both in the 'sip' table.
$sql = "SELECT DISTINCT(`data`) FROM `sip` WHERE `keyword`='host'";
$q = $this->db->query($sql);
$siphosts = $q->fetchAll(\PDO::FETCH_ASSOC);
foreach ($siphosts as $sip) {
// Trim anything after a semicolon, which could be a comment
$hostarr = explode(";", $sip['data']);
$host = trim($hostarr[0]);
if ($host == "dynamic") {
continue;
}
$discovered[$host] = true;
}
// Does an extension specifically permit a range?
$sql = "SELECT DISTINCT(`data`) FROM `sip` WHERE `keyword`='permit'";
$q = $this->db->query($sql);
$sippermits = $q->fetchAll(\PDO::FETCH_ASSOC);
foreach ($sippermits as $sip) {
// permits may be seperated by ampersands, so
// make sure they are all added.
$permits = explode("&", $sip['data']);
foreach ($permits as $p) {
$discovered[$p] = true;
}
}
}
if ($this->iax) {
// Find IAX trunks...
$sql = "SELECT DISTINCT(`data`) FROM `iax` WHERE `keyword`='host'";
$q = $this->db->query($sql);
$iaxhosts = $q->fetchAll(\PDO::FETCH_ASSOC);
foreach ($iaxhosts as $iax) {
// Trim anything after a semicolon, which could be a comment
$hostarr = explode(";", $iax['data']);
$host = trim($hostarr[0]);
if ($host == "dynamic") {
continue;
}
$discovered[$host] = true;
}
// Extensions?
$sql = "SELECT DISTINCT(`data`) FROM `iax` WHERE `keyword`='permit'";
$q = $this->db->query($sql);
$iaxpermits = $q->fetchAll(\PDO::FETCH_ASSOC);
foreach ($iaxpermits as $iax) {
// permits may be seperated by ampersands, so
// make sure they are all added.
$permits = explode("&", $iax['data']);
foreach ($permits as $p) {
$discovered[$p] = true;
}
}
}
// PJSIP?
if ($this->pjsip) {
$sql = "SELECT DISTINCT(`data`) FROM `pjsip` WHERE `keyword`='sip_server' OR `keyword`='match'";
$q = $this->db->query($sql);
$pjsiptrunks = $q->fetchAll(\PDO::FETCH_ASSOC);
foreach ($pjsiptrunks as $p) {
if (!empty($p['data'])) {
if (strpos($p['data'], ",")) {
$match_split = explode(",", $p['data']);
foreach ($match_split as $k=>$v) $discovered[$v] = true;
} else {
$discovered[$p['data']] = true;
}
}
}
// PJSip extensions don't have allow/deny at the moment.
}
// Now validate them all!
$retarr = array();
foreach (array_keys($discovered) as $d) {
// It's possible it's blank, or a space, or something
$d = trim($d);
if (!$d) {
continue;
}
// Ensure we don't start with "0.0.0.0"
if (strpos($d, "0.0.0.0") === 0) {
continue;
}
// Is this an IP address?
if (filter_var($d, FILTER_VALIDATE_IP)) {
$retarr[$d] = $d;
continue;
}
// Is this a Network definition?
if (strpos($d, "/") !== false) {
// Yes it is.
$entry = $this->returnCidr($d);
$retarr[$entry] = $entry;
continue;
}
// Well that means it's a hostname.
$retarr = array_merge($retarr, $this->lookup($d));
// Is there an SRV record?
$srvdns = @dns_get_record('_sip._udp.'.$d, \DNS_SRV);
if (!$srvdns) {
// Avoid to flood logs.
//dbug("An error occured on SRV record _sip._udp.$d : ");
$srvdns = false;
}
if(!empty($srvdns) && is_array($srvdns)){
//There's a SRV record
foreach($srvdns as $sd) {
$srvrecord = $this->lookup($sd['target']);
$retarr = array_merge($retarr, $srvrecord);
}
}
}
return $retarr;
}
public function returnCidr($entry = false) {
if (!$entry) {
throw new \Exception("No Net/CIDR Given");
}
// To start with, does it have a / in it?
if (strpos($entry, "/") === false) {
throw new \Exception("Asked to parse $entry, don't know why");
}
// Good.
list($subnet, $network) = explode("/", $entry);
// And it's a valid network, right?
if (!filter_var($subnet, FILTER_VALIDATE_IP)) {
// Wut.
return false;
}
// OK. We either have IP/CIDR or a IP/NETMASK
// If cidr validates as an IP address, that means it's a netmask.
if (filter_var($network, FILTER_VALIDATE_IP)) {
// netmask.
// Make sure it's not /32
if ($network === "255.255.255.255") {
return $subnet;
}
$cidr = 32-log((ip2long($network)^4294967295)+1,2);
return $this->trimSubnet($subnet,$cidr);
}
// Otherwise it should be a valid CIDR.
$net = (int) $network;
if ($net >= 8 && $net <= 128) { // 128 == ipv6
if (filter_var($subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
// If it's /32 and it's ipv4, just return the host
if ($net == 32) {
return $subnet;
}
}
return $this->trimSubnet($subnet,$net);
}
return false;
}
private function trimSubnet($subnet, $cidr) {
// IPv6 check
if (filter_var($subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
// Don't even try to think about it. Just return it as it is.
return "$subnet/$cidr";
}
// OK, we're IPv4. Get a long from the cidr
$netmask = pow(2, $cidr)-1 << (32 - $cidr);
// Get a long from the Subnet
$longnet = ip2long($subnet);
// Now AND them and return the bits that should be on
return long2ip($longnet & $netmask)."/$cidr";
}
public function lookup($host = false, $allowcache = true) {
static $cache;
static $previous;
if (!$host) {
throw new \Exception("No host given");
}
// This is for PHP 5.4 and below
if (!is_array($cache)) {
$cache = array();
$previous = array();
}
// Do we need to refresh this lookup?
if (!$allowcache) {
unset($cache[$host]);
}
// Have we looked this up previously?
if (!isset($cache[$host])) {
// No. OK, so is this an IP?
if (filter_var($host, FILTER_VALIDATE_IP)) {
// Well that was easy.
$cache[$host] = array($host);
return array($host);
}
// Let's do some DNS-ing
// TODO: See how this goes. It might be better to use something like http://www.purplepixie.org/phpdns/
try {
$dns = dns_get_record($host, \DNS_A|\DNS_AAAA);
} catch (\Exception $e) {
$dns = array();
}
// Sometimes we may have a transient DNS error. If dns_get_record returned nothing,
// but last time it returned something, we return the last one. This only happens
// once.
if (!$dns) {
if (isset($previous[$host]) && $previous[$host]) {
$dns = $previous[$host];
unset($previous[$host]);
}
} else {
$previous[$host] = $dns;
}
$retarr = array();
// TODO: IPv6
foreach ($dns as $record) {
if ($record['type'] == "A") {
$retarr[$record['ip']] = true;
}
}
$keys = array_keys($retarr);
$cache[$host] = $keys;
}
$ret = $cache[$host];
return $ret;
}
public function getRegistrations() {
// Get all registered devices
$astman = \FreePBX::create()->astman;
// This gives us an array
$contacts = $this->getPjsipContacts($astman);
// Pass by ref to the rest to remove dupes
$this->getChansipContacts($astman, $contacts);
$this->getIaxContacts($astman, $contacts);
return array_keys($contacts);
}
private function getPjsipContacts($astman) {
$response = $astman->send_request('Command',array('Command'=>"pjsip show contacts"));
// This is an amazingly awful format to parse.
$lines = explode("\n", $response['data']);
$inheader = true;
$istrunk = $isendpoint = false;
$contacts = array();
foreach ($lines as $l) {
if ($inheader) {
if (isset($l[1]) && $l[1] == "=") {
// Last line of the header.
$inheader = false;
}
continue;
}
$l = trim($l);
if (!$l) {
continue;
}
// If we have a line starting with 'Contact:' then we found one!
// This will be along the lines of '400/sip:[email protected]:5061 Avail 10.121'
if (strpos($l, "Contact:") === 0) {
// FREEPBX-12143 - Don't return unavail endpoints
if (strpos($l, " Unavail") !== false) {
continue;
}
// If there is no @, we pick it up as part of a trunk.
if (preg_match("/Contact:\s+(.+)@(.+?)\s/", $l, $out)) {
// Ok, we have a contact. This should be an IP address. Is it?
if (preg_match("/(?:\[?)([0-9a-f:\.]+)(?:\]?):(.+)/", $out[2], $ipaddr)) {
// Ensure a random hostname like 'e.de' doesn't appear to be valid
if (filter_var($ipaddr[1], FILTER_VALIDATE_IP)) {
$contacts[$ipaddr[1]] = true;
} else {
// it might be possible that due to 15 digit emergency cid did, asterisk is
// striping last few octets of IP due to which VALIDATE IP might fail, hence
// pick the ip from the show aor command */
if (isset($out[1]) && !empty($out[1])) {
$extData = explode('/', $out[1]);
$extNum = $extData[0];
}
if (strlen((string)$extNum) == 15) {
$ip = $this->getPjsipContactAOR($extNum);
if (filter_var($ip, FILTER_VALIDATE_IP)) {
$contacts[$ip] = true;
}
}
}
} else {
$ip = $this->filterDataByAOR($out);
if (!empty($ip)) {
$contacts[$ip] = true;
} else {
// It's a hostname, likely to be a trunk. Don't resolve,
// as we've already done that as part of the registration
// print "Unknown host ".$out[2].", trunk?\n";
continue;
}
}
}
}
}
return $contacts;
}
private function getChansipContacts($astman, &$contacts) {
$response = $astman->send_request('Command',array('Command'=>"sip show peers"));
$lines = explode("\n", $response['data']);
foreach ($lines as $l) {
if (!$l) {
continue;
}
$tmparr = preg_split("/\s+/", $l);
if (filter_var($tmparr[1], FILTER_VALIDATE_IP)) {
$contacts[$tmparr[1]] = true;
}
}
}
private function getIaxContacts($astman, &$contacts) {
$response = $astman->send_request('Command',array('Command'=>"iax2 show peers"));
$lines = explode("\n", $response['data']);
foreach ($lines as $l) {
if (!$l) {
continue;
}
$tmparr = preg_split("/\s+/", $l);
if (filter_var($tmparr[1], FILTER_VALIDATE_IP)) {
$contacts[$tmparr[1]] = true;
}
}
}
private function getPjsipContactAOR($extNum) {
$astman = \FreePBX::create()->astman;
$command = "pjsip show aor " . $extNum;
$response = $astman->send_request('Command',array('Command'=>$command));
$lines = explode("\n", $response['data']);
$inheader = true;
$istrunk = $isendpoint = false;
$contacts = array();
foreach ($lines as $l) {
if ($inheader) {
if (isset($l[1]) && $l[1] == "=") {
// Last line of the header.
$inheader = false;
}
continue;
}
$l = trim($l);
if (!$l) {
continue;
}
// If we have a line starting with 'contact:' then we found one!
if (strpos($l, "contact") === 0) {
if (strpos($l, " Unavail") !== false) {
continue;
}
// If there is no @, we pick it up as part of a trunk.
if (preg_match("/contact\s+:\s+(.+)@(.+)/", $l, $out)) {
// Ok, we have a contact. This should be an IP address. Is it?
if (preg_match("/(?:\[?)([0-9a-f:\.]+)(?:\]?):(.+)/", $out[2], $ipaddr)) {
// Ensure a random hostname like 'e.de' doesn't appear to be valid
if (filter_var($ipaddr[1], FILTER_VALIDATE_IP)) {
return $ipaddr[1];
}
}
}
}
}
}
private function filterDataByAOR($out) {
if (isset($out[1]) && !empty($out[1])) {
$extData = explode('/', $out[1]);
$extNum = $extData[0];
}
if (strlen((string)$extNum) == 15) {
$ip = $this->getPjsipContactAOR($extNum);
if (!empty($ip)) {
return $ip;
}
}
return false;
}
function getFirewallObj() {
if (!$this->firewall) {
$this->firewall = \FreePBX::Firewall();
}
return $this->firewall;
}
}