/
Session.java
2827 lines (2530 loc) · 84.4 KB
/
Session.java
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
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2002-2015 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcraft.jsch;
import java.io.*;
import java.net.*;
import java.util.Vector;
public class Session implements Runnable{
// http://ietf.org/internet-drafts/draft-ietf-secsh-assignednumbers-01.txt
static final int SSH_MSG_DISCONNECT= 1;
static final int SSH_MSG_IGNORE= 2;
static final int SSH_MSG_UNIMPLEMENTED= 3;
static final int SSH_MSG_DEBUG= 4;
static final int SSH_MSG_SERVICE_REQUEST= 5;
static final int SSH_MSG_SERVICE_ACCEPT= 6;
static final int SSH_MSG_KEXINIT= 20;
static final int SSH_MSG_NEWKEYS= 21;
static final int SSH_MSG_KEXDH_INIT= 30;
static final int SSH_MSG_KEXDH_REPLY= 31;
static final int SSH_MSG_KEX_DH_GEX_GROUP= 31;
static final int SSH_MSG_KEX_DH_GEX_INIT= 32;
static final int SSH_MSG_KEX_DH_GEX_REPLY= 33;
static final int SSH_MSG_KEX_DH_GEX_REQUEST= 34;
static final int SSH_MSG_GLOBAL_REQUEST= 80;
static final int SSH_MSG_REQUEST_SUCCESS= 81;
static final int SSH_MSG_REQUEST_FAILURE= 82;
static final int SSH_MSG_CHANNEL_OPEN= 90;
static final int SSH_MSG_CHANNEL_OPEN_CONFIRMATION= 91;
static final int SSH_MSG_CHANNEL_OPEN_FAILURE= 92;
static final int SSH_MSG_CHANNEL_WINDOW_ADJUST= 93;
static final int SSH_MSG_CHANNEL_DATA= 94;
static final int SSH_MSG_CHANNEL_EXTENDED_DATA= 95;
static final int SSH_MSG_CHANNEL_EOF= 96;
static final int SSH_MSG_CHANNEL_CLOSE= 97;
static final int SSH_MSG_CHANNEL_REQUEST= 98;
static final int SSH_MSG_CHANNEL_SUCCESS= 99;
static final int SSH_MSG_CHANNEL_FAILURE= 100;
private static final int PACKET_MAX_SIZE = 256 * 1024;
private byte[] V_S; // server version
private byte[] V_C=Util.str2byte("SSH-2.0-JSCH-"+JSch.VERSION); // client version
private byte[] I_C; // the payload of the client's SSH_MSG_KEXINIT
private byte[] I_S; // the payload of the server's SSH_MSG_KEXINIT
private byte[] K_S; // the host key
private byte[] session_id;
private byte[] IVc2s;
private byte[] IVs2c;
private byte[] Ec2s;
private byte[] Es2c;
private byte[] MACc2s;
private byte[] MACs2c;
private int seqi=0;
private int seqo=0;
String[] guess=null;
private Cipher s2ccipher;
private Cipher c2scipher;
private MAC s2cmac;
private MAC c2smac;
//private byte[] mac_buf;
private byte[] s2cmac_result1;
private byte[] s2cmac_result2;
private Compression deflater;
private Compression inflater;
private IO io;
private Socket socket;
private int timeout=0;
private volatile boolean isConnected=false;
private boolean isAuthed=false;
private Thread connectThread=null;
private Object lock=new Object();
boolean x11_forwarding=false;
boolean agent_forwarding=false;
InputStream in=null;
OutputStream out=null;
static Random random;
Buffer buf;
Packet packet;
SocketFactory socket_factory=null;
static final int buffer_margin = 32 + // maximum padding length
20 + // maximum mac length
32; // margin for deflater; deflater may inflate data
private java.util.Hashtable config=null;
private Proxy proxy=null;
private UserInfo userinfo;
private String hostKeyAlias=null;
private int serverAliveInterval=0;
private int serverAliveCountMax=1;
private IdentityRepository identityRepository = null;
private HostKeyRepository hostkeyRepository = null;
protected boolean daemon_thread=false;
private long kex_start_time=0L;
int max_auth_tries = 6;
int auth_failures = 0;
String host="127.0.0.1";
String org_host="127.0.0.1";
int port=22;
String username=null;
byte[] password=null;
JSch jsch;
Session(JSch jsch, String username, String host, int port) throws JSchException{
super();
this.jsch=jsch;
buf=new Buffer();
packet=new Packet(buf);
this.username = username;
this.org_host = this.host = host;
this.port = port;
applyConfig();
if(this.username==null) {
try {
this.username=(String)(System.getProperties().get("user.name"));
}
catch(SecurityException e){
// ignore e
}
}
if(this.username==null) {
throw new JSchException("username is not given.");
}
}
public void connect() throws JSchException{
connect(timeout);
}
public void connect(int connectTimeout) throws JSchException{
if(isConnected){
throw new JSchException("session is already connected");
}
io=new IO();
if(random==null){
try{
Class c=Class.forName(getConfig("random"));
random=(Random)(c.newInstance());
}
catch(Exception e){
throw new JSchException(e.toString(), e);
}
}
Packet.setRandom(random);
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"Connecting to "+host+" port "+port);
}
try {
int i, j;
if(proxy==null){
InputStream in;
OutputStream out;
if(socket_factory==null){
socket=Util.createSocket(host, port, connectTimeout);
in=socket.getInputStream();
out=socket.getOutputStream();
}
else{
socket=socket_factory.createSocket(host, port);
in=socket_factory.getInputStream(socket);
out=socket_factory.getOutputStream(socket);
}
//if(timeout>0){ socket.setSoTimeout(timeout); }
socket.setTcpNoDelay(true);
io.setInputStream(in);
io.setOutputStream(out);
}
else{
synchronized(proxy){
proxy.connect(socket_factory, host, port, connectTimeout);
io.setInputStream(proxy.getInputStream());
io.setOutputStream(proxy.getOutputStream());
socket=proxy.getSocket();
}
}
if(connectTimeout>0 && socket!=null){
socket.setSoTimeout(connectTimeout);
}
isConnected=true;
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"Connection established");
}
jsch.addSession(this);
{
// Some Cisco devices will miss to read '\n' if it is sent separately.
byte[] foo=new byte[V_C.length+1];
System.arraycopy(V_C, 0, foo, 0, V_C.length);
foo[foo.length-1]=(byte)'\n';
io.put(foo, 0, foo.length);
}
while(true){
i=0;
j=0;
while(i<buf.buffer.length){
j=io.getByte();
if(j<0)break;
buf.buffer[i]=(byte)j; i++;
if(j==10)break;
}
if(j<0){
throw new JSchException("connection is closed by foreign host");
}
if(buf.buffer[i-1]==10){ // 0x0a
i--;
if(i>0 && buf.buffer[i-1]==13){ // 0x0d
i--;
}
}
if(i<=3 ||
((i!=buf.buffer.length) &&
(buf.buffer[0]!='S'||buf.buffer[1]!='S'||
buf.buffer[2]!='H'||buf.buffer[3]!='-'))){
// It must not start with 'SSH-'
//System.err.println(new String(buf.buffer, 0, i);
continue;
}
if(i==buf.buffer.length ||
i<7 || // SSH-1.99 or SSH-2.0
(buf.buffer[4]=='1' && buf.buffer[6]!='9') // SSH-1.5
){
throw new JSchException("invalid server's version string");
}
break;
}
V_S=new byte[i]; System.arraycopy(buf.buffer, 0, V_S, 0, i);
//System.err.println("V_S: ("+i+") ["+new String(V_S)+"]");
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"Remote version string: "+Util.byte2str(V_S));
JSch.getLogger().log(Logger.INFO,
"Local version string: "+Util.byte2str(V_C));
}
send_kexinit();
buf=read(buf);
if(buf.getCommand()!=SSH_MSG_KEXINIT){
in_kex=false;
throw new JSchException("invalid protocol: "+buf.getCommand());
}
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"SSH_MSG_KEXINIT received");
}
KeyExchange kex=receive_kexinit(buf);
while(true){
buf=read(buf);
if(kex.getState()==buf.getCommand()){
kex_start_time=System.currentTimeMillis();
boolean result=kex.next(buf);
if(!result){
//System.err.println("verify: "+result);
in_kex=false;
throw new JSchException("verify: "+result);
}
}
else{
in_kex=false;
throw new JSchException("invalid protocol(kex): "+buf.getCommand());
}
if(kex.getState()==KeyExchange.STATE_END){
break;
}
}
try{ checkHost(host, port, kex); }
catch(JSchException ee){
in_kex=false;
throw ee;
}
send_newkeys();
// receive SSH_MSG_NEWKEYS(21)
buf=read(buf);
//System.err.println("read: 21 ? "+buf.getCommand());
if(buf.getCommand()==SSH_MSG_NEWKEYS){
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"SSH_MSG_NEWKEYS received");
}
receive_newkeys(buf, kex);
}
else{
in_kex=false;
throw new JSchException("invalid protocol(newkyes): "+buf.getCommand());
}
try{
String s = getConfig("MaxAuthTries");
if(s!=null){
max_auth_tries = Integer.parseInt(s);
}
}
catch(NumberFormatException e){
throw new JSchException("MaxAuthTries: "+getConfig("MaxAuthTries"), e);
}
boolean auth=false;
boolean auth_cancel=false;
UserAuth ua=null;
try{
Class c=Class.forName(getConfig("userauth.none"));
ua=(UserAuth)(c.newInstance());
}
catch(Exception e){
throw new JSchException(e.toString(), e);
}
auth=ua.start(this);
String cmethods=getConfig("PreferredAuthentications");
String[] cmethoda=Util.split(cmethods, ",");
String smethods=null;
if(!auth){
smethods=((UserAuthNone)ua).getMethods();
if(smethods!=null){
smethods=smethods.toLowerCase();
}
else{
// methods: publickey,password,keyboard-interactive
//smethods="publickey,password,keyboard-interactive";
smethods=cmethods;
}
}
String[] smethoda=Util.split(smethods, ",");
int methodi=0;
loop:
while(true){
while(!auth &&
cmethoda!=null && methodi<cmethoda.length){
String method=cmethoda[methodi++];
boolean acceptable=false;
for(int k=0; k<smethoda.length; k++){
if(smethoda[k].equals(method)){
acceptable=true;
break;
}
}
if(!acceptable){
continue;
}
//System.err.println(" method: "+method);
if(JSch.getLogger().isEnabled(Logger.INFO)){
String str="Authentications that can continue: ";
for(int k=methodi-1; k<cmethoda.length; k++){
str+=cmethoda[k];
if(k+1<cmethoda.length)
str+=",";
}
JSch.getLogger().log(Logger.INFO,
str);
JSch.getLogger().log(Logger.INFO,
"Next authentication method: "+method);
}
ua=null;
try{
Class c=null;
if(getConfig("userauth."+method)!=null){
c=Class.forName(getConfig("userauth."+method));
ua=(UserAuth)(c.newInstance());
}
}
catch(Exception e){
if(JSch.getLogger().isEnabled(Logger.WARN)){
JSch.getLogger().log(Logger.WARN,
"failed to load "+method+" method");
}
}
if(ua!=null){
auth_cancel=false;
try{
auth=ua.start(this);
if(auth &&
JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"Authentication succeeded ("+method+").");
}
}
catch(JSchAuthCancelException ee){
auth_cancel=true;
}
catch(JSchPartialAuthException ee){
String tmp = smethods;
smethods=ee.getMethods();
smethoda=Util.split(smethods, ",");
if(!tmp.equals(smethods)){
methodi=0;
}
//System.err.println("PartialAuth: "+methods);
auth_cancel=false;
continue loop;
}
catch(RuntimeException ee){
throw ee;
}
catch(JSchException ee){
throw ee;
}
catch(Exception ee){
//System.err.println("ee: "+ee); // SSH_MSG_DISCONNECT: 2 Too many authentication failures
if(JSch.getLogger().isEnabled(Logger.WARN)){
JSch.getLogger().log(Logger.WARN,
"an exception during authentication\n"+ee.toString());
}
break loop;
}
}
}
break;
}
if(!auth){
if(auth_failures >= max_auth_tries){
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"Login trials exceeds "+max_auth_tries);
}
}
if(auth_cancel)
throw new JSchException("Auth cancel");
throw new JSchException("Auth fail");
}
if(socket!=null && (connectTimeout>0 || timeout>0)){
socket.setSoTimeout(timeout);
}
isAuthed=true;
synchronized(lock){
if(isConnected){
connectThread=new Thread(this);
connectThread.setName("Connect thread "+host+" session");
if(daemon_thread){
connectThread.setDaemon(daemon_thread);
}
connectThread.start();
requestPortForwarding();
}
else{
// The session has been already down and
// we don't have to start new thread.
}
}
}
catch(Exception e) {
in_kex=false;
try{
if(isConnected){
String message = e.toString();
packet.reset();
buf.checkFreeSize(1+4*3+message.length()+2+buffer_margin);
buf.putByte((byte)SSH_MSG_DISCONNECT);
buf.putInt(3);
buf.putString(Util.str2byte(message));
buf.putString(Util.str2byte("en"));
write(packet);
}
}
catch(Exception ee){}
try{ disconnect(); } catch(Exception ee){ }
isConnected=false;
//e.printStackTrace();
if(e instanceof RuntimeException) throw (RuntimeException)e;
if(e instanceof JSchException) throw (JSchException)e;
throw new JSchException("Session.connect: "+e);
}
finally{
Util.bzero(this.password);
this.password=null;
}
}
private KeyExchange receive_kexinit(Buffer buf) throws Exception {
int j=buf.getInt();
if(j!=buf.getLength()){ // packet was compressed and
buf.getByte(); // j is the size of deflated packet.
I_S=new byte[buf.index-5];
}
else{
I_S=new byte[j-1-buf.getByte()];
}
System.arraycopy(buf.buffer, buf.s, I_S, 0, I_S.length);
if(!in_kex){ // We are in rekeying activated by the remote!
send_kexinit();
}
guess=KeyExchange.guess(I_S, I_C);
if(guess==null){
throw new JSchException("Algorithm negotiation fail");
}
if(!isAuthed &&
(guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS].equals("none") ||
(guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC].equals("none")))){
throw new JSchException("NONE Cipher should not be chosen before authentification is successed.");
}
KeyExchange kex=null;
try{
Class c=Class.forName(getConfig(guess[KeyExchange.PROPOSAL_KEX_ALGS]));
kex=(KeyExchange)(c.newInstance());
}
catch(Exception e){
throw new JSchException(e.toString(), e);
}
kex.init(this, V_S, V_C, I_S, I_C);
return kex;
}
private volatile boolean in_kex=false;
public void rekey() throws Exception {
send_kexinit();
}
private void send_kexinit() throws Exception {
if(in_kex)
return;
String cipherc2s=getConfig("cipher.c2s");
String ciphers2c=getConfig("cipher.s2c");
String[] not_available_ciphers=checkCiphers(getConfig("CheckCiphers"));
if(not_available_ciphers!=null && not_available_ciphers.length>0){
cipherc2s=Util.diffString(cipherc2s, not_available_ciphers);
ciphers2c=Util.diffString(ciphers2c, not_available_ciphers);
if(cipherc2s==null || ciphers2c==null){
throw new JSchException("There are not any available ciphers.");
}
}
String kex=getConfig("kex");
String[] not_available_kexes=checkKexes(getConfig("CheckKexes"));
if(not_available_kexes!=null && not_available_kexes.length>0){
kex=Util.diffString(kex, not_available_kexes);
if(kex==null){
throw new JSchException("There are not any available kexes.");
}
}
String server_host_key = getConfig("server_host_key");
String[] not_available_shks =
checkSignatures(getConfig("CheckSignatures"));
if(not_available_shks!=null && not_available_shks.length>0){
server_host_key=Util.diffString(server_host_key, not_available_shks);
if(server_host_key==null){
throw new JSchException("There are not any available sig algorithm.");
}
}
in_kex=true;
kex_start_time=System.currentTimeMillis();
// byte SSH_MSG_KEXINIT(20)
// byte[16] cookie (random bytes)
// string kex_algorithms
// string server_host_key_algorithms
// string encryption_algorithms_client_to_server
// string encryption_algorithms_server_to_client
// string mac_algorithms_client_to_server
// string mac_algorithms_server_to_client
// string compression_algorithms_client_to_server
// string compression_algorithms_server_to_client
// string languages_client_to_server
// string languages_server_to_client
Buffer buf = new Buffer(); // send_kexinit may be invoked
Packet packet = new Packet(buf); // by user thread.
packet.reset();
buf.putByte((byte) SSH_MSG_KEXINIT);
synchronized(random){
random.fill(buf.buffer, buf.index, 16); buf.skip(16);
}
buf.putString(Util.str2byte(kex));
buf.putString(Util.str2byte(server_host_key));
buf.putString(Util.str2byte(cipherc2s));
buf.putString(Util.str2byte(ciphers2c));
buf.putString(Util.str2byte(getConfig("mac.c2s")));
buf.putString(Util.str2byte(getConfig("mac.s2c")));
buf.putString(Util.str2byte(getConfig("compression.c2s")));
buf.putString(Util.str2byte(getConfig("compression.s2c")));
buf.putString(Util.str2byte(getConfig("lang.c2s")));
buf.putString(Util.str2byte(getConfig("lang.s2c")));
buf.putByte((byte)0);
buf.putInt(0);
buf.setOffSet(5);
I_C=new byte[buf.getLength()];
buf.getByte(I_C);
write(packet);
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"SSH_MSG_KEXINIT sent");
}
}
private void send_newkeys() throws Exception {
// send SSH_MSG_NEWKEYS(21)
packet.reset();
buf.putByte((byte)SSH_MSG_NEWKEYS);
write(packet);
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"SSH_MSG_NEWKEYS sent");
}
}
private void checkHost(String chost, int port, KeyExchange kex) throws JSchException {
String shkc=getConfig("StrictHostKeyChecking");
if(hostKeyAlias!=null){
chost=hostKeyAlias;
}
//System.err.println("shkc: "+shkc);
byte[] K_S=kex.getHostKey();
String key_type=kex.getKeyType();
String key_fprint=kex.getFingerPrint();
if(hostKeyAlias==null && port!=22){
chost=("["+chost+"]:"+port);
}
HostKeyRepository hkr=getHostKeyRepository();
String hkh=getConfig("HashKnownHosts");
if(hkh.equals("yes") && (hkr instanceof KnownHosts)){
hostkey=((KnownHosts)hkr).createHashedHostKey(chost, K_S);
}
else{
hostkey=new HostKey(chost, K_S);
}
int i=0;
synchronized(hkr){
i=hkr.check(chost, K_S);
}
boolean insert=false;
if((shkc.equals("ask") || shkc.equals("yes")) &&
i==HostKeyRepository.CHANGED){
String file=null;
synchronized(hkr){
file=hkr.getKnownHostsRepositoryID();
}
if(file==null){file="known_hosts";}
boolean b=false;
if(userinfo!=null){
String message=
"WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!\n"+
"IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!\n"+
"Someone could be eavesdropping on you right now (man-in-the-middle attack)!\n"+
"It is also possible that the "+key_type+" host key has just been changed.\n"+
"The fingerprint for the "+key_type+" key sent by the remote host "+chost+" is\n"+
key_fprint+".\n"+
"Please contact your system administrator.\n"+
"Add correct host key in "+file+" to get rid of this message.";
if(shkc.equals("ask")){
b=userinfo.promptYesNo(message+
"\nDo you want to delete the old key and insert the new key?");
}
else{ // shkc.equals("yes")
userinfo.showMessage(message);
}
}
if(!b){
throw new JSchException("HostKey has been changed: "+chost);
}
synchronized(hkr){
hkr.remove(chost,
kex.getKeyAlgorithName(),
null);
insert=true;
}
}
if((shkc.equals("ask") || shkc.equals("yes")) &&
(i!=HostKeyRepository.OK) && !insert){
if(shkc.equals("yes")){
throw new JSchException("reject HostKey: "+host);
}
//System.err.println("finger-print: "+key_fprint);
if(userinfo!=null){
boolean foo=userinfo.promptYesNo(
"The authenticity of host '"+host+"' can't be established.\n"+
key_type+" key fingerprint is "+key_fprint+".\n"+
"Are you sure you want to continue connecting?"
);
if(!foo){
throw new JSchException("reject HostKey: "+host);
}
insert=true;
}
else{
if(i==HostKeyRepository.NOT_INCLUDED)
throw new JSchException("UnknownHostKey: "+host+". "+key_type+" key fingerprint is "+key_fprint);
else
throw new JSchException("HostKey has been changed: "+host);
}
}
if(shkc.equals("no") &&
HostKeyRepository.NOT_INCLUDED==i){
insert=true;
}
if(i==HostKeyRepository.OK){
HostKey[] keys =
hkr.getHostKey(chost, kex.getKeyAlgorithName());
String _key= Util.byte2str(Util.toBase64(K_S, 0, K_S.length));
for(int j=0; j< keys.length; j++){
if(keys[i].getKey().equals(_key) &&
keys[j].getMarker().equals("@revoked")){
if(userinfo!=null){
userinfo.showMessage(
"The "+ key_type +" host key for "+ host +" is marked as revoked.\n"+
"This could mean that a stolen key is being used to "+
"impersonate this host.");
}
if(JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"Host '"+host+"' has provided revoked key.");
}
throw new JSchException("revoked HostKey: "+host);
}
}
}
if(i==HostKeyRepository.OK &&
JSch.getLogger().isEnabled(Logger.INFO)){
JSch.getLogger().log(Logger.INFO,
"Host '"+host+"' is known and matches the "+key_type+" host key");
}
if(insert &&
JSch.getLogger().isEnabled(Logger.WARN)){
JSch.getLogger().log(Logger.WARN,
"Permanently added '"+host+"' ("+key_type+") to the list of known hosts.");
}
if(insert){
synchronized(hkr){
hkr.add(hostkey, userinfo);
}
}
}
//public void start(){ (new Thread(this)).start(); }
public Channel openChannel(String type) throws JSchException{
if(!isConnected){
throw new JSchException("session is down");
}
try{
Channel channel=Channel.getChannel(type);
addChannel(channel);
channel.init();
if(channel instanceof ChannelSession){
applyConfigChannel((ChannelSession)channel);
}
return channel;
}
catch(Exception e){
//e.printStackTrace();
}
return null;
}
// encode will bin invoked in write with synchronization.
public void encode(Packet packet) throws Exception{
//System.err.println("encode: "+packet.buffer.getCommand());
//System.err.println(" "+packet.buffer.index);
//if(packet.buffer.getCommand()==96){
//Thread.dumpStack();
//}
if(deflater!=null){
compress_len[0]=packet.buffer.index;
packet.buffer.buffer=deflater.compress(packet.buffer.buffer,
5, compress_len);
packet.buffer.index=compress_len[0];
}
if(c2scipher!=null){
//packet.padding(c2scipher.getIVSize());
packet.padding(c2scipher_size);
int pad=packet.buffer.buffer[4];
synchronized(random){
random.fill(packet.buffer.buffer, packet.buffer.index-pad, pad);
}
}
else{
packet.padding(8);
}
if(c2smac!=null){
c2smac.update(seqo);
c2smac.update(packet.buffer.buffer, 0, packet.buffer.index);
c2smac.doFinal(packet.buffer.buffer, packet.buffer.index);
}
if(c2scipher!=null){
byte[] buf=packet.buffer.buffer;
c2scipher.update(buf, 0, packet.buffer.index, buf, 0);
}
if(c2smac!=null){
packet.buffer.skip(c2smac.getBlockSize());
}
}
int[] uncompress_len=new int[1];
int[] compress_len=new int[1];
private int s2ccipher_size=8;
private int c2scipher_size=8;
public Buffer read(Buffer buf) throws Exception{
int j=0;
while(true){
buf.reset();
io.getByte(buf.buffer, buf.index, s2ccipher_size);
buf.index+=s2ccipher_size;
if(s2ccipher!=null){
s2ccipher.update(buf.buffer, 0, s2ccipher_size, buf.buffer, 0);
}
j=((buf.buffer[0]<<24)&0xff000000)|
((buf.buffer[1]<<16)&0x00ff0000)|
((buf.buffer[2]<< 8)&0x0000ff00)|
((buf.buffer[3] )&0x000000ff);
// RFC 4253 6.1. Maximum Packet Length
if(j<5 || j>PACKET_MAX_SIZE){
start_discard(buf, s2ccipher, s2cmac, j, PACKET_MAX_SIZE);
}
int need = j+4-s2ccipher_size;
//if(need<0){
// throw new IOException("invalid data");
//}
if((buf.index+need)>buf.buffer.length){
byte[] foo=new byte[buf.index+need];
System.arraycopy(buf.buffer, 0, foo, 0, buf.index);
buf.buffer=foo;
}
if((need%s2ccipher_size)!=0){
String message="Bad packet length "+need;
if(JSch.getLogger().isEnabled(Logger.FATAL)){
JSch.getLogger().log(Logger.FATAL, message);
}
start_discard(buf, s2ccipher, s2cmac, j, PACKET_MAX_SIZE-s2ccipher_size);
}
if(need>0){
io.getByte(buf.buffer, buf.index, need); buf.index+=(need);
if(s2ccipher!=null){
s2ccipher.update(buf.buffer, s2ccipher_size, need, buf.buffer, s2ccipher_size);
}
}
if(s2cmac!=null){
s2cmac.update(seqi);
s2cmac.update(buf.buffer, 0, buf.index);
s2cmac.doFinal(s2cmac_result1, 0);
io.getByte(s2cmac_result2, 0, s2cmac_result2.length);
if(!java.util.Arrays.equals(s2cmac_result1, s2cmac_result2)){
if(need > PACKET_MAX_SIZE){
throw new IOException("MAC Error");
}
start_discard(buf, s2ccipher, s2cmac, j, PACKET_MAX_SIZE-need);
continue;
}
}
seqi++;
if(inflater!=null){
//inflater.uncompress(buf);
int pad=buf.buffer[4];
uncompress_len[0]=buf.index-5-pad;
byte[] foo=inflater.uncompress(buf.buffer, 5, uncompress_len);
if(foo!=null){
buf.buffer=foo;
buf.index=5+uncompress_len[0];
}
else{
System.err.println("fail in inflater");
break;
}
}
int type=buf.getCommand()&0xff;
//System.err.println("read: "+type);
if(type==SSH_MSG_DISCONNECT){
buf.rewind();
buf.getInt();buf.getShort();
int reason_code=buf.getInt();
byte[] description=buf.getString();
byte[] language_tag=buf.getString();
throw new JSchException("SSH_MSG_DISCONNECT: "+
reason_code+
" "+Util.byte2str(description)+
" "+Util.byte2str(language_tag));
//break;