forked from blinksh/blink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSSHClient.m
1460 lines (1219 loc) · 40 KB
/
SSHClient.m
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
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
//////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2018 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink 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 3 of the License, or
// (at your option) any later version.
//
// Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
#import "SSHClient.h"
#import "BKHosts.h"
#import "BKPubKey.h"
#import "SSHClientConnectedChannel.h"
#import "SSHClientPortListener.h"
#import "BlinkPaths.h"
#import <signal.h>
#import <pthread.h>
#import <poll.h>
#include <sys/ioctl.h>
#include <libssh/callbacks.h>
#import <sys/socket.h>
#import <sys/un.h>
#import <arpa/inet.h>
void __write(dispatch_fd_t fd, NSString *message) {
if (message == nil) {
return;
}
write(fd, message.UTF8String, [message lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
}
void __write_ssh_chars_and_free(dispatch_fd_t fd, char *buffer) {
if (buffer == NULL) {
return;
}
write(fd, buffer, strlen(buffer));
ssh_string_free_char(buffer);
}
@interface SSHClient (internal) <SSHClientConnectedChannelDelegate, SSHClientPortListenerDelegate>
- (int) _ssh_auth_fn_prompt:(const char *)prompt buf:(char *)buf len:(size_t) len echo:(int) echo verify:(int)verify;
@end
int __ssh_auth_fn(const char *prompt, char *buf, size_t len,
int echo, int verify, void *userdata) {
SSHClient *client = (__bridge SSHClient *)userdata;
return [client _ssh_auth_fn_prompt:prompt buf:buf len:len echo:echo verify:verify];
}
@implementation SSHClient {
SSHClientOptions *_options;
ssh_session _session;
NSTimer *_serverKeepAliveTimer;
NSRunLoop *_runLoop;
dispatch_fd_t _fdIn;
dispatch_fd_t _fdOut;
dispatch_fd_t _fdErr;
BOOL _isTTY;
NSMutableArray<SSHClientPortListener *> *_portListeners;
SSHClientConnectedChannel *_sessionChannel;
NSMutableArray<SSHClientConnectedChannel *> *_connectedChannels;
NSMutableDictionary<NSNumber *, NSNumber *> *_reversePortsMap;
struct ssh_callbacks_struct _ssh_callbacks;
BOOL _doExit;
BOOL _killed;
int _exitCode;
__weak TermDevice *_device;
}
- (instancetype)initWithStdIn:(dispatch_fd_t)fdIn stdOut:(dispatch_fd_t)fdOut stdErr:(dispatch_fd_t)fdErr device:(TermDevice *)device isTTY:(BOOL)isTTY {
if (self = [super init]) {
_portListeners = [[NSMutableArray alloc] init];
_connectedChannels = [[NSMutableArray alloc] init];
_device = device;
_fdIn = fdIn;
_fdOut = fdOut;
_fdErr = fdErr;
_options = [[SSHClientOptions alloc] init];
_runLoop = [NSRunLoop currentRunLoop];
_isTTY = isTTY;
_doExit = NO;
_killed = NO;
_exitCode = 0;
}
return self;
}
- (void)close {
if (_serverKeepAliveTimer) {
[_serverKeepAliveTimer invalidate];
_serverKeepAliveTimer = nil;
}
for (SSHClientConnectedChannel *connectedChannel in _connectedChannels) {
connectedChannel.delegate = nil;
[connectedChannel close];
}
_connectedChannels = nil;
for (SSHClientPortListener *listener in _portListeners) {
listener.delegate = nil;
[listener close];
}
_portListeners = nil;
if (_sessionChannel) {
_sessionChannel.delegate = nil;
[_sessionChannel close];
_sessionChannel = nil;
}
if (_session) {
ssh_free(_session);
_session = NULL;
}
_ssh_callbacks.userdata = NULL;
_doExit = YES;
}
- (void)dealloc {
[self close];
}
#pragma mark - UTILS
- (void)sigwinch {
__weak SSHClient *weakSelf = self;
[self _schedule:^{
SSHClient *client = weakSelf;
if (client == nil) {
return;
}
ssh_channel channel = client->_sessionChannel.channel;
if (channel == NULL) {
return;
}
ssh_channel_change_pty_size(channel, _device->win.ws_col, _device->win.ws_row);
}];
}
- (void)kill {
_killed = YES;
__weak SSHClient *weakSelf = self;
[self _schedule:^{
[weakSelf _exitWithCode:-1];
}];
}
- (int)_exitWithCode:(int)code {
_doExit = YES;
_exitCode = code;
[self close];
return code;
}
- (int)_exitWithCode:(int)code andMessage: (NSString *)message {
if (message == nil) {
return [self _exitWithCode:code];
}
message = [message stringByAppendingString:@"\n"];
__write(_fdErr, message);
return [self _exitWithCode:code];
}
- (void)_schedule:(dispatch_block_t)block {
[_runLoop performBlock:block];
}
- (int)_ssh_auth_fn_prompt:(const char *)prompt buf:(char *)buf len:(size_t) len echo:(int) echo verify:(int)verify {
NSString *nsPrompt = @(prompt);
if (![nsPrompt hasSuffix:@":"]) {
nsPrompt = [nsPrompt stringByAppendingString:@":"];
}
NSString *answer = [[self _getAnswersWithName:nil instruction:nil andPrompts:@[@[nsPrompt, @(echo)]]] firstObject];
if (!answer) {
return SSH_ERROR;
}
if (![answer getCString:buf maxLength:len encoding:NSUTF8StringEncoding]) {
return SSH_ERROR;
}
return SSH_OK;
}
- (void)_printVersion {
ssh_session s = ssh_new();
int v = ssh_get_openssh_version(s);
NSArray<NSString *> *lines = @[
[NSString stringWithFormat:@"%@", @(v)],
@"",
];
NSString *message = [lines componentsJoinedByString:@"\n"];
[self _exitWithCode:SSH_OK andMessage:message];
}
- (NSArray<NSString *>*)_getAnswersWithName:(NSString *)name instruction: (NSString *)instruction andPrompts:(NSArray *)prompts {
BOOL rawMode = _device.rawMode;
[_device setRawMode:NO];
if (name.length > 0) {
name = [name stringByAppendingString:@"\n"];
fwrite(name.UTF8String, [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding], 1, _device.stream.out);
}
if (instruction.length > 0) {
instruction = [instruction stringByAppendingString:@"\n"];
fwrite(instruction.UTF8String, [instruction lengthOfBytesUsingEncoding:NSUTF8StringEncoding], 1, _device.stream.out);
}
NSMutableArray<NSString *> *answers = [[NSMutableArray alloc] init];
BOOL echoMode = _device.echoMode;
for (int i = 0; i < prompts.count; i++) {
BOOL echo = [prompts[i][1] boolValue];
_device.echoMode = echo;
NSString *prompt = prompts[i][0];
// write prompt directly to device stream?...
fwrite(prompt.UTF8String, [prompt lengthOfBytesUsingEncoding:NSUTF8StringEncoding], 1, _device.stream.out);
char * line = NULL;
size_t len = 0;
ssize_t read = getline(&line, &len, _device.stream.in);
if (read == -1) {
[self _log_verbose:@"Can't read input"];
}
if (line) {
NSString * lineStr = [@(line) stringByReplacingOccurrencesOfString:@"\n" withString:@""];
[answers addObject:lineStr];
free(line);
}
fwrite("\n", 1, 1, _device.stream.out);
// fclose(fp);
}
[_device setEchoMode:echoMode];
[_device setRawMode:rawMode];
return answers;
}
- (void)_poll {
[_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
- (BOOL)_notConnected {
return _doExit || !ssh_is_connected(_session);
}
#pragma mark - CONNECT
- (int)_connect {
int attempts = [_options[SSHOptionConnectionAttempts] intValue];
if (attempts <= 0) {
attempts = 1;
}
bool tcpKeepAlive = [_options[SSHOptionTCPKeepAlive] isEqual:SSHOptionValueYES];
NSNumber *connectTimeout = _options[SSHOptionConnectTimeout];
NSDate *connectStart = [NSDate date];
for(;;) {
if (_doExit) {
return SSH_ERROR;
}
if (connectTimeout.integerValue > 0 && -connectStart.timeIntervalSinceNow > connectTimeout.integerValue) {
[self _log_info:@"Connect timeout"];
return SSH_ERROR;
}
int rc = ssh_connect(_session);
switch(rc) {
case SSH_AGAIN:
[self _poll];
continue;
case SSH_ERROR: {
const char *err = ssh_get_error(_session);
NSString *error = [NSString stringWithUTF8String:err];
if (error) {
// Check compression error
NSString *noCompressionOnServer = @"no match for method compression algo client->server: server [none]";
if ([_options[SSHOptionCompression] isEqual:SSHOptionValueYES] && [error containsString:noCompressionOnServer]) {
ssh_free(_session);
[self _log_verbose:@"Server doesn't support compression. Connecting without compression\n"];
_options[[SSHOptionCompression copy]] = [SSHOptionValueNO copy];
_session = [self _configured_session];
continue;
}
[self _log_error];
}
attempts--;
if (attempts > 0) {
ssh_free(_session);
_session = [self _configured_session];
connectStart = [NSDate date];
continue;
}
}
return rc;
case SSH_OK: {
int sock = ssh_get_fd(_session);
CFSocketRef sockRef = CFSocketCreateWithNative(NULL, sock, 0, NULL, NULL);
NSData * data = (__bridge_transfer NSData *)CFSocketCopyPeerAddress(sockRef);
CFRelease(sockRef);
if (data) {
// We got connected to socket. Lets tune it
int flags = 0;
socklen_t optlen = 0;
if (getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &flags, &optlen)) {
return SSH_ERROR;
}
if (flags != tcpKeepAlive) {
flags = tcpKeepAlive;
[self _log_verbose:[NSString stringWithFormat:@"setting socket keepalive: %@\n", @(tcpKeepAlive)]];
if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags))) {
return SSH_ERROR;
}
}
// Print peer host to pickup in mosh command
char host[NI_MAXHOST];
getnameinfo((const struct sockaddr *)[data bytes], (socklen_t)data.length, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
NSString *address = [NSString stringWithUTF8String:host];
if (address && address.length && [_options[SSHOptionPrintAddress] isEqual:SSHOptionValueYES]) {
[self _log_info:[NSString stringWithFormat:@"Connected to %@", address]];
}
}
return rc;
}
default:
return rc;
}
}
}
#pragma mark - AUTHENTICATION
- (int)_auth {
// 1. try auth none
int rc = [self _auth_none];
// Who knows? we can success here too. See https://github.com/blinksh/blink/issues/450
if (rc == SSH_AUTH_SUCCESS) {
return SSH_OK;
}
if (rc == SSH_AUTH_ERROR) {
return SSH_ERROR;
}
// 2. print issue banner if any
__write_ssh_chars_and_free(_fdOut, ssh_get_issue_banner(_session));
BOOL optionPasswordAuth = [SSHOptionValueYES isEqual:_options[SSHOptionPasswordAuthentication]];
BOOL optionKbdInteractiveAuth = [SSHOptionValueYES isEqual:_options[SSHOptionKbdInteractiveAuthentication]];
BOOL optionPubKeyAuth = [SSHOptionValueYES isEqual:_options[SSHOptionPubkeyAuthentication]];
BOOL optionIdenitiesOnly = [SSHOptionValueYES isEqual:_options[SSHOptionIdentitiesOnly]];
int optionPasswordPromptsCount = [_options[SSHOptionNumberOfPasswordPrompts] intValue];
NSString *optionPassword = _options[SSHOptionPassword];
if (optionPassword.length == 0) {
optionPassword = nil;
}
int maxPartialAuths = 5;
for (int i = 0; i < maxPartialAuths; i++) {
[self _log_verbose:[NSString stringWithFormat:@"using auth methods attempt: %@ of %@\n", @(i + 1), @(maxPartialAuths)]];
// 3. get auth methods from server
int methods = ssh_userauth_list(_session, NULL);
// 4. user entered password in settings. So try to use it first to save AuthTries
if (optionPassword) {
if (methods & SSH_AUTH_METHOD_PASSWORD && optionPasswordAuth) {
rc = [self _auth_with_password: optionPassword prompts: 1];
if (rc == SSH_AUTH_SUCCESS) {
return SSH_OK;
} else if (rc == SSH_AUTH_PARTIAL) {
continue;
}
} else if (methods & SSH_AUTH_METHOD_INTERACTIVE && optionKbdInteractiveAuth) {
rc = [self _auth_with_interactive_with_password:optionPassword prompts:1];
if (rc == SSH_AUTH_SUCCESS) {
return SSH_OK;
} else if (rc == SSH_AUTH_PARTIAL) {
continue;
}
}
}
// 5. public keys
// 5.1 Agent first if possible
if (methods & SSH_AUTH_METHOD_PUBLICKEY && optionPubKeyAuth && !optionIdenitiesOnly) {
rc = [self _auth_with_agent];
if (rc == SSH_AUTH_SUCCESS) {
return SSH_OK;
} else if (rc == SSH_AUTH_PARTIAL) {
continue;
}
}
// 5.2 Identities
if (methods & SSH_AUTH_METHOD_PUBLICKEY && optionPubKeyAuth) {
rc = [self _auth_with_publickey];
if (rc == SSH_AUTH_SUCCESS) {
return SSH_OK;
} else if (rc == SSH_AUTH_PARTIAL) {
continue;
}
}
// 6. interactive
if (methods & SSH_AUTH_METHOD_INTERACTIVE && optionKbdInteractiveAuth) {
rc = [self _auth_with_interactive_with_password:optionPassword prompts:optionPasswordPromptsCount];
if (rc == SSH_AUTH_SUCCESS) {
return SSH_OK;
} else if (rc == SSH_AUTH_PARTIAL) {
continue;
}
}
// 7. password
if (methods & SSH_AUTH_METHOD_PASSWORD && optionPasswordAuth) {
// even we don't have password. Ask it
rc = [self _auth_with_password: optionPassword prompts:optionPasswordPromptsCount];
if (rc == SSH_AUTH_SUCCESS) {
return SSH_OK;
} else if (rc == SSH_AUTH_PARTIAL) {
continue;
}
}
break;
}
return [self _exitWithCode:SSH_ERROR];
}
- (int)_auth_none {
for (;;) {
if ([self _notConnected]) {
return SSH_ERROR;
}
int rc = ssh_userauth_none(_session, NULL);
switch (rc) {
case SSH_AUTH_AGAIN:
[self _poll];
continue;
default:
return rc;
}
}
}
- (int)_auth_with_publickey {
int rc = SSH_ERROR;
NSArray<NSString *> *identityfiles = _options[SSHOptionIdentityFile];
for (NSString *identityfile in identityfiles) {
ssh_key pkey;
BKPubKey *secureKey = [BKPubKey withID:identityfile];
NSFileManager *fileManager = [NSFileManager defaultManager];
// we have this identity in
if (secureKey) {
[self _log_verbose:[NSString stringWithFormat:@"import key %@\n", identityfile]];
rc = ssh_pki_import_privkey_base64(secureKey.privateKey.UTF8String,
NULL, /* TODO: get stored */
__ssh_auth_fn,
(__bridge void *) self,
&pkey);
NSString *identityFilePath = [[BlinkPaths ssh] stringByAppendingPathComponent:identityfile];
if ([fileManager fileExistsAtPath:identityFilePath]) {
[self _log_verbose:[NSString stringWithFormat:@"warning: key '%@' duplicate in SE and file system. Using key from SE \n", identityfile]];
}
} else {
NSString *identityFilePath = identityfile;
// if file doesn't exists. Fallback to ~/.ssh/<identifyfile>
if (![fileManager fileExistsAtPath:identityFilePath]) {
identityFilePath = [[BlinkPaths ssh] stringByAppendingPathComponent:identityFilePath];
}
if (![fileManager fileExistsAtPath:identityFilePath]) {
[self _log_verbose:[NSString stringWithFormat:@"warning: no key found: '%@' \n", identityfile]];
continue;
}
[self _log_verbose:[NSString stringWithFormat:@"import key from file %@\n", identityfile]];
rc = ssh_pki_import_privkey_file(identityFilePath.UTF8String,
NULL,
__ssh_auth_fn,
(__bridge void *) self,
&pkey);
}
if (rc == SSH_ERROR) {
continue;
}
bool tryNextIdentityFile = NO;
for (;;) {
if ([self _notConnected]) {
ssh_key_free(pkey);
return SSH_ERROR;
}
rc = ssh_userauth_try_publickey(_session, NULL, pkey);
switch (rc) {
case SSH_AUTH_ERROR:
break;
case SSH_AUTH_SUCCESS:
break;
case SSH_AUTH_AGAIN:
[self _poll];
continue;
case SSH_AUTH_DENIED:
tryNextIdentityFile = YES;
break;
case SSH_AUTH_PARTIAL: {
int methods = ssh_userauth_list(_session, NULL);
tryNextIdentityFile = methods & SSH_AUTH_METHOD_PUBLICKEY;
break;
}
}
break;
}
if (tryNextIdentityFile) {
ssh_key_free(pkey);
continue;
}
if (rc != SSH_AUTH_SUCCESS) {
ssh_key_free(pkey);
return rc;
}
tryNextIdentityFile = NO;
for (;;) {
if ([self _notConnected]) {
ssh_key_free(pkey);
return SSH_ERROR;
}
rc = ssh_userauth_publickey(_session, NULL, pkey);
switch (rc) {
case SSH_AUTH_SUCCESS:
ssh_key_free(pkey);
return rc;
case SSH_AUTH_AGAIN:
[self _poll];
continue;
case SSH_AUTH_DENIED:
tryNextIdentityFile = YES;
break;
case SSH_AUTH_PARTIAL: {
int methods = ssh_userauth_list(_session, NULL);
tryNextIdentityFile = methods & SSH_AUTH_METHOD_PUBLICKEY;
}
break;
default:
break;
}
break;
}
ssh_key_free(pkey);
if (tryNextIdentityFile) {
continue;
}
break;
}
return rc;
}
- (int)_auth_with_agent {
int rc = SSH_ERROR;
for (;;) {
if ([self _notConnected]) {
return SSH_ERROR;
}
rc = ssh_userauth_agent(_session, NULL);
switch (rc) {
case SSH_AUTH_AGAIN:
[self _poll];
continue;
default:
return rc;
}
}
}
- (int)_auth_with_password:(NSString *)password prompts:(int)promptsCount {
for (;;) {
if ([self _notConnected]) {
return SSH_ERROR;
}
if (!password) {
const int NO_ECHO = NO;
NSArray *prompts = @[@[@"Password:", @(NO_ECHO)]];
password = [[self _getAnswersWithName:NULL instruction:NULL andPrompts:prompts] firstObject];
}
int rc = ssh_userauth_password(_session, NULL, password.UTF8String);
switch (rc) {
case SSH_AUTH_AGAIN:
[self _poll];
continue;
case SSH_AUTH_DENIED: {
if (--promptsCount > 0) {
[self _log_info:@"Permission denied, please try again."];
password = nil;
continue;
}
return rc;
}
default:
return rc;
}
}
}
- (int)_auth_with_interactive_with_password:(NSString *)password prompts:(int)promptsCount {
// https://gitlab.com/libssh/libssh-mirror/blob/master/doc/authentication.dox#L124
BOOL wasInAuthInfo = NO;
for (;;) {
if ([self _notConnected]) {
return SSH_ERROR;
}
int rc = ssh_userauth_kbdint(_session, NULL, NULL);
switch (rc) {
case SSH_AUTH_AGAIN:
[self _poll];
continue;
case SSH_AUTH_INFO: {
wasInAuthInfo = YES;
const char *nameChars = ssh_userauth_kbdint_getname(_session);
const char *instructionChars = ssh_userauth_kbdint_getinstruction(_session);
NSString *name = nameChars ? @(nameChars) : nil;
NSString *instruction = instructionChars ? @(instructionChars) : nil;
int nprompts = ssh_userauth_kbdint_getnprompts(_session);
if (nprompts < 0) {
return SSH_AUTH_ERROR;
}
NSMutableArray *prompts = [[NSMutableArray alloc] initWithCapacity:nprompts];
for (int i = 0; i < nprompts; i++) {
char echo = NO;
const char *prompt = ssh_userauth_kbdint_getprompt(_session, i, &echo);
[prompts addObject:@[prompt == NULL ? @"" : @(prompt), @(echo)]];
}
NSArray * answers = nil;
if (password && nprompts == 1 && [@"Password:" isEqual: [[prompts firstObject] firstObject]]) {
answers = @[password];
} else {
answers = [self _getAnswersWithName:name instruction:instruction andPrompts:prompts];
}
for (int i = 0; i < answers.count; i++) {
int rc = ssh_userauth_kbdint_setanswer(_session, i, [answers[i] UTF8String]);
if (rc < 0) {
return SSH_AUTH_ERROR;
}
}
continue;
}
case SSH_AUTH_DENIED: {
if (!wasInAuthInfo) {
return rc;
}
if (--promptsCount > 0) {
if (password == nil) {
[self _log_info:@"Permission denied, please try again."];
}
password = nil;
continue;
}
return rc;
}
default:
return rc;
}
}
}
#pragma mark - HOST VERIFICATION
- (const NSString *)_keyTypeNameForKey:(ssh_key) ssh_key {
enum ssh_keytypes_e type = ssh_key_type(ssh_key);
switch (type) {
case SSH_KEYTYPE_DSS:
return BK_KEYTYPE_DSA;
case SSH_KEYTYPE_RSA:
case SSH_KEYTYPE_RSA1:
return BK_KEYTYPE_RSA;
case SSH_KEYTYPE_ECDSA:
return BK_KEYTYPE_ECDSA;
case SSH_KEYTYPE_ED25519:
return BK_KEYTYPE_Ed25519;
default:
return @(ssh_key_type_to_char(type));
}
}
- (NSString *)_pubkeyFingerPrint:(ssh_key) ssh_key {
unsigned char *hash = NULL;
size_t hlen;
int rc = ssh_get_publickey_hash(ssh_key,
SSH_PUBLICKEY_HASH_SHA256,
&hash,
&hlen);
if (rc < 0) {
return nil;
}
char *fingerprint = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256, hash, hlen);
ssh_clean_pubkey_hash(&hash);
if (!fingerprint) {
return nil;
}
NSString *result = @(fingerprint);
ssh_string_free_char(fingerprint);
return result;
}
- (int)_verify_known_host {
ssh_key srv_pubkey;
int rc;
rc = ssh_get_server_publickey(_session, &srv_pubkey);
if (rc < 0) {
return rc;
}
NSString *fingerprint = [self _pubkeyFingerPrint:srv_pubkey];
NSString *fingerprintMsg = [NSString stringWithFormat:@"%@ key fingerprint is %@.",
[self _keyTypeNameForKey:srv_pubkey],
fingerprint];
ssh_key_free(srv_pubkey);
if (!fingerprint) {
return SSH_ERROR;
}
enum ssh_known_hosts_e state = ssh_session_is_known_server(_session);
if (state == SSH_KNOWN_HOSTS_OTHER) {
[self _log_verbose:@"The host key for this server was not found but an other type of key exists.\n"];
[self _log_verbose:@"An attacker might change the default server key to confuse your client\n"];
[self _log_verbose:@"into thinking the key does not exist.\n"];
state = SSH_KNOWN_HOSTS_UNKNOWN;
}
switch(state) {
case SSH_KNOWN_HOSTS_CHANGED:
[self _device_log_info:@"Host key for server changed."];
[self _device_log_info:fingerprintMsg];
[self _device_log_info:@"For security reason, connection will be stopped"];
return SSH_ERROR;
case SSH_KNOWN_HOSTS_OTHER:
[self _device_log_info:@"The host key for this server was not found but an other type of key exists."];
[self _device_log_info:@"An attacker might change the default server key to confuse your client"];
[self _device_log_info:@"into thinking the key does not exist"];
[self _device_log_info:@"For security reason, connection will be stopped"];
return SSH_ERROR;
case SSH_KNOWN_HOSTS_NOT_FOUND:
[self _device_log_info: [
@[@"Could not find known host file. If you accept the host key here.",
@"the file will be automatically created."]
componentsJoinedByString:@"\n"] ];
// FALL_THROUGH;
case SSH_KNOWN_HOSTS_UNKNOWN: {
[self _device_log_info: fingerprintMsg];
NSNumber * doEcho = @(YES);
NSString *answer = [[[self _getAnswersWithName:@""
instruction:@"The server is unknown."
andPrompts:@[@[@"Do you trust the host key? (yes/no):", doEcho]]] firstObject] lowercaseString];
if ([answer isEqual:@"yes"] || [answer isEqual:@"y"]) {
} else {
return SSH_ERROR;
}
answer = [[[self _getAnswersWithName:@""
instruction:@"This new key will be written on disk for further usage."
andPrompts:@[@[@"Do you agree? (yes/no):", doEcho]]] firstObject] lowercaseString];
if ([answer isEqual:@"yes"] || [answer isEqual:@"y"]) {
if (ssh_write_knownhost(_session) < 0) {
[self _log_error];
return SSH_ERROR;
}
}
}
break;
case SSH_KNOWN_HOSTS_ERROR:
[self _log_error];
return SSH_ERROR;
case SSH_KNOWN_HOSTS_OK:
break; /* ok */
}
return SSH_OK;
}
#pragma mark - CHANNELS
- (int)_open_channels {
[self _log_verbose:@"open channels\n"];
int rc = SSH_ERROR;
NSString * hostPort = _options[SSHOptionSTDIOForwarding];
if (hostPort) {
rc = [self _start_stdio_forwarding:hostPort];
} else {
rc = [self _start_session_channel];
}
if (rc != SSH_OK) {
return [self _exitWithCode:rc];
}
for (NSString *address in _options[SSHOptionLocalForward]) {
rc = [self _start_listen_direct_forward: address];
if (rc != SSH_OK && [SSHOptionValueYES isEqual:_options[SSHOptionExitOnForwardFailure]]) {
return [self _exitWithCode:rc];
}
}
for (NSString *address in _options[SSHOptionRemoteForward]) {
[self _start_listen_reverse_forward: address];
}
return SSH_OK;
}
- (int)_request_pty:(ssh_channel)channel {
int rc = SSH_ERROR;
char *default_term = "xterm-256color";
char *term = getenv("TERM");
if (term) {
if (strlen(term) == 0) {
term = default_term;
}
} else {
term = default_term;
}
for (;;) {
if ([self _notConnected]) {
return SSH_ERROR;
}
rc = ssh_channel_request_pty_size(channel, term, _device->win.ws_col, _device->win.ws_row);
switch (rc) {
case SSH_AGAIN:
[self _poll];
continue;
case SSH_OK:
[_device setRawMode:YES];
return rc;
default:
return rc;
}
}
}
- (int)_start_session_channel {
[self _log_verbose:@"open session\n"];
int rc = SSH_ERROR;
ssh_channel channel = ssh_channel_new(_session);
ssh_channel_set_blocking(channel, 0);
for (;;) {
if ([self _notConnected]) {
return SSH_ERROR;
}
rc = ssh_channel_open_session(channel);
switch (rc) {
case SSH_AGAIN:
[self _poll];
continue;
case SSH_OK:
break;
default:
case SSH_ERROR:
[self _log_error];
ssh_channel_free(channel);
return rc;
}
break;
}
if ([SSHOptionValueYES isEqual:_options[SSHOptionForwardAgent]]) {
rc = ssh_channel_request_auth_agent(channel);
}
BOOL doRequestPTY = [_options[SSHOptionRequestTTY] isEqual:SSHOptionValueYES]
|| ([_options[SSHOptionRequestTTY] isEqual:SSHOptionValueAUTO] && _isTTY);
if (doRequestPTY) {
rc = [self _request_pty: channel];
if (rc != SSH_OK) {
ssh_channel_close(channel);
ssh_channel_free(channel);
return rc;
}
}
[self _ssh_send_env: channel];
NSString *remoteCommand = _options[SSHOptionRemoteCommand];
for (;;) {
if ([self _notConnected]) {
ssh_channel_close(channel);
ssh_channel_free(channel);
return SSH_ERROR;
}
if (remoteCommand) {
rc = ssh_channel_request_exec(channel, remoteCommand.UTF8String);
} else {
rc = ssh_channel_request_shell(channel);
}