forked from Yasushi/putty
-
Notifications
You must be signed in to change notification settings - Fork 6
/
ssh.c
9921 lines (8891 loc) · 319 KB
/
ssh.c
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
/*
* SSH backend.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <limits.h>
#include <signal.h>
#include "putty.h"
#include "pageant.h" /* for AGENT_MAX_MSGLEN */
#include "tree234.h"
#include "storage.h"
#include "marshal.h"
#include "ssh.h"
#include "sshcr.h"
#include "sshbpp.h"
#include "sshchan.h"
#ifndef NO_GSSAPI
#include "sshgssc.h"
#include "sshgss.h"
#define MIN_CTXT_LIFETIME 5 /* Avoid rekey with short lifetime (seconds) */
#define GSS_KEX_CAPABLE (1<<0) /* Can do GSS KEX */
#define GSS_CRED_UPDATED (1<<1) /* Cred updated since previous delegation */
#define GSS_CTXT_EXPIRES (1<<2) /* Context expires before next timer */
#define GSS_CTXT_MAYFAIL (1<<3) /* Context may expire during handshake */
#endif
static const char *const ssh2_disconnect_reasons[] = {
NULL,
"host not allowed to connect",
"protocol error",
"key exchange failed",
"host authentication failed",
"MAC error",
"compression error",
"service not available",
"protocol version not supported",
"host key not verifiable",
"connection lost",
"by application",
"too many connections",
"auth cancelled by user",
"no more auth methods available",
"illegal user name",
};
#define DH_MIN_SIZE 1024
#define DH_MAX_SIZE 8192
/* Safely convert rekey_time to unsigned long minutes */
static unsigned long rekey_mins(int rekey_time, unsigned long def)
{
if (rekey_time < 0 || rekey_time > MAX_TICK_MINS)
rekey_time = def;
return (unsigned long)rekey_time;
}
/* Enumeration values for fields in SSH-1 packets */
enum {
PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
};
static void ssh2_pkt_send(Ssh, struct PktOut *);
static void do_ssh1_login(void *vctx);
static void do_ssh2_userauth(void *vctx);
static void ssh2_connection_setup(Ssh ssh);
static void do_ssh2_connection(void *vctx);
static void ssh_channel_init(struct ssh_channel *c);
static struct ssh_channel *ssh_channel_msg(Ssh ssh, PktIn *pktin);
static void ssh_channel_got_eof(struct ssh_channel *c);
static void ssh2_channel_check_close(struct ssh_channel *c);
static void ssh_channel_close_local(struct ssh_channel *c, char const *reason);
static void ssh_channel_destroy(struct ssh_channel *c);
static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
static void ssh2_msg_something_unimplemented(Ssh ssh, PktIn *pktin);
static void ssh2_general_packet_processing(Ssh ssh, PktIn *pktin);
static void ssh1_login_input(Ssh ssh);
static void ssh2_userauth_input(Ssh ssh);
static void ssh2_connection_input(Ssh ssh);
struct ssh_signkey_with_user_pref_id {
const ssh_keyalg *alg;
int id;
};
const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
{ &ssh_ecdsa_ed25519, HK_ED25519 },
{ &ssh_ecdsa_nistp256, HK_ECDSA },
{ &ssh_ecdsa_nistp384, HK_ECDSA },
{ &ssh_ecdsa_nistp521, HK_ECDSA },
{ &ssh_dss, HK_DSA },
{ &ssh_rsa, HK_RSA },
};
const static struct ssh2_macalg *const macs[] = {
&ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
};
const static struct ssh2_macalg *const buggymacs[] = {
&ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
};
static ssh_compressor *ssh_comp_none_init(void)
{
return NULL;
}
static void ssh_comp_none_cleanup(ssh_compressor *handle)
{
}
static ssh_decompressor *ssh_decomp_none_init(void)
{
return NULL;
}
static void ssh_decomp_none_cleanup(ssh_decompressor *handle)
{
}
static void ssh_comp_none_block(ssh_compressor *handle,
unsigned char *block, int len,
unsigned char **outblock, int *outlen,
int minlen)
{
}
static int ssh_decomp_none_block(ssh_decompressor *handle,
unsigned char *block, int len,
unsigned char **outblock, int *outlen)
{
return 0;
}
const static struct ssh_compression_alg ssh_comp_none = {
"none", NULL,
ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
ssh_decomp_none_init, ssh_decomp_none_cleanup, ssh_decomp_none_block,
NULL
};
const static struct ssh_compression_alg *const compressions[] = {
&ssh_zlib, &ssh_comp_none
};
typedef void (*handler_fn_t)(Ssh ssh, PktIn *pktin);
typedef void (*chandler_fn_t)(Ssh ssh, PktIn *pktin, void *ctx);
typedef void (*cchandler_fn_t)(struct ssh_channel *, PktIn *, void *);
/*
* Each channel has a queue of outstanding CHANNEL_REQUESTS and their
* handlers.
*/
struct outstanding_channel_request {
cchandler_fn_t handler;
void *ctx;
struct outstanding_channel_request *next;
};
/*
* 2-3-4 tree storing channels.
*/
struct ssh_channel {
Ssh ssh; /* pointer back to main context */
unsigned remoteid, localid;
int type;
/* True if we opened this channel but server hasn't confirmed. */
int halfopen;
/*
* In SSH-1, this value contains four bits:
*
* 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
* 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
* 4 We have received SSH1_MSG_CHANNEL_CLOSE.
* 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
*
* A channel is completely finished with when all four bits are set.
*
* In SSH-2, the four bits mean:
*
* 1 We have sent SSH2_MSG_CHANNEL_EOF.
* 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
* 4 We have received SSH2_MSG_CHANNEL_EOF.
* 8 We have received SSH2_MSG_CHANNEL_CLOSE.
*
* A channel is completely finished with when we have both sent
* and received CLOSE.
*
* The symbolic constants below use the SSH-2 terminology, which
* is a bit confusing in SSH-1, but we have to use _something_.
*/
#define CLOSES_SENT_EOF 1
#define CLOSES_SENT_CLOSE 2
#define CLOSES_RCVD_EOF 4
#define CLOSES_RCVD_CLOSE 8
int closes;
/*
* This flag indicates that an EOF is pending on the outgoing side
* of the channel: that is, wherever we're getting the data for
* this channel has sent us some data followed by EOF. We can't
* actually send the EOF until we've finished sending the data, so
* we set this flag instead to remind us to do so once our buffer
* is clear.
*/
int pending_eof;
/*
* True if this channel is causing the underlying connection to be
* throttled.
*/
int throttling_conn;
/*
* True if we currently have backed-up data on the direction of
* this channel pointing out of the SSH connection, and therefore
* would prefer the 'Channel' implementation not to read further
* local input if possible.
*/
int throttled_by_backlog;
union {
struct ssh2_data_channel {
bufchain outbuffer;
unsigned remwindow, remmaxpkt;
/* locwindow is signed so we can cope with excess data. */
int locwindow, locmaxwin;
/*
* remlocwin is the amount of local window that we think
* the remote end had available to it after it sent the
* last data packet or window adjust ack.
*/
int remlocwin;
/*
* These store the list of channel requests that haven't
* been acked.
*/
struct outstanding_channel_request *chanreq_head, *chanreq_tail;
enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
} v2;
} v;
ssh_sharing_connstate *sharectx; /* sharing context, if this is a
* downstream channel */
Channel *chan; /* handle the client side of this channel, if not */
SshChannel sc; /* entry point for chan to talk back to */
};
static int sshchannel_write(SshChannel *c, const void *buf, int len);
static void sshchannel_write_eof(SshChannel *c);
static void sshchannel_unclean_close(SshChannel *c, const char *err);
static void sshchannel_unthrottle(SshChannel *c, int bufsize);
static Conf *sshchannel_get_conf(SshChannel *c);
static void sshchannel_window_override_removed(SshChannel *c);
static void sshchannel_x11_sharing_handover(
SshChannel *c, ssh_sharing_connstate *share_cs, share_channel *share_chan,
const char *peer_addr, int peer_port, int endian,
int protomajor, int protominor, const void *initial_data, int initial_len);
const struct SshChannelVtable sshchannel_vtable = {
sshchannel_write,
sshchannel_write_eof,
sshchannel_unclean_close,
sshchannel_unthrottle,
sshchannel_get_conf,
sshchannel_window_override_removed,
sshchannel_x11_sharing_handover,
};
/*
* 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
* use this structure in different ways, reflecting SSH-2's
* altogether saner approach to port forwarding.
*
* In SSH-1, you arrange a remote forwarding by sending the server
* the remote port number, and the local destination host:port.
* When a connection comes in, the server sends you back that
* host:port pair, and you connect to it. This is a ready-made
* security hole if you're not on the ball: a malicious server
* could send you back _any_ host:port pair, so if you trustingly
* connect to the address it gives you then you've just opened the
* entire inside of your corporate network just by connecting
* through it to a dodgy SSH server. Hence, we must store a list of
* host:port pairs we _are_ trying to forward to, and reject a
* connection request from the server if it's not in the list.
*
* In SSH-2, each side of the connection minds its own business and
* doesn't send unnecessary information to the other. You arrange a
* remote forwarding by sending the server just the remote port
* number. When a connection comes in, the server tells you which
* of its ports was connected to; and _you_ have to remember what
* local host:port pair went with that port number.
*
* Hence, in SSH-1 this structure is indexed by destination
* host:port pair, whereas in SSH-2 it is indexed by source port.
*/
struct ssh_portfwd; /* forward declaration */
struct ssh_rportfwd {
unsigned sport, dport;
char *shost, *dhost;
int addressfamily;
char *log_description; /* name of remote listening port, for logging */
ssh_sharing_connstate *share_ctx;
PortFwdRecord *pfr;
};
static void free_rportfwd(struct ssh_rportfwd *pf)
{
if (pf) {
sfree(pf->log_description);
sfree(pf->shost);
sfree(pf->dhost);
sfree(pf);
}
}
static void ssh1_protocol_setup(Ssh ssh);
static void ssh2_protocol_setup(Ssh ssh);
static void ssh2_bare_connection_protocol_setup(Ssh ssh);
static void ssh_size(Backend *be, int width, int height);
static void ssh_special(Backend *be, Telnet_Special);
static int ssh2_try_send(struct ssh_channel *c);
static int ssh_send_channel_data(struct ssh_channel *c,
const char *buf, int len);
static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
static void ssh2_set_window(struct ssh_channel *c, int newwin);
static int ssh_sendbuffer(Backend *be);
static int ssh_do_close(Ssh ssh, int notify_exit);
static void ssh2_timer(void *ctx, unsigned long now);
static int ssh2_timer_update(Ssh ssh, unsigned long rekey_time);
#ifndef NO_GSSAPI
static void ssh2_gss_update(Ssh ssh, int definitely_rekeying);
static PktOut *ssh2_gss_authpacket(Ssh ssh, Ssh_gss_ctx gss_ctx,
const char *authtype);
#endif
static void ssh2_msg_unexpected(Ssh ssh, PktIn *pktin);
struct queued_handler;
struct queued_handler {
int msg1, msg2;
chandler_fn_t handler;
void *ctx;
struct queued_handler *next;
};
/*
* Enumeration of high-level classes of reason why we might need to do
* a repeat key exchange. The full detailed reason in human-readable
* form for the Event Log is kept in ssh->rekey_reason, but
* ssh->rekey_class is a variable with this enum type which is used to
* discriminate between classes of reason that the code needs to treat
* differently.
*
* RK_NONE == 0 is the value indicating that no rekey is currently
* needed at all. RK_INITIAL indicates that we haven't even done the
* _first_ key exchange yet. RK_NORMAL is the usual case.
* RK_GSS_UPDATE indicates that we're rekeying because we've just got
* new GSSAPI credentials (hence there's no point in doing a
* preliminary check for new GSS creds, because we already know the
* answer); RK_POST_USERAUTH indicates that _if_ we're going to need a
* post-userauth immediate rekey for any reason, this is the moment to
* do it.
*
* So RK_POST_USERAUTH only tells the transport layer to _consider_
* rekeying, not to definitely do it. Also, that one enum value is
* special in that do_ssh2_transport fills in the reason text after it
* decides whether it needs a rekey at all. In the other cases,
* rekey_reason is set up at the same time as rekey_class.
*/
enum RekeyClass {
RK_NONE = 0,
RK_INITIAL,
RK_NORMAL,
RK_POST_USERAUTH,
RK_GSS_UPDATE
};
struct ssh_tag {
char *v_c, *v_s;
struct ssh_version_receiver version_receiver;
ssh_hash *exhash;
Socket s;
const Plug_vtable *plugvt;
Backend backend;
Ldisc *ldisc;
LogContext *logctx;
unsigned char session_key[32];
int v1_remote_protoflags;
int v1_local_protoflags;
int agentfwd_enabled;
int X11_fwd_enabled;
int remote_bugs;
const struct ssh_kex *kex;
const ssh_keyalg *hostkey_alg;
char *hostkey_str; /* string representation, for easy checking in rekeys */
unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
int v2_session_id_len;
int v2_cbc_ignore_workaround;
int v2_out_cipherblksize;
struct dh_ctx *dh_ctx;
int bare_connection;
int attempting_connshare;
ssh_sharing_state *connshare;
char *savedhost;
int savedport;
int send_ok;
int echoing, editing;
int session_started;
Frontend *frontend;
int ospeed, ispeed; /* temporaries */
int term_width, term_height;
tree234 *channels; /* indexed by local id */
struct ssh_channel *mainchan; /* primary session channel */
int ncmode; /* is primary channel direct-tcpip? */
int exitcode;
int close_expected;
int clean_exit;
int disconnect_message_seen;
tree234 *rportfwds;
PortFwdManager *portfwdmgr;
ConnectionLayer cl;
enum {
SSH_STATE_PREPACKET,
SSH_STATE_BEFORE_SIZE,
SSH_STATE_INTERMED,
SSH_STATE_SESSION,
SSH_STATE_CLOSED
} state;
int size_needed, eof_needed;
int sent_console_eof;
int got_pty; /* affects EOF behaviour on main channel */
PktOutQueue outq;
int queueing;
/*
* Gross hack: pscp will try to start SFTP but fall back to
* scp1 if that fails. This variable is the means by which
* scp.c can reach into the SSH code and find out which one it
* got.
*/
int fallback_cmd;
bufchain banner; /* accumulates banners during do_ssh2_userauth */
struct X11Display *x11disp;
struct X11FakeAuth *x11auth;
tree234 *x11authtree;
int version;
int conn_throttle_count;
int overall_bufsize;
int throttled_all;
int v1_stdout_throttling;
int do_ssh1_connection_crstate;
void *do_ssh_init_state;
void *do_ssh1_login_state;
void *do_ssh2_transport_state;
void *do_ssh2_userauth_state;
void *do_ssh2_connection_state;
void *do_ssh_connection_init_state;
bufchain incoming_data;
struct IdempotentCallback incoming_data_consumer;
int incoming_data_seen_eof;
char *incoming_data_eof_message;
PktInQueue pq_full;
struct IdempotentCallback pq_full_consumer;
PktInQueue pq_ssh1_login;
struct IdempotentCallback ssh1_login_icb;
PktInQueue pq_ssh1_connection;
struct IdempotentCallback ssh1_connection_icb;
PktInQueue pq_ssh2_transport;
struct IdempotentCallback ssh2_transport_icb;
PktInQueue pq_ssh2_userauth;
struct IdempotentCallback ssh2_userauth_icb;
PktInQueue pq_ssh2_connection;
struct IdempotentCallback ssh2_connection_icb;
bufchain user_input;
struct IdempotentCallback user_input_consumer;
bufchain outgoing_data;
struct IdempotentCallback outgoing_data_sender;
const char *rekey_reason;
enum RekeyClass rekey_class;
PacketLogSettings pls;
BinaryPacketProtocol *bpp;
void (*general_packet_processing)(Ssh ssh, PktIn *pkt);
void (*current_user_input_fn) (Ssh ssh);
/*
* We maintain our own copy of a Conf structure here. That way,
* when we're passed a new one for reconfiguration, we can check
* the differences and potentially reconfigure port forwardings
* etc in mid-session.
*/
Conf *conf;
/*
* Dynamically allocated username string created during SSH
* login. Stored in here rather than in the coroutine state so
* that it'll be reliably freed if we shut down the SSH session
* at some unexpected moment.
*/
char *username;
/*
* Used to transfer data back from async callbacks.
*/
void *agent_response;
int agent_response_len;
int user_response;
/*
* The SSH connection can be set as `frozen', meaning we are
* not currently accepting incoming data from the network.
*/
int frozen;
/*
* Dispatch table for packet types that we may have to deal
* with at any time.
*/
handler_fn_t packet_dispatch[SSH_MAX_MSG];
/*
* Queues of one-off handler functions for success/failure
* indications from a request.
*/
struct queued_handler *qhead, *qtail;
handler_fn_t q_saved_handler1, q_saved_handler2;
/*
* This module deals with sending keepalives.
*/
Pinger pinger;
/*
* Track incoming and outgoing data sizes and time, for
* size-based rekeys.
*/
unsigned long max_data_size;
struct DataTransferStats stats;
int kex_in_progress;
unsigned long next_rekey, last_rekey;
const char *deferred_rekey_reason;
/*
* Fully qualified host name, which we need if doing GSSAPI.
*/
char *fullhostname;
#ifndef NO_GSSAPI
/*
* GSSAPI libraries for this session. We need them at key exchange
* and userauth time.
*
* And the gss_ctx we setup at initial key exchange will be used
* during gssapi-keyex userauth time as well.
*/
struct ssh_gss_liblist *gsslibs;
struct ssh_gss_library *gsslib;
int gss_status;
time_t gss_cred_expiry; /* Re-delegate if newer */
unsigned long gss_ctxt_lifetime; /* Re-delegate when short */
Ssh_gss_name gss_srv_name; /* Cached for KEXGSS */
Ssh_gss_ctx gss_ctx; /* Saved for gssapi-keyex */
tree234 *transient_hostkey_cache;
#endif
int gss_kex_used; /* outside ifdef; always FALSE if NO_GSSAPI */
/*
* The last list returned from get_specials.
*/
struct telnet_special *specials;
/*
* List of host key algorithms for which we _don't_ have a stored
* host key. These are indices into the main hostkey_algs[] array
*/
int uncert_hostkeys[lenof(hostkey_algs)];
int n_uncert_hostkeys;
/*
* Flag indicating that the current rekey is intended to finish
* with a newly cross-certified host key.
*/
int cross_certifying;
/*
* Any asynchronous query to our SSH agent that we might have in
* flight from the main authentication loop. (Queries from
* agent-forwarding channels live in their channel structure.)
*/
agent_pending_query *auth_agent_query;
int need_random_unref;
};
static const char *ssh_pkt_type(Ssh ssh, int type)
{
if (ssh->version == 1)
return ssh1_pkt_type(type);
else
return ssh2_pkt_type(ssh->pls.kctx, ssh->pls.actx, type);
}
Frontend *ssh_get_frontend(Ssh ssh)
{
return ssh->frontend;
}
#define logevent(s) logevent(ssh->frontend, s)
/* logevent, only printf-formatted. */
static void logeventf(Ssh ssh, const char *fmt, ...)
{
va_list ap;
char *buf;
va_start(ap, fmt);
buf = dupvprintf(fmt, ap);
va_end(ap);
logevent(buf);
sfree(buf);
}
static void bomb_out(Ssh ssh, char *text)
{
ssh_do_close(ssh, FALSE);
logevent(text);
connection_fatal(ssh->frontend, "%s", text);
sfree(text);
}
#define bombout(msg) bomb_out(ssh, dupprintf msg)
static int ssh_channelcmp(void *av, void *bv)
{
struct ssh_channel *a = (struct ssh_channel *) av;
struct ssh_channel *b = (struct ssh_channel *) bv;
if (a->localid < b->localid)
return -1;
if (a->localid > b->localid)
return +1;
return 0;
}
static int ssh_channelfind(void *av, void *bv)
{
unsigned *a = (unsigned *) av;
struct ssh_channel *b = (struct ssh_channel *) bv;
if (*a < b->localid)
return -1;
if (*a > b->localid)
return +1;
return 0;
}
static int ssh_rportcmp_ssh1(void *av, void *bv)
{
struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
int i;
if ( (i = strcmp(a->dhost, b->dhost)) != 0)
return i < 0 ? -1 : +1;
if (a->dport > b->dport)
return +1;
if (a->dport < b->dport)
return -1;
return 0;
}
static int ssh_rportcmp_ssh2(void *av, void *bv)
{
struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
int i;
if ( (i = strcmp(a->shost, b->shost)) != 0)
return i < 0 ? -1 : +1;
if (a->sport > b->sport)
return +1;
if (a->sport < b->sport)
return -1;
return 0;
}
static void c_write(Ssh ssh, const void *buf, int len)
{
from_backend(ssh->frontend, 1, buf, len);
}
static void c_write_str(Ssh ssh, const char *buf)
{
c_write(ssh, buf, strlen(buf));
}
static int s_write(Ssh ssh, const void *data, int len)
{
if (len && ssh->logctx)
log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
0, NULL, NULL, 0, NULL);
if (!ssh->s)
return 0;
return sk_write(ssh->s, data, len);
}
static void ssh_pkt_write(Ssh ssh, PktOut *pkt)
{
if (ssh->version == 2 && ssh->v2_cbc_ignore_workaround &&
bufchain_size(&ssh->outgoing_data) != 0) {
/*
* When using a CBC-mode cipher in SSH-2, it's necessary to
* ensure that an attacker can't provide data to be encrypted
* using an IV that they know. We ensure this by prefixing
* each packet that might contain user data with an
* SSH_MSG_IGNORE.
*/
PktOut *ipkt = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_IGNORE);
put_stringz(ipkt, "");
ssh_bpp_format_packet(ssh->bpp, ipkt);
}
ssh_bpp_format_packet(ssh->bpp, pkt);
queue_idempotent_callback(&ssh->outgoing_data_sender);
}
/*
* Either queue or send a packet, depending on whether queueing is
* set.
*/
static void ssh2_pkt_send(Ssh ssh, PktOut *pkt)
{
if (ssh->queueing) {
pq_push(&ssh->outq, pkt);
} else {
ssh_pkt_write(ssh, pkt);
}
}
static void ssh_send_outgoing_data(void *ctx)
{
Ssh ssh = (Ssh)ctx;
while (bufchain_size(&ssh->outgoing_data) > 0) {
void *data;
int len, backlog;
bufchain_prefix(&ssh->outgoing_data, &data, &len);
backlog = s_write(ssh, data, len);
bufchain_consume(&ssh->outgoing_data, len);
if (ssh->version == 2 && !ssh->kex_in_progress &&
ssh->state != SSH_STATE_PREPACKET &&
!ssh->bare_connection && !ssh->stats.out.running) {
ssh->rekey_reason = "too much data sent";
ssh->rekey_class = RK_NORMAL;
queue_idempotent_callback(&ssh->ssh2_transport_icb);
}
if (backlog > SSH_MAX_BACKLOG) {
ssh_throttle_all(ssh, 1, backlog);
return;
}
}
}
/*
* Send all queued SSH-2 packets.
*/
static void ssh2_pkt_queuesend(Ssh ssh)
{
PktOut *pkt;
assert(!ssh->queueing);
while ((pkt = pq_pop(&ssh->outq)) != NULL)
ssh_pkt_write(ssh, pkt);
}
#if 0
void bndebug(char *string, Bignum b)
{
unsigned char *p;
int i, len;
p = ssh2_mpint_fmt(b, &len);
debug(("%s", string));
for (i = 0; i < len; i++)
debug((" %02x", p[i]));
debug(("\n"));
sfree(p);
}
#endif
/*
* Helper function to add an SSH-2 signature blob to a packet. Expects
* to be shown the public key blob as well as the signature blob.
* Normally just appends the sig blob unmodified as a string, except
* that it optionally breaks it open and fiddle with it to work around
* BUG_SSH2_RSA_PADDING.
*/
static void ssh2_add_sigblob(Ssh ssh, PktOut *pkt,
const void *pkblob, int pkblob_len,
const void *sigblob, int sigblob_len)
{
BinarySource pk[1], sig[1];
BinarySource_BARE_INIT(pk, pkblob, pkblob_len);
BinarySource_BARE_INIT(sig, sigblob, sigblob_len);
/* dmemdump(pkblob, pkblob_len); */
/* dmemdump(sigblob, sigblob_len); */
/*
* See if this is in fact an ssh-rsa signature and a buggy
* server; otherwise we can just do this the easy way.
*/
if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
ptrlen_eq_string(get_string(pk), "ssh-rsa") &&
ptrlen_eq_string(get_string(sig), "ssh-rsa")) {
ptrlen mod_mp, sig_mp;
size_t sig_prefix_len;
/*
* Find the modulus and signature integers.
*/
get_string(pk); /* skip over exponent */
mod_mp = get_string(pk); /* remember modulus */
sig_prefix_len = sig->pos;
sig_mp = get_string(sig);
if (get_err(pk) || get_err(sig))
goto give_up;
/*
* Find the byte length of the modulus, not counting leading
* zeroes.
*/
while (mod_mp.len > 0 && *(const char *)mod_mp.ptr == 0) {
mod_mp.len--;
mod_mp.ptr = (const char *)mod_mp.ptr + 1;
}
/* debug(("modulus length is %d\n", len)); */
/* debug(("signature length is %d\n", siglen)); */
if (mod_mp.len != sig_mp.len) {
strbuf *substr = strbuf_new();
put_data(substr, sigblob, sig_prefix_len);
put_uint32(substr, mod_mp.len);
put_padding(substr, mod_mp.len - sig_mp.len, 0);
put_data(substr, sig_mp.ptr, sig_mp.len);
put_stringsb(pkt, substr);
return;
}
/* Otherwise fall through and do it the easy way. We also come
* here as a fallback if we discover above that the key blob
* is misformatted in some way. */
give_up:;
}
put_string(pkt, sigblob, sigblob_len);
}
static void ssh_feed_to_bpp(Ssh ssh)
{
PacketQueueNode *prev_tail = ssh->pq_full.pqb.end.prev;
assert(ssh->bpp);
ssh_bpp_handle_input(ssh->bpp);
if (ssh->bpp->error) {
bomb_out(ssh, ssh->bpp->error); /* also frees the error string */
return;
}
if (ssh->bpp->seen_disconnect) {
/*
* If we've seen a DISCONNECT message, we should unset the
* close_expected flag, because now we _do_ expect the server
* to close the network connection afterwards. That way, the
* more informative connection_fatal message for the
* disconnect itself won't fight with 'Server unexpectedly
* closed network connection'.
*/
ssh->clean_exit = FALSE;
ssh->close_expected = TRUE;
ssh->disconnect_message_seen = TRUE;
}
if (ssh->pq_full.pqb.end.prev != prev_tail)
queue_idempotent_callback(&ssh->pq_full_consumer);
}
static void ssh_got_ssh_version(struct ssh_version_receiver *rcv,
int major_version)
{
Ssh ssh = FROMFIELD(rcv, struct ssh_tag, version_receiver);
BinaryPacketProtocol *old_bpp;
/*
* This is as good a time as any to stop printing proxy-command
* diagnostics in the terminal window, on the assumption that the
* proxy command must by now have made a sensible connection and
* the real session output will start shortly.
*/
ssh->session_started = TRUE;
/*
* Queue an outgoing-data run: if the version string has been sent
* late rather than early, it'll still be sitting on our output
* raw data queue.
*/
queue_idempotent_callback(&ssh->outgoing_data_sender);
/*
* We don't support choosing a major protocol version dynamically,
* so this should always be the same value we set up in
* connect_to_host().
*/
assert(ssh->version == major_version);
old_bpp = ssh->bpp;
ssh->remote_bugs = ssh_verstring_get_bugs(old_bpp);
if (!ssh->bare_connection) {
if (ssh->version == 2) {
/*
* Retrieve both version strings from the old BPP before
* we free it.
*/
ssh->v_s = dupstr(ssh_verstring_get_remote(old_bpp));
ssh->v_c = dupstr(ssh_verstring_get_local(old_bpp));
/*
* Initialise SSH-2 protocol.
*/
ssh2_protocol_setup(ssh);
ssh->general_packet_processing = ssh2_general_packet_processing;
ssh->current_user_input_fn = NULL;
} else {
/*
* Initialise SSH-1 protocol.
*/
ssh1_protocol_setup(ssh);
ssh->current_user_input_fn = ssh1_login_input;
}
if (ssh->version == 2)
queue_idempotent_callback(&ssh->ssh2_transport_icb);
} else {
assert(ssh->version == 2); /* can't do SSH-1 bare connection! */
logeventf(ssh, "Using bare ssh-connection protocol");
ssh2_bare_connection_protocol_setup(ssh);
ssh->current_user_input_fn = ssh2_connection_input;
}
ssh->bpp->out_raw = &ssh->outgoing_data;
ssh->bpp->in_raw = &ssh->incoming_data;
ssh->bpp->in_pq = &ssh->pq_full;
ssh->bpp->pls = &ssh->pls;
ssh->bpp->logctx = ssh->logctx;
queue_idempotent_callback(&ssh->incoming_data_consumer);
queue_idempotent_callback(&ssh->user_input_consumer);
update_specials_menu(ssh->frontend);
ssh->state = SSH_STATE_BEFORE_SIZE;
ssh->pinger = pinger_new(ssh->conf, &ssh->backend);
if (ssh->bare_connection) {
/*
* Get connection protocol under way.
*/
do_ssh2_connection(ssh);
}
}
static void ssh_process_incoming_data(void *ctx)