def recv(self): """Receive a packet at the Enqueue layer, performing reassemble of fragmented packets if necessary. :return: received :class:`SAPEnqueue` packet :rtype: :class:`SAPEnqueue` :raise socket.error: if the connection was close """ # Receive the NI packet packet = SAPRoutedStreamSocket.recv(self) if SAPEnqueue in packet and packet[SAPEnqueue].more_frags: log_sapenqueue.debug("Received Enqueue fragmented packet") head = str(packet[SAPEnqueue])[:20] data = str(packet[SAPEnqueue])[20:] total_length = packet[SAPEnqueue].len - 20 recvd_length = len(packet[SAPEnqueue]) - 20 log_sapenqueue.debug("Received %d up to %d bytes", recvd_length, total_length) while recvd_length < total_length and packet[SAPEnqueue].more_frags == 1: response = SAPRoutedStreamSocket.recv(self)[SAPEnqueue] data += str(response)[20:] recvd_length += len(response) - 20 log_sapenqueue.debug("Received %d up to %d bytes", recvd_length, total_length) packet = SAPEnqueue(head + data) return packet
def recv(self): """Receive a packet at the Enqueue layer, performing reassemble of fragmented packets if necessary. :return: received :class:`SAPEnqueue` packet :rtype: :class:`SAPEnqueue` :raise socket.error: if the connection was close """ # Receive the NI packet packet = SAPRoutedStreamSocket.recv(self) if SAPEnqueue in packet and packet[SAPEnqueue].more_frags: log_sapenqueue.debug("Received Enqueue fragmented packet") head = str(packet[SAPEnqueue])[:20] data = str(packet[SAPEnqueue])[20:] total_length = packet[SAPEnqueue].len - 20 recvd_length = len(packet[SAPEnqueue]) - 20 log_sapenqueue.debug("Received %d up to %d bytes", recvd_length, total_length) while recvd_length < total_length and packet[ SAPEnqueue].more_frags == 1: response = SAPRoutedStreamSocket.recv(self)[SAPEnqueue] data += str(response)[20:] recvd_length += len(response) - 20 log_sapenqueue.debug("Received %d up to %d bytes", recvd_length, total_length) packet = SAPEnqueue(head + data) return packet
def test_saproutedstreamsocket(self): """Test SAPRoutedStreamSocket""" self.start_server(SAPRouterServerTestHandler) sock = socket.socket() sock.connect((self.test_address, self.test_port)) route = [ SAPRouterRouteHop(hostname=self.test_address, port=self.test_port), SAPRouterRouteHop(hostname="10.0.0.1", port="3200") ] self.client = SAPRoutedStreamSocket(sock, route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) self.client.close() self.stop_server()
def test_saproutedstreamsocket_error(self): """Test SAPRoutedStreamSocket throwing of Exception if an invalid or unexpected packet is received""" self.start_server(SAPRouterServerTestHandler) sock = socket.socket() sock.connect((self.test_address, self.test_port)) with self.assertRaises(Exception): self.client = SAPRoutedStreamSocket(sock, route=None, router_version=40) self.stop_server()
def test_saproutedstreamsocket_getnisocket(self): """Test SAPRoutedStreamSocket get nisocket class method""" self.start_server(SAPRouterServerTestHandler) # Test using a complete route route = [ SAPRouterRouteHop(hostname=self.test_address, port=self.test_port), SAPRouterRouteHop(hostname="10.0.0.1", port="3200") ] self.client = SAPRoutedStreamSocket.get_nisocket(route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) # Test using a route and a target host/port route = [ SAPRouterRouteHop(hostname=self.test_address, port=self.test_port) ] self.client = SAPRoutedStreamSocket.get_nisocket("10.0.0.1", "3200", route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) # Test using a route string route = "/H/%s/S/%s/H/10.0.0.1/S/3200" % (self.test_address, self.test_port) self.client = SAPRoutedStreamSocket.get_nisocket(route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) self.client.close() self.stop_server()
def do_connect(self, args): """ Initiate the connection to the Message Server service. The connection is registered using the client_string runtime option. """ # Create the socket connection try: self.connection = SAPRoutedStreamSocket.get_nisocket(self.options.remote_host, self.options.remote_port, self.options.route_string, base_cls=SAPMS) except SocketError as e: self._error("Error connecting with the Message Server") self._error(str(e)) return self._print("Attached to %s / %d" % (self.options.remote_host, self.options.remote_port)) # Send MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, toname=self.runtimeoptions["client_string"], fromname=self.runtimeoptions["client_string"]) self._debug("Sending login packet") response = self.connection.sr(p)[SAPMS] if response.errorno == 0: self.runtimeoptions["server_string"] = response.fromname self._debug("Login performed, server string: %s" % response.fromname) self._print("pysap's Message Server monitor, connected to %s / %d" % (self.options.remote_host, self.options.remote_port)) self.connected = True else: if response.errorno in ms_errorno_values: self._error("Error performing login: %s" % ms_errorno_values[response.errorno]) else: self._error("Unknown error performing login: %d" % response.errorno)
def send_crash(host, port, item, verbose, route=None): # Create the connection to the SAP Netweaver server if verbose: print("[*] Sending crash") # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(host, port, route, base_cls=SAPEnqueue) conn.send(item)
def do_connect(self, args): """ Initiate the connection to the Gateway service. The connection is registered using the client_string runtime option. """ # Create the socket connection try: self.connection = SAPRoutedStreamSocket.get_nisocket( self.options.remote_host, self.options.remote_port, self.options.route_string, base_cls=SAPRFC) except SocketError as e: self._error("Error connecting with the Gateway service") self._error(str(e)) return self._print("Attached to %s / %d" % (self.options.remote_host, self.options.remote_port)) p = SAPRFC(version=int(self.runtimeoptions["version"]), req_type=1) self._debug("Sending check gateway packet") try: response = self.connection.send(p) except SocketError: self._error("Error connecting to the gateway monitor service") else: self.connected = True
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) domain = ms_domain_values_inv[options.domain] # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) client_string = options.client # Send MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, domain=domain, toname=client_string, fromname=client_string) print("[*] Sending login packet") response = conn.sr(p)[SAPMS] print("[*] Login performed, server string: %s" % response.fromname) # Sends a message to another client p = SAPMS(flag=0x02, iflag=0x01, domain=domain, toname=options.target, fromname=client_string, opcode=1) p /= Raw(options.message) print("[*] Sending packet to: %s" % options.target) conn.send(p)
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket( options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS ) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) client_string = options.client # Send MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, toname=client_string, fromname=client_string) print("[*] Sending login packet") response = conn.sr(p)[SAPMS] print("[*] Login performed, server string: %s" % response.fromname) print("[*] Listening to server messages") try: while True: # Send MS_SERVER_LST packet response = conn.recv()[SAPMS] print("[*] Message received !") response.show() except SocketError: print("[*] Connection error") except KeyboardInterrupt: print("[*] Cancelled by the user")
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) print("[*] Testing IGS ZIPPER interpreter on %s:%d" % (options.remote_host, options.remote_port)) # open input file try: with open(options.file_input, 'rb') as f: file_input_content=f.read() except IOError: print("[!] Error reading %s file." % options.file_input) exit(2) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPIGS) # the xml request for zipper interpreter xml = '<?xml version="1.0"?><REQUEST><COMPRESS type="zip"><FILES>' xml += '<FILE name="{}" '.format(options.file_input) xml += 'path="{}" '.format(options.file_path) xml += 'size="{}"/>'.format(len(file_input_content)) xml += '</FILES></COMPRESS></REQUEST>' # create tables descriptions # table with xml content table_xml = SAPIGSTable.add_entry('XMLDESC', 1, len(xml), 1, 'XMLDESC', len(xml) ) # table with file content table_file = SAPIGSTable.add_entry('FILE1', 1, len(file_input_content), 1, 'FILE1', len(file_input_content) ) # get the futur offset where table entries begin offset = (len(table_xml) + len(table_file)) # filling tables content_xml = xml content_file = file_input_content # total size of packet # total_size need to be a multiple of 1024 total_size = offset + 244 # 244 IGS header size total_size += 1023 total_size -= (total_size % 1024) # Put all together p = SAPIGS(function='ZIPPER', listener='L', offset_content=str(offset), packet_size=str(total_size)) p = p / table_xml / table_file / content_xml / content_file # Send the IGS packet print("[*] Send %s to ZIPPER interpreter..." % options.file_input) conn.send(p) print("[*] File sent.")
def route_test(rhost, rport, thost, tport, talk_mode, router_version): logging.info("[*] Routing connections to %s:%s" % (thost, tport)) # Build the route to the target host passing through the SAP Router route = [ SAPRouterRouteHop(hostname=rhost, port=rport), SAPRouterRouteHop(hostname=thost, port=tport) ] # Try to connect to the target host using the routed stream socket try: conn = SAPRoutedStreamSocket.get_nisocket( route=route, talk_mode=talk_mode, router_version=router_version) conn.close() status = 'open' # If an SAPRouteException is raised, the route was denied or an error # occurred with the SAP router except SAPRouteException: status = 'denied' # Another error occurred on the server (e.g. timeout), mark the target as error except Exception: status = 'error' return status
def route_test(rhost, rport, thost, tport, talk_mode, router_version): print("[*] Routing connections to %s:%s" % (thost, tport)) # Build the route to the target host passing through the SAP Router route = [SAPRouterRouteHop(hostname=rhost, port=rport), SAPRouterRouteHop(hostname=thost, port=tport)] # Try to connect to the target host using the routed stream socket try: conn = SAPRoutedStreamSocket.get_nisocket(route=route, talk_mode=talk_mode, router_version=router_version) conn.close() status = 'open' # If an SAPRouteException is raised, the route was denied or an error # occurred with the SAP router except SAPRouteException: status = 'denied' # Another error occurred on the server (e.g. timeout), mark the target as error except Exception: status = 'error' return status
def connect(self): """Creates a :class:`SAPNIStreamSocket` connection to the host/port. If a route was specified, connect to the target Diag server through the SAP Router. """ self._connection = SAPRoutedStreamSocket.get_nisocket(self.host, self.port, self.route, base_cls=SAPDiag)
def test_saproutedstreamsocket_getnisocket(self): """Test SAPRoutedStreamSocket get nisocket class method""" self.start_server(SAPRouterServerTestHandler) # Test using a complete route route = [SAPRouterRouteHop(hostname=self.test_address, port=self.test_port), SAPRouterRouteHop(hostname="10.0.0.1", port="3200")] self.client = SAPRoutedStreamSocket.get_nisocket(route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) # Test using a route and a target host/port route = [SAPRouterRouteHop(hostname=self.test_address, port=self.test_port)] self.client = SAPRoutedStreamSocket.get_nisocket("10.0.0.1", "3200", route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) # Test using a route string route = "/H/%s/S/%s/H/10.0.0.1/S/3200" % (self.test_address, self.test_port) self.client = SAPRoutedStreamSocket.get_nisocket(route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) self.client.close() self.stop_server()
def test_saproutedstreamsocket_route_error(self): """Test SAPRoutedStreamSocket throwing of SAPRouteException if a route denied return error is received""" self.start_server(SAPRouterServerTestHandler) sock = socket.socket() sock.connect((self.test_address, self.test_port)) route = [SAPRouterRouteHop(hostname=self.test_address, port=self.test_port), SAPRouterRouteHop(hostname="10.0.0.2", port="3200")] with self.assertRaises(SAPRouteException): self.client = SAPRoutedStreamSocket(sock, route=route, router_version=40) self.stop_server()
def send_crash(host, port, item, verbose, route=None): # Create the connection to the SAP Netweaver server if verbose: print("[*] Sending crash") # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket( host, port, route, talk_mode=ROUTER_TALK_MODE_NI_RAW_IO) conn.send(item) conn.close()
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) domain = ms_domain_values_inv[options.domain] # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) client_string = options.client # Send MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, domain=domain, toname=client_string, fromname=client_string) print("[*] Sending login packet:") response = conn.sr(p)[SAPMS] print("[*] Login OK, Server string: %s" % response.fromname) server_string = response.fromname # Send a Dump Info packet for each possible Dump for i in ms_dump_command_values.keys(): # Skip MS_DUMP_MSADM and MS_DUMP_COUNTER commands as the info # is included in other dump commands if i in [1, 12]: continue p = SAPMS(flag=0x02, iflag=0x01, domain=domain, toname=server_string, fromname=client_string, opcode=0x1e, dump_dest=0x02, dump_command=i) print("[*] Sending dump info", ms_dump_command_values[i]) response = conn.sr(p)[SAPMS] if response.opcode_error != 0: print("Error:", ms_opcode_error_values[response.opcode_error]) print(response.opcode_value)
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) # Open image to convert try: with open(options.input_image, "rb") as f: image = f.read() except IOError: print("Error reading image file !") exit(0) print("[*] Testing IGS IMGCONV on http://%s:%d" % (options.remote_host, options.remote_port)) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket( options.remote_host, options.remote_port, options.route_string, talk_mode=ROUTER_TALK_MODE_NI_RAW_IO) # XML file request # JPEG to PNG size 100x100 xml = '''<?xml version="1.0" encoding="UTF-8"?> <IMAGE> <WIDTH>100</WIDTH> <HEIGTH>100</HEIGTH> <INPUT>image/jpeg</INPUT> <OUTPUT>image/png</OUTPUT> </IMAGE> ''' # build http packet files = {"xml": ("xml", xml), "img": ("img", image)} p = SAPIGS.http(options.remote_host, options.remote_port, 'IMGCONV', files) # Send request print("[*] Send packet to IGS...") conn.send(p) print("[*] Response :") response = conn.recv() response.show() # Extract picture url from response print("[*] Generated file(s) :") for url in str(response).split('href='): if "output" in url: print( "http://%s:%d%s" % (options.remote_host, options.remote_port, url.split('"')[1]))
def connect(self): """Creates a :class:`SAPNIStreamSocket` connection to the host/port. If a route was specified, connect to the target HANA server through the SAP Router. :raises: SAPHDBConnectionError """ try: self._stream_socket = SAPRoutedStreamSocket.get_nisocket(self.host, self.port, self.route, base_cls=SAPHDB, talk_mode=1) except socket.error as e: raise SAPHDBConnectionError("Error connecting to the server (%s)" % e)
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) print("[*] Testing IGS ZIPPER interpreter on %s:%d" % (options.remote_host, options.remote_port)) # open input file try: with open(options.file_input, 'rb') as f: file_input_content = f.read() except IOError: print("[!] Error reading %s file." % options.file_input) exit(2) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket( options.remote_host, options.remote_port, options.route_string, talk_mode=ROUTER_TALK_MODE_NI_RAW_IO) # the xml request for zipper interpreter xml = '<?xml version="1.0"?><REQUEST><COMPRESS type="zip"><FILES>' xml += '<FILE name="%s" ' % (options.file_input) xml += 'path="%s" ' % (options.file_path) xml += 'size="%s"/>' % (len(file_input_content)) xml += '</FILES></COMPRESS></REQEST>' # http request type multipart/form-data files = {"xml": ("xml", xml), "zipme": ("zipme", file_input_content)} p = SAPIGS.http(options.remote_host, options.remote_port, 'ZIPPER', files) # Send/Receive request print("[*] Send %s to ZIPPER interpreter..." % options.file_input) conn.send(p) print("[*] Response :") response = conn.recv(1024) response.show() # Extract zip from response print("[*] Generated file(s) :") for url in str(response).split('href='): if "output" in url: print( "http://%s:%d%s" % (options.remote_host, options.remote_port, url.split('"')[1]))
def do_connect(self, args): """ Initiate the connection to the Gateway service. The connection is registered using the client_string runtime option. """ # Create the socket connection try: self.connection = SAPRoutedStreamSocket.get_nisocket(self.options.remote_host, self.options.remote_port, self.options.route_string, base_cls=SAPRFC) except SocketError as e: self._error("Error connecting with the Gateway service") self._error(str(e)) return self._print("Attached to %s / %d" % (self.options.remote_host, self.options.remote_port))
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) print("[*] Testing IGS ZIPPER interpreter on %s:%d" % (options.remote_host, options.remote_port)) # open input file try: with open(options.file_input, 'rb') as f: file_input_content = f.read() except IOError: print("[!] Error reading %s file." % options.file_input) exit(2) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, talk_mode=1) # the xml request for zipper interpreter xml = '<?xml version="1.0"?><REQUEST><COMPRESS type="zip"><FILES>' xml += '<FILE name="%s" ' % (options.file_input) xml += 'path="%s" ' % (options.file_path) xml += 'size="%s"/>' % (len(file_input_content)) xml += '</FILES></COMPRESS></REQEST>' # http request type multipart/form-data files = {"xml": ("xml", xml), "zipme": ("zipme", file_input_content)} p = SAPIGS.http(options.remote_host, options.remote_port, 'ZIPPER', files) # Send/Receive request print("[*] Send %s to ZIPPER interpreter..." % options.file_input) conn.send(p) print("[*] Response :") response = conn.recv(1024) response.show() # Extract zip from response print("[*] Generated file(s) :") for url in str(response).split('href='): if "output" in url: print("http://%s:%d%s" % (options.remote_host, options.remote_port, url.split('"')[1]))
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) print("[*] Testing XXE over IGS XMLCHART on http://%s:%d" % (options.remote_host, options.remote_port)) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket( options.remote_host, options.remote_port, options.route_string, talk_mode=ROUTER_TALK_MODE_NI_RAW_IO) # XML Data content data = '''<?xml version="1.0" encoding="utf-8"?> <ChartData> <Categories> <Category>Fus Ro Dah</Category> </Categories> <Series label="bla"> <Point><Value type="y">42</Value></Point> </Series> </ChartData>''' # http POST request type multipart/form-data files = {'data': ('data', data)} p = SAPIGS.http(options.remote_host, options.remote_port, 'XMLCHART', files) # Send/Receive request print("[*] Send request to IGS...") conn.send(p) print("[*] Response :") response = conn.recv(1024) response.show() # Extract picture from response print("[*] Generated file(s) :") for url in str(response).split('href='): if "output" in url: print( "http://%s:%d%s" % (options.remote_host, options.remote_port, url.split('"')[1]))
def do_connect(self, args): """ Initiate the connection to the Gateway service. The connection is registered using the client_string runtime option. """ # Create the socket connection try: self.connection = SAPRoutedStreamSocket.get_nisocket( self.options.remote_host, self.options.remote_port, self.options.route_string, base_cls=SAPRFC) except SocketError as e: self._error("Error connecting with the Gateway service") self._error(str(e)) return self._print("Attached to %s / %d" % (self.options.remote_host, self.options.remote_port))
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) print("[*] Testing XXE over IGS XMLCHART on http://%s:%d" % (options.remote_host, options.remote_port)) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, talk_mode=1) # XML Data content data = '''<?xml version="1.0" encoding="utf-8"?> <ChartData> <Categories> <Category>Fus Ro Dah</Category> </Categories> <Series label="bla"> <Point><Value type="y">42</Value></Point> </Series> </ChartData>''' # http POST request type multipart/form-data files = {'data': ('data', data)} p = SAPIGS.http(options.remote_host, options.remote_port, 'XMLCHART', files) # Send/Receive request print("[*] Send request to IGS...") conn.send(p) print("[*] Response :") response = conn.recv(1024) response.show() # Extract picture from response print("[*] Generated file(s) :") for url in str(response).split('href='): if "output" in url: print("http://%s:%d%s" % (options.remote_host, options.remote_port, url.split('"')[1]))
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) domain = ms_domain_values_inv[options.domain] # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) client_string = options.client # Send MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, domain=domain, toname=client_string, fromname=client_string) print("[*] Sending login packet") response = conn.sr(p)[SAPMS] print("[*] Login performed, server string: %s" % response.fromname) print("[*] Listening to server messages") try: while (True): # Send MS_SERVER_LST packet response = conn.recv()[SAPMS] print("[*] Message received !") response.show() except SocketError: print("[*] Connection error") except KeyboardInterrupt: print("[*] Cancelled by the user")
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) client_string = options.client # Send MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, toname=client_string, fromname=client_string) print("[*] Sending login packet:") response = conn.sr(p)[SAPMS] print("[*] Login OK, Server string: %s" % response.fromname) server_string = response.fromname # Send a Dump Info packet for each possible Dump for i in ms_dump_command_values.keys(): # Skip MS_DUMP_MSADM and MS_DUMP_COUNTER commands as the info # is included in other dump commands if i in [1, 12]: continue p = SAPMS(flag=0x02, iflag=0x01, toname=server_string, fromname=client_string, opcode=0x1e, dump_dest=0x02, dump_command=i) print("[*] Sending dump info", ms_dump_command_values[i]) response = conn.sr(p)[SAPMS] if (response.opcode_error != 0): print("Error:", ms_opcode_error_values[response.opcode_error]) print(response.opcode_value)
def test_saproutedstreamsocket(self): """Test SAPRoutedStreamSocket""" self.start_server(SAPRouterServerTestHandler) sock = socket.socket() sock.connect((self.test_address, self.test_port)) route = [SAPRouterRouteHop(hostname=self.test_address, port=self.test_port), SAPRouterRouteHop(hostname="10.0.0.1", port="3200")] self.client = SAPRoutedStreamSocket(sock, route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) self.client.close() self.stop_server()
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) domain = ms_domain_values_inv[options.domain] # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) client_string = options.client # Build MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, domain=domain, toname=client_string, fromname=client_string) # Send MS_LOGIN_2 packet print("[*] Sending login packet") response = conn.sr(p)[SAPMS] print("[*] Login performed, server string: %s" % response.fromname) server_string = response.fromname print("[*] Retrieving current value of parameter: %s" % options.param_name) # Send ADM AD_PROFILE request adm = SAPMSAdmRecord(opcode=0x1, parameter=options.param_name) p = SAPMS(toname=server_string, fromname=client_string, version=4, flag=0x04, iflag=0x05, domain=domain, adm_records=[adm]) print("[*] Sending packet") response = conn.sr(p)[SAPMS] if options.verbose: print("[*] Response:") response.show() param_old_value = response.adm_records[0].parameter print("[*] Parameter %s" % param_old_value) # If a parameter change was requested, send an ADM AD_SHARED_PARAMETER request if options.param_value: print("[*] Changing parameter value from: %s to: %s" % (param_old_value, options.param_value)) # Build the packet adm = SAPMSAdmRecord(opcode=0x2e, parameter="%s=%s" % (options.param_name, options.param_value)) p = SAPMS(toname=server_string, fromname=client_string, version=4, iflag=5, flag=4, domain=domain, adm_records=[adm]) # Send the packet print("[*] Sending packet") response = conn.sr(p)[SAPMS] if options.verbose: print("[*] Response:") response.show() if response.adm_records[0].errorno != 0: print("[*] Error requesting parameter change (error number %d)" % response.adm_records[0].errorno) else: print("[*] Parameter changed for the current session !")
def __init__(self, sock, *args, **kwargs): """Initialization defaults to SAPEnqueue as base class""" if "base_cls" not in kwargs: kwargs["base_cls"] = SAPEnqueue SAPRoutedStreamSocket.__init__(self, sock, *args, **kwargs)
def client_mode(options): """"Implements the niping client running mode :param options: option set from the command line :type options: Values """ times = [] p = Raw("EYECATCHER" + "\x00" * (options.buffer_size - 10)) try: # Establish the connection conn = SAPRoutedStreamSocket.get_nisocket(options.host, options.port, options.route_string) print("") print(datetime.today().ctime()) print("connect to server o.k.") # Send the messages for i in range(options.loops): # Send the packet and grab the response start_time = datetime.now() r = conn.sr(p) end_time = datetime.now() # Check the response if str(r.payload) != str(p): print("[-] Response on message {} differs".format(i)) # Calculate and record the elapsed time times.append(end_time - start_time) # Close the connection properly conn.send(Raw()) conn.close() except SocketError: print("[*] Connection error") except KeyboardInterrupt: print("[*] Cancelled by the user") if times: print("") print(datetime.today().ctime()) print("send and receive {} messages (len {})".format(len(times), options.buffer_size)) # Calculate the stats times = [x.total_seconds() * 1000 for x in times] times_min = min(times) times_max = max(times) times_avg = float(sum(times)) / max(len(times), 1) times_tr = float(options.buffer_size * len(times)) / float(sum(times)) times2 = [x for x in times if x not in [times_min, times_max]] times2_avg = float(sum(times2)) / max(len(times2), 1) times2_tr = float(options.buffer_size * len(times2)) / float(sum(times2)) # Print the stats print("") print("------- times -----") print("avg {:8.3f} ms".format(times_avg)) print("max {:8.3f} ms".format(times_max)) print("min {:8.3f} ms".format(times_min)) print("tr {:8.3f} kB/s".format(times_tr)) print("excluding max and min:") print("av2 {:8.3f} ms".format(times2_avg)) print("tr2 {:8.3f} kB/s".format(times2_tr)) print("")
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) # initiate the connection : print("[*] Initiate connection to message server %s:%d" % (options.remote_host, options.remote_port)) try: conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) except Exception as e: print(e) print ("Error during MS connection. Is internal ms port %d reachable ?" % options.remote_port) else: print ("[*] Connected. I check parameters...") client_string = options.client # Send MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, toname=client_string, fromname=client_string) print("[*] Sending login packet:") response = conn.sr(p)[SAPMS] print("[*] Login OK, Server string: %s\n" % response.fromname) server_string = response.fromname try: with open(options.file_param) as list_param: for line in list_param.readlines(): line = line.strip() # Check for comments or empty lines if len(line) == 0 or line.startswith("#"): continue # Get parameters, check type and expected value # param2c = the SAP parameter to check # check_type = EQUAL, SUP, INF, REGEX, <none> # value2c = the expect value for 'ok' status (param2c, check_type, value2c) = line.split(':') status = '[!]' # create request adm = SAPMSAdmRecord(opcode=0x1, parameter=param2c) p = SAPMS(toname=server_string, fromname=client_string, version=4, flag=0x04, iflag=0x05, adm_records=[adm]) # send request respond = conn.sr(p)[SAPMS] value = respond.adm_records[0].parameter.replace(respond.adm_records[0].parameter.split('=')[0] + '=', '') # Verify if value match with expected value if value == '': value = 'NOT_EXIST' status = '[ ]' elif check_type == 'EQUAL': if value.upper() == str(value2c).upper(): status = '[+]' elif check_type == 'NOTEQUAL': if value.upper() != str(value2c).upper(): status = '[+]' elif check_type == 'REGEX': if re.match(value2c.upper(), value.upper()) and value2c != 'NOT_EXIST': status = '[+]' elif check_type == 'SUP': if float(value) >= float(value2c): status = '[+]' elif check_type == 'INF': if float(value) <= float(value2c): status = '[+]' else: status = '[ ]' # display result print ("%s %s = %s" % (status, param2c, value)) except IOError: print("Error reading parameters file !") exit(0) except ValueError: print("Invalid parameters file format or access denied!") exit(0)
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) domain = ms_domain_values_inv[options.domain] # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) # Generate a random client string to differentiate our connection client_string = options.client # Send MS_LOGIN_2 packet print("[*] Sending login packet") p = SAPMS(flag=0x00, iflag=0x08, domain=domain, toname=client_string, fromname=client_string) response = conn.sr(p)[SAPMS] print("[*] Login performed, server string: %s" % response.fromname) server_string = response.fromname # Send MS_SERVER_CHG packet print("[*] Sending server change packet") p = SAPMS(flag=0x02, iflag=0x01, domain=domain, toname=server_string, fromname=client_string, opcode=0x01, opcode_version=4) response = conn.sr(p)[SAPMS] # Send MS_SERVER_LONG_LIST packet print("[*] Sending server long list packet") p = SAPMS(flag=0x01, iflag=0x01, domain=domain, toname=server_string, fromname=client_string, opcode=0x40, opcode_charset=0x00) conn.send(p) clients = [] def print_client(msg, client): if options.verbose: print("[*] %s %s (host=%s, service=%s, port=%d)" % (msg, client.client.strip(), client.host.strip(), client.service.strip(), client.servno)) # Send MS_SERVER_LST packet print("[*] Retrieving list of current clients") p = SAPMS(flag=0x02, iflag=0x01, domain=domain, toname=server_string, fromname=client_string, opcode=0x05, opcode_version=0x68) response = conn.sr(p)[SAPMS] for client in response.clients: if client.client != client_string: clients.append(("LIST", client)) print_client("Client", client) try: while (True): response = conn.recv()[SAPMS] response.show() if response.opcode == 0x02: # Added client client = response.clients[0] clients.append(("ADD", client)) print_client("Added client", client) elif response.opcode == 0x03: # Deleted client client = response.clients[0] clients.append(("DEL", client)) print_client("Deleted client", client) elif response.opcode == 0x04: # Modified client client = response.clients[0] clients.append(("MOD", client)) print_client("Modified client", client) except SocketError: print("[*] Connection error") except KeyboardInterrupt: print("[*] Cancelled by the user") finally: print("[*] Observed clients:") for action, client in clients: print("\t%s\tclient %s (host=%s, service=%s, port=%d)" % (action, client.client.strip(), client.host.strip(), client.service.strip(), client.servno))
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) # Set release information prop = SAPMSProperty(id=7, release="720", patchno=70, supplvl=0, platform=0) p = SAPMS(flag=0x01, iflag=0x01, toname="MSG_SERVER", fromname=options.client, opcode=0x43, property=prop) print("[*] Setting release information") conn.send(p) # Perform the login enabling the DIA+BTC+ICM services p = SAPMS(flag=0x08, iflag=0x08, msgtype=0x89, toname="-", fromname=options.client) print("[*] Sending login packet") conn.sr(p)[SAPMS] print("[*] Login performed") # Changing the status to starting p = SAPMS(flag=0x01, iflag=0x09, msgtype=0x05, toname="-", fromname=options.client) print("[*] Changing server's status to starting") conn.send(p) # Set IP address p = SAPMS(flag=0x01, iflag=0x01, toname="MSG_SERVER", fromname=options.client, opcode=0x06, opcode_version=0x01, change_ip_addressv4=options.logon_address) print("[*] Setting IP address") response = conn.sr(p)[SAPMS] print("[*] IP address set") response.show() # Set logon information l = SAPMSLogon(type=2, port=3200, address=options.logon_address, host=options.client, misc="LB=3") p = SAPMS(flag=0x01, iflag=0x01, msgtype=0x01, toname="MSG_SERVER", fromname=options.client, opcode=0x2b, logon=l) print("[*] Setting logon information") response = conn.sr(p)[SAPMS] print("[*] Logon information set") response.show() # Set the IP Address property prop = SAPMSProperty(client=options.client, id=0x03, address=options.logon_address) p = SAPMS(flag=0x02, iflag=0x01, toname="-", fromname=options.client, opcode=0x43, property=prop) print("[*] Setting IP address property") response = conn.sr(p)[SAPMS] print("[*] IP Address property set") response.show() # Changing the status to active p = SAPMS(flag=0x01, iflag=0x09, msgtype=0x01, toname="-", fromname=options.client) print("[*] Changing server's status to active") conn.send(p) # Wait for connections try: while True: response = conn.recv()[SAPMS] response.show() except KeyboardInterrupt: print("[*] Cancelled by the user !") # Send MS_LOGOUT packet p = SAPMS(flag=0x00, iflag=0x04, toname="MSG_SERVER", fromname=options.client) print("[*] Sending logout packet") conn.send(p)
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) client_string = options.client # Build MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, toname=client_string, fromname=client_string) # Send MS_LOGIN_2 packet print("[*] Sending login packet") response = conn.sr(p)[SAPMS] print("[*] Login performed, server string: %s" % response.fromname) server_string = response.fromname print("[*] Retrieving current value of parameter: %s" % options.param_name) # Send ADM AD_PROFILE request adm = SAPMSAdmRecord(opcode=0x1, parameter=options.param_name) p = SAPMS(toname=server_string, fromname=client_string, version=4, flag=0x04, iflag=0x05, adm_records=[adm]) print("[*] Sending packet") response = conn.sr(p)[SAPMS] if options.verbose: print("[*] Response:") response.show() param_old_value = response.adm_records[0].parameter print("[*] Parameter %s" % param_old_value) # If a parameter change was requested, send an ADM AD_SHARED_PARAMETER request if options.param_value: print("[*] Changing parameter value from: %s to: %s" % (param_old_value, options.param_value)) # Build the packet adm = SAPMSAdmRecord(opcode=0x2e, parameter="%s=%s" % (options.param_name, options.param_value)) p = SAPMS(toname=server_string, fromname=client_string, version=4, iflag=5, flag=4, adm_records=[adm]) # Send the packet print("[*] Sending packet") response = conn.sr(p)[SAPMS] if options.verbose: print("[*] Response:") response.show() if response.adm_records[0].errorno != 0: print("[*] Error requesting parameter change (error number %d)" % response.adm_records[0].errorno) else: print("[*] Parameter changed for the current session !")
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) # Generate a random client string to differentiate our connection client_string = options.client # Send MS_LOGIN_2 packet print("[*] Sending login packet") p = SAPMS(flag=0x00, iflag=0x08, toname=client_string, fromname=client_string) response = conn.sr(p)[SAPMS] print("[*] Login performed, server string: %s" % response.fromname) server_string = response.fromname # Send MS_SERVER_CHG packet print("[*] Sending server change packet") p = SAPMS(flag=0x02, iflag=0x01, toname=server_string, fromname=client_string, opcode=0x01, opcode_version=4) response = conn.sr(p)[SAPMS] # Send MS_SERVER_LONG_LIST packet print("[*] Sending server long list packet") p = SAPMS(flag=0x01, iflag=0x01, toname=server_string, fromname=client_string, opcode=0x40, opcode_charset=0x00) conn.send(p) clients = [] def print_client(msg, client): if options.verbose: print("[*] %s %s (host=%s, service=%s, port=%d)" % (msg, client.client.strip(), client.host.strip(), client.service.strip(), client.servno)) # Send MS_SERVER_LST packet print("[*] Retrieving list of current clients") p = SAPMS(flag=0x02, iflag=0x01, toname=server_string, fromname=client_string, opcode=0x05, opcode_version=0x68) response = conn.sr(p)[SAPMS] for client in response.clients: if client.client != client_string: clients.append(("LIST", client)) print_client("Client", client) try: while (True): response = conn.recv()[SAPMS] response.show() if response.opcode == 0x02: # Added client client = response.clients[0] clients.append(("ADD", client)) print_client("Added client", client) elif response.opcode == 0x03: # Deleted client client = response.clients[0] clients.append(("DEL", client)) print_client("Deleted client", client) elif response.opcode == 0x04: # Modified client client = response.clients[0] clients.append(("MOD", client)) print_client("Modified client", client) except SocketError: print("[*] Connection error") except KeyboardInterrupt: print("[*] Cancelled by the user") finally: print("[*] Observed clients:") for action, client in clients: print("\t%s\tclient %s (host=%s, service=%s, port=%d)" % (action, client.client.strip(), client.host.strip(), client.service.strip(), client.servno))
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) domain = ms_domain_values_inv[options.domain] # Initiate the connection conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) print("[*] Connected to the message server %s:%d" % (options.remote_host, options.remote_port)) # Set release information prop = SAPMSProperty(id=7, release="720", patchno=70, supplvl=0, platform=0) p = SAPMS(flag=0x01, iflag=0x01, domain=domain, toname="MSG_SERVER", fromname=options.client, opcode=0x43, property=prop) print("[*] Setting release information") conn.send(p) # Perform the login enabling the DIA+BTC+ICM services p = SAPMS(flag=0x08, iflag=0x08, msgtype=0x89, domain=domain, toname="-", fromname=options.client) print("[*] Sending login packet") conn.sr(p)[SAPMS] print("[*] Login performed") # Changing the status to starting p = SAPMS(flag=0x01, iflag=0x09, msgtype=0x05, domain=domain, toname="-", fromname=options.client) print("[*] Changing server's status to starting") conn.send(p) # Set IP address p = SAPMS(flag=0x01, iflag=0x01, domain=domain, toname="MSG_SERVER", fromname=options.client, opcode=0x06, opcode_version=0x01, change_ip_addressv4=options.logon_address) print("[*] Setting IP address") response = conn.sr(p)[SAPMS] print("[*] IP address set") response.show() # Set logon information l = SAPMSLogon(type=2, port=3200, address=options.logon_address, host=options.client, misc="LB=3") p = SAPMS(flag=0x01, iflag=0x01, msgtype=0x01, domain=domain, toname="MSG_SERVER", fromname=options.client, opcode=0x2b, logon=l) print("[*] Setting logon information") response = conn.sr(p)[SAPMS] print("[*] Logon information set") response.show() # Set the IP Address property prop = SAPMSProperty(client=options.client, id=0x03, address=options.logon_address) p = SAPMS(flag=0x02, iflag=0x01, domain=domain, toname="-", fromname=options.client, opcode=0x43, property=prop) print("[*] Setting IP address property") response = conn.sr(p)[SAPMS] print("[*] IP Address property set") response.show() # Changing the status to active p = SAPMS(flag=0x01, iflag=0x09, msgtype=0x01, domain=domain, toname="-", fromname=options.client) print("[*] Changing server's status to active") conn.send(p) # Wait for connections try: while True: response = conn.recv()[SAPMS] response.show() except KeyboardInterrupt: print("[*] Cancelled by the user !") # Send MS_LOGOUT packet p = SAPMS(flag=0x00, iflag=0x04, domain=domain, toname="MSG_SERVER", fromname=options.client) print("[*] Sending logout packet") conn.send(p)
def client_mode(options): """"Implements the niping client running mode :param options: option set from the command line :type options: Values """ times = [] p = Raw("EYECATCHER" + "\x00" * (options.buffer_size - 10)) try: # Establish the connection conn = SAPRoutedStreamSocket.get_nisocket(options.host, options.port, options.route_string) print("") print(datetime.today().ctime()) print("connect to server o.k.") # Send the messages for i in range(options.loops): # Send the packet and grab the response start_time = datetime.now() r = conn.sr(p) end_time = datetime.now() # Check the response if str(r.payload) != str(p): print("[-] Response on message {} differs".format(i)) # Calculate and record the elapsed time times.append(end_time - start_time) # Close the connection properly conn.send(Raw()) conn.close() except SocketError: print("[*] Connection error") except KeyboardInterrupt: print("[*] Cancelled by the user") if times: print("") print(datetime.today().ctime()) print("send and receive {} messages (len {})".format( len(times), options.buffer_size)) # Calculate the stats times = [x.total_seconds() * 1000 for x in times] times_min = min(times) times_max = max(times) times_avg = float(sum(times)) / max(len(times), 1) times_tr = float(options.buffer_size * len(times)) / float(sum(times)) times2 = [x for x in times if x not in [times_min, times_max]] times2_avg = float(sum(times2)) / max(len(times2), 1) times2_tr = float(options.buffer_size * len(times2)) / float( sum(times2)) # Print the stats print("") print("------- times -----") print("avg {:8.3f} ms".format(times_avg)) print("max {:8.3f} ms".format(times_max)) print("min {:8.3f} ms".format(times_min)) print("tr {:8.3f} kB/s".format(times_tr)) print("excluding max and min:") print("av2 {:8.3f} ms".format(times2_avg)) print("tr2 {:8.3f} kB/s".format(times2_tr)) print("")
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) # initiate the connection : print("[*] Initiate connection to message server %s:%d" % (options.remote_host, options.remote_port)) try: conn = SAPRoutedStreamSocket.get_nisocket(options.remote_host, options.remote_port, options.route_string, base_cls=SAPMS) except Exception as e: print(e) print( "Error during MS connection. Is internal ms port %d reachable ?" % options.remote_port) else: print("[*] Connected. I check parameters...") client_string = options.client # Send MS_LOGIN_2 packet p = SAPMS(flag=0x00, iflag=0x08, toname=client_string, fromname=client_string) print("[*] Sending login packet:") response = conn.sr(p)[SAPMS] print("[*] Login OK, Server string: %s\n" % response.fromname) server_string = response.fromname try: with open(options.file_param) as list_param: for line in list_param.readlines(): line = line.strip() # Check for comments or empty lines if len(line) == 0 or line.startswith("#"): continue # Get parameters, check type and expected value # param2c = the SAP parameter to check # check_type = EQUAL, SUP, INF, REGEX, <none> # value2c = the expect value for 'ok' status (param2c, check_type, value2c) = line.split(':') status = '[!]' # create request adm = SAPMSAdmRecord(opcode=0x1, parameter=param2c) p = SAPMS(toname=server_string, fromname=client_string, version=4, flag=0x04, iflag=0x05, adm_records=[adm]) # send request respond = conn.sr(p)[SAPMS] value = respond.adm_records[0].parameter.replace( respond.adm_records[0].parameter.split('=')[0] + '=', '') # Verify if value match with expected value if value == '': value = 'NOT_EXIST' status = '[ ]' elif check_type == 'EQUAL': if value.upper() == str(value2c).upper(): status = '[+]' elif check_type == 'NOTEQUAL': if value.upper() != str(value2c).upper(): status = '[+]' elif check_type == 'REGEX': if re.match(value2c.upper(), value.upper()) and value2c != 'NOT_EXIST': status = '[+]' elif check_type == 'SUP': if float(value) >= float(value2c): status = '[+]' elif check_type == 'INF': if float(value) <= float(value2c): status = '[+]' else: status = '[ ]' # display result print("%s %s = %s" % (status, param2c, value)) except IOError: print("Error reading parameters file !") exit(0) except ValueError: print("Invalid parameters file format or access denied!") exit(0)
class PySAPRoutedStreamSocketTest(unittest.TestCase): test_port = 8005 test_address = "127.0.0.1" test_string = "TEST" * 10 def start_server(self, handler_cls): self.server = SAPNIServerThreaded((self.test_address, self.test_port), handler_cls, bind_and_activate=False) self.server.allow_reuse_address = True self.server.server_bind() self.server.server_activate() self.server_thread = Thread(target=self.server.serve_forever) self.server_thread.start() def stop_server(self): self.server.shutdown() self.server.server_close() self.server_thread.join() def test_saproutedstreamsocket(self): """Test SAPRoutedStreamSocket""" self.start_server(SAPRouterServerTestHandler) sock = socket.socket() sock.connect((self.test_address, self.test_port)) route = [SAPRouterRouteHop(hostname=self.test_address, port=self.test_port), SAPRouterRouteHop(hostname="10.0.0.1", port="3200")] self.client = SAPRoutedStreamSocket(sock, route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) self.client.close() self.stop_server() def test_saproutedstreamsocket_route_error(self): """Test SAPRoutedStreamSocket throwing of SAPRouteException if a route denied return error is received""" self.start_server(SAPRouterServerTestHandler) sock = socket.socket() sock.connect((self.test_address, self.test_port)) route = [SAPRouterRouteHop(hostname=self.test_address, port=self.test_port), SAPRouterRouteHop(hostname="10.0.0.2", port="3200")] with self.assertRaises(SAPRouteException): self.client = SAPRoutedStreamSocket(sock, route=route, router_version=40) self.stop_server() def test_saproutedstreamsocket_error(self): """Test SAPRoutedStreamSocket throwing of Exception if an invalid or unexpected packet is received""" self.start_server(SAPRouterServerTestHandler) sock = socket.socket() sock.connect((self.test_address, self.test_port)) with self.assertRaises(Exception): self.client = SAPRoutedStreamSocket(sock, route=None, router_version=40) self.stop_server() def test_saproutedstreamsocket_getnisocket(self): """Test SAPRoutedStreamSocket get nisocket class method""" self.start_server(SAPRouterServerTestHandler) # Test using a complete route route = [SAPRouterRouteHop(hostname=self.test_address, port=self.test_port), SAPRouterRouteHop(hostname="10.0.0.1", port="3200")] self.client = SAPRoutedStreamSocket.get_nisocket(route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) # Test using a route and a target host/port route = [SAPRouterRouteHop(hostname=self.test_address, port=self.test_port)] self.client = SAPRoutedStreamSocket.get_nisocket("10.0.0.1", "3200", route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) # Test using a route string route = "/H/%s/S/%s/H/10.0.0.1/S/3200" % (self.test_address, self.test_port) self.client = SAPRoutedStreamSocket.get_nisocket(route=route, router_version=40) packet = self.client.sr(self.test_string) self.assertIn(SAPNI, packet) self.assertEqual(packet[SAPNI].length, len(self.test_string) + 4) self.assertEqual(unpack("!I", packet[SAPNI].payload.load[:4]), (len(self.test_string), )) self.assertEqual(packet[SAPNI].payload.load[4:], self.test_string) self.client.close() self.stop_server()