tiptunnel.c 13 KB
Newer Older
Chad Barb's avatar
Chad Barb committed
1 2 3 4 5 6 7 8 9 10
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

Chad Barb's avatar
 
Chad Barb committed
11 12
#ifdef WITHSSL
#include <openssl/ssl.h>
Chad Barb's avatar
 
Chad Barb committed
13
#include <openssl/err.h>
Chad Barb's avatar
 
Chad Barb committed
14
#endif /* WITHSSL */
Chad Barb's avatar
Chad Barb committed
15 16 17

#include "capdecls.h"

Chad Barb's avatar
 
Chad Barb committed
18
int localmode = 0;
19

Chad Barb's avatar
 
Chad Barb committed
20
#define DEFAULT_PROGRAM "xterm -T TIP -e telnet localhost @s"
21

Chad Barb's avatar
Chad Barb committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35
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;

secretkey_t key;

Chad Barb's avatar
 
Chad Barb committed
36 37 38 39 40 41
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
42 43 44 45 46 47 48
void usage();
void loadAcl( const char * filename );
void doConnect();
void doAuthenticate();
void doCreateTunnel();
void doTunnelConnection();

Chad Barb's avatar
 
Chad Barb committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
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
67 68 69

int main( int argc, char ** argv )
{
Chad Barb's avatar
 
Chad Barb committed
70
  const char * name = argv[0];
Chad Barb's avatar
Chad Barb committed
71 72
  int op;

Chad Barb's avatar
 
Chad Barb committed
73 74 75 76 77
#ifdef LOCALBYDEFAULT
  localmode++;
#endif

  while ((op = getopt( argc, argv, "hlsp:rd" )) != -1) {
Chad Barb's avatar
Chad Barb committed
78
    switch (op) {
Chad Barb's avatar
 
Chad Barb committed
79 80 81 82 83 84
      case 'h':
        usage(name);
        break;
      case 'l':
	localmode++;
	break;
Chad Barb's avatar
Chad Barb committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
      case 'p':
        tunnelPort = atoi( optarg );
	break;
      case 'd':
	debug++;
	break;
      case 'r':
	allowRemote++;
	break;
    }
  }

  argc -= optind;
  argv += optind;

  if (argc < 1) {
Chad Barb's avatar
 
Chad Barb committed
101
    usage( name );
Chad Barb's avatar
Chad Barb committed
102 103 104 105
  }

  if (argc > 1) {
    programToLaunch = strdup( argv[1] );    
106
  } else {
Chad Barb's avatar
 
Chad Barb committed
107
    programToLaunch = strdup( DEFAULT_PROGRAM );
Chad Barb's avatar
Chad Barb committed
108 109
  }

Chad Barb's avatar
 
Chad Barb committed
110 111 112 113 114 115 116
  if (localmode) {
    char localAclName[1024];
    sprintf( localAclName, "/var/log/tiplogs/%s.acl", argv[0] );
    loadAcl( localAclName );
  } else {
    loadAcl( argv[0] );
  }
Chad Barb's avatar
Chad Barb committed
117

Chad Barb's avatar
 
Chad Barb committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
#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();
  }

Chad Barb's avatar
Chad Barb committed
134 135
  doAuthenticate();
  doCreateTunnel();
Chad Barb's avatar
 
Chad Barb committed
136

Chad Barb's avatar
Chad Barb committed
137 138
  if (programToLaunch) {
    char portString[12];
139

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

Chad Barb's avatar
 
Chad Barb committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155
    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
156 157 158 159 160
      for (foo = programToLaunch; *foo; foo++) {
	if (*foo == '@') { *foo = '%'; }
      }

      sprintf(runString, programToLaunch, portString);
Chad Barb's avatar
 
Chad Barb committed
161 162 163 164 165 166 167

      if (debug) printf("Running '%s'\n", runString);

      for (foo = runString; *foo; foo++);
      foo[0] = ' ';
      foo[1] = '&';
      foo[2] = '\0';
168

Chad Barb's avatar
 
Chad Barb committed
169 170 171
      system( runString );
    }
   
172
    /*
Chad Barb's avatar
Chad Barb committed
173 174 175 176
    if (!fork()) {
      execlp( programToLaunch, 
	      programToLaunch, "localhost", portString, NULL );
    }
177
    */
Chad Barb's avatar
Chad Barb committed
178
  }
Chad Barb's avatar
 
Chad Barb committed
179
  //if (localmode) { sleep(3); }
Chad Barb's avatar
Chad Barb committed
180 181 182 183
  doTunnelConnection();
  if (debug) { printf("tiptunnel closing.\n"); }
}

Chad Barb's avatar
 
Chad Barb committed
184
void usage(const char * name)
Chad Barb's avatar
Chad Barb committed
185
{
Chad Barb's avatar
 
Chad Barb committed
186 187 188 189 190 191 192 193 194 195 196
#ifdef LOCALBYDEFAULT

  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
	 );

#else

Chad Barb's avatar
 
Chad Barb committed
197 198 199 200 201
  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
202
  printf("Usage:\n"
Chad Barb's avatar
 
Chad Barb committed
203 204 205 206 207
	 "%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
208
	 "-p <portnum>     specifies tunnel port number\n"
Chad Barb's avatar
 
Chad Barb committed
209
	 "-d               turns on more verbose debug messages\n"
Chad Barb's avatar
Chad Barb committed
210 211
	 "-r               allows connections to tunnel from non-localhost\n"
	 "\n"
Chad Barb's avatar
 
Chad Barb committed
212 213
	 "<program>        (non-local-mode only)\n"
	 "                 path of program to launch; default is\n"
Chad Barb's avatar
 
Chad Barb committed
214 215
	 "                 \"%s\"\n"
         "                 ('@s' indicates where to put port number.)\n",
Chad Barb's avatar
 
Chad Barb committed
216
	 name,
217
         DEFAULT_PROGRAM
Chad Barb's avatar
 
Chad Barb committed
218
	 //"-k keeps accepting connections until killed"
Chad Barb's avatar
Chad Barb committed
219
	 );
Chad Barb's avatar
 
Chad Barb committed
220 221

#endif
Chad Barb's avatar
Chad Barb committed
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
  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) {
    if ( strcmp(b1, "host:") == 0 ) {
      hostname = strdup( b2 );
    } else if ( strcmp(b1, "port:") == 0 ) {
      port = atoi( b2 );
    } else if ( strcmp(b1, "keylen:") == 0 ) {
      key.keylen = atoi( b2 );
    } else if ( strcmp(b1, "key:") == 0 ) {
      strcpy( key.key, b2 );
Chad Barb's avatar
 
Chad Barb committed
250 251 252 253 254 255
#ifdef WITHSSL
    } 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
256 257 258 259 260 261 262 263 264 265 266 267
    } else {
      fprintf(stderr, "Ignored unknown ACL: %s %s\n", b1, b2);
    }
  }

  if (!port || !hostname || !key.keylen || !strlen(key.key)) {
    fprintf(stderr, "Incomplete ACL\n");
    exit(-1);
  }

}

Chad Barb's avatar
 
Chad Barb committed
268 269 270 271 272 273 274 275 276 277
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
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
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
311 312 313 314
  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
315
      return;
Chad Barb's avatar
 
Chad Barb committed
316
    case CAPBUSY:       
Chad Barb's avatar
Chad Barb committed
317
      fprintf(stderr, "Tip line busy.\n");
Chad Barb's avatar
 
Chad Barb committed
318 319 320 321 322 323 324
      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
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
    }
  } 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
370
  if (debug) { printf("Listening on port %i.\n", tunnelPort); }
Chad Barb's avatar
Chad Barb committed
371 372 373 374 375 376 377 378 379

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

void doTunnelConnection()
{
Chad Barb's avatar
 
Chad Barb committed
380
  int i;
Chad Barb's avatar
Chad Barb committed
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
  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
409 410 411 412 413
  if (conSock == 0) {
    if (debug) { printf("Zero consock. Retrying.\n" ); }
    goto acceptor;
  }

Chad Barb's avatar
 
Chad Barb committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
  { 
    /*
      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
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  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
459

Chad Barb's avatar
 
Chad Barb committed
460 461 462 463 464 465 466 467
      /*  
	  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) {
468 469 470 471 472 473 474 475 476 477 478 479 480 481

	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
482 483 484 485
	if (writeFunc( /*sock,*/ buf, got ) < 0) {
	  perror("write sock");
	  return;
	}
486
      } 
Chad Barb's avatar
Chad Barb committed
487 488 489
    }

    if ( FD_ISSET( sock, &fds ) ) {
Chad Barb's avatar
 
Chad Barb committed
490
      int got = readFunc( /*sock,*/ buf, 4096);
Chad Barb's avatar
Chad Barb committed
491 492 493 494 495 496
      if (got <= 0) {
	if (got < 0) { perror("read sock"); }
	if (debug) { printf("sock read %i; exiting.\n", got); }
	return;
      }

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

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
      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
515 516 517 518
      }
    }
  }
}
Chad Barb's avatar
 
Chad Barb committed
519 520 521 522 523 524 525 526


#ifdef WITHSSL

void initSSL()
{
  SSL_library_init();
  ctx = SSL_CTX_new( SSLv23_method() );
Chad Barb's avatar
 
Chad Barb committed
527
  SSL_load_error_strings();
Chad Barb's avatar
 
Chad Barb committed
528 529 530 531 532 533 534 535 536 537 538 539
  
  //  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
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
  
  // inform server of desire to use SSL
  {
    secretkey_t sslHintKey;
    char ret[4];

    sslHintKey.keylen = 7;
    strncpy( sslHintKey.key, "USESSL", 7 );
    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);
    }
    */
  } 
Chad Barb's avatar
 
Chad Barb committed
557 558 559 560

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

Chad Barb's avatar
 
Chad Barb committed
561 562 563 564 565 566 567 568 569 570
  /*
  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
571 572
  // sbio = BIO_new_socket( sock, BIO_NOCLOSE );
  // SSL_set_bio( ssl, sbio, sbio );
Chad Barb's avatar
 
Chad Barb committed
573
  sleep(1);
Chad Barb's avatar
 
Chad Barb committed
574 575 576
  
  if (SSL_connect( ssl ) <= 0) {
    fprintf(stderr, "SSL Connect error.\n");
Chad Barb's avatar
 
Chad Barb committed
577
    ERR_print_errors_fp( stderr );
Chad Barb's avatar
 
Chad Barb committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    exit(-1);
  }

  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 );

  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
601
  if (/*!localmode && */0 != strcmp( certString, digestHex )) {
Chad Barb's avatar
 
Chad Barb committed
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    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 */