#include #include #include #include #include #include #include #include #define SEMTEX "semtex.labs.overthewire.org" #define X86PORT "24000" #define SEMTEXFILE "result.2" #define DEBUG int create_socket(int sockfd, struct addrinfo *servinfo) { if ((sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1) { perror("socket"); return -1; } return sockfd; } int create_addrinfo(struct addrinfo *hints, struct addrinfo **servinfo) { int status = -1; memset(hints, 0, sizeof(hints)); hints->ai_family = AF_INET; hints->ai_socktype = SOCK_STREAM; hints->ai_flags = AI_PASSIVE; if ((status = getaddrinfo(SEMTEX,X86PORT, hints, servinfo)) != 0) { fprintf(stderr,"getaddrinfo: %s\n", gai_strerror(status)); return -1; } return status; } void write_bytes(unsigned char *bytes, FILE *fp, int len) { int i = 0,j = 0; size_t bytes_write = 0; int blen = (len/2)+1; unsigned char *buffer = NULL; if (len > 0) { buffer = (unsigned char *)calloc(blen,sizeof(unsigned char)); if (!buffer) { perror("calloc"); exit(-1); } if (len > 1) { j = 0; i = 0; #ifdef DEBUG puts("len > 1"); #endif for (i = 0; i < len/2 ; i++) { buffer[i] = bytes[i*2]; } } else { #ifdef DEBUG puts("len < 1"); #endif buffer[0] = bytes[0]; } #ifdef DEBUG printf("[DEBUG:%s:] Writing %d (blen) bytes (%u len) %d %% 2 = %d\n%s\n",__FUNCTION__, sizeof(unsigned char) * blen, len, len,len / 2, buffer); #endif if ((bytes_write = fwrite(buffer, sizeof(unsigned char) * blen ,1,fp)) == 0) { perror("fwrite"); exit(0); } free(buffer); } } void recv_loop(int sockfd) { int bytes_read = 0; unsigned char *bytes_recv = (unsigned char *)calloc(255,sizeof(unsigned char)); FILE *fp = fopen(SEMTEXFILE,"w"); if (!fp) { perror("fopen"); exit(0); } while((bytes_read = recv(sockfd, bytes_recv, sizeof(unsigned char)*255, 0)) != 0) { #ifdef DEBUG printf("[DEBUG:%s] read %d bytes \n",__FUNCTION__, bytes_read); #endif write_bytes(bytes_recv, fp, bytes_read); } free(bytes_recv); fclose(fp); } int main() { int sockfd = -1; struct addrinfo hints; struct addrinfo *servinfo; if (create_addrinfo(&hints, &servinfo) == -1) return -1; #ifdef DEBUG puts("[+] getaddrinfo successfully called"); #endif sockfd = create_socket(sockfd, servinfo); #ifdef DEBUG puts("[+] Got a socket"); #endif if ((connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen)) == -1) { perror("connect"); return -1; } #ifdef DEBUG puts("[+] Successfully connected"); #endif recv_loop(sockfd); close(sockfd); free(servinfo); return 0; }