function add_device($hostname, $snmp_version = array(), $snmp_port = 161, $snmp_transport = 'udp', $options = array(), $flags = OBS_DNS_ALL) { global $config; // If $options['break'] set as TRUE, break recursive function execute if (isset($options['break']) && $options['break']) { return FALSE; } $return = FALSE; // By default return FALSE // Reset snmp timeout and retries options for speedup device adding unset($config['snmp']['timeout'], $config['snmp']['retries']); $snmp_transport = strtolower($snmp_transport); $hostname = strtolower(trim($hostname)); // Try detect if hostname is IP switch (get_ip_version($hostname)) { case 6: $hostname = Net_IPv6::compress($hostname, TRUE); // Always use compressed IPv6 name // Always use compressed IPv6 name case 4: if ($config['require_hostname']) { print_error("Hostname should be a valid resolvable FQDN name. Or set config option \$config['require_hostname'] as FALSE."); return $return; } $ip = $hostname; break; default: if ($snmp_transport == 'udp6' || $snmp_transport == 'tcp6') { $flags = $flags ^ OBS_DNS_A; // exclude A } // Test DNS lookup. $ip = gethostbyname6($hostname, $flags); } // Test if host exists in database if (dbFetchCell("SELECT COUNT(*) FROM `devices` WHERE `hostname` = ?", array($hostname)) == '0') { if ($ip) { $ip_version = get_ip_version($ip); // Test reachability $options['ping_skip'] = isset($options['ping_skip']) && $options['ping_skip']; if ($options['ping_skip']) { $flags = $flags | OBS_PING_SKIP; } if (isPingable($hostname, $flags)) { // Test directory exists in /rrd/ if (!$config['rrd_override'] && file_exists($config['rrd_dir'] . '/' . $hostname)) { print_error("Directory <observium>/rrd/{$hostname} already exists."); return FALSE; } // Detect snmp transport if (stripos($snmp_transport, 'tcp') !== FALSE) { $snmp_transport = $ip_version == 4 ? 'tcp' : 'tcp6'; } else { $snmp_transport = $ip_version == 4 ? 'udp' : 'udp6'; } // Detect snmp port if (!is_numeric($snmp_port) || $snmp_port < 1 || $snmp_port > 65535) { $snmp_port = 161; } else { $snmp_port = (int) $snmp_port; } // Detect snmp version if (empty($snmp_version)) { // Here set default snmp version order $i = 1; $snmp_version_order = array(); foreach (array('v2c', 'v3', 'v1') as $tmp_version) { if ($config['snmp']['version'] == $tmp_version) { $snmp_version_order[0] = $tmp_version; } else { $snmp_version_order[$i] = $tmp_version; } $i++; } ksort($snmp_version_order); foreach ($snmp_version_order as $tmp_version) { $ret = add_device($hostname, $tmp_version, $snmp_port, $snmp_transport, $options); if ($ret === FALSE) { // Set $options['break'] for break recursive $options['break'] = TRUE; } else { if (is_numeric($ret) && $ret != 0) { return $ret; } } } } else { if ($snmp_version === "v3") { // Try each set of parameters from config foreach ($config['snmp']['v3'] as $snmp_v3) { $device = build_initial_device_array($hostname, NULL, $snmp_version, $snmp_port, $snmp_transport, $snmp_v3); print_message("Trying v3 parameters " . $device['snmp_authname'] . "/" . $device['snmp_authlevel'] . " ... "); if (isSNMPable($device)) { if (!check_device_duplicated($device)) { if (isset($options['test']) && $options['test']) { print_message('%WDevice "' . $hostname . '" has successfully been tested and available by ' . strtoupper($snmp_transport) . ' transport with SNMP ' . $snmp_version . ' credentials.%n', 'color'); $device_id = -1; } else { $device_id = createHost($hostname, NULL, $snmp_version, $snmp_port, $snmp_transport, $snmp_v3); if ($options['ping_skip']) { set_entity_attrib('device', $device_id, 'ping_skip', 1); // Force pingable check if (isPingable($hostname, $flags ^ OBS_PING_SKIP)) { print_warning("You passed option for skip device is pingable checks, but device available by ismp echo. Check device preferences."); } } } return $device_id; } } else { print_warning("No reply on credentials " . $device['snmp_authname'] . "/" . $device['snmp_authlevel'] . " using {$snmp_version}."); } } } else { if ($snmp_version === "v2c" || $snmp_version === "v1") { // Try each community from config foreach ($config['snmp']['community'] as $snmp_community) { $device = build_initial_device_array($hostname, $snmp_community, $snmp_version, $snmp_port, $snmp_transport); print_message("Trying {$snmp_version} community {$snmp_community} ..."); if (isSNMPable($device)) { if (!check_device_duplicated($device)) { if (isset($options['test']) && $options['test']) { print_message('%WDevice "' . $hostname . '" has successfully been tested and available by ' . strtoupper($snmp_transport) . ' transport with SNMP ' . $snmp_version . ' credentials.%n', 'color'); $device_id = -1; } else { $device_id = createHost($hostname, $snmp_community, $snmp_version, $snmp_port, $snmp_transport); if ($options['ping_skip']) { set_entity_attrib('device', $device_id, 'ping_skip', 1); // Force pingable check if (isPingable($hostname, $flags ^ OBS_PING_SKIP)) { print_warning("You passed option for skip device is pingable checks, but device available by ismp echo. Check device preferences."); } } } return $device_id; } } else { print_warning("No reply on community {$snmp_community} using {$snmp_version}."); $return = 0; // Return zero for continue trying next auth } } } else { print_error("Unsupported SNMP Version \"{$snmp_version}\"."); $return = 0; // Return zero for continue trying next auth } } } if (!$device_id) { // Failed SNMP print_error("Could not reach {$hostname} with given SNMP parameters using {$snmp_version}."); $return = 0; // Return zero for continue trying next auth } } else { // failed Reachability print_error("Could not ping {$hostname}."); } } else { // Failed DNS lookup print_error("Could not resolve {$hostname}."); } } else { // found in database print_error("Already got device {$hostname}."); } return $return; }
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; }
} else { unset($peername); } // display overlib graphs $graph_type = 'bgp_updates'; $local_daily_url = 'graph.php?id=' . $peer['bgpPeer_id'] . '&type=' . $graph_type . '&from=' . $config['time']['day'] . '&to=' . $config['time']['now'] . '&width=500&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'] . '&type=' . $graph_type . '&from=' . $config['time']['day'] . '&to=' . $config['time']['now'] . '&width=500&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 }
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"; }
/** * 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; }
/** * 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; }
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 }
if (!$mask) { $mask = "128"; } if (!Net_IPv6::isInNetmask($interface['ipv6_address'], $addy, $mask)) { $ignore = 1; } else { $ignore = 0; } } if (!$ignore) { if (is_integer($row / 2)) { $row_colour = $list_colour_a; } else { $row_colour = $list_colour_b; } $speed = humanspeed($interface['ifSpeed']); $type = humanmedia($interface['ifType']); list($prefix, $length) = explode("/", $interface['ipv6_network']); if ($interface['in_errors'] > 0 || $interface['out_errors'] > 0) { $error_img = generateiflink($interface, "<img src='images/16/chart_curve_error.png' alt='Interface Errors' border=0>", errors); } else { $error_img = ""; } if (interfacepermitted($interface['interface_id'])) { echo "<tr bgcolor={$row_colour}><td></td>\n <td class=list-bold>" . generatedevicelink($interface) . "</td>\n <td class=list-bold>" . generateiflink($interface, makeshortif(fixifname($interface['ifDescr']))) . " {$error_img}</td>\n <td>" . Net_IPv6::compress($interface['ipv6_address']) . "/" . $length . "</td>\n <td>" . $interface['ifAlias'] . "</td>\n </tr>\n"; $row++; } } unset($ignore); } echo "</table>";
/** * 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']; pagination($vars, 0, TRUE); // Get default pagesize/pageno $pageno = $vars['pageno']; $pagesize = $vars['pagesize']; $start = $pagesize * $pageno - $pagesize; $param = array(); $where = ' WHERE 1 '; foreach ($vars as $var => $value) { if ($value != '') { switch ($var) { case 'device': case 'device_id': $where .= generate_query_values($value, 'device_id'); break; case 'port': case 'port_id': $where .= generate_query_values($value, 'I.port_id'); break; case 'ip_version': $where .= generate_query_values($value, 'ip_version'); break; case 'address': if (isset($vars['searchby']) && $vars['searchby'] == 'ip') { $value = trim($value); if (strpos($value, ':') !== FALSE) { if (Net_IPv6::checkIPv6($value)) { $value = Net_IPv6::uncompress($value, TRUE); } else { // FIXME. Need another conversion ("2001:b08:b08" -> "2001:0b08:0b08") -- mike } } $where .= generate_query_values($value, 'ip_address', '%LIKE%'); } else { // MAC Addresses $value = str_replace(array(':', ' ', '-', '.', '0x'), '', $value); $where .= generate_query_values($value, 'mac_address', '%LIKE%'); } break; } } } if (isset($vars['sort'])) { switch ($vars['sort']) { case "port": $sort = " ORDER BY `I`.`port_label`"; break; case "ip_version": $sort = " ORDER BY `ip_version`"; break; case "ip": case "address": $sort = " ORDER BY `ip_address`"; break; case "mac": default: $sort = " ORDER BY `mac_address`"; } } // 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 .= $sort; $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 = generate_box_open(); $string .= '<table class="table table-striped table-hover table-condensed">' . PHP_EOL; $cols = array('mac' => 'MAC Address', 'ip' => 'IP Address', 'device' => 'Device', 'port' => 'Port', '!remote_device' => 'Remote Device', '!remote_port' => 'Remote Port'); if (!$list['device']) { unset($cols['device']); } if (!$list['port']) { unset($cols['port']); } if (!$short) { $string .= get_table_header($cols, $vars); // Currently sorting is not available } 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 style="width: 160px;" class="entity">' . generate_popup_link('mac', format_mac($entry['mac_address'])) . '</td>' . PHP_EOL; $string .= ' <td style="width: 140px;">' . generate_popup_link('ip', $ip_address) . '</td>' . PHP_EOL; if ($list['device']) { $dev = device_by_id_cache($entry['device_id']); $string .= ' <td class="entity" style="white-space: 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, $entry['port_label_short']) . ' ' . $port_error . '</td>' . PHP_EOL; } $string .= ' <td class="entity" style="width: 200px;">' . $arp_name . '</td>' . PHP_EOL; $string .= ' <td class="entity">' . $arp_if . '</td>' . PHP_EOL; $string .= ' </tr>' . PHP_EOL; } $string .= ' </tbody>' . PHP_EOL; $string .= '</table>'; $string .= generate_box_close(); // Print pagination header if ($pagination) { $string = pagination($vars, $count) . $string . pagination($vars, $count); } // Print ARP/NDP table echo $string; }
do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors); if ($_POST['prefixrange_from'] && !is_ipaddrv6($_POST['prefixrange_from'])) { $input_errors[] = gettext("A valid prefix range must be specified."); } if ($_POST['prefixrange_to'] && !is_ipaddrv6($_POST['prefixrange_to'])) { $input_errors[] = gettext("A valid prefix range must be specified."); } if ($_POST['prefixrange_from'] && $_POST['prefixrange_to'] && $_POST['prefixrange_length']) { $netmask = Net_IPv6::getNetmask($_POST['prefixrange_from'], $_POST['prefixrange_length']); $netmask = Net_IPv6::compress($netmask); if ($netmask != Net_IPv6::compress(strtolower($_POST['prefixrange_from']))) { $input_errors[] = sprintf(gettext("Prefix Delegation From address is not a valid IPv6 Netmask for %s"), $netmask . '/' . $_POST['prefixrange_length']); } $netmask = Net_IPv6::getNetmask($_POST['prefixrange_to'], $_POST['prefixrange_length']); $netmask = Net_IPv6::compress($netmask); if ($netmask != Net_IPv6::compress(strtolower($_POST['prefixrange_to']))) { $input_errors[] = sprintf(gettext("Prefix Delegation To address is not a valid IPv6 Netmask for %s"), $netmask . '/' . $_POST['prefixrange_length']); } } $range_from_to_ok = true; if ($_POST['range_from']) { if (!is_ipaddrv6($_POST['range_from'])) { $input_errors[] = gettext("A valid range must be specified."); $range_from_to_ok = false; } elseif ($config['interfaces'][$if]['ipaddrv6'] == 'track6' && !Net_IPv6::isInNetmask($_POST['range_from'], '::', $ifcfgsn)) { $input_errors[] = sprintf(gettext("The prefix (upper %s bits) must be zero. Use the form %s"), $ifcfgsn, $str_help_mask); $range_from_to_ok = false; } } if ($_POST['range_to']) { if (!is_ipaddrv6($_POST['range_to'])) {
/** * verify ip address /mask 10.10.10.10./24 - CIDR * * if subnet == 0 we dont check if IP is subnet -> needed for ipCalc */ function verifyCidr($cidr, $issubnet = 1) { /* split it to network and subnet */ $temp = explode("/", $cidr); $network = $temp[0]; $netmask = $temp[1]; //if one part is missing die if (empty($network) || empty($netmask)) { $errors[] = _("Invalid CIDR format!"); } /* Identify address type */ $type = IdentifyAddress($network); /* IPv4 verification */ if ($type == 'IPv4') { require_once 'PEAR/Net/IPv4.php'; $Net_IPv4 = new Net_IPv4(); if ($net = $Net_IPv4->parseAddress($cidr)) { //validate IP if (!$Net_IPv4->validateIP($net->ip)) { $errors[] = _("Invalid IP address!"); } elseif ($net->network != $net->ip && $issubnet == 1) { $errors[] = _("IP address cannot be subnet! (Consider using") . " " . $net->network . ")"; } elseif (!$Net_IPv4->validateNetmask($net->netmask)) { $errors[] = _('Invalid netmask') . ' ' . $net->netmask; } } else { $errors[] = _('Invalid CIDR format!'); } } else { require_once 'PEAR/Net/IPv6.php'; $Net_IPv6 = new Net_IPv6(); //validate IPv6 if (!$Net_IPv6->checkIPv6($cidr)) { $errors[] = _("Invalid IPv6 address!"); } else { //validate subnet $subnet = $Net_IPv6->getNetmask($cidr); $subnet = $Net_IPv6->compress($subnet); //get subnet part $subnetParse = explode("/", $cidr); $subnetMask = $subnetParse[1]; $subnetNet = $subnetParse[0]; if ($subnetNet != $subnet && $issubnet == 1) { $errors[] = _("IP address cannot be subnet! (Consider using") . " " . $subnet . "/" . $subnetMask . ")"; } } } /* return array of errors */ return $errors; }
function humanize_bgp(&$peer) { // Exit if already humanized if ($peer['humanized']) { return; } // Set colours and classes based on the status of the peer if ($peer['bgpPeerAdminStatus'] == 'stop' || $peer['bgpPeerAdminStatus'] == 'halted') { // Peer is disabled, set row to warning and text classes to muted. $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 is up, set colour to blue and disable row class $peer['state_class'] = "text-success"; $peer['table_tab_colour'] = "#194B7F"; $peer['html_row_class'] = ""; } else { // Peer is down, set colour to red and row class to error. $peer['state_class'] = "text-danger"; $peer['table_tab_colour'] = "#cc0000"; $peer['html_row_class'] = "error"; } } // Set text and colour if peer is same AS, private AS or external. 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>"; } // Format (compress) the local/remote IPs if they're IPv6 $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']; // Set humanized entry in the array so we can tell later $peer['humanized'] = TRUE; }
function discover_process_ipv6(&$valid, $ifIndex, $ipv6_address, $ipv6_prefixlen, $ipv6_origin) { global $device, $config; $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), 'ipv6_networks'); echo "N"; } // Below looks like a duplicate of the above FIXME if (dbFetchCell("SELECT COUNT(*) FROM `ipv6_networks` WHERE `ipv6_network` = ?", array($ipv6_network)) < '1') { dbInsert(array('ipv6_network' => $ipv6_network), 'ipv6_networks'); echo "N"; } $ipv6_network_id = dbFetchCell("SELECT `ipv6_network_id` FROM `ipv6_networks` WHERE `ipv6_network` = ?", array($ipv6_network)); 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), 'ipv6_addresses'); echo "+"; } else { echo "."; } $full_address = "{$ipv6_address}/{$ipv6_prefixlen}"; $valid_address = $full_address . "-" . $port_id; $valid['ipv6'][$valid_address] = 1; } }
/** * Display IPv4/IPv6 addresses. * * Display pages with IP addresses from device Interfaces. * * @param array $vars * @return none * */ function print_addresses($vars) { // With pagination? (display page numbers in header) $pagination = isset($vars['pagination']) && $vars['pagination']; pagination($vars, 0, TRUE); // Get default pagesize/pageno $pageno = $vars['pageno']; $pagesize = $vars['pagesize']; $start = $pagesize * $pageno - $pagesize; if (in_array($vars['search'], array('6', 'v6', 'ipv6')) || in_array($vars['view'], array('6', 'v6', 'ipv6'))) { $address_type = 'ipv6'; } else { $address_type = 'ipv4'; } $ip_array = array(); $param = array(); $where = ' WHERE 1 '; $param_netscaler = array(); $where_netscaler = " WHERE `vsvr_ip` != '0.0.0.0' AND `vsvr_ip` != '' "; foreach ($vars as $var => $value) { if ($value != '') { switch ($var) { case 'device': case 'device_id': $where .= generate_query_values($value, 'I.device_id'); $where_netscaler .= generate_query_values($value, 'N.device_id'); break; case 'interface': $where .= generate_query_values($value, 'I.ifDescr', 'LIKE%'); break; case 'network': list($net, $mask) = explode('/', $value); if (is_numeric(stripos($net, ':abcdef'))) { $address_type = 'ipv6'; } $where .= generate_query_values($value, 'N.ip_network', 'LIKE%'); break; case 'address': list($addr, $mask) = explode('/', $value); if (is_numeric(stripos($addr, ':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'; } $where_netscaler .= generate_query_values($addr, 'N.vsvr_ip'); } else { // If address not valid -> seek LIKE $where .= generate_query_values($addr, 'A.ip_address', '%LIKE%'); $where_netscaler .= generate_query_values($addr, 'N.vsvr_ip', '%LIKE%'); } break; } } } $query_device_permitted = generate_query_permitted(array('device'), array('device_table' => 'D')); $query_port_permitted = generate_query_permitted(array('port'), array('port_table' => 'I')); // Also search netscaler Vserver IPs $query_netscaler = 'FROM `netscaler_vservers` AS N '; $query_netscaler .= 'LEFT JOIN `devices` AS D ON N.`device_id` = D.`device_id` '; $query_netscaler .= $where_netscaler . $query_device_permitted; //$query_netscaler_count = 'SELECT COUNT(`vsvr_id`) ' . $query_netscaler; $query_netscaler = 'SELECT * ' . $query_netscaler; $query_netscaler .= ' ORDER BY N.`vsvr_ip`'; // Override by address type if ($address_type == 'ipv6') { $query_netscaler = str_replace(array('vsvr_ip', '0.0.0.0'), array('vsvr_ipv6', '0:0:0:0:0:0:0:0'), $query_netscaler); //$query_netscaler_count = str_replace(array('vsvr_ip', '0.0.0.0'), array('vsvr_ipv6', '0:0:0:0:0:0:0:0'), $query_netscaler_count); } $entries = dbFetchRows($query_netscaler, $param_netscaler); // Rewrite netscaler addresses foreach ($entries as $entry) { $ip_address = $address_type == 'ipv4' ? $entry['vsvr_ip'] : $entry['vsvr_' . $address_type]; $ip_network = $address_type == 'ipv4' ? $entry['vsvr_ip'] . '/32' : $entry['vsvr_' . $address_type] . '/128'; $ip_array[] = array('type' => 'netscaler_vsvr', 'device_id' => $entry['device_id'], 'hostname' => $entry['hostname'], 'vsvr_id' => $entry['vsvr_id'], 'vsvr_label' => $entry['vsvr_label'], 'ifAlias' => 'Netscaler: ' . $entry['vsvr_type'] . '/' . $entry['vsvr_entitytype'], $address_type . '_address' => $ip_address, $address_type . '_network' => $ip_network); } //print_message($query_netscaler_count); $query = 'FROM `ip_addresses` AS A '; $query .= 'LEFT JOIN `ports` AS I ON I.`port_id` = A.`port_id` '; $query .= 'LEFT JOIN `devices` AS D ON I.`device_id` = D.`device_id` '; $query .= 'LEFT JOIN `ip_networks` AS N ON N.`ip_network_id` = A.`ip_network_id` '; $query .= $where . $query_port_permitted; //$query_count = 'SELECT COUNT(`ip_address_id`) ' . $query; $query = 'SELECT * ' . $query; $query .= ' ORDER BY A.`ip_address`'; if ($ip_valid) { $pagination = FALSE; } // Override by address type $query = str_replace(array('ip_address', 'ip_network'), array($address_type . '_address', $address_type . '_network'), $query); //$query_count = str_replace(array('ip_address', 'ip_network'), array($address_type.'_address', $address_type.'_network'), $query_count); // Query addresses $entries = dbFetchRows($query, $param); $ip_array = array_merge($ip_array, $entries); $ip_array = array_sort($ip_array, $address_type . '_address'); // Query address count //if ($pagination) { $count = dbFetchCell($query_count, $param); } if ($pagination) { $count = count($ip_array); $ip_array = array_slice($ip_array, $start, $pagesize); } $list = array('device' => FALSE); if (!isset($vars['device']) || empty($vars['device']) || $vars['page'] == 'search') { $list['device'] = TRUE; } $string = generate_box_open($vars['header']); $string .= '<table class="' . OBS_CLASS_TABLE_STRIPED . '">' . PHP_EOL; if (!$short) { $string .= ' <thead>' . PHP_EOL; $string .= ' <tr>' . PHP_EOL; if ($list['device']) { $string .= ' <th>Device</th>' . PHP_EOL; } $string .= ' <th>Interface</th>' . PHP_EOL; $string .= ' <th>Address</th>' . PHP_EOL; $string .= ' <th>Description</th>' . PHP_EOL; $string .= ' </tr>' . PHP_EOL; $string .= ' </thead>' . PHP_EOL; } $string .= ' <tbody>' . PHP_EOL; foreach ($ip_array as $entry) { $address_show = TRUE; if ($ip_valid) { // If address not in specified network, don't show entry. if ($address_type === 'ipv4') { $address_show = Net_IPv4::ipInNetwork($entry[$address_type . '_address'], $addr . '/' . $mask); } else { $address_show = Net_IPv6::isInNetmask($entry[$address_type . '_address'], $addr, $mask); } } if ($address_show) { list($prefix, $length) = explode('/', $entry[$address_type . '_network']); if (port_permitted($entry['port_id']) || $entry['type'] == 'netscaler_vsvr') { if ($entry['type'] == 'netscaler_vsvr') { $entity_link = generate_entity_link($entry['type'], $entry); } else { humanize_port($entry); if ($entry['ifInErrors_delta'] > 0 || $entry['ifOutErrors_delta'] > 0) { $port_error = generate_port_link($entry, '<span class="label label-important">Errors</span>', 'port_errors'); } $entity_link = generate_port_link($entry, $entry['port_label_short']) . ' ' . $port_error; } $device_link = generate_device_link($entry); $string .= ' <tr>' . PHP_EOL; if ($list['device']) { $string .= ' <td class="entity" style="white-space: nowrap">' . $device_link . '</td>' . PHP_EOL; } $string .= ' <td class="entity">' . $entity_link . '</td>' . PHP_EOL; if ($address_type === 'ipv6') { $entry[$address_type . '_address'] = Net_IPv6::compress($entry[$address_type . '_address']); } $string .= ' <td>' . generate_popup_link('ip', $entry[$address_type . '_address'] . '/' . $length) . '</td>' . PHP_EOL; $string .= ' <td>' . $entry['ifAlias'] . '</td>' . PHP_EOL; $string .= ' </tr>' . PHP_EOL; } } } $string .= ' </tbody>' . PHP_EOL; $string .= '</table>'; $string .= generate_box_close(); // Print pagination header if ($pagination) { $string = pagination($vars, $count) . $string . pagination($vars, $count); } // Print addresses echo $string; }
} $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 {
echo ' </tr>'; echo ' </thead>'; $i = "0"; foreach (dbFetchRows("SELECT * FROM `netscaler_vservers` WHERE `device_id` = ? ORDER BY `vsvr_label`", array($device['device_id'])) as $vsvr) { $vsvr['num_services'] = dbFetchCell("SELECT COUNT(*) FROM `netscaler_services_vservers` AS SV, `netscaler_services` AS S WHERE SV.device_id = ? AND SV.vsvr_name = ? AND S.svc_name = SV.svc_name", array($device['device_id'], $vsvr['vsvr_name'])); if ($vsvr['vsvr_state'] == "up") { $vsvr_class = "green"; } else { $vsvr_class = "red"; } if ($vsvr['vsvr_port'] != "0") { if ($vsvr['vsvr_ip'] != "0.0.0.0") { $vsvr['addrs'][] = $vsvr['vsvr_ip'] . ":" . $vsvr['vsvr_port']; } if ($vsvr['vsvr_ipv6'] != "0:0:0:0:0:0:0:0") { $vsvr['addrs'][] = "[" . Net_IPv6::compress($vsvr['vsvr_ipv6']) . "]:" . $vsvr['vsvr_port']; } } echo "<tr>"; echo '<td class="entity-name"><a href="' . generate_url($vars, array('vsvr' => $vsvr['vsvr_id'], 'view' => NULL, 'graph' => NULL)) . '">' . $vsvr['vsvr_label'] . '</a></td>'; echo "<td>" . implode($vsvr['addrs'], "<br />") . "</td>"; echo '<td>' . $vsvr['vsvr_type'] . '<br />' . $vsvr['vsvr_entitytype'] . '</td>'; echo "<td><span class='" . $vsvr_class . "'>" . $vsvr['vsvr_state'] . "</span><br />" . $vsvr['num_services'] . " service(s)</td>"; echo "<td><img src='images/16/arrow_left.png' align=absmiddle> " . format_si($vsvr['vsvr_bps_in'] * 8) . "bps <br />"; echo "<img src='images/16/arrow_out.png' align=absmiddle> " . format_si($vsvr['vsvr_bps_out'] * 8) . "bps</a></td>"; echo "</tr>"; if ($vars['view'] == "services") { $svcs = dbFetchRows("SELECT * FROM `netscaler_services_vservers` AS SV, `netscaler_services` AS S WHERE SV.device_id = ? AND SV.vsvr_name = ? AND S.svc_name = SV.svc_name", array($device['device_id'], $vsvr['vsvr_name'])); echo '<tr><td colspan="5">'; if (count($svcs)) { echo '<table class="table table-striped table-condensed table-bordered">';
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') {
foreach (dbFetchRows('SELECT DISTINCT `' . $column . '`, `astext` FROM `bgpPeers` WHERE 1 ' . $cache['where']['devices_permitted'] . ' ORDER BY `' . $column . '`') as $entry) { if (empty($entry[$column])) { continue; } $form_items[$param][$entry[$column]]['name'] = 'AS' . $entry[$column]; $form_items[$param][$entry[$column]]['subtext'] = $entry['astext']; } $form_params = array('local_ip' => 'bgpPeerLocalAddr', 'peer_ip' => 'bgpPeerRemoteAddr'); foreach ($form_params as $param => $column) { foreach (dbFetchColumn('SELECT DISTINCT `' . $column . '` FROM `bgpPeers` WHERE 1 ' . $cache['where']['devices_permitted'] . ' ORDER BY `' . $column . '`') as $entry) { if (empty($entry)) { continue; } if (strpos($entry, ':') !== FALSE) { $form_items[$param][$entry]['group'] = 'IPv6'; $form_items[$param][$entry]['name'] = Net_IPv6::compress($entry); } else { $form_items[$param][$entry]['group'] = 'IPv4'; $form_items[$param][$entry]['name'] = escape_html($entry); } } } $form = array('type' => 'rows', 'space' => '5px', 'submit_by_key' => TRUE, 'url' => generate_url($vars)); $form['row'][0]['device'] = array('type' => 'multiselect', 'name' => 'Local Device', 'width' => '100%', 'value' => $vars['device'], 'values' => $form_items['devices']); $form['row'][0]['local_ip'] = array('type' => 'multiselect', 'name' => 'Local address', 'width' => '100%', 'value' => $vars['local_ip'], 'values' => $form_items['local_ip']); $form['row'][0]['peer_ip'] = array('type' => 'multiselect', 'name' => 'Peer address', 'width' => '100%', 'value' => $vars['peer_ip'], 'values' => $form_items['peer_ip']); $form['row'][0]['peer_as'] = array('type' => 'multiselect', 'name' => 'Remote AS', 'width' => '100%', 'value' => $vars['peer_as'], 'values' => $form_items['peer_as']); $form['row'][0]['type'] = array('type' => 'select', 'name' => 'Type', 'width' => '100%', 'value' => $vars['type'], 'values' => array('' => 'All', 'internal' => 'iBGP', 'external' => 'eBGP')); // search button $form['row'][0]['search'] = array('type' => 'submit', 'right' => TRUE); $panel_form = array('type' => 'rows', 'title' => 'Search BGP', 'space' => '10px', 'submit_by_key' => TRUE, 'url' => generate_url($vars));
} 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&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&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&id=" . $port['port_id'] . "&from=" . $config['time']['day'] . "&to=" . $config['time']['now'] . "&width=100&height=20&legend=no&bg=" . str_replace("#", "", $row_colour) . "'>"); $port['graph_type'] = "port_upkts"; echo generate_port_link($port, "<img src='graph.php?type=port_upkts&id=" . $port['port_id'] . "&from=" . $config['time']['day'] . "&to=" . $config['time']['now'] . "&width=100&height=20&legend=no&bg=" . str_replace("#", "", $row_colour) . "'>"); $port['graph_type'] = "port_errors"; echo generate_port_link($port, "<img src='graph.php?type=port_errors&id=" . $port['port_id'] . "&from=" . $config['time']['day'] . "&to=" . $config['time']['now'] . "&width=100&height=20&legend=no&bg=" . str_replace("#", "", $row_colour) . "'>"); } echo "</td><td width=120>"; if ($port['ifOperStatus'] == "up") {
function ip_range_to_subnet_array_temp($ip1, $ip2) { if (is_ipaddrv4($ip1) && is_ipaddrv4($ip2)) { $proto = 'ipv4'; // for clarity $bits = 32; $ip1bin = decbin(ip2long32($ip1)); $ip2bin = decbin(ip2long32($ip2)); } elseif (is_ipaddrv6($ip1) && is_ipaddrv6($ip2)) { $proto = 'ipv6'; $bits = 128; $ip1bin = Net_IPv6::_ip2Bin($ip1); $ip2bin = Net_IPv6::_ip2Bin($ip2); } else { return array(); } // it's *crucial* that binary strings are guaranteed the expected length; do this for certainty even though for IPv6 it's redundant $ip1bin = str_pad($ip1bin, $bits, '0', STR_PAD_LEFT); $ip2bin = str_pad($ip2bin, $bits, '0', STR_PAD_LEFT); if ($ip1bin === $ip2bin) { return array($ip1 . '/' . $bits); } if (strcmp($ip1bin, $ip2bin) > 0) { list($ip1bin, $ip2bin) = array($ip2bin, $ip1bin); } // swap contents of ip1 <= ip2 $rangesubnets = array(); $netsize = 0; do { // at loop start, $ip1 is guaranteed strictly less than $ip2 (important for edge case trapping and preventing accidental binary wrapround) // which means the assignments $ip1 += 1 and $ip2 -= 1 will always be "binary-wrapround-safe" // step #1 if start ip (as shifted) ends in any '1's, then it must have a single cidr to itself (any cidr would include the '0' below it) if (substr($ip1bin, -1, 1) == '1') { // the start ip must be in a separate one-IP cidr range $new_subnet_ip = substr($ip1bin, $netsize, $bits - $netsize) . str_repeat('0', $netsize); $rangesubnets[$new_subnet_ip] = $bits - $netsize; $n = strrpos($ip1bin, '0'); //can't be all 1's $ip1bin = ($n == 0 ? '' : substr($ip1bin, 0, $n)) . '1' . str_repeat('0', $bits - $n - 1); // BINARY VERSION OF $ip1 += 1 } // step #2, if end ip (as shifted) ends in any zeros then that must have a cidr to itself (as cidr cant span the 1->0 gap) if (substr($ip2bin, -1, 1) == '0') { // the end ip must be in a separate one-IP cidr range $new_subnet_ip = substr($ip2bin, $netsize, $bits - $netsize) . str_repeat('0', $netsize); $rangesubnets[$new_subnet_ip] = $bits - $netsize; $n = strrpos($ip2bin, '1'); //can't be all 0's $ip2bin = ($n == 0 ? '' : substr($ip2bin, 0, $n)) . '0' . str_repeat('1', $bits - $n - 1); // BINARY VERSION OF $ip2 -= 1 // already checked for the edge case where end = start+1 and start ends in 0x1, above, so it's safe } // this is the only edge case arising from increment/decrement. // it happens if the range at start of loop is exactly 2 adjacent ips, that spanned the 1->0 gap. (we will have enumerated both by now) if (strcmp($ip2bin, $ip1bin) < 0) { continue; } // step #3 the start and end ip MUST now end in '0's and '1's respectively // so we have a non-trivial range AND the last N bits are no longer important for CIDR purposes. $shift = $bits - max(strrpos($ip1bin, '0'), strrpos($ip2bin, '1')); // num of low bits which are '0' in ip1 and '1' in ip2 $ip1bin = str_repeat('0', $shift) . substr($ip1bin, 0, $bits - $shift); $ip2bin = str_repeat('0', $shift) . substr($ip2bin, 0, $bits - $shift); $netsize += $shift; if ($ip1bin === $ip2bin) { // we're done. $new_subnet_ip = substr($ip1bin, $netsize, $bits - $netsize) . str_repeat('0', $netsize); $rangesubnets[$new_subnet_ip] = $bits - $netsize; continue; } // at this point there's still a remaining range, and either startip ends with '1', or endip ends with '0'. So repeat cycle. } while (strcmp($ip1bin, $ip2bin) < 0); // subnets are ordered by bit size. Re sort by IP ("naturally") and convert back to IPv4/IPv6 ksort($rangesubnets, SORT_STRING); $out = array(); foreach ($rangesubnets as $ip => $netmask) { if ($proto == 'ipv4') { $i = str_split($ip, 8); $out[] = implode('.', array(bindec($i[0]), bindec($i[1]), bindec($i[2]), bindec($i[3]))) . '/' . $netmask; } else { $out[] = Net_IPv6::compress(Net_IPv6::_bin2Ip($ip)) . '/' . $netmask; } } return $out; }
/** * 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>'; }
} $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']); }
/** * Checks, if an IPv6 adress can be compressed * * @param String $ip a valid IPv6 adress * * @return Boolean true, if adress can be compressed * * @access public * @since 1.2.0b * @static * @author Manuel Schmitt */ public static function isCompressible($ip) { return (bool) ($ip != Net_IPv6::compress($address)); }
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]); }
/** * 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']; }
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) ";
<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&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&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&id=" . $port['port_id'] . "&from=" . $config['time']['day'] . "&to=" . $config['time']['now'] . "&width=100&height=20&legend=no' alt=\"\" />"); $port['graph_type'] = "port_upkts"; echo generate_port_link($port, "<img src='graph.php?type=port_upkts&id=" . $port['port_id'] . "&from=" . $config['time']['day'] . "&to=" . $config['time']['now'] . "&width=100&height=20&legend=no' alt=\"\" />"); $port['graph_type'] = "port_errors"; echo generate_port_link($port, "<img src='graph.php?type=port_errors&id=" . $port['port_id'] . "&from=" . $config['time']['day'] . "&to=" . $config['time']['now'] . "&width=100&height=20&legend=no' alt=\"\" />"); } echo '</td><td style="width: 120px; white-space: nowrap;">';
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; }
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);
$valid[$ip_version] = array(); $check_networks = array(); if (count($ip_data)) { foreach ($ip_data as $ifIndex => $addresses) { if (!isset($cache['port_index'][$device_id][$ifIndex])) { continue; } // continue if ifIndex not found $port_id = $cache['port_index'][$device_id][$ifIndex]; foreach ($addresses as $ipv6_address => $entry) { $update_array = array(); $ipv6_prefixlen = $entry['ipAddressPrefix']; $ipv6_origin = $entry['ipAddressOrigin']; $full_address = $ipv6_address . '/' . $ipv6_prefixlen; $ipv6_network = Net_IPv6::getNetmask($full_address) . '/' . $ipv6_prefixlen; $ipv6_compressed = Net_IPv6::compress($ipv6_address); $full_compressed = $ipv6_compressed . '/' . $ipv6_prefixlen; // First check networks $ipv6_network_id = dbFetchCell('SELECT `ipv6_network_id` FROM `ipv6_networks` WHERE `ipv6_network` = ?', array($ipv6_network)); if (empty($ipv6_network_id)) { $ipv6_network_id = dbInsert(array('ipv6_network' => $ipv6_network), 'ipv6_networks'); echo 'N'; } // Check IPs in DB if (isset($old_table[$ifIndex][$ipv6_address])) { foreach (array('ipv6_prefixlen', 'ipv6_origin', 'ipv6_network_id', 'port_id') as $param) { if ($old_table[$ifIndex][$ipv6_address][$param] != ${$param}) { $update_array[$param] = ${$param}; } } if (count($update_array)) {