Protostar – net2

Information

This code tests the ability to add up 4 unsigned 32-bit integers. Hint: Keep in mind that it wraps.

This level is at /opt/protostar/bin/net2

Source code

#include "../common/common.c"

#define NAME "net2"
#define UID 997
#define GID 997
#define PORT 2997

void run()
{
  unsigned int quad[4];
  int i;
  unsigned int result, wanted;

  result = 0;
  for(i = 0; i < 4; i++) {
      quad[i] = random();
      result += quad[i];

      if(write(0, &(quad[i]), sizeof(result)) != sizeof(result)) {
          errx(1, ":(\n");
      }
  }

  if(read(0, &wanted, sizeof(result)) != sizeof(result)) {
      errx(1, ":<\n");
  }


  if(result == wanted) {
      printf("you added them correctly\n");
  } else {
      printf("sorry, try again. invalid\n");
  }
}

int main(int argc, char **argv, char **envp)
{
  int fd;
  char *username;

  /* Run the process as a daemon */
  background_process(NAME, UID, GID); 
  
  /* Wait for socket activity and return */
  fd = serve_forever(PORT);

  /* Set the client socket to STDIN, STDOUT, and STDERR */
  set_io(fd);

  /* Don't do this :> */
  srandom(time(NULL));

  run();
}

Solution

Again, a server is waiting on the port 2997. It sends 4 integer in little endian format and it waits in return the sum of them in little endian format..

I use the following python script :

#!/usr/bin/python

import socket
import struct

host='192.168.0.46'
port=2997

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((host,port))

number = 0
sum = 0

for i in range(4):
    recv = sock.recv(4)
	#convert to unsigned integer
	number = int(struct.unpack("<I",recv)[0])
	recv = ''
	sum += number
	number = 0

# handle error
sum &= 0xffffffff

# convert to little endian
sum_packed = struct.pack("<I",sum)

sock.send(sum_packed)

recv = sock.recv(1024)

print recv

sock.close()

Let’s fire up :

$ python net2.py
you added them correctly

That’s it, net2 is done.


Laisser un commentaire