Example #1
0
function get_cache($host, $value)
{
    global $dev_cache;
    $host = strtolower(trim($host));
    // Check cache expiration
    $now = time();
    $expired = TRUE;
    if (isset($dev_cache[$host]['lastchecked'])) {
        if ($now - $dev_cache[$host]['lastchecked'] < 3600) {
            $expired = FALSE;
        }
        // will expire after 1 hour
    }
    if ($expired) {
        $dev_cache[$host]['lastchecked'] = $now;
    }
    if (!isset($dev_cache[$host][$value]) || $expired) {
        switch ($value) {
            case 'device_id':
                // Try by hostname
                $dev_cache[$host]['device_id'] = dbFetchCell('SELECT `device_id` FROM `devices` WHERE `hostname` = ? OR `sysName` = ?', array($host, $host));
                // If failed, try by IP
                if (!is_numeric($dev_cache[$host]['device_id'])) {
                    $ip = $host;
                    $ip_version = get_ip_version($ip);
                    if ($ip_version !== FALSE) {
                        if ($ip_version == 6) {
                            $ip = Net_IPv6::uncompress($ip, TRUE);
                        }
                        $address_count = dbFetchCell('SELECT COUNT(*) FROM `ipv' . $ip_version . '_addresses` WHERE `ipv' . $ip_version . '_address` = ?;', array($ip));
                        if ($address_count) {
                            $query = 'SELECT `device_id` FROM `ipv' . $ip_version . '_addresses` AS A, `ports` AS I WHERE A.`ipv' . $ip_version . '_address` = ? AND I.`port_id` = A.`port_id`';
                            // If more than one IP address, also check the status of the port.
                            if ($address_count > 1) {
                                $query .= " AND I.`ifOperStatus` = 'up'";
                            }
                            $dev_cache[$host]['device_id'] = dbFetchCell($query, array($ip));
                        }
                    }
                }
                break;
            case 'os':
            case 'version':
                $dev_cache[$host][$value] = dbFetchCell('SELECT `' . $value . '` FROM `devices` WHERE `device_id` = ?', array(get_cache($host, 'device_id')));
                break;
            case 'os_group':
                $os = get_cache($host, 'os');
                $dev_cache[$host]['os_group'] = isset($GLOBALS['config']['os'][$os]['group']) ? $GLOBALS['config']['os'][$os]['group'] : '';
                break;
            default:
                return NULL;
        }
    }
    return $dev_cache[$host][$value];
}
 /**
  * Set the host. Returns true on success, false on failure (if there are
  * any invalid characters).
  *
  * @access public
  * @param string $host
  * @return bool
  */
 public function set_host($host)
 {
     if ($host === null || $host === '') {
         $this->host = null;
         $this->valid[__FUNCTION__] = true;
         return true;
     } elseif ($host[0] === '[' && substr($host, -1) === ']') {
         if (Net_IPv6::checkIPv6(substr($host, 1, -1))) {
             $this->host = $host;
             $this->valid[__FUNCTION__] = true;
             return true;
         } else {
             $this->host = null;
             $this->valid[__FUNCTION__] = false;
             return false;
         }
     } else {
         $this->host = $this->replace_invalid_with_pct_encoding($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$&\'()*+,;=', SIMPLEPIE_LOWERCASE);
         $this->valid[__FUNCTION__] = true;
         return true;
     }
 }
Example #3
0
function ipv62snmp($ipv6)
{
    $ipv6_split = array();
    $ipv6_ex = explode(':', Net_IPv6::uncompress($ipv6));
    for ($i = 0; $i < 8; $i++) {
        $ipv6_ex[$i] = zeropad($ipv6_ex[$i], 4);
    }
    $ipv6_ip = implode('', $ipv6_ex);
    for ($i = 0; $i < 32; $i += 2) {
        $ipv6_split[] = hexdec(substr($ipv6_ip, $i, 2));
    }
    return implode('.', $ipv6_split);
}
Example #4
0
  <div id="center">
    <div id="top" style="background: <?php 
echo $config['header_color'];
?>
;">
      <table cellpadding="0" cellspacing="0" width="100%">
        <tr>
          <td align="left"></td>
          <td align="right">
  <?php 
if ($_SESSION['authenticated']) {
    echo "Logged in as <b>" . $_SESSION['username'] . "</b> (<a href='?logout=yes'>Logout</a>)";
} else {
    echo "Not logged in!";
}
if (Net_IPv6::checkIPv6($_SERVER['REMOTE_ADDR'])) {
    echo " via <b>IPv6</b>";
} else {
    echo " via <b>IPv4</b>";
}
?>
          </td>
        </tr>
      </table>
    </div>

    <div id="header" style="border: 1px none #ccf;">
      <table width="100%" style="padding: 0px; margin:0px;">
        <tr>
          <td style="padding: 0px; margin:0px; border: none;">
            <div id="logo" style="padding: 10px"><a href="index.php"><img src="<?php 
function get_status_array($status)
{
    // Mike: I know that there are duplicated variables, but later will remove global
    global $config, $cache;
    $max_interval = filter_var($status['max']['interval'], FILTER_VALIDATE_INT, array('options' => array('default' => 24, 'min_range' => 1)));
    $max_count = filter_var($status['max']['count'], FILTER_VALIDATE_INT, array('options' => array('default' => 200, 'min_range' => 1)));
    $query_device_permitted = generate_query_permitted(array('device'), array('device_table' => 'D'));
    $query_port_permitted = generate_query_permitted(array('port'), array('port_table' => 'I'));
    // Show Device Status
    if ($status['devices']) {
        $query = 'SELECT * FROM `devices` AS D ';
        $query .= 'WHERE D.`status` = 0' . $query_device_permitted;
        $query .= 'ORDER BY D.`hostname` ASC';
        $entries = dbFetchRows($query);
        foreach ($entries as $device) {
            $boxes[] = array('sev' => 100, 'class' => 'Device', 'event' => 'Down', 'device_link' => generate_device_link($device, short_hostname($device['hostname'])), 'time' => deviceUptime($device, 'short-3'));
        }
    }
    // Uptime
    if ($status['uptime']) {
        if (filter_var($config['uptime_warning'], FILTER_VALIDATE_FLOAT) !== FALSE && $config['uptime_warning'] > 0) {
            $query = 'SELECT * FROM `devices` AS D ';
            $query .= 'WHERE D.`status` = 1 AND D.`uptime` > 0 AND D.`uptime` < ' . $config['uptime_warning'];
            $query .= $query_device_permitted;
            $query .= 'ORDER BY D.`hostname` ASC';
            $entries = dbFetchRows($query);
            foreach ($entries as $device) {
                $boxes[] = array('sev' => 10, 'class' => 'Device', 'event' => 'Rebooted', 'device_link' => generate_device_link($device, short_hostname($device['hostname'])), 'time' => deviceUptime($device, 'short-3'), 'location' => $device['location']);
            }
        }
    }
    // Ports Down
    if ($status['ports'] || $status['links']) {
        // warning about deprecated option: $config['warn']['ifdown']
        if (isset($config['warn']['ifdown']) && !$config['warn']['ifdown']) {
            print_warning("<strong>Config option obsolete</strong>\n                    Please note that config option <strong>\$config['warn']['ifdown']</strong> is now obsolete.\n                    Use options: <strong>\$config['frontpage']['device_status']['ports']</strong> and <strong>\$config['frontpage']['device_status']['errors']</strong>\n                    To remove this message, delete <strong>\$config['warn']['ifdown']</strong> from configuration file.");
        }
        $query = 'SELECT * FROM `ports` AS I ';
        if ($status['links'] && !$status['ports']) {
            $query .= 'INNER JOIN `links` as L ON I.`port_id` = L.`local_port_id` ';
        }
        $query .= 'LEFT JOIN `devices` AS D ON I.`device_id` = D.`device_id` ';
        $query .= "WHERE I.`ifOperStatus` = 'down' AND I.`ifAdminStatus` = 'up' ";
        if ($status['links'] && !$status['ports']) {
            $query .= ' AND L.`active` = 1 ';
        }
        $query .= $query_port_permitted;
        $query .= ' AND I.`ifLastChange` >= DATE_SUB(NOW(), INTERVAL ' . $max_interval . ' HOUR) ';
        $query .= 'ORDER BY I.`ifLastChange` DESC, D.`hostname` ASC, I.`ifDescr` * 1 ASC ';
        $entries = dbFetchRows($query);
        $i = 1;
        foreach ($entries as $port) {
            if ($i > $max_count) {
                // Limit to 200 ports on overview page
                break;
            }
            humanize_port($port);
            $boxes[] = array('sev' => 50, 'class' => 'Port', 'event' => 'Down', 'device_link' => generate_device_link($port, short_hostname($port['hostname'])), 'entity_link' => generate_port_link($port, short_ifname($port['label'], 13)), 'time' => formatUptime($config['time']['now'] - strtotime($port['ifLastChange'])), 'location' => $device['location']);
        }
    }
    // Ports Errors (only deltas)
    if ($status['errors']) {
        foreach ($cache['ports']['errored'] as $port_id) {
            $port = get_port_by_id($port_id);
            $device = device_by_id_cache($port['device_id']);
            humanize_port($port);
            if ($port['ifInErrors_delta']) {
                $port['string'] .= 'Rx: ' . format_number($port['ifInErrors_delta']);
            }
            if ($port['ifInErrors_delta'] && $port['ifOutErrors_delta']) {
                $port['string'] .= ', ';
            }
            if ($port['ifOutErrors_delta']) {
                $port['string'] .= 'Tx: ' . format_number($port['ifOutErrors_delta']);
            }
            $boxes[] = array('sev' => 75, 'class' => 'Port', 'event' => 'Errors', 'device_link' => generate_device_link($device, short_hostname($device['hostname'])), 'entity_link' => generate_port_link($port, short_ifname($port['label'], 13)), 'time' => $port['string'], 'location' => $device['location']);
        }
    }
    // Services
    if ($status['services']) {
        $query = 'SELECT * FROM `services` AS S ';
        $query .= 'LEFT JOIN `devices` AS D ON S.device_id = D.device_id ';
        $query .= "WHERE S.`service_status` = 'down' AND S.`service_ignore` = 0";
        $query .= $query_device_permitted;
        $query .= 'ORDER BY D.`hostname` ASC';
        $entries = dbFetchRows($query);
        foreach ($entries as $service) {
            $boxes[] = array('sev' => 50, 'class' => 'Service', 'event' => 'Down', 'device_link' => generate_device_link($service, short_hostname($service['hostname'])), 'entity_link' => $service['service_type'], 'time' => formatUptime($config['time']['now'] - strtotime($service['service_changed']), 'short'), 'location' => $device['location']);
        }
    }
    // BGP
    if ($status['bgp']) {
        if (isset($config['enable_bgp']) && $config['enable_bgp']) {
            $query = 'SELECT * FROM `devices` AS D ';
            $query .= 'LEFT JOIN `bgpPeers` AS B ON B.`device_id` = D.`device_id` ';
            $query .= 'LEFT JOIN `bgpPeers-state` AS BS ON B.`bgpPeer_id` = BS.`bgpPeer_id` ';
            $query .= "WHERE (`bgpPeerAdminStatus` = 'start' OR `bgpPeerAdminStatus` = 'running') AND `bgpPeerState` != 'established' ";
            $query .= $query_device_permitted;
            $query .= 'ORDER BY D.`hostname` ASC';
            $entries = dbFetchRows($query);
            foreach ($entries as $peer) {
                $peer_ip = strstr($peer['bgpPeerRemoteAddr'], ':') ? Net_IPv6::compress($peer['bgpPeerRemoteAddr']) : $peer['bgpPeerRemoteAddr'];
                $peer['wide'] = strstr($peer['bgpPeerRemoteAddr'], ':') ? TRUE : FALSE;
                $boxes[] = array('sev' => 75, 'class' => 'BGP Peer', 'event' => 'Down', 'device_link' => generate_device_link($peer, short_hostname($peer['hostname'])), 'entity_link' => $peer_ip, 'wide' => $peer['wide'], 'time' => formatUptime($peer['bgpPeerFsmEstablishedTime'], 'short-3'), 'location' => $device['location']);
            }
        }
    }
    // Return boxes array
    return $boxes;
}
Example #6
0
/**
 * ipCalc calculations
 */
function calculateIpCalcResult($cidr)
{
    /* first verify address type */
    $type = IdentifyAddress($cidr);
    /* IPv4 */
    if ($type == "IPv4") {
        $net = Net_IPv4::parseAddress($cidr);
        //set ip address type
        $out['Type'] = 'IPv4';
        //calculate network details
        $out['IP address'] = $net->ip;
        // 192.168.0.50
        $out['Network'] = $net->network;
        // 192.168.0.0
        $out['Broadcast'] = $net->broadcast;
        // 192.168.255.255
        $out['Subnet bitmask'] = $net->bitmask;
        // 16
        $out['Subnet netmask'] = $net->netmask;
        // 255.255.0.0
        $out['Subnet wildcard'] = long2ip(~ip2long($net->netmask));
        //0.0.255.255
        //calculate min/max IP address
        $out['Min host IP'] = long2ip(ip2long($out['Network']) + 1);
        $out['Max host IP'] = long2ip(ip2long($out['Broadcast']) - 1);
        $out['Number of hosts'] = ip2long($out['Broadcast']) - ip2long($out['Min host IP']);
        //subnet class
        $out['Subnet Class'] = checkIpv4AddressType($out['Network'], $out['Broadcast']);
        //if IP == subnet clear the Host fields
        if ($out['IP address'] == $out['Network']) {
            $out['IP address'] = "/";
        }
    } else {
        //set ip address type
        $out['Type'] = 'IPv6';
        //calculate network details
        /*         $out['Host address']              = Net_IPv6::removeNetmaskSpec ( $cidr );  */
        $out['Host address'] = $cidr;
        $out['Host address'] = Net_IPv6::compress($out['Host address'], 1);
        $out['Host address (uncompressed)'] = Net_IPv6::uncompress($out['Host address']);
        $mask = Net_IPv6::getNetmaskSpec($cidr);
        $subnet = Net_IPv6::getNetmask($cidr);
        $out['Subnet prefix'] = Net_IPv6::compress($subnet) . '/' . $mask;
        $out['Prefix length'] = Net_IPv6::getNetmaskSpec($cidr);
        // get reverse DNS entries
        $out['Host Reverse DNS'] = calculateReverseDNS6($out['Host address (uncompressed)']);
        $out['Subnet Reverse DNS'] = calculateReverseDNS6($subnet, $mask);
        //if IP == subnet clear the Host fields and Host Reverse DNS
        if ($out['Host address'] == $out['Subnet prefix']) {
            $out['Host address'] = '/';
            $out['Host address (uncompressed)'] = '/';
            unset($out['Host Reverse DNS']);
        }
        //min / max hosts
        $maxIp = gmp_strval(gmp_add(gmp_sub(gmp_pow(2, 128 - $mask), 1), ip2long6($subnet)));
        $out['Min host IP'] = long2ip6(gmp_strval(gmp_add(ip2long6($subnet), 1)));
        $out['Max host IP'] = long2ip6($maxIp);
        $out['Number of hosts'] = MaxHosts($mask, 1);
        //address type
        $out['Address type'] = Net_IPv6::getAddressType($cidr);
        $out['Address type'] = checkIpv6AddressType($out['Address type']);
    }
    /* return results */
    return $out;
}
require dirname(__FILE__) . '/../../../functions/PEAR/Spreadsheet/Excel/Writer.php';
# initialize required objects
$Database = new Database_PDO();
$Result = new Result();
$User = new User($Database);
$Subnets = new Subnets($Database);
$Sections = new Sections($Database);
$Tools = new Tools($Database);
$Addresses = new Addresses($Database);
# verify that user is logged in
$User->check_user_session();
# fetch search term
$search_term = $_REQUEST['search_term'];
//initialize Pear IPv6 object
require_once dirname(__FILE__) . '/../../../functions/PEAR/Net/IPv6.php';
$Net_IPv6 = new Net_IPv6();
// ipv6 ?
if ($Net_IPv6->checkIPv6($search_term) != false) {
    $type = "IPv6";
} elseif (strlen($search_term) == 17 && substr_count($search_term, ":") == 5) {
    $type = "mac";
    //count : -> must be 5
} else {
    if (strlen($search_term) == 12 && substr_count($search_term, ":") == 0 && substr_count($search_term, ".") == 0) {
        $type = "mac";
        //no dots or : -> mac without :
    } else {
        $type = $Addresses->identify_address($search_term);
        //identify address type
    }
}
Example #8
0
/**
 * Generate common popup links which uses ajax/entitypopup.php
 *
 * @param string $type Popup type, see possible types in html/ajax/entitypopup.php
 * @param string $text Text used as link name and ajax data
 * @param array $vars Array for generate url
 * @param string Additional css classes for link
 * @param boolean $escape Escape or not text in url
 * @return string Returns string with link, when hover on this link show popup message based on type
 */
function generate_popup_link($type, $text = NULL, $vars = array(), $class = NULL, $escape = TRUE)
{
    if (!is_string($type) || !is_string($text)) {
        return '';
    }
    if ($type == 'ip') {
        list($ip, $mask) = explode('/', $text, 2);
        $ip_version = get_ip_version($ip);
        if ($ip_version === 6) {
            // Autocompress IPv6 addresses
            $ip = Net_IPv6::compress($ip);
            $text = $ip;
            if (strlen($mask)) {
                $text .= '/' . $mask;
            }
        }
        if (!$ip_version || in_array($ip, array('0.0.0.0', '127.0.0.1', '::', '::1'))) {
            return $text;
        }
    }
    $url = count($vars) ? generate_url($vars) : 'javascript:void(0)';
    // If vars empty, set link not clickable
    $data = $text;
    if ($escape) {
        $text = escape_html($text);
    }
    return '<a href="' . $url . '" class="entity-popup' . ($class ? " {$class}" : '') . '" data-eid="' . $data . '" data-etype="' . $type . '">' . $text . '</a>';
}
Example #9
0
function discover_new_device($hostname, $source = 'xdp', $protocol = NULL, $device = NULL, $snmp_port = 161)
{
    global $config;
    $source = strtolower($source);
    // Check if source is enabled for autodiscovery
    if ($config['autodiscovery'][$source]) {
        $flags = OBS_DNS_ALL;
        if (!$protocol) {
            $protocol = strtoupper($source);
        }
        print_cli_data("Try discovering host", "{$hostname} through {$protocol}", 3);
        // By first detect hostname is IP or domain name (IPv4/6 == 4/6, hostname == FALSE)
        $ip_version = get_ip_version($hostname);
        if ($ip_version) {
            // Hostname is IPv4/IPv6
            $use_ip = TRUE;
            $ip = $hostname;
        } else {
            $use_ip = FALSE;
            // Add "mydomain" configuration if this resolves, converts switch1 -> switch1.mydomain.com
            if (!empty($config['mydomain']) && isDomainResolves($hostname . '.' . $config['mydomain'], $flags)) {
                $hostname .= '.' . $config['mydomain'];
            }
            // Determine v4 vs v6
            $ip = gethostbyname6($hostname, $flags);
            if ($ip) {
                $ip_version = get_ip_version($ip);
                print_debug("Host {$hostname} resolved as {$ip}");
            } else {
                // No DNS records
                print_debug("Host {$hostname} not resolved, autodiscovery fails.");
                return FALSE;
            }
        }
        if ($ip_version == 6) {
            $flags = $flags ^ OBS_DNS_A;
            // Exclude IPv4
        }
        if (isset($config['autodiscovery']['ping_skip']) && $config['autodiscovery']['ping_skip']) {
            $flags = $flags | OBS_PING_SKIP;
            // Add skip pings flag
        }
        if (match_network($ip, $config['autodiscovery']['ip_nets'])) {
            print_debug("Host {$hostname} ({$ip}) founded inside configured nets, trying to add:");
            // By first check if pingable
            $pingable = isPingable($ip, $flags);
            if (!$pingable && (isset($config['autodiscovery']['ping_skip']) && $config['autodiscovery']['ping_skip'])) {
                $flags = $flags | OBS_PING_SKIP;
                // Add skip pings flag if allowed in config
                $pingable = TRUE;
            }
            if ($pingable) {
                // Check if device duplicated by IP
                $ip = $ip_version == 4 ? $ip : Net_IPv6::uncompress($ip, TRUE);
                $db = dbFetchRow('SELECT D.`hostname` FROM ipv' . $ip_version . '_addresses AS A
                         LEFT JOIN `ports`   AS P ON A.`port_id`   = P.`port_id`
                         LEFT JOIN `devices` AS D ON D.`device_id` = P.`device_id`
                         WHERE D.`disabled` = 0 AND A.`ipv' . $ip_version . '_address` = ?', array($ip));
                if ($db) {
                    print_debug('Already have device ' . $db['hostname'] . " with IP {$ip}");
                    return FALSE;
                }
                // Detect snmp transport, net-snmp needs udp6 for ipv6
                $snmp_transport = $ip_version == 4 ? 'udp' : 'udp6';
                $new_device = detect_device_snmpauth($ip, $snmp_port, $snmp_transport);
                if ($new_device) {
                    if ($use_ip) {
                        // Detect FQDN hostname
                        // by sysName
                        $snmphost = snmp_get($new_device, 'sysName.0', '-Oqv', 'SNMPv2-MIB');
                        if ($snmphost) {
                            $snmp_ip = gethostbyname6($snmphost, $flags);
                        }
                        if ($snmp_ip == $ip) {
                            $hostname = $snmphost;
                        } else {
                            // by PTR
                            $ptr = gethostbyaddr6($ip);
                            if ($ptr) {
                                $ptr_ip = gethostbyname6($ptr, $flags);
                            }
                            if ($ptr && $ptr_ip == $ip) {
                                $hostname = $ptr;
                            } else {
                                if ($config['autodiscovery']['require_hostname']) {
                                    print_debug("Device IP {$ip} does not seem to have FQDN.");
                                    return FALSE;
                                } else {
                                    $hostname = $ip_version == 4 ? $ip : Net_IPv6::compress($hostname, TRUE);
                                    // Always use compressed IPv6 name
                                }
                            }
                        }
                        print_debug("Device IP {$ip} linked to FQDN name: {$hostname}");
                    }
                    $new_device['hostname'] = $hostname;
                    if (!check_device_duplicated($new_device)) {
                        $snmp_v3 = array();
                        if ($new_device['snmp_version'] === 'v3') {
                            $snmp_v3['snmp_authlevel'] = $new_device['snmp_authlevel'];
                            $snmp_v3['snmp_authname'] = $new_device['snmp_authname'];
                            $snmp_v3['snmp_authpass'] = $new_device['snmp_authpass'];
                            $snmp_v3['snmp_authalgo'] = $new_device['snmp_authalgo'];
                            $snmp_v3['snmp_cryptopass'] = $new_device['snmp_cryptopass'];
                            $snmp_v3['snmp_cryptoalgo'] = $new_device['snmp_cryptoalgo'];
                        }
                        $remote_device_id = createHost($new_device['hostname'], $new_device['snmp_community'], $new_device['snmp_version'], $new_device['snmp_port'], $new_device['snmp_transport'], $snmp_v3);
                        if ($remote_device_id) {
                            if (is_flag_set(OBS_PING_SKIP, $flags)) {
                                set_entity_attrib('device', $remote_device_id, 'ping_skip', 1);
                            }
                            $remote_device = device_by_id_cache($remote_device_id, 1);
                            if ($port) {
                                humanize_port($port);
                                log_event("Device autodiscovered through {$protocol} on " . $device['hostname'] . " (port " . $port['port_label'] . ")", $remote_device_id, 'port', $port['port_id']);
                            } else {
                                log_event("Device autodiscovered through {$protocol} on " . $device['hostname'], $remote_device_id, $protocol);
                            }
                            //array_push($GLOBALS['devices'], $remote_device); // createHost() already puth this
                            return $remote_device_id;
                        }
                    }
                }
            }
        } else {
            print_debug("IP {$ip} ({$hostname}) not permitted inside \$config['autodiscovery']['ip_nets'] in config.php");
        }
        print_debug('Autodiscovery for host ' . $hostname . ' failed.');
    } else {
        print_debug('Autodiscovery for protocol ' . $protocol . ' disabled.');
    }
    return FALSE;
}
Example #10
0
include "../config.php";
include_once "../includes/definitions.inc.php";
include "includes/functions.inc.php";
include "../includes/functions.inc.php";
include "includes/authenticate.inc.php";
if (!$_SESSION['authenticated']) {
    echo "unauthenticated";
    exit;
}
if ($_GET['query'] && $_GET['cmd']) {
    $host = $_GET['query'];
    $ip = '';
    if (Net_IPv4::validateIP($host)) {
        $ip = $host;
        $ip_version = 4;
    } elseif (Net_IPv6::checkIPv6($host)) {
        $ip = $host;
        $ip_version = 6;
    } else {
        $ip = gethostbyname($host);
        if ($ip && $ip != $host) {
            $ip_version = 4;
        } else {
            $ip = gethostbyname6($host, FALSE);
            if ($ip) {
                $ip_version = 6;
            }
        }
    }
    if ($ip) {
        switch ($_GET['cmd']) {
Example #11
0
                echo "Found peer {$peer_ip} (AS{$peer_as})\n";
            }
            $peerlist[] = array('ip' => $peer_ip, 'as' => $peer_as);
        }
    }
    # Foreach
    if ($device['os'] == "junos") {
        ## Juniper BGP4-V2 MIB, ipv6 only for now, because v4 should be covered in BGP4-MIB above
        $peers_cmd = $config['snmpwalk'] . " -M +" . $config['install_dir'] . "/mibs/junos -m BGP4-V2-MIB-JUNIPER -CI -Onq -" . $device['snmpver'] . " -c" . $device['community'] . " " . $device['hostname'] . ":" . $device['port'] . " ";
        $peers_cmd .= "jnxBgpM2PeerRemoteAs.0.ipv6";
        # FIXME: is .0 the only possible value here?
        $peers = trim(str_replace(".1.3.6.1.4.1.2636.5.1.1.2.1.1.1.13.0.", "", `{$peers_cmd}`));
        foreach (explode("\n", $peers) as $peer) {
            list($peer_ip_snmp, $peer_as) = split(" ", $peer);
            # Magic! Basically, takes SNMP form and finds peer IPs from the walk OIDs.
            $peer_ip = Net_IPv6::compress(snmp2ipv6(implode('.', array_slice(explode('.', $peer_ip_snmp), count(explode('.', $peer_ip_snmp)) - 16))));
            if ($peer) {
                if ($debug) {
                    echo "Found peer {$peer_ip} (AS{$peer_as})\n";
                }
                $peerlist[] = array('ip' => $peer_ip, 'as' => $peer_as);
            }
        }
        # Foreach
    }
    # OS junos
} else {
    echo "No BGP on host";
    if ($device['bgpLocalAs']) {
        mysql_query("UPDATE devices SET bgpLocalAs = NULL WHERE device_id = '" . $device['device_id'] . "'");
        echo " (Removed ASN) ";
     if (!is_hostname($_POST['hostname'])) {
         $input_errors[] = gettext("The hostname can only contain the characters A-Z, 0-9 and '-'.");
     } else {
         if (!is_unqualified_hostname($_POST['hostname'])) {
             $input_errors[] = gettext("A valid hostname is specified, but the domain name part should be omitted");
         }
     }
 }
 if ($_POST['ipaddrv6']) {
     if (!is_ipaddrv6($_POST['ipaddrv6'])) {
         $input_errors[] = gettext("A valid IPv6 address must be specified.");
     } elseif ($config['interfaces'][$if]['ipaddrv6'] == 'track6') {
         $trackifname = $config['interfaces'][$if]['track6-interface'];
         $trackcfg = $config['interfaces'][$trackifname];
         $pdlen = 64 - $trackcfg['dhcp6-ia-pd-len'];
         if (!Net_IPv6::isInNetmask($_POST['ipaddrv6'], '::', $pdlen)) {
             $input_errors[] = sprintf(gettext("The prefix (upper %s bits) must be zero.  Use the form %s"), $pdlen, dhcpv6_pd_str_help($ifcfgsn));
         }
     }
 }
 if (empty($_POST['duid'])) {
     $input_errors[] = gettext("A valid DUID must be specified.");
 }
 /* check for overlaps */
 foreach ($a_maps as $mapent) {
     if (isset($id) && $a_maps[$id] && $a_maps[$id] === $mapent) {
         continue;
     }
     if ($mapent['hostname'] == $_POST['hostname'] && $mapent['hostname'] || $mapent['duid'] == $_POST['duid']) {
         $input_errors[] = gettext("This Hostname, IP or DUID already exists.");
         break;
Example #13
0
foreach ($cache_arp as $entry) {
    $old_if = $entry['ifIndex'];
    $old_mac = $entry['mac_address'];
    $old_address = $entry['ip_address'];
    $old_version = $entry['ip_version'];
    $old_table[$old_if][$old_version][$old_address] = $old_mac;
}
$ipv4_pattern = '/\\[(\\d+)\\](?:\\[ipv4\\])?\\["?([\\d\\.]+)"?\\]\\s+([a-f\\d]+):([a-f\\d]+):([a-f\\d]+):([a-f\\d]+):([a-f\\d]+):([a-f\\d]{1,2})/i';
$ipv6_pattern = '/\\[(\\d+)\\](?:\\[ipv6\\])?\\["?([a-f\\d:]+)"?\\]\\s+(?:([a-f\\d]+):([a-f\\d]+):)?([a-f\\d]+):([a-f\\d]+):([a-f\\d]+):([a-f\\d]{1,2})/i';
foreach (explode("\n", $oid_data) as $data) {
    if (preg_match($ipv4_pattern, $data, $matches)) {
        $ip = $matches[2];
        $ip_version = 4;
    } elseif (preg_match($ipv6_pattern, $data, $matches)) {
        if (count(explode(':', $matches[2])) === 8) {
            $ip = Net_IPv6::uncompress($matches[2], TRUE);
        } else {
            $ip = hex2ip($matches[2]);
        }
        $ip_version = 6;
    } else {
        // In principle the such shouldn't be.
        continue;
    }
    $if = $matches[1];
    $port_id = $interface[$if];
    if ($ip & $port_id) {
        if ($matches[3] === '' && $matches[4] === '') {
            // Convert IPv4 to fake MAC for 6to4 tunnels
            //ipNetToPhysicalPhysAddress[27][ipv6]["20:02:c0:58:63:01:00:00:00:00:00:00:00:00:00:00"] 0:0:c0:58
            $matches[3] = 'ff';
Example #14
0
         foreach ($cbgp_oids as $cbgp_oid) {
             $c_oid = $use_cisco_v2 ? str_replace('cbgpPeer', 'cbgpPeer2', $cbgp_oid) : $cbgp_oid;
             echo "{$c_oid} ";
             $c_prefixes = snmpwalk_cache_oid($device, $c_oid, $c_prefixes, 'CISCO-BGP4-MIB', mib_dirs('cisco'));
         }
     }
     #print_vars($bgp_peers);
 }
 $sql = 'SELECT *, `bgpPeers`.bgpPeer_id as bgpPeer_id ';
 $sql .= 'FROM `bgpPeers` ';
 $sql .= 'LEFT JOIN `bgpPeers-state` ON `bgpPeers`.bgpPeer_id = `bgpPeers-state`.bgpPeer_id ';
 $sql .= 'WHERE `device_id` = ?';
 foreach (dbFetchRows($sql, array($device['device_id'])) as $peer) {
     // Poll BGP Peer
     $peer_ip = $peer['bgpPeerRemoteAddr'];
     $remote_ip = strstr($peer_ip, ':') ? Net_IPv6::compress($peer_ip) : $peer_ip;
     // Compact IPv6. Used only for log.
     echo "Checking BGP peer: " . $peer_ip . " ";
     if (!strstr($peer_ip, ':') && !$use_cisco_v2) {
         // Common IPv4 BGP4 MIB
         foreach ($bgp_oids as $bgp_oid) {
             ${$bgp_oid} = $bgp_peers[$peer_ip][$bgp_oid];
         }
     } elseif ($use_cisco_v2) {
         // Cisco BGP4 V2 MIB
         $c_index = strstr($peer_ip, ':') ? 'ipv6.' . ip2hex($peer_ip, ':') : 'ipv4.' . $peer_ip;
         foreach ($bgp_oids as $bgp_oid) {
             $c_oid = str_replace(array('bgpPeer', 'Identifier'), array('cbgpPeer2', 'RemoteIdentifier'), $bgp_oid);
             if ($bgp_oid == 'bgpPeerLocalAddr') {
                 $cisco_peers[$c_index][$c_oid] = hex2ip($cisco_peers[$c_index][$c_oid]);
             }
Example #15
0
}
$sql .= " ORDER BY {$sort}";
if (isset($current)) {
    $limit_low = $current * $rowCount - $rowCount;
    $limit_high = $rowCount;
}
if ($rowCount != -1) {
    $sql .= " LIMIT {$limit_low},{$limit_high}";
}
$sql = "SELECT *,`I`.`ifDescr` AS `interface` {$sql}";
foreach (dbFetchRows($sql, $param) as $interface) {
    $speed = humanspeed($interface['ifSpeed']);
    $type = humanmedia($interface['ifType']);
    if ($_POST['search_type'] == 'ipv6') {
        list($prefix, $length) = explode("/", $interface['ipv6_network']);
        $address = Net_IPv6::compress($interface['ipv6_address']) . '/' . $length;
    } elseif ($_POST['search_type'] == 'mac') {
        $address = formatMac($interface['ifPhysAddress']);
    } else {
        list($prefix, $length) = explode("/", $interface['ipv4_network']);
        $address = $interface['ipv4_address'] . '/' . $length;
    }
    if ($interface['in_errors'] > 0 || $interface['out_errors'] > 0) {
        $error_img = generate_port_link($interface, "<img src='images/16/chart_curve_error.png' alt='Interface Errors' border=0>", errors);
    } else {
        $error_img = "";
    }
    if (port_permitted($interface['port_id'])) {
        $interface = ifLabel($interface, $interface);
        $response[] = array('hostname' => generate_device_link($interface), 'interface' => generate_port_link($interface) . ' ' . $error_img, 'address' => $address, 'description' => $interface['ifAlias']);
    }
if (!isset($config['mib_dir'])) {
    $config['mib_dir'] = $config['install_dir'] . '/mibs';
} else {
    $config['mib_dir'] = rtrim($config['mib_dir'], ' /');
}
// Old variable backwards compatibility
if (isset($config['rancid_configs']) && !is_array($config['rancid_configs'])) {
    $config['rancid_configs'] = array($config['rancid_configs']);
}
if (isset($config['auth_ldap_group']) && !is_array($config['auth_ldap_group'])) {
    $config['auth_ldap_group'] = array($config['auth_ldap_group']);
}
// Database currently stores v6 networks non-compressed, check for any compressed subnet and expand them
foreach ($config['ignore_common_subnet'] as $index => $content) {
    if (strstr($content, ':') !== FALSE) {
        $config['ignore_common_subnet'][$index] = Net_IPv6::uncompress($content);
    }
}
// Disable nonexistant features in CE, do not try to turn on, it will not give effect
if (OBSERVIUM_EDITION == 'community') {
    $config['enable_billing'] = 0;
    $config['poller-wrapper']['alerter'] = FALSE;
}
// If we're on SSL, let's properly detect it
// DOCME needs phpdoc block
// TESTME needs unit testing
// MOVEME to includes/common.inc.php
function is_ssl()
{
    if (isset($_SERVER['HTTPS'])) {
        if ('on' == strtolower($_SERVER['HTTPS'])) {
Example #17
0
function discover_process_ipv6(&$valid, $ifIndex, $ipv6_address, $ipv6_prefixlen, $ipv6_origin, $context_name = '')
{
    global $device;
    $ipv6_network = Net_IPv6::getNetmask("{$ipv6_address}/{$ipv6_prefixlen}") . '/' . $ipv6_prefixlen;
    $ipv6_compressed = Net_IPv6::compress($ipv6_address);
    if (Net_IPv6::getAddressType($ipv6_address) == NET_IPV6_LOCAL_LINK) {
        // ignore link-locals (coming from IPV6-MIB)
        return;
    }
    if (dbFetchCell('SELECT COUNT(*) FROM `ports` WHERE device_id = ? AND `ifIndex` = ?', array($device['device_id'], $ifIndex)) != '0' && $ipv6_prefixlen > '0' && $ipv6_prefixlen < '129' && $ipv6_compressed != '::1') {
        $port_id = dbFetchCell('SELECT port_id FROM `ports` WHERE device_id = ? AND ifIndex = ?', array($device['device_id'], $ifIndex));
        if (dbFetchCell('SELECT COUNT(*) FROM `ipv6_networks` WHERE `ipv6_network` = ?', array($ipv6_network)) < '1') {
            dbInsert(array('ipv6_network' => $ipv6_network, 'context_name' => $context_name), 'ipv6_networks');
            echo 'N';
        } else {
            //Update Context
            dbUpdate(array('context_name' => $device['context_name']), 'ipv6_network', '`ipv6_network` = ?', array($ipv6_network));
            echo 'n';
        }
        $ipv6_network_id = dbFetchCell('SELECT `ipv6_network_id` FROM `ipv6_networks` WHERE `ipv6_network` = ? AND `context_name` = ?', array($ipv6_network, $context_name));
        if (dbFetchCell('SELECT COUNT(*) FROM `ipv6_addresses` WHERE `ipv6_address` = ? AND `ipv6_prefixlen` = ? AND `port_id` = ?', array($ipv6_address, $ipv6_prefixlen, $port_id)) == '0') {
            dbInsert(array('ipv6_address' => $ipv6_address, 'ipv6_compressed' => $ipv6_compressed, 'ipv6_prefixlen' => $ipv6_prefixlen, 'ipv6_origin' => $ipv6_origin, 'ipv6_network_id' => $ipv6_network_id, 'port_id' => $port_id, 'context_name' => $context_name), 'ipv6_addresses');
            echo '+';
        } else {
            //Update Context
            dbUpdate(array('context_name' => $device['context_name']), 'ipv6_address', '`ipv6_address` = ? AND `ipv6_prefixlen` = ? AND `port_id` = ?', array($ipv6_address, $ipv6_prefixlen, $port_id));
            echo '.';
        }
        $full_address = "{$ipv6_address}/{$ipv6_prefixlen}";
        $valid_address = $full_address . '-' . $port_id;
        $valid['ipv6'][$valid_address] = 1;
    }
    //end if
}
Example #18
0
        list($net, $mask) = explode('/', trim($range));
        if (Net_IPv4::validateIP($net)) {
            // IPv4
            $mask = $mask != NULL ? $mask : '32';
            $range = $net . '/' . $mask;
            if ($mask >= 0 && $mask <= 32 && Net_IPv4::ipInNetwork($_SERVER['REMOTE_ADDR'], $range)) {
                $auth = TRUE;
                // hardcode authenticated for matched subnet
                print_debug("认证的CIDR匹配IPv4 {$range}.");
                break;
            }
        } elseif (Net_IPv6::checkIPv6($net)) {
            // IPv6
            $mask = $mask != NULL ? $mask : '128';
            $range = $net . '/' . $mask;
            if ($mask >= 0 && $mask <= 128 && Net_IPv6::isInNetmask($_SERVER['REMOTE_ADDR'], $range)) {
                $auth = TRUE;
                // hardcode authenticated for matched subnet
                print_debug("认证的CIDR匹配IPv6 {$range}");
                break;
            }
        }
    }
}
if (!$auth) {
    // Normal auth
    include $config['html_dir'] . "/includes/authenticate.inc.php";
}
// Push $_GET into $vars to be compatible with web interface naming
$vars = get_vars('GET');
include $config['html_dir'] . "/includes/graphs/graph.inc.php";
Example #19
0
 if ($_POST['network_subnet'] && !is_numeric($_POST['network_subnet'])) {
     $input_errors[] = gettext("A valid destination network bit count must be specified.");
 }
 if ($_POST['gateway'] && is_ipaddr($_POST['network'])) {
     if (!isset($a_gateways[$_POST['gateway']])) {
         $input_errors[] = gettext("A valid gateway must be specified.");
     }
     if (!validate_address_family($_POST['network'], lookup_gateway_ip_by_name($_POST['gateway']))) {
         $input_errors[] = gettext("The gateway '{$a_gateways[$_POST['gateway']]['gateway']}' is a different Address Family as network '{$_POST['network']}'.");
     }
 }
 /* check for overlaps */
 $current_targets = get_staticroutes(true);
 $new_targets = array();
 if (is_ipaddrv6($_POST['network'])) {
     $osn = Net_IPv6::compress(gen_subnetv6($_POST['network'], $_POST['network_subnet'])) . "/" . $_POST['network_subnet'];
     $new_targets[] = $osn;
 }
 if (is_ipaddr($_POST['network'])) {
     if ($_POST['network_subnet'] > 32) {
         $input_errors[] = gettext("A IPv4 subnet can not be over 32 bits.");
     } else {
         $osn = gen_subnet($_POST['network'], $_POST['network_subnet']) . "/" . $_POST['network_subnet'];
         $new_targets[] = $osn;
     }
 } elseif (is_alias($_POST['network'])) {
     $osn = $_POST['network'];
     foreach (filter_expand_alias_array($_POST['network']) as $tgt) {
         if (is_ipaddr($tgt)) {
             $tgt .= "/32";
         }
Example #20
0
         }
         $peer_data = trim(`{$peer_cmd}`);
         list($bgpPeerState, $bgpPeerAdminStatus, $bgpPeerInUpdates, $bgpPeerOutUpdates, $bgpPeerInTotalMessages, $bgpPeerOutTotalMessages, $bgpPeerFsmEstablishedTime, $bgpPeerInUpdateElapsedTime, $bgpLocalAddr) = explode("\n", $peer_data);
         if ($debug) {
             echo "State = {$bgpPeerState} - AdminStatus: {$bgpPeerAdminStatus}\n";
         }
         $bgpLocalAddr = str_replace('"', '', str_replace(' ', '', $bgpLocalAddr));
         if ($bgpLocalAddr == "00000000000000000000000000000000") {
             $bgpLocalAddr = '';
             # Unknown?
         } else {
             $bgpLocalAddr = strtolower($bgpLocalAddr);
             for ($i = 0; $i < 32; $i += 4) {
                 $bgpLocalAddr6[] = substr($bgpLocalAddr, $i, 4);
             }
             $bgpLocalAddr = Net_IPv6::compress(implode(':', $bgpLocalAddr6));
             unset($bgpLocalAddr6);
         }
     }
 }
 if ($bgpPeerFsmEstablishedTime) {
     if ($bgpPeerFsmEstablishedTime < $peer['bgpPeerFsmEstablishedTime'] || $bgpPeerState != $peer['bgpPeerState']) {
         if ($device['sysContact']) {
             $email = $device['sysContact'];
         } else {
             $email = $config['email_default'];
         }
         if ($peer['bgpPeerState'] == $bgpPeerState) {
             mail($email, "BGP Session flapped: " . $peer['bgpPeerIdentifier'] . ' (AS' . $peer['bgpPeerRemoteAs'] . ' - ' . $peer['astext'] . ')', "BGP Session flapped " . formatUptime($bgpPeerFsmEstablishedTime) . " ago.\n\nHostname : " . $device['hostname'] . "\nPeer IP  : " . $peer['bgpPeerIdentifier'] . "\nRemote AS: " . $peer['bgpPeerRemoteAs'] . ' (' . $peer['astext'] . ')', $config['email_headers']);
             eventlog('BGP Session Flap: ' . $peer['bgpPeerIdentifier'] . ' (AS' . $peer['bgpPeerRemoteAs'] . ')', $device['device_id']);
         } else {
Example #21
0
 /**
 * Converts an IPv6 address from Hex into Binary representation.
 *
 * @param String $ip the IP to convert (a:b:c:d:e:f:g:h),
 *                   compressed IPs are allowed
 *
 * @return String the binary representation
 * @access private
 @ @since 1.1.0
 */
 protected static function _ip2Bin($ip)
 {
     $binstr = '';
     $ip = Net_IPv6::removeNetmaskSpec($ip);
     $ip = Net_IPv6::Uncompress($ip);
     $parts = explode(':', $ip);
     foreach ($parts as $v) {
         $str = base_convert($v, 16, 2);
         $binstr .= str_pad($str, 16, '0', STR_PAD_LEFT);
     }
     return $binstr;
 }
Example #22
0
             d_echo($peer_data_tmp);
         }
         $bgpPeerState = $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerState'];
         $bgpPeerAdminStatus = $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerStatus'];
         $bgpPeerInUpdates = $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerInUpdates'];
         $bgpPeerOutUpdates = $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerOutUpdates'];
         $bgpPeerInTotalMessages = $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerInTotalMessages'];
         $bgpPeerOutTotalMessages = $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerOutTotalMessages'];
         $bgpPeerFsmEstablishedTime = $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerFsmEstablishedTime'];
         $bgpPeerInUpdateElapsedTime = $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerInUpdatesElapsedTime'];
         if ($peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerRemoteAddrType'] == 'ipv4') {
             $bgpLocalAddr = long2ip(hexdec($peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerLocalAddr']));
         } elseif ($peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerRemoteAddrType'] == 'ipv6') {
             $ip6 = trim(str_replace(' ', '', $peer_data_tmp[$junos[$peer_ip]['hash']]['jnxBgpM2PeerLocalAddr']), '"');
             $ip6 = substr($ip6, 0, 4) . ':' . substr($ip6, 4, 4) . ':' . substr($ip6, 8, 4) . ':' . substr($ip6, 12, 4) . ':' . substr($ip6, 16, 4) . ':' . substr($ip6, 20, 4) . ':' . substr($ip6, 24, 4) . ':' . substr($ip6, 28, 4);
             $bgpLocalAddr = Net_IPv6::compress($ip6);
         }
         d_echo("State = {$bgpPeerState} - AdminStatus: {$bgpPeerAdminStatus}\n");
         if ($bgpLocalAddr == '00000000000000000000000000000000') {
             $bgpLocalAddr = '';
             // Unknown?
         }
     }
     //end if
 }
 //end if
 if ($bgpPeerFsmEstablishedTime) {
     if (!(is_array($config['alerts']['bgp']['whitelist']) && !in_array($peer['bgpPeerRemoteAs'], $config['alerts']['bgp']['whitelist'])) && ($bgpPeerFsmEstablishedTime < $peer['bgpPeerFsmEstablishedTime'] || $bgpPeerState != $peer['bgpPeerState'])) {
         if ($peer['bgpPeerState'] == $bgpPeerState) {
             log_event('BGP Session Flap: ' . $peer['bgpPeerIdentifier'] . ' (AS' . $peer['bgpPeerRemoteAs'] . ')', $device, 'bgpPeer', $bgpPeer_id);
         } elseif ($bgpPeerState == 'established') {
Example #23
0
/**
 * Humanize BGP Peer
 *
 * Returns a the $peer array with processed information:
 * row_class, table_tab_colour, state_class, admin_class
 *
 * @param array $peer
 * @return array $peer
 *
 */
function humanize_bgp(&$peer)
{
    // Peer is disabled, set all things grey.
    if ($peer['bgpPeerAdminStatus'] == "stop") {
        $peer['table_tab_colour'] = "#aaaaaa";
        $peer['html_row_class'] = "warning";
        $peer['state_class'] = "muted";
        $peer['admin_class'] = "muted";
        $peer['alert'] = 0;
        $peer['disabled'] = 1;
    } elseif ($peer['bgpPeerAdminStatus'] == "start" || $peer['bgpPeerAdminStatus'] == "running") {
        // Peer is enabled, set state green and check other things
        $peer['admin_class'] = "text-success";
        if ($peer['bgpPeerState'] == "established") {
            $peer['state_class'] = "text-success";
            $peer['table_tab_colour'] = "#194B7F";
            $peer['html_row_class'] = "";
        } else {
            $peer['state_class'] = "text-error";
            $peer['table_tab_colour'] = "#cc0000";
            $peer['html_row_class'] = "error";
        }
    }
    if ($peer['bgpPeerRemoteAs'] == $peer['bgpLocalAs']) {
        $peer['peer_type'] = "<span style='color: #00f;'>iBGP</span>";
    } elseif ($peer['bgpPeerRemoteAS'] >= '64512' && $peer['bgpPeerRemoteAS'] <= '65535') {
        $peer['peer_type'] = "<span style='color: #f00;'>Priv eBGP</span>";
    } else {
        $peer['peer_type'] = "<span style='color: #0a0;'>eBGP</span>";
    }
    $peer['human_localip'] = strstr($peer['bgpPeerLocalAddr'], ':') ? Net_IPv6::compress($peer['bgpPeerLocalAddr']) : $peer['bgpPeerLocalAddr'];
    $peer['human_remoteip'] = strstr($peer['bgpPeerRemoteAddr'], ':') ? Net_IPv6::compress($peer['bgpPeerRemoteAddr']) : $peer['bgpPeerRemoteAddr'];
}
Example #24
0
         <dd><strong>' . highlight_search(htmlentities($name)) . '</h5>
              <small>' . $result['hostname'] . '<br />
              ' . htmlentities($result['location'], 0, 'UTF-8') . ' | Accesspoint</small></strong></dd>
         </dl>';
     }
     echo "</a></li>";
 }
 /// SEARCH IP ADDRESSES
 list($addr, $mask) = explode('/', $queryString);
 $address_type = "ipv4";
 if (is_numeric(stripos($queryString, ':abcdef'))) {
     $address_type = 'ipv6';
 }
 switch ($address_type) {
     case 'ipv6':
         $ip_valid = Net_IPv6::checkIPv6($addr);
         break;
     case 'ipv4':
         $ip_valid = Net_IPv4::validateIP($addr);
         break;
 }
 #    if ($ip_valid)
 #    {
 #      // If address valid -> seek occurrence in network
 #      if (!$mask) { $mask = ($address_type === 'ipv4') ? '32' : '128'; }#
 #     } else {
 // If address not valid -> seek LIKE
 $where .= ' AND A.`ipv4_address` LIKE ?';
 $param[] = '%' . $addr . '%';
 #    }
 // FIXME no v6 yet.
Example #25
0
         <td style="width: 350px;">';
echo "        <span class='entity-title'>\n              " . generate_port_link($port) . " " . $port['tags'] . "\n           </span><br /><span class=small>" . htmlentities($port['ifAlias']) . "</span>";
if ($port['ifAlias']) {
    echo "<br />";
}
unset($break);
if ($port_details) {
    if (!isset($ports_has_ext['ipv4_addresses']) || in_array($port['port_id'], $ports_has_ext['ipv4_addresses'])) {
        foreach (dbFetchRows("SELECT * FROM `ipv4_addresses` WHERE `port_id` = ?", array($port['port_id'])) as $ip) {
            echo $break . "<a class=small href=\"javascript:popUp('/netcmd.php?cmd=whois&amp;query=" . $ip['ipv4_address'] . "')\">" . $ip['ipv4_address'] . "/" . $ip['ipv4_prefixlen'] . "</a>";
            $break = "<br />";
        }
    }
    if (!isset($ports_has_ext['ipv6_addresses']) || in_array($port['port_id'], $ports_has_ext['ipv6_addresses'])) {
        foreach (dbFetchRows("SELECT * FROM `ipv6_addresses` WHERE `port_id` = ?", array($port['port_id'])) as $ip6) {
            echo $break . "<a class=small href=\"javascript:popUp('/netcmd.php?cmd=whois&amp;query=" . $ip6['ipv6_address'] . "')\">" . Net_IPv6::compress($ip6['ipv6_address']) . "/" . $ip6['ipv6_prefixlen'] . "</a>";
            $break = "<br />";
        }
    }
}
//echo("</span>");
echo "</td><td style='width: 147px;'>";
if ($port_details) {
    $port['graph_type'] = "port_bits";
    echo generate_port_link($port, "<img src='graph.php?type=port_bits&amp;id=" . $port['port_id'] . "&amp;from=" . $config['time']['day'] . "&amp;to=" . $config['time']['now'] . "&amp;width=100&amp;height=20&amp;legend=no' alt=\"\" />");
    $port['graph_type'] = "port_upkts";
    echo generate_port_link($port, "<img src='graph.php?type=port_upkts&amp;id=" . $port['port_id'] . "&amp;from=" . $config['time']['day'] . "&amp;to=" . $config['time']['now'] . "&amp;width=100&amp;height=20&amp;legend=no' alt=\"\" />");
    $port['graph_type'] = "port_errors";
    echo generate_port_link($port, "<img src='graph.php?type=port_errors&amp;id=" . $port['port_id'] . "&amp;from=" . $config['time']['day'] . "&amp;to=" . $config['time']['now'] . "&amp;width=100&amp;height=20&amp;legend=no' alt=\"\" />");
}
echo '</td><td style="width: 120px; white-space: nowrap;">';
Example #26
0
 //  local(7)           ->  ifIndex
 switch ($lldp['lldpRemPortIdSubtype']) {
     case 'interfaceAlias':
         $id = snmp_hexstring($id);
         $remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE (`ifAlias` = ? OR `ifDescr` = ?) AND `device_id` = ?", array($id, $if, $remote_device_id));
         break;
     case 'interfaceName':
         $remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE (`ifName` = ?  OR `ifDescr` = ?) AND `device_id` = ?", array($id, $if, $remote_device_id));
         break;
     case 'macAddress':
         $remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE `ifPhysAddress` = ? AND `device_id` = ?", array(strtolower(str_replace(array(' ', '-'), '', $id)), $remote_device_id));
         break;
     case 'networkAddress':
         $ip_version = get_ip_version($id);
         if ($ip_version) {
             $ip = $ip_version === 6 ? Net_IPv6::uncompress($id, TRUE) : $id;
             $remote_port_id = dbFetchCell("SELECT `port_id` FROM `ipv" . $ip_version . "_addresses` LEFT JOIN `ports` USING (`port_id`) WHERE `ipv" . $ip_version . "_address` = ? AND `device_id` = ?", array($ip, $remote_device_id));
         }
         break;
     case 'local':
         // local not always ifIndex or FIXME (see: http://jira.observium.org/browse/OBSERVIUM-1716)
         if (!ctype_digit($id)) {
             // Not sure what should be if $id ifName and it just numeric
             $remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE (`ifName`= ? OR `ifDescr` = ?) AND `device_id` = ?", array($id, $if, $remote_device_id));
         }
     case 'ifIndex':
         // These cases are handled by the ifDescr/ifIndex combination fallback below
     // These cases are handled by the ifDescr/ifIndex combination fallback below
     default:
         break;
 }
Example #27
0
 } else {
     unset($peername);
 }
 // display overlib graphs
 $graph_type = 'bgp_updates';
 $local_daily_url = 'graph.php?id=' . $peer['bgpPeer_id'] . '&amp;type=' . $graph_type . '&amp;from=' . $config['time']['day'] . '&amp;to=' . $config['time']['now'] . '&amp;width=500&amp;height=150&&afi=ipv4&safi=unicast';
 if (filter_var($peer['bgpLocalAddr'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
     $peer_ip = Net_IPv6::compress($peer['bgpLocalAddr']);
 } else {
     $peer_ip = $peer['bgpLocalAddr'];
 }
 $localaddresslink = "<span class=list-large><a href='device/device=" . $peer['device_id'] . "/tab=routing/proto=bgp/' onmouseover=\"return overlib('<img src=\\'{$local_daily_url}\\'>', LEFT" . $config['overlib_defaults'] . ');" onmouseout="return nd();">' . $peer_ip . '</a></span>';
 $graph_type = 'bgp_updates';
 $peer_daily_url = 'graph.php?id=' . $peer['bgpPeer_id'] . '&amp;type=' . $graph_type . '&amp;from=' . $config['time']['day'] . '&amp;to=' . $config['time']['now'] . '&amp;width=500&amp;height=150';
 if (filter_var($peer['bgpPeerIdentifier'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
     $peer_ident = Net_IPv6::compress($peer['bgpPeerIdentifier']);
 } else {
     $peer_ident = $peer['bgpPeerIdentifier'];
 }
 $peeraddresslink = "<span class=list-large><a href='device/device=" . $peer['device_id'] . "/tab=routing/proto=bgp/' onmouseover=\"return overlib('<img src=\\'{$peer_daily_url}\\'>', LEFT" . $config['overlib_defaults'] . ');" onmouseout="return nd();">' . $peer_ident . '</a></span>';
 echo '<tr class="bgp"' . ($peer['alert'] ? ' bordercolor="#cc0000"' : '') . ($peer['disabled'] ? ' bordercolor="#cccccc"' : '') . '>';
 unset($sep);
 foreach (dbFetchRows('SELECT * FROM `bgpPeers_cbgp` WHERE `device_id` = ? AND bgpPeerIdentifier = ?', array($peer['device_id'], $peer['bgpPeerIdentifier'])) as $afisafi) {
     $afi = $afisafi['afi'];
     $safi = $afisafi['safi'];
     $this_afisafi = $afi . $safi;
     $peer['afi'] .= $sep . $afi . '.' . $safi;
     $sep = '<br />';
     $peer['afisafi'][$this_afisafi] = 1;
     // Build a list of valid AFI/SAFI for this peer
 }
/**
 * Display ARP/NDP table addresses.
 *
 * Display pages with ARP/NDP tables addresses from devices.
 *
 * @param array $vars
 * @return none
 *
 */
function print_arptable($vars)
{
    // With pagination? (display page numbers in header)
    $pagination = isset($vars['pagination']) && $vars['pagination'];
    $pageno = isset($vars['pageno']) && !empty($vars['pageno']) ? $vars['pageno'] : 1;
    $pagesize = isset($vars['pagesize']) && !empty($vars['pagesize']) ? $vars['pagesize'] : 10;
    $start = $pagesize * $pageno - $pagesize;
    $param = array();
    $where = ' WHERE 1 ';
    foreach ($vars as $var => $value) {
        if ($value != '') {
            switch ($var) {
                case 'device':
                case 'device_id':
                    $where .= ' AND I.`device_id` = ?';
                    $param[] = $value;
                    break;
                case 'port':
                case 'port_id':
                    $where .= ' AND I.`port_id` = ?';
                    $param[] = $value;
                    break;
                case 'ip_version':
                    $where .= ' AND `ip_version` = ?';
                    $param[] = $value;
                    break;
                case 'address':
                    if (isset($vars['searchby']) && $vars['searchby'] == 'ip') {
                        $where .= ' AND `ip_address` LIKE ?';
                        $value = trim($value);
                        ///FIXME. Need another conversion ("2001:b08:b08" -> "2001:0b08:0b08") -- mike
                        if (Net_IPv6::checkIPv6($value)) {
                            $value = Net_IPv6::uncompress($value, true);
                        }
                        $param[] = '%' . $value . '%';
                    } else {
                        $where .= ' AND `mac_address` LIKE ?';
                        $param[] = '%' . str_replace(array(':', ' ', '-', '.', '0x'), '', mres($value)) . '%';
                    }
                    break;
            }
        }
    }
    // Show ARP tables only for permitted ports
    $query_permitted = generate_query_permitted(array('port'), array('port_table' => 'I'));
    $query = 'FROM `ip_mac` AS M ';
    $query .= 'LEFT JOIN `ports` AS I ON I.`port_id` = M.`port_id` ';
    $query .= $where . $query_permitted;
    $query_count = 'SELECT COUNT(`mac_id`) ' . $query;
    $query = 'SELECT * ' . $query;
    $query .= ' ORDER BY M.`mac_address`';
    $query .= " LIMIT {$start},{$pagesize}";
    // Query ARP/NDP table addresses
    $entries = dbFetchRows($query, $param);
    // Query ARP/NDP table address count
    if ($pagination) {
        $count = dbFetchCell($query_count, $param);
    }
    $list = array('device' => FALSE, 'port' => FALSE);
    if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') {
        $list['device'] = TRUE;
    }
    if (!isset($vars['port']) || empty($vars['port']) || $vars['page'] == 'search') {
        $list['port'] = TRUE;
    }
    $string = '<table class="table table-bordered table-striped table-hover table-condensed">' . PHP_EOL;
    if (!$short) {
        $string .= '  <thead>' . PHP_EOL;
        $string .= '    <tr>' . PHP_EOL;
        $string .= '      <th>MAC Address</th>' . PHP_EOL;
        $string .= '      <th>IP Address</th>' . PHP_EOL;
        if ($list['device']) {
            $string .= '      <th>Device</th>' . PHP_EOL;
        }
        if ($list['port']) {
            $string .= '      <th>Interface</th>' . PHP_EOL;
        }
        $string .= '      <th>Remote Device</th>' . PHP_EOL;
        $string .= '      <th>Remote Interface</th>' . PHP_EOL;
        $string .= '    </tr>' . PHP_EOL;
        $string .= '  </thead>' . PHP_EOL;
    }
    $string .= '  <tbody>' . PHP_EOL;
    foreach ($entries as $entry) {
        humanize_port($entry);
        $ip_version = $entry['ip_version'];
        $ip_address = $ip_version == 6 ? Net_IPv6::compress($entry['ip_address']) : $entry['ip_address'];
        $arp_host = dbFetchRow('SELECT * FROM `ipv' . $ip_version . '_addresses` AS A
                           LEFT JOIN `ports` AS I ON A.`port_id` = I.`port_id`
                           LEFT JOIN `devices` AS D ON D.`device_id` = I.`device_id`
                           WHERE A.`ipv' . $ip_version . '_address` = ?', array($ip_address));
        $arp_name = $arp_host ? generate_device_link($arp_host) : '';
        $arp_if = $arp_host ? generate_port_link($arp_host) : '';
        if ($arp_host['device_id'] == $entry['device_id']) {
            $arp_name = 'Self Device';
        }
        if ($arp_host['port_id'] == $entry['port_id']) {
            $arp_if = 'Self Port';
        }
        $string .= '  <tr>' . PHP_EOL;
        $string .= '    <td width="160">' . formatMac($entry['mac_address']) . '</td>' . PHP_EOL;
        $string .= '    <td width="140">' . $ip_address . '</td>' . PHP_EOL;
        if ($list['device']) {
            $dev = device_by_id_cache($entry['device_id']);
            $string .= '    <td class="entity" nowrap>' . generate_device_link($dev) . '</td>' . PHP_EOL;
        }
        if ($list['port']) {
            if ($entry['ifInErrors_delta'] > 0 || $entry['ifOutErrors_delta'] > 0) {
                $port_error = generate_port_link($entry, '<span class="label label-important">Errors</span>', 'port_errors');
            }
            $string .= '    <td class="entity">' . generate_port_link($entry, short_ifname($entry['label'])) . ' ' . $port_error . '</td>' . PHP_EOL;
        }
        $string .= '    <td class="entity" width="200">' . $arp_name . '</td>' . PHP_EOL;
        $string .= '    <td class="entity">' . $arp_if . '</td>' . PHP_EOL;
        $string .= '  </tr>' . PHP_EOL;
    }
    $string .= '  </tbody>' . PHP_EOL;
    $string .= '</table>';
    // Print pagination header
    if ($pagination) {
        $string = pagination($vars, $count) . $string . pagination($vars, $count);
    }
    // Print ARP/NDP table
    echo $string;
}
Example #29
0
 if ($device['os'] == 'junos') {
     // Missing: cbgpPeerAdminLimit cbgpPeerPrefixThreshold cbgpPeerPrefixClearThreshold cbgpPeerSuppressedPrefixes cbgpPeerWithdrawnPrefixes
     $safis['unicast'] = 1;
     $safis['multicast'] = 2;
     if (!isset($peerIndexes)) {
         $j_bgp = snmpwalk_cache_multi_oid($device, 'jnxBgpM2PeerTable', $jbgp, 'BGP4-V2-MIB-JUNIPER', $config['install_dir'] . '/mibs/junos');
         foreach ($j_bgp as $index => $entry) {
             switch ($entry['jnxBgpM2PeerRemoteAddrType']) {
                 case 'ipv4':
                     $ip = long2ip(hexdec($entry['jnxBgpM2PeerRemoteAddr']));
                     $j_peerIndexes[$ip] = $entry['jnxBgpM2PeerIndex'];
                     break;
                 case 'ipv6':
                     $ip6 = trim(str_replace(' ', '', $entry['jnxBgpM2PeerRemoteAddr']), '"');
                     $ip6 = substr($ip6, 0, 4) . ':' . substr($ip6, 4, 4) . ':' . substr($ip6, 8, 4) . ':' . substr($ip6, 12, 4) . ':' . substr($ip6, 16, 4) . ':' . substr($ip6, 20, 4) . ':' . substr($ip6, 24, 4) . ':' . substr($ip6, 28, 4);
                     $ip6 = Net_IPv6::compress($ip6);
                     $j_peerIndexes[$ip6] = $entry['jnxBgpM2PeerIndex'];
                     break;
                 default:
                     echo "PANIC: Don't know RemoteAddrType " . $entry['jnxBgpM2PeerRemoteAddrType'] . "!\n";
                     break;
             }
         }
     }
     //end if
     $j_prefixes = snmpwalk_cache_multi_oid($device, 'jnxBgpM2PrefixCountersTable', $jbgp, 'BGP4-V2-MIB-JUNIPER', $config['install_dir'] . '/mibs/junos');
     $cbgpPeerAcceptedPrefixes = $j_prefixes[$j_peerIndexes[$peer['bgpPeerIdentifier']] . ".{$afi}." . $safis[$safi]]['jnxBgpM2PrefixInPrefixesAccepted'];
     $cbgpPeerDeniedPrefixes = $j_prefixes[$j_peerIndexes[$peer['bgpPeerIdentifier']] . ".{$afi}." . $safis[$safi]]['jnxBgpM2PrefixInPrefixesRejected'];
     $cbgpPeerAdvertisedPrefixes = $j_prefixes[$j_peerIndexes[$peer['bgpPeerIdentifier']] . ".{$afi}." . $safis[$safi]]['jnxBgpM2PrefixOutPrefixes'];
     unset($j_prefixes);
     unset($j_bgp);
} else {
    $mac = "";
}
echo "<tr style=\"background-color: {$row_colour};\" valign=top onmouseover=\"this.style.backgroundColor='{$list_highlight}';\" onmouseout=\"this.style.backgroundColor='{$row_colour}';\" onclick=\"location.href='" . generate_port_url($port) . "'\" style='cursor: pointer;'>\n         <td valign=top width=350>";
echo "        <span class=list-large>\n              " . generate_port_link($port, $port['ifIndex'] . ". " . $port['label']) . " {$error_img} {$mac}\n           </span><br /><span class=interface-desc>" . $port['ifAlias'] . "</span>";
if ($port['ifAlias']) {
    echo "<br />";
}
unset($break);
if ($port_details) {
    foreach (dbFetchRows("SELECT * FROM `ipv4_addresses` WHERE `port_id` = ?", array($port['port_id'])) as $ip) {
        echo "{$break} <a class=interface-desc href=\"javascript:popUp('/netcmd.php?cmd=whois&amp;query={$ip['ipv4_address']}')\">" . $ip['ipv4_address'] . "/" . $ip['ipv4_prefixlen'] . "</a>";
        $break = "<br />";
    }
    foreach (dbFetchRows("SELECT * FROM `ipv6_addresses` WHERE `port_id` = ?", array($port['port_id'])) as $ip6) {
        echo "{$break} <a class=interface-desc href=\"javascript:popUp('/netcmd.php?cmd=whois&amp;query=" . $ip6['ipv6_address'] . "')\">" . Net_IPv6::compress($ip6['ipv6_address']) . "/" . $ip6['ipv6_prefixlen'] . "</a>";
        $break = "<br />";
    }
}
echo "</span>";
echo "</td><td width=100>";
if ($port_details) {
    $port['graph_type'] = "port_bits";
    echo generate_port_link($port, "<img src='graph.php?type=port_bits&amp;id=" . $port['port_id'] . "&amp;from=" . $config['time']['day'] . "&amp;to=" . $config['time']['now'] . "&amp;width=100&amp;height=20&amp;legend=no&amp;bg=" . str_replace("#", "", $row_colour) . "'>");
    $port['graph_type'] = "port_upkts";
    echo generate_port_link($port, "<img src='graph.php?type=port_upkts&amp;id=" . $port['port_id'] . "&amp;from=" . $config['time']['day'] . "&amp;to=" . $config['time']['now'] . "&amp;width=100&amp;height=20&amp;legend=no&amp;bg=" . str_replace("#", "", $row_colour) . "'>");
    $port['graph_type'] = "port_errors";
    echo generate_port_link($port, "<img src='graph.php?type=port_errors&amp;id=" . $port['port_id'] . "&amp;from=" . $config['time']['day'] . "&amp;to=" . $config['time']['now'] . "&amp;width=100&amp;height=20&amp;legend=no&amp;bg=" . str_replace("#", "", $row_colour) . "'>");
}
echo "</td><td width=120>";
if ($port['ifOperStatus'] == "up") {