Skip to content
This repository
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 671 lines (527 sloc) 19.186 kb
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
//
// Tunnel.m
// MongoHub
//
// Created by Syd on 10-12-15.
// Copyright 2010 ThePeppersStudio.COM. All rights reserved.
//

#import "Tunnel.h"
#import <Security/Security.h>
#import "NSString+Extras.h"

#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/sysctl.h>

typedef struct kinfo_proc kinfo_proc;

static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount)
// Returns a list of all BSD processes on the system. This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount. You are responsible for freeing
// this list (use "free" from System framework).
// On success, the function returns 0.
// On error, the function returns a BSD errno value.
{
    int err;
    kinfo_proc * result;
    bool done;
    static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
    // Declaring name as const requires us to cast it when passing it to
    // sysctl because the prototype doesn't include the const modifier.
    size_t length;

    assert( procList != NULL);
    assert(*procList == NULL);
    assert(procCount != NULL);

    *procCount = 0;

    // We start by calling sysctl with result == NULL and length == 0.
    // That will succeed, and set length to the appropriate length.
    // We then allocate a buffer of that size and call sysctl again
    // with that buffer. If that succeeds, we're done. If that fails
    // with ENOMEM, we have to throw away our buffer and loop. Note
    // that the loop causes use to call sysctl with NULL again; this
    // is necessary because the ENOMEM failure case sets length to
    // the amount of data returned, not the amount of data that
    // could have been returned.

    result = NULL;
    done = false;
    do {
        assert(result == NULL);

        // Call sysctl with a NULL buffer.

        length = 0;
        err = sysctl( (int *) name, (sizeof(name) / sizeof(*name)) - 1,
NULL, &length,
NULL, 0);
        if (err == -1) {
            err = errno;
        }

        // Allocate an appropriately sized buffer based on the results
        // from the previous call.

        if (err == 0) {
            result = malloc(length);
            if (result == NULL) {
                err = ENOMEM;
            }
        }

        // Call sysctl again with the new buffer. If we get an ENOMEM
        // error, toss away our buffer and start again.

        if (err == 0) {
            err = sysctl( (int *) name, (sizeof(name) / sizeof(*name)) - 1,
result, &length,
NULL, 0);
            if (err == -1) {
                err = errno;
            }
            if (err == 0) {
                done = true;
            } else if (err == ENOMEM) {
                assert(result != NULL);
                free(result);
                result = NULL;
                err = 0;
            }
        }
    } while (err == 0 && ! done);

    // Clean up and establish post conditions.

    if (err != 0 && result != NULL) {
        free(result);
        result = NULL;
    }
    *procList = result;
    if (err == 0) {
        *procCount = length / sizeof(kinfo_proc);
    }

    assert( (err == 0) == (*procList != NULL) );

    return err;
}


static int GetFirstChildPID(int pid)
/*" Returns the parent process id
for the given process id (pid). "*/
{
int pidFound = -1;

kinfo_proc* plist = nil;
size_t len = 0;
GetBSDProcessList(&plist,&len);

if(plist != nil){
for(int i = 0;i<len;i++){
if(plist[i].kp_eproc.e_ppid == pid){
pidFound = plist[i].kp_proc.p_pid;
break;
}
}

free(plist);
}

return pidFound;
}

@implementation Tunnel

- (id) init {
if(self = [super init]){
        uid = [NSString UUIDString];
        
        lock = [NSLock new];
        portForwardings = [NSMutableArray array];
        isRunning = NO;
}

return (self);
}

@synthesize uid;
@synthesize name;
@synthesize host;
@synthesize port;
@synthesize user;
@synthesize password;
@synthesize keyfile;
@synthesize aliveInterval;
@synthesize aliveCountMax;
@synthesize tcpKeepAlive;
@synthesize compression;
@synthesize additionalArgs;
@synthesize portForwardings;

- (void)setDelegate:(id)val {
    delegate = val;
}

- (id)delegate {
    return delegate;
}


-(void) start {
[lock lock];

isRunning = YES;

task = [NSTask new];
pipe = [NSPipe pipe];

[task setLaunchPath: [[NSBundle bundleForClass:[self class]] pathForResource: @"SSHCommand" ofType: @"sh"] ];
[task setArguments: [self prepareSSHCommandArgs] ];
[task setStandardOutput: pipe];
//The magic line that keeps your log where it belongs
[task setStandardInput:[NSPipe pipe]];

[task launch];
    /*NSData *output = [[pipe fileHandleForReading] readDataToEndOfFile];
NSString *string = [[[NSString alloc] initWithData: output encoding: NSUTF8StringEncoding] autorelease];
NSLog(@"\n%@\n", string);*/
pipeData = @"";
retStatus = @"";
startDate = [NSDate date];
NSLog(@"%@", startDate);
if ( [delegate respondsToSelector:@selector(tunnelStatusChanged:status:)] ) {
[delegate tunnelStatusChanged: self status: @"START"];
}

[lock unlock];
}

-(void) stop {
[lock lock];

isRunning = NO;
    
if ( [task isRunning] ){
int chpid = GetFirstChildPID([task processIdentifier]);
if(chpid != -1)
kill(chpid, SIGTERM);
[task terminate];
task = nil;
}
if ( [delegate respondsToSelector:@selector(tunnelStatusChanged:status:)] ) {
[delegate tunnelStatusChanged: self status: @"STOP"];
}

[lock unlock];
}

-(BOOL) running {
BOOL ret = NO;

[lock lock];
ret = isRunning;
[lock unlock];

return ret;
}

-(void) readStatus {
[lock lock];
if(isRunning && [retStatus isEqualToString: @""]){
NSString *pipeStr = [[NSString alloc] initWithData: [[pipe fileHandleForReading] availableData] encoding: NSASCIIStringEncoding];
        //NSLog(@"%@", pipeStr);
pipeData = [pipeData stringByAppendingString: pipeStr];
        [pipeStr release];
NSRange r = [pipeData rangeOfString: @"CONNECTED"];
if( r.location != NSNotFound ){
retStatus = @"CONNECTED";

if ( [delegate respondsToSelector:@selector(tunnelStatusChanged: status:)] ) {
[delegate tunnelStatusChanged: self status: retStatus];
}
[lock unlock];
return;
}

r = [pipeData rangeOfString: @"CONNECTION_ERROR"];
if( r.location != NSNotFound ){
retStatus = @"CONNECTION_ERROR";

if ( [delegate respondsToSelector:@selector(tunnelStatusChanged: status:)] ) {
[delegate tunnelStatusChanged: self status: retStatus];
}
[lock unlock];
return;
}

r = [pipeData rangeOfString: @"CONNECTION_REFUSED"];
if( r.location != NSNotFound ){
retStatus = @"CONNECTION_REFUSED";

if ( [delegate respondsToSelector:@selector(tunnelStatusChanged: status:)] ) {
[delegate tunnelStatusChanged: self status: retStatus];
}
[lock unlock];
return;
}

r = [pipeData rangeOfString: @"WRONG_PASSWORD"];
if( r.location != NSNotFound ){
retStatus = @"WRONG_PASSWORD";

if ( [delegate respondsToSelector:@selector(tunnelStatusChanged: status:)] ) {
[delegate tunnelStatusChanged: self status: retStatus];
}
[lock unlock];
return;
}
//NSLog(@"%@", startDate);
/*if( [[NSDate date] timeIntervalSinceDate: startDate] > 30 ){
retStatus = @"TIME_OUT";
if ( [delegate respondsToSelector:@selector(tunnelStatusChanged: status:)] ) {
[delegate tunnelStatusChanged: self status: retStatus];
}
return;
}*/
}
[lock unlock];
}

-(BOOL) checkProcess {
BOOL ret = NO;
[lock lock];
ret = isRunning;
if( ret )
ret = GetFirstChildPID( [task processIdentifier] ) != -1;
[lock unlock];

return ret;
}

-(NSArray*) prepareSSHCommandArgs {

NSString* pfs = @"";
for(NSString* pf in portForwardings){
NSArray* pfa = [pf componentsSeparatedByString: @":"];
pfs = [NSString stringWithFormat: @"%@ -%@ %@:%@:%@:%@", pfs, [pfa objectAtIndex: 0], [pfa objectAtIndex: 2], [pfa objectAtIndex: 1], [pfa objectAtIndex: 3], [pfa objectAtIndex: 4] ];
}

NSString* cmd;
    if ([password isNotEqualTo:@""]|| [keyfile isEqualToString:@""]) {
        cmd = [NSString stringWithFormat: @"ssh -N -o ConnectTimeout=28 %@%@%@%@%@%@-p %d %@@%@",
               [additionalArgs length] > 0 ? [NSString stringWithFormat: @"%@ ", additionalArgs] : @"",
               [pfs length] > 0 ? [NSString stringWithFormat: @"%@ ",pfs] : @"",
               aliveInterval > 0 ? [NSString stringWithFormat: @"-o ServerAliveInterval=%d ",aliveInterval] : @"",
               aliveCountMax > 0 ? [NSString stringWithFormat: @"-o ServerAliveCountMax=%d ",aliveCountMax] : @"",
               tcpKeepAlive == YES ? @"-o TCPKeepAlive=yes " : @"",
               compression == YES ? @"-C " : @"",
               port,user,host];
    }else {
        cmd = [NSString stringWithFormat: @"ssh -N -o ConnectTimeout=28 %@%@%@%@%@%@-p %d -i %@ %@@%@",
               [additionalArgs length] > 0 ? [NSString stringWithFormat: @"%@ ", additionalArgs] : @"",
               [pfs length] > 0 ? [NSString stringWithFormat: @"%@ ",pfs] : @"",
               aliveInterval > 0 ? [NSString stringWithFormat: @"-o ServerAliveInterval=%d ",aliveInterval] : @"",
               aliveCountMax > 0 ? [NSString stringWithFormat: @"-o ServerAliveCountMax=%d ",aliveCountMax] : @"",
               tcpKeepAlive == YES ? @"-o TCPKeepAlive=yes " : @"",
               compression == YES ? @"-C " : @"",
               port,keyfile,user,host];
    }

    
NSLog(@"cmd: %@", cmd);
return [NSArray arrayWithObjects: cmd, password, nil];
}

-(void) tunnelLoaded {

if(uid == nil || [uid length] == 0){
CFUUIDRef uidref = CFUUIDCreate(nil);
uid = (NSString*)CFUUIDCreateString(nil, uidref);
CFRelease(uidref);
}

if([self keychainItemExists]){
password = [self keychainGetPassword];
}else{
password = @"";
}
}

-(void) tunnelSaved{
if([self keychainItemExists]){
[self keychainModifyItem];
}else{
[self keychainAddItem];
}
}

-(void) tunnelRemoved {
if([self keychainItemExists])
[self keychainDeleteItem];
}

-(BOOL) keychainItemExists {

SecKeychainSearchRef search;
SecKeychainAttributeList list;
SecKeychainAttribute attributes[3];

NSString* keychainItemName = [NSString stringWithFormat: @"SSHTunnel <%@>", uid];
NSString* keychainItemKind = @"application password";

attributes[0].tag = kSecAccountItemAttr;
    attributes[0].data = (void *)[uid UTF8String];
    attributes[0].length = [uid length];
    
    attributes[1].tag = kSecDescriptionItemAttr;
    attributes[1].data = (void *)[keychainItemKind UTF8String];
    attributes[1].length = [keychainItemKind length];

attributes[2].tag = kSecLabelItemAttr;
    attributes[2].data = (void *)[keychainItemName UTF8String];
    attributes[2].length = [keychainItemName length];

list.count = 3;
list.attr = attributes;

OSErr result = SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &list, &search);

    if (result != noErr) {
        NSLog (@"Error status %d from SecKeychainSearchCreateFromAttributes\n", result);
return FALSE;
    }

uint itemsFound = 0;
SecKeychainItemRef item;

while (SecKeychainSearchCopyNext (search, &item) == noErr) {
        CFRelease (item);
        itemsFound++;
    }

CFRelease (search);
return itemsFound > 0;
}

-(BOOL) keychainAddItem {

SecKeychainItemRef item;
SecKeychainAttributeList list;
SecKeychainAttribute attributes[3];

NSString* keychainItemName = [NSString stringWithFormat: @"SSHTunnel <%@>", uid];
NSString* keychainItemKind = @"application password";

attributes[0].tag = kSecAccountItemAttr;
    attributes[0].data = (void *)[uid UTF8String];
    attributes[0].length = [uid length];
    
    attributes[1].tag = kSecDescriptionItemAttr;
    attributes[1].data = (void *)[keychainItemKind UTF8String];
    attributes[1].length = [keychainItemKind length];

attributes[2].tag = kSecLabelItemAttr;
    attributes[2].data = (void *)[keychainItemName UTF8String];
    attributes[2].length = [keychainItemName length];

list.count = 3;
list.attr = attributes;

OSStatus status = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &list, [password length], [password UTF8String], NULL,NULL,&item);
    if (status != 0) {
        NSLog(@"Error creating new item: %d for %@\n", (int)status, keychainItemName);
    }

return !status;
}

-(BOOL) keychainModifyItem {

SecKeychainItemRef item;
SecKeychainSearchRef search;
    OSStatus status;
OSErr result;
SecKeychainAttributeList list;
SecKeychainAttribute attributes[3];

NSString* keychainItemName = [NSString stringWithFormat: @"SSHTunnel <%@>", uid];
NSString* keychainItemKind = @"application password";

attributes[0].tag = kSecAccountItemAttr;
    attributes[0].data = (void *)[uid UTF8String];
    attributes[0].length = [uid length];
    
    attributes[1].tag = kSecDescriptionItemAttr;
    attributes[1].data = (void *)[keychainItemKind UTF8String];
    attributes[1].length = [keychainItemKind length];

attributes[2].tag = kSecLabelItemAttr;
    attributes[2].data = (void *)[keychainItemName UTF8String];
    attributes[2].length = [keychainItemName length];

list.count = 3;
list.attr = attributes;

result = SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &list, &search);
    NSLog(@"%@", result);
SecKeychainSearchCopyNext (search, &item);
    status = SecKeychainItemModifyContent(item, &list, [password length], [password UTF8String]);

    if (status != 0) {
        NSLog(@"Error modifying item: %d", (int)status);
    }

CFRelease (item);
CFRelease(search);

return !status;
}

-(BOOL) keychainDeleteItem {

SecKeychainItemRef item;
SecKeychainSearchRef search;
    OSStatus status = 0;
OSErr result;
SecKeychainAttributeList list;
SecKeychainAttribute attributes[3];
uint itemsFound = 0;

NSString* keychainItemName = [NSString stringWithFormat: @"SSHTunnel <%@>", uid];
NSString* keychainItemKind = @"application password";

attributes[0].tag = kSecAccountItemAttr;
    attributes[0].data = (void *)[uid UTF8String];
    attributes[0].length = [uid length];
    
    attributes[1].tag = kSecDescriptionItemAttr;
    attributes[1].data = (void *)[keychainItemKind UTF8String];
    attributes[1].length = [keychainItemKind length];

attributes[2].tag = kSecLabelItemAttr;
    attributes[2].data = (void *)[keychainItemName UTF8String];
    attributes[2].length = [keychainItemName length];

list.count = 3;
list.attr = attributes;

result = SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &list, &search);
    NSLog(@"%@", result);
while (SecKeychainSearchCopyNext (search, &item) == noErr) {
        itemsFound++;
    }
if (itemsFound) {
status = SecKeychainItemDelete(item);
}

    if (status != 0) {
        NSLog(@"Error deleting item: %d\n", (int)status);
    }
CFRelease (item);
CFRelease (search);

return !status;
}

-(NSString*) keychainGetPassword {

SecKeychainItemRef item;
SecKeychainSearchRef search;
    OSErr result;
SecKeychainAttributeList list;
SecKeychainAttribute attributes[3];

NSString* keychainItemName = [NSString stringWithFormat: @"SSHTunnel <%@>", uid];
NSString* keychainItemKind = @"application password";

attributes[0].tag = kSecAccountItemAttr;
    attributes[0].data = (void *)[uid UTF8String];
    attributes[0].length = [uid length];
    
    attributes[1].tag = kSecDescriptionItemAttr;
    attributes[1].data = (void *)[keychainItemKind UTF8String];
    attributes[1].length = [keychainItemKind length];

attributes[2].tag = kSecLabelItemAttr;
    attributes[2].data = (void *)[keychainItemName UTF8String];
    attributes[2].length = [keychainItemName length];


list.count = 3;
list.attr = attributes;

result = SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &list, &search);

    if (result != noErr) {
        NSLog (@"status %d from SecKeychainSearchCreateFromAttributes\n", result);
    }

NSString *pass = @"";
    if (SecKeychainSearchCopyNext (search, &item) == noErr) {
pass = [self keychainGetPasswordFromItemRef:item];
if(!pass) {
pass = @"";
}
CFRelease (item);
CFRelease (search);
}

return pass;
}

-(NSString*) keychainGetPasswordFromItemRef: (SecKeychainItemRef)item {

NSString* retPass = nil;

UInt32 length;
    char *pass;
    SecKeychainAttribute attributes[8];
    SecKeychainAttributeList list;
    OSStatus status;

    attributes[0].tag = kSecAccountItemAttr;
    attributes[1].tag = kSecDescriptionItemAttr;
    attributes[2].tag = kSecLabelItemAttr;
    attributes[3].tag = kSecModDateItemAttr;

    list.count = 4;
    list.attr = attributes;

    status = SecKeychainItemCopyContent (item, NULL, &list, &length, (void **)&pass);

if (status == noErr) {
        if (pass != NULL) {

            // copy the password into a buffer so we can attach a
            // trailing zero byte in order to be able to print
            // it out with printf
            char passwordBuffer[1024];

            if (length > 1023) {
                length = 1023; // save room for trailing \0
            }
            strncpy (passwordBuffer, pass, length);

            passwordBuffer[length] = '\0';

retPass = [NSString stringWithUTF8String:passwordBuffer];
        }

        SecKeychainItemFreeContent (&list, pass);

return retPass;
    } else {
        printf("Error getting password = %d\n", (int)status);
return @"";
    }
}

- (void)encodeWithCoder:(NSCoder *)coder {

[coder encodeObject: uid forKey: @"uid"];
[coder encodeObject: name forKey: @"name"];
[coder encodeObject: host forKey: @"host"];
[coder encodeInt: port forKey: @"port"];
[coder encodeObject: user forKey: @"user"];
    [coder encodeObject: password forKey: @"password"];
    [coder encodeObject: keyfile forKey: @"keyfile"];
[coder encodeInt: aliveInterval forKey: @"aliveInterval"];
[coder encodeInt: aliveCountMax forKey: @"aliveCountMax"];
[coder encodeBool: tcpKeepAlive forKey: @"tcpKeepAlive"];
[coder encodeBool: compression forKey: @"compression"];
[coder encodeObject: additionalArgs forKey: @"additionalArgs"];
[coder encodeObject: portForwardings forKey: @"portForwardings"];

[self tunnelSaved];
}

- (id)initWithCoder:(NSCoder *)coder {

uid = [coder decodeObjectForKey: @"uid"];
name = [coder decodeObjectForKey: @"name"];
host = [coder decodeObjectForKey: @"host"];
port = [coder decodeIntForKey: @"port"];
user = [coder decodeObjectForKey: @"user"];
    password = [coder decodeObjectForKey: @"password"];
    keyfile = [coder decodeObjectForKey: @"keyfile"];
aliveInterval = [coder decodeIntForKey: @"aliveInterval"];
aliveCountMax = [coder decodeIntForKey: @"aliveCountMax"];
tcpKeepAlive = [coder decodeBoolForKey: @"tcpKeepAlive"];
compression = [coder decodeBoolForKey: @"compression"];
additionalArgs = [coder decodeObjectForKey: @"additionalArgs"];
portForwardings = [coder decodeObjectForKey: @"portForwardings"];

[self tunnelLoaded];

return (self);
}

@end
Something went wrong with that request. Please try again.