• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

NathanGibbs3 / BASE / 587

pending completion
587

push

travis-ci-com

NathanGibbs3
Merge branch 'devel'

504 of 504 new or added lines in 21 files covered. (100.0%)

2594 of 16816 relevant lines covered (15.43%)

20.97 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

22.64
/base_common.php
1
<?php
2
/*******************************************************************************
3
** Basic Analysis and Security Engine (BASE)
4
** Copyright (C) 2004 BASE Project Team
5
** Copyright (C) 2000 Carnegie Mellon University
6
**
7
** (see the file 'base_main.php' for license details)
8
**
9
** Project Leads: Kevin Johnson <kjohnson@secureideas.net>
10
**                Sean Muller <samwise_diver@users.sourceforge.net>
11
** Built upon work by Roman Danyliw <rdd@cert.org>, <roman@danyliw.com>
12
**
13
** Purpose: Common Functions
14
********************************************************************************
15
** Authors:
16
********************************************************************************
17
** Kevin Johnson <kjohnson@secureideas.net
18
**
19
********************************************************************************
20
*/
21

22
function GetSensorIDs($db)
23
{
24
   $result = $db->baseExecute("SELECT sid FROM sensor;");
×
25

26
   while( $myrow = $result->baseFetchRow() ) {
×
27
        $sensor_ids[] = $myrow[0];
×
28
   }
29

30
   $result->baseFreeRows();
×
31

32
   return $sensor_ids;
×
33
}
34

35
function GetSensorName($sid, $db)
36
{
37
    $name = "";
×
38

39
    $temp_sql = "SELECT sid, hostname, interface, filter FROM sensor WHERE sid='".$sid."'";
×
40
    $tmp_result = $db->baseExecute($temp_sql);
×
41
    if ( $tmp_result )
42
    {
43
       $myrow = $tmp_result->baseFetchRow();
×
44
       $name = $myrow[1].':'.$myrow[2];
×
45
       if ( $myrow[3] != "" )
×
46
          $name = $name.':'.$myrow[3];
×
47
    }
48
    $tmp_result->baseFreeRows();
×
49

50
    return $name;
×
51
}
52

53
function GetVendor($mac) {
54
        $mac = str_replace(":", "", $mac);
66✔
55
        $mac = substr($mac, 0, 6);
66✔
56
        $vendor = 'unknown';
66✔
57
        if (@$fp = fopen("base_mac_prefixes.map", "r")) {
66✔
58
                while (!feof($fp)) {
44✔
59
                        $line = fgets($fp);
44✔
60
                        if (strcmp($mac, substr($line, 0, 6)) == 0) {
44✔
61
                                $vendor = substr($line, 8, strlen($line)-9);
22✔
62
                        }
8✔
63
                }
16✔
64
                fclose($fp);
44✔
65
        }else{
16✔
66
                return "Can't open vendor map.";
22✔
67
        }
68
        return $vendor;
44✔
69
}
70

71
function InputSafeSQL (&$SQLstr)
72
/* Removes the escape sequence of \' => ' which arise when a variable containing a '-character is passed
73
   through a POST query.  This is needed since otherwise the MySQL parser complains */
74
{
75
   $SQLstr = str_replace("\'", "'", $SQLstr);
×
76
   $SQLstr = str_replace("\\\"", "\"", $SQLstr);
×
77
}
78

79
function PrintProtocolProfileGraphs ($db){
80
        $tcp_cnt = TCPPktCnt($db);
×
81
        $udp_cnt = UDPPktCnt($db);
×
82
        $icmp_cnt = ICMPPktCnt($db);
×
83
        $portscan_cnt = PortscanPktCnt($db);
×
84
        $layer4_cnt = $tcp_cnt + $udp_cnt + $icmp_cnt + $portscan_cnt;
×
85
        $tcp_percent_show = HtmlPercent($tcp_cnt,$layer4_cnt);
×
86
        $udp_percent_show = HtmlPercent($udp_cnt,$layer4_cnt);
×
87
        $icmp_percent_show = HtmlPercent($icmp_cnt,$layer4_cnt);
×
88
        $portscan_percent_show = HtmlPercent($portscan_cnt,$layer4_cnt);
×
89
   echo '<TABLE WIDTH="100%" BORDER=0>
90
         <TR><TD>TCP<A HREF="base_qry_main.php?new=1'.
91
                           '&amp;layer4=TCP&amp;num_result_rows=-1&amp;sort_order=time_d&amp;submit='._QUERYDBP.'">
92
                           ('.$tcp_percent_show.')</A></TD><TD></TD></TR></TABLE>
93
                  <TABLE class="summarygraph" WIDTH="100%" BORDER=1 CELLSPACING=0 CELLPADDING=0>';
94
        print '<tr>'. HBarGraph($tcp_cnt,$layer4_cnt,'ff0000','cccccc');
×
95
                      echo '</TR></TABLE>';
×
96

97
    echo '<TABLE WIDTH="100%" BORDER=0>
98
          <TR><TD>UDP<A HREF="base_qry_main.php?new=1'.
99
                            '&amp;layer4=UDP&amp;num_result_rows=-1&amp;sort_order=time_d&amp;submit='._QUERYDBP.'">
100
                            ('.$udp_percent_show.')</A></TD><TD></TD></TR></TABLE>
101
                  <TABLE class="summarygraph" WIDTH="100%" BORDER=1 CELLSPACING=0 CELLPADDING=0>';
102
        print '<tr>'. HBarGraph($udp_cnt,$layer4_cnt,'ff0000','cccccc');
×
103
                      echo '</TR></TABLE>';
×
104

105
     echo '<TABLE WIDTH="100%" BORDER=0>
106
           <TR><TD>ICMP<A HREF="base_qry_main.php?new=1'.
107
                              '&amp;layer4=ICMP&amp;num_result_rows=-1&amp;sort_order=time_d&amp;submit='._QUERYDBP.'">
108
                              ('.$icmp_percent_show.')</A></TD><TD></TD></TR></TABLE>
109
                  <TABLE class="summarygraph" WIDTH="100%" BORDER=1 CELLSPACING=0 CELLPADDING=0>';
110
        print '<tr>'. HBarGraph($icmp_cnt,$layer4_cnt,'ff0000','cccccc');
×
111
                      echo '</TR></TABLE>';
×
112
    
113
     echo '<CENTER><HR NOSHADE WIDTH="70%"></CENTER>';
×
114

115
     echo '<TABLE WIDTH="100%" BORDER=0>
116
           <TR><TD>'._PORTSCAN.'
117
               <A HREF="base_qry_main.php?new=1'.
118
'&amp;layer4=RawIP&amp;num_result_rows=-1&amp;sort_order=time_d&amp;submit='._QUERYDBP.'">('.$portscan_percent_show.')</A>
119
                    </TD><TD></TD></TR></TABLE>
120
                  <TABLE class="summarygraph" WIDTH="100%" BORDER=1 CELLSPACING=0 CELLPADDING=0>';
121
        print '<tr>'. HBarGraph($portscan_cnt,$layer4_cnt,'ff0000','cccccc');
×
122
                      echo '</TR></TABLE>';
×
123
}
124

125
function BuildIPFormVars($ipaddr)
126
{
127
    return ''.
128
    '&amp;ip_addr%5B0%5D%5B0%5D=+&amp;ip_addr%5B0%5D%5B1%5D=ip_src&amp;ip_addr%5B0%5D%5B2%5D=%3D'.
129
    '&amp;ip_addr%5B0%5D%5B3%5D='.$ipaddr.
130
    '&amp;ip_addr%5B0%5D%5B8%5D=+&amp;ip_addr%5B0%5D%5B9%5D=OR'.
131
    '&amp;ip_addr%5B1%5D%5B0%5D=+&amp;ip_addr%5B1%5D%5B1%5D=ip_dst&amp;ip_addr%5B1%5D%5B2%5D=%3D'.
132
    '&amp;ip_addr%5B1%5D%5B3%5D='.$ipaddr.
133
    '&amp;ip_addr%5B1%5D%5B8%5D=+&amp;ip_addr%5B1%5D%5B9%5D=+';
134
}
135

136
function BuildSrcIPFormVars($ipaddr)
137
{
138
    return ''.
139
    '&amp;ip_addr%5B0%5D%5B0%5D=+&amp;ip_addr%5B0%5D%5B1%5D=ip_src&amp;ip_addr%5B0%5D%5B2%5D=%3D'.
140
    '&amp;ip_addr%5B0%5D%5B3%5D='.$ipaddr.
141
    '&amp;ip_addr%5B0%5D%5B8%5D=+&amp;ip_addr%5B0%5D%5B9%5D=+';
142
}
143

144
function BuildDstIPFormVars($ipaddr)
145
{
146
    return ''.
147
    '&amp;ip_addr%5B0%5D%5B0%5D=+&amp;ip_addr%5B0%5D%5B1%5D=ip_dst&amp;ip_addr%5B0%5D%5B2%5D=%3D'.
148
    '&amp;ip_addr%5B0%5D%5B3%5D='.$ipaddr.
149
    '&amp;ip_addr%5B0%5D%5B8%5D=+&amp;ip_addr%5B0%5D%5B9%5D=+';
150
}
151

152
function BuildUniqueAddressLink($addr_type, $raw = "" )
153
{
154
   return '<A HREF="base_stat_uaddr.php?addr_type='.$addr_type.$raw.'">';
×
155
}
156

157
function BuildUniqueAlertLink($raw)
158
{
159
   return '<A HREF="base_stat_alerts.php'.$raw.'">';
×
160
}
161

162
function BuildAddressLink($ipaddr, $netmask)
163
{
164
   return '<A HREF="base_stat_ipaddr.php?ip='.rawurlencode($ipaddr).
×
165
                                       '&amp;netmask='.$netmask.'">';
166
}
167

168
/* Adds another blank row to a given criteria element */
169
function AddCriteriaFormRow ( &$submit, $submit_value, &$cnt, &$criteria_array, $max )
170
{
171
   $submit = $submit_value;
×
172

173
  ++$cnt;
×
174
  InitArray($criteria_array[$cnt-1], $max, 0, "");   
×
175
}
176

177
function IPProto2str($ipproto_code)
178
{
179
   switch($ipproto_code)
180
   {
181
      case 0:
×
182
          return "IP";
×
183
      case 1:
×
184
          return "ICMP";
×
185
      case 2:
×
186
          return "IGMP";
×
187
      case 4:
×
188
          return "IPIP tunnels";
×
189
      case 6:
×
190
          return "TCP";
×
191
      case 8:
×
192
          return "EGP";
×
193
      case 12:
×
194
          return "PUP";
×
195
      case  17:
×
196
          return "UDP";
×
197
      case 22:
×
198
          return "XNS UDP";
×
199
      case 29:
×
200
          return "SO TP Class 4";
×
201
      case 41:
×
202
          return "IPv6 header";
×
203
      case 43:
×
204
          return "IPv6 routing header";
×
205
      case 44:
×
206
          return "IPv6 fragmentation header";
×
207
      case 46: 
×
208
          return "RSVP";
×
209
      case 47:
×
210
          return "GRE";
×
211
      case 50: 
×
212
          return "IPSec ESP";
×
213
      case 51: 
×
214
          return "IPSec AH";
×
215
      case 58: 
×
216
          return "ICMPv6";
×
217
      case 59: 
×
218
          return "IPv6 no next header";
×
219
      case 60:
×
220
          return "IPv6 destination options";
×
221
      case 92:
×
222
          return "MTP";
×
223
      case 98:
×
224
          return "Encapsulation header";
×
225
      case 103: 
×
226
          return "PIM";
×
227
      case 108:
×
228
          return "COMP";
×
229
      case 255: 
×
230
          return "Raw IP";
×
231
      default:
232
          return $ipproto_code;
×
233
   }
234
} 
235

236
function TCPOption2str($tcpopt_code)
237
/* per RFC 1072, 1323, 1644 */
238
{
239
   switch($tcpopt_code)
240
   {
241
      case 2:                  /* TCPOPT_MAXSEG - maximum segment*/ 
×
242
          return "(2) MSS";
×
243
      case 0:                  /* TCPOPT_EOL */
×
244
          return "(0) EOL";
×
245
      case 1:                  /* TCPOPT_NOP */
×
246
          return "(1) NOP";
×
247
      case 3:                  /* TCPOPT_WSCALE (rfc1072)- window scale factor */
×
248
          return "(3) WS";
×
249
      case 5:                  /* TCPOPT_SACK (rfc1072)- selective ACK */
×
250
          return "(5) SACK";
×
251
      case 4:                  /* TCPOPT_SACKOK (rfc1072)- selective ACK OK */
×
252
          return "(4) SACKOK";
×
253
      case 6:                  /* TCPOPT_ECHO (rfc1072)- echo */
×
254
          return "(6) Echo";
×
255
      case 7:                  /* TCPOPT_ECHOREPLY (rfc1072)- echo reply */
×
256
          return "(7) Echo Reply";
×
257
      case 8:                  /* TCPOPT_TIMESTAMP (rfc1323)- timestamps */
×
258
          return "(8) TS";
×
259
      case 9:                  /* RFC1693 */
×
260
          return "(9) Partial Order Connection Permitted";
×
261
      case 10:                  /* RFC1693 */ 
×
262
          return "(10) Partial Order Service Profile";
×
263
      case 11:                 /* TCPOPT_CC (rfc1644)- CC options */
×
264
          return "(11) CC";
×
265
      case 12:                 /* TCPOPT_CCNEW (rfc1644)- CC options */
×
266
          return "(12) CCNEW";
×
267
      case 13:                 /* TCPOPT_CCECHO (rfc1644)- CC options */
×
268
          return "(13) CCECHO";
×
269
      case 14:                 /* RFC1146 */
×
270
          return "(14) TCP Alternate Checksum Request";
×
271
      case 15:                 /* RFC1146 */
×
272
          return "(15) TCP Alternate Checksum Data";
×
273
      case 16:
×
274
          return "(16) Skeeter";
×
275
      case 17:
×
276
          return "(17) Bubba";
×
277
      case 18:                 /* Subbu and Monroe */
×
278
          return "(18) Trailer Checksum Option";
×
279
      case 19:                 /* Subbu and Monroe */
×
280
          return "(19) MD5 Signature";
×
281
      case 20:                 /* Scott */
×
282
          return "(20) SCPS Capabilities";
×
283
      case 21:                /* Scott */
×
284
          return "(21) Selective Negative Acknowledgements";
×
285
      case 22:                /* Scott */
×
286
          return "(22) Record Boundaries";
×
287
      case 23:                /* Scott */
×
288
          return "(23) Corruption Experienced";
×
289
      case 24:                /* Sukonnik */
×
290
          return "(24) SNAP";
×
291
      case 25:
×
292
          return "(25) Unassigned";
×
293
      case 26:                /* Bellovin */
×
294
          return "(26) TCP Compression Filter";
×
295
      default:
296
          return $tcpopt_code;
×
297
   }
298
}
299

300
function IPOption2str($ipopt_code)
301
{
302
   switch($ipopt_code)
303
   {
304
      case 7:              /* IPOPT_RR */
×
305
          return "RR";
×
306
      case 0:              /* IPOPT_EOL */
×
307
          return "EOL";
×
308
      case 1:              /* IPOPT_NOP */
×
309
          return "NOP";
×
310
      case 0x44:           /* IPOPT_TS */
×
311
          return "TS";
×
312
      case 0x82:           /* IPOPT_SECURITY */
×
313
          return "SEC";
×
314
      case 0x83:           /* IPOPT_LSRR */
×
315
          return "LSRR";
×
316
      case 0x84:           /* IPOPT_LSRR_E */
×
317
          return "LSRR_E";
×
318
      case 0x88:           /* IPOPT_SATID */
×
319
          return "SID";
×
320
      case 0x89:           /* IPOPT_SSRR */
×
321
          return "SSRR";
×
322
  }
323
}
324

325
function ICMPType2str($icmp_type)
326
{
327
  switch ($icmp_type)
328
  {
329
      case 0:                             /* ICMP_ECHOREPLY */
×
330
          return "Echo Reply";
×
331
      case 3:                             /* ICMP_DEST_UNREACH */
×
332
          return "Destination Unreachable";
×
333
      case 4:                             /* ICMP_SOURCE_QUENCH */
×
334
          return "Source Quench";
×
335
      case 5:                             /* ICMP_REDIRECT */
×
336
          return "Redirect";
×
337
      case 8:                             /* ICMP_ECHO */
×
338
          return "Echo Request";
×
339
      case 9:
×
340
          return "Router Advertisement";
×
341
      case 10:
×
342
          return "Router Solicitation"; 
×
343
      case 11:                            /* ICMP_TIME_EXCEEDED */
×
344
          return "Time Exceeded";
×
345
      case 12:                            /* ICMP_PARAMETERPROB */
×
346
          return "Parameter Problem";
×
347
      case 13:                            /* ICMP_TIMESTAMP */
×
348
          return "Timestamp Request";
×
349
      case 14:                            /* ICMP_TIMESTAMPREPLY */
×
350
          return "Timestamp Reply";
×
351
      case 15:                            /* ICMP_INFO_REQUEST */
×
352
          return "Information Request";
×
353
      case 16:                            /* ICMP_INFO_REPLY */
×
354
          return "Information Reply";
×
355
      case 17:                            /* ICMP_ADDRESS */
×
356
          return "Address Mask Request";
×
357
      case 18:                            /* ICMP_ADDRESSREPLY */
×
358
          return "Address Mask Reply";
×
359
      case 19:
×
360
          return "Reserved (security)";
×
361
      case 20:
×
362
          return "Reserved (robustness)";
×
363
      case 21:
×
364
          return "Reserved (robustness)";
×
365
      case 22:
×
366
          return "Reserved (robustness)";
×
367
      case 23:
×
368
          return "Reserved (robustness)";
×
369
      case 24:
×
370
          return "Reserved (robustness)";
×
371
      case 25:
×
372
          return "Reserved (robustness)";
×
373
      case 26:
×
374
          return "Reserved (robustness)";
×
375
      case 27:
×
376
          return "Reserved (robustness)";
×
377
      case 28:
×
378
          return "Reserved (robustness)";
×
379
      case 29:
×
380
          return "Reserved (robustness)";
×
381
      case 30:
×
382
          return "Traceroute";
×
383
      case 31:
×
384
          return "Datagram Conversion Error";
×
385
      case 32:
×
386
          return "Mobile Host Redirect";
×
387
      case 33:
×
388
          return "IPv6 Where-Are-You";
×
389
      case 34:
×
390
          return "IPv6 I-Am-Here";
×
391
      case 35:
×
392
          return "Mobile Registration Request";
×
393
      case 36:
×
394
          return "Mobile Registration Reply";
×
395
      case 37:
×
396
          return "Domain Name Request";
×
397
      case 38:
×
398
          return "Domain Name Reply";
×
399
      case 39:
×
400
          return "SKIP";
×
401
      case 40:
×
402
          return "Photuris";
×
403
      default:
404
          return $icmp_type;
×
405
  }
406
}
407

408
function ICMPCode2str($icmp_type, $icmp_code)
409
{
410
  if ( $icmp_type == 3 )
×
411
  {
412
     switch ($icmp_code)
413
     {
414
        case 0:                                    /* ICMP_NET_UNREACH */
×
415
            return "Network Unreachable";
×
416
        case 1:                                    /* ICMP_HOST_UNREACH */
×
417
            return "Host Unreachable";
×
418
        case 2:                                    /* ICMP_PROT_UNREACH */
×
419
            return "Protocol Unreachable";
×
420
        case 3:                                    /* ICMP_PORT_UNREACH */
×
421
            return "Port Unreachable";
×
422
        case 4:                                    /* ICMP_FRAG_NEEDED */
×
423
            return "Fragmentation Needed/DF set";
×
424
        case 5:                                    /* ICMP_SR_FAILED */
×
425
            return "Source Route failed";
×
426
        case 6:                                    /* ICMP_NET_UNKNOWN */
×
427
            return "Network Unknown";
×
428
        case 7:                                    /* ICMP_HOST_UNKNOWN */
×
429
            return "Host Unknown";
×
430
        case 8:                                    /* ICMP_HOST_ISOLATED */
×
431
            return "Host Isolated";
×
432
        case 9:                                    /* ICMP_NET_ANO */
×
433
            return "Network ANO";
×
434
        case 10:                                   /* ICMP_HOST_ANO */
×
435
            return "Host ANO";
×
436
        case 11:                                   /* ICMP_NET_UNR_TOS */
×
437
            return "Network Unreach TOS";
×
438
        case 12:                                   /* ICMP_HOST_UNR_TOS */
×
439
            return "Host Unreach TOS";
×
440
        case 13:                                   /* ICMP_PKT_FILTERED */
×
441
            return "Packet Filtered";
×
442
        case 14:                                   /* ICMP_PREC_VIOLATION */
×
443
            return "Precedence violation";
×
444
        case 15:                                   /* ICMP_PREC_CUTOFF */
×
445
            return "Precedence cut off";
×
446
        default:
447
            return $icmp_code;
×
448
     }
449
  } 
450
  elseif ( $icmp_type == 5 )
×
451
  {
452
     switch ($icmp_code)
453
     {
454
        case 0:
×
455
            return "Redirect datagram for network/subnet";
×
456
        case 1:
×
457
            return "Redirect datagram for host";
×
458
        case 2:
×
459
            return "Redirect datagram for ToS and network";
×
460
        case 3:
×
461
            return "Redirect datagram for Tos and host";
×
462
        default:
463
            return $icmp_code;
×
464
      }
465
   }
466
   elseif ( $icmp_type == 9 ) 
×
467
   {
468
      switch ($icmp_code)
469
      {
470
         case 0:
×
471
             return "Normal router advertisement";
×
472
         case 16:
×
473
             return "Does not route common traffic";
×
474
         default:
475
             return $icmp_code;
×
476
      }
477
   }
478
   elseif ( $icmp_type == 11 )
×
479
   {
480
      switch ($icmp_code)
481
      {
482
         case 0:
×
483
             return "TTL exceeded in transit";
×
484
         case 1:
×
485
             return "Fragment reassembly time exceeded";
×
486
         default:
487
             return $icmp_code;
×
488
      }
489
   }
490
   elseif ( $icmp_type == 12 ) 
×
491
   {
492
      switch ($icmp_code)
493
      {
494
         case 0:
×
495
             return "Pointer indicates error";
×
496
         case 1:
×
497
             return "Missing a required option";
×
498
         case 2:
×
499
             return "Bad length";
×
500
         default:
501
             return $icmp_code;
×
502
      }
503
   }
504
   elseif ( $icmp_type == 40 )
×
505
   {
506
      switch ($icmp_code)
507
      {
508
         case 0:
×
509
            return "Bad SPI";
×
510
         case 1:
×
511
            return "Authentication failed";
×
512
         case 2:
×
513
            return "Decompression failed";
×
514
         case 3:
×
515
            return "Decryption failed";
×
516
         case 4:
×
517
            return "Need authentication";
×
518
         case 5:
×
519
            return "Need authorization";
×
520
         default:
521
             return $icmp_code;
×
522
      }
523
   }
524
  else
525
     return $icmp_code;
×
526
}
527

528
function PrintPayloadChar( $char, $output_type )
529
{
530
   if ( $char >= 32 && $char <= 127 )
×
531
   {
532
      if ( $output_type == 2 )
×
533
         return chr($char);
×
534
      else
535
         return htmlspecialchars(chr($char));
×
536
   }
537
   else
538
      return '.';
×
539
}
540

541
function PrintBase64PacketPayload ( $encoded_payload, $output_type )
542
{
543
     /* strip out the <CR> at the end of each block */
544
     $encoded_payload = str_replace("\n", "", $encoded_payload);
×
545

546
     $payload = base64_decode($encoded_payload);
×
547
     $len = strlen($payload);
×
548
     $s = " "._LENGTH." = ".strlen($payload)."\n";
×
549

550
     for ($i = 0; $i < strlen($payload); $i++ )
×
551
     {
552
          if ( $i % 16 == 0 )
×
553
          {
554
             /* dump the ASCII characters */
555
             if ( $i != 0 )
×
556
             {
557
                $s = $s.'  ';
×
558
                for ($j = $i-16; $j < $i; $j++ )
×
559
                   $s = $s.PrintPayloadChar(ord($payload[$j]), $output_type);
×
560
             }
561
             $s = $s.sprintf("\n%03x : ", $i);
×
562
          }
563

564
          $s = $s.sprintf("%s ", bin2hex($payload[$i]) );
×
565
     }
566

567
     /* print the remained of any ASCII chars */
568
     if ( ($i % 16) != 0 )
×
569
     {
570
        for ( $j = 0; $j < 16 - ($i % 16); $j++)
×
571
            $s = $s.'   ';
×
572

573
        $s = $s.'  ';
×
574
        
575
        for ( $j = $len - ($i % 16); $j < $len; $j++ )
×
576
           $s = $s.PrintPayloadChar(ord($payload[$j]), $output_type);
×
577
     } else {
578
        $s = $s.'  ';
×
579
        for ( $j = $len - 16; $j < $len && $j > 0; $j++ )
×
580
           $s = $s.PrintPayloadChar(ord($payload[$j]), $output_type);
×
581
     }
582

583
     return $s;
×
584
}
585

586
function PrintAsciiPacketPayload ( $encoded_payload, $output_type )
587
{
588
   return wordwrap($encoded_payload, 70);
×
589
}
590

591
function PrintHexPacketPayload ( $encoded_payload, $output_type )
592
{
593
     /* strip out the <CR> at the end of each block */
594
     $encoded_payload = str_replace("\n", "", $encoded_payload);
×
595
     $payload = $encoded_payload;
×
596

597
     $len = strlen($payload);
×
598
     $s = " "._LENGTH." = ".(strlen($payload)/2)."\n";
×
599

600
     for ($i = 0; $i < strlen($payload); $i += 2 )
×
601
     {
602
          if ( $i % 32 == 0 )
×
603
          {
604
             /* dump the ASCII characters */
605
             if ( $i != 0 )
×
606
             {
607
                $s = $s.'  ';
×
608
                for ($j = $i-32; $j < $i; $j+=2 )
×
609
                {
610
                    $t = hexdec($payload[$j].$payload[$j+1]);
×
611
                    $s = $s.PrintPayloadChar($t, $output_type);
×
612
                }
613
             }
614
             $s = $s.sprintf("\n%03x : ", $i/2);
×
615
          }
616
          $s = $s.sprintf("%s%s ", $payload[$i], $payload[$i+1] );
×
617
     }
618

619
     /* space through to align end of hex dump */
620
     if ( $i % 32 )
×
621
        for ( $j = 0; $j < 32 - ($i % 32); $j+=2)
×
622
           $s = $s.'   ';
×
623

624
     $s = $s.'  ';
×
625

626
     /* print the ASCII decode */
627
     if ( $i % 32 )
×
628
        $start = $len - ($i % 32);
×
629
     else
630
        $start = $len - 32;
×
631

632
     for ( $j = $start; $j < $i; $j+=2 )
×
633
     {
634
        $t = hexdec($payload[$j].$payload[$j+1]);
×
635
        $s = $s.PrintPayloadChar($t, $output_type);
×
636
     } 
637

638
     return $s;
×
639
}
640

641
// ************************************************************************************
642
function PrintCleanHexPacketPayload( $encoded_payload, $output_type )
643
{
644
     $len = strlen($encoded_payload);
×
645
     $s = '';
×
646
     $count = 0;
×
647
     for ($i = 0; $i < $len; $i += 2 )
×
648
     {
649
         /* dump the ASCII characters */
650
         $t = hexdec($encoded_payload[$i].$encoded_payload[$i+1]);
×
651
         $s_tmp = PrintCleanPayloadChar($t, $output_type);
×
652

653
         /* Join together several sequential non-ASCII characters displaying their count
654
          * in one line. It makes easyer to look through payload in plain display mode.
655
          * If current character is '<br>' and this is not last character of payload
656
          * increment counter, else output non-ASCII count and flush counter.
657
          */
658
         if ( ($s_tmp == '<br>') && !($i+2 == $len) ) {
×
659
             $count++;
×
660
         } else {
661
             if ($count > 1)
×
662
                 $s .= '<DIV class="nonascii">['. $count .' non-ASCII characters]</DIV>';
×
663
             elseif ($count == 1)
×
664
                 $s .= '<br>';
×
665
             $s .= $s_tmp;
×
666
             $count = 0;
×
667
         }
668
     }
669
     return $s;
×
670
}
671

672
function PrintCleanPayloadChar( $char, $output_type )
673
{
674
   if ( $char >= 32 && $char <= 127 )
×
675
   {
676
      if ( $output_type == 2 )
×
677
         return chr($char);
×
678
      else
679
         return htmlspecialchars(chr($char));
×
680
   }
681
   else
682
      return '<br>';
×
683
}
684

685
// ************************************************************************************
686

687
function PrintPacketPayload($data, $encode_type, $output_type)
688
{
689
     if ( $output_type == 1 )
×
690
        printf("\n<PRE>\n");
×
691

692
     /* print the packet based on encoding type */;
693
     if ( $encode_type == "1" )
×
694
         $payload = PrintBase64PacketPayload($data, $output_type);
×
695
     else if ($encode_type == "0" )
×
696
     {
697
                if ( GetAsciiClean() ){ // Print clean ascii display
×
698
                        $payload = PrintCleanHexPacketPayload($data, $output_type);
×
699
                }else{
700
                        $payload = PrintHexPacketPayload($data, $output_type);
×
701
                }
702
     }
703
     else if ($encode_type == "2" )
×
704
         $payload = PrintAsciiPacketPayload($data, $output_type); 
×
705
   
706
     if ( $output_type == 1 )
×
707
        echo "$payload\n</PRE>\n";
×
708
     
709
     return $payload;
×
710
}
711

712
function GetQueryResultID($submit, &$seq, &$sid, &$cid){
713
        // Extract the sid and cid from the $submit variable of the form
714
        // #XX-(XX-XX)
715
        //  |   |  |
716
        //  |   |  |--- cid
717
        //  |   |------ sid
718
        //  |---------- sequence number of DB lookup
719

720
        if (preg_match('/#[0-9]+-\([0-9]+-[0-9]+\)$/', $submit)){
44✔
721
                $submit = strstr($submit, '#');
22✔
722
                $find = array('#','(',')');
22✔
723
                $submit = str_replace($find, '', $submit);
22✔
724
                // Since the submit variable is not cleaned do so here:
725
                $tmp = CleanVariable(explode("-", $submit), VAR_DIGIT);
22✔
726
                $seq = intval($tmp[0]);
22✔
727
                $sid = intval($tmp[1]);
22✔
728
                $cid = intval($tmp[2]);
22✔
729
                return true;
22✔
730
        }else{
731
                return false;
22✔
732
        }
733
}
734

735
function ExportPacket($sid, $cid, $db)
736
{
737
  GLOBAL $action, $action_arg;
738

739
  /* Event */
740
  $sql2 = "SELECT signature, timestamp FROM acid_event WHERE sid='".$sid."' AND cid='".$cid."'";
×
741
  $result2 = $db->baseExecute($sql2);
×
742
  $myrow2 = $result2->baseFetchRow();
×
743

744
  $s = "------------------------------------------------------------------------------\n";
×
745
  $s = $s."#($sid - $cid) [$myrow2[1]] ".BuildSigByID($myrow2[0], $db, 2)."\r\n";
×
746

747
  $sql4 = "SELECT hostname, interface, filter FROM sensor  WHERE sid='".$sid."'";
×
748
  $result4 = $db->baseExecute($sql4);
×
749
  $myrow4 = $result4->baseFetchRow();
×
750

751
  $result4->baseFreeRows();
×
752
  $result2->baseFreeRows();
×
753

754
  /* IP */
755
  $sql2 = "SELECT ip_src, ip_dst, ".
756
          "ip_ver, ip_hlen, ip_tos, ip_len, ip_id, ip_flags, ip_off, ip_ttl, ip_csum, ip_proto". 
757
          " FROM iphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
758

759
  $result2 = $db->baseExecute($sql2);
×
760
  $myrow2 = $result2->baseFetchRow();
×
761
  $layer4_proto = $myrow2[11];
×
762

763
  if ( $myrow2[0] != "" )
×
764
  {
765
    $sql3 = "SELECT * FROM opt  WHERE sid='".$sid."' AND cid='".$cid."' AND opt_proto='0'";
×
766
    $result3 = $db->baseExecute($sql3);
×
767
    $num_opt = $result3->baseRecordCount();
×
768

769
    $s = $s."IPv$myrow2[2]: ".
×
770
          baseLong2IP($myrow2[0])." -> ".
×
771
          baseLong2IP($myrow2[1])."\n".
×
772
          "      hlen=$myrow2[3] TOS=$myrow2[4] dlen=$myrow2[5] ID=$myrow2[6]".
×
773
          " flags=$myrow2[7] offset=$myrow2[8] TTL=$myrow2[9] chksum=$myrow2[10]\n";
×
774

775
    if ( $num_opt > 0 )
×
776
    {
777
      $s = $s."    Options\n";
×
778
      for ( $i = 0; $i < $num_opt; $i++)
×
779
      {
780
         $myrow3 = $result3->baseFetchRow();
×
781
         $s = $s."      #".($i+1)." - ".IPOption2str($myrow3[4])." len=$myrow3[5]";
×
782
         if ( $myrow3[5] != 0 )
×
783
            $s = $s." data=$myrow3[6]";
×
784
         $s = $s."\n";  
×
785
       }
786
    }
787
                       
788
    $result3->baseFreeRows();
×
789
  }
790
  $result2->baseFreeRows();
×
791

792
  /* TCP */
793
  if ( $layer4_proto == "6" )  
×
794
  {
795
     $sql2 = "SELECT tcp_sport, tcp_dport, tcp_seq, tcp_ack, tcp_off, tcp_res, tcp_flags, tcp_win, ".
796
             "       tcp_csum, tcp_urp FROM tcphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
797
     $result2 = $db->baseExecute($sql2);
×
798
     $myrow2 = $result2->baseFetchRow();
×
799

800
     $sql3 = "SELECT * FROM opt  WHERE sid='".$sid."' AND cid='".$cid."' AND opt_proto='6'";
×
801
     $result3 = $db->baseExecute($sql3);
×
802
     $num_opt = $result3->baseRecordCount();
×
803

804
     $s = $s."TCP:  port=$myrow2[0] -> dport: $myrow2[1]  flags=";
×
805

806
      if ( ($myrow2[6] & 128) != 0 )  $s = $s.'2';  else $s = $s.'*';
×
807
      if ( ($myrow2[6] & 64 ) != 0 )  $s = $s.'1';  else $s = $s.'*';
×
808
      if ( ($myrow2[6] & 32) != 0  )  $s = $s.'U';  else $s = $s.'*';
×
809
      if ( ($myrow2[6] & 16 ) != 0 )  $s = $s.'A';  else $s = $s.'*';
×
810
      if ( ($myrow2[6] & 8) != 0   )  $s = $s.'P';  else $s = $s.'*';
×
811
      if ( ($myrow2[6] & 4 ) != 0  )  $s = $s.'R';  else $s = $s.'*';
×
812
      if ( ($myrow2[6] & 2 ) != 0  )  $s = $s.'S';  else $s = $s.'*';
×
813
      if ( ($myrow2[6] & 1 ) != 0  )  $s = $s.'F';  else $s = $s.'*';
×
814

815
      $s = $s." seq=$myrow2[2]\n".
×
816
              "      ack=$myrow2[3] off=$myrow2[4] res=$myrow2[5] win=$myrow2[7] urp=$myrow2[9] ".
×
817
              "chksum=$myrow2[8]\n";
×
818

819
      if ( $num_opt != 0)
×
820
      {
821
         $s = $s."      Options:\n";
×
822
         for ( $i = 0; $i < $num_opt; $i++)
×
823
         {
824
             $myrow3 = $result3->baseFetchRow();
×
825
             $s = $s."       #".($i+1)." - ".TCPOption2str($myrow3[4])." len=$myrow3[5]";
×
826
             if ( $myrow3[5] != 0 )
×
827
                $s = $s." data=".$myrow3[6];
×
828
            $s = $s."\n";           
×
829
         }
830
      }
831

832
      $result2->baseFreeRows();
×
833
      $result3->baseFreeRows();
×
834
  }
835

836
  /* UDP */
837
  if ( $layer4_proto == "17" )
×
838
  {
839

840
     $sql2 = "SELECT * FROM udphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
×
841
     $result2 = $db->baseExecute($sql2);
×
842
     $myrow2 = $result2->baseFetchRow();
×
843

844
     $s = $s."UDP:  port=$myrow2[2] -> dport: $myrow2[3] len=$myrow2[4]\n";
×
845

846
     $result2->baseFreeRows();
×
847
  }
848

849
  /* ICMP */
850
  if ( $layer4_proto == "1" )
×
851
  {
852
     $sql2 = "SELECT icmp_type, icmp_code, icmp_csum, icmp_id, icmp_seq FROM icmphdr ".
853
             "WHERE sid='".$sid."' AND cid='".$cid."'";
854
     $result2 = $db->baseExecute($sql2);
×
855
     $myrow2 = $result2->baseFetchRow();
×
856

857
     $s = $s."ICMP: type=".ICMPType2str($myrow2[0])." code=".ICMPCode2str($myrow2[0],$myrow2[1])."\n".
×
858
             "      checksum=$myrow2[2] id=$myrow2[3] seq=$myrow2[4]\n";
×
859

860
     $result2->baseFreeRows();
×
861
  }
862

863
  /* Print the Payload */
864
  $sql2 = "SELECT data_payload FROM data WHERE sid='".$sid."' AND cid='".$cid."'";
×
865
  $result2 = $db->baseExecute($sql2);
×
866

867
  /* get encoding information and detail_level on the payload */
868
  $sql3 = 'SELECT encoding, detail FROM sensor WHERE sid='.$sid;
×
869
  $result3 = $db->baseExecute($sql3);
×
870
  $myrow3 = $result3->baseFetchRow();  
×
871
  
872
  $s = $s."Payload: ";
×
873

874
  $myrow2 = $result2->baseFetchRow();
×
875
  if ( $myrow2 )
876
  {
877
     /* print the packet based on encoding type */
878
     $s = $s.PrintPacketPayload($myrow2[0], $myrow3[0], 2)."\n";
×
879

880
     $result3->baseFreeRows();     
×
881
  }
882
  else
883
  {
884
     /* Don't have payload so lets print out why by checking the detail level */
885

886
     /* if have fast detail level */
887
     if ( $myrow3[1] == "0" )
×
888
        $s = $s."Fast logging used so payload was discarded\n";
×
889
     else
890
        $s = $s."none\n";
×
891
  }
892

893
  $result2->baseFreeRows();
×
894
 
895
  return $s; 
×
896
}
897

898
function ExportPacket_summary($sid, $cid, $db, $export_type = 0)
899
{
900
  GLOBAL $action, $action_arg;
901

902
  /* Event */
903
  $sql2 = "SELECT signature, timestamp FROM acid_event WHERE sid='".$sid."' AND cid='".$cid."'";
×
904
  $result2 = $db->baseExecute($sql2);
×
905
  $myrow2 = $result2->baseFetchRow();
×
906

907
  $alert_timestamp = $myrow2[1];
×
908
  $alert_sig = BuildSigByID($myrow2[0], $db, 2);
×
909

910
  $result2->baseFreeRows();
×
911

912
  /* IP */
913
  $src_ip = $dst_ip = $src_port = $dst_port = "";
×
914
  $sql2 = "SELECT ip_src, ip_dst, ip_proto". 
915
          " FROM iphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
916

917
  $result2 = $db->baseExecute($sql2);
×
918
  $myrow2 = $result2->baseFetchRow();
×
919

920
  $layer4_proto = "";
×
921
  if ( $myrow2[0] != "" )
×
922
  {
923
     $src_ip = baseLong2IP($myrow2[0]);
×
924
     $dst_ip = baseLong2IP($myrow2[1]);
×
925
     $layer4_proto = $myrow2[2];
×
926
  }
927
  $result2->baseFreeRows();
×
928

929
  /* TCP */
930
  if ( $layer4_proto == "6" )  
×
931
  {
932
     $sql2 = "SELECT tcp_sport, tcp_dport FROM tcphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
×
933
     $result2 = $db->baseExecute($sql2);
×
934
     $myrow2 = $result2->baseFetchRow();
×
935

936
     if ( $export_type == 0 )
×
937
     {
938
        $src_port = ":".$myrow2[0]." -> ";
×
939
        $dst_port = ":".$myrow2[1];
×
940
     }  
941
     else
942
     {
943
        $src_port = $myrow2[0];
×
944
        $dst_port = $myrow2[1];
×
945
     }   
946

947
     $result2->baseFreeRows();
×
948
  }
949

950
  /* UDP */
951
  if ( $layer4_proto == "17" )
×
952
  {
953

954
     $sql2 = "SELECT * FROM udphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
×
955
     $result2 = $db->baseExecute($sql2);
×
956
     $myrow2 = $result2->baseFetchRow();
×
957

958
     if ( $export_type == 0 )
×
959
     {
960
       $src_port = ":".$myrow2[2]." -> ";
×
961
       $dst_port = ":".$myrow2[3];
×
962
     }
963
     else
964
     {
965
       $src_port = $myrow2[2];
×
966
       $dst_port = $myrow2[3];
×
967
     }
968

969
     $result2->baseFreeRows();
×
970
  }
971

972
  /* ICMP */
973
  if ( $layer4_proto == "1" )
×
974
  {
975
     if ( $export_type == 0 )
×
976
       $src_ip = $src_ip." -> ";
×
977
     $src_port = $dst_port = "";
×
978
  }
979
  
980
 /* Portscan Traffic */
981
   if ( $layer4_proto == "255" )
×
982
   {
983
      if ( $export_type == 0 )
×
984
         $src_ip = $src_ip." -> ";
×
985
   }
986

987
  if ( $export_type == 0 )
×
988
  {
989
    $s = sprintf("#%d-%d| [%s] %s%s%s%s %s\r\n",
×
990
                 $sid, $cid, $alert_timestamp, 
991
                 $src_ip, $src_port, $dst_ip, $dst_port,
992
                 $alert_sig); 
993
  }
994
  else /* CSV format */
995
  {
996
    $s = sprintf("\"%d\", \"%d\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"\r\n",
×
997
                 $sid, $cid, $alert_timestamp,
998
                 $src_ip, $src_port, $dst_ip, $dst_port,
999
                 $alert_sig);
1000
  }
1001

1002
  return $s; 
×
1003
}
1004

1005
function base_header($url){
1006
        if (!headers_sent()) {
×
1007
                header($url);
×
1008
                exit;
×
1009
        }
1010
}
1011

1012
function base_microtime()
1013
{
1014
  list($usec, $sec) = explode(" ", microtime());
×
1015
  return ((float)$usec + (float)$sec);
×
1016
}
1017

1018
// Returns true if color is valid html color code.
1019
function HtmlColor ( $color ){
1020
        $color = strtolower($color);
264✔
1021
        $wsc = array(
48✔
1022
                'black', 'silver', 'gray', 'white', 'maroon', 'red', 'pruple',
192✔
1023
                'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal',
96✔
1024
                'aqua'
1025
        );
96✔
1026
        $Ret = false;
264✔
1027
        if (
1028
                in_array($color, $wsc) // Web Safe Color.
264✔
1029
                || preg_match("/^#?[0-9A-F]{6}$/i", $color) // Hex RGB Color Code.
240✔
1030
        ){
96✔
1031
                $Ret = true;
176✔
1032
        }
64✔
1033
        return ($Ret);
264✔
1034
}
1035

1036
function Percent ( $Value = 1, $Count = 1 ){
1037
        if ( $Value > $Count ){
110✔
1038
                $Count = $Value;
22✔
1039
        }
8✔
1040
        if ( $Count <= 0 ){
110✔
1041
                $Count = 1;
22✔
1042
        }
8✔
1043
        if ( $Value <= 0 ){ // Set %
110✔
1044
                $Ret = 0;
44✔
1045
        }else{
16✔
1046
                $Ret = round($Value/$Count*100);
66✔
1047
        }
1048
        return ($Ret);
110✔
1049
}
1050

1051
// Returns true if var is a string containing data.
1052
function LoadedString ( $var ){
1053
        $Ret = false;
1,230✔
1054
        if ( is_string($var) && !empty($var)){
1,230✔
1055
                $Ret = true;
1,076✔
1056
        }
362✔
1057
        return $Ret;
1,230✔
1058
}
1059

1060
// Returns true if file passes include safety checks.
1061
// Also includes the file.
1062
function base_include ( $file='' ){
1063
        GLOBAL $BASE_path, $debug_mode;
176✔
1064
        $Ret = false;
242✔
1065
        $EMsg = '';
242✔
1066
        $tfile = "$BASE_path/custom/" . $file;
242✔
1067
        $ReqRE = preg_quote("$BASE_path/custom/",'/');
242✔
1068
        $ReqRE .= ".*\.htm(l)?";
242✔
1069
        if ( preg_match("/^" . $ReqRE ."$/i", $tfile) ){
242✔
1070
                // File must be in specific location with specific extension.
1071
                $Loc = realpath($tfile); // Final file must
176✔
1072
                if ( $Loc != false // exist and resolve to an absolute path.
112✔
1073
                        && fileowner($Loc) != false // not be owned by UID 0 (root).
176✔
1074
                        && ChkAccess($Loc) == 1 // be a real file & be readable.
176✔
1075
                ){
64✔
1076
                        if ( preg_match("/^" . $ReqRE ."$/i", $Loc) ){
110✔
1077
                                // be in specific location with specific extension.
1078
                                $Ret = true;
88✔
1079
                                $EMsg = 'OK';
88✔
1080
                                include_once($Loc);
88✔
1081
                        }else{
32✔
1082
                                $EMsg = 'Loc';
22✔
1083
                                $tfile .= " -> $Loc";
78✔
1084
                        }
1085
                }else{
40✔
1086
                        $EMsg = 'Access';
136✔
1087
                }
1088
        }else{
64✔
1089
                $EMsg = 'File';
66✔
1090
        }
1091
        if ( $debug_mode > 0 ){
242✔
1092
                print "Test: $file\n";
242✔
1093
                print "$EMsg: $tfile\n";
242✔
1094
        }
88✔
1095
        return $Ret;
242✔
1096
}
1097

1098
// Returns true if asciiclean is set.
1099
// HTTP GET params take precedence over cookie values.
1100
function GetAsciiClean(){
1101
        $Ret = false;
132✔
1102
        if ( isset($_GET['asciiclean']) ){ // Check HTTP GET param.
132✔
1103
                $Ret = ChkGet('asciiclean', 1);
66✔
1104
        }else{ // No GET, check for cookie.
24✔
1105
                $Ret = ChkCookie('asciiclean', 'clean');
66✔
1106
        }
1107
        return $Ret;
132✔
1108
}
1109

1110
// Returns 1 if file or directory passes access checks.
1111
// Returns < 1 error code otherwise.
1112
function ChkAccess( $path, $type='f' ){
1113
        $Ret = 0; // Path Error
830✔
1114
        if ( LoadedString($path) ){
830✔
1115
                $type = strtolower($type);
830✔
1116
                $rcf = 0;
830✔
1117
                $Ret = -1; // Type Error
830✔
1118
                if ( $type == 'f' ){
830✔
1119
                        if ( is_file($path) ){
808✔
1120
                                $rcf = 1;
768✔
1121
                        }
222✔
1122
                }elseif ( $type == 'd' ){
284✔
1123
                        if ( is_dir($path) ){
22✔
1124
                                $rcf = 1;
22✔
1125
                        }
8✔
1126
                }
8✔
1127
                if ( $rcf == 1 ){
830✔
1128
                        $Ret = -2; // Readable Error
720✔
1129
                        $version = explode('.', phpversion());
720✔
1130
                        // PHP Safe Mode cutout.
1131
                        //    Added: 2005-03-25 for compatabibility with PHP 4x & 5.0x
1132
                        //      See: https://sourceforge.net/p/secureideas/bugs/47
1133
                        // PHP Safe Mode w/o cutout successful.
1134
                        // Verified: 2019-05-31 PHP 5.3.29 via CI & Unit Tests.
1135
                        //      See: https://github.com/NathanGibbs3/BASE/issues/34
1136
                        // May work: PHP > 5.1.4.
1137
                        //      See: https://www.php.net/manual/en/function.is-readable.php
1138
                        if (
1139
                                $version[0] > 5
720✔
1140
                                || ($version[0] == 5 && $version[1] > 1)
230✔
1141
                                || ($version[0] == 5 && $version[1] == 1 && $version[2] > 4 )
230✔
1142
                                || ini_get("safe_mode") != true
490✔
1143
                        ){
230✔
1144
                                if ( is_readable($path) ){
720✔
1145
                                        $Ret = 1;
708✔
1146
                                }
218✔
1147
                        }else{
230✔
1148
                                // @codeCoverageIgnoreStart
1149
                                // PHPUnit test only covers this code path on PHP < 5.1.5
1150
                                // Unable to validate in CI.
1151
                                $Ret = 1;
1152
                                // @codeCoverageIgnoreEnd
1153
                        }
1154
                }
230✔
1155
        }
270✔
1156
        return $Ret;
830✔
1157
}
1158

1159
// Returns Library if found & file passes access checks.
1160
// Returns empty string otherwise.
1161
function ChkLib ( $path='', $LibLoc='', $LibFile='' ){
1162
        GLOBAL $debug_mode;
432✔
1163
        $EMPfx = __FUNCTION__ . ': ';
612✔
1164
        $Ret = '';
612✔
1165
        if ( LoadedString($LibFile) ){
612✔
1166
                $sc = DIRECTORY_SEPARATOR;
590✔
1167
                $tmp = $LibFile;
590✔
1168
                // Strip leading or trailing seperators from Lib file.
1169
                $ReqRE = "(^\\$sc|\\$sc\$)";
590✔
1170
                $LibFile = preg_replace("/".$ReqRE."/", '', $LibFile);
590✔
1171
                if ( $debug_mode > 1 && $tmp != $LibFile ){
590✔
1172
                        ErrorMessage('Req Lib: ' . XSSPrintSafe($tmp), 0, 1);
22✔
1173
                        ErrorMessage('Mod Lib: ' . XSSPrintSafe($LibFile), 0, 1);
22✔
1174
                }
8✔
1175
                if ( LoadedString($path) ){ // Path to Lib
590✔
1176
                        $tmp = $path; // Strip trailing seperator from path.
590✔
1177
                        $ReqRE = "\\$sc\$";
590✔
1178
                        $path = preg_replace("/".$ReqRE."/", '', $path);
590✔
1179
                        if ( $debug_mode > 1 && $tmp != $path ){
590✔
1180
                                ErrorMessage('Req Loc: ' . XSSPrintSafe($tmp), 0, 1);
44✔
1181
                                ErrorMessage('Mod Loc: ' . XSSPrintSafe($path), 0, 1);
44✔
1182
                        }
16✔
1183
                        $LibFile .= '.php';
590✔
1184
                        $FinalLib = implode( $sc, array($path, $LibFile) );
590✔
1185
                        if ( $debug_mode > 1 ){
590✔
1186
                                ErrorMessage(
130✔
1187
                                        XSSPrintSafe($EMPfx . "Chk: $FinalLib"),'black',1
130✔
1188
                                );
46✔
1189
                        }
46✔
1190
                        $tmp = ChkAccess($FinalLib);
590✔
1191
                        $Msg = $EMPfx . "Lib: $FinalLib ";
590✔
1192
                        $clr = 'red';
590✔
1193
                        if ( $tmp == 1 ){
590✔
1194
                                $Msg .= 'found';
526✔
1195
                                $clr = 'black';
526✔
1196
                                $Ret = $FinalLib;
526✔
1197
                        }else{
162✔
1198
                                $Msg .= 'not ';
86✔
1199
                        }
1200
                        if ( $tmp == -1 ){
590✔
1201
                                $Msg .= 'found';
66✔
1202
                        }elseif ( $tmp == -2 ){
562✔
1203
                                $Msg .= 'readable';
20✔
1204
                        }
6✔
1205
                        $Msg .= '.';
590✔
1206
                        if ( $debug_mode > 1 ){
590✔
1207
                                ErrorMessage($Msg, $clr, 1);
452✔
1208
                        }
46✔
1209
                }else{ // Relative path to Lib.
184✔
1210
                        if ( LoadedString($LibLoc) ){
44✔
1211
                                $tmp = $LibLoc; // Strip leading seperators from Loc.
22✔
1212
                                $ReqRE = "^\\$sc";
22✔
1213
                                $LibLoc = preg_replace("/".$ReqRE."/", '', $LibLoc);
22✔
1214
                                if ( $debug_mode > 1 && $tmp != $LibLoc ){
22✔
1215
                                        ErrorMessage('Req Loc: ' . XSSPrintSafe($tmp), 0, 1);
22✔
1216
                                        ErrorMessage('Mod Loc: ' . XSSPrintSafe($LibLoc), 0, 1);
22✔
1217
                                }
8✔
1218
                        }
8✔
1219
                        $PSPath = explode(PATH_SEPARATOR, ini_get('include_path'));
44✔
1220
                        foreach( $PSPath as $single_path ){
314✔
1221
                                if ( LoadedString($LibLoc) ){
44✔
1222
                                        $FinalLoc = implode( $sc, array($single_path, $LibLoc) );
22✔
1223
                                }else{
8✔
1224
                                        $FinalLoc = $single_path;
22✔
1225
                                }
1226
                                $tmp = ChkLib( $FinalLoc, '', $LibFile);
44✔
1227
                                if ( LoadedString($tmp) ){
44✔
1228
                                        $Ret = $tmp;
22✔
1229
                                        break;
134✔
1230
                                }
1231
                        }
16✔
1232
                }
1233
        }else{
184✔
1234
                if ( $debug_mode > 0 ){
22✔
1235
                        ErrorMessage($EMPfx . 'No Lib specified.', 0, 1);
22✔
1236
                }
8✔
1237
        }
1238
        return $Ret;
612✔
1239
}
1240

1241
// Returns true if cookie is set & contains value.
1242
function ChkCookie($var,$val){
1243
        $Ret = false;
614✔
1244
        if ( LoadedString($var) ){
614✔
1245
                if ( isset($_COOKIE[$var]) && $_COOKIE[$var] == $val ){
592✔
1246
                        $Ret = true;
64✔
1247
                }
22✔
1248
        }
186✔
1249
        return $Ret;
614✔
1250
}
1251

1252
// Returns true if HTTP GET param is set & contains value.
1253
function ChkGET($var,$val){
1254
        $Ret = false;
154✔
1255
        if ( LoadedString($var) ){
154✔
1256
                if ( isset($_GET[$var]) && $_GET[$var] == $val ){
132✔
1257
                        $Ret = true;
44✔
1258
                }
16✔
1259
        }
48✔
1260
        return $Ret;
154✔
1261
}
1262

1263
// Returns true when key is in array, false otherwise.
1264
function base_array_key_exists( $SKey, $SArray ){ // PHP Version Agnostic.
1265
        $Ret = false;
154✔
1266
        if ( is_array($SArray) && count($SArray) > 0 ){
154✔
1267
                $version = explode('.', phpversion());
132✔
1268
                // Use built in functions when we can.
1269
                if ( $version[0] > 4 || ($version[0] == 4 && $version[1] > 1) ){
132✔
1270
                        // PHP > 4.1
1271
                        $Ret = array_key_exists( $SKey, $SArray );
132✔
1272
                // @codeCoverageIgnoreStart
1273
                // PHPUnit test only covers this code path on PHP < 4.2.0
1274
                // Unable to validate in CI.
1275
                }elseif (
1276
                        ($version[0] == 4 && $version[1] > 0 )
1277
                        || ($version[0] == 4 && $version[1] == 0 && $version[2] > 5)
1278
                ){ // PHP > 4.0.5
1279
                        $Ret = key_exists($SKey, $SArray);
1280
                }else{ // No built in functions, PHP Version agnostic.
1281
                        $Ret = in_array($SKey, array_keys($SArray) );
1282
                }
1283
                // @codeCoverageIgnoreEnd
1284
        }
48✔
1285
        return $Ret;
154✔
1286
}
1287
?>
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc