--- /dev/null
+from sender import Sender\r
+import sys\r
+\r
+# before running this program, be sure to run the TCPServer\r
+# also make sure to run the below command to prevent the OS from canceling our connection\r
+# sudo iptables -A OUTPUT -p tcp --tcp-flags PSH PSH -j ACCEPT\r
+# sudo iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP\r
+\r
+# for running tests, you may need to store information on the received sequence number for the server\r
+# you can do that by defining new fields within the sender class/global variables to store such info\r
+\r
+# for non local communication, you can comment the raw sockets setting in sender.py (line 132)\r
+\r
+# run using sudo (!!!) from a command line terminal\r
+# and don't mind/ignore eclipse's red markings.\r
+\r
+if __name__ == "__main__":\r
+ serverPort = 10000\r
+ if len(sys.argv) > 1:\r
+ serverPort = int(sys.argv[1])\r
+ sender = Sender(serverIP="127.0.0.1", networkInterface="lo", isLocal=True, serverPort=serverPort, waitTime=1, isVerbose=1)\r
+ # isLocal is True if the interface is a local one\r
+ response = sender.sendInput("S", 100, 100) \r
+\r
+ # triggers the response SA _ 101 if the server is listening on the specified port\r
+ # if the server isn't listening, there are no responses\r
+ print sender.lastAckReceived\r
+ print sender.isTimeout\r
+ \r
+ # an example for the echo handling server\r
+ if sender.isTimeout == False: # in case something was received\r
+ sender.sendInput("A", 101, sender.lastSeqReceived + 1) # connection is established\r
+ sender.sendInput("A", 101, sender.lastSeqReceived + 1, data = "C") # send some data\r
+ sender.sendInput("A", 102, sender.lastSeqReceived + 1, data = "C") # send some data\r
+ sender.sendInput("FA", 103, sender.lastSeqReceived + 1) # close connection (the echo also closes)\r
+ sender.sendInput("RP", 104, 0) # reset connection\r
+ \r
+ sender.sendReset() # switch sender port\r
--- /dev/null
+from scapy.all import *\r
+\r
+verbose = 1\r
+\r
+def vb_print(msg):\r
+ global verbose\r
+ if verbose == 1:\r
+ print msg\r
+\r
+# the sender sends packets with configurable parameters to a server and retrieves responses\r
+class Sender:\r
+ # information on the SUT\r
+ def __init__(self, serverIP, serverPort=8000,\r
+ networkInterface="lo", isLocal=True, senderPortMinimum=20000,\r
+ senderPortMaximum=40000, portNumberFile="sn.txt",\r
+ isVerbose=0, waitTime=1):\r
+ \r
+ \r
+ # file where the last sender port used is stored\r
+ self.portNumberFile = portNumberFile;\r
+ \r
+ # when choosing a fresh port, a new port is chosen\r
+ # within boundaries defined by the parameters below\r
+ self.senderPortMinimum = senderPortMinimum\r
+ self.senderPortMaximum = senderPortMaximum\r
+ \r
+ # data on sender and server needed to send packets \r
+ self.serverIP = serverIP\r
+ self.serverPort = serverPort\r
+ self.networkInterface = networkInterface\r
+ self.senderPort = self.getNextPort()\r
+ self.isLocal = isLocal\r
+ \r
+ # time to wait for a response from the server before concluding a timeout\r
+ self.waitTime = waitTime\r
+ \r
+ # verbose or not\r
+ self.isVerbose = isVerbose\r
+ \r
+ # variables added so you can easily test the last system response\r
+ self.lastSeqReceived = None\r
+ self.lastAckReceived = None\r
+ self.isTimeout = None\r
+ self.lastFlagsReceived = None\r
+ self.lastDataReceived = None\r
+ \r
+\r
+ # chooses a new port to send packets from\r
+ def refreshNetworkPort(self):\r
+ vb_print("previous local port: " + str(self.senderPort))\r
+ self.senderPort = self.getNextPort()\r
+ vb_print("next local port: " + str(self.senderPort) + "\n")\r
+ return self.senderPort\r
+\r
+ # gets a new port number, an increment of the old within the specified limits. Uses a file.\r
+ def getNextPort(self):\r
+ f = open(self.portNumberFile, "a+")\r
+ f.seek(0)\r
+ line = f.readline()\r
+ if line == '' or int(line) < self.senderPortMinimum:\r
+ networkPort = self.senderPortMinimum\r
+ else:\r
+ networkPort = (int(line) + 1) % self.senderPortMaximum\r
+ f.closed\r
+ f = open(self.portNumberFile, "w")\r
+ f.write(str(networkPort))\r
+ f.closed\r
+ return networkPort\r
+\r
+ # send a packet onto the network with the given parameters, and return the response packet\r
+ # in case of a timeout, returns None, otherwise, returns the tuple (flags, seqNo, ackNo)\r
+ def sendPacket(self, flagsSet, seqNr, ackNr, data = None):\r
+ packet = self.createPacket(flagsSet, seqNr, ackNr, data)\r
+ # consider adding the parameter: iface="ethx" if you don't receive a response. Also consider increasing the wait time\r
+ scapyResponse = sr1(packet, timeout=self.waitTime, verbose=self.isVerbose)\r
+ if scapyResponse is not None:\r
+ scapyResponse.show() \r
+ # ^^ in case you want to show the packet content \r
+ # here is what you store from every packet response\r
+ if Raw not in scapyResponse: \r
+ response = (self.intToFlags(scapyResponse[TCP].flags), scapyResponse[TCP].seq, scapyResponse[TCP].ack, None)\r
+ else: \r
+ response = (self.intToFlags(scapyResponse[TCP].flags), scapyResponse[TCP].seq, scapyResponse[TCP].ack, scapyResponse[Raw].load)\r
+ else:\r
+ response = "Timeout"\r
+ return response\r
+ \r
+ # function that creates packet from data strings/integers \r
+ # data is used for attaching data to the packet\r
+ def createPacket(self, tcpFlagsSet, seqNr, ackNr, data=None):\r
+ vb_print("" + tcpFlagsSet + " " + str(seqNr) + " " + str(ackNr))\r
+ pIP = IP(dst=self.serverIP, flags="DF")\r
+ pTCP = TCP(sport=self.senderPort,\r
+ dport=self.serverPort,\r
+ seq=seqNr,\r
+ ack=ackNr,\r
+ flags=tcpFlagsSet)\r
+ if data is None:\r
+ p = pIP / pTCP\r
+ else:\r
+ p = pIP / pTCP / Raw(load=data)\r
+ return p\r
+ \r
+ # check whether there is a 1 at the given bit-position of the integer\r
+ def checkForFlag(self, x, flagPosition):\r
+ if x & 2 ** flagPosition == 0:\r
+ return False\r
+ else:\r
+ return True\r
+\r
+ # the flags-parameter of a network packets is returned as an int, this function converts\r
+ # it to a string (such as "FA" if the Fin-flag and Ack-flag have been set)\r
+ def intToFlags(self, x):\r
+ result = ""\r
+ if self.checkForFlag(x, 0):\r
+ result = result + "F"\r
+ if self.checkForFlag(x, 1):\r
+ result = result + "S"\r
+ if self.checkForFlag(x, 2):\r
+ result = result + "R"\r
+ if self.checkForFlag(x, 3):\r
+ result = result + "P"\r
+ if self.checkForFlag(x, 4):\r
+ result = result + "A"\r
+ return result\r
+ \r
+ # sends input over the network to the server\r
+ def sendInput(self, input1, seqNr, ackNr, data = None):\r
+ conf.sniff_promisc = False\r
+ conf.iface = self.networkInterface\r
+ if self.isLocal == True:\r
+ conf.L3socket = L3RawSocket # if the connection is local/localhost, use l3 raw sockets\r
+ vb_print("sending: "+ str((input1, seqNr, ackNr, data)))\r
+ response = self.sendPacket(input1, seqNr, ackNr, data)\r
+ \r
+ # updating sender state variables\r
+ if response != "Timeout":\r
+ (self.lastFlagsReceived, self.lastSeqReceived, self.lastAckReceived, self.lastDataReceived) = response\r
+ self.isTimeout = False\r
+ else: \r
+ self.isTimeout = True\r
+ \r
+ # printing response\r
+ vb_print("received: "+ str(response))\r
+ return response\r
+\r
+ # resets the connection by changing the port number. On some OSes (Win 8) upon hitting a certain number of\r
+ # connections opened on a port, packets are sent to close down connections. \r
+ def sendReset(self):\r
+ self.refreshNetworkPort()\r
--- /dev/null
+20233
\ No newline at end of file
--- /dev/null
+import java.net.Socket;\r
+import java.net.SocketException;\r
+\r
+/**\r
+ * Default connection handler. Very basic, does not read or send anything.\r
+ */\r
+public class DefaultHandler implements Runnable {\r
+ private Socket socket;\r
+\r
+ public DefaultHandler(Socket socket) {\r
+ this.socket = socket;\r
+ try {\r
+ socket.setTcpNoDelay(false);\r
+ } catch (SocketException e) {\r
+ // TODO Auto-generated catch block\r
+ e.printStackTrace();\r
+ }\r
+ new Thread(this).start();\r
+ }\r
+\r
+ public void run() {\r
+ {\r
+ // here you can customize operations you want to test though it's not necessary\r
+ System.out.println("new socket opening on " + socket.getLocalPort());\r
+ while (!socket.isOutputShutdown()) {\r
+ try {\r
+ Thread.sleep(100);\r
+ } catch (InterruptedException e) {\r
+ // TODO Auto-generated catch block\r
+ e.printStackTrace();\r
+ }\r
+ }\r
+ }\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+import java.io.InputStreamReader;\r
+import java.io.OutputStreamWriter;\r
+import java.net.Socket;\r
+import java.net.SocketException;\r
+\r
+/**\r
+ * Connection echo handler. Everything it receives is sent back.\r
+ */\r
+public class EchoHandler implements Runnable {\r
+ private Socket socket;\r
+\r
+ public EchoHandler(Socket socket) {\r
+ this.socket = socket;\r
+ try {\r
+ socket.setTcpNoDelay(false);\r
+ } catch (SocketException e) {\r
+ // TODO Auto-generated catch block\r
+ e.printStackTrace();\r
+ }\r
+ new Thread(this).start();\r
+ }\r
+\r
+ public void run() {\r
+ {\r
+ try {\r
+ System.out.println("new socket opening on "\r
+ + socket.getLocalPort());\r
+ InputStreamReader in = new InputStreamReader(\r
+ socket.getInputStream());\r
+ OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());\r
+ int s;\r
+ while(((s=in.read()) != -1)) {\r
+ out.append((char)s);\r
+ out.flush();\r
+ System.out.print((char)s);\r
+ }\r
+ System.out.println();\r
+ System.out.println("Closing handler");\r
+ } catch (Exception e) {\r
+ // TODO Auto-generated catch block\r
+ e.printStackTrace();\r
+ }\r
+\r
+ }\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+import java.net.InetAddress;\r
+\r
+// Run the TCPServer on the the port testPort\r
+public class Main {\r
+ private static final int DEFAULT_PORT = 10000;\r
+ private static final String DEFAULT_ADDRESS = "127.0.0.1";\r
+\r
+ /**\r
+ * Run the program with arguments to set a custom port and address, see the comments in the code\r
+ * @param args\r
+ * @throws Exception\r
+ */\r
+ public static void main(String[] args) throws Exception { \r
+ System.setProperty("java.net.preferIPv4Stack", "true"); // force ipv4\r
+ int port;\r
+ String address;\r
+ if (args.length == 0) {\r
+ // no arguments: default port and address\r
+ port = DEFAULT_PORT;\r
+ address = DEFAULT_ADDRESS;\r
+ } else if (args.length == 1) {\r
+ // one argument for port, default address\r
+ port = Integer.valueOf(args[0]);\r
+ address = DEFAULT_ADDRESS;\r
+ } else if (args.length == 2) {\r
+ // two arguments for port and address\r
+ // for example, call it like 'java Main 10000 127.0.0.1'\r
+ port = Integer.valueOf(args[0]);\r
+ address = args[1];\r
+ } else {\r
+ return;\r
+ }\r
+ TCPServer server = new TCPServer(port, InetAddress.getByName(address));\r
+ \r
+ // comment this for the default handler, otherwise the echo server is used\r
+ server.setHandlerType("echo");\r
+ \r
+ server.handleConnections();\r
+ }\r
+}\r
--- /dev/null
+all: Main.class
+
+%.class: %.java
+ javac $<
+
+clean:
+ $(RM) *.class
--- /dev/null
+import static java.lang.System.out;\r
+\r
+import java.net.InetAddress;\r
+import java.net.NetworkInterface;\r
+import java.net.SocketException;\r
+import java.util.Collections;\r
+import java.util.Enumeration;\r
+\r
+// this utility displays information on addresses and ports, you don't need to use it\r
+public class NetHelper \r
+{\r
+ public static void main(String args[]) throws SocketException {\r
+ Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();\r
+ \r
+ for (NetworkInterface netIf : Collections.list(nets)) {\r
+ out.printf("Display name: %s\n", netIf.getDisplayName());\r
+ out.printf("Name: %s\n", netIf.getName());\r
+ displayInterfaceInformation(netIf);\r
+ displaySubInterfaces(netIf);\r
+ out.printf("\n");\r
+ }\r
+ }\r
+ \r
+ public static NetworkInterface getNetworkInterface(String netName) {\r
+ NetworkInterface netIntf = null;\r
+ try {\r
+ for (Enumeration<NetworkInterface> en = NetworkInterface\r
+ .getNetworkInterfaces(); en.hasMoreElements();) {\r
+ NetworkInterface intf = en.nextElement();\r
+ if (intf.getName().compareToIgnoreCase(netName) == 0) {\r
+ netIntf = intf;\r
+ break;\r
+ }\r
+ }\r
+ } catch (SocketException e) {\r
+ System.out\r
+ .println("Socket Exception failed to find internet addresses!");\r
+ e.printStackTrace();\r
+ System.exit(0);\r
+ }\r
+ return netIntf;\r
+ }\r
+\r
+ public static InetAddress getFirstNonLocalHost(NetworkInterface netIntf) {\r
+ Enumeration<InetAddress> hosts = netIntf.getInetAddresses();\r
+ InetAddress address = null;\r
+ while (hosts.hasMoreElements()) {\r
+ InetAddress host = hosts.nextElement();\r
+ if (!host.isLinkLocalAddress() && !host.isLoopbackAddress()) {\r
+ address = host;\r
+ break;\r
+ }\r
+ }\r
+ return address;\r
+ }\r
+\r
+ \r
+ \r
+ static String getMac(NetworkInterface netint) throws SocketException {\r
+ byte[] mac = netint.getHardwareAddress();\r
+ String rez = "null";\r
+ if(mac != null) {\r
+ StringBuilder sb = new StringBuilder();\r
+ for (int i = 0; i < mac.length; i++) {\r
+ sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); \r
+ }\r
+ rez = sb.toString();\r
+ }\r
+ return rez;\r
+ //System.out.println(sb.toString());\r
+ }\r
+ \r
+ static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {\r
+ out.printf("Display name: %s\n", netint.getDisplayName());\r
+ out.printf("Name: %s\n", netint.getName());\r
+ out.printf("MAC: %s\n", getMac(netint));\r
+ Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();\r
+ for (InetAddress inetAddress : Collections.list(inetAddresses)) {\r
+ out.printf("InetAddress: %s\n", inetAddress);\r
+ out.println("LOCAL:" + Boolean.toString(inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress()));\r
+ }\r
+ out.printf("\n");\r
+ }\r
+\r
+ static void displaySubInterfaces(NetworkInterface netIf) throws SocketException {\r
+ Enumeration<NetworkInterface> subIfs = netIf.getSubInterfaces();\r
+ \r
+ for (NetworkInterface subIf : Collections.list(subIfs)) {\r
+ out.printf("\tSub Interface Display name: %s\n", subIf.getDisplayName());\r
+ out.printf("\tSub Interface Name: %s\n", subIf.getName());\r
+ displayInterfaceInformation(subIf);\r
+ }\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+import java.io.IOException;\r
+import java.net.InetAddress;\r
+import java.net.ServerSocket;\r
+import java.net.Socket;\r
+import java.net.UnknownHostException;\r
+\r
+/**\r
+ * A simple TCP server. Listens for connections, and for each incoming connection,\r
+ * it creates a 'handler' (either echo handler or default handler) which controls\r
+ * that connection\r
+ */\r
+public class TCPServer implements Runnable {\r
+ public ServerSocket server;\r
+ public Socket socket;\r
+ private String handler;\r
+ \r
+ public TCPServer(int port, InetAddress address) {\r
+ try {\r
+ server = new ServerSocket(port, 0, address);\r
+ server.setReuseAddress(true);\r
+ System.out.println("Listening on:\n"\r
+ + server.getInetAddress().toString() + "\nport: "\r
+ + server.getLocalPort());\r
+ } catch (IOException e) {\r
+ e.printStackTrace();\r
+ }\r
+ }\r
+ \r
+ public TCPServer(int port) throws UnknownHostException {\r
+ this(port,InetAddress.getLocalHost());\r
+ }\r
+ \r
+ public void setHandlerType(String handlerClass) {\r
+ this.handler = handlerClass;\r
+ }\r
+ \r
+ private void startHandler(Socket socket) {\r
+ System.out.println("Starting handler '"+ ((handler!=null) ? handler : "default") + "'");\r
+ if("echo".equalsIgnoreCase(handler)) {\r
+ new EchoHandler(socket);\r
+ } else {\r
+ new DefaultHandler(socket);\r
+ }\r
+ }\r
+\r
+ public void handleConnections() {\r
+ Thread thread = new Thread(this);\r
+ thread.start();\r
+ }\r
+\r
+ @Override\r
+ public void run() {\r
+ System.out.println("Waiting for client messages...");\r
+\r
+ // accept all requests for connections\r
+ while (true) {\r
+ try {\r
+ socket = server.accept();\r
+ startHandler(socket);\r
+ } catch (IOException e) {\r
+ //e.printStackTrace();\r
+ System.err.println("Closed socket");\r
+ break;\r
+ }\r
+ }\r
+ }\r
+}\r