def parse_bindings(binding_info, host_ips):
    """
    Parse binding info from binding_info['bindingInformation'] using below format and return list protocol_name, ips, port, hostnamr
        <network interface ip or "*">:<port>:<host header>

    :param binding_info: Binding string which have such format:
    :type binding_info: dict[str, str]
    :return: list[str, list(IPAddress), int, str]
    :rtype: list[str, list(IPAddress), int, str]
    """
    binding_string = binding_info.get("bindingInformation")
    protocol = binding_info.get("protocol")
    if not binding_string or not protocol:
        raise ValueError("Incorrect binding's information was passed")
    tokens = binding_string.split(":")
    if len(tokens) != 3:
        raise ValueError("Incorrect binding's string was passed")
    interface = tokens[0].strip()
    port = int(tokens[1].strip())
    hostname = tokens[2].strip()
    interfaces = []
    if interface == "*":
        interfaces = host_ips or []
    elif interface:
        interfaces.append(str(ip_addr.IPAddress(interface)))

    endpoints = []
    for interface in interfaces:
        endpoint = netutils.Endpoint(port, netutils.ProtocolType.TCP_PROTOCOL, interface, portType=protocol)
        endpoints.append(endpoint)

    return hostname, protocol, endpoints
    def getBindings(self, binding_str):
        binding_elements = binding_str.split(',')
        bindings = []
        try:
            for binding_element in binding_elements:
                if '/' not in binding_element:
                    continue
                protocol, address = binding_element.split('/')
                parts = address.split(':')
                if len(parts) == 3:
                    ip, port, hostname = parts
                    ips = []
                    if not ip or ip == '*':
                        if self.ips:
                            ips = self.ips
                    else:
                        ips = [ip]
                    endpoints = []
                    for ip in ips:
                        endpoint = netutils.Endpoint(
                            port,
                            netutils.ProtocolType.TCP_PROTOCOL,
                            ip,
                            portType=protocol)
                        endpoints.append(endpoint)
                    binding = (hostname, protocol, endpoints)
                    bindings.append(binding)

            logger.debug('Get bindings of site:', bindings)
        except:
            logger.warnException('Failed to get binding info')
        return bindings
def modelConnectedPortByAppcmd(context, ispowershell=False):
    endpointOSHV = ObjectStateHolderVector()
    logger.debug("reporting endpoints for iis using appcmd")
    CMD_PATH = r'%windir%\system32\inetsrv\appcmd.exe'
    LIST_SITE = CMD_PATH + ' list site /xml'
    if ispowershell:
        LIST_SITE = r'cmd /c "$env:windir\system32\inetsrv\appcmd.exe list site /xml"'
    result = context.client.execCmd(LIST_SITE)
    if context.client.getLastCmdReturnCode() == 0 and result:
        root = ET.fromstring(result)
        site_elements = root.findall('SITE')
        for element in site_elements:
            binding_str = element.get('bindings')
            binding_elements = binding_str.split(',')
            try:
                for binding_element in binding_elements:
                    if '/' not in binding_element:
                        continue
                    protocol, address = binding_element.split('/')
                    parts = address.split(':')
                    if len(parts) == 3:
                        ip, port, hostname = parts
                        ips = []
                        if not ip or ip == '*':
                            if context.application.getApplicationIp():
                                ips = [context.application.getApplicationIp()]
                        else:
                            ips = [ip]
                        endpoints = []
                        for ip in ips:
                            endpoint = netutils.Endpoint(
                                port,
                                netutils.ProtocolType.TCP_PROTOCOL,
                                ip,
                                portType=protocol)
                            endpointOSH = visitEndpoint(endpoint)
                            hostosh = modeling.createHostOSH(ip)
                            endpointOSH.setContainer(hostosh)
                            linkOsh = modeling.createLinkOSH(
                                "usage", context.application.getOsh(),
                                endpointOSH)
                            endpointOSHV.add(endpointOSH)
                            endpointOSHV.add(linkOsh)
                logger.debug('Get port using appcmd:', port)
            except:
                logger.warnException('Failed to get binding info')
    else:
        logger.debug("Cannot get port from appcmd")

    return endpointOSHV
示例#4
0
def filterEndpointsByPorts(Framework, endpoints, connections, warninglist):
    restrictPortNumber = Framework.getParameter('restrictPortNumber')
    restrictPortNumber = not restrictPortNumber or restrictPortNumber.lower() == 'true' or restrictPortNumber.lower() == 'on'

    logger.debug('Use %s to filter port: ' % CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME,
                 restrictPortNumber and 'yes' or 'no')

    result = []

    if restrictPortNumber:
        cfg_file = Framework.getConfigFile(CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME)
        ports = [port.getPortNumber() for port in cfg_file.getPorts(PortType.TCP)]
        filtered_connections = [x for x in connections if x and x.dstPort in ports]
        portlistbefiltered = set()
        for connection in connections:
            if not connection.dstPort in ports:
                portlistbefiltered.add(int(connection.dstPort))

        if portlistbefiltered:
            portlistbefiltered = sorted(portlistbefiltered)
            portlistbefiltered = [str(x) for x in portlistbefiltered]
            portlistbefiltered = ', '.join(portlistbefiltered)
            logger.debug("The following outgoing ports are filtered because they are not in %s: %s" %
                         (CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME, portlistbefiltered))
            errobj = errorobject.createError(errorcodes.PORT_NOT_IN_CONFIGFILE,
                                             [CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME,
                                              portlistbefiltered],
                                             "The following outgoing ports are filtered because they are not in %s: %s"
                                             % (CollectorsParameters.KEY_COLLECTORS_SERVERDATA_PORTNUMBERTOPORTNAME,
                                                portlistbefiltered))
            warninglist.append(errobj)
    else:
        filtered_connections = connections

    for endpoint in endpoints:
        local_endpoints = endpoint.getEndpoints()
        filtered = []
        for endp in local_endpoints:
            connections = getConnectionsBySrcPort(endp.getPort(), filtered_connections)
            for connection in connections:
                filtered.append(netutils.Endpoint(connection.dstPort, endp.getProtocolType(), connection.dstAddr, 1,
                                                  endp.getPortType()))
        logger.debug('filtered is %s ' % filtered)
        if filtered:
            result.append(netutils.ConnectivityEndpoint(endpoint.getKey(), filtered))

    return result
示例#5
0
 def __discoverConnectionInfo(self, shell, path):
     provider, agent = self.get_regutils(shell)
     builder = provider.getBuilder(regutils.HKLM, path)
     items = agent.execQuery(builder)
     hosts = {}
     for item in items:
         values = item.getAsDict()
         for connectionItem in values.keys():
             connectInfo = values.get(connectionItem)
             if connectInfo is not None and ',' in connectInfo:
                 tokens = connectInfo.split(',')
                 host = tokens[1]
                 if len(tokens) > 2:
                     port = tokens[2]
                 else:
                     port = MSSQLRegistryEntryDiscoverer.DEFAULT_PORT
                 hosts[connectionItem] = netutils.Endpoint(
                     port, netutils.ProtocolType.TCP_PROTOCOL, host)
     return hosts
 def _filterEndpointsByPorts(self, endpoints, connections):
     result = []
     connections_map = {}
     [connections_map.update({str(x.srcPort): x}) for x in connections]
     for endpoint in endpoints:
         local_endpoints = endpoint.getEndpoints()
         filtered = []
         for endp in local_endpoints:
             connection = connections_map.get(str(endp.getPort()))
             if connection:
                 filtered.append(
                     netutils.Endpoint(connection.dstPort,
                                       endp.getProtocolType(),
                                       connection.dstAddr, 1,
                                       endp.getPortType()))
         logger.debug('filtered is %s ' % filtered)
         if filtered:
             result.append(
                 netutils.ConnectivityEndpoint(endpoint.getKey(), filtered))
     return result
示例#7
0
    def _addTcpData(self,
                    ipaddress,
                    port,
                    process_pid,
                    listen=0,
                    protocol=modeling.TCP_PROTOCOL,
                    ProcessName=None,
                    listenIpPorts=None):
        port = int(port)
        ips = []
        if self.hostIps and (ipaddress.startswith('0.')
                             or ipaddress.find("*") >= 0):
            ips.extend(self.hostIps)
        elif self.hostIps and (ipaddress == '::'):
            ips.extend(self.hostIps)  # TODO add only ipv6 addresses
        else:
            ips.append(ipaddress)

        processEndpoints = []
        for ip in ips:
            if not listenIpPorts is None:
                listenIpPorts.append('%s:%s' % (ip, port))
            self.pdu.addPortToProcess(ip, port, process_pid, listen, protocol,
                                      ProcessName)

            if ip and port:
                endpoint = netutils.Endpoint(port, protocol, ip, listen)
                processEndpoints.append(endpoint)
        if processEndpoints and process_pid:
            processPidInt = None
            try:
                processPidInt = int(process_pid)
            except:
                logger.warn("Failed to convert process PID to int")
            else:
                connectivityEndpoint = netutils.ConnectivityEndpoint(
                    processPidInt, processEndpoints)
                self._processesEndPoints.append(connectivityEndpoint)
示例#8
0
 def _convertToTcpEndpoint(self, item):
     r'@types: com.amazonaws.services.rds.model.Endpoint -> netutils.Endpoint'
     return netutils.Endpoint(item.getPort(),
                              netutils.ProtocolType.TCP_PROTOCOL,
                              item.getAddress())
示例#9
0
        nodeOsh = rdsReporter.reportInstanceNode(instance)
        vector.add(nodeOsh)
        vector.add(rdsReporter.linkAccountWithInstanceNode(
            accountOsh, nodeOsh))
        # report instance (node as container)
        instanceOsh = dbReporter.reportServer(dbServer, nodeOsh)
        vector.add(instanceOsh)
        # membership link between instance node + availability zone
        zoneName = instance.getAvailabilityZoneName()
        if zoneName:
            zoneOsh = awsReporter.reportAvailabilityZoneByName(zoneName)
            vector.add(zoneOsh)
            vector.add(rdsReporter.linkZoneWithInstanceNode(zoneOsh, nodeOsh))
        # report endpoint
        endpoint = netutils.Endpoint(dbServer.getPort(),
                                     netutils.ProtocolType.TCP_PROTOCOL,
                                     dbServer.address)

        vector.add(endpointReporter.reportEndpoint(endpoint, instanceOsh))
        # reporting of parameter and security groups
        # link with parameter groups
        for group in instance.getParameterGroups():
            if paramGroupByName.has_key(group.getName()):
                group = paramGroupByName.get(group.getName())
            else:
                logger.warn("Failed to find %s for %s" % (group, instance))
            configOsh = rdsReporter.reportParameterGroupConfig(
                group, accountOsh)
            vector.add(configOsh)
            vector.add(
                rdsReporter.linkInstanceWithGroupConfig(