tiptunnel.c 27.4 KB
Newer Older
1 2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2004, 2005, 2006 University of Utah and the Flux Group.
4 5
 * All rights reserved.
 */
Timothy Stack's avatar
 
Timothy Stack committed
6 7 8 9

#include "config.h"

#include <errno.h>
Chad Barb's avatar
Chad Barb committed
10 11 12 13
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
14
#include <termios.h>
Timothy Stack's avatar
 
Timothy Stack committed
15 16 17 18 19 20 21 22
#include <fcntl.h>
#include <grp.h>
#include <pwd.h>
#include <signal.h>
#include <assert.h>
#include <paths.h>

#include <sys/time.h>
Chad Barb's avatar
Chad Barb committed
23

Timothy Stack's avatar
 
Timothy Stack committed
24
#include <sys/types.h>
Chad Barb's avatar
Chad Barb committed
25 26 27 28 29
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

Chad Barb's avatar
 
Chad Barb committed
30 31
#ifdef WITHSSL
#include <openssl/ssl.h>
Chad Barb's avatar
 
Chad Barb committed
32
#include <openssl/err.h>
Chad Barb's avatar
 
Chad Barb committed
33
#endif /* WITHSSL */
Chad Barb's avatar
Chad Barb committed
34 35 36

#include "capdecls.h"

Chad Barb's avatar
 
Chad Barb committed
37
int localmode = 0;
Timothy Stack's avatar
 
Timothy Stack committed
38
int uploadmode = 0;
39 40
int optionsmode = 0;
int speed = -1;
41

Timothy Stack's avatar
 
Timothy Stack committed
42
#define ACLDIR "/var/log/tiplogs"
Chad Barb's avatar
 
Chad Barb committed
43
#define DEFAULT_PROGRAM "xterm -T TIP -e telnet localhost @s"
44

Chad Barb's avatar
Chad Barb committed
45 46 47 48 49 50 51 52 53 54 55 56
int debug = 0;
int allowRemote = 0;

unsigned short port = 0;
int sock = 0;

unsigned short tunnelPort = 0;
int tunnelSock = 0;

char * programToLaunch = NULL;
char * hostname = NULL;

Timothy Stack's avatar
 
Timothy Stack committed
57 58 59
char * certfile = NULL;
char * user = NULL;

Chad Barb's avatar
Chad Barb committed
60 61
secretkey_t key;

Chad Barb's avatar
 
Chad Barb committed
62 63 64 65 66 67
typedef int WriteFunc( void * data, int size );
typedef int ReadFunc( void * data, int size );

WriteFunc * writeFunc;
ReadFunc  * readFunc;

Chad Barb's avatar
Chad Barb committed
68 69 70 71 72 73 74
void usage();
void loadAcl( const char * filename );
void doConnect();
void doAuthenticate();
void doCreateTunnel();
void doTunnelConnection();

Chad Barb's avatar
 
Chad Barb committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
int writeNormal( void * data, int size );
int readNormal( void * data, int size );

#ifdef WITHSSL

void initSSL();
void sslConnect();

int writeSSL( void * data, int size );
int readSSL( void * data, int size );

SSL * ssl;
SSL_CTX * ctx;

int usingSSL = 0;
char * certString = NULL;

#endif /* WITHSSL */
Chad Barb's avatar
Chad Barb committed
93

94 95
static void dotippipe(int capsock,int localin,int localout);

Timothy Stack's avatar
 
Timothy Stack committed
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
#if defined(TIPPTY)

#if defined(__FreeBSD__)
# include <libutil.h>
#endif

#if defined(linux)
# if !defined(INFTIM)
#  define INFTIM -1
# endif
# include <pty.h>
# include <utmp.h>
#endif

#include <poll.h>
#include <termios.h>

#define TIPDIR "/dev/tip"
#define POLL_HUP_INTERVAL (250) /* ms */

typedef struct {
    char data[4096];
    size_t inuse;
} buffer_t;

static void pack_buffer(buffer_t *buffer, int amount);
static void dotippty(char *nodename);

static char pidfilename[1024] = "";
125
static char linkpath[128] = "";
Timothy Stack's avatar
 
Timothy Stack committed
126

127
static void cleanup_atexit(void)
Timothy Stack's avatar
 
Timothy Stack committed
128 129 130
{
  if (strlen(pidfilename) > 0)
    unlink(pidfilename);
131 132 133 134 135 136
  if (strlen(linkpath) > 0)
    unlink(linkpath);
}

static void sigquit(int sig)
{
Timothy Stack's avatar
 
Timothy Stack committed
137 138 139 140
  exit(0);
}
#endif

Chad Barb's avatar
Chad Barb committed
141 142
int main( int argc, char ** argv )
{
Chad Barb's avatar
 
Chad Barb committed
143
  const char * name = argv[0];
144
  char * aclfile = (char *) NULL;
Chad Barb's avatar
Chad Barb committed
145
  int op;
146 147
  int oldflags;
  struct termios tios;
Chad Barb's avatar
Chad Barb committed
148

Timothy Stack's avatar
 
Timothy Stack committed
149
#if defined(LOCALBYDEFAULT) || defined(TIPPTY)
Chad Barb's avatar
 
Chad Barb committed
150
  localmode++;
151 152 153
#if defined(TIPPTY)
  atexit(cleanup_atexit);
#endif
Chad Barb's avatar
 
Chad Barb committed
154 155
#endif

156
  while ((op = getopt( argc, argv, "hlp:rdu:c:a:os:" )) != -1) {
Chad Barb's avatar
Chad Barb committed
157
    switch (op) {
Chad Barb's avatar
 
Chad Barb committed
158 159 160
      case 'h':
        usage(name);
        break;
161 162 163
      case 'a':
	aclfile = optarg;
        break;
Chad Barb's avatar
 
Chad Barb committed
164 165 166
      case 'l':
	localmode++;
	break;
Chad Barb's avatar
Chad Barb committed
167 168 169 170 171 172 173 174 175
      case 'p':
        tunnelPort = atoi( optarg );
	break;
      case 'd':
	debug++;
	break;
      case 'r':
	allowRemote++;
	break;
Timothy Stack's avatar
 
Timothy Stack committed
176 177 178 179 180 181
#ifdef WITHSSL
      case 'u':
	user = optarg;
	uploadmode++;
	usingSSL++;
	break;
182 183 184 185 186 187 188 189 190
      case 's':
	speed = atoi(optarg);
	if (speed <= 0) {
	    fprintf(stderr,"Speed option must be greater than 0\n");
	    usage(name);
	}
	optionsmode++;
	usingSSL++;
	break;
Timothy Stack's avatar
 
Timothy Stack committed
191 192 193 194
      case 'c':
	certfile = optarg;
	break;
#endif
Chad Barb's avatar
Chad Barb committed
195 196 197 198 199 200 201
    }
  }

  argc -= optind;
  argv += optind;

  if (argc < 1) {
Chad Barb's avatar
 
Chad Barb committed
202
    usage( name );
Chad Barb's avatar
Chad Barb committed
203 204 205 206
  }

  if (argc > 1) {
    programToLaunch = strdup( argv[1] );    
207
  } else {
Chad Barb's avatar
 
Chad Barb committed
208
    programToLaunch = strdup( DEFAULT_PROGRAM );
Chad Barb's avatar
Chad Barb committed
209
  }
210 211 212 213 214 215 216 217
  if (debug) printf("Will launch program '%s'\n",programToLaunch);

  if (uploadmode && optionsmode) {
      fprintf(stderr,
	      "You cannot specify both an upload and options; "
	      "  they must be done with multiple invocations of %s",name);
      usage(name);
  }
Chad Barb's avatar
Chad Barb committed
218

Chad Barb's avatar
 
Chad Barb committed
219
  if (localmode) {
220 221 222 223 224 225 226
    if (aclfile)
      loadAcl( aclfile );
    else {
      char localAclName[1024];
      sprintf( localAclName, "%s/%s.acl", ACLDIR, argv[0] );
      loadAcl( localAclName );
    }
Chad Barb's avatar
 
Chad Barb committed
227 228 229
  } else {
    loadAcl( argv[0] );
  }
Chad Barb's avatar
Chad Barb committed
230

Chad Barb's avatar
 
Chad Barb committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
#ifdef WITHSSL
  if (usingSSL) { 
    writeFunc = writeSSL;
    readFunc  = readSSL;
    initSSL();
    doConnect();
    sslConnect();
  } else
#endif /* WITHSSL */
  {
    /* either there is no SSL, or they're not using it. */
    writeFunc = writeNormal;
    readFunc  = readNormal;
    doConnect();
  }

Timothy Stack's avatar
 
Timothy Stack committed
247 248 249 250 251 252
  if (user && (getuid() == 0)) {
    struct passwd *pw;
    struct group *gr;
    uid_t uid;
    int rc;
    
253 254 255 256 257 258
    if (sscanf(user, "%d", &uid) == 1)
      pw = getpwuid(uid);
    else
      pw = getpwnam(user);

    if (pw == NULL) {
Timothy Stack's avatar
 
Timothy Stack committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
      fprintf(stderr, "invalid user: %s %d\n", user, uid);
      exit(1);
    }
    
    if ((gr = getgrgid(pw->pw_gid)) == NULL) {
      fprintf(stderr, "invalid group: %d\n", pw->pw_gid);
      exit(1);
    }
    
    /*
     * Initialize the group list, and then flip to uid.
     */
    if (setgid(pw->pw_gid) ||
	initgroups(user, pw->pw_gid) ||
	setuid(pw->pw_uid)) {
      fprintf(stderr, "Could not become user: %s\n", user);
      exit(1);
    }
  }

279 280 281
  if (optionsmode)
      exit(0);

Timothy Stack's avatar
 
Timothy Stack committed
282
  if (uploadmode) {
283
    int fd = STDIN_FILENO;
Timothy Stack's avatar
 
Timothy Stack committed
284 285 286 287 288 289 290 291 292 293 294 295 296

    if ((strcmp(argv[1], "-") != 0) && (fd = open(argv[1], O_RDONLY)) < 0) {
      fprintf(stderr, "Cannot open file: %s\n", argv[1]);
      exit(1);
    }
    else {
      char buf[4096];
      int rc;

      while ((rc = read(fd, buf, sizeof(buf))) > 0) {
	writeFunc(buf, rc);
      }
      close(fd);
297
      fd = -1;
Timothy Stack's avatar
 
Timothy Stack committed
298 299 300 301
    }
    exit(0);
  }
  
Chad Barb's avatar
Chad Barb committed
302
  doAuthenticate();
Timothy Stack's avatar
 
Timothy Stack committed
303 304

#if defined(TIPPTY)
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
  if (!debug) {
    FILE *file;
    
    daemon(0, 0);
    signal(SIGINT, sigquit);
    signal(SIGTERM, sigquit);
    signal(SIGQUIT, sigquit);
    snprintf(pidfilename, sizeof(pidfilename),
	     "%s/tippty.%s.pid",
	     _PATH_VARRUN, argv[0]);
    if ((file = fopen(pidfilename, "w")) != NULL) {
      fprintf(file, "%d\n", getpid());
      fclose(file);
    }
  }

Timothy Stack's avatar
 
Timothy Stack committed
321 322
  dotippty(argv[0]);
#else
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
  if (localmode && strcmp(programToLaunch,"-") == 0) {
      // just hook stdin/out to connection ;)
      oldflags = fcntl(STDIN_FILENO,F_GETFL);
      oldflags |= O_NONBLOCK;
      fcntl(STDIN_FILENO,F_SETFL,oldflags);

      // also get rid of line buffering -- we do enough buffering
      // internally!
      setvbuf(stdin,NULL,_IONBF,0);
      setvbuf(stdout,NULL,_IONBF,0);

      if (isatty(STDOUT_FILENO)) {
	  tcgetattr(STDOUT_FILENO,&tios);
	  tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
	  tios.c_oflag &= ~OPOST;
	  tcsetattr(STDOUT_FILENO,TCSANOW,&tios);
      }

      oldflags = fcntl(STDOUT_FILENO,F_GETFL);
      oldflags |= O_NONBLOCK;
      fcntl(STDOUT_FILENO,F_SETFL,oldflags);

      oldflags = fcntl(sock,F_GETFL);
      oldflags |= O_NONBLOCK;
      fcntl(sock,F_SETFL,oldflags);

      dotippipe(sock,STDIN_FILENO,STDOUT_FILENO);
      exit(0);
  }

Chad Barb's avatar
Chad Barb committed
353
  doCreateTunnel();
Chad Barb's avatar
 
Chad Barb committed
354

Chad Barb's avatar
Chad Barb committed
355 356
  if (programToLaunch) {
    char portString[12];
357

Chad Barb's avatar
Chad Barb committed
358
    sprintf( portString, "%i", tunnelPort );
359

Chad Barb's avatar
 
Chad Barb committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373
    if (localmode) {
      if (!fork()) {
	char * foo[4];
	foo[0] = "telnet";
	foo[1] = "localhost";
	foo[2] = portString;
	foo[3] = NULL;
	execvp( "telnet", foo );
	exit(666);
      }
    } else {
      char runString[1024];
      char * foo;

Chad Barb's avatar
 
Chad Barb committed
374
      for (foo = programToLaunch; *foo; foo++) {
375
	if (*foo == '@') { *foo = '%'; break; }
Chad Barb's avatar
 
Chad Barb committed
376 377 378
      }

      sprintf(runString, programToLaunch, portString);
Chad Barb's avatar
 
Chad Barb committed
379 380

      if (debug) printf("Running '%s'\n", runString);
381 382 383 384
      
      if (! fork()) {
        exit(system( runString ));
      }
Chad Barb's avatar
 
Chad Barb committed
385 386
    }
   
387
    /*
Chad Barb's avatar
Chad Barb committed
388 389 390 391
    if (!fork()) {
      execlp( programToLaunch, 
	      programToLaunch, "localhost", portString, NULL );
    }
392
    */
Chad Barb's avatar
Chad Barb committed
393
  }
Chad Barb's avatar
 
Chad Barb committed
394
  //if (localmode) { sleep(3); }
Chad Barb's avatar
Chad Barb committed
395 396
  doTunnelConnection();
  if (debug) { printf("tiptunnel closing.\n"); }
Timothy Stack's avatar
 
Timothy Stack committed
397
#endif
Chad Barb's avatar
Chad Barb committed
398 399
}

Chad Barb's avatar
 
Chad Barb committed
400
void usage(const char * name)
Chad Barb's avatar
Chad Barb committed
401
{
Timothy Stack's avatar
 
Timothy Stack committed
402
#if defined(LOCALBYDEFAULT)
Chad Barb's avatar
 
Chad Barb committed
403 404 405 406 407 408 409 410

  printf("Usage:\n"
	 "%s [-d] <pcname>\n"
	 "-d               turns on more verbose debug messages\n"
	 "<pcname>         name of machine to connect to (e.g. \"pc42\")\n",
	 name
	 );

Timothy Stack's avatar
 
Timothy Stack committed
411 412 413 414 415 416
#elif defined(TIPPTY)

  printf("Usage:\n"
	 "%s [-d] <node>\n",
	 name);
  
Chad Barb's avatar
 
Chad Barb committed
417 418
#else

Chad Barb's avatar
 
Chad Barb committed
419 420 421 422 423
  printf("No aclfile specified.\n"
         "If you are using a web browser, perhaps\n"
         "it is not properly configured to pass\n"
         "an argument to tiptunnel.\n\n");

Chad Barb's avatar
Chad Barb committed
424
  printf("Usage:\n"
Chad Barb's avatar
 
Chad Barb committed
425 426 427 428 429
	 "%s [-l] [-p <portnum>] [-d] [-r] aclfile [<program>]\n"
	 "-l               enables local mode.\n"
	 "                 acl file will be looked for in:\n"
	 "                 /var/log/tiplogs/<aclfile>.acl\n"
	 "                 (also, server certificate will not be checked)\n"
Chad Barb's avatar
Chad Barb committed
430
	 "-p <portnum>     specifies tunnel port number\n"
Chad Barb's avatar
 
Chad Barb committed
431
	 "-d               turns on more verbose debug messages\n"
Chad Barb's avatar
Chad Barb committed
432
	 "-r               allows connections to tunnel from non-localhost\n"
Timothy Stack's avatar
 
Timothy Stack committed
433
	 "-u <user>        upload mode\n"
Chad Barb's avatar
Chad Barb committed
434
	 "\n"
Chad Barb's avatar
 
Chad Barb committed
435 436
	 "<program>        (non-local-mode only)\n"
	 "                 path of program to launch; default is\n"
Chad Barb's avatar
 
Chad Barb committed
437 438
	 "                 \"%s\"\n"
         "                 ('@s' indicates where to put port number.)\n",
Chad Barb's avatar
 
Chad Barb committed
439
	 name,
440
         DEFAULT_PROGRAM
Chad Barb's avatar
 
Chad Barb committed
441
	 //"-k keeps accepting connections until killed"
Chad Barb's avatar
Chad Barb committed
442
	 );
Chad Barb's avatar
 
Chad Barb committed
443 444

#endif
Chad Barb's avatar
Chad Barb committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
  exit(-1);
}

void loadAcl( const char * filename )
{
  FILE * aclFile = fopen( filename, "r" );
  char b1[256];
  char b2[256];

  if (!aclFile) {
    perror("open");
    fprintf( stderr, "Error opening ACL file '%s'\n", filename );
    exit(-1);
  }

  if (debug) { printf("Opened ACL file '%s'\n", filename ); }
  
  bzero( &key, sizeof( key ) );

  while (fscanf(aclFile, "%s %s\n", &b1, &b2) != EOF) {
465
    if ( strcmp(b1, "host:") == 0 || strcmp(b1, "server:") == 0 ) {
Timothy Stack's avatar
 
Timothy Stack committed
466 467
      if (!uploadmode)
	hostname = strdup( b2 );
468
    } else if ( strcmp(b1, "port:") == 0 || strcmp(b1, "portnum:") == 0 ) {
Timothy Stack's avatar
 
Timothy Stack committed
469 470
      if (!uploadmode)
	port = atoi( b2 );
Chad Barb's avatar
Chad Barb committed
471 472
    } else if ( strcmp(b1, "keylen:") == 0 ) {
      key.keylen = atoi( b2 );
473
    } else if ( strcmp(b1, "key:") == 0 || strcmp(b1, "keydata:") == 0) {
Chad Barb's avatar
Chad Barb committed
474
      strcpy( key.key, b2 );
Chad Barb's avatar
 
Chad Barb committed
475
#ifdef WITHSSL
Timothy Stack's avatar
 
Timothy Stack committed
476 477 478 479 480 481
    } else if ( strcmp(b1, "uphost:") == 0 ) {
      if (uploadmode)
	hostname = strdup( b2 );
    } else if ( strcmp(b1, "upport:") == 0 ) {
      if (uploadmode)
	port = atoi( b2 );
Chad Barb's avatar
 
Chad Barb committed
482 483 484 485 486
    } else if ( strcmp(b1, "ssl-server-cert:") == 0 ) {
      if (debug) { printf("Using SSL to connect to capture.\n"); }
      certString = strdup( b2 );
      usingSSL++;
#endif /* WITHSSL */
Chad Barb's avatar
Chad Barb committed
487
    } else {
488
      /* fprintf(stderr, "Ignored unknown ACL: %s %s\n", b1, b2); */
Chad Barb's avatar
Chad Barb committed
489 490
    }
  }
491 492 493 494
  fclose(aclFile);

  if (!key.keylen)
    key.keylen = strlen(key.key);
Chad Barb's avatar
Chad Barb committed
495

496
  if (!port || !hostname || !strlen(key.key)) {
Chad Barb's avatar
Chad Barb committed
497 498 499 500 501 502
    fprintf(stderr, "Incomplete ACL\n");
    exit(-1);
  }

}

Chad Barb's avatar
 
Chad Barb committed
503 504 505 506 507 508 509 510 511 512
int writeNormal( void * data, int size )
{
  return write( sock, data, size );
}

int readNormal( void * data, int size )
{
  return read( sock, data, size );
}

Chad Barb's avatar
Chad Barb committed
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
void doConnect()
{
  struct sockaddr_in name;
  struct hostent *he;

  name.sin_family = AF_INET;
  name.sin_port   = htons(port);

  he = gethostbyname(hostname);   
  if (!he) {
    fprintf(stderr, "Unknown hostname %s: %s\n",
	    hostname, hstrerror(h_errno));
    exit(-1);
  }
  
  memcpy ((char *)&name.sin_addr, he->h_addr, he->h_length);
  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0) {
    perror("socket");
    exit(-1);
  }

  if (connect( sock, (struct sockaddr *)&name, sizeof(name)) < 0) {
    close( sock );
    perror("connect");
    exit(-1);
  }
}
  
void doAuthenticate()
{
  capret_t capret;

Chad Barb's avatar
 
Chad Barb committed
546 547 548 549
  if ( writeFunc( /*sock,*/ &key, sizeof(key) ) == sizeof(key) &&
       readFunc( /*sock,*/ &capret, sizeof(capret)) > 0 ) {
    switch( capret ) {
    case CAPOK: 
Chad Barb's avatar
Chad Barb committed
550
      return;
Chad Barb's avatar
 
Chad Barb committed
551
    case CAPBUSY:       
Chad Barb's avatar
Chad Barb committed
552
      fprintf(stderr, "Tip line busy.\n");
Chad Barb's avatar
 
Chad Barb committed
553 554 555 556 557 558 559
      break;
    case CAPNOPERM:
      fprintf(stderr, "You do not have permission. No TIP for you!\n");
      break;
    default:
      fprintf(stderr, "Unknown return code 0x%02x.\n", (unsigned int)capret);
      return; // XXX Final version should break here. 
Chad Barb's avatar
Chad Barb committed
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
    }
  } else {
    // write or read hosed.
    fprintf(stderr, "Error authenticating\n");
  }

  close( sock );
  exit(-1);
}


void doCreateTunnel()
{
  int i;
  struct sockaddr_in name;

  tunnelSock = socket(AF_INET, SOCK_STREAM, 0);
  if (tunnelSock < 0) { 
    perror("socket");
    exit(-1);
  }

  i = 1;
  if (setsockopt(tunnelSock, SOL_SOCKET, SO_REUSEADDR,
		 (char *)&i, sizeof(i)) < 0) {
    perror("setsockopt: SO_REUSEADDR");
    exit(-1);
  }

  name.sin_family = AF_INET;
  name.sin_addr.s_addr = INADDR_ANY;
  name.sin_port = htons( tunnelPort );
  if (bind(tunnelSock, (struct sockaddr *) &name, sizeof(name))) {
    perror("bind");
    exit(-1);
  }

  i = sizeof(name);
  if (getsockname(tunnelSock, (struct sockaddr *)&name, &i)) {
    perror("getsockname");
    exit(-1);
  }

  tunnelPort = ntohs(name.sin_port);

Chad Barb's avatar
 
Chad Barb committed
605
  if (debug) { printf("Listening on port %i.\n", tunnelPort); }
Chad Barb's avatar
Chad Barb committed
606 607 608 609 610 611 612 613 614

  if (listen(tunnelSock, 1) < 0) {
    perror("listen");
    exit(-1);
  }
}

void doTunnelConnection()
{
Chad Barb's avatar
 
Chad Barb committed
615
  int i;
Chad Barb's avatar
Chad Barb committed
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
  int conSock;
  struct sockaddr_in name;
  socklen_t namelen = sizeof( name );

acceptor:
  conSock = accept( tunnelSock, (struct sockaddr *)&name, &namelen );

  if (name.sin_family != AF_INET) {
    fprintf(stderr,"Error: non AF_INET connection.\n");
    exit(-1);
  }

  if (!allowRemote && 
      ntohl( name.sin_addr.s_addr ) != INADDR_LOOPBACK) {
    const char reject[] = 
      "Connection attempted from non-local machine (ignored.)\n"
      "Use -r switch to allow non-local connections.\n";
    write( conSock, reject, sizeof( reject ) );
    fprintf( stderr, "%s", reject );
    close( conSock );
    goto acceptor;
  }

  if (conSock < 0 ) {
    perror("accept");
    exit(-1);
  }

Chad Barb's avatar
 
Chad Barb committed
644 645 646 647 648
  if (conSock == 0) {
    if (debug) { printf("Zero consock. Retrying.\n" ); }
    goto acceptor;
  }

Chad Barb's avatar
 
Chad Barb committed
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
  { 
    /*
      lets pretend that we are a telnetd (RFC854).. 
      It will be crackling good fun! 

      we enable "SUPPRESS GO AHEAD" and "ECHO",
      thus (through something commonly called "kludge line mode")
      telling the client _not_ to send a line at a time (and not to echo locally.) 

      I'm actually not totally sure why this works, but I'm afraid if I 
      think too hard about it, it will stop.
    */

    const char telnet_commands[] = 
    { 
      // IAC WILL SUPPRESS GO AHEAD:
      255, 251, 3,
      // IAC WILL ECHO:
      255, 251, 1   
    };

    write( conSock, telnet_commands, sizeof( telnet_commands ) );
  }

Chad Barb's avatar
Chad Barb committed
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
  while (1) {
    fd_set fds;
    char buf[4096];
    
    FD_ZERO( &fds );
    FD_SET( conSock, &fds );
    FD_SET( sock, &fds );
    
    if (select( MAX( conSock, sock ) + 1, &fds, NULL, NULL, NULL ) < 0) {
      perror("select");
      exit(-1);
    }

    if ( FD_ISSET( conSock, &fds ) ) {
      int got = read( conSock, buf, 4096);
      if (got <= 0) {
	if (got < 0) { perror("read conSock"); }
	if (debug) { printf("conSock read %i; exiting.\n", got); }
	return;
      }

Chad Barb's avatar
 
Chad Barb committed
694

Chad Barb's avatar
 
Chad Barb committed
695 696 697 698 699 700 701 702
      /*  
	  we could implement some kind of search to remove 
	  "IAC DO SUPPRESS GO AHEAD" and "IAC DO ECHO" bytes from the stream,
	  or just trash any packet starting in "IAC" (255).
	  Yeah.
      */

      if ((unsigned char)buf[0] != 255) {
703 704 705 706 707 708 709 710 711 712 713 714 715 716

	if (buf[got - 1] == '\0') { got--; }

	/*
	for(i = 0; i < got; i++ ) {
	  if ((unsigned char)buf[i] > 127 || 
	      (unsigned char)buf[i] < 32) {
	    printf("Special to server %i\n", 
		   (unsigned int)(unsigned char)buf[i] );
	    //buf[i] = '#';
	  }
	}
	*/

Chad Barb's avatar
 
Chad Barb committed
717 718 719 720
	if (writeFunc( /*sock,*/ buf, got ) < 0) {
	  perror("write sock");
	  return;
	}
721
      } 
Chad Barb's avatar
Chad Barb committed
722 723 724
    }

    if ( FD_ISSET( sock, &fds ) ) {
Chad Barb's avatar
 
Chad Barb committed
725
      int got = readFunc( /*sock,*/ buf, 4096);
Chad Barb's avatar
Chad Barb committed
726 727 728 729 730 731
      if (got <= 0) {
	if (got < 0) { perror("read sock"); }
	if (debug) { printf("sock read %i; exiting.\n", got); }
	return;
      }

732
      //printf("%i server->consock\n", got );
Chad Barb's avatar
 
Chad Barb committed
733

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
      if ((unsigned char)buf[0] != 255) {
	/*
	for(i = 0; i < got; i++ ) {
	  if (buf[i] == '^') { buf[i] = '!'; }
	  if ((unsigned char)buf[i] > 127 || 
	      (unsigned char)buf[i] < 32) {
	    printf("Special from server %i\n", 
		   (unsigned int)(unsigned char)buf[i] );
	    //buf[i] = '#';
	  }
	}
	*/
	if (write( conSock, buf, got ) < 0) {
	  perror("write conSock");
	  return;
	}
Chad Barb's avatar
Chad Barb committed
750 751 752 753
      }
    }
  }
}
Chad Barb's avatar
 
Chad Barb committed
754 755 756 757


#ifdef WITHSSL

Timothy Stack's avatar
 
Timothy Stack committed
758 759
#define DEFAULT_CERTFILE TBROOT"/etc/capture.pem"

Chad Barb's avatar
 
Chad Barb committed
760 761 762 763
void initSSL()
{
  SSL_library_init();
  ctx = SSL_CTX_new( SSLv23_method() );
Chad Barb's avatar
 
Chad Barb committed
764
  SSL_load_error_strings();
Timothy Stack's avatar
 
Timothy Stack committed
765 766 767 768 769 770 771 772 773 774 775 776 777 778

  if (uploadmode) {
    if (!certfile) { certfile = DEFAULT_CERTFILE; }
    
    if (SSL_CTX_use_certificate_file( ctx, certfile, SSL_FILETYPE_PEM ) <= 0) {
      fprintf( stderr, "Could not load %s as certificate file.", certfile );
      exit(1);
    }
    
    if (SSL_CTX_use_PrivateKey_file( ctx, certfile, SSL_FILETYPE_PEM ) <= 0) {
      fprintf( stderr, "Could not load %s as key file.", certfile );
      exit(1);
    }
  }
Chad Barb's avatar
 
Chad Barb committed
779 780 781 782 783 784 785 786 787 788 789
  //  if (!(SSL_CTX_load_verify_location( ctx, CA_LIST, 0 ))
}

void sslConnect()
{
  unsigned char digest[256];
  unsigned int len = sizeof( digest );
  unsigned char digestHex[512];
  X509 * peer;
  BIO * sbio;
  int i;
Chad Barb's avatar
 
Chad Barb committed
790 791 792 793 794 795 796
  
  // inform server of desire to use SSL
  {
    secretkey_t sslHintKey;
    char ret[4];

    sslHintKey.keylen = 7;
Timothy Stack's avatar
 
Timothy Stack committed
797 798
    if (uploadmode)
      strcpy( sslHintKey.key, "UPLOAD" );
799 800 801 802 803 804 805 806 807
    else if (optionsmode) {
	strcpy(sslHintKey.key,"OPTIONS ");
	if (speed > 0) {
	    // copy in the speed option safely
	    snprintf((char *)(sslHintKey.key+strlen(sslHintKey.key)),
		     sizeof(sslHintKey.key)-strlen(sslHintKey.key)-1,
		     "SPEED=%d ",speed);
	}
    }
Timothy Stack's avatar
 
Timothy Stack committed
808 809
    else
      strncpy( sslHintKey.key, "USESSL", 7 );
Chad Barb's avatar
 
Chad Barb committed
810 811 812 813 814 815 816 817
    write( sock, &sslHintKey, sizeof( sslHintKey ) );
    /*
    if (4 != read( sock, ret, 4 ) || 
	0 != strncmp( ret, "OKAY", 4) ) {
      fprintf( stderr, "Didnt get SSL OKAY from server.\n");
      exit(-1);
    }
    */
Timothy Stack's avatar
 
Timothy Stack committed
818
  }
Chad Barb's avatar
 
Chad Barb committed
819 820 821 822

  ssl = SSL_new( ctx );
  SSL_set_fd( ssl, sock );

Chad Barb's avatar
 
Chad Barb committed
823 824 825 826 827 828 829 830 831 832
  /*
  i = 0;
  while (1) {
    char * n = SSL_get_cipher_list( ssl, i );
    if (!n) { break;}
    printf("Cipher #%i is %s\n", i, n );
    i++;
  }
  */

Chad Barb's avatar
 
Chad Barb committed
833 834
  // sbio = BIO_new_socket( sock, BIO_NOCLOSE );
  // SSL_set_bio( ssl, sbio, sbio );
Timothy Stack's avatar
 
Timothy Stack committed
835
  // sleep(1);
Chad Barb's avatar
 
Chad Barb committed
836 837 838
  
  if (SSL_connect( ssl ) <= 0) {
    fprintf(stderr, "SSL Connect error.\n");
Chad Barb's avatar
 
Chad Barb committed
839
    ERR_print_errors_fp( stderr );
Chad Barb's avatar
 
Chad Barb committed
840 841 842
    exit(-1);
  }

843
  if (uploadmode || optionsmode)
Timothy Stack's avatar
 
Timothy Stack committed
844 845
    return;

Chad Barb's avatar
 
Chad Barb committed
846 847 848 849 850 851 852 853 854
  peer = SSL_get_peer_certificate( ssl );

  // X509_print_fp( stdout );
  // X509_digest( &peer, EVP_sha() , digest, &len );

  //X509_digest( peer, EVP_md5(), digest, &len );
  
  X509_digest( peer, EVP_sha(), digest, &len );

Timothy Stack's avatar
 
Timothy Stack committed
855 856
  X509_free( peer );

Chad Barb's avatar
 
Chad Barb committed
857 858 859 860 861 862 863 864 865 866 867
  for (i = 0; i < len; i++) {
    sprintf( digestHex + (i * 2), "%02x", (unsigned int) digest[i] );
  }

  if (debug) {
    printf("ACL's  cert digest: %s\n"
	   "Server cert digest: %s\n",
	   certString, 
	   digestHex );
  }

Chad Barb's avatar
 
Chad Barb committed
868
  if (/*!localmode && */0 != strcmp( certString, digestHex )) {
Chad Barb's avatar
 
Chad Barb committed
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    fprintf(stderr, 
	    "Server does not have certificate described in ACL:\n"
	    "ACL's  cert digest: %s\n" 
	    "Server cert digest: %s\n"
	    "Possible man-in-the-middle attack. Aborting.\n\n",
	    certString,
	    digestHex );

    exit(-1);
  }
}


int writeSSL( void * data, int size )
{
  return SSL_write( ssl, data, size );
}

int readSSL( void * data, int size )
{
  return SSL_read( ssl, data, size );
}

#endif /* WITHSSL */
Timothy Stack's avatar
 
Timothy Stack committed
893

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
// Just do a very simple select loop that ties the remote capture
// to a pair of fds -- probably stdin/out.
static void dotippipe(int capsock,int localin,int localout) {
    fd_set rfds,rfds_master,wfds,wfds_master;
    int nfds = 0;
    struct timeval tv = { 1,0 };
    int retval, rc;
    char fromsock[1024];
    char fromlocal[1024];
    int sockrc = 0,localrc = 0,len = 0;
    char *sockhptr,*socktptr,*localhptr,*localtptr;
    sockhptr = socktptr = fromsock;
    localhptr = localtptr = fromlocal;


    nfds = (capsock > localin) ? capsock + 1 : localin + 1;
    nfds = (nfds > localout) ? nfds : localout + 1;

    FD_ZERO(&rfds_master);
    FD_ZERO(&wfds_master);
    FD_SET(capsock,&rfds_master);
    FD_SET(localin,&rfds_master);
    FD_SET(capsock,&wfds_master);
    FD_SET(localout,&wfds_master);

    while (1) {
	memcpy(&rfds,&rfds_master,sizeof(rfds));
	memcpy(&wfds,&wfds_master,sizeof(wfds));

	retval = select(nfds,&rfds,NULL,NULL,NULL);
	if (retval < 0) {
	    printf("dotippipe select: %s\n",strerror(retval));
	    exit(retval);
	}

	if (FD_ISSET(capsock,&rfds)) {
	    if (sockrc == sizeof(fromsock)) {
		// we're full... let it buffer elsewhere
		if (debug) fprintf(stderr,"sock read buf full\n");
	    }
	    else {
		// simple, non-optimal ring buffering
		if (socktptr > sockhptr || sockrc == 0) 
		    len = (fromsock + sizeof(fromsock)) - socktptr;
		else
		    len = sockhptr - socktptr;

		if (len > 0) {
		    retval = readFunc(socktptr,len);
		    if (retval < 0) {
			if (retval == ECONNRESET) {
			    if (debug) fprintf(stderr,"remote hung up\n");
			    FD_CLR(capsock,&rfds_master);
			    FD_CLR(capsock,&wfds_master);
			}
			else {
			    fprintf(stderr,"dotippipe sock read: %s\n",
				    strerror(retval));
			    exit(retval);
			}
		    }
		    else if (retval > 0) {
			if (debug) fprintf(stderr,"read %d sock\n",retval);
			sockrc += retval;
			socktptr += retval;
			if (socktptr == fromsock + sizeof(fromsock)) {
			    // move from end to head of buffer
			    socktptr = fromsock;
			}
		    }
		    else {
			if (debug) fprintf(stderr,"sock EOF\n");
			FD_CLR(capsock,&rfds_master);
		    }
		}
	    }
	}

	if (FD_ISSET(localin,&rfds)) {
	    if (localrc == sizeof(fromlocal)) {
		// we're full... let it buffer elsewhere
	    }
	    else {
		// simple, non-optimal ring buffering
		if (localtptr > localhptr || localrc == 0) 
		    len = (fromlocal + sizeof(fromlocal)) - localtptr;
		else 
		    len = localhptr - localtptr;

		if (len > 0) {
		    retval = read(localin,localtptr,len);
		    if (retval < 0) {
			if (retval == ECONNRESET) {
			    FD_CLR(localin,&rfds_master);
			    FD_CLR(localin,&wfds_master);
			}
			else {
			    printf("dotippipe localin read: %s\n",
				    strerror(retval));
			    exit(retval);
			}
		    }
		    else if (retval > 0) {
			if (debug) fprintf(stderr,"read %d local\n",retval);
			localrc += retval;
			localtptr += retval;
			if (localtptr == fromlocal + sizeof(fromlocal)) {
			    // move from end to head of buffer
			    localtptr = fromlocal;
			}
		    }
		    else {
			FD_CLR(localin,&rfds_master);
		    }
		}
	    }
	}

	if (sockrc && FD_ISSET(localout,&wfds)) {
	    // write what we can
	    if (sockhptr > socktptr || sockrc == sizeof(fromsock)) 
		len = (fromsock + sizeof(fromsock)) - sockhptr;
	    else
		len = socktptr - sockhptr;

	    if (debug) fprintf(stderr,"trying write %d local\n",len);
	    retval = write(localout,sockhptr,len);
	    if (retval < 0) {
		if (retval == EPIPE) {
		    FD_CLR(localout,&wfds_master);
		    FD_CLR(capsock,&rfds_master);
		    sockrc = 0;
		}
		else if (retval == EAGAIN) {
		    ;
		}
		else {
		    printf("dotippipe local write: %s\n",
			    strerror(retval));
		    exit(retval);
		}
	    }
	    else {
		if (debug) fprintf(stderr,"wrote %d local\n",retval);
		sockrc -= retval;
		sockhptr += retval;
		if (sockhptr == fromsock + sizeof(fromsock)) {
		    // move from end to head of buffer
		    sockhptr = fromsock;
		}
	    }
	}

	if (localrc && FD_ISSET(capsock,&wfds)) {
	    // write what we can
	    if (localhptr > localtptr || localrc == sizeof(fromlocal)) 
		len = (fromlocal + sizeof(fromlocal)) - localhptr;
	    else
		len = localtptr - localhptr;

	    retval = writeFunc(localhptr,len);
	    if (retval < 0) {
		if (retval == EPIPE) {
		    FD_CLR(capsock,&wfds_master);
		    FD_CLR(localin,&rfds_master);
		    localrc = 0;
		}
		else if (retval == EAGAIN) {
		    ;
		}
		else {
		    printf("dotippipe sock write: %s\n",
			    strerror(retval));
		    exit(retval);
		}
	    }
	    else {
		if (debug) fprintf(stderr,"wrote %d sock\n",retval);
		localrc -= retval;
		localhptr += retval;
		if (localhptr == fromlocal + sizeof(fromlocal)) {
		    // move from end to head of buffer
		    localhptr = fromlocal;
		}
	    }
	}

        if ((!FD_ISSET(capsock,&rfds_master) 
	     || !FD_ISSET(localin,&rfds_master))
	    && sockrc == 0 && localrc == 0) {
	    // if one of the src ends has closed, and we have nothing 
	    // queued, we're done
	    if (debug) fprintf(stderr,"Exiting sanely.\n");
	    exit(0);
	}
    }
    
}

Timothy Stack's avatar
 
Timothy Stack committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
#ifdef TIPPTY

static void pack_buffer(buffer_t *buffer, int amount)
{
    assert(buffer != NULL);
    assert((amount == -1) ||
	   ((amount >= 0) && (amount < sizeof(buffer->data))));
    
    if (amount > 0) {
	buffer->inuse -= amount;
	memmove(buffer->data, &buffer->data[amount], buffer->inuse);
    }
}

static void dotippty(char *nodename)
{
  int rc, master, slave;
  char path[64];

  assert(nodename != NULL);
  assert(strlen(nodename) > 0);
  
  if ((mkdir(TIPDIR, 0755) < 0) && (errno != EEXIST))
    perror("unable to make " TIPDIR);
  
  if ((rc = openpty(&master, &slave, path, NULL, NULL)) < 0) {
    perror("openpty");
    exit(1);
  }
  else {
    struct pollfd pf[2] = {
      [0] = { .fd = sock, .events = POLLIN },
      [1] = { .fd = master, .events = POLLHUP },
    };
    
    buffer_t from_pty = { .inuse = 0 }, to_pty = { .inuse = 0 };
    int tweaked = 0, fd_count = 2;
    struct timeval now, before;
    
    fcntl(master, F_SETFL, O_NONBLOCK);
    fcntl(sock, F_SETFL, O_NONBLOCK);
    close(slave);
    slave = -1;

    if (chmod(path, 0666) < 0)
      perror("unable to change permissions");

    snprintf(linkpath, sizeof(linkpath), "%s/%s", TIPDIR, nodename);
    if ((symlink(path, linkpath) < 0) && (errno != EEXIST))
      perror("unable to create symlink");

    gettimeofday(&now, NULL);
    before = now;
    while ((rc = poll(pf,
		      fd_count,
		      fd_count == 1 ? POLL_HUP_INTERVAL : INFTIM)) >= 0) {
      if (rc == 0) { // Timeout
	/* ... check for a slave connection on the next loop. */
	fd_count = 2;
      }
      else if (pf[1].revents & POLLHUP) {
	struct timeval diff;
	
	/* No slave connection. */
	if (pf[0].revents & POLLIN) // Drain the input side.
	  rc = readFunc(to_pty.data, sizeof(to_pty.data));
1159
	if (rc <= 0)
Timothy Stack's avatar
 
Timothy Stack committed
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
	  exit(0);
	if ((pf[0].revents & POLLOUT) && from_pty.inuse > 0) {
	  // Drain our buffer to the output.
	  rc = writeFunc(from_pty.data, from_pty.inuse);
	  if (rc < 0)
	    exit(0);
	  pack_buffer(&from_pty, rc);
	}
	to_pty.inuse = 0; // Nowhere to send.
	gettimeofday(&now, NULL);
	timersub(&now, &before, &diff);
	if (diff.tv_sec > 0 || diff.tv_usec > (POLL_HUP_INTERVAL * 100)) {
	  before = now;
	  fd_count = 2;
	}
	else {
	  fd_count = 1; // Don't poll the master and turn on timeout.
	}
	tweaked = 0;
      }
      else {
	if (!tweaked) {
1182 1183 1184 1185 1186
	  /*
	   * XXX This next bit is a brutal hack to forcefully turn off echo on
	   * the pseudo terminal.  Otherwise we get a nasty loop of data
	   * echoing back and forth.
	   */
Timothy Stack's avatar
 
Timothy Stack committed
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
	  if ((slave = open(path, O_RDONLY)) >= 0) {
	    struct termios tio;
	    
	    tcgetattr(slave, &tio);
	    cfmakeraw(&tio);
	    tio.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ECHOCTL|ECHOKE);
	    tcsetattr(slave, TCSANOW, &tio);
	    close(slave);
	    slave = -1;
	    
	    tweaked = 1;
	  }
	}
	if (pf[1].revents & POLLIN) {
	  rc = read(pf[1].fd,
		    &from_pty.data[from_pty.inuse],
		    sizeof(from_pty.data) - from_pty.inuse);
	  if (rc > 0)
	    from_pty.inuse += rc;
	}
	if (pf[1].revents & POLLOUT) {
	  rc = write(pf[1].fd, to_pty.data, to_pty.inuse);
	  pack_buffer(&to_pty, rc);
	}
	if (pf[0].revents & POLLIN) {
	  rc = readFunc(&to_pty.data[to_pty.inuse],
			sizeof(to_pty.data) - to_pty.inuse);
	  if (rc >= 0)
	    to_pty.inuse += rc;
	  else
	    exit(0);
	}
	if (pf[0].revents & POLLOUT) {
	  rc = writeFunc(from_pty.data, from_pty.inuse);
	  if (rc < 0)
	    exit(0);
	  pack_buffer(&from_pty, rc);
	}
      }
      
      pf[0].events = 0;
      if (to_pty.inuse < sizeof(to_pty.data))
	pf[0].events |= POLLIN;
      if (from_pty.inuse > 0)
	pf[0].events |= POLLOUT;
      
      pf[1].events = POLLHUP;
      if (from_pty.inuse < sizeof(from_pty.data))
	pf[1].events |= POLLIN;
      if (to_pty.inuse > 0)
	pf[1].events |= POLLOUT;
    }
  }
}

#endif