Protostar net2 Write-up

net2

#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, &amp;(quad[i]), sizeof(result)) != sizeof(result)) {
          errx(1, ":(\n");
      }
  }

  if(read(0, &amp;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();
}

需要4个随机数,然后求和,只需要将net1.py程序修改一下,获取四次随机数值,然后求和发送就OK了

net2.py源码

from socket import *
from struct import *

s = socket(AF_INET, SOCK_STREAM)
s.connect(("127.0.0.1",2997))
sum = 0
for i in range(4):
        res = s.recv(10)
        print res.encode('hex')
        sum += int(unpack("<I",res)[0])
print sum
s.send(str(pack("<I",sum)))
print (s.recv(1024))
s.close()

运行成功

但是程序执行时因为求和没有进行边界检查,会造成整型溢出

所以在程序求和结束后可以进行一次AND运算

修改后的net2.py

from socket import *
from struct import *

s = socket(AF_INET, SOCK_STREAM)
s.connect(("127.0.0.1",2997))
sum = 0
for i in range(4):
        res = s.recv(10)
        print res.encode('hex')
        sum += int(unpack("<I",res)[0])
sum &amp;= 0xffffffff
print sum
s.send(str(pack("<I",sum)))
print (s.recv(1024))
s.close()

您可能还喜欢...