def Main(): cgiEnv = lib_common.CgiEnv() # instanceName = cgiEnv.GetId() # instanceName = cgiEnv.m_entity_id_dict["Instance"] hostname = cgiEnv.GetId() hostAddr = lib_util.GlobalGetHostByName(hostname) hostNode = lib_common.gUriGen.HostnameUri(hostname) cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() propInstance = lib_common.MakeProp("Mysql instance") # Now it looks for Mysql instances which are hosted on this machine. credList = lib_credentials.GetCredentialsNames("MySql") for instanceName in credList: # This does not even need mysql package, so it can always detect instances. sqlInstHost = instanceName.split(":")[0].strip() if (sqlInstHost != hostname) and (sqlInstHost != hostAddr): sqlInstAddr = lib_util.GlobalGetHostByName(sqlInstHost) if (sqlInstAddr != hostname) and (sqlInstAddr != hostAddr): continue # Intentionaly, it does not use mysql package. # nodeInstance = lib_common.gUriGen.UriMakeFromDict("mysql/instance", { "Instance": instanceName } ) nodeInstance = survol_mysql_instance.MakeUri(instanceName) grph.add((hostNode, propInstance, nodeInstance)) cgiEnv.OutCgiRdf()
def make_universal_alias_no_cache(an_object): # It is a rdflib.term.URIRef # The prefix of the URL which contain the host name, # maybe with a port number, maybe with a WBEM prefix, WMI machine, CGI script etc... # is simply replaced by the IP address of the machine. # The resulting string is the same for all servers running on the same machine. an_object_as_str = str(an_object) parsed_url = lib_util.survol_urlparse(an_object_as_str) # netloc=u'desktop-ni99v8e:8000' entity_host = parsed_url.netloc.split(":")[0] # FIXME: This is very slow. if False: try: # Might throw: socket.gaierror: [Errno 11004] getaddrinfo failed with "entity_host=desktop-ni99v8e" entity_ip_addr = lib_util.GlobalGetHostByName(entity_host) except: entity_ip_addr = entity_host else: entity_ip_addr = entity_host # RFC4343: Hostname are case-insensitive. entity_ip_addr = entity_ip_addr.lower() # TODO: Many things are calculated several times. lab_text, subj_entity_graphic_class, entity_id = lib_naming.ParseEntityUri( an_object_as_str, long_display=True, force_entity_ip_addr=entity_ip_addr) return lab_text
def AddInfo(grph, node, entity_ids_arr): smb_nam = entity_ids_arr[0] smb_ip = lib_util.GlobalGetHostByName(smb_nam) node_host = lib_uris.gUriGen.HostnameUri(smb_ip) grph.add((node, lib_common.MakeProp("SMB server"), node_host))
def GetWmiUserPass(machWithBackSlashes): # WmiConnect cimom=\\\\rchateau-HP\\:. wmiNamspace=aspnet # cleanMachNam = machWithBackSlashes.replace("\\","").lower() cleanMachNam = machWithBackSlashes.replace("\\", "") #sys.stderr.write("GetWmiUserPass cimom=%s cleanMachNam=%s\n" % ( machWithBackSlashes, cleanMachNam ) ) wmiUserPass = lib_credentials.GetCredentials("WMI", cleanMachNam) #sys.stderr.write("GetWmiUserPass wmiUserPass=%s\n" % ( str(wmiUserPass) ) ) if wmiUserPass[0]: return cleanMachNam, wmiUserPass[0], wmiUserPass[1] # WMI does not do local connection with the local IP. try: machIP = lib_util.GlobalGetHostByName(cleanMachNam) except: exc = sys.exc_info()[1] lib_common.ErrorMessageHtml( "GetWmiUserPass: Cannot connect to WMI server:%s" % cleanMachNam) #sys.stderr.write("GetWmiUserPass machIP=%s\n" % ( machIP ) ) wmiUserPass = lib_credentials.GetCredentials("WMI", machIP) return machIP, wmiUserPass[0], wmiUserPass[1]
def MakeUniversalAliasNoCache(anObj): # The prefix of the URL which contain the host name, # maybe with a port number, maybe with a WBEM prefix, WMI machine, # CGI script etc... # is simply replaced by the IP address of the machine. # The resulting string is the same for all servers # running on the same machine. parsed_url = lib_util.survol_urlparse(anObject) #sys.stderr.write("MakeUniversalAliasNoCache parsed_url=%s\n"%str(parsed_url)) # netloc=u'desktop-ni99v8e:8000' entity_host = parsed_url.netloc.split(":")[0] #sys.stderr.write("MakeUniversalAliasNoCache entity_host=%s\n"%str(entity_host)) # FIXME: This is very slow. if False: try: # Might throw: socket.gaierror: [Errno 11004] getaddrinfo failed with "entity_host=desktop-ni99v8e" entity_ip_addr = lib_util.GlobalGetHostByName(entity_host) except: entity_ip_addr = entity_host else: entity_ip_addr = entity_host # RFC4343: Hostname are case-insensitive. entity_ip_addr = entity_ip_addr.lower() # TODO: Many things are calculated several times. (labText, subjEntityGraphicClass, entity_id) = lib_naming.ParseEntityUri( anObject, longDisplay=True, force_entity_ip_addr=entity_ip_addr) # sys.stderr.write("MakeUniversalAliasNoCache anObject=%s labText=%s\n"%(str(anObject),labText)) return labText
def Main(): formAction = os.environ['SCRIPT_NAME'] cgiArguments = cgi.FieldStorage() credFilename = os.path.normpath(lib_credentials.credentials_filename()) page_title = "Edit Survol credentials in %s" % credFilename # Hostname=Unknown-30-b5-c2-02-0c-b5-2.home # Host address=192.168.0.17 # Remote client=82.45.12.63 currHostNam = socket.gethostname() currHostAddr = lib_util.GlobalGetHostByName(currHostNam) try: addrRemote = os.environ['REMOTE_ADDR'] except KeyError: #ERROR("edit_credentials.py: Cannot get REMOTE_ADDR") sys.stderr.write("edit_credentials.py: Cannot get REMOTE_ADDR\n") raise if addrRemote not in ["82.45.12.63","192.168.0.14","127.0.0.1"]: lib_common.ErrorMessageHtml("Access forbidden from %s"% addrRemote ) InsertedCredMap(cgiArguments) credMap = UpdatedCredMap(cgiArguments) credTypesWellKnown = CredDefinitions() credTypeList=sorted(credTypesWellKnown.keys()) if lib_util.GetJinja2(): MainJinja(page_title,currHostNam,currHostAddr,addrRemote,credMap,formAction,credTypeList) else: MainNoJinja(page_title,currHostNam,currHostAddr,addrRemote,credMap,formAction,credTypeList)
def Main(): cgiEnv = lib_common.CgiEnv( ) instanceName = cgiEnv.m_entity_id_dict["Instance"] instanceNode = survol_mysql_instance.MakeUri(instanceName) (hostname,hostport) = survol_mysql.InstanceToHostPort(instanceName) cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() hostAddr = lib_util.GlobalGetHostByName(hostname) # BEWARE: The rule whether we use the host name or the host IP is not very clear ! # The IP address would be unambiguous but less clear. hostNode = lib_common.gUriGen.HostnameUri(hostname) # BEWARE: This is duplicated. propDb = lib_common.MakeProp("Mysql database") aCred = lib_credentials.GetCredentials("MySql", instanceName) # If user/password incorrect, nothing we can do. try: aUser = aCred[0] connMysql = survol_mysql.MysqlConnect(instanceName,aUser,aPass=aCred[1]) except : exc = sys.exc_info() lib_common.ErrorMessageHtml("Cannot connect to instance=%s user=%s:%s"%(instanceName,aUser,str(exc))) cursorMysql = connMysql.cursor() cursorMysql.execute("show databases") propDb = lib_common.MakeProp("Mysql database") grph.add( ( hostNode, lib_common.MakeProp("Mysql instance"), instanceNode ) ) for dbInfo in cursorMysql: #('information_schema',) #('primhilltcsrvdb1',) sys.stderr.write("dbInfo=%s\n"%str(dbInfo)) dbNam = dbInfo[0] nodeMysqlDatabase = survol_mysql_database.MakeUri(instanceName,dbNam) # Create a node for each database. grph.add( ( nodeMysqlDatabase, pc.property_user, lib_common.NodeLiteral(aCred[0]) ) ) grph.add( ( instanceNode, propDb, nodeMysqlDatabase ) ) cursorMysql.close() connMysql.close() cgiEnv.OutCgiRdf("LAYOUT_SPLINE")
def Main(): formAction = os.environ['SCRIPT_NAME'] cgiArguments = cgi.FieldStorage() credFilename = os.path.normpath(lib_credentials.CredFilNam()) page_title = "Edit Survol credentials in %s" % credFilename lib_export_html.DisplayHtmlTextHeader(page_title) WrtAsUtf(""" <body><h2>Edit Survol credentials in %s</h2> """ % credFilename) # Hostname=Unknown-30-b5-c2-02-0c-b5-2.home # Host address=192.168.0.17 # Remote client=82.45.12.63 currHostNam = socket.gethostname() currHostAddr = lib_util.GlobalGetHostByName(currHostNam) addrRemote = os.environ['REMOTE_ADDR'] WrtAsUtf(""" <table border="1" width='100%%'> <tr><td><b>Host name</b></td><td>%s</td></tr> <tr><td><b>Host address</b></td><td>%s</td></tr> <tr><td><b>Remote address</b></td><td>%s</td></tr> """ % (currHostNam, currHostAddr, addrRemote)) if addrRemote in ["82.45.12.63", "192.168.0.14", "127.0.0.1"]: InsertedCredMap(cgiArguments) credMap = UpdatedCredMap(cgiArguments) credTypesWellKnown = CredDefinitions() WrtAsUtf("""<table border="1" width='100%%'>""") if credMap: FormUpdateCredentials(formAction, credMap, credTypesWellKnown) FormInsertCredentials(formAction, sorted(credTypesWellKnown.keys())) WrtAsUtf("""</table>""") else: WrtAsUtf("<b>ACCESS FORBIDDEN</b><br>") lib_export_html.DisplayHtmlTextFooter() #WrtAsUtf('<br><a href="edit_configuration.py">Configuration</a>') #urlIndex = lib_exports.UrlWWW("index.htm") #WrtAsUtf('<br><a href="' + urlIndex + '">Return to Survol</a>') WrtAsUtf("</body></html>")
def UniversalAlias(entity_ids_arr, entity_host, entity_class): # If IPV4, "host:port". Could be IPv6 socketAddr, socketPort = SplitAddrPort(entity_ids_arr[0]) # Is the host an IP address ? try: socket.inet_aton(socketAddr) sockIP = socketAddr except socket.error: # This is not an IP address, therefore must be converted. sockIP = lib_util.GlobalGetHostByName(socketAddr) if sockIP == "127.0.0.1": sockIP = lib_util.GlobalGetHostByName(socket.getfqdn()) # Just in case this would be a service name, turn into a protocol number. try: socketPortNumber = socket.getservbyname(socketPort) except: socketPortNumber = socketPort uniAlias = str(sockIP) + ":" + str(socketPortNumber) return uniAlias
def UniversalAlias(entity_ids_arr, entity_host, entity_class): # TOO SLOW !!! return "ThisComputer:" + entity_ids_arr[0].lower() try: # (entity_ids_arr=[u'desktop-ni99v8e'], entity_host='192.168.0.14', entity_class=u'CIM_ComputerSystem') # might possibly throw: # "[Errno 11004] getaddrinfo failed " aHostName = lib_util.GlobalGetHostByName(entity_ids_arr[0]) except: aHostName = entity_host # Hostnames are case-insensitive, RFC4343 https://tools.ietf.org/html/rfc4343 return "ThisComputer:" + aHostName.lower()
def AddInfo(grph, node, entity_ids_arr): timeStart = time.time() socketNam = entity_ids_arr[0] #sys.stderr.write("socketNam=%s\n"%socketNam) socketSplit = SplitAddrPort(socketNam) socketAddr = socketSplit[0] #sys.stderr.write("socketAddr=%s\n"%socketAddr) sockIP = lib_util.GlobalGetHostByName(socketAddr) timeEnd = time.time() timeDelta = timeEnd - timeStart DEBUG("addr.AddInfo tm=%f sockIP=%s", timeDelta, sockIP) nodeHost = lib_common.gUriGen.HostnameUri(sockIP) # Should be the otherway round, but it makes the graph ugly. grph.add((node, pc.property_has_socket, nodeHost))
def UniversalAlias(entity_ids_arr, entity_host, entity_class): """This does not care about the entity_host as this is simply the machine from which this machine was detected, so nothing more than a computer on the same network.""" return "ThisComputer:" + entity_ids_arr[0].lower() # TODO: This is too slow and not used yet. Consider using a cache. try: # (entity_ids_arr=[u'desktop-ni99v8e'], entity_host='192.168.0.14', entity_class=u'CIM_ComputerSystem') # might possibly throw: # "[Errno 11004] getaddrinfo failed " a_host_name = lib_util.GlobalGetHostByName(entity_ids_arr[0]) except: a_host_name = entity_host # Hostnames are case-insensitive, RFC4343 https://tools.ietf.org/html/rfc4343 return "ThisComputer:" + a_host_name.lower()
def Main(): cgiEnv = lib_common.CgiEnv() hostname = cgiEnv.GetId() cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() hostAddr = lib_util.GlobalGetHostByName(hostname) hostNode = lib_common.gUriGen.HostnameUri(hostname) for proc in CIM_Process.ProcessIter(): pid = proc.pid cgiEnv.OutCgiRdf()
def AddInfo(grph, node, entity_ids_arr): theHostname = entity_ids_arr[0] try: ipv4 = lib_util.GlobalGetHostByName(theHostname) except: grph.add((node, pc.property_information, lib_common.NodeLiteral("Unknown machine"))) return grph.add((node, lib_common.MakeProp("IP address"), lib_common.NodeLiteral(ipv4))) fqdn = socket.getfqdn(theHostname) grph.add((node, lib_common.MakeProp("FQDN"), lib_common.NodeLiteral(fqdn))) # No need to do that, because it is done in entity.py if mode!=json. # nameSpace = "" # AddWbemWmiServers(grph,node,theHostname, nameSpace, "CIM_ComputerSystem", "Name="+theHostname) AddGeocoder(grph, node, ipv4)
def AddInfo(grph, node, entity_ids_arr): """The URL is hard-coded but very important because it allows to visit another host with WMI access.""" the_hostname = entity_ids_arr[0] try: ipv4 = lib_util.GlobalGetHostByName(the_hostname) except: grph.add((node, pc.property_information, lib_util.NodeLiteral("Unknown machine"))) return grph.add( (node, lib_common.MakeProp("IP address"), lib_util.NodeLiteral(ipv4))) fqdn = socket.getfqdn(the_hostname) grph.add((node, lib_common.MakeProp("FQDN"), lib_util.NodeLiteral(fqdn))) # No need to do that, because it is done in entity.py if mode!=json. # nameSpace = "" # _add_wbem_wmi_servers(grph,node,the_hostname, nameSpace, "CIM_ComputerSystem", "Name="+the_hostname) AddGeocoder(grph, node, ipv4)
def Main(): paramkeyPortsRange = "Ports Range" cgiEnv = lib_common.ScriptEnvironment() # net_mask = "192.168.1.0/24" # '10.102.235.173' local_ip_addr = lib_util.GlobalGetHostByName(socket.gethostname()) split_ip_addr = local_ip_addr.split(".") split_ip_addr[3] = "0" net_mask = ".".join(split_ip_addr) + "/24" # "sP" is ping scan. # args = ["nmap", '-oX', '-', '-sP', '192.168.1.0/24', ] args = [ "nmap", '-oX', '-', '-sP', net_mask, ] # TODO: Get the netmask for the interface. # The program nmap must be in the PATH. p = lib_common.SubProcPOpen(args) grph = cgiEnv.GetGraph() nmap_last_output, nmap_err = p.communicate() dom = xml.dom.minidom.parseString(nmap_last_output) # <host><status state="down" reason="no-response"/> # <address addr="192.168.1.67" addrtype="ipv4" /> # </host> # <host><status state="up" reason="syn-ack"/> # <address addr="192.168.1.68" addrtype="ipv4" /> # <hostnames><hostname name="Unknown-00-18-e7-08-02-81.home" type="PTR" /></hostnames> # </host> # Possibly # <address addr="08:2E:5F:13:0E:48" addrtype="mac" vendor="Hewlett Packard"/> for dhost in dom.getElementsByTagName('host'): status = dhost.getElementsByTagName('status')[0].getAttributeNode( 'state').value node_host = None addr_vendor = None # TODO: This could be an option. Test this. if status != "up": continue for addr_element in dhost.getElementsByTagName('address'): # "mac", "ipv4" addr_type = addr_element.getAttributeNode('addrtype').value if addr_type == "ipv4": host = addr_element.getAttributeNode('addr').value node_host = lib_uris.gUriGen.HostnameUri(host) elif addr_type == "mac": try: addr_vendor = addr_element.getAttributeNode('vendor').value mac_addr = addr_element.getAttributeNode('addr').value except: addr_vendor = None if node_host: if addr_vendor: grph.add((node_host, lib_common.MakeProp("MAC address"), lib_util.NodeLiteral(mac_addr))) grph.add((node_host, lib_common.MakeProp("Vendor"), lib_util.NodeLiteral(addr_vendor))) for dhostname in dhost.getElementsByTagName('hostname'): hostnam = dhostname.getAttributeNode('name').value grph.add((node_host, pc.property_hostname, lib_util.NodeLiteral(hostnam))) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() instanceName = cgiEnv.m_entity_id_dict["Instance"] dbNam = cgiEnv.m_entity_id_dict["Database"] tableNam = cgiEnv.m_entity_id_dict["Table"] (hostname, hostport) = survol_mysql.InstanceToHostPort(instanceName) cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() hostAddr = lib_util.GlobalGetHostByName(hostname) # BEWARE: The rule whether we use the host name or the host IP is not very clear ! # The IP address would be unambiguous but less clear. hostNode = lib_common.gUriGen.HostnameUri(hostname) # BEWARE: This is duplicated. propDb = lib_common.MakeProp("Mysql database") nodeMysqlDatabase = survol_mysql_database.MakeUri(instanceName, dbNam) grph.add((hostNode, propDb, nodeMysqlDatabase)) aCred = lib_credentials.GetCredentials("MySql", instanceName) connMysql = survol_mysql.MysqlConnect(instanceName, aUser=aCred[0], aPass=aCred[1]) cursorMysql = connMysql.cursor() cursorMysql.execute( "select * from information_schema.TABLES where TABLE_SCHEMA='%s' and TABLE_NAME='%s'" % (dbNam.upper(), tableNam.upper())) propTable = lib_common.MakeProp("Mysql table") # >>> conn = MySQLdb.connect(user="******",passwd="?????",host="primhilltcsrvdb1.mysql.db") # >>> curs=conn.cursor() # >>> curs.execute("select * from information_schema.TABLES where TABLE_SCHEMA='primhilltcsrvdb1'") # >>> for x in curs: # TABLE_CATALOG def # TABLE_SCHEMA Table_... # TABLE_NAME Table_... # TABLE_TYPE # ENGINE Engine MySQL extension # VERSION Version The version number of the table's .frm file, MySQL extension # ROW_FORMAT Row_format MySQL extension # TABLE_ROWS Rows MySQL extension # AVG_ROW_LENGTH Avg_row_length MySQL extension # DATA_LENGTH Data_length MySQL extension # MAX_DATA_LENGTH Max_data_length MySQL extension # INDEX_LENGTH Index_length MySQL extension # DATA_FREE Data_free MySQL extension # AUTO_INCREMENT Auto_increment MySQL extension # CREATE_TIME Create_time MySQL extension # UPDATE_TIME Update_time MySQL extension # CHECK_TIME Check_time MySQL extension # TABLE_COLLATION Collation MySQL extension # CHECKSUM Checksum MySQL extension # CREATE_OPTIONS Create_options MySQL extension # TABLE_COMMENT Comment MySQL extension # ... print(x) # ( 'def', 'primhilltcsrvdb1', 'Test_Table', 'BASE TABLE', 'InnoDB', # 10L, 'Compact', 2L, 8192L, 16384L, # 0L, 0L, 0L, None, datetime.datetime(2017, 12, 13, 8, 59, 24), # None, None, 'latin1_swedish_ci', None, '', # 'Comment about this test table.') # There should be only one row, maximum. for tabInfo in cursorMysql: DEBUG("tabInfo=%s", str(tabInfo)) tableNam = tabInfo[2] nodeMysqlTable = survol_mysql_table.MakeUri(hostname, dbNam, tableNam) grph.add((nodeMysqlTable, lib_common.MakeProp("Table type"), lib_common.NodeLiteral(tabInfo[3]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Engine"), lib_common.NodeLiteral(tabInfo[4]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Version"), lib_common.NodeLiteral(tabInfo[5]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Row format"), lib_common.NodeLiteral(tabInfo[6]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Table rows"), lib_common.NodeLiteral(tabInfo[7]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Average row length"), lib_common.NodeLiteral(tabInfo[8]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Data length"), lib_common.NodeLiteral(tabInfo[9]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Maximum data length"), lib_common.NodeLiteral(tabInfo[10]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Index length"), lib_common.NodeLiteral(tabInfo[11]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Data free"), lib_common.NodeLiteral(tabInfo[12]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Auto increment"), lib_common.NodeLiteral(tabInfo[13]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Creation time"), lib_common.NodeLiteral(tabInfo[14]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Update time"), lib_common.NodeLiteral(tabInfo[15]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Check time"), lib_common.NodeLiteral(tabInfo[16]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Table collation"), lib_common.NodeLiteral(tabInfo[17]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Checksum"), lib_common.NodeLiteral(tabInfo[18]))) grph.add((nodeMysqlTable, lib_common.MakeProp("Create options"), lib_common.NodeLiteral(tabInfo[19]))) grph.add((nodeMysqlTable, pc.property_information, lib_common.NodeLiteral(tabInfo[20]))) grph.add((nodeMysqlDatabase, propTable, nodeMysqlTable)) cursorMysql.close() connMysql.close() cgiEnv.OutCgiRdf("LAYOUT_RECT_TB")
def Main(): cgiEnv = lib_common.ScriptEnvironment() socket_nam = cgiEnv.GetId() grph = cgiEnv.GetGraph() # See AddrUri() to understand the syntax of a socket name. socket_split = socket_nam.split(':') socket_name = socket_split[0] socket_addr = lib_util.GlobalGetHostByName(socket_name) all_ip_addrs = [ i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None) ] # If the address is one of our IP addresses, replace it. if socket_addr in all_ip_addrs: socket_addr = "127.0.0.1" # TODO: If the input address is not "127.0.0.1", there is NO POINT doing this !! # Maybe the port is given as a string, "ssh" or "telnet". # See usage of socket.getservbyport socket_port_string = socket_split[1] try: socket_port = int(socket_port_string) except ValueError: socket_port = socket.getservbyname(socket_port_string) logging.debug("socket_name=%s socket_addr=%s socket_port=%d", socket_name, socket_addr, socket_port) # TBH, I do not understand why a local address is sometimes displayed as "192.168.1.83", # "127.0.0.1", "0.0.0.0" etc... # l[0]= 192.168.1.83 l[1]= 5353 NO END # l[0]= ::1 l[1]= 5353 NO END # l[0]= 0.0.0.0 l[1]=59135 NO END # l[0]= :: l[1]=59136 NO END # l[0]= 192.168.56.1 l[1]= 5353 NO END # l[0]= 127.0.0.1 l[1]= 5354 NO END # l[0]= 0.0.0.0 l[1]= 1433 NO END # l[0]= :: l[1]= 1433 NO END def is_good_socket(xarray): try: # Compares the port number first because this is faster. if xarray[1] != socket_port: return False # Beware: We may have socket_name='192.168.1.83', socket_addr='127.0.0.1' # but the list of socket will display '192.168.1.83', at least on Windows. addr = xarray[0] if addr == socket_addr or addr == socket_name: return True # "::1" is equivalent to 127.0.0.1 for IPV6. if addr == "0.0.0.0" or addr == "::" or addr == "::1": return socket_addr == "127.0.0.1" except IndexError: pass return False for proc in psutil.process_iter(): node_process = None # All sockets connected to this process. all_connect = CIM_Process.PsutilProcConnections(proc, 'all') for cnt in all_connect: # pconn(fd=13, family=<AddressFamily.AF_INET: 2>, type=<SocketKind.SOCK_STREAM: 1>, laddr=('127.0.0.1', 8000), raddr=(), status='LISTEN') # The socket can be empty. # pconn(fd=15, family=<AddressFamily.AF_UNIX: 1>, type=2, laddr='/run/user/1001/systemd/notify', raddr=None, status='NONE') larray, rarray = cnt.laddr, cnt.raddr if not larray or not rarray: logging.debug("Empty socket. Continue.") continue try: logging.debug("l[0]=%16s l[1]=%5d r[0]=%16s r[1]=%5d", larray[0], larray[1], rarray[0], rarray[1]) except IndexError: try: logging.debug("l[0]=%16s l[1]=%5d NO END", larray[0], larray[1]) except IndexError: logging.debug("No socket") is_the_sock = is_good_socket(larray) or is_good_socket(rarray) if is_the_sock: # Creates the process only if not done before. if node_process == None: pid = proc.pid node_process = lib_uris.gUriGen.PidUri(pid) grph.add((node_process, pc.property_host, lib_common.nodeMachine)) grph.add((node_process, pc.property_pid, lib_util.NodeLiteral(pid))) # No need to be asynchronous because this is always the same socket. survol_addr.PsutilAddSocketToGraphOne(node_process, cnt, grph) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() instanceName = cgiEnv.m_entity_id_dict["Instance"] dbNam = cgiEnv.m_entity_id_dict["Database"].upper() tableNam = cgiEnv.m_entity_id_dict["Table"].upper() (hostname, hostport) = survol_mysql.InstanceToHostPort(instanceName) cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() hostAddr = lib_util.GlobalGetHostByName(hostname) # BEWARE: The rule whether we use the host name or the host IP is not very clear ! # The IP address would be unambiguous but less clear. hostNode = lib_common.gUriGen.HostnameUri(hostname) # BEWARE: This is duplicated. propDb = lib_common.MakeProp("Mysql database") nodeMysqlDatabase = survol_mysql_database.MakeUri(instanceName, dbNam) grph.add((hostNode, propDb, nodeMysqlDatabase)) aCred = lib_credentials.GetCredentials("MySql", instanceName) propTable = lib_common.MakeProp("Mysql table") propConstraint = lib_common.MakeProp("Table type") connMysql = survol_mysql.MysqlConnect(instanceName, aUser=aCred[0], aPass=aCred[1]) cursorMysql = connMysql.cursor() cursorMysql.execute( "select TABLE_NAME, REFERENCED_TABLE_NAME from information_schema.referential_constraints" " where CONSTRAINT_SCHEMA='%s' " " and ( TABLE_NAME='%s' or REFERENCED_TABLE_NAME='%s' ) " % (dbNam, tableNam, tableNam)) # There should be only one row, maximum. for constraintInfo in cursorMysql: sys.stderr.write("constraintInfo=%s\n" % str(constraintInfo)) tableNam = constraintInfo[0] tableNamRef = constraintInfo[1] sys.stderr.write("tableNam=%s\n" % (tableNam)) nodeMysqlTable = survol_mysql_table.MakeUri(hostname, dbNam, tableNam) nodeMysqlTableRef = survol_mysql_table.MakeUri(hostname, dbNam, tableNamRef) grph.add((nodeMysqlTable, propConstraint, nodeMysqlTableRef)) grph.add((nodeMysqlDatabase, propTable, nodeMysqlTable)) cursorMysql.close() connMysql.close() cgiEnv.OutCgiRdf("LAYOUT_RECT_TB")
def Main(): cgiEnv = lib_common.CgiEnv() socketNam = cgiEnv.GetId() grph = cgiEnv.GetGraph() # See AddrUri() to understand the syntax of a socket name. socketSplit = socketNam.split(':') socketName = socketSplit[0] socketAddr = lib_util.GlobalGetHostByName(socketName) allIpAddrs = [ i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None) ] # If the address is one of our IP addresses, replace it. if socketAddr in allIpAddrs: socketAddr = "127.0.0.1" # TODO: If the input address is not "127.0.0.1", there is NO POINT doing this !! # Maybe the port is given as a string, "ssh" or "telnet". # See usage of socket.getservbyport socketPortString = socketSplit[1] try: socketPort = int(socketPortString) except ValueError: socketPort = socket.getservbyname(socketPortString) sys.stderr.write("socketName=%s socketAddr=%s socketPort=%d\n" % (socketName, socketAddr, socketPort)) # TBH, I do not understand why a local address is sometimes displayed as "192.168.1.83", # "127.0.0.1", "0.0.0.0" etc... # l[0]= 192.168.1.83 l[1]= 5353 NO END # l[0]= ::1 l[1]= 5353 NO END # l[0]= 0.0.0.0 l[1]=59135 NO END # l[0]= :: l[1]=59136 NO END # l[0]= 192.168.56.1 l[1]= 5353 NO END # l[0]= 127.0.0.1 l[1]= 5354 NO END # l[0]= 0.0.0.0 l[1]= 1433 NO END # l[0]= :: l[1]= 1433 NO END def IsGoodSocket(xarray): try: # Compares the port number first because this is faster. if xarray[1] != socketPort: return False # Beware: We may have socketName='192.168.1.83', socketAddr='127.0.0.1' # but the list of socket will display '192.168.1.83', at least on Windows. addr = xarray[0] if addr == socketAddr or addr == socketName: return True # "::1" is equivalent to 127.0.0.1 for IPV6. if addr == "0.0.0.0" or addr == "::" or addr == "::1": return socketAddr == "127.0.0.1" except IndexError: pass return False for proc in CIM_Process.ProcessIter(): node_process = None # All sockets connected to this process. # all_connect = proc.get_connections('all') # all_connect = proc.get_connections() all_connect = CIM_Process.PsutilProcConnections(proc, 'all') for cnt in all_connect: (larray, rarray) = survol_addr.SocketToPair(cnt) try: sys.stderr.write("l[0]=%16s l[1]=%5d r[0]=%16s r[1]=%5d\n" % (larray[0], larray[1], rarray[0], rarray[1])) except IndexError: sys.stderr.write("l[0]=%16s l[1]=%5d NO END\n" % (larray[0], larray[1])) isTheSock = IsGoodSocket(larray) or IsGoodSocket(rarray) if isTheSock: # Creates the process only if not done before. if node_process == None: pid = proc.pid node_process = lib_common.gUriGen.PidUri(pid) # PAS BON: CAR PEUT_ETRE LE PROCESS PARENT EST DANS LA LISTE DES PROCESSES QU ON AJOUTE, # DONC C EST PAS CLAIR. FAUT VERIFIER LA RELATION DE PARENTE. grph.add((node_process, pc.property_host, lib_common.nodeMachine)) grph.add((node_process, pc.property_pid, lib_common.NodeLiteral(pid))) # No need to be asynchronous because this is always the same socket. survol_addr.PsutilAddSocketToGraphOne(node_process, cnt, grph) cgiEnv.OutCgiRdf()
def Main(): form_action = os.environ['SCRIPT_NAME'] cgi_arguments = cgi.FieldStorage() cred_filename = os.path.normpath(lib_credentials.credentials_filename()) page_title = "Edit Survol credentials in %s" % cred_filename # Hostname=Unknown-30-b5-c2-02-0c-b5-2.home # Host address=192.168.0.17 # Remote client=82.45.12.63 curr_host_nam = socket.gethostname() curr_host_addr = lib_util.GlobalGetHostByName(curr_host_nam) try: addr_remote = os.environ['REMOTE_ADDR'] except KeyError: logging.error("Cannot get REMOTE_ADDR") raise # Hard-coded protection. if addr_remote not in ["82.45.12.63", "192.168.0.14", "192.168.1.10", "192.168.56.1", "127.0.0.1"]: lib_common.ErrorMessageHtml("Access forbidden from %s" % addr_remote) _inserted_cred_map(cgi_arguments) cred_map = _updated_cred_map(cgi_arguments) cred_types_well_known = _cred_definitions() cred_type_list = sorted(cred_types_well_known.keys()) def main_no_jinja(): """Simple HTML page if jinja2 is not installed.""" lib_util.WrtHeader('text/html') lib_export_html.display_html_text_header(page_title) WrtAsUtf(""" <body><h2>%s</h2> """ % page_title) WrtAsUtf(""" <table border="1" width='100%%'> <tr><td><b>Host name</b></td><td>%s</td></tr> <tr><td><b>Host address</b></td><td>%s</td></tr> <tr><td><b>Remote address</b></td><td>%s</td></tr> """ % (curr_host_nam, curr_host_addr, addr_remote)) WrtAsUtf("""<table border="1" width='100%%'>""") if cred_map: _form_update_credentials_no_jinja(form_action, cred_map) _form_insert_credentials_no_jinja(form_action, cred_type_list) WrtAsUtf("""</table>""") html_footer = "".join(lib_export_html.display_html_text_footer()) WrtAsUtf(html_footer) WrtAsUtf("</body></html>") def main_jinja(): THIS_DIR = os.path.dirname(os.path.abspath(__file__)) template_file_name = "www/edit_credentials.template.htm" # Create the jinja2 environment. # Notice the use of trim_blocks, which greatly helps control whitespace. jinja2 = lib_util.GetJinja2() jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(THIS_DIR), trim_blocks=True) jinja_template = jinja_env.get_template(template_file_name) ordered_map = collections.OrderedDict() for cred_type in sorted(cred_map): sub_ordered_map = collections.OrderedDict() for cred_nam in sorted(cred_map[cred_type]): sub_ordered_map[cred_nam] = cred_map[cred_type][cred_nam] ordered_map[cred_type] = sub_ordered_map jinja_render = jinja_template.render( page_title=page_title, currHostNam=curr_host_nam, currHostAddr=curr_host_addr, addrRemote=addr_remote, credMap=ordered_map, credTypeList=cred_type_list ) lib_util.WrtHeader('text/html') WrtAsUtf(jinja_render) if lib_util.GetJinja2(): main_jinja() else: main_no_jinja()
def OraMachineToIp(oraMachine): # Maybe different on Linux ??? "WORKGROUP\RCHATEAU-HP" user_machine = lib_util.GlobalGetHostByName(oraMachine.split("\\")[-1]) return user_machine
def Main(): cgiEnv = lib_common.CgiEnv() hostname = cgiEnv.GetId() cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() hostAddr = lib_util.GlobalGetHostByName(hostname) # hostNode = lib_common.gUriGen.HostnameUri(hostAddr) # BEWARE: The rule whether we use the host name or the host IP is not very clear ! # The IP address would be unambiguous but less clear. hostNode = lib_common.gUriGen.HostnameUri(hostname) # serverBox = lib_common.RemoteBox(hostAddr) # Similar code in "enumerate_sockets.py" for proc in CIM_Process.ProcessIter(): try: if lib_common.is_useless_process(proc): continue pid = proc.pid # TCP sockets only. all_connect = CIM_Process.PsutilProcConnections(proc) Main.node_process = None def AssociateWithSockets(grph, larray, rarray): if Main.node_process == None: Main.node_process = lib_common.gUriGen.PidUri(pid) grph.add((Main.node_process, pc.property_host, lib_common.nodeMachine)) grph.add((Main.node_process, pc.property_pid, lib_common.NodeLiteral(pid))) lsocketNode = lib_common.gUriGen.AddrUri(larray[0], larray[1]) grph.add((lsocketNode, pc.property_information, lib_common.NodeLiteral(cnt.status))) rsocketNode = lib_common.gUriGen.AddrUri(rarray[0], rarray[1]) grph.add((lsocketNode, pc.property_information, lib_common.NodeLiteral(cnt.status))) grph.add((lsocketNode, pc.property_socket_end, rsocketNode)) grph.add( (Main.node_process, pc.property_has_socket, rsocketNode)) grph.add((hostNode, pc.property_has_socket, lsocketNode)) for cnt in all_connect: if ((cnt.family == socket.AF_INET) and (cnt.type == socket.SOCK_STREAM) and (cnt.status == 'ESTABLISHED')): (larray, rarray) = survol_addr.SocketToPair(cnt) if hostAddr == larray[0]: AssociateWithSockets(grph, larray, rarray) elif hostAddr == rarray[0]: AssociateWithSockets(grph, rarray, larray) except: pass cgiEnv.OutCgiRdf("LAYOUT_SPLINE")
def Main(): paramkeyPortsRange = "Ports Range" cgiEnv = lib_common.CgiEnv() # netMask = "192.168.1.0/24" # '10.102.235.173' localIpAddr = lib_util.GlobalGetHostByName(socket.gethostname()) splitIpAddr = localIpAddr.split(".") splitIpAddr[3] = "0" netMask = ".".join(splitIpAddr) + "/24" # "sP" is ping scan. # args = ["nmap", '-oX', '-', '-sP', '192.168.1.0/24', ] args = [ "nmap", '-oX', '-', '-sP', netMask, ] # TODO: Get the netmask for the interface. # The program nmap must be in the PATH. p = lib_common.SubProcPOpen(args) #except WindowsError: # On Windows, this cannot find "FileNotFoundError" # exc = sys.exc_info()[1] # lib_common.ErrorMessageHtml("Cannot find nmap:"+str(exc)+". Maybe a dependency problem") #except FileNotFoundError: # lib_common.ErrorMessageHtml("Cannot find nmap") #except : # On Windows, this cannot find "FileNotFoundError" # exc = sys.exc_info() # lib_common.ErrorMessageHtml("Cannot run nmap:"+str(exc)) grph = cgiEnv.GetGraph() (nmap_last_output, nmap_err) = p.communicate() dom = xml.dom.minidom.parseString(nmap_last_output) # <host><status state="down" reason="no-response"/> # <address addr="192.168.1.67" addrtype="ipv4" /> # </host> # <host><status state="up" reason="syn-ack"/> # <address addr="192.168.1.68" addrtype="ipv4" /> # <hostnames><hostname name="Unknown-00-18-e7-08-02-81.home" type="PTR" /></hostnames> # </host> # Possibly # <address addr="08:2E:5F:13:0E:48" addrtype="mac" vendor="Hewlett Packard"/> for dhost in dom.getElementsByTagName('host'): status = dhost.getElementsByTagName('status')[0].getAttributeNode( 'state').value nodeHost = None addrVendor = None # TODO: This could be an option. Test this. if status != "up": continue for addrElement in dhost.getElementsByTagName('address'): # "mac", "ipv4" addrType = addrElement.getAttributeNode('addrtype').value if addrType == "ipv4": host = addrElement.getAttributeNode('addr').value # sys.stderr.write("host=%s\n"%host) nodeHost = lib_common.gUriGen.HostnameUri(host) elif addrType == "mac": try: addrVendor = addrElement.getAttributeNode('vendor').value macAddr = addrElement.getAttributeNode('addr').value except: addrVendor = None if nodeHost: if addrVendor: grph.add((nodeHost, lib_common.MakeProp("MAC address"), lib_common.NodeLiteral(macAddr))) grph.add((nodeHost, lib_common.MakeProp("Vendor"), lib_common.NodeLiteral(addrVendor))) for dhostname in dhost.getElementsByTagName('hostname'): hostnam = dhostname.getAttributeNode('name').value # sys.stderr.write(" hostnam=%s\n"%hostnam) grph.add((nodeHost, pc.property_hostname, lib_common.NodeLiteral(hostnam))) cgiEnv.OutCgiRdf()
def Main(): cgiEnv = lib_common.CgiEnv() instanceName = cgiEnv.m_entity_id_dict["Instance"] instanceNode = survol_mysql_instance.MakeUri(instanceName) (hostname, hostport) = survol_mysql.InstanceToHostPort(instanceName) cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() hostAddr = lib_util.GlobalGetHostByName(hostname) # BEWARE: The rule whether we use the host name or the host IP is not very clear ! # The IP address would be unambiguous but less clear. hostNode = lib_common.gUriGen.HostnameUri(hostname) # BEWARE: This is duplicated. propDb = lib_common.MakeProp("Mysql database") #nodeMysqlDatabase = survol_mysql_database.MakeUri(instanceName,dbNam) #grph.add( ( hostNode, propDb, nodeMysqlDatabase ) ) aCred = lib_credentials.GetCredentials("MySql", instanceName) connMysql = survol_mysql.MysqlConnect(instanceName, aUser=aCred[0], aPass=aCred[1]) cursorMysql = connMysql.cursor() # mysql> select * from information_schema.processlist; # +--------+------------------+------------------+------+---------+------+-----------+----------------------------------------------+ # | ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO | # +--------+------------------+------------------+------+---------+------+-----------+----------------------------------------------+ # | 439768 | primhilltcsrvdb1 | 10.2.123.9:52146 | NULL | Query | 0 | executing | select * from information_schema.processlist | # | 439765 | primhilltcsrvdb1 | 10.2.123.9:52062 | NULL | Sleep | 13 | | NULL | # +--------+------------------+------------------+------+---------+------+-----------+----------------------------------------------+ cursorMysql.execute("select * from information_schema.processlist") propTable = lib_common.MakeProp("Mysql table") grph.add((hostNode, lib_common.MakeProp("Mysql instance"), instanceNode)) for sessInfo in cursorMysql: sys.stderr.write("sessInfo=%s\n" % str(sessInfo)) mysqlSessionId = sessInfo[0] mysqlUser = sessInfo[1] sessionNode = survol_mysql_session.MakeUri(instanceName, mysqlSessionId) # If there is a proper socket, then create a name for it. mysqlSocket = sessInfo[2] try: (mysqlSocketHost, mysqlSocketPort) = mysqlSocket.split(":") socketNode = lib_common.gUriGen.AddrUri(mysqlSocketHost, mysqlSocketPort) grph.add((sessionNode, lib_common.MakeProp("Connection socket"), socketNode)) except: pass # If there is a running query, then display it. mysqlCommand = sessInfo[4] mysqlState = sessInfo[6] if (mysqlCommand == "Query") and (mysqlState == "executing"): mysqlQuery = sessInfo[7] nodeQuery = survol_mysql_query.MakeUri(instanceName, mysqlQuery) grph.add( (sessionNode, lib_common.MakeProp("Mysql query"), nodeQuery)) grph.add((sessionNode, lib_common.MakeProp("User"), lib_common.NodeLiteral(mysqlUser))) grph.add( (sessionNode, lib_common.MakeProp("Mysql session"), instanceNode)) cursorMysql.close() connMysql.close() cgiEnv.OutCgiRdf("LAYOUT_SPLINE")
def OraMachineToIp(ora_machine): """This returns an IP address.""" # Maybe different on Linux ??? "WORKGROUP\MYMACHINE" user_machine = lib_util.GlobalGetHostByName(ora_machine.split("\\")[-1]) return user_machine