Recent Entries 10
- pattern minor 112d agoSending a file over a socket with AES encryptionI'm not sure what's the best way to deal with streams that need to be closed whenever I'm done using them? Usually the need to also catch the exception inside the `finally` statement is very, very annoying. Am I doing this right? ``` public class FileSender { public static final String KEY = "00000000000000000000000000000000"; public static final String ALGORITHM = "AES"; public static final String FILE = "C:\\Users\\Andres\\Desktop\\file.txt"; public static final String HASH_ALG = "MD5"; private String filePath; private String serverMachine; private int serverPort; public FileSender(String filePath, String serverMachine, int serverPort){ this.filePath = filePath; this.serverMachine = serverMachine; this.serverPort = serverPort; } public void sendFile(){ CipherOutputStream cipherOut = null; Socket client = null; String checkSum; try { System.out.println("Running client ..."); client = connectToServer(); checkSum = getHashChecksum(); cipherOut = initCipherStream(client); transferData(cipherOut, checkSum); } catch (Exception e) { System.out.println(e.getMessage()); } finally { } } private String getHashChecksum() { FileInputStream fis = null; try { MessageDigest md = MessageDigest.getInstance(HASH_ALG); fis = new FileInputStream(this.filePath); byte[] byteArray = new byte[1024]; int bytesCount = 0; while ((bytesCount = fis.read(byteArray)) >= 0) md.update(byteArray, 0, bytesCount); byte[] hash = md.digest(); fis.close(); return String.format("%032x",new BigInteger(1, hash)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Error in checksum"); } finally { try {
- pattern minor 112d agoFlexible socket frameworkI'm working on an async socket server, would really appreciate any critique and some advices regarding the place where i process received messages. My interfaces are as follows: IAsyncClient ``` public delegate void ConnectedHandler(IAsyncClient a); public delegate void ClientMessageReceivedHandler(IAsyncClient a, List msg); public delegate void ClientMessageSubmittedHandler(IAsyncClient a, bool close = false); public delegate void ClientReceivingStarted(); public delegate void ClientErrorHandler(string errorMessage); public interface IAsyncClient : IDisposable { bool IsConnected { get; } IClientChainsContainer ClientChainsContainer { get; set; } event ConnectedHandler Connected; event ClientMessageReceivedHandler MessageReceived; event ClientMessageSubmittedHandler MessageSubmitted; event ClientReceivingStarted ReceivingStarted; event ClientErrorHandler Error; void InvokeConnected(IAsyncClient a); void InvokeMessageReceived(IAsyncClient a, List msg); void InvokeMessageSubmitted(IAsyncClient a, bool close = false); void InvokeReceivingStarted(); void InvokeError(string errorMessage); Task StartClient(); void StartReceiving(); void SetId(Guid clientId); Task Send(IProcessable message, bool close = false); Task SendSomeCommand(); Task SendAlarm(); } ``` IAsyncSocketListener ``` public delegate void MessageReceivedHandler(Guid id, List msg); public delegate void MessageSubmittedHandler(Guid id, bool close); public interface IAsyncSocketListener : IDisposable { event MessageReceivedHandler MessageReceived; event MessageSubmittedHandler MessageSubmitted; IServerChainsContainer ServerChainsContainer { get; set; } void StartListening(); bool IsConnected(Guid id); Task Send(Guid id, IProcessable msg, bool close = false); Task SendToAll(IProcessable msg, bool close = false); Task SendToAllExcept(List exludedClientIds, IProcessable msg, bool close =
- pattern minor 112d agoTCP/IP multithread chatI'm learning C# and would love to receive some feedback for my code. Server: ``` class Program { const char EoM = (char)3; //End of Messege mark const char separator = (char)29; // main delimiter const char clientSeparator = (char)31; //client delimiter enum broadcastStatus { connect, disconnect }; static readonly object _lock = new object(); static List client_list = new List(); static int count = 0; static void Main(string[] args) { Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(IPAddress.Any, 7000)); serverSocket.Listen(1); Console.WriteLine(""); while (true) { Connection connection = new Connection(); connection.socket = serverSocket.Accept(); Thread connectionThread = new Thread(() => handle_connection(connection)); connectionThread.Start(); } } static void handle_connection(Connection connection) { //get client nickname connection.nickname = receive_data(connection); if (authenticate(connection.nickname)) { //adding to list broadcast_status(connection.nickname, broadcastStatus.connect); lock (_lock) client_list.Add(connection); count++; // send ok to client && send client list string response = "" + separator + client_list_to_string(); send_data(connection, response); try { //listening and broadcasting to others clients while (true) { string data = receive_data(connection); broadcast_msg(connection.nickname, data); } } catch (ConnectionEndException) { lock (_lock) client_list.Remove(connection);
- pattern minor 112d agoWriting a chunk of a file to a socket in SwiftI'm writing a chunk of a file from an offset to a socket. This is my implementation and it's working OK from my tests. Any comments or speed improvements? ``` private func sendChunk(_ source: Int32, _ target: Int32, _ offset: off_t, _ count: UInt64) -> Int64 { let bufferSize:Int = 1024 var buffer = [UInt8](repeating: 0, count: bufferSize) var writed:UInt64 = 0 var read:Int = 0 while true { let remaining = Int(count - writed) if remaining 0 else {return Int64(read)} var writeCounter = 0 while writeCounter 0 else {return Int64(writeResult)} writeCounter = writeCounter + writeResult writed += UInt64(writeCounter) } } } ```
- pattern minor 112d agoNetwork protocol using TCP, sending images through socketsI would like to ask about your opinion about my code. The idea is simple: I designed my own protocol, where client asks the server about the image, and the server sends the image, following the below steps (this is the actual protocol I wanted to implement): ``` CLIENT SERVER GET\r\n -----------------------------------> OK\r\n SIZE 1024\r\n IMG_DATA with when image sending is over EOF\r\n <----------------------------------- ``` Everything works (it seems so) but I would like to ask about what else I could possibly improve here. - Does the implementation reflects in 100% what I wanted to achieve in my protocol flow? - Are the steps implemented as I wanted them to be in my protocol? client.py: ``` #!/usr/bin/env python import socket import sys HOST = '127.0.0.1' PORT = 6666 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (HOST, PORT) sock.connect(server_address) fname = 'fromserver.png' try: sock.sendall("GET\r\n") data = sock.recv(4096) if data: txt = data.strip() print '--%s--' % txt if txt == 'OK': sock.sendall("GET_SIZE\r\n") data = sock.recv(4096) if data: txt = data.strip() print '--%s--' % txt if txt.startswith('SIZE'): tmp = txt.split() size = int(tmp[1]) print '--%s--' % size sock.sendall("GET_IMG\r\n") myfile = open(fname, 'wb') amount_received = 0 while amount_received < size: data = sock.recv(4096) if not data : break amount_received += len(data) print amount_received txt
- pattern major 112d agoSimple and effective port checker in C++Intro A couple of weeks ago I finished a Python implementation of a multithreaded port checker and I wasn't quite happy with the result I've got (speed). I needed it to be faster, so I've built another one using CPP (and a bit of C). Here is the Python code, if anyone wants to see it. At the moment, I didn't implemented the threading module for my script because I'd like to get some advice on what would be the wisest choice (while asking for an answer which adds this part is forbidden here, I wouldn't mind seeing an example of it) Description The program takes as command line arguments the following: - a text file which contains one domain name per line - the port number for which the above domains will be checked - number of threads - the timeout - a text file where the domains which have the port open will be written (along with their IP address) e.g: `google.com:172.217.22.46` What the program is currently doing is to translate each domain into an IP address, and check if the given port is opened or not. If it's opened, write the `domain:ip` to an output file. The program can be compiled and run using the below commands: ``` g++ port_checker.cpp -o checker ./checker domains.txt 80 2 2 output.txt ``` Code ``` #include #include #include #include #include #include #include std::vector get_domains_from_file(std::string domains_file) { std::vector domains_array; std::ifstream file(domains_file); std::string domain; if (!file.is_open()) { std::cerr > domain) { domains_array.push_back(domain); } return domains_array; } int main(int argc, char *argv[]) { struct hostent *h; struct sockaddr_in servaddr; int sd, rval; if (argc != 6) { std::cerr domains = get_domains_from_file(domains_file); std::ofstream myfile; myfile.open(output_file); for (int i = 0; i h_addr)) h_addr, h -> h_length); rval = connect(sd, (struct sockaddr *) &servaddr, sizeof(servaddr));
- pattern moderate 112d agoPython bot to answer mathematical questions for a remote serverThe MSP Tech Club puts on an annual CTF, available here. I've worked on a solution but was wondering if there's a better way to write it or if I have any particular bad habits showing themselves? The challenge is to write a script to connect to a server and answer math problems presented to it, it looks like this: Answering 500 questions in a small enough timeframe reveals this: I've left the netcat server in the code to allow for testing of changes. Since the CTF is public facing I don't think this poses an issue but feel free to remove if I'm breaking any S/O rules. ``` #!/usr/bin/python3 import socket import re if __name__ == '__main__': client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('195.154.53.62', 1337)) while True: data = b'' while True: chunk = client.recv(4096) data += chunk if len(chunk) < 4096: break # our flag contains ALEXCTF, once it's revealed print recevied data and exit if 'ALEXCTF' in data.decode('utf-8'): print(data.decode('utf-8')) break # \d+ matches a digit (equal to [0-9]) # .{3} matches any character, except line terminators exactly three times m = re.search('\d+.{3}\d+', data.decode('utf-8')) expression = m.group(0) #properly handle division if '/' in expression: expression = expression.replace('/', '//') result = eval(expression) #print results to screen to see script progress print(expression + ' = ' + str(result)) #encode and transfer data = str(result).encode('utf-8') + b'\n' client.send(data) ```
- pattern minor 112d agoLet's check that domain portIntro This simple script will allow me to check for a specific opened port on a list of domains that I own. Instead of manually doing this check, I found Python a pretty good idea for such a task. After profiling my code, I found out that `def check_for_open_ports():` is really slow. It takes about 0:01:16.799242 seconds for 4 domains. I wondered if there's a good / recommended way of improving this (maybe multithreading / multiprocessing). While asking for an answer which implements one of the above two methods is forbidden here, I wouldn't mind seeing one. I know that one shall use multiprocessing when there're I/O bound tasks which makes me believe I might go with a multithreading solution. The code ``` from socket import gethostbyname, gaierror, error, socket, AF_INET, SOCK_STREAM from sys import argv, exit import re DOMAINS_FILE = argv[1] PORT = argv[2] OUTPUT_FILE = argv[3] def get_domains(): """ Return a list of domains from domains.txt """ domains = [] if len(argv) != 4: exit("Wrong number of arguments\n") try: with open(DOMAINS_FILE) as domains_file: for line in domains_file: domains.append(line.rstrip()) except IOError: exit("First argument should be a file containing domains") return domains def check_domain_format(domain): """ This function removes the beginning of a domain if it starts with: www. http:// http://www. https:// https://www. """ clear_domain = re.match(r"(https?://(?:www\.)?|www\.)(.*)", domain) if clear_domain: return clear_domain.group(2) return domain def transform_domains_to_ips(): """ Return a list of ips specific to the domains in domains.txt """ domains = get_domains() domains_ip = [] for each_domain in domains: each_domain = check_domain_format(each_domain) try: domains_ip.append(gethostbyname(each_domain)) except gaierror:
- pattern minor 112d agoSubclass of socket with optional TLS``` import ssl from socket import socket class testsock(socket): def __init__(self, tls=True): super(testsock, self).__init__() self.connect(('192.168.0.1', 443)) if tls: self = ssl.wrap_socket(self) # Ugly "handover" testsock(tls=True) ``` This code works, it's the second ugliest bodge I've done as of today. But it works with the behavior I desire, that `.send()` and `.close()` etc are "intact". However, if I ever try to add any other values to my custom class `testsock` those will effectively be gone, since I replace `self` with whatever `wrap_socket` spits out. I could use something that looks like this: ``` class testsock(): def __init__(self, tls=True): self.s = socket() ... self.s = ssl.wrap_socket(self.s) def send(self, data): self.s.send(data) ``` But that goes against the elegance of inheriting the socket object and not having to create all the functions you'd expect out of a ordinary socket. (I know, lazy programming, but it looks cleaner without all the definitions). I could probably iterate over all the `.__dict__` or inspect.getmembers() functions and replace them with the matching available items from `wrap_socket`, but that would also cause for concerns later on, but it would look something like: ``` for name, obj in inspect.getmembers(self): print(name, obj) ``` It would yield something like: ``` close > ``` I'm not sure how I'd get `socket` from this, `obj.__class__.__name__` doesn't yield this. If I could some how get `socket` from the object I would know that it's a socket() bound method, and replace the corresponding method from `wrap_socket()` return. I've heard of metaclass programming, and I'm having a go at it. But my question is, out of all the options - Which would be the best according to the community? Would it be possible to inline-replace the inherited socket object with whatever `ssl.wrap_socket` returns?
- pattern minor 112d agoSocket client in C using threadsI'm working on socket programming in C. I have no problem with usage the threads. This all works fine but I'm new in this area. I wrote this code in client.c but is there any misused code or something may cause problems in the future? My client sends a message to the server and client can receive it. There are 2 major operations: recv and send. CLIENT ``` #include #include #include // for inet_addr #include #include #include #include void *sendMessage(void *sock_desc) { //Send some data while (1) { char message[2000]; printf("%s","> "); scanf("%[^\n]%*c", message); fflush(stdin); if (send(*((int *) sock_desc), message, strlen(message) + 1, 0) < 0) { puts("Send failed"); } } } void *receiveMessage(void *sock_desc) { while (1) { char server_reply[2000]; if (recv(*((int *) sock_desc), server_reply, 2000, 0) < 0) { puts("recv failed"); } //Receive a reply from the server printf("\033[32;1m %s \033[0m\n", server_reply); } } int main(int argc, char *argv[]) { int sock; struct sockaddr_in server; //char message[2000], server_reply[2000]; //Create socket sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { printf("Could not create socket"); } server.sin_addr.s_addr = inet_addr("127.0.0.1"); server.sin_family = AF_INET; server.sin_port = htons(8888); //Connect to remote server if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) { perror("Connect failed. Error"); return 1; } puts("Connected to server\n"); int *new_sock; new_sock = malloc(1); *new_sock = sock; //keep communicating with server pthread_t send_thread, receive_thread; pthread_create(&send_thread, NULL, sendMessage, (void *) new_sock); pthread_create(&receive_thread, NULL, receiveMessage, (void *) new_s