/*
 * Copyright (C) 2004
 * "Ian (Larry) Latter" <ian dot latter at midnightcode dot org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/*
 * door
 *
 *   -- Generic shell door, originally written October 2004 as
 *	a dirty netcat clone to access the Belkin (broadcom) 54g
 *	wireless router. Reduced to the most basic components to
 *	support simple cross compilation (mipsel for Belkin)
 *
 *   -- Adapted from "gibd00r v3.0" by axess of March 2000
 *
 *   -- Binds a shell to a port, by default we use 2323
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <strings.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>


int main(int argc, char *argv[])
{
	struct sockaddr_in local;
	struct sockaddr_in remote;
	char pwd[256];

	int s,r,size,uid;

	signal(SIGCHLD, SIG_IGN);

	size = sizeof(struct sockaddr_in);
	memset(pwd, 0, 256);

	local.sin_family = AF_INET;
	local.sin_port = htons(2323);
	local.sin_addr.s_addr = INADDR_ANY;

	if((s=socket(AF_INET, SOCK_STREAM, 0)) == 1)
	{
		perror("Socket");
		exit(1);
	}

	if(bind(s, (struct sockaddr *)&local, sizeof(struct sockaddr)) == -1)
	{
		perror("Port");
		exit(1);
	}

	if(listen(s, 5) == -1)
	{
		perror("Listen");
		exit(1);
	}

	uid = getuid();

	for(;;)
	{
		if((r=accept(s, (struct sockaddr *)&remote, &size)) == -1)
		{
			perror("accept");
			exit(1);
		}

		if(!fork())
		{
			close(0);
			close(1);
			close(2);
			dup2(r,0);
			dup2(r,1);
			dup2(r,2);

			chdir("/");

			printf("Welcome to -door- from midnightcode.org\n\n");
			if(getcwd(pwd, 255) != NULL)
			{
				printf("You are user id [%d] in "
				       "directory [%s]\n", uid, pwd);
			} else {
				printf("You are user id [%d]\n", uid, pwd);
			}
			printf("You have stdin, stdout and stderr on this "
			       "socket\n");
			printf("__________________________"
			       "_________________________\n\n");
			execl("/bin/sh","/bin/sh","-i",(char *)0);
			close(r);
			exit(0);
		}
		close(r);
	}
}

