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

NathanGibbs3 / BASE / 590

pending completion
590

push

travis-ci-com

NathanGibbs3
20230420 Fix CI build breakage. 2

2755 of 16977 relevant lines covered (16.23%)

21.61 hits per line

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

27.61
/base_common.php
1
<?php
2
// Basic Analysis and Security Engine (BASE)
3
// Copyright (C) 2019-2023 Nathan Gibbs
4
// Copyright (C) 2004 BASE Project Team
5
// Copyright (C) 2000 Carnegie Mellon University
6
//
7
//   For license info: See the file 'base_main.php'
8
//
9
//       Project Lead: Nathan Gibbs
10
// Built upon work by: Kevin Johnson & the BASE Project Team
11
//                     Roman Danyliw <rdd@cert.org>, <roman@danyliw.com>
12
//
13
//            Purpose: Common Functions
14
//
15
//          Author(s): Nathan Gibbs
16
//                     Kevin Johnson
17

18
function GetSensorIDs( $db ){
19
        $result = $db->baseExecute("SELECT sid FROM sensor;");
×
20
        while( $myrow = $result->baseFetchRow() ){
×
21
                $sensor_ids[] = $myrow[0];
×
22
        }
23
        $result->baseFreeRows();
×
24
        return $sensor_ids;
×
25
}
26

27
function GetSensorName( $sid, $db ){
28
        $name = '';
×
29
    $temp_sql = "SELECT sid, hostname, interface, filter FROM sensor WHERE sid='".$sid."'";
×
30
    $tmp_result = $db->baseExecute($temp_sql);
×
31
    if ( $tmp_result )
32
    {
33
       $myrow = $tmp_result->baseFetchRow();
×
34
       $name = $myrow[1].':'.$myrow[2];
×
35
       if ( $myrow[3] != "" )
×
36
          $name = $name.':'.$myrow[3];
×
37
    }
38
    $tmp_result->baseFreeRows();
×
39
        return $name;
×
40
}
41

42
function GetVendor( $mac ){
43
        $mac = str_replace(':', '', $mac);
60✔
44
        $mac = substr($mac, 0, 6);
60✔
45
        $vendor = 'unknown';
60✔
46
        $file = 'base_mac_prefixes.map';
60✔
47
        if ( ChkAccess($file) == 1 ){
60✔
48
                $fp = fopen($file, 'r');
40✔
49
                while ( !feof($fp) ){
40✔
50
                        $line = fgets($fp);
40✔
51
                        if ( strcmp($mac, substr($line, 0, 6)) == 0 ){
40✔
52
                                $vendor = substr($line, 8, strlen($line)-9);
20✔
53
                        }
6✔
54
                }
12✔
55
                fclose($fp);
40✔
56
        }else{
12✔
57
                return "Can't open vendor map.";
20✔
58
        }
59
        return $vendor;
40✔
60
}
61

62
function InputSafeSQL( &$SQLstr ){
63
        // Removes the escape sequence of \' => ' which arise when a variable
64
        // containing a '-character is passed through a POST query. This is
65
        // needed since otherwise the MySQL parser complains.
66
        $SQLstr = str_replace("\'", "'", $SQLstr);
×
67
        $SQLstr = str_replace("\\\"", "\"", $SQLstr);
×
68
}
69

70
function PrintProtocolProfileGraphs( $db ){
71
        $tcp_cnt = TCPPktCnt($db);
×
72
        $udp_cnt = UDPPktCnt($db);
×
73
        $icmp_cnt = ICMPPktCnt($db);
×
74
        $portscan_cnt = PortscanPktCnt($db);
×
75
        $layer4_cnt = $tcp_cnt + $udp_cnt + $icmp_cnt + $portscan_cnt;
×
76
        $tcp_percent_show = HtmlPercent($tcp_cnt,$layer4_cnt);
×
77
        $udp_percent_show = HtmlPercent($udp_cnt,$layer4_cnt);
×
78
        $icmp_percent_show = HtmlPercent($icmp_cnt,$layer4_cnt);
×
79
        $portscan_percent_show = HtmlPercent($portscan_cnt,$layer4_cnt);
×
80
   echo '<TABLE WIDTH="100%" BORDER=0>
81
         <TR><TD>TCP<A HREF="base_qry_main.php?new=1'.
82
                           '&amp;layer4=TCP&amp;num_result_rows=-1&amp;sort_order=time_d&amp;submit='._QUERYDBP.'">
83
                           ('.$tcp_percent_show.')</A></TD><TD></TD></TR></TABLE>
84
                  <TABLE class="summarygraph" WIDTH="100%" BORDER=1 CELLSPACING=0 CELLPADDING=0>';
85
        print '<tr>' . HBarGraph($tcp_cnt,$layer4_cnt,'ff0000','cccccc');
×
86
        PrintFramedBoxFooter(0,2);
×
87

88
    echo '<TABLE WIDTH="100%" BORDER=0>
89
          <TR><TD>UDP<A HREF="base_qry_main.php?new=1'.
90
                            '&amp;layer4=UDP&amp;num_result_rows=-1&amp;sort_order=time_d&amp;submit='._QUERYDBP.'">
91
                            ('.$udp_percent_show.')</A></TD><TD></TD></TR></TABLE>
92
                  <TABLE class="summarygraph" WIDTH="100%" BORDER=1 CELLSPACING=0 CELLPADDING=0>';
93
        print '<tr>' . HBarGraph($udp_cnt,$layer4_cnt,'ff0000','cccccc');
×
94
        PrintFramedBoxFooter(0,2);
×
95

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

104
     echo '<CENTER><HR NOSHADE WIDTH="70%"></CENTER>';
×
105

106
     echo '<TABLE WIDTH="100%" BORDER=0>
107
           <TR><TD>'._PORTSCAN.'
108
               <A HREF="base_qry_main.php?new=1'.
109
'&amp;layer4=RawIP&amp;num_result_rows=-1&amp;sort_order=time_d&amp;submit='._QUERYDBP.'">('.$portscan_percent_show.')</A>
110
                    </TD><TD></TD></TR></TABLE>
111
                  <TABLE class="summarygraph" WIDTH="100%" BORDER=1 CELLSPACING=0 CELLPADDING=0>';
112
        print '<tr>' . HBarGraph($portscan_cnt,$layer4_cnt,'ff0000','cccccc');
×
113
        PrintFramedBoxFooter(0,2);
×
114
}
115

116
function BuildIPFormVars( $ipaddr ){
117
        return '' .
118
    '&amp;ip_addr%5B0%5D%5B0%5D=+&amp;ip_addr%5B0%5D%5B1%5D=ip_src&amp;ip_addr%5B0%5D%5B2%5D=%3D'.
119
    '&amp;ip_addr%5B0%5D%5B3%5D='.$ipaddr.
120
    '&amp;ip_addr%5B0%5D%5B8%5D=+&amp;ip_addr%5B0%5D%5B9%5D=OR'.
121
    '&amp;ip_addr%5B1%5D%5B0%5D=+&amp;ip_addr%5B1%5D%5B1%5D=ip_dst&amp;ip_addr%5B1%5D%5B2%5D=%3D'.
122
    '&amp;ip_addr%5B1%5D%5B3%5D='.$ipaddr.
123
    '&amp;ip_addr%5B1%5D%5B8%5D=+&amp;ip_addr%5B1%5D%5B9%5D=+';
124
}
125

126
function BuildSrcIPFormVars( $ipaddr ){
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=+';
131
}
132

133
function BuildDstIPFormVars( $ipaddr ){
134
        return '' .
135
    '&amp;ip_addr%5B0%5D%5B0%5D=+&amp;ip_addr%5B0%5D%5B1%5D=ip_dst&amp;ip_addr%5B0%5D%5B2%5D=%3D'.
136
    '&amp;ip_addr%5B0%5D%5B3%5D='.$ipaddr.
137
    '&amp;ip_addr%5B0%5D%5B8%5D=+&amp;ip_addr%5B0%5D%5B9%5D=+';
138
}
139

140
function BuildUniqueAddressLink( $addr_type, $raw = '' ){
141
        return '<A HREF="base_stat_uaddr.php?addr_type=' . $addr_type . $raw . '">';
×
142
}
143

144
function BuildUniqueAlertLink( $raw ){
145
        return '<A HREF="base_stat_alerts.php' . $raw . '">';
×
146
}
147

148
function BuildAddressLink( $ipaddr, $netmask ){
149
        return '<A HREF="base_stat_ipaddr.php?ip=' . rawurlencode($ipaddr)
×
150
        . '&amp;netmask=' . $netmask . '">';
151
}
152

153
// Add blank row to given criteria element.
154
function AddCriteriaFormRow(
155
        &$submit, $submit_value, &$cnt, &$criteria_array, $max
156
){
157
        $submit = $submit_value;
×
158
        ++$cnt;
×
159
        InitArray($criteria_array[$cnt-1], $max, 0, '');
×
160
}
161

162
function IPProto2str( $ipproto_code ){
163
        switch( $ipproto_code ){
164
      case 0:
×
165
          return "IP";
×
166
      case 1:
×
167
          return "ICMP";
×
168
      case 2:
×
169
          return "IGMP";
×
170
      case 4:
×
171
          return "IPIP tunnels";
×
172
      case 6:
×
173
          return "TCP";
×
174
      case 8:
×
175
          return "EGP";
×
176
      case 12:
×
177
          return "PUP";
×
178
      case  17:
×
179
          return "UDP";
×
180
      case 22:
×
181
          return "XNS UDP";
×
182
      case 29:
×
183
          return "SO TP Class 4";
×
184
      case 41:
×
185
          return "IPv6 header";
×
186
      case 43:
×
187
          return "IPv6 routing header";
×
188
      case 44:
×
189
          return "IPv6 fragmentation header";
×
190
      case 46: 
×
191
          return "RSVP";
×
192
      case 47:
×
193
          return "GRE";
×
194
      case 50: 
×
195
          return "IPSec ESP";
×
196
      case 51: 
×
197
          return "IPSec AH";
×
198
      case 58: 
×
199
          return "ICMPv6";
×
200
      case 59: 
×
201
          return "IPv6 no next header";
×
202
      case 60:
×
203
          return "IPv6 destination options";
×
204
      case 92:
×
205
          return "MTP";
×
206
      case 98:
×
207
          return "Encapsulation header";
×
208
      case 103: 
×
209
          return "PIM";
×
210
      case 108:
×
211
          return "COMP";
×
212
      case 255: 
×
213
          return "Raw IP";
×
214
      default:
215
          return $ipproto_code;
×
216
   }
217
}
218

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

280
function IPOption2str( $ipopt_code ){
281
        switch( $ipopt_code ){
282
      case 7:              /* IPOPT_RR */
×
283
          return "RR";
×
284
      case 0:              /* IPOPT_EOL */
×
285
          return "EOL";
×
286
      case 1:              /* IPOPT_NOP */
×
287
          return "NOP";
×
288
      case 0x44:           /* IPOPT_TS */
×
289
          return "TS";
×
290
      case 0x82:           /* IPOPT_SECURITY */
×
291
          return "SEC";
×
292
      case 0x83:           /* IPOPT_LSRR */
×
293
          return "LSRR";
×
294
      case 0x84:           /* IPOPT_LSRR_E */
×
295
          return "LSRR_E";
×
296
      case 0x88:           /* IPOPT_SATID */
×
297
          return "SID";
×
298
      case 0x89:           /* IPOPT_SSRR */
×
299
          return "SSRR";
×
300
  }
301
}
302

303
function ICMPType2str( $icmp_type ){
304
        switch ( $icmp_type ){
305
      case 0:                             /* ICMP_ECHOREPLY */
×
306
          return "Echo Reply";
×
307
      case 3:                             /* ICMP_DEST_UNREACH */
×
308
          return "Destination Unreachable";
×
309
      case 4:                             /* ICMP_SOURCE_QUENCH */
×
310
          return "Source Quench";
×
311
      case 5:                             /* ICMP_REDIRECT */
×
312
          return "Redirect";
×
313
      case 8:                             /* ICMP_ECHO */
×
314
          return "Echo Request";
×
315
      case 9:
×
316
          return "Router Advertisement";
×
317
      case 10:
×
318
          return "Router Solicitation"; 
×
319
      case 11:                            /* ICMP_TIME_EXCEEDED */
×
320
          return "Time Exceeded";
×
321
      case 12:                            /* ICMP_PARAMETERPROB */
×
322
          return "Parameter Problem";
×
323
      case 13:                            /* ICMP_TIMESTAMP */
×
324
          return "Timestamp Request";
×
325
      case 14:                            /* ICMP_TIMESTAMPREPLY */
×
326
          return "Timestamp Reply";
×
327
      case 15:                            /* ICMP_INFO_REQUEST */
×
328
          return "Information Request";
×
329
      case 16:                            /* ICMP_INFO_REPLY */
×
330
          return "Information Reply";
×
331
      case 17:                            /* ICMP_ADDRESS */
×
332
          return "Address Mask Request";
×
333
      case 18:                            /* ICMP_ADDRESSREPLY */
×
334
          return "Address Mask Reply";
×
335
      case 19:
×
336
          return "Reserved (security)";
×
337
      case 20:
×
338
          return "Reserved (robustness)";
×
339
      case 21:
×
340
          return "Reserved (robustness)";
×
341
      case 22:
×
342
          return "Reserved (robustness)";
×
343
      case 23:
×
344
          return "Reserved (robustness)";
×
345
      case 24:
×
346
          return "Reserved (robustness)";
×
347
      case 25:
×
348
          return "Reserved (robustness)";
×
349
      case 26:
×
350
          return "Reserved (robustness)";
×
351
      case 27:
×
352
          return "Reserved (robustness)";
×
353
      case 28:
×
354
          return "Reserved (robustness)";
×
355
      case 29:
×
356
          return "Reserved (robustness)";
×
357
      case 30:
×
358
          return "Traceroute";
×
359
      case 31:
×
360
          return "Datagram Conversion Error";
×
361
      case 32:
×
362
          return "Mobile Host Redirect";
×
363
      case 33:
×
364
          return "IPv6 Where-Are-You";
×
365
      case 34:
×
366
          return "IPv6 I-Am-Here";
×
367
      case 35:
×
368
          return "Mobile Registration Request";
×
369
      case 36:
×
370
          return "Mobile Registration Reply";
×
371
      case 37:
×
372
          return "Domain Name Request";
×
373
      case 38:
×
374
          return "Domain Name Reply";
×
375
      case 39:
×
376
          return "SKIP";
×
377
      case 40:
×
378
          return "Photuris";
×
379
      default:
380
          return $icmp_type;
×
381
  }
382
}
383

384
function ICMPCode2str( $icmp_type, $icmp_code ){
385
        if ( $icmp_type == 3 ){
×
386
                switch ( $icmp_code ){
387
        case 0:                                    /* ICMP_NET_UNREACH */
×
388
            return "Network Unreachable";
×
389
        case 1:                                    /* ICMP_HOST_UNREACH */
×
390
            return "Host Unreachable";
×
391
        case 2:                                    /* ICMP_PROT_UNREACH */
×
392
            return "Protocol Unreachable";
×
393
        case 3:                                    /* ICMP_PORT_UNREACH */
×
394
            return "Port Unreachable";
×
395
        case 4:                                    /* ICMP_FRAG_NEEDED */
×
396
            return "Fragmentation Needed/DF set";
×
397
        case 5:                                    /* ICMP_SR_FAILED */
×
398
            return "Source Route failed";
×
399
        case 6:                                    /* ICMP_NET_UNKNOWN */
×
400
            return "Network Unknown";
×
401
        case 7:                                    /* ICMP_HOST_UNKNOWN */
×
402
            return "Host Unknown";
×
403
        case 8:                                    /* ICMP_HOST_ISOLATED */
×
404
            return "Host Isolated";
×
405
        case 9:                                    /* ICMP_NET_ANO */
×
406
            return "Network ANO";
×
407
        case 10:                                   /* ICMP_HOST_ANO */
×
408
            return "Host ANO";
×
409
        case 11:                                   /* ICMP_NET_UNR_TOS */
×
410
            return "Network Unreach TOS";
×
411
        case 12:                                   /* ICMP_HOST_UNR_TOS */
×
412
            return "Host Unreach TOS";
×
413
        case 13:                                   /* ICMP_PKT_FILTERED */
×
414
            return "Packet Filtered";
×
415
        case 14:                                   /* ICMP_PREC_VIOLATION */
×
416
            return "Precedence violation";
×
417
        case 15:                                   /* ICMP_PREC_CUTOFF */
×
418
            return "Precedence cut off";
×
419
        default:
420
            return $icmp_code;
×
421
     }
422
        }elseif ( $icmp_type == 5 ){
×
423
                switch ( $icmp_code ){
424
        case 0:
×
425
            return "Redirect datagram for network/subnet";
×
426
        case 1:
×
427
            return "Redirect datagram for host";
×
428
        case 2:
×
429
            return "Redirect datagram for ToS and network";
×
430
        case 3:
×
431
            return "Redirect datagram for Tos and host";
×
432
        default:
433
            return $icmp_code;
×
434
      }
435
        }elseif ( $icmp_type == 9 ){
×
436
                switch ( $icmp_code ){
437
         case 0:
×
438
             return "Normal router advertisement";
×
439
         case 16:
×
440
             return "Does not route common traffic";
×
441
         default:
442
             return $icmp_code;
×
443
      }
444
        }elseif ( $icmp_type == 11 ){
×
445
                switch ( $icmp_code ){
446
         case 0:
×
447
             return "TTL exceeded in transit";
×
448
         case 1:
×
449
             return "Fragment reassembly time exceeded";
×
450
         default:
451
             return $icmp_code;
×
452
      }
453
        }elseif ( $icmp_type == 12 ){
×
454
      switch ($icmp_code)
455
      {
456
         case 0:
×
457
             return "Pointer indicates error";
×
458
         case 1:
×
459
             return "Missing a required option";
×
460
         case 2:
×
461
             return "Bad length";
×
462
         default:
463
             return $icmp_code;
×
464
      }
465
        }elseif ( $icmp_type == 40 ){
×
466
      switch ($icmp_code)
467
      {
468
         case 0:
×
469
            return "Bad SPI";
×
470
         case 1:
×
471
            return "Authentication failed";
×
472
         case 2:
×
473
            return "Decompression failed";
×
474
         case 3:
×
475
            return "Decryption failed";
×
476
         case 4:
×
477
            return "Need authentication";
×
478
         case 5:
×
479
            return "Need authorization";
×
480
         default:
481
             return $icmp_code;
×
482
      }
483
        }else{
484
                return $icmp_code;
×
485
        }
486
}
487

488
function PrintPayloadChar( $char, $output_type ){
489
   if ( $char >= 32 && $char <= 127 )
×
490
   {
491
      if ( $output_type == 2 )
×
492
         return chr($char);
×
493
      else
494
         return htmlspecialchars(chr($char));
×
495
   }
496
   else
497
      return '.';
×
498
}
499

500
function PrintBase64PacketPayload( $encoded_payload, $output_type ){
501
     /* strip out the <CR> at the end of each block */
502
     $encoded_payload = str_replace("\n", "", $encoded_payload);
×
503

504
     $payload = base64_decode($encoded_payload);
×
505
     $len = strlen($payload);
×
506
     $s = " "._LENGTH." = ".strlen($payload)."\n";
×
507

508
     for ($i = 0; $i < strlen($payload); $i++ )
×
509
     {
510
          if ( $i % 16 == 0 )
×
511
          {
512
             /* dump the ASCII characters */
513
             if ( $i != 0 )
×
514
             {
515
                $s = $s.'  ';
×
516
                for ($j = $i-16; $j < $i; $j++ )
×
517
                   $s = $s.PrintPayloadChar(ord($payload[$j]), $output_type);
×
518
             }
519
             $s = $s.sprintf("\n%03x : ", $i);
×
520
          }
521

522
          $s = $s.sprintf("%s ", bin2hex($payload[$i]) );
×
523
     }
524

525
     /* print the remained of any ASCII chars */
526
     if ( ($i % 16) != 0 )
×
527
     {
528
        for ( $j = 0; $j < 16 - ($i % 16); $j++)
×
529
            $s = $s.'   ';
×
530

531
        $s = $s.'  ';
×
532
        
533
        for ( $j = $len - ($i % 16); $j < $len; $j++ )
×
534
           $s = $s.PrintPayloadChar(ord($payload[$j]), $output_type);
×
535
     } else {
536
        $s = $s.'  ';
×
537
        for ( $j = $len - 16; $j < $len && $j > 0; $j++ )
×
538
           $s = $s.PrintPayloadChar(ord($payload[$j]), $output_type);
×
539
     }
540

541
     return $s;
×
542
}
543

544
function PrintAsciiPacketPayload( $encoded_payload, $output_type ){
545
        return wordwrap($encoded_payload, 70);
×
546
}
547

548
function PrintHexPacketPayload( $encoded_payload, $output_type ){
549
     /* strip out the <CR> at the end of each block */
550
     $encoded_payload = str_replace("\n", "", $encoded_payload);
×
551
     $payload = $encoded_payload;
×
552

553
     $len = strlen($payload);
×
554
     $s = " "._LENGTH." = ".(strlen($payload)/2)."\n";
×
555

556
     for ($i = 0; $i < strlen($payload); $i += 2 )
×
557
     {
558
          if ( $i % 32 == 0 )
×
559
          {
560
             /* dump the ASCII characters */
561
             if ( $i != 0 )
×
562
             {
563
                $s = $s.'  ';
×
564
                for ($j = $i-32; $j < $i; $j+=2 )
×
565
                {
566
                    $t = hexdec($payload[$j].$payload[$j+1]);
×
567
                    $s = $s.PrintPayloadChar($t, $output_type);
×
568
                }
569
             }
570
             $s = $s.sprintf("\n%03x : ", $i/2);
×
571
          }
572
          $s = $s.sprintf("%s%s ", $payload[$i], $payload[$i+1] );
×
573
     }
574

575
     /* space through to align end of hex dump */
576
     if ( $i % 32 )
×
577
        for ( $j = 0; $j < 32 - ($i % 32); $j+=2)
×
578
           $s = $s.'   ';
×
579

580
     $s = $s.'  ';
×
581

582
     /* print the ASCII decode */
583
     if ( $i % 32 )
×
584
        $start = $len - ($i % 32);
×
585
     else
586
        $start = $len - 32;
×
587

588
     for ( $j = $start; $j < $i; $j+=2 )
×
589
     {
590
        $t = hexdec($payload[$j].$payload[$j+1]);
×
591
        $s = $s.PrintPayloadChar($t, $output_type);
×
592
     } 
593

594
     return $s;
×
595
}
596

597
function PrintCleanHexPacketPayload( $encoded_payload, $output_type ){
598
     $len = strlen($encoded_payload);
×
599
     $s = '';
×
600
     $count = 0;
×
601
     for ($i = 0; $i < $len; $i += 2 )
×
602
     {
603
         /* dump the ASCII characters */
604
         $t = hexdec($encoded_payload[$i].$encoded_payload[$i+1]);
×
605
         $s_tmp = PrintCleanPayloadChar($t, $output_type);
×
606

607
         /* Join together several sequential non-ASCII characters displaying their count
608
          * in one line. It makes easyer to look through payload in plain display mode.
609
          * If current character is '<br>' and this is not last character of payload
610
          * increment counter, else output non-ASCII count and flush counter.
611
          */
612
         if ( ($s_tmp == '<br>') && !($i+2 == $len) ) {
×
613
             $count++;
×
614
         } else {
615
             if ($count > 1)
×
616
                 $s .= '<DIV class="nonascii">['. $count .' non-ASCII characters]</DIV>';
×
617
             elseif ($count == 1)
×
618
                 $s .= '<br>';
×
619
             $s .= $s_tmp;
×
620
             $count = 0;
×
621
         }
622
     }
623
     return $s;
×
624
}
625

626
function PrintCleanPayloadChar( $char, $output_type ){
627
   if ( $char >= 32 && $char <= 127 )
×
628
   {
629
      if ( $output_type == 2 )
×
630
         return chr($char);
×
631
      else
632
         return htmlspecialchars(chr($char));
×
633
   }
634
   else
635
      return '<br>';
×
636
}
637

638
function PrintPacketPayload( $data, $encode_type, $output_type ){
639
     if ( $output_type == 1 )
×
640
        printf("\n<PRE>\n");
×
641

642
     /* print the packet based on encoding type */;
643
     if ( $encode_type == "1" )
×
644
         $payload = PrintBase64PacketPayload($data, $output_type);
×
645
     else if ($encode_type == "0" )
×
646
     {
647
                if ( GetAsciiClean() ){ // Print clean ascii display
×
648
                        $payload = PrintCleanHexPacketPayload($data, $output_type);
×
649
                }else{
650
                        $payload = PrintHexPacketPayload($data, $output_type);
×
651
                }
652
     }
653
     else if ($encode_type == "2" )
×
654
         $payload = PrintAsciiPacketPayload($data, $output_type); 
×
655
   
656
     if ( $output_type == 1 )
×
657
        echo "$payload\n</PRE>\n";
×
658

659
        return $payload;
×
660
}
661

662
function GetQueryResultID( $submit, &$seq, &$sid, &$cid ){
663
        // Extract the sid and cid from the $submit variable of the form
664
        // #XX-(XX-XX)
665
        //  |   |  |
666
        //  |   |  |--- cid
667
        //  |   |------ sid
668
        //  |---------- sequence number of DB lookup
669

670
        if ( preg_match('/#[0-9]+-\([0-9]+-[0-9]+\)$/', $submit) ){
40✔
671
                $submit = strstr($submit, '#');
20✔
672
                $find = array('#','(',')');
20✔
673
                $submit = str_replace($find, '', $submit);
20✔
674
                // Since the submit variable is not cleaned do so here:
675
                $tmp = CleanVariable(explode("-", $submit), VAR_DIGIT);
20✔
676
                $seq = intval($tmp[0]);
20✔
677
                $sid = intval($tmp[1]);
20✔
678
                $cid = intval($tmp[2]);
20✔
679
                return true;
20✔
680
        }else{
681
                return false;
20✔
682
        }
683
}
684

685
function ExportPacket( $sid, $cid, $db ){
686
        GLOBAL $action, $action_arg;
687
        // Event.
688
  $sql2 = "SELECT signature, timestamp FROM acid_event WHERE sid='".$sid."' AND cid='".$cid."'";
×
689
  $result2 = $db->baseExecute($sql2);
×
690
  $myrow2 = $result2->baseFetchRow();
×
691

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

695
  $sql4 = "SELECT hostname, interface, filter FROM sensor  WHERE sid='".$sid."'";
×
696
  $result4 = $db->baseExecute($sql4);
×
697
  $myrow4 = $result4->baseFetchRow();
×
698

699
  $result4->baseFreeRows();
×
700
  $result2->baseFreeRows();
×
701

702
  /* IP */
703
  $sql2 = "SELECT ip_src, ip_dst, ".
704
          "ip_ver, ip_hlen, ip_tos, ip_len, ip_id, ip_flags, ip_off, ip_ttl, ip_csum, ip_proto". 
705
          " FROM iphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
706

707
  $result2 = $db->baseExecute($sql2);
×
708
  $myrow2 = $result2->baseFetchRow();
×
709
  $layer4_proto = $myrow2[11];
×
710

711
  if ( $myrow2[0] != "" )
×
712
  {
713
    $sql3 = "SELECT * FROM opt  WHERE sid='".$sid."' AND cid='".$cid."' AND opt_proto='0'";
×
714
    $result3 = $db->baseExecute($sql3);
×
715
    $num_opt = $result3->baseRecordCount();
×
716

717
    $s = $s."IPv$myrow2[2]: ".
×
718
          baseLong2IP($myrow2[0])." -> ".
×
719
          baseLong2IP($myrow2[1])."\n".
×
720
          "      hlen=$myrow2[3] TOS=$myrow2[4] dlen=$myrow2[5] ID=$myrow2[6]".
×
721
          " flags=$myrow2[7] offset=$myrow2[8] TTL=$myrow2[9] chksum=$myrow2[10]\n";
×
722

723
    if ( $num_opt > 0 )
×
724
    {
725
      $s = $s."    Options\n";
×
726
      for ( $i = 0; $i < $num_opt; $i++)
×
727
      {
728
         $myrow3 = $result3->baseFetchRow();
×
729
         $s = $s."      #".($i+1)." - ".IPOption2str($myrow3[4])." len=$myrow3[5]";
×
730
         if ( $myrow3[5] != 0 )
×
731
            $s = $s." data=$myrow3[6]";
×
732
         $s = $s."\n";  
×
733
       }
734
    }
735
                       
736
    $result3->baseFreeRows();
×
737
  }
738
  $result2->baseFreeRows();
×
739

740
  /* TCP */
741
  if ( $layer4_proto == "6" )  
×
742
  {
743
     $sql2 = "SELECT tcp_sport, tcp_dport, tcp_seq, tcp_ack, tcp_off, tcp_res, tcp_flags, tcp_win, ".
744
             "       tcp_csum, tcp_urp FROM tcphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
745
     $result2 = $db->baseExecute($sql2);
×
746
     $myrow2 = $result2->baseFetchRow();
×
747

748
     $sql3 = "SELECT * FROM opt  WHERE sid='".$sid."' AND cid='".$cid."' AND opt_proto='6'";
×
749
     $result3 = $db->baseExecute($sql3);
×
750
     $num_opt = $result3->baseRecordCount();
×
751

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

754
      if ( ($myrow2[6] & 128) != 0 )  $s = $s.'2';  else $s = $s.'*';
×
755
      if ( ($myrow2[6] & 64 ) != 0 )  $s = $s.'1';  else $s = $s.'*';
×
756
      if ( ($myrow2[6] & 32) != 0  )  $s = $s.'U';  else $s = $s.'*';
×
757
      if ( ($myrow2[6] & 16 ) != 0 )  $s = $s.'A';  else $s = $s.'*';
×
758
      if ( ($myrow2[6] & 8) != 0   )  $s = $s.'P';  else $s = $s.'*';
×
759
      if ( ($myrow2[6] & 4 ) != 0  )  $s = $s.'R';  else $s = $s.'*';
×
760
      if ( ($myrow2[6] & 2 ) != 0  )  $s = $s.'S';  else $s = $s.'*';
×
761
      if ( ($myrow2[6] & 1 ) != 0  )  $s = $s.'F';  else $s = $s.'*';
×
762

763
      $s = $s." seq=$myrow2[2]\n".
×
764
              "      ack=$myrow2[3] off=$myrow2[4] res=$myrow2[5] win=$myrow2[7] urp=$myrow2[9] ".
×
765
              "chksum=$myrow2[8]\n";
×
766

767
      if ( $num_opt != 0)
×
768
      {
769
         $s = $s."      Options:\n";
×
770
         for ( $i = 0; $i < $num_opt; $i++)
×
771
         {
772
             $myrow3 = $result3->baseFetchRow();
×
773
             $s = $s."       #".($i+1)." - ".TCPOption2str($myrow3[4])." len=$myrow3[5]";
×
774
             if ( $myrow3[5] != 0 )
×
775
                $s = $s." data=".$myrow3[6];
×
776
            $s = $s."\n";           
×
777
         }
778
      }
779

780
      $result2->baseFreeRows();
×
781
      $result3->baseFreeRows();
×
782
  }
783

784
  /* UDP */
785
  if ( $layer4_proto == "17" )
×
786
  {
787

788
     $sql2 = "SELECT * FROM udphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
×
789
     $result2 = $db->baseExecute($sql2);
×
790
     $myrow2 = $result2->baseFetchRow();
×
791

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

794
     $result2->baseFreeRows();
×
795
  }
796

797
  /* ICMP */
798
  if ( $layer4_proto == "1" )
×
799
  {
800
     $sql2 = "SELECT icmp_type, icmp_code, icmp_csum, icmp_id, icmp_seq FROM icmphdr ".
801
             "WHERE sid='".$sid."' AND cid='".$cid."'";
802
     $result2 = $db->baseExecute($sql2);
×
803
     $myrow2 = $result2->baseFetchRow();
×
804

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

808
     $result2->baseFreeRows();
×
809
  }
810

811
  /* Print the Payload */
812
  $sql2 = "SELECT data_payload FROM data WHERE sid='".$sid."' AND cid='".$cid."'";
×
813
  $result2 = $db->baseExecute($sql2);
×
814

815
  /* get encoding information and detail_level on the payload */
816
  $sql3 = 'SELECT encoding, detail FROM sensor WHERE sid='.$sid;
×
817
  $result3 = $db->baseExecute($sql3);
×
818
  $myrow3 = $result3->baseFetchRow();  
×
819
  
820
  $s = $s."Payload: ";
×
821

822
  $myrow2 = $result2->baseFetchRow();
×
823
  if ( $myrow2 )
824
  {
825
     /* print the packet based on encoding type */
826
     $s = $s.PrintPacketPayload($myrow2[0], $myrow3[0], 2)."\n";
×
827

828
     $result3->baseFreeRows();     
×
829
  }
830
  else
831
  {
832
     /* Don't have payload so lets print out why by checking the detail level */
833

834
     /* if have fast detail level */
835
     if ( $myrow3[1] == "0" )
×
836
        $s = $s."Fast logging used so payload was discarded\n";
×
837
     else
838
        $s = $s."none\n";
×
839
  }
840

841
  $result2->baseFreeRows();
×
842
 
843
  return $s; 
×
844
}
845

846
function ExportPacket_summary( $sid, $cid, $db, $export_type = 0 ){
847
        GLOBAL $action, $action_arg;
848
        // Event.
849
  $sql2 = "SELECT signature, timestamp FROM acid_event WHERE sid='".$sid."' AND cid='".$cid."'";
×
850
  $result2 = $db->baseExecute($sql2);
×
851
  $myrow2 = $result2->baseFetchRow();
×
852

853
  $alert_timestamp = $myrow2[1];
×
854
  $alert_sig = BuildSigByID($myrow2[0], $db, 2);
×
855

856
  $result2->baseFreeRows();
×
857

858
  /* IP */
859
  $src_ip = $dst_ip = $src_port = $dst_port = "";
×
860
  $sql2 = "SELECT ip_src, ip_dst, ip_proto". 
861
          " FROM iphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
862

863
  $result2 = $db->baseExecute($sql2);
×
864
  $myrow2 = $result2->baseFetchRow();
×
865

866
  $layer4_proto = "";
×
867
  if ( $myrow2[0] != "" )
×
868
  {
869
     $src_ip = baseLong2IP($myrow2[0]);
×
870
     $dst_ip = baseLong2IP($myrow2[1]);
×
871
     $layer4_proto = $myrow2[2];
×
872
  }
873
  $result2->baseFreeRows();
×
874

875
  /* TCP */
876
  if ( $layer4_proto == "6" )  
×
877
  {
878
     $sql2 = "SELECT tcp_sport, tcp_dport FROM tcphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
×
879
     $result2 = $db->baseExecute($sql2);
×
880
     $myrow2 = $result2->baseFetchRow();
×
881

882
     if ( $export_type == 0 )
×
883
     {
884
        $src_port = ":".$myrow2[0]." -> ";
×
885
        $dst_port = ":".$myrow2[1];
×
886
     }  
887
     else
888
     {
889
        $src_port = $myrow2[0];
×
890
        $dst_port = $myrow2[1];
×
891
     }   
892

893
     $result2->baseFreeRows();
×
894
  }
895

896
  /* UDP */
897
  if ( $layer4_proto == "17" )
×
898
  {
899

900
     $sql2 = "SELECT * FROM udphdr  WHERE sid='".$sid."' AND cid='".$cid."'";
×
901
     $result2 = $db->baseExecute($sql2);
×
902
     $myrow2 = $result2->baseFetchRow();
×
903

904
     if ( $export_type == 0 )
×
905
     {
906
       $src_port = ":".$myrow2[2]." -> ";
×
907
       $dst_port = ":".$myrow2[3];
×
908
     }
909
     else
910
     {
911
       $src_port = $myrow2[2];
×
912
       $dst_port = $myrow2[3];
×
913
     }
914

915
     $result2->baseFreeRows();
×
916
  }
917

918
  /* ICMP */
919
  if ( $layer4_proto == "1" )
×
920
  {
921
     if ( $export_type == 0 )
×
922
       $src_ip = $src_ip." -> ";
×
923
     $src_port = $dst_port = "";
×
924
  }
925
  
926
 /* Portscan Traffic */
927
   if ( $layer4_proto == "255" )
×
928
   {
929
      if ( $export_type == 0 )
×
930
         $src_ip = $src_ip." -> ";
×
931
   }
932

933
  if ( $export_type == 0 )
×
934
  {
935
    $s = sprintf("#%d-%d| [%s] %s%s%s%s %s\r\n",
×
936
                 $sid, $cid, $alert_timestamp, 
937
                 $src_ip, $src_port, $dst_ip, $dst_port,
938
                 $alert_sig); 
939
  }
940
  else /* CSV format */
941
  {
942
    $s = sprintf("\"%d\", \"%d\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"\r\n",
×
943
                 $sid, $cid, $alert_timestamp,
944
                 $src_ip, $src_port, $dst_ip, $dst_port,
945
                 $alert_sig);
946
  }
947

948
  return $s; 
×
949
}
950

951
function base_header( $url ){
952
        if ( !headers_sent() ){
×
953
                header($url);
×
954
                exit;
×
955
        }
956
}
957

958
function base_microtime(){
959
  list($usec, $sec) = explode(" ", microtime());
×
960
  return ((float)$usec + (float)$sec);
×
961
}
962

963
// Returns true if color is valid html color code.
964
function HtmlColor ( $color ){
965
        $color = strtolower($color);
340✔
966
        $wsc = array(
68✔
967
                'black', 'silver', 'gray', 'white', 'maroon', 'red', 'pruple',
238✔
968
                'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal',
102✔
969
                'aqua'
970
        );
102✔
971
        $Ret = false;
340✔
972
        if (
973
                in_array($color, $wsc) // Web Safe Color.
340✔
974
                || preg_match("/^#?[0-9A-F]{6}$/i", $color) // Hex RGB Color Code.
322✔
975
        ){
102✔
976
                $Ret = true;
200✔
977
        }
60✔
978
        return ($Ret);
340✔
979
}
980

981
function Percent ( $Value = 1, $Count = 1 ){
982
        if ( $Value > $Count ){
100✔
983
                $Count = $Value;
20✔
984
        }
6✔
985
        if ( $Count <= 0 ){
100✔
986
                $Count = 1;
20✔
987
        }
6✔
988
        if ( $Value <= 0 ){ // Set %
100✔
989
                $Ret = 0;
40✔
990
        }else{
12✔
991
                $Ret = round($Value/$Count*100);
60✔
992
        }
993
        return ($Ret);
100✔
994
}
995

996
// Returns true if var is a string containing data.
997
function LoadedString ( $var ){
998
        $Ret = false;
1,720✔
999
        if ( is_string($var) && !empty($var)){
1,720✔
1000
                $Ret = true;
1,500✔
1001
        }
450✔
1002
        return $Ret;
1,720✔
1003
}
1004

1005
// Returns true if file passes include safety checks.
1006
// Also includes the file.
1007
function base_include ( $file = '' ){
1008
        GLOBAL $BASE_path, $debug_mode;
154✔
1009
        $Ret = false;
220✔
1010
        $EMsg = '';
220✔
1011
        $tfile = "$BASE_path/custom/" . $file;
220✔
1012
        $ReqRE = preg_quote("$BASE_path/custom/",'/');
220✔
1013
        $ReqRE .= ".*\.htm(l)?";
220✔
1014
        if ( preg_match("/^" . $ReqRE ."$/i", $tfile) ){
220✔
1015
                // File must be in specific location with specific extension.
1016
                $Loc = realpath($tfile); // Final file must
160✔
1017
                if ( $Loc != false // exist and resolve to an absolute path.
112✔
1018
                        && fileowner($Loc) != false // not be owned by UID 0 (root).
160✔
1019
                        && ChkAccess($Loc) == 1 // be a real file & be readable.
160✔
1020
                ){
48✔
1021
                        if ( preg_match("/^" . $ReqRE ."$/i", $Loc) ){
100✔
1022
                                // be in specific location with specific extension.
1023
                                $Ret = true;
80✔
1024
                                $EMsg = 'OK';
80✔
1025
                                include_once($Loc);
80✔
1026
                        }else{
24✔
1027
                                $EMsg = 'Loc';
20✔
1028
                                $tfile .= " -> $Loc";
76✔
1029
                        }
1030
                }else{
30✔
1031
                        $EMsg = 'Access';
130✔
1032
                }
1033
        }else{
48✔
1034
                $EMsg = 'File';
60✔
1035
        }
1036
        if ( $debug_mode > 0 ){
220✔
1037
                print "Test: $file\n";
220✔
1038
                print "$EMsg: $tfile\n";
220✔
1039
        }
66✔
1040
        return $Ret;
220✔
1041
}
1042

1043
// Returns true if asciiclean is set.
1044
// HTTP GET params take precedence over cookie values.
1045
function GetAsciiClean(){
1046
        $Ret = false;
120✔
1047
        if ( isset($_GET['asciiclean']) ){ // Check HTTP GET param.
120✔
1048
                $Ret = ChkGet('asciiclean', 1);
60✔
1049
        }else{ // No GET, check for cookie.
18✔
1050
                $Ret = ChkCookie('asciiclean', 'clean');
60✔
1051
        }
1052
        return $Ret;
120✔
1053
}
1054

1055
// Returns 1 if file or directory passes access checks.
1056
// Returns < 1 error code otherwise.
1057
function ChkAccess( $path, $type='f' ){
1058
        $Ret = 0; // Path Error
1,020✔
1059
        if ( LoadedString($path) ){
1,020✔
1060
                $type = strtolower($type);
1,020✔
1061
                $rcf = 0;
1,020✔
1062
                $Ret = -1; // Type Error
1,020✔
1063
                if ( $type == 'f' ){
1,020✔
1064
                        if ( is_file($path) ){
1,000✔
1065
                                $rcf = 1;
940✔
1066
                        }
240✔
1067
                }elseif ( $type == 'd' ){
320✔
1068
                        if ( is_dir($path) ){
20✔
1069
                                $rcf = 1;
20✔
1070
                        }
6✔
1071
                }
6✔
1072
                if ( $rcf == 1 ){
1,020✔
1073
                        $Ret = -2; // Readable Error
820✔
1074
                        $version = explode('.', phpversion());
820✔
1075
                        // PHP Safe Mode cutout.
1076
                        //    Added: 2005-03-25 for compatabibility with PHP 4x & 5.0x
1077
                        //      See: https://sourceforge.net/p/secureideas/bugs/47
1078
                        // PHP Safe Mode w/o cutout successful.
1079
                        // Verified: 2019-05-31 PHP 5.3.29 via CI & Unit Tests.
1080
                        //      See: https://github.com/NathanGibbs3/BASE/issues/34
1081
                        // May work: PHP > 5.1.4.
1082
                        //      See: https://www.php.net/manual/en/function.is-readable.php
1083
                        if (
1084
                                $version[0] > 5
820✔
1085
                                || ($version[0] == 5 && $version[1] > 1)
246✔
1086
                                || ($version[0] == 5 && $version[1] == 1 && $version[2] > 4 )
246✔
1087
                                || ini_get("safe_mode") != true
574✔
1088
                        ){
246✔
1089
                                if ( is_readable($path) ){
820✔
1090
                                        $Ret = 1;
808✔
1091
                                }
234✔
1092
                        }else{
246✔
1093
                                // @codeCoverageIgnoreStart
1094
                                // PHPUnit test only covers this code path on PHP < 5.1.5
1095
                                // Unable to validate in CI.
1096
                                $Ret = 1;
1097
                                // @codeCoverageIgnoreEnd
1098
                        }
1099
                }
246✔
1100
        }
306✔
1101
        return $Ret;
1,020✔
1102
}
1103

1104
// Returns Library if found & file passes access checks.
1105
// Returns empty string otherwise.
1106
function ChkLib ( $path='', $LibLoc='', $LibFile='' ){
1107
        GLOBAL $debug_mode;
532✔
1108
        $EMPfx = __FUNCTION__ . ': ';
760✔
1109
        $Ret = '';
760✔
1110
        if ( LoadedString($LibFile) ){
760✔
1111
                $sc = DIRECTORY_SEPARATOR;
740✔
1112
                $tmp = $LibFile;
740✔
1113
                // Strip leading or trailing seperators from Lib file.
1114
                $ReqRE = "(^\\$sc|\\$sc\$)";
740✔
1115
                $LibFile = preg_replace("/".$ReqRE."/", '', $LibFile);
740✔
1116
                if ( $debug_mode > 1 && $tmp != $LibFile ){
740✔
1117
                        ErrorMessage('Req Lib: ' . XSSPrintSafe($tmp), 0, 1);
20✔
1118
                        ErrorMessage('Mod Lib: ' . XSSPrintSafe($LibFile), 0, 1);
20✔
1119
                }
6✔
1120
                if ( LoadedString($path) ){ // Path to Lib
740✔
1121
                        $tmp = $path; // Strip trailing seperator from path.
740✔
1122
                        $ReqRE = "\\$sc\$";
740✔
1123
                        $path = preg_replace("/".$ReqRE."/", '', $path);
740✔
1124
                        if ( $debug_mode > 1 && $tmp != $path ){
740✔
1125
                                ErrorMessage('Req Loc: ' . XSSPrintSafe($tmp), 0, 1);
40✔
1126
                                ErrorMessage('Mod Loc: ' . XSSPrintSafe($path), 0, 1);
40✔
1127
                        }
12✔
1128
                        $LibFile .= '.php';
740✔
1129
                        $FinalLib = implode( $sc, array($path, $LibFile) );
740✔
1130
                        if ( $debug_mode > 1 ){
740✔
1131
                                ErrorMessage(
120✔
1132
                                        XSSPrintSafe($EMPfx . "Chk: $FinalLib"),'black',1
120✔
1133
                                );
36✔
1134
                        }
36✔
1135
                        $tmp = ChkAccess($FinalLib);
740✔
1136
                        $Msg = $EMPfx . "Lib: $FinalLib ";
740✔
1137
                        $clr = 'red';
740✔
1138
                        if ( $tmp == 1 ){
740✔
1139
                                $Msg .= 'found';
600✔
1140
                                $clr = 'black';
600✔
1141
                                $Ret = $FinalLib;
600✔
1142
                        }else{
180✔
1143
                                $Msg .= 'not ';
240✔
1144
                        }
1145
                        if ( $tmp == -1 ){
740✔
1146
                                $Msg .= 'found';
220✔
1147
                        }elseif ( $tmp == -2 ){
656✔
1148
                                $Msg .= 'readable';
20✔
1149
                        }
6✔
1150
                        $Msg .= '.';
740✔
1151
                        if ( $debug_mode > 1 ){
740✔
1152
                                ErrorMessage($Msg, $clr, 1);
554✔
1153
                        }
36✔
1154
                }else{ // Relative path to Lib.
222✔
1155
                        if ( LoadedString($LibLoc) ){
200✔
1156
                                $tmp = $LibLoc; // Strip leading seperators from Loc.
100✔
1157
                                $ReqRE = "^\\$sc";
100✔
1158
                                $LibLoc = preg_replace("/".$ReqRE."/", '', $LibLoc);
100✔
1159
                                if ( $debug_mode > 1 && $tmp != $LibLoc ){
100✔
1160
                                        ErrorMessage('Req Loc: ' . XSSPrintSafe($tmp), 0, 1);
20✔
1161
                                        ErrorMessage('Mod Loc: ' . XSSPrintSafe($LibLoc), 0, 1);
20✔
1162
                                }
6✔
1163
                        }
30✔
1164
                        $PSPath = explode(PATH_SEPARATOR, ini_get('include_path'));
200✔
1165
                        foreach( $PSPath as $single_path ){
470✔
1166
                                if ( LoadedString($LibLoc) ){
200✔
1167
                                        $FinalLoc = implode( $sc, array($single_path, $LibLoc) );
100✔
1168
                                }else{
30✔
1169
                                        $FinalLoc = $single_path;
120✔
1170
                                }
1171
                                $tmp = ChkLib( $FinalLoc, '', $LibFile);
200✔
1172
                                if ( LoadedString($tmp) ){
200✔
1173
                                        $Ret = $tmp;
100✔
1174
                                        break;
228✔
1175
                                }
1176
                        }
60✔
1177
                }
1178
        }else{
222✔
1179
                if ( $debug_mode > 0 ){
20✔
1180
                        ErrorMessage($EMPfx . 'No Lib specified.', 0, 1);
20✔
1181
                }
6✔
1182
        }
1183
        return $Ret;
760✔
1184
}
1185

1186
// Returns true if cookie is set & contains value.
1187
function ChkCookie( $var, $val ){
1188
        $Ret = false;
220✔
1189
        if ( LoadedString($var) ){
220✔
1190
                if ( isset($_COOKIE[$var]) && $_COOKIE[$var] == $val ){
200✔
1191
                        $Ret = true;
80✔
1192
                }
24✔
1193
        }
60✔
1194
        return $Ret;
220✔
1195
}
1196

1197
// Returns true if HTTP GET param is set & contains value.
1198
function ChkGET( $var, $val ){
1199
        $Ret = false;
180✔
1200
        if ( LoadedString($var) ){
180✔
1201
                if ( isset($_GET[$var]) && $_GET[$var] == $val ){
160✔
1202
                        $Ret = true;
60✔
1203
                }
18✔
1204
        }
48✔
1205
        return $Ret;
180✔
1206
}
1207

1208
// Returns true when key is in array, false otherwise.
1209
function base_array_key_exists( $SKey, $SArray ){ // PHP Version Agnostic.
1210
        $Ret = false;
360✔
1211
        if ( is_array($SArray) && count($SArray) > 0 ){
360✔
1212
                $version = explode('.', phpversion());
340✔
1213
                // Use built in functions when we can.
1214
                if ( $version[0] > 4 || ($version[0] == 4 && $version[1] > 1) ){
340✔
1215
                        // PHP > 4.1
1216
                        $Ret = array_key_exists( $SKey, $SArray );
340✔
1217
                // @codeCoverageIgnoreStart
1218
                // PHPUnit test only covers this code path on PHP < 4.2.0
1219
                // Unable to validate in CI.
1220
                }elseif (
1221
                        ($version[0] == 4 && $version[1] > 0 )
1222
                        || ($version[0] == 4 && $version[1] == 0 && $version[2] > 5)
1223
                ){ // PHP > 4.0.5
1224
                        $Ret = key_exists($SKey, $SArray);
1225
                }else{ // No built in functions, PHP Version agnostic.
1226
                        $Ret = in_array($SKey, array_keys($SArray) );
1227
                }
1228
                // @codeCoverageIgnoreEnd
1229
        }
102✔
1230
        return $Ret;
360✔
1231
}
1232

1233
// Returns true if PEAR library can be loaded, false otherwise.
1234
function PearInc( $Desc = '', $Loc = '', $Lib = '', $Silent = 1, $Fatal = 0 ){
1235
        GLOBAL $debug_mode;
126✔
1236
        $EMPfx = __FUNCTION__ . ': ';
180✔
1237
        $Ret = false;
180✔
1238
        if ( LoadedString($Lib) ){
180✔
1239
                if ( !is_int($Silent) ){ // Input Validation
160✔
1240
                        $Silent = 1; // Default to no error message display.
20✔
1241
                }
6✔
1242
                if ( !is_int($Fatal) ){
160✔
1243
                        $Fatal = 0;
20✔
1244
                }
6✔
1245
                $LLF = ChkLib('', $Loc , $Lib); // Load Lib File.
160✔
1246
                if ( LoadedString($LLF) ){
160✔
1247
                        $LLI = include_once($LLF); // Load Lib Include.
80✔
1248
                }
24✔
1249
                if ( $LLF == '' || $LLI == false ){
160✔
1250
                        if ( LoadedString($Loc) ){
80✔
1251
                                $LibName = $Loc.'_'.$Lib;
40✔
1252
                        }else{
12✔
1253
                                $LibName = $Lib;
40✔
1254
                                $Loc = '';
40✔
1255
                        }
1256
                        if ( !LoadedString($Desc) ){
80✔
1257
                                $Desc = $LibName;
80✔
1258
                        }
24✔
1259
                        $sc = DIRECTORY_SEPARATOR;
80✔
1260
                        $Lib = implode( $sc, array($Loc, $Lib) ).'.php';
80✔
1261
                        $EMsg = "$Desc Lib: $Lib not ";
80✔
1262
                        if ( $LLF == '' ){
80✔
1263
                                $EMsg .= 'accessable';
80✔
1264
                        }elseif ( $LLI == false ){
24✔
1265
                                // @codeCoverageIgnoreStart
1266
                                // This code path should never run.
1267
                                $EMsg .= 'loaded';
1268
                                // @codeCoverageIgnoreEnd
1269
                        }
1270
                        $EMsg .= '.';
80✔
1271
                        if ( $Silent != 1 ){ // Display fancy error to user.
80✔
1272
                                $URL = "https://pear.php.net/package/$LibName";
40✔
1273
                                LibIncError (
40✔
1274
                                        $Desc, $Loc, $Lib, $EMsg, $LibName, $URL, $Fatal, 1
28✔
1275
                                );
12✔
1276
                        }else{
12✔
1277
                                if ( $debug_mode > 0 ){
40✔
1278
                                        ErrorMessage("$EMPfx$EMsg", 0, 1);
68✔
1279
                                }
12✔
1280
                        }
1281
                }else{
24✔
1282
                        $Ret = true;
136✔
1283
                }
1284
        }else{
48✔
1285
                if ( $debug_mode > 0 ){
20✔
1286
                        ErrorMessage($EMPfx . 'No Lib specified.', 0, 1);
20✔
1287
                }
6✔
1288
        }
1289
        return $Ret;
180✔
1290
}
1291

1292
// Returns true if Archive DB is in use, false otherwise.
1293
function ChkArchive(){ // Issue #183
1294
        GLOBAL $archive_exists;
406✔
1295
        $EMPfx = 'BASE Security Alert ' . __FUNCTION__ . ': ';
580✔
1296
        $Ret = false;
580✔
1297
        if ( $archive_exists != 0 ){
580✔
1298
                if ( ChkCookie ('archive', 1) || ChkGet ('archive', 1) ){
80✔
1299
                        $Ret = true;
74✔
1300
                }
18✔
1301
        }else{ // Archive DB disabled. Alert on param tampering.
24✔
1302
                $tmp = ''; // No Alert
520✔
1303
                if ( isset($_GET['archive']) ){ // Get param Hack Alert
520✔
1304
                        $tmp = 'HTTP GET';
20✔
1305
                }
6✔
1306
                if ( isset($_COOKIE['archive']) ){ // Cookie Hack Alert.
520✔
1307
                        $tmp = 'COOKIE';
20✔
1308
                }
6✔
1309
                if ( $tmp != '' ){
520✔
1310
                        error_log($EMPfx . "$tmp tampering detected.");
40✔
1311
                }
12✔
1312
        }
1313
        return $Ret;
580✔
1314
}
1315
?>
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