Пример #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];
}
Пример #2
0
         // Other way by using Pear::Net_MAC, see here: http://pear.php.net/manual/en/package.networking.net-mac.importvendors.php
         $url = 'http://api.macvendors.com/' . urlencode($vars['entity_id']);
         $response = get_http_request($url);
         if ($response) {
             echo 'MAC vendor: ' . $response;
         } else {
             echo 'Not Found';
         }
     } else {
         echo 'Not correct MAC address';
     }
     exit;
     break;
 case "ip":
     list($ip) = explode('/', $vars['entity_id']);
     $ip_version = get_ip_version($ip);
     if ($ip_version) {
         if (isset($_SESSION['cache']['response_' . $vars['entity_type'] . '_' . $ip])) {
             echo $_SESSION['cache']['response_' . $vars['entity_type'] . '_' . $ip];
             //echo '<h2>CACHED!</h2>';
             exit;
         }
         $response = '';
         $reverse_dns = gethostbyaddr6($ip);
         if ($reverse_dns) {
             $response .= '<h4>' . $reverse_dns . '</h4><hr />' . PHP_EOL;
         }
         // WHOIS
         if (is_executable($config['whois']) && !isset($config['http_proxy'])) {
             // Use direct whois cmd query (preferred)
             // NOTE, for now not tested and not supported for KRNIC, ie: 202.30.50.0, 2001:02B8:00A2::
Пример #3
0
//$pws = snmpwalk_cache_oid($device, 'pwRemoteIfMtu',    $pws, 'JUNIPER-VPN-MIB');
$pws = snmpwalk_cache_threepart_oid($device, 'jnxVpnPwRemoteSiteId', $pws, 'JUNIPER-VPN-MIB', NULL, $flags);
// pwMplsPeerLdpID
if (OBS_DEBUG > 1) {
    echo 'PWS_WALK: ' . count($pws) . "\n";
    print_vars($pws);
}
foreach ($pws as $pw_type => $entry) {
    foreach ($entry as $pw_name => $entry2) {
        foreach ($entry2 as $pw_ifIndex => $pw) {
            //if (strlen($pw['jnxVpnPwRowStatus']) && $pw['jnxVpnPwRowStatus'] != 'active') { continue; } // Skip inactive (active, notinService, notReady, createAndGo, createAndWait, destroy)
            // Get full index
            $pw_index = snmp_translate('jnxVpnPwRowStatus.' . $pw_type . '."' . $pw_name . '".' . $pw_ifIndex, 'JUNIPER-VPN-MIB');
            $pw_index = str_replace('.1.3.6.1.4.1.2636.3.26.1.4.1.4.', '', $pw_index);
            $peer_addr = hex2ip($pw['jnxVpnRemotePeIdAddress']);
            $peer_addr_version = get_ip_version($peer_addr);
            $peer_addr_type = $pw['jnxVpnRemotePeIdAddrType'];
            if ($peer_addr_version) {
                $peer_addr_type = 'ipv' . $peer_addr_version;
                // Override address type, because snmp sometime return incorrect
                $peer_rdns = gethostbyaddr6($peer_addr);
                // PTR name
                if ($peer_addr_type == 'ipv6') {
                    $peer_addr = Net_IPv6::uncompress($peer_addr, TRUE);
                }
                // FIXME. Retarded way
                $remote_device = dbFetchCell('SELECT `device_id` FROM `' . $peer_addr_type . '_addresses`
                                        LEFT JOIN `ports` USING(`port_id`)
                                        WHERE `' . $peer_addr_type . '_address` = ? LIMIT 1;', array($peer_addr));
            } else {
                $peer_rdns = '';
Пример #4
0
function discover_new_device($hostname, $source = 'xdp', $protocol = NULL, $device = NULL, $port = 161)
{
    global $config;
    $source = strtolower($source);
    if ($config['autodiscovery'][$source]) {
        if (!$protocol) {
            $protocol = strtoupper($source);
        }
        print_message("Discovering new host {$hostname} through {$protocol}");
        // 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;
        } else {
            $use_ip = FALSE;
            if (!empty($config['mydomain']) && isDomainResolves($hostname . '.' . $config['mydomain'])) {
                $hostname .= '.' . $config['mydomain'];
            }
            $ip = gethostbyname6($hostname);
            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 (match_network($ip, $config['autodiscovery']['ip_nets'])) {
            print_debug("Host {$hostname} ({$ip}) founded inside configured nets, try to adding:");
            if (isPingable($ip)) {
                // Check if device duplicated by IP
                $ip = $ip_version == 4 ? $hostname : Net_IPv6::uncompress($hostname, 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}");
                    return FALSE;
                }
                // Detect snmp transport
                $transport = $ip_version == 4 ? 'udp' : 'udp6';
                $new_device = detect_device_snmpauth($ip, $port, $transport);
                if ($new_device) {
                    if ($use_ip) {
                        // Detect FQDN hostname
                        // by sysName
                        $snmphost = snmp_get($new_device, "sysName.0", "-Oqv", "SNMPv2-MIB", mib_dirs());
                        if ($snmphost) {
                            $snmp_ip = gethostbyname6($snmphost);
                        }
                        if ($snmp_ip == $ip) {
                            $hostname = $snmphost;
                        } else {
                            // by PTR
                            $ptr = gethostbyaddr6($ip);
                            if ($ptr) {
                                $ptr_ip = gethostbyname6($ptr);
                            }
                            if ($ptr && $ptr_ip == $ip) {
                                $hostname = $ptr;
                            } else {
                                print_debug("Device IP {$ip} not have FQDN name");
                                return FALSE;
                            }
                        }
                        print_debug("Device IP {$ip} founded FQDN name: {$hostname}");
                    }
                    $new_device['hostname'] = $hostname;
                    if (!check_device_duplicated($new_device)) {
                        $v3 = array();
                        if ($new_device['snmpver'] === 'v3') {
                            $v3['authlevel'] = $new_device['authlevel'];
                            $v3['authname'] = $new_device['authname'];
                            $v3['authpass'] = $new_device['authpass'];
                            $v3['authalgo'] = $new_device['authalgo'];
                            $v3['cryptopass'] = $new_device['cryptopass'];
                            $v3['cryptoalgo'] = $new_device['cryptoalgo'];
                        }
                        $remote_device_id = createHost($new_device['hostname'], $new_device['community'], $new_device['snmpver'], $new_device['port'], $new_device['transport'], $v3);
                        if ($remote_device_id) {
                            $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['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 . ' fails.');
    } else {
        print_debug('Autodiscovery for protocol ' . $protocol . ' disabled.');
    }
    return FALSE;
}
/**
 * Params:
 *
 * pagination, pageno, pagesize
 * device, port
 */
function get_pseudowires_array($vars)
{
    $array = array();
    // With pagination? (display page numbers in header)
    $array['pagination'] = isset($vars['pagination']) && $vars['pagination'];
    pagination($vars, 0, TRUE);
    // Get default pagesize/pageno
    $array['pageno'] = $vars['pageno'];
    $array['pagesize'] = $vars['pagesize'];
    $start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
    $pagesize = $array['pagesize'];
    // Begin query generate
    $param = array();
    $where = ' WHERE 1 ';
    foreach ($vars as $var => $value) {
        if ($value != '') {
            switch ($var) {
                case 'device':
                case 'device_a':
                    $where .= generate_query_values($value, 'device_id');
                    break;
                case 'port':
                case 'port_a':
                    $where .= generate_query_values($value, 'port_id');
                    break;
                    //case 'type':
                    //  $where .= generate_query_values($value, 'type');
                    //  break;
                    //case 'message':
                    //  $where .= generate_query_values($value, 'message', '%LIKE%');
                    //  break;
            }
        }
    }
    // Show pseudowires only for permitted devices and ports
    $query_permitted = generate_query_permitted(array('device', 'port'));
    $query = 'FROM `pseudowires` ';
    $query .= $where . $query_permitted;
    $query_count = 'SELECT COUNT(*) ' . $query;
    //$query_updated = 'SELECT MAX(`timestamp`) '.$query;
    $query = 'SELECT * ' . $query;
    //$query .= ' ORDER BY `event_id` DESC ';
    $query .= " LIMIT {$start},{$pagesize}";
    // Query pseudowires
    foreach (dbFetchRows($query, $param) as $entry) {
        if ($entry['peer_addr']) {
            $peer_addr = $entry['peer_addr'];
        } else {
            if ($entry['pwMplsPeerLdpID']) {
                $peer_addr = preg_replace('/:\\d+$/', '', $pw['pwMplsPeerLdpID']);
            }
        }
        $peer_addr_type = get_ip_version($peer_addr);
        if ($peer_addr_type) {
            if ($peer_addr_type == 6) {
                $peer_addr = Net_IPv6::uncompress($peer_addr, TRUE);
            }
            $peer_addr_type = 'ipv' . $peer_addr_type;
            $entry['peer_addr'] = $peer_addr;
            $entry['peer_addr_type'] = $peer_addr_type;
        } else {
            continue;
            // Peer address unknown
        }
        if (!is_array($cache_pseudowires['ips'][$peer_addr])) {
            $cache_pseudowires['ips'][$peer_addr]['port_id'] = dbFetchCell('SELECT `port_id` FROM `' . $peer_addr_type . '_addresses` WHERE `' . $peer_addr_type . '_address` = ? ' . generate_query_values($GLOBALS['cache']['ports']['pseudowires'], 'port_id') . ' LIMIT 1;', array($peer_addr));
            if (!is_numeric($cache_pseudowires['ips'][$peer_addr]['port_id'])) {
                $cache_pseudowires['ips'][$peer_addr]['port_id'] = dbFetchCell('SELECT `port_id` FROM `' . $peer_addr_type . '_addresses` WHERE `' . $peer_addr_type . '_address` = ? ' . $GLOBALS['cache']['where']['ports_permitted'] . ' LIMIT 1;', array($peer_addr));
                if (is_numeric($cache_pseudowires['ips'][$peer_addr]['port_id'])) {
                    // If we found port on remote device, than both devices in DB and will try to fix real port
                    $peer_port_tmp = get_port_by_id_cache($cache_pseudowires['ips'][$peer_addr]['port_id']);
                    $peer_port_fix = dbFetchCell('SELECT `port_id` FROM `pseudowires` WHERE `device_id` = ? AND `pwID` = ? LIMIT 1;', array($peer_port_tmp['device_id'], $entry['pwID']));
                    if (is_numeric($peer_port_fix)) {
                        $cache_pseudowires['ips'][$peer_addr]['port_id'] = $peer_port_fix;
                    }
                }
            }
            //$cache_pseudowires['ips'][$peer_addr]['host'] = $entry['reverse_dns'];
        }
        $entry['peer_port_id'] = $cache_pseudowires['ips'][$peer_addr]['port_id'];
        //$entry['peer_port']      = get_port_by_id_cache($entry['peer_port_id']);
        //$entry['peer_device_id'] = $entry['peer_port']['device_id'];
        //$entry['peer_device']    = device_by_id_cache($entry['peer_device_id']);
        $array['entries'][] = $entry;
    }
    // Query pseudowires count
    if ($array['pagination']) {
        $array['count'] = dbFetchCell($query_count, $param);
        $array['pagination_html'] = pagination($vars, $array['count']);
    } else {
        $array['count'] = count($array['entries']);
    }
    // Query for last timestamp
    //$array['updated'] = dbFetchCell($query_updated, $param);
    return $array;
}
function discover_new_device($hostname, $source = 'xdp', $protocol = NULL, $device = NULL, $snmp_port = 161)
{
    global $config;
    $source = strtolower($source);
    if ($config['autodiscovery'][$source]) {
        if (!$protocol) {
            $protocol = strtoupper($source);
        }
        print_message("发现新主机 {$hostname} 通过 {$protocol}");
        // 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;
            if (!empty($config['mydomain']) && isDomainResolves($hostname . '.' . $config['mydomain'])) {
                $hostname .= '.' . $config['mydomain'];
            }
            $ip = gethostbyname6($hostname);
            if ($ip) {
                $ip_version = get_ip_version($ip);
                print_debug("主机 {$hostname} 解析为 {$ip}");
            } else {
                // No DNS records
                print_debug("主机 {$hostname} 无法解析, 自动发现失败.");
                return FALSE;
            }
        }
        if (match_network($ip, $config['autodiscovery']['ip_nets'])) {
            print_debug("主机 {$hostname} ({$ip}) 内部网络创建配置, 尝试增加:");
            if (isPingable($ip)) {
                // 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('已经有设备 ' . $db['hostname'] . " 包含 {$ip}");
                    return FALSE;
                }
                // Detect snmp transport
                $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", mib_dirs());
                        if ($snmphost) {
                            $snmp_ip = gethostbyname6($snmphost);
                        }
                        if ($snmp_ip == $ip) {
                            $hostname = $snmphost;
                        } else {
                            // by PTR
                            $ptr = gethostbyaddr6($ip);
                            if ($ptr) {
                                $ptr_ip = gethostbyname6($ptr);
                            }
                            if ($ptr && $ptr_ip == $ip) {
                                $hostname = $ptr;
                            } else {
                                print_debug("设备 IP {$ip} 没有 FQDN 名称");
                                return FALSE;
                            }
                        }
                        print_debug("设备 IP {$ip} 发现 FQDN 名称: {$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) {
                            $remote_device = device_by_id_cache($remote_device_id, 1);
                            if ($port) {
                                humanize_port($port);
                                log_event("设备自动发现通过 {$protocol} 在 " . $device['hostname'] . " (port " . $port['label'] . ")", $remote_device_id, 'port', $port['port_id']);
                            } else {
                                log_event("设备自动发现通过 {$protocol} 在 " . $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}) 不允许内部 \$config['autodiscovery']['ip_nets'] 位于 config.php");
        }
        print_debug('自动发现主机 ' . $hostname . ' 错误.');
    } else {
        print_debug('自动发现协议 ' . $protocol . ' 禁用.');
    }
    return FALSE;
}
Пример #7
0
         $vendor_bgp = snmpwalk_cache_oid($device, $vendor_PeerRemoteAddrType, $vendor_bgp, $vendor_mib, NULL, OBS_SNMP_ALL_NUMERIC_INDEX);
     }
     if ($vendor_PeerIndex && !isset($vendor_use_index[$vendor_PeerIndex])) {
         $vendor_bgp = snmpwalk_cache_oid($device, $vendor_PeerIndex, $vendor_bgp, $vendor_mib, NULL, OBS_SNMP_ALL_NUMERIC_INDEX);
     }
     $vendor_counters = snmpwalk_cache_oid($device, $vendor_PrefixCountersSafi, array(), $vendor_mib, NULL, OBS_SNMP_ALL_NUMERIC_INDEX);
 }
 echo PHP_EOL;
 foreach ($peerlist as $peer) {
     $astext = get_astext($peer['as']);
     $reverse_dns = gethostbyaddr6($peer['ip']);
     if ($reverse_dns == $peer['ip']) {
         unset($reverse_dns);
     }
     // Search remote device if possible
     $peer_addr_type = get_ip_version($peer['ip']);
     if ($peer_addr_type) {
         if (in_array($peer['ip'], array('0.0.0.0', '127.0.0.1', '0000:0000:0000:0000:0000:0000:0000:0001', '0000:0000:0000:0000:0000:0000:0000:0000'))) {
             $ip_array = FALSE;
         } else {
             $peer_addr_type = 'ipv' . $peer_addr_type;
             $query_ip = 'SELECT `device_id`, `port_id`, `ifOperStatus`, `ifAdminStatus` FROM `' . $peer_addr_type . '_addresses`
                LEFT JOIN `ports` USING(`port_id`)
                WHERE `' . $peer_addr_type . '_address` = ? AND `device_id` IN
                (SELECT `device_id` FROM `devices` WHERE `bgpLocalAs` > 0 AND `disabled` = 0)';
             $ip_array = dbFetchRows($query_ip, array($peer['ip']));
         }
         if (count($ip_array) > 1) {
             // multiple devices found, heh I not sure
             $peer_device_id = array('NULL');
             foreach ($ip_array as $entry) {
Пример #8
0
 //  interfaceName(5),  ->  ifName
 //  agentCircuitId(6), ->  agent-local identifier of the circuit (defined in RFC 3046) (FIXME, not know)
 //  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:
Пример #9
0
function get_cache($host, $value)
{
    global $dev_cache;
    if (empty($host)) {
        return;
    }
    // Check cache expiration
    $now = time();
    $expired = TRUE;
    if (isset($dev_cache[$host]['lastchecked'])) {
        if ($now - $dev_cache[$host]['lastchecked'] < 600) {
            $expired = FALSE;
        }
        // will expire after 10 min
    }
    if ($expired) {
        $dev_cache[$host]['lastchecked'] = $now;
    }
    if (!isset($dev_cache[$host][$value]) || $expired) {
        switch ($value) {
            case 'device_id':
                // Try by map in config
                if (isset($GLOBALS['config']['syslog']['host_map'][$host])) {
                    $new_host = $GLOBALS['config']['syslog']['host_map'][$host];
                    if (is_numeric($new_host)) {
                        // Check if device id exist
                        $dev_cache[$host]['device_id'] = dbFetchCell('SELECT `device_id` FROM `devices` WHERE `device_id` = ?', array($new_host));
                    } else {
                        $dev_cache[$host]['device_id'] = dbFetchCell('SELECT `device_id` FROM `devices` WHERE `hostname` = ? OR `sysName` = ?', array($new_host, $new_host));
                    }
                    // If syslog host map correct, return device id or try onward
                    if ($dev_cache[$host]['device_id']) {
                        return $dev_cache[$host]['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 && preg_match('/::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)/', $ip, $matches)) {
                            // IPv4 mapped to IPv6, like ::ffff:192.0.2.128
                            // See: http://jira.observium.org/browse/OBSERVIUM-1274
                            $ip = $matches[1];
                            $ip_version = 4;
                        } else {
                            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':
                if ($device_id = get_cache($host, 'device_id')) {
                    $dev_cache[$host][$value] = dbFetchCell('SELECT `' . $value . '` FROM `devices` WHERE `device_id` = ?', array($device_id));
                } else {
                    return NULL;
                }
                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];
}
 $pws = snmpwalk_cache_oid($device, "cpwVcRemoteIfString", $pws, $mib, mib_dirs('cisco'));
 // For MPLS pseudowires
 $pws = snmpwalk_cache_oid($device, "cpwVcMplsLocalLdpID", $pws, "CISCO-IETF-PW-MPLS-MIB", mib_dirs('cisco'));
 $pws = snmpwalk_cache_oid($device, "cpwVcMplsPeerLdpID", $pws, "CISCO-IETF-PW-MPLS-MIB", mib_dirs('cisco'));
 //echo("PWS_WALK: ".count($pws)."\n"); var_dump($pws);
 foreach ($pws as $pw_id => $pw) {
     $peer_addr_type = $pw['cpwVcPeerAddrType'];
     if ($peer_addr_type == "ipv4" || $peer_addr_type == "ipv6") {
         $peer_addr = hex2ip($pw['cpwVcPeerAddr']);
     }
     if (!get_ip_version($peer_addr) && $pw['cpwVcMplsPeerLdpID']) {
         // Sometime return wrong peer addr (not hex string):
         // cpwVcPeerAddr.8 = "\\<h&"
         $peer_addr = preg_replace('/:\\d+$/', '', $pw['cpwVcMplsPeerLdpID']);
     }
     if (get_ip_version($peer_addr)) {
         $peer_rdns = gethostbyaddr6($peer_addr);
         // PTR name
         if ($peer_addr_type == 'ipv6') {
             $peer_addr = Net_IPv6::uncompress($peer_addr, TRUE);
         }
         // FIXME. Retarded way
         $cpw_remote_device = dbFetchCell('SELECT `device_id` FROM `' . $peer_addr_type . '_addresses` AS A, `ports` AS I WHERE A.`' . $peer_addr_type . '_address` = ? AND A.`port_id` = I.`port_id` LIMIT 1;', array($peer_addr));
     } else {
         $peer_addr = '';
         // Unset peer address
         print_debug("Not found correct peer address. See snmpwalk for 'cpwVcPeerAddr' and 'cpwVcMplsPeerLdpID'.");
     }
     if (empty($cpw_remote_device)) {
         $cpw_remote_device = array('NULL');
     }
Пример #11
0
function get_pseudowire_table($vars)
{
    $sql = generate_pseudowire_query($vars);
    $entries = array();
    foreach (dbFetchRows($sql) as $entry) {
        if (!isset($GLOBALS['cache']['devices']['id'][$entry['device_id']])) {
            continue;
        }
        // Device hostname
        $entry['hostname'] = $GLOBALS['cache']['devices']['id'][$entry['device_id']]['hostname'];
        // Remote Peer
        $peer_addr = $entry['peer_addr'];
        $peer_addr_type = get_ip_version($peer_addr);
        if ($peer_addr_type && $entry['peer_device_id']) {
            if ($peer_addr_type == 6) {
                $peer_addr = Net_IPv6::uncompress($peer_addr, TRUE);
            }
            $peer_addr_type = 'ipv' . $peer_addr_type;
            //$entry['peer_addr']      = $peer_addr;
            //$entry['peer_addr_type'] = $peer_addr_type;
            if (!is_array($cache_pseudowires['ips'][$peer_addr])) {
                $cache_pseudowires['ips'][$peer_addr]['port_id'] = dbFetchCell('SELECT `port_id` FROM `' . $peer_addr_type . '_addresses` WHERE `' . $peer_addr_type . '_address` = ? ' . generate_query_values($GLOBALS['cache']['ports']['pseudowires'], 'port_id') . ' LIMIT 1;', array($peer_addr));
                if (!is_numeric($cache_pseudowires['ips'][$peer_addr]['port_id'])) {
                    // Separate entry for find correct port
                    $cache_pseudowires['ips'][$peer_addr]['port_id_fix'] = dbFetchCell('SELECT `port_id` FROM `' . $peer_addr_type . '_addresses` WHERE `' . $peer_addr_type . '_address` = ? ' . $GLOBALS['cache']['where']['ports_permitted'] . ' LIMIT 1;', array($peer_addr));
                }
                //$cache_pseudowires['ips'][$peer_addr]['host'] = $entry['reverse_dns'];
            }
            $entry['peer_port_id'] = $cache_pseudowires['ips'][$peer_addr]['port_id'];
            if (is_numeric($cache_pseudowires['ips'][$peer_addr]['port_id_fix'])) {
                // If we found port on remote device, than both devices in DB and will try to fix real port
                $peer_port_tmp = get_port_by_id_cache($cache_pseudowires['ips'][$peer_addr]['port_id_fix']);
                $peer_port_fix = dbFetchCell('SELECT `port_id` FROM `pseudowires` WHERE `device_id` = ? AND `pwID` = ? LIMIT 1;', array($peer_port_tmp['device_id'], $entry['pwID']));
                if (is_numeric($peer_port_fix)) {
                    $entry['peer_port_id'] = $peer_port_fix;
                } else {
                    $entry['peer_port_id'] = $cache_pseudowires['ips'][$peer_addr]['port_id_fix'];
                }
            }
            //r($entry['peer_port_id']);
            if ($entry['peer_port_id']) {
                $entry['peer_port'] = get_port_by_id_cache($entry['peer_port_id']);
                //r($entry['peer_port']);
                $entry['peer_device_id'] = $entry['peer_port']['device_id'];
                //r($entry['peer_device_id']);
                $entry['peer_device'] = device_by_id_cache($entry['peer_device_id']);
            }
        }
        $entry['hostname'] = $GLOBALS['cache']['devices']['id'][$entry['device_id']]['hostname'];
        // Attach hostname for sorting
        $entries[] = $entry;
    }
    // Sorting
    switch ($vars['sort_order']) {
        case 'desc':
            $sort_order = SORT_DESC;
            $sort_neg = SORT_ASC;
            break;
        case 'reset':
            unset($vars['sort'], $vars['sort_order']);
            // no break here
        // no break here
        default:
            $sort_order = SORT_ASC;
            $sort_neg = SORT_DESC;
    }
    switch ($vars['sort']) {
        case 'device':
            $entries = array_sort_by($entries, 'hostname', $sort_order, SORT_STRING);
            break;
        case 'pwid':
            $entries = array_sort_by($entries, 'pwID', $sort_order, SORT_NUMERIC);
            break;
        case 'pwtype':
            $entries = array_sort_by($entries, 'pwType', $sort_order, SORT_STRING, 'pwPsnType', $sort_order, SORT_STRING);
            //$pws = array_sort_by($pws, 'pwType',  $sort_order, SORT_STRING);
            break;
        case 'peer_addr':
            $entries = array_sort_by($entries, 'peer_addr', $sort_order, SORT_NUMERIC);
            break;
        case 'event':
            $entries = array_sort_by($entries, 'event', $sort_order, SORT_STRING);
            break;
        case 'uptime':
            $entries = array_sort_by($entries, 'pwUptime', $sort_order, SORT_NUMERIC);
            break;
        case 'last_change':
            $entries = array_sort_by($entries, 'last_change', $sort_neg, SORT_NUMERIC);
            break;
        case 'status':
            $entries = array_sort_by($entries, 'pwOperStatus', $sort_order, SORT_STRING);
            break;
        default:
            // Not sorted
    }
    return $entries;
}
Пример #12
0
/**
 * Check username and password against RADIUS authentication backend.
 *
 * @param string $username User name to check
 * @param string $password User password to check
 * @return int Authentication success (0 = fail, 1 = success) FIXME bool
 */
function radius_authenticate($username, $password)
{
    global $config, $rad;
    radius_init();
    if ($username && $rad) {
        //print_vars(radius_server_secret($rad));
        radius_create_request($rad, RADIUS_ACCESS_REQUEST);
        radius_put_attr($rad, RADIUS_USER_NAME, $username);
        switch (strtolower($config['auth_radius_method'])) {
            // CHAP-MD5 see RFC1994
            case 'chap':
            case 'chap_md5':
                $chapid = 1;
                // Specify a CHAP identifier
                //$challenge = mt_rand(); // Generate a challenge
                //$cresponse = md5(pack('Ca*', $chapid, $password.$challenge), TRUE);
                new Crypt_CHAP();
                // Pre load class
                $crpt = new Crypt_CHAP_MD5();
                $crpt->password = $password;
                $challenge = $crpt->challenge;
                $resp_md5 = $crpt->challengeResponse();
                $resp = pack('C', $chapid) . $resp_md5;
                radius_put_attr($rad, RADIUS_CHAP_PASSWORD, $resp);
                // Add the Chap-Password attribute
                radius_put_attr($rad, RADIUS_CHAP_CHALLENGE, $challenge);
                // Add the Chap-Challenge attribute.
                break;
                // MS-CHAPv1 see RFC2433
            // MS-CHAPv1 see RFC2433
            case 'mschapv1':
                $chapid = 1;
                // Specify a CHAP identifier
                $flags = 1;
                // 0 = use LM-Response, 1 = use NT-Response (we not use old LM)
                new Crypt_CHAP();
                // Pre load class
                $crpt = new Crypt_CHAP_MSv1();
                $crpt->password = $password;
                $challenge = $crpt->challenge;
                $resp_lm = str_repeat("", 24);
                $resp_nt = $crpt->challengeResponse();
                $resp = pack('CC', $chapid, $flags) . $resp_lm . $resp_nt;
                radius_put_vendor_attr($rad, RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_RESPONSE, $resp);
                radius_put_vendor_attr($rad, RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_CHALLENGE, $challenge);
                break;
                // MS-CHAPv2 see RFC2759
            // MS-CHAPv2 see RFC2759
            case 'mschapv2':
                $chapid = 1;
                // Specify a CHAP identifier
                $flags = 1;
                // 0 = use LM-Response, 1 = use NT-Response (we not use old LM)
                new Crypt_CHAP();
                // Pre load class
                $crpt = new Crypt_CHAP_MSv2();
                $crpt->username = $username;
                $crpt->password = $password;
                $challenge = $crpt->authChallenge;
                $challenge_p = $crpt->peerChallenge;
                $resp_nt = $crpt->challengeResponse();
                // Response: chapid, flags (1 = use NT Response), Peer challenge, reserved, Response
                $resp = pack('CCa16a8a24', $chapid, $flags, $challenge_p, str_repeat("", 8), $resp_nt);
                radius_put_vendor_attr($rad, RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP2_RESPONSE, $resp);
                radius_put_vendor_attr($rad, RADIUS_VENDOR_MICROSOFT, RADIUS_MICROSOFT_MS_CHAP_CHALLENGE, $challenge);
                break;
                // PAP (Plaintext)
            // PAP (Plaintext)
            default:
                radius_put_attr($rad, RADIUS_USER_PASSWORD, $password);
        }
        // Puts standard attributes
        $radius_ip = get_ip_version($config['auth_radius_nas_address']) ? $config['auth_radius_nas_address'] : $_SERVER['SERVER_ADDR'];
        if (get_ip_version($radius_ip) == 6) {
            // FIXME, not sure that this work correctly
            radius_put_attr($rad, RADIUS_NAS_IPV6_ADDRESS, $radius_ip);
        } else {
            radius_put_addr($rad, RADIUS_NAS_IP_ADDRESS, $radius_ip);
        }
        $radius_id = empty($config['auth_radius_id']) ? get_localhost() : $config['auth_radius_id'];
        radius_put_attr($rad, RADIUS_NAS_IDENTIFIER, $radius_id);
        //radius_put_attr($rad, RADIUS_NAS_PORT_TYPE, RADIUS_VIRTUAL);
        //radius_put_attr($rad, RADIUS_SERVICE_TYPE, RADIUS_FRAMED);
        //radius_put_attr($rad, RADIUS_FRAMED_PROTOCOL, RADIUS_PPP);
        radius_put_attr($rad, RADIUS_CALLING_STATION_ID, isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1');
        $response = radius_send_request($rad);
        //print_vars($response);
        switch ($response) {
            case RADIUS_ACCESS_ACCEPT:
                // An Access-Accept response to an Access-Request indicating that the RADIUS server authenticated the user successfully.
                //echo 'Authentication successful';
                return 1;
                break;
            case RADIUS_ACCESS_REJECT:
                // An Access-Reject response to an Access-Request indicating that the RADIUS server could not authenticate the user.
                //echo 'Authentication failed';
                break;
            case RADIUS_ACCESS_CHALLENGE:
                // An Access-Challenge response to an Access-Request indicating that the RADIUS server requires further information
                // in another Access-Request before authenticating the user.
                //echo 'Challenge required';
                break;
            default:
                print_error('A RADIUS error has occurred: ' . radius_strerror($rad));
        }
    }
    //session_logout();
    return 0;
}
Пример #13
0
function get_port_id_by_ip_cache($device, $ip)
{
    global $cache;
    $ip_version = get_ip_version($ip);
    if (is_array($device) && isset($device['device_id'])) {
        $device_id = $device['device_id'];
    } else {
        if (is_numeric($device)) {
            $device_id = $device;
        }
    }
    if (!isset($device_id) || !$ip_version) {
        print_error("Invalid arguments passed into function get_port_id_by_ip_cache(). Please report to developers.");
        return FALSE;
    }
    if ($ip_version == 6) {
        $ip = Net_IPv6::uncompress($ip, TRUE);
    }
    if (isset($cache['port_ip'][$device_id][$ip])) {
        return $cache['port_ip'][$device_id][$ip];
    }
    $ips = dbFetchRows('SELECT `port_id`, `ifOperStatus`, `ifAdminStatus` FROM `ipv' . $ip_version . '_addresses`
                      LEFT JOIN `ports` USING(`port_id`)
                      WHERE `deleted` = 0 AND `device_id` = ? AND `ipv' . $ip_version . '_address` = ?', array($device_id, $ip));
    if (count($ips) === 1) {
        // Simple
        $port = current($ips);
        //return $port['port_id'];
    } else {
        foreach ($ips as $entry) {
            if ($entry['ifAdminStatus'] == 'up' && $entry['ifOperStatus'] == 'up') {
                // First UP entry
                $port = $entry;
                break;
            } else {
                if ($entry['ifAdminStatus'] == 'up') {
                    // Admin up, but port down or other state
                    $ips_up[] = $entry;
                } else {
                    // Admin down
                    $ips_down[] = $entry;
                }
            }
        }
        if (!isset($port)) {
            if ($ips_up) {
                $port = current($ips_up);
            } else {
                $port = current($ips_down);
            }
        }
    }
    $cache['port_ip'][$device_id][$ip] = $port['port_id'] ? $port['port_id'] : FALSE;
    return $cache['port_ip'][$device_id][$ip];
}
Пример #14
0
function short_hostname($hostname, $len = NULL, $escape = TRUE)
{
    $len = is_numeric($len) ? (int) $len : (int) $GLOBALS['config']['short_hostname']['length'];
    if (function_exists('custom_shorthost')) {
        $short_hostname = custom_shorthost($hostname, $len);
    } else {
        if (function_exists('custom_short_hostname')) {
            $short_hostname = custom_short_hostname($hostname, $len);
        } else {
            if (get_ip_version($hostname)) {
                return $hostname;
            }
            // If hostname is IP address, always return full hostname
            $parts = explode('.', $hostname);
            $short_hostname = $parts[0];
            $i = 1;
            while ($i < count($parts) && strlen($short_hostname . '.' . $parts[$i]) < $len) {
                $short_hostname = $short_hostname . '.' . $parts[$i];
                $i++;
            }
        }
    }
    if ($escape) {
        $short_hostname = escape_html($short_hostname);
    }
    return $short_hostname;
}
Пример #15
0
                    $remote_device_id = $GLOBALS['cache']['discovery-protocols'][$isdp_entry['agentIsdpCacheDeviceId']];
                } else {
                    $remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?", array($isdp_entry['agentIsdpCacheDeviceId'], $isdp_entry['agentIsdpCacheDeviceId']));
                    // FIXME do LLDP-code-style hostname overwrite here as well? (see below)
                    if (!$remote_device_id && is_valid_hostname($isdp_entry['agentIsdpCacheDeviceId']) && !is_bad_xdp($isdp_entry['agentIsdpCacheDeviceId'], $isdp_entry['agentIsdpCachePlatform'])) {
                        // For now it's a Cisco so CDP discovery is ok
                        $remote_device_id = discover_new_device($isdp_entry['agentIsdpCacheDeviceId'], 'xdp', 'ISDP', $device, $port);
                    }
                    // Cache remote device ID for other protocols
                    $GLOBALS['cache']['discovery-protocols'][$isdp_entry['agentIsdpCacheDeviceId']] = $remote_device_id;
                }
                if ($remote_device_id) {
                    $if = $isdp_entry['agentIsdpCacheDevicePort'];
                    $remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?", array($if, $if, $remote_device_id));
                } else {
                    $remote_port_id = "0";
                }
                if (!is_bad_xdp($isdp_entry['agentIsdpCacheDeviceId']) && $port['port_id'] && $isdp_entry['agentIsdpCacheDeviceId'] && $isdp_entry['agentIsdpCacheDevicePort']) {
                    $remote_address = $isdp_entry['agentIsdpCacheAddress'];
                    if (!get_ip_version($remote_address)) {
                        $remote_address = NULL;
                    }
                    discover_link($valid_link, $port['port_id'], 'isdp', $remote_port_id, $isdp_entry['agentIsdpCacheDeviceId'], $isdp_entry['agentIsdpCacheDevicePort'], $isdp_entry['agentIsdpCachePlatform'], $isdp_entry['agentIsdpCacheVersion'], $remote_address);
                }
            } else {
                echo "X";
            }
        }
    }
}
// EOF
Пример #16
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;
}
Пример #17
0
/**
 * Convert BGP peer index to vendor MIB specific entries
 *
 * @param array $peer Array with walked peer oids
 * @param string $index Peer index
 * @param string $mib MIB name
 */
function parse_bgp_peer_index(&$peer, $index, $mib = 'BGP4V2-MIB')
{
    $address_types = $GLOBALS['config']['mibs']['INET-ADDRESS-MIB']['rewrite']['InetAddressType'];
    $index_parts = explode('.', $index);
    switch ($mib) {
        case 'BGP4-MIB':
            // bgpPeerRemoteAddr
            if (get_ip_version($index)) {
                $peer['bgpPeerRemoteAddr'] = $index;
            }
            break;
        case 'ARISTA-BGP4V2-MIB':
            // 1. aristaBgp4V2PeerInstance
            $peer['aristaBgp4V2PeerInstance'] = array_shift($index_parts);
            // 2. aristaBgp4V2PeerRemoteAddrType.
            $peer_addr_type = array_shift($index_parts);
            if (strlen($peer['aristaBgp4V2PeerRemoteAddrType']) == 0) {
                $peer['aristaBgp4V2PeerRemoteAddrType'] = $peer_addr_type;
            }
            if (isset($address_types[$peer['aristaBgp4V2PeerRemoteAddrType']])) {
                $peer['aristaBgp4V2PeerRemoteAddrType'] = $address_types[$peer['aristaBgp4V2PeerRemoteAddrType']];
            }
            // 3. length of the IP address
            $ip_len = array_shift($index_parts);
            // 4. IP address
            $ip_parts = array_slice($index_parts, 0, $ip_len);
            // 5. aristaBgp4V2PeerRemoteAddr
            $peer_ip = implode('.', $ip_parts);
            if ($ip_len == 16) {
                $peer_ip = snmp2ipv6($peer_ip);
            }
            if ($peer_addr_type = get_ip_version($peer_ip)) {
                $peer['aristaBgp4V2PeerRemoteAddr'] = $peer_ip;
                $peer['aristaBgp4V2PeerRemoteAddrType'] = 'ipv' . $peer_addr_type;
                // FIXME. not sure, but seems as Arista use only ipv4/ipv6 for afi
            }
            break;
        case 'BGP4-V2-MIB-JUNIPER':
            // 1. jnxBgpM2PeerRoutingInstance
            $peer['jnxBgpM2PeerRoutingInstance'] = array_shift($index_parts);
            // 2. jnxBgpM2PeerLocalAddrType
            $local_addr_type = array_shift($index_parts);
            if (strlen($peer['jnxBgpM2PeerLocalAddrType']) == 0) {
                $peer['jnxBgpM2PeerLocalAddrType'] = $local_addr_type;
            }
            if (isset($address_types[$peer['jnxBgpM2PeerLocalAddrType']])) {
                $peer['jnxBgpM2PeerLocalAddrType'] = $address_types[$peer['jnxBgpM2PeerLocalAddrType']];
            }
            // 3. length of the local IP address
            $ip_len = strstr($peer['jnxBgpM2PeerLocalAddrType'], 'ipv6') ? 16 : 4;
            // 4. IP address
            $ip_parts = array_slice($index_parts, 0, $ip_len);
            // 5. jnxBgpM2PeerLocalAddr
            $local_ip = implode('.', $ip_parts);
            if ($ip_len == 16) {
                $local_ip = snmp2ipv6($local_ip);
            }
            if (get_ip_version($local_ip)) {
                $peer['jnxBgpM2PeerLocalAddr'] = $local_ip;
            }
            // Get second part of index
            $index_parts = array_slice($index_parts, $ip_len);
            // 6. jnxBgpM2PeerRemoteAddrType
            $peer_addr_type = array_shift($index_parts);
            if (strlen($peer['jnxBgpM2PeerRemoteAddrType']) == 0) {
                $peer['jnxBgpM2PeerRemoteAddrType'] = $peer_addr_type;
            }
            if (isset($address_types[$peer['jnxBgpM2PeerRemoteAddrType']])) {
                $peer['jnxBgpM2PeerRemoteAddrType'] = $address_types[$peer['jnxBgpM2PeerRemoteAddrType']];
            }
            // 7. length of the remote IP address
            $ip_len = strstr($peer['jnxBgpM2PeerRemoteAddrType'], 'ipv6') ? 16 : 4;
            // 8. IP address
            $ip_parts = array_slice($index_parts, 0, $ip_len);
            // 9. jnxBgpM2PeerRemoteAddr
            $peer_ip = implode('.', $ip_parts);
            if ($ip_len == 16) {
                $peer_ip = snmp2ipv6($peer_ip);
            }
            if (get_ip_version($peer_ip)) {
                $peer['jnxBgpM2PeerRemoteAddr'] = $peer_ip;
            }
            break;
        case 'FORCE10-BGP4-V2-MIB':
            // 1. f10BgpM2PeerInstance
            $peer['f10BgpM2PeerInstance'] = array_shift($index_parts);
            // 2. f10BgpM2PeerLocalAddrType
            $local_addr_type = array_shift($index_parts);
            if (strlen($peer['f10BgpM2PeerLocalAddrType']) == 0) {
                $peer['f10BgpM2PeerLocalAddrType'] = $local_addr_type;
            }
            if (isset($address_types[$peer['f10BgpM2PeerLocalAddrType']])) {
                $peer['f10BgpM2PeerLocalAddrType'] = $address_types[$peer['f10BgpM2PeerLocalAddrType']];
            }
            // 3. length of the local IP address
            $ip_len = strstr($peer['f10BgpM2PeerLocalAddrType'], 'ipv6') ? 16 : 4;
            // 4. IP address
            $ip_parts = array_slice($index_parts, 0, $ip_len);
            // 5. f10BgpM2PeerLocalAddr
            $local_ip = implode('.', $ip_parts);
            if ($ip_len == 16) {
                $local_ip = snmp2ipv6($local_ip);
            }
            if (get_ip_version($local_ip)) {
                $peer['f10BgpM2PeerLocalAddr'] = $local_ip;
            }
            // Get second part of index
            $index_parts = array_slice($index_parts, $ip_len);
            // 6. f10BgpM2PeerRemoteAddrType
            $peer_addr_type = array_shift($index_parts);
            if (strlen($peer['f10BgpM2PeerRemoteAddrType']) == 0) {
                $peer['f10BgpM2PeerRemoteAddrType'] = $peer_addr_type;
            }
            if (isset($address_types[$peer['f10BgpM2PeerRemoteAddrType']])) {
                $peer['f10BgpM2PeerRemoteAddrType'] = $address_types[$peer['f10BgpM2PeerRemoteAddrType']];
            }
            // 7. length of the remote IP address
            $ip_len = strstr($peer['f10BgpM2PeerRemoteAddrType'], 'ipv6') ? 16 : 4;
            // 8. IP address
            $ip_parts = array_slice($index_parts, 0, $ip_len);
            // 9. f10BgpM2PeerRemoteAddr
            $peer_ip = implode('.', $ip_parts);
            if ($ip_len == 16) {
                $peer_ip = snmp2ipv6($peer_ip);
            }
            if (get_ip_version($peer_ip)) {
                $peer['f10BgpM2PeerRemoteAddr'] = $peer_ip;
            }
            break;
    }
}
Пример #18
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>';
}
/**
 * Params:
 *
 * pagination, pageno, pagesize
 * device, type, adminstatus, state
 */
function get_bgp_array($vars)
{
    $array = array();
    // With pagination? (display page numbers in header)
    $array['pagination'] = isset($vars['pagination']) && $vars['pagination'];
    pagination($vars, 0, TRUE);
    // Get default pagesize/pageno
    $array['pageno'] = $vars['pageno'];
    $array['pagesize'] = $vars['pagesize'];
    $start = $array['pagesize'] * $array['pageno'] - $array['pagesize'];
    $pagesize = $array['pagesize'];
    // Require cached IDs from html/includes/cache-data.inc.php
    $cache_bgp =& $GLOBALS['cache']['bgp'];
    // Begin query generate
    $param = array();
    $where = ' WHERE 1 ';
    foreach ($vars as $var => $value) {
        if ($value != '') {
            switch ($var) {
                case 'device':
                case 'device_id':
                    $where .= generate_query_values($value, 'B.device_id');
                    break;
                case 'type':
                    if ($value == 'external' || $value == 'ebgp') {
                        $where .= generate_query_values($cache_bgp['external'], 'B.bgpPeer_id');
                    } else {
                        if ($value == 'internal' || $value == 'ibgp') {
                            $where .= generate_query_values($cache_bgp['internal'], 'B.bgpPeer_id');
                        }
                    }
                    break;
                case 'adminstatus':
                    if ($value == 'stop') {
                        $where .= generate_query_values($cache_bgp['start'], 'B.bgpPeer_id', '!=');
                        // NOT IN
                    } else {
                        if ($value == 'start') {
                            $where .= generate_query_values($cache_bgp['start'], 'B.bgpPeer_id');
                        }
                    }
                    break;
                case 'state':
                    if ($value == 'down') {
                        $where .= generate_query_values($cache_bgp['up'], 'B.bgpPeer_id', '!=');
                        // NOT IN
                    } else {
                        if ($value == 'up') {
                            $where .= generate_query_values($cache_bgp['up'], 'B.bgpPeer_id');
                        }
                    }
                    break;
            }
        }
    }
    // Cache IP array
    $cache_ip = dbFetchColumn("SELECT `ipv4_address` FROM `ipv4_addresses` WHERE `ipv4_address` NOT IN (?, ?)" . $GLOBALS['cache']['where']['ports_permitted'], array('127.0.0.1', '0.0.0.0'));
    $cache_ip = array_merge($cache_ip, dbFetchColumn("SELECT `ipv6_address` FROM `ipv6_addresses` WHERE `ipv6_compressed` NOT IN (?)" . $GLOBALS['cache']['where']['ports_permitted'], array('::1')));
    //r($cache_ip);
    // Show peers only for permitted devices
    $query_permitted = generate_query_values($cache_bgp['permitted'], 'B.bgpPeer_id');
    $query = 'FROM `bgpPeers` AS B';
    $query_count = 'SELECT COUNT(*) ' . $query . $where . $query_permitted;
    // Use only bgpPeer_id and device_id in query!
    $query .= ' LEFT JOIN `bgpPeers-state` AS S ON B.`bgpPeer_id` = S.`bgpPeer_id`';
    $query .= ' LEFT JOIN `devices` AS D ON B.`device_id` = D.`device_id`';
    $query .= $where . $query_permitted;
    $query = 'SELECT D.`hostname`, D.`bgpLocalAs`, B.*, S.* ' . $query;
    $query .= ' ORDER BY D.`hostname`, B.`bgpPeerRemoteAs`, B.`bgpPeerRemoteAddr`';
    $query .= " LIMIT {$start},{$pagesize}";
    // Query BGP
    foreach (dbFetchRows($query, $param) as $entry) {
        humanize_bgp($entry);
        $peer_addr = $entry['bgpPeerRemoteAddr'];
        $peer_devices[$entry['device_id']] = 1;
        // Collect devices for AFIs query
        if (!isset($cache_bgp['ips'][$peer_addr])) {
            $cache_bgp['ips'][$peer_addr] = array();
            if (in_array($peer_addr, $cache_ip)) {
                $peer_addr_type = get_ip_version($peer_addr);
                if ($peer_addr_type) {
                    $peer_addr_type = 'ipv' . $peer_addr_type;
                    $query_ip = 'SELECT `device_id`, `port_id`, `ifOperStatus`, `ifAdminStatus` FROM `' . $peer_addr_type . '_addresses`
                       JOIN `ports` USING (`port_id`) WHERE `' . $peer_addr_type . '_address` = ?;';
                    $ip_array = dbFetchRows($query_ip, array($peer_addr));
                    if (count($ip_array) > 1) {
                        // We have multiple ports for same IPs, complicated logic
                        foreach ($ip_array as $ip) {
                            $device_tmp = device_by_id_cache($ip['device_id']);
                            // Crazy logic, exclude down/disabled ports/devices
                            if (!$device_tmp['bgpLocalAs'] || $device_tmp['status'] == 0 || $ip['ifAdminStatus'] != 'up') {
                                continue;
                            }
                            $cache_bgp['ips'][$peer_addr]['device_id'] = $ip['device_id'];
                            $cache_bgp['ips'][$peer_addr]['port_id'] = $ip['port_id'];
                        }
                    } else {
                        $device_tmp = device_by_id_cache($ip_array[0]['device_id']);
                        if ($device_tmp['bgpLocalAs']) {
                            // We found device in DB by IP, but this device really have BGP?
                            $cache_bgp['ips'][$peer_addr]['device_id'] = $ip_array[0]['device_id'];
                            $cache_bgp['ips'][$peer_addr]['port_id'] = $ip_array[0]['port_id'];
                        }
                    }
                }
                //r($cache_bgp['ips'][$peer_addr]);
            }
        }
        $entry['peer_port_id'] = $cache_bgp['ips'][$peer_addr]['port_id'];
        //$entry['peer_port']      = get_port_by_id_cache($entry['peer_port_id']);
        $entry['peer_device_id'] = $cache_bgp['ips'][$peer_addr]['device_id'];
        //$entry['peer_device']    = device_by_id_cache($entry['peer_device_id']);
        $array['entries'][] = $entry;
    }
    // Query AFI/SAFI
    $query_afi = 'SELECT * FROM `bgpPeers_cbgp` WHERE 1' . generate_query_values(array_keys($peer_devices), 'device_id');
    //.generate_query_values(array_keys($cache_bgp['ips']), 'bgpPeerRemoteAddr');
    foreach (dbFetchRows($query_afi) as $entry) {
        $array['afisafi'][$entry['device_id']][$entry['bgpPeerRemoteAddr']][] = $entry['afi'] . '.' . $entry['safi'];
    }
    // Query BGP peers count
    if ($array['pagination']) {
        $array['count'] = dbFetchCell($query_count, $param);
        $array['pagination_html'] = pagination($vars, $array['count']);
    } else {
        $array['count'] = count($array['entries']);
    }
    return $array;
}
function match_network($ip, $nets, $first = FALSE)
{
    $return = FALSE;
    $ip_version = get_ip_version($ip);
    if ($ip_version) {
        if (!is_array($nets)) {
            $nets = array($nets);
        }
        foreach ($nets as $net) {
            $ip_in_net = FALSE;
            $revert = preg_match("/^\\!/", $net) ? TRUE : FALSE;
            // NOT match network
            $net = preg_replace("/^\\!/", "", $net);
            if ($ip_version == 4) {
                if (strpos($net, '.') === FALSE) {
                    continue;
                }
                // NOT IPv4 net, skip
                if (strpos($net, '/') === FALSE) {
                    $net .= '/32';
                }
                // NET without mask as single IP
                $ip_in_net = Net_IPv4::ipInNetwork($ip, $net);
            } else {
                if (strpos($net, ':') === FALSE) {
                    continue;
                }
                if (strpos($net, '/') === FALSE) {
                    $net .= '/128';
                }
                // NET without mask as single IP
                $ip_in_net = Net_IPv6::isInNetmask($ip, $net);
            }
            if ($revert && $ip_in_net) {
                return FALSE;
            }
            // Return FALSE if IP founded in network where should NOT match
            if ($first && $ip_in_net) {
                return TRUE;
            }
            // Return TRUE if IP founded in first match
            $return = $return || $ip_in_net;
        }
    }
    return $return;
}
Пример #21
0
 /**
  * @dataProvider providerGetIpVersion
  * @group ip
  */
 public function testGetIpVersion($string, $result)
 {
     $this->assertSame($result, get_ip_version($string));
 }