summaryrefslogtreecommitdiff
path: root/mactelnetd.c
blob: afb89fbdad15279e8b769f17df6e8e1ca0d30422 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/*
    Mac-Telnet - Connect to RouterOS routers via MAC address
    Copyright (C) 2010, Håkon Nessjøen <haakon.nessjoen@gmail.com>

    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.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#define _XOPEN_SOURCE 600
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ether.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <linux/if_ether.h>
#include <sys/ioctl.h>
#include <pwd.h>
#include "md5.h"
#include "protocol.h"
#include "udp.h"
#include "console.h"
#include "devices.h"
#include "users.h"
#include "config.h"
#include <utmp.h>

int sockfd;
int insockfd;
int deviceIndex;

struct in_addr sourceip; 
struct in_addr destip;
int sourceport;

unsigned char trypassword[17];

/* Protocol data direction */
unsigned char mt_direction_fromserver = 1;

/* Anti-timeout is every 10 seconds. Give up after 15. */
#define MT_CONNECTION_TIMEOUT 15

/* Connection states */
#define STATE_AUTH 1
#define STATE_CLOSED 2
#define STATE_ACTIVE 3

/** Connection struct */
struct mt_connection {
	unsigned short seskey;
	unsigned short incounter;
	unsigned short outcounter;
	time_t lastdata;
	int terminalMode;
	unsigned char username[30];
	unsigned char srcip[4];
	unsigned char srcmac[6];
	unsigned short srcport;
	unsigned char dstmac[6];
	unsigned char enckey[16];
	int state;
	int ptsfd;
	int slavefd;
	int pid;
	unsigned short terminal_width;
	unsigned short terminal_height;
	unsigned char terminal_type[30];

	int waitForAck;

	struct mt_connection *next;
};

struct mt_connection *connections_head = NULL;

void list_addConnection(struct mt_connection *conn) {
	struct mt_connection *p;
	struct mt_connection *last;
	if (connections_head == NULL) {
		connections_head = conn;
		connections_head->next = NULL;
		return;
	}
	for (p = connections_head; p != NULL; p = p->next) {last = p;}
	last->next = conn;
	conn->next = NULL;
}

void list_removeConnection(struct mt_connection *conn) {
	struct mt_connection *p;
	struct mt_connection *last;
	if (connections_head == NULL)
		return;

	if (conn->state == STATE_ACTIVE && conn->ptsfd > 0) {
		close(conn->ptsfd);
	}
	if (conn->state == STATE_ACTIVE && conn->slavefd > 0) {
		close(conn->slavefd);
	}


	if (connections_head == conn) {
		connections_head = conn->next;
		free(conn);
		return;
	}

	for (p = connections_head; p != NULL; p = p->next) {
		if (p == conn) {
			last->next = p->next;
			free(p);
			return;
		}
		last = p;
	}
}

struct mt_connection *list_findConnection(unsigned short seskey, unsigned char *srcmac) {
	struct mt_connection *p;

	if (connections_head == NULL)
		return NULL;

	for (p = connections_head; p != NULL; p = p->next) {
		if (p->seskey == seskey && memcmp(srcmac, p->srcmac, 6) == 0) {
			return p;
		}
	}

	return NULL;
}

int sendUDP(const struct mt_connection *conn, const struct mt_packet *data) {
	return sendCustomUDP(sockfd, 2, conn->dstmac, conn->srcmac, &sourceip, sourceport, &destip, conn->srcport, data->data, data->size);
}

void motd() {
	FILE *fp;
	int c;
	
	if ((fp = fopen("/etc/motd", "r"))) {
		while ((c = getc(fp)) != EOF) {
			putchar(c);
		}
		fclose(fp);
	}
}

void adduwtmp(struct mt_connection *curconn) {
	struct utmp utent;
	pid_t pid;

	pid = getpid();
	
	char *line = ttyname(curconn->slavefd);
	if (strncmp(line, "/dev/", 5) == 0)
		line += 5;

	/* Setup utmp struct */
	memset((void *) &utent, 0, sizeof(utent));
	utent.ut_type = USER_PROCESS;
	utent.ut_pid = pid;
	strncpy(utent.ut_user, curconn->username, sizeof(utent.ut_user));
	strncpy(utent.ut_line, line, sizeof(utent.ut_line));
	strncpy(utent.ut_id, utent.ut_line + 3, sizeof(utent.ut_id));
	strncpy(utent.ut_host,ether_ntoa((const struct ether_addr *)curconn->dstmac), sizeof(utent.ut_host));
	time(&utent.ut_time);
	
	/* Update utmp and/or wtmp */
	setutent();
	pututline(&utent);
	endutent();
	updwtmp(_PATH_WTMP, &utent);
}

void doLogin(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr) {
	struct mt_packet pdata;
	unsigned char md5sum[17];
	unsigned char md5data[100];
	struct mt_credentials *user;
	char shouldDoLogin = 0;
	char *slavename;

	/* Reparse user file before each login */
	readUserfile();

	if ((user = findUser(curconn->username)) != NULL) {
		md5_state_t state;
		/* Concat string of 0 + password + encryptionkey */
		md5data[0] = 0;
		strncpy(md5data + 1, user->password, 82);
		memcpy(md5data + 1 + strlen(user->password), curconn->enckey, 16);

		/* Generate md5 sum of md5data with a leading 0 */
		md5_init(&state);
		md5_append(&state, (const md5_byte_t *)md5data, strlen(user->password) + 17);
		md5_finish(&state, (md5_byte_t *)md5sum + 1);
		md5sum[0] = 0;

		initPacket(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
		curconn->outcounter += addControlPacket(&pdata, MT_CPTYPE_END_AUTH, NULL, 0);
		sendUDP(curconn, &pdata);

		if (curconn->state == STATE_ACTIVE)
			return;
	} else {
		//printf("User %s not found\n", curconn->username);
	}

	if (user != NULL && memcmp(md5sum, trypassword, 17) == 0) {
		curconn->state = STATE_ACTIVE;
	} else {
		/* TODO: syslog */
		printf("(%d) Invalid login by %s.\n", curconn->seskey, curconn->username);

		initPacket(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
		curconn->outcounter += addControlPacket(&pdata, MT_CPTYPE_PLAINDATA, "Login FAILED!\r\n", 15);

		sendUDP(curconn, &pdata);
		curconn->state = STATE_CLOSED;

		/* Should acctually wait for ACK of the previous packet before sending this */
		initPacket(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
		sendUDP(curconn, &pdata);

		/* TODO: should wait some time (not with sleep) before returning, to minimalize brute force attacks */
		return;
	}

	/* Enter terminal mode */
	curconn->terminalMode = 1;
	
	/* Open pts handle */
	curconn->ptsfd = posix_openpt(O_RDWR);
	if (curconn->ptsfd == -1 || grantpt(curconn->ptsfd) == -1 || unlockpt(curconn->ptsfd) == -1) {
			perror("openpt");
			initPacket(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
			addControlPacket(&pdata, MT_CPTYPE_PLAINDATA, "Terminal error\r\n", 15);
			sendUDP(curconn, &pdata);
			curconn->state = STATE_CLOSED;
			initPacket(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
			sendUDP(curconn, &pdata);
			return;
	}

	/* Get file path for our pts */
	slavename = ptsname(curconn->ptsfd);
	if (slavename != NULL) {
		pid_t pid;
		curconn->slavefd = open(slavename, O_RDWR);
		if (curconn->slavefd == -1) {
			perror ("Error opening the slave");
			list_removeConnection(curconn);
			return;
		}

		/* Don't let child process inherit slavefd */
		fcntl (curconn->slavefd, F_SETFD, FD_CLOEXEC);
		if ((pid = fork()) == 0) {			
			struct passwd *user = (struct passwd *)getpwnam(curconn->username);
			if (user == NULL) {
				printf("(%d) Login ok, but local user not accessible (%s).\n", curconn->seskey, curconn->username);
				initPacket(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
				addControlPacket(&pdata, MT_CPTYPE_PLAINDATA, "User not found\r\n", 16);
				sendUDP(curconn, &pdata);
				curconn->state = STATE_CLOSED;
				initPacket(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
				sendUDP(curconn, &pdata);
				return;
			}

			/* Add login information to utmp/wtmp */
			adduwtmp(curconn);

			/* Set user id/group id */
			if ((setgid(user->pw_gid) != 0) || (setuid(user->pw_uid) != 0)) {
				printf("(%d) Could not log in %s (%d:%d): setuid/setgid: %s\n", curconn->seskey, curconn->username, user->pw_uid, user->pw_gid, strerror(errno));
				initPacket(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
				addControlPacket(&pdata, MT_CPTYPE_PLAINDATA, "Internal error\r\n", 16);
				sendUDP(curconn, &pdata);
				curconn->state = STATE_CLOSED;
				initPacket(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
				sendUDP(curconn, &pdata);
				return;
			}

			/* TODO: syslog */
			printf("(%d) User %s logged in.\n", curconn->seskey, curconn->username);

			/* Initialize terminal environment */			
			setenv("USER", user->pw_name,1);
			setenv("HOME", user->pw_dir, 1);
			setenv("SHELL", user->pw_shell, 1);
			setenv("TERM", curconn->terminal_type, 1);
			close(sockfd);
			close(insockfd);
			setsid();

			/* Redirect STDIN/STDIO/STDERR */
			close(0);
			dup(curconn->slavefd);
			close(1);
			dup(curconn->slavefd);
			close(2);
			dup(curconn->slavefd);
			close(curconn->slavefd);
			close(curconn->ptsfd);

			/* Set controlling terminal */
			ioctl (0, TIOCSCTTY, 1);

			/* Display MOTD */
			motd();

			/* Spawn shell */
			chdir(user->pw_dir);
			execl (user->pw_shell, user->pw_shell, (char *) 0);
			exit(0); // just to be sure.
		}
		close(curconn->slavefd);
		curconn->pid = pid;
		setTerminalSize(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
	}
	
}

void handleDataPacket(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr, int data_len) {
	struct mt_mactelnet_control_hdr cpkt;
	struct mt_packet pdata;
	unsigned char *data = pkthdr->data;
	int gotUserPacket = 0;
	int gotPassPacket = 0;
	int gotWidthPacket = 0;
	int gotHeightPacket = 0;
	int success;

	/* Calculate how much more there is in the packet */
	success = parseControlPacket(data, data_len - MT_HEADER_LEN, &cpkt);

	while (success) {
		if (cpkt.cptype == MT_CPTYPE_BEGINAUTH) {

			int plen,i;
			for (i = 0; i < 16; ++i) {
				curconn->enckey[i] = rand() % 256;
			}

			initPacket(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
			plen = addControlPacket(&pdata, MT_CPTYPE_ENCRYPTIONKEY, (curconn->enckey), 16);
			curconn->outcounter += plen;

			sendUDP(curconn, &pdata);

			memset(trypassword, 0, sizeof(trypassword));

		} else if (cpkt.cptype == MT_CPTYPE_USERNAME) {

			memcpy(curconn->username, cpkt.data, cpkt.length > 29 ? 29 : cpkt.length);
			curconn->username[cpkt.length > 29 ? 29 : cpkt.length] = 0;
			gotUserPacket = 1;

		} else if (cpkt.cptype == MT_CPTYPE_TERM_WIDTH) {

			curconn->terminal_width = cpkt.data[0] | (cpkt.data[1]<<8);
			gotWidthPacket = 1;

		} else if (cpkt.cptype == MT_CPTYPE_TERM_HEIGHT) {

			curconn->terminal_height = cpkt.data[0] | (cpkt.data[1]<<8);
			gotHeightPacket = 1;

		} else if (cpkt.cptype == MT_CPTYPE_TERM_TYPE) {

			memcpy(curconn->terminal_type, cpkt.data, cpkt.length > 29 ? 29 : cpkt.length);
			curconn->terminal_type[cpkt.length > 29 ? 29 : cpkt.length] = 0;

		} else if (cpkt.cptype == MT_CPTYPE_PASSWORD) {

			memcpy(trypassword, cpkt.data, 17);
			gotPassPacket = 1;

		} else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) {

			/* relay data from client to shell */
			if (curconn->state == STATE_ACTIVE && curconn->ptsfd != -1) {
				write(curconn->ptsfd, cpkt.data, cpkt.length);
			}

		} else {
			printf("(%d) Unhandeled control packet type: %d\n", curconn->seskey, cpkt.cptype);
		}

		/* Parse next controlpacket */
		success = parseControlPacket(NULL, 0, &cpkt);
	}
	
	if (gotUserPacket && gotPassPacket) {
		doLogin(curconn, pkthdr);
	}
	
	if (curconn->state == STATE_ACTIVE && (gotWidthPacket || gotHeightPacket)) {
		setTerminalSize(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);

	}
}

void handlePacket(unsigned char *data, int data_len, const struct sockaddr_in *address) {
	struct mt_mactelnet_hdr pkthdr;
	struct mt_connection *curconn;
	struct mt_packet pdata;

	parsePacket(data, &pkthdr);

	switch (pkthdr.ptype) {

		case MT_PTYPE_SESSIONSTART:
			printf("(%d) New connection\n", pkthdr.seskey);
			curconn = calloc(1, sizeof(struct mt_connection));
			curconn->seskey = pkthdr.seskey;
			curconn->lastdata = time(NULL);
			curconn->state = STATE_AUTH;
			memcpy(curconn->srcmac, pkthdr.srcaddr, 6);
			memcpy(curconn->srcip, &(address->sin_addr), 4);
			curconn->srcport = htons(address->sin_port);
			memcpy(curconn->dstmac, pkthdr.dstaddr, 6);

			list_addConnection(curconn);

			initPacket(&pdata, MT_PTYPE_ACK, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter);
			sendUDP(curconn, &pdata);
			break;

		case MT_PTYPE_END:
			curconn = list_findConnection(pkthdr.seskey, (unsigned char *)&(pkthdr.srcaddr));
			if (curconn == NULL) {
				break;
			}
			if (curconn->state != STATE_CLOSED) {
				initPacket(&pdata, MT_PTYPE_END, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter);
				sendUDP(curconn, &pdata);
			}
			printf("(%d) Connection closed.\n", curconn->seskey);
			list_removeConnection(curconn);
			return;

		case MT_PTYPE_ACK:
			curconn = list_findConnection(pkthdr.seskey, (unsigned char *)&(pkthdr.srcaddr));
			if (curconn == NULL) {
				break;
			}
			curconn->lastdata = time(NULL);

			if (pkthdr.counter <= curconn->outcounter) {
				curconn->waitForAck = 0;
			}

			if (pkthdr.counter == curconn->outcounter) {
				// Answer to anti-timeout packet
				initPacket(&pdata, MT_PTYPE_ACK, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter);
				sendUDP(curconn, &pdata);
			}
				return;
			break;

		case MT_PTYPE_DATA:
			curconn = list_findConnection(pkthdr.seskey, (unsigned char *)&(pkthdr.srcaddr));
			if (curconn == NULL) {
				break;
			}
			curconn->lastdata = time(NULL);

			/* ack the data packet */
			initPacket(&pdata, MT_PTYPE_ACK, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter + (data_len - MT_HEADER_LEN));
			sendUDP(curconn, &pdata);

			/* Accept first packet, and all packets greater than incounter, and if counter has
			wrapped around. */
			if (curconn->incounter == 0 || pkthdr.counter > curconn->incounter || (curconn->incounter - pkthdr.counter) > 65535) {
				curconn->incounter = pkthdr.counter;
			} else {
				/* Ignore double or old packets */
				return;
			}

			handleDataPacket(curconn, &pkthdr, data_len);
			break;
		default:
			printf("(%d) Unhandeled packet type: %d\n", curconn->seskey, pkthdr.ptype);
			initPacket(&pdata, MT_PTYPE_ACK, pkthdr.dstaddr, pkthdr.srcaddr, pkthdr.seskey, pkthdr.counter);
			sendUDP(curconn, &pdata);
	}
	if (0 && curconn != NULL) {
		printf("Packet, incounter %d, outcounter %d\n", curconn->incounter, curconn->outcounter);
	}
}

/*
 * TODO: Rewrite main() when all sub-functionality is tested
 */
int main (int argc, char **argv) {
	int result;
	struct sockaddr_in si_me;
	struct timeval timeout;
	int keepalive_counter = 0;
	struct mt_packet pdata;
	fd_set read_fds;

	/* Try to read user file */
	readUserfile();

	/* Seed randomizer */
	srand(time(NULL));

	if (geteuid() != 0) {
		fprintf(stderr, "You need to have root privileges to use %s.\n", argv[0]);
		return 1;
	}

	/* Transmit raw packets with this socket */
	sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if (sockfd < 0) {
		perror("sockfd");
		return 1;
	}

	/* Receive regular udp packets with this socket */
	insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (insockfd < 0) {
		perror("insockfd");
		return 1;
	}

	/* Set random source port */
	sourceport = MT_MACTELNET_PORT;

	/* Listen address*/
	inet_pton(AF_INET, (char *)"0.0.0.0", &sourceip);

	/* Set up global info about the connection */
	inet_pton(AF_INET, (char *)"255.255.255.255", &destip);

	/* Initialize receiving socket on the device chosen */
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(MT_MACTELNET_PORT);
	memcpy(&(si_me.sin_addr), &sourceip, 4);

	/* Bind to udp port */
	if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me))==-1) {
		fprintf(stderr, "Error binding to %s:%d, %s\n", inet_ntoa(si_me.sin_addr), sourceport, strerror(errno));
		return 1;
	}

	printf("Bound to %s:%d\n", inet_ntoa(si_me.sin_addr), sourceport);

	while (1) {
		int reads;
		struct mt_connection *p;
		int maxfd=0;

		/* Init select */
		FD_ZERO(&read_fds);
		FD_SET(insockfd, &read_fds);
		maxfd = sockfd > insockfd ? sockfd : insockfd;

		/* Add active connections to select queue */
		for (p = connections_head; p != NULL; p = p->next) {
			if (p->state == STATE_ACTIVE && p->waitForAck == 0 && p->ptsfd > 0) {
				FD_SET(p->ptsfd, &read_fds);
				if (p->ptsfd > maxfd)
					maxfd = p->ptsfd;
			}
		}

		timeout.tv_sec = 0;
		timeout.tv_usec = 100000;

		/* Wait for data or timeout */
		reads = select(maxfd+1, &read_fds, NULL, NULL, &timeout);
		if (reads > 0) {
			/* Handle data from clients */
			if (FD_ISSET(insockfd, &read_fds)) {
				unsigned char buff[1500];
				struct sockaddr_in saddress;
				int slen = sizeof(saddress);
				result = recvfrom(insockfd, buff, 1500, 0, (struct sockaddr *)&saddress, &slen);
				handlePacket(buff, result, &saddress);
			}
			/* Handle data from terminal sessions */
			for (p = connections_head; p != NULL; p = p->next) {
				/* Check if we have data ready in the pty buffer for the active session */
				if (p->state == STATE_ACTIVE && p->ptsfd > 0 && p->waitForAck == 0 && FD_ISSET(p->ptsfd, &read_fds)) {
					unsigned char keydata[1024];
					int datalen,plen;

					/* Read it */
					datalen = read(p->ptsfd, &keydata, 1024);
					if (datalen != -1) {
						/* Send it */
						initPacket(&pdata, MT_PTYPE_DATA, p->dstmac, p->srcmac, p->seskey, p->outcounter);
						plen = addControlPacket(&pdata, MT_CPTYPE_PLAINDATA, &keydata, datalen);
						p->outcounter += plen;
						p->waitForAck = 1;
						result = sendUDP(p, &pdata);
					} else {
						/* Shell exited */
						struct mt_connection tmp;
						initPacket(&pdata, MT_PTYPE_END, p->dstmac, p->srcmac, p->seskey, p->outcounter);
						sendUDP(p, &pdata);
						if (p->username != NULL) {
							printf("(%d) Connection to user %s closed.\n", p->seskey, p->username);
						} else {
							printf("(%d) Connection closed.\n", p->seskey);
						}
						tmp.next = p->next;
						list_removeConnection(p);
						p = &tmp;
					}
				}
				else if (p->state == STATE_ACTIVE && p->ptsfd > 0 && p->waitForAck == 1 && FD_ISSET(p->ptsfd, &read_fds)) {
					printf("(%d) Waiting for ack\n", p->seskey);
				}
			}
		/* Handle select() timeout */
		} else {
			/* TODO: Kill timed out sessions */
			if (connections_head != NULL) {
				struct mt_connection *p,tmp;
				for (p = connections_head; p != NULL; p = p->next) {
					if (time(NULL) - p->lastdata >= MT_CONNECTION_TIMEOUT) {
						printf("(%d) Session timed out\n", p->seskey);
						initPacket(&pdata, MT_PTYPE_DATA, p->dstmac, p->srcmac, p->seskey, p->outcounter);
						addControlPacket(&pdata, MT_CPTYPE_PLAINDATA, "Timeout\r\n", 9);
						sendUDP(p, &pdata);
						initPacket(&pdata, MT_PTYPE_END, p->dstmac, p->srcmac, p->seskey, p->outcounter);
						sendUDP(p, &pdata);

						tmp.next = p->next;
						list_removeConnection(p);
						p = &tmp;
					}
				}
			}
		}
	}

	close(sockfd);
	close(insockfd);
	return 0;
}