Upgrade libgit2
[TortoiseGit.git] / src / TortoisePlink / ssh / common.c
blob23b4591cac8c387fc404572a54a4e09963620a48
1 /*
2 * Supporting routines used in common by all the various components of
3 * the SSH system.
4 */
6 #include <assert.h>
7 #include <stdlib.h>
9 #include "putty.h"
10 #include "mpint.h"
11 #include "ssh.h"
12 #include "storage.h"
13 #include "bpp.h"
14 #include "ppl.h"
15 #include "channel.h"
17 /* ----------------------------------------------------------------------
18 * Implementation of PacketQueue.
21 static void pq_ensure_unlinked(PacketQueueNode *node)
23 if (node->on_free_queue) {
24 node->next->prev = node->prev;
25 node->prev->next = node->next;
26 } else {
27 assert(!node->next);
28 assert(!node->prev);
32 void pq_base_push(PacketQueueBase *pqb, PacketQueueNode *node)
34 pq_ensure_unlinked(node);
35 node->next = &pqb->end;
36 node->prev = pqb->end.prev;
37 node->next->prev = node;
38 node->prev->next = node;
39 pqb->total_size += node->formal_size;
41 if (pqb->ic)
42 queue_idempotent_callback(pqb->ic);
45 void pq_base_push_front(PacketQueueBase *pqb, PacketQueueNode *node)
47 pq_ensure_unlinked(node);
48 node->prev = &pqb->end;
49 node->next = pqb->end.next;
50 node->next->prev = node;
51 node->prev->next = node;
52 pqb->total_size += node->formal_size;
54 if (pqb->ic)
55 queue_idempotent_callback(pqb->ic);
58 static PacketQueueNode pktin_freeq_head = {
59 &pktin_freeq_head, &pktin_freeq_head, true
62 static void pktin_free_queue_callback(void *vctx)
64 while (pktin_freeq_head.next != &pktin_freeq_head) {
65 PacketQueueNode *node = pktin_freeq_head.next;
66 PktIn *pktin = container_of(node, PktIn, qnode);
67 pktin_freeq_head.next = node->next;
68 sfree(pktin);
71 pktin_freeq_head.prev = &pktin_freeq_head;
74 static IdempotentCallback ic_pktin_free = {
75 pktin_free_queue_callback, NULL, false
78 static inline void pq_unlink_common(PacketQueueBase *pqb,
79 PacketQueueNode *node)
81 node->next->prev = node->prev;
82 node->prev->next = node->next;
84 /* Check total_size doesn't drift out of sync downwards, by
85 * ensuring it doesn't underflow when we do this subtraction */
86 assert(pqb->total_size >= node->formal_size);
87 pqb->total_size -= node->formal_size;
89 /* Check total_size doesn't drift out of sync upwards, by checking
90 * that it's returned to exactly zero whenever a queue is
91 * emptied */
92 assert(pqb->end.next != &pqb->end || pqb->total_size == 0);
95 static PktIn *pq_in_after(PacketQueueBase *pqb,
96 PacketQueueNode *prev, bool pop)
98 PacketQueueNode *node = prev->next;
99 if (node == &pqb->end)
100 return NULL;
102 if (pop) {
103 pq_unlink_common(pqb, node);
105 node->prev = pktin_freeq_head.prev;
106 node->next = &pktin_freeq_head;
107 node->next->prev = node;
108 node->prev->next = node;
109 node->on_free_queue = true;
111 queue_idempotent_callback(&ic_pktin_free);
114 return container_of(node, PktIn, qnode);
117 static PktOut *pq_out_after(PacketQueueBase *pqb,
118 PacketQueueNode *prev, bool pop)
120 PacketQueueNode *node = prev->next;
121 if (node == &pqb->end)
122 return NULL;
124 if (pop) {
125 pq_unlink_common(pqb, node);
127 node->prev = node->next = NULL;
130 return container_of(node, PktOut, qnode);
133 void pq_in_init(PktInQueue *pq)
135 pq->pqb.ic = NULL;
136 pq->pqb.end.next = pq->pqb.end.prev = &pq->pqb.end;
137 pq->after = pq_in_after;
138 pq->pqb.total_size = 0;
141 void pq_out_init(PktOutQueue *pq)
143 pq->pqb.ic = NULL;
144 pq->pqb.end.next = pq->pqb.end.prev = &pq->pqb.end;
145 pq->after = pq_out_after;
146 pq->pqb.total_size = 0;
149 void pq_in_clear(PktInQueue *pq)
151 PktIn *pkt;
152 pq->pqb.ic = NULL;
153 while ((pkt = pq_pop(pq)) != NULL) {
154 /* No need to actually free these packets: pq_pop on a
155 * PktInQueue will automatically move them to the free
156 * queue. */
160 void pq_out_clear(PktOutQueue *pq)
162 PktOut *pkt;
163 pq->pqb.ic = NULL;
164 while ((pkt = pq_pop(pq)) != NULL)
165 ssh_free_pktout(pkt);
169 * Concatenate the contents of the two queues q1 and q2, and leave the
170 * result in qdest. qdest must be either empty, or one of the input
171 * queues.
173 void pq_base_concatenate(PacketQueueBase *qdest,
174 PacketQueueBase *q1, PacketQueueBase *q2)
176 struct PacketQueueNode *head1, *tail1, *head2, *tail2;
178 size_t total_size = q1->total_size + q2->total_size;
181 * Extract the contents from both input queues, and empty them.
184 head1 = (q1->end.next == &q1->end ? NULL : q1->end.next);
185 tail1 = (q1->end.prev == &q1->end ? NULL : q1->end.prev);
186 head2 = (q2->end.next == &q2->end ? NULL : q2->end.next);
187 tail2 = (q2->end.prev == &q2->end ? NULL : q2->end.prev);
189 q1->end.next = q1->end.prev = &q1->end;
190 q2->end.next = q2->end.prev = &q2->end;
191 q1->total_size = q2->total_size = 0;
194 * Link the two lists together, handling the case where one or
195 * both is empty.
198 if (tail1)
199 tail1->next = head2;
200 else
201 head1 = head2;
203 if (head2)
204 head2->prev = tail1;
205 else
206 tail2 = tail1;
209 * Check the destination queue is currently empty. (If it was one
210 * of the input queues, then it will be, because we emptied both
211 * of those just a moment ago.)
214 assert(qdest->end.next == &qdest->end);
215 assert(qdest->end.prev == &qdest->end);
218 * If our concatenated list has anything in it, then put it in
219 * dest.
222 if (!head1) {
223 assert(!tail2);
224 } else {
225 assert(tail2);
226 qdest->end.next = head1;
227 qdest->end.prev = tail2;
228 head1->prev = &qdest->end;
229 tail2->next = &qdest->end;
231 if (qdest->ic)
232 queue_idempotent_callback(qdest->ic);
235 qdest->total_size = total_size;
238 /* ----------------------------------------------------------------------
239 * Low-level functions for the packet structures themselves.
242 static void ssh_pkt_BinarySink_write(BinarySink *bs,
243 const void *data, size_t len);
244 PktOut *ssh_new_packet(void)
246 PktOut *pkt = snew(PktOut);
248 BinarySink_INIT(pkt, ssh_pkt_BinarySink_write);
249 pkt->data = NULL;
250 pkt->length = 0;
251 pkt->maxlen = 0;
252 pkt->downstream_id = 0;
253 pkt->additional_log_text = NULL;
254 pkt->qnode.next = pkt->qnode.prev = NULL;
255 pkt->qnode.on_free_queue = false;
257 return pkt;
260 static void ssh_pkt_adddata(PktOut *pkt, const void *data, int len)
262 sgrowarrayn_nm(pkt->data, pkt->maxlen, pkt->length, len);
263 memcpy(pkt->data + pkt->length, data, len);
264 pkt->length += len;
265 pkt->qnode.formal_size = pkt->length;
268 static void ssh_pkt_BinarySink_write(BinarySink *bs,
269 const void *data, size_t len)
271 PktOut *pkt = BinarySink_DOWNCAST(bs, PktOut);
272 ssh_pkt_adddata(pkt, data, len);
275 void ssh_free_pktout(PktOut *pkt)
277 sfree(pkt->data);
278 sfree(pkt);
281 /* ----------------------------------------------------------------------
282 * Implement zombiechan_new() and its trivial vtable.
285 static void zombiechan_free(Channel *chan);
286 static size_t zombiechan_send(
287 Channel *chan, bool is_stderr, const void *, size_t);
288 static void zombiechan_set_input_wanted(Channel *chan, bool wanted);
289 static void zombiechan_do_nothing(Channel *chan);
290 static void zombiechan_open_failure(Channel *chan, const char *);
291 static bool zombiechan_want_close(Channel *chan, bool sent_eof, bool rcvd_eof);
292 static char *zombiechan_log_close_msg(Channel *chan) { return NULL; }
294 static const ChannelVtable zombiechan_channelvt = {
295 .free = zombiechan_free,
296 .open_confirmation = zombiechan_do_nothing,
297 .open_failed = zombiechan_open_failure,
298 .send = zombiechan_send,
299 .send_eof = zombiechan_do_nothing,
300 .set_input_wanted = zombiechan_set_input_wanted,
301 .log_close_msg = zombiechan_log_close_msg,
302 .want_close = zombiechan_want_close,
303 .rcvd_exit_status = chan_no_exit_status,
304 .rcvd_exit_signal = chan_no_exit_signal,
305 .rcvd_exit_signal_numeric = chan_no_exit_signal_numeric,
306 .run_shell = chan_no_run_shell,
307 .run_command = chan_no_run_command,
308 .run_subsystem = chan_no_run_subsystem,
309 .enable_x11_forwarding = chan_no_enable_x11_forwarding,
310 .enable_agent_forwarding = chan_no_enable_agent_forwarding,
311 .allocate_pty = chan_no_allocate_pty,
312 .set_env = chan_no_set_env,
313 .send_break = chan_no_send_break,
314 .send_signal = chan_no_send_signal,
315 .change_window_size = chan_no_change_window_size,
316 .request_response = chan_no_request_response,
319 Channel *zombiechan_new(void)
321 Channel *chan = snew(Channel);
322 chan->vt = &zombiechan_channelvt;
323 chan->initial_fixed_window_size = 0;
324 return chan;
327 static void zombiechan_free(Channel *chan)
329 assert(chan->vt == &zombiechan_channelvt);
330 sfree(chan);
333 static void zombiechan_do_nothing(Channel *chan)
335 assert(chan->vt == &zombiechan_channelvt);
338 static void zombiechan_open_failure(Channel *chan, const char *errtext)
340 assert(chan->vt == &zombiechan_channelvt);
343 static size_t zombiechan_send(Channel *chan, bool is_stderr,
344 const void *data, size_t length)
346 assert(chan->vt == &zombiechan_channelvt);
347 return 0;
350 static void zombiechan_set_input_wanted(Channel *chan, bool enable)
352 assert(chan->vt == &zombiechan_channelvt);
355 static bool zombiechan_want_close(Channel *chan, bool sent_eof, bool rcvd_eof)
357 return true;
360 /* ----------------------------------------------------------------------
361 * Common routines for handling SSH tty modes.
364 static unsigned real_ttymode_opcode(unsigned our_opcode, int ssh_version)
366 switch (our_opcode) {
367 case TTYMODE_ISPEED:
368 return ssh_version == 1 ? TTYMODE_ISPEED_SSH1 : TTYMODE_ISPEED_SSH2;
369 case TTYMODE_OSPEED:
370 return ssh_version == 1 ? TTYMODE_OSPEED_SSH1 : TTYMODE_OSPEED_SSH2;
371 default:
372 return our_opcode;
376 static unsigned our_ttymode_opcode(unsigned real_opcode, int ssh_version)
378 if (ssh_version == 1) {
379 switch (real_opcode) {
380 case TTYMODE_ISPEED_SSH1:
381 return TTYMODE_ISPEED;
382 case TTYMODE_OSPEED_SSH1:
383 return TTYMODE_OSPEED;
384 default:
385 return real_opcode;
387 } else {
388 switch (real_opcode) {
389 case TTYMODE_ISPEED_SSH2:
390 return TTYMODE_ISPEED;
391 case TTYMODE_OSPEED_SSH2:
392 return TTYMODE_OSPEED;
393 default:
394 return real_opcode;
399 struct ssh_ttymodes get_ttymodes_from_conf(Seat *seat, Conf *conf)
401 struct ssh_ttymodes modes;
402 size_t i;
404 static const struct mode_name_type {
405 const char *mode;
406 int opcode;
407 enum { TYPE_CHAR, TYPE_BOOL } type;
408 } modes_names_types[] = {
409 #define TTYMODE_CHAR(name, val, index) { #name, val, TYPE_CHAR },
410 #define TTYMODE_FLAG(name, val, field, mask) { #name, val, TYPE_BOOL },
411 #include "ttymode-list.h"
412 #undef TTYMODE_CHAR
413 #undef TTYMODE_FLAG
416 memset(&modes, 0, sizeof(modes));
418 for (i = 0; i < lenof(modes_names_types); i++) {
419 const struct mode_name_type *mode = &modes_names_types[i];
420 const char *sval = conf_get_str_str(conf, CONF_ttymodes, mode->mode);
421 char *to_free = NULL;
423 if (!sval)
424 sval = "N"; /* just in case */
427 * sval[0] can be
428 * - 'V', indicating that an explicit value follows it;
429 * - 'A', indicating that we should pass the value through from
430 * the local environment via get_ttymode; or
431 * - 'N', indicating that we should explicitly not send this
432 * mode.
434 if (sval[0] == 'A') {
435 sval = to_free = seat_get_ttymode(seat, mode->mode);
436 } else if (sval[0] == 'V') {
437 sval++; /* skip the 'V' */
438 } else {
439 /* else 'N', or something from the future we don't understand */
440 continue;
443 if (sval) {
445 * Parse the string representation of the tty mode
446 * into the integer value it will take on the wire.
448 unsigned ival = 0;
450 switch (mode->type) {
451 case TYPE_CHAR:
452 if (*sval) {
453 char *next = NULL;
454 /* We know ctrlparse won't write to the string, so
455 * casting away const is ugly but allowable. */
456 ival = ctrlparse((char *)sval, &next);
457 if (!next)
458 ival = sval[0];
459 } else {
460 ival = 255; /* special value meaning "don't set" */
462 break;
463 case TYPE_BOOL:
464 if (stricmp(sval, "yes") == 0 ||
465 stricmp(sval, "on") == 0 ||
466 stricmp(sval, "true") == 0 ||
467 stricmp(sval, "+") == 0)
468 ival = 1; /* true */
469 else if (stricmp(sval, "no") == 0 ||
470 stricmp(sval, "off") == 0 ||
471 stricmp(sval, "false") == 0 ||
472 stricmp(sval, "-") == 0)
473 ival = 0; /* false */
474 else
475 ival = (atoi(sval) != 0);
476 break;
477 default:
478 unreachable("Bad mode->type");
481 modes.have_mode[mode->opcode] = true;
482 modes.mode_val[mode->opcode] = ival;
485 sfree(to_free);
489 unsigned ospeed, ispeed;
491 /* Unpick the terminal-speed config string. */
492 ospeed = ispeed = 38400; /* last-resort defaults */
493 sscanf(conf_get_str(conf, CONF_termspeed), "%u,%u", &ospeed, &ispeed);
494 /* Currently we unconditionally set these */
495 modes.have_mode[TTYMODE_ISPEED] = true;
496 modes.mode_val[TTYMODE_ISPEED] = ispeed;
497 modes.have_mode[TTYMODE_OSPEED] = true;
498 modes.mode_val[TTYMODE_OSPEED] = ospeed;
501 return modes;
504 struct ssh_ttymodes read_ttymodes_from_packet(
505 BinarySource *bs, int ssh_version)
507 struct ssh_ttymodes modes;
508 memset(&modes, 0, sizeof(modes));
510 while (1) {
511 unsigned real_opcode, our_opcode;
513 real_opcode = get_byte(bs);
514 if (real_opcode == TTYMODE_END_OF_LIST)
515 break;
516 if (real_opcode >= 160) {
518 * RFC 4254 (and the SSH 1.5 spec): "Opcodes 160 to 255
519 * are not yet defined, and cause parsing to stop (they
520 * should only be used after any other data)."
522 * My interpretation of this is that if one of these
523 * opcodes appears, it's not a parse _error_, but it is
524 * something that we don't know how to parse even well
525 * enough to step over it to find the next opcode, so we
526 * stop parsing now and assume that the rest of the string
527 * is composed entirely of things we don't understand and
528 * (as usual for unsupported terminal modes) silently
529 * ignore.
531 return modes;
534 our_opcode = our_ttymode_opcode(real_opcode, ssh_version);
535 assert(our_opcode < TTYMODE_LIMIT);
536 modes.have_mode[our_opcode] = true;
538 if (ssh_version == 1 && real_opcode >= 1 && real_opcode <= 127)
539 modes.mode_val[our_opcode] = get_byte(bs);
540 else
541 modes.mode_val[our_opcode] = get_uint32(bs);
544 return modes;
547 void write_ttymodes_to_packet(BinarySink *bs, int ssh_version,
548 struct ssh_ttymodes modes)
550 unsigned i;
552 for (i = 0; i < TTYMODE_LIMIT; i++) {
553 if (modes.have_mode[i]) {
554 unsigned val = modes.mode_val[i];
555 unsigned opcode = real_ttymode_opcode(i, ssh_version);
557 put_byte(bs, opcode);
558 if (ssh_version == 1 && opcode >= 1 && opcode <= 127)
559 put_byte(bs, val);
560 else
561 put_uint32(bs, val);
565 put_byte(bs, TTYMODE_END_OF_LIST);
568 /* ----------------------------------------------------------------------
569 * Routine for allocating a new channel ID, given a means of finding
570 * the index field in a given channel structure.
573 unsigned alloc_channel_id_general(tree234 *channels, size_t localid_offset)
575 const unsigned CHANNEL_NUMBER_OFFSET = 256;
576 search234_state ss;
579 * First-fit allocation of channel numbers: we always pick the
580 * lowest unused one.
582 * Every channel before that, and no channel after it, has an ID
583 * exactly equal to its tree index plus CHANNEL_NUMBER_OFFSET. So
584 * we can use the search234 system to identify the length of that
585 * initial sequence, in a single log-time pass down the channels
586 * tree.
588 search234_start(&ss, channels);
589 while (ss.element) {
590 unsigned localid = *(unsigned *)((char *)ss.element + localid_offset);
591 if (localid == ss.index + CHANNEL_NUMBER_OFFSET)
592 search234_step(&ss, +1);
593 else
594 search234_step(&ss, -1);
598 * Now ss.index gives exactly the number of channels in that
599 * initial sequence. So adding CHANNEL_NUMBER_OFFSET to it must
600 * give precisely the lowest unused channel number.
602 return ss.index + CHANNEL_NUMBER_OFFSET;
605 /* ----------------------------------------------------------------------
606 * Functions for handling the comma-separated strings used to store
607 * lists of protocol identifiers in SSH-2.
610 void add_to_commasep_pl(strbuf *buf, ptrlen data)
612 if (buf->len > 0)
613 put_byte(buf, ',');
614 put_datapl(buf, data);
617 void add_to_commasep(strbuf *buf, const char *data)
619 add_to_commasep_pl(buf, ptrlen_from_asciz(data));
622 bool get_commasep_word(ptrlen *list, ptrlen *word)
624 const char *comma;
627 * Discard empty list elements, should there be any, because we
628 * never want to return one as if it was a real string. (This
629 * introduces a mild tolerance of badly formatted data in lists we
630 * receive, but I think that's acceptable.)
632 while (list->len > 0 && *(const char *)list->ptr == ',') {
633 list->ptr = (const char *)list->ptr + 1;
634 list->len--;
637 if (!list->len)
638 return false;
640 comma = memchr(list->ptr, ',', list->len);
641 if (!comma) {
642 *word = *list;
643 list->len = 0;
644 } else {
645 size_t wordlen = comma - (const char *)list->ptr;
646 word->ptr = list->ptr;
647 word->len = wordlen;
648 list->ptr = (const char *)list->ptr + wordlen + 1;
649 list->len -= wordlen + 1;
651 return true;
654 /* ----------------------------------------------------------------------
655 * Functions for translating SSH packet type codes into their symbolic
656 * string names.
659 #define TRANSLATE_UNIVERSAL(y, name, value) \
660 if (type == value) return #name;
661 #define TRANSLATE_KEX(y, name, value, ctx) \
662 if (type == value && pkt_kctx == ctx) return #name;
663 #define TRANSLATE_AUTH(y, name, value, ctx) \
664 if (type == value && pkt_actx == ctx) return #name;
666 const char *ssh1_pkt_type(int type)
668 SSH1_MESSAGE_TYPES(TRANSLATE_UNIVERSAL, y);
669 return "unknown";
671 const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
673 SSH2_MESSAGE_TYPES(TRANSLATE_UNIVERSAL, TRANSLATE_KEX, TRANSLATE_AUTH, y);
674 return "unknown";
677 #undef TRANSLATE_UNIVERSAL
678 #undef TRANSLATE_KEX
679 #undef TRANSLATE_AUTH
681 /* ----------------------------------------------------------------------
682 * Common helper function for clients and implementations of
683 * PacketProtocolLayer.
686 void ssh_ppl_replace(PacketProtocolLayer *old, PacketProtocolLayer *new)
688 new->bpp = old->bpp;
689 ssh_ppl_setup_queues(new, old->in_pq, old->out_pq);
690 new->selfptr = old->selfptr;
691 new->seat = old->seat;
692 new->ssh = old->ssh;
694 *new->selfptr = new;
695 ssh_ppl_free(old);
697 /* The new layer might need to be the first one that sends a
698 * packet, so trigger a call to its main coroutine immediately. If
699 * it doesn't need to go first, the worst that will do is return
700 * straight away. */
701 queue_idempotent_callback(&new->ic_process_queue);
704 void ssh_ppl_free(PacketProtocolLayer *ppl)
706 delete_callbacks_for_context(ppl);
707 ppl->vt->free(ppl);
710 static void ssh_ppl_ic_process_queue_callback(void *context)
712 PacketProtocolLayer *ppl = (PacketProtocolLayer *)context;
713 ssh_ppl_process_queue(ppl);
716 void ssh_ppl_setup_queues(PacketProtocolLayer *ppl,
717 PktInQueue *inq, PktOutQueue *outq)
719 ppl->in_pq = inq;
720 ppl->out_pq = outq;
721 ppl->in_pq->pqb.ic = &ppl->ic_process_queue;
722 ppl->ic_process_queue.fn = ssh_ppl_ic_process_queue_callback;
723 ppl->ic_process_queue.ctx = ppl;
725 /* If there's already something on the input queue, it will want
726 * handling immediately. */
727 if (pq_peek(ppl->in_pq))
728 queue_idempotent_callback(&ppl->ic_process_queue);
731 void ssh_ppl_user_output_string_and_free(PacketProtocolLayer *ppl, char *text)
733 /* Messages sent via this function are from the SSH layer, not
734 * from the server-side process, so they always have the stderr
735 * flag set. */
736 seat_stderr_pl(ppl->seat, ptrlen_from_asciz(text));
737 sfree(text);
740 size_t ssh_ppl_default_queued_data_size(PacketProtocolLayer *ppl)
742 return ppl->out_pq->pqb.total_size;
745 void ssh_ppl_default_final_output(PacketProtocolLayer *ppl)
749 static void ssh_ppl_prompts_callback(void *ctx)
751 ssh_ppl_process_queue((PacketProtocolLayer *)ctx);
754 prompts_t *ssh_ppl_new_prompts(PacketProtocolLayer *ppl)
756 prompts_t *p = new_prompts();
757 p->callback = ssh_ppl_prompts_callback;
758 p->callback_ctx = ppl;
759 return p;
762 /* ----------------------------------------------------------------------
763 * Common helper functions for clients and implementations of
764 * BinaryPacketProtocol.
767 static void ssh_bpp_input_raw_data_callback(void *context)
769 BinaryPacketProtocol *bpp = (BinaryPacketProtocol *)context;
770 Ssh *ssh = bpp->ssh; /* in case bpp is about to get freed */
771 ssh_bpp_handle_input(bpp);
772 /* If we've now cleared enough backlog on the input connection, we
773 * may need to unfreeze it. */
774 ssh_conn_processed_data(ssh);
777 static void ssh_bpp_output_packet_callback(void *context)
779 BinaryPacketProtocol *bpp = (BinaryPacketProtocol *)context;
780 ssh_bpp_handle_output(bpp);
783 void ssh_bpp_common_setup(BinaryPacketProtocol *bpp)
785 pq_in_init(&bpp->in_pq);
786 pq_out_init(&bpp->out_pq);
787 bpp->input_eof = false;
788 bpp->ic_in_raw.fn = ssh_bpp_input_raw_data_callback;
789 bpp->ic_in_raw.ctx = bpp;
790 bpp->ic_out_pq.fn = ssh_bpp_output_packet_callback;
791 bpp->ic_out_pq.ctx = bpp;
792 bpp->out_pq.pqb.ic = &bpp->ic_out_pq;
795 void ssh_bpp_free(BinaryPacketProtocol *bpp)
797 delete_callbacks_for_context(bpp);
798 bpp->vt->free(bpp);
801 void ssh2_bpp_queue_disconnect(BinaryPacketProtocol *bpp,
802 const char *msg, int category)
804 PktOut *pkt = ssh_bpp_new_pktout(bpp, SSH2_MSG_DISCONNECT);
805 put_uint32(pkt, category);
806 put_stringz(pkt, msg);
807 put_stringz(pkt, "en"); /* language tag */
808 pq_push(&bpp->out_pq, pkt);
811 #define BITMAP_UNIVERSAL(y, name, value) \
812 | (value >= y && value < y+32 \
813 ? 1UL << (value >= y && value < y+32 ? (value-y) : 0) \
814 : 0)
815 #define BITMAP_CONDITIONAL(y, name, value, ctx) \
816 BITMAP_UNIVERSAL(y, name, value)
817 #define SSH2_BITMAP_WORD(y) \
818 (0 SSH2_MESSAGE_TYPES(BITMAP_UNIVERSAL, BITMAP_CONDITIONAL, \
819 BITMAP_CONDITIONAL, (32*y)))
821 bool ssh2_bpp_check_unimplemented(BinaryPacketProtocol *bpp, PktIn *pktin)
823 static const unsigned valid_bitmap[] = {
824 SSH2_BITMAP_WORD(0),
825 SSH2_BITMAP_WORD(1),
826 SSH2_BITMAP_WORD(2),
827 SSH2_BITMAP_WORD(3),
828 SSH2_BITMAP_WORD(4),
829 SSH2_BITMAP_WORD(5),
830 SSH2_BITMAP_WORD(6),
831 SSH2_BITMAP_WORD(7),
834 if (pktin->type < 0x100 &&
835 !((valid_bitmap[pktin->type >> 5] >> (pktin->type & 0x1F)) & 1)) {
836 PktOut *pkt = ssh_bpp_new_pktout(bpp, SSH2_MSG_UNIMPLEMENTED);
837 put_uint32(pkt, pktin->sequence);
838 pq_push(&bpp->out_pq, pkt);
839 return true;
842 return false;
845 #undef BITMAP_UNIVERSAL
846 #undef BITMAP_CONDITIONAL
847 #undef SSH2_BITMAP_WORD
849 /* ----------------------------------------------------------------------
850 * Centralised component of SSH host key verification.
852 * verify_ssh_host_key is called from both the SSH-1 and SSH-2
853 * transport layers, and does the initial work of checking whether the
854 * host key is already known. If so, it returns success on its own
855 * account; otherwise, it calls out to the Seat to give an interactive
856 * prompt (the nature of which varies depending on the Seat itself).
859 SeatPromptResult verify_ssh_host_key(
860 InteractionReadySeat iseat, Conf *conf, const char *host, int port,
861 ssh_key *key, const char *keytype, char *keystr, const char *keydisp,
862 char **fingerprints, int ca_count,
863 void (*callback)(void *ctx, SeatPromptResult result), void *ctx)
866 * First, check if the Conf includes a manual specification of the
867 * expected host key. If so, that completely supersedes everything
868 * else, including the normal host key cache _and_ including
869 * manual overrides: we return success or failure immediately,
870 * entirely based on whether the key matches the Conf.
872 if (conf_get_str_nthstrkey(conf, CONF_ssh_manual_hostkeys, 0)) {
873 if (fingerprints) {
874 for (size_t i = 0; i < SSH_N_FPTYPES; i++) {
876 * Each fingerprint string we've been given will have
877 * things like 'ssh-rsa 2048' at the front of it. Strip
878 * those off and narrow down to just the hash at the end
879 * of the string.
881 const char *fingerprint = fingerprints[i];
882 if (!fingerprint)
883 continue;
884 const char *p = strrchr(fingerprint, ' ');
885 fingerprint = p ? p+1 : fingerprint;
886 if (conf_get_str_str_opt(conf, CONF_ssh_manual_hostkeys,
887 fingerprint))
888 return SPR_OK;
892 if (key) {
894 * Construct the base64-encoded public key blob and see if
895 * that's listed.
897 strbuf *binblob;
898 char *base64blob;
899 int atoms, i;
900 binblob = strbuf_new();
901 ssh_key_public_blob(key, BinarySink_UPCAST(binblob));
902 atoms = (binblob->len + 2) / 3;
903 base64blob = snewn(atoms * 4 + 1, char);
904 for (i = 0; i < atoms; i++)
905 base64_encode_atom(binblob->u + 3*i,
906 binblob->len - 3*i, base64blob + 4*i);
907 base64blob[atoms * 4] = '\0';
908 strbuf_free(binblob);
909 if (conf_get_str_str_opt(conf, CONF_ssh_manual_hostkeys,
910 base64blob)) {
911 sfree(base64blob);
912 return SPR_OK;
914 sfree(base64blob);
917 return SPR_SW_ABORT("Host key not in manually configured list");
921 * Next, check the host key cache.
923 int storage_status = check_stored_host_key(host, port, keytype, keystr);
924 if (storage_status == 0) /* matching key was found in the cache */
925 return SPR_OK;
928 * The key is either missing from the cache, or does not match.
929 * Either way, fall back to an interactive prompt from the Seat.
931 SeatDialogText *text = seat_dialog_text_new();
932 const SeatDialogPromptDescriptions *pds =
933 seat_prompt_descriptions(iseat.seat);
935 FingerprintType fptype_default =
936 ssh2_pick_default_fingerprint(fingerprints);
938 seat_dialog_text_append(
939 text, SDT_TITLE, "%s Security Alert", appname);
941 HelpCtx helpctx;
943 if (key && ssh_key_alg(key)->is_certificate) {
944 seat_dialog_text_append(
945 text, SDT_SCARY_HEADING, "WARNING - POTENTIAL SECURITY BREACH!");
946 seat_dialog_text_append(
947 text, SDT_PARA, "This server presented a certified host key:");
948 seat_dialog_text_append(
949 text, SDT_DISPLAY, "%s (port %d)", host, port);
950 if (ca_count) {
951 seat_dialog_text_append(
952 text, SDT_PARA, "which was signed by a different "
953 "certification authority from the %s %s is configured to "
954 "trust for this server.", ca_count > 1 ? "ones" : "one",
955 appname);
956 if (storage_status == 2) {
957 seat_dialog_text_append(
958 text, SDT_PARA, "ALSO, that key does not match the key "
959 "%s had previously cached for this server.", appname);
960 seat_dialog_text_append(
961 text, SDT_PARA, "This means that either another "
962 "certification authority is operating in this realm AND "
963 "the server administrator has changed the host key, or "
964 "you have actually connected to another computer "
965 "pretending to be the server.");
966 } else {
967 seat_dialog_text_append(
968 text, SDT_PARA, "This means that either another "
969 "certification authority is operating in this realm, or "
970 "you have actually connected to another computer "
971 "pretending to be the server.");
973 } else {
974 assert(storage_status == 2);
975 seat_dialog_text_append(
976 text, SDT_PARA, "which does not match the certified key %s "
977 "had previously cached for this server.", appname);
978 seat_dialog_text_append(
979 text, SDT_PARA, "This means that either the server "
980 "administrator has changed the host key, or you have actually "
981 "connected to another computer pretending to be the server.");
983 seat_dialog_text_append(
984 text, SDT_PARA, "The new %s key fingerprint is:", keytype);
985 seat_dialog_text_append(
986 text, SDT_DISPLAY, "%s", fingerprints[fptype_default]);
987 seat_dialog_text_append(
988 text, SDT_DISPLAY, "%s", fingerprints[SSH_FPTYPE_MD5]);
989 helpctx = HELPCTX(errors_cert_mismatch);
990 } else if (storage_status == 1) {
991 seat_dialog_text_append(
992 text, SDT_PARA, "The host key is not cached for this server:");
993 seat_dialog_text_append(
994 text, SDT_DISPLAY, "%s (port %d)", host, port);
995 seat_dialog_text_append(
996 text, SDT_PARA, "You have no guarantee that the server is the "
997 "computer you think it is.");
998 seat_dialog_text_append(
999 text, SDT_PARA, "The server's %s key fingerprint is:", keytype);
1000 seat_dialog_text_append(
1001 text, SDT_DISPLAY, "%s", fingerprints[fptype_default]);
1002 seat_dialog_text_append(
1003 text, SDT_DISPLAY, "%s", fingerprints[SSH_FPTYPE_MD5]);
1004 helpctx = HELPCTX(errors_hostkey_absent);
1005 } else {
1006 seat_dialog_text_append(
1007 text, SDT_SCARY_HEADING, "WARNING - POTENTIAL SECURITY BREACH!");
1008 seat_dialog_text_append(
1009 text, SDT_PARA, "The host key does not match the one %s has "
1010 "cached for this server:", appname);
1011 seat_dialog_text_append(
1012 text, SDT_DISPLAY, "%s (port %d)", host, port);
1013 seat_dialog_text_append(
1014 text, SDT_PARA, "This means that either the server administrator "
1015 "has changed the host key, or you have actually connected to "
1016 "another computer pretending to be the server.");
1017 seat_dialog_text_append(
1018 text, SDT_PARA, "The new %s key fingerprint is:", keytype);
1019 seat_dialog_text_append(
1020 text, SDT_DISPLAY, "%s", fingerprints[fptype_default]);
1021 seat_dialog_text_append(
1022 text, SDT_DISPLAY, "%s", fingerprints[SSH_FPTYPE_MD5]);
1023 helpctx = HELPCTX(errors_hostkey_changed);
1026 /* The above text is printed even in batch mode. Here's where we stop if
1027 * we can't present interactive prompts. */
1028 seat_dialog_text_append(
1029 text, SDT_BATCH_ABORT, "Connection abandoned.");
1031 if (storage_status == 1) {
1032 seat_dialog_text_append(
1033 text, SDT_PARA, "If you trust this host, %s to add the key to "
1034 "%s's cache and carry on connecting.",
1035 pds->hk_accept_action, appname);
1036 if (key && ssh_key_alg(key)->is_certificate) {
1037 seat_dialog_text_append(
1038 text, SDT_PARA, "(Storing this certified key in the cache "
1039 "will NOT cause its certification authority to be trusted "
1040 "for any other key or host.)");
1042 seat_dialog_text_append(
1043 text, SDT_PARA, "If you want to carry on connecting just once, "
1044 "without adding the key to the cache, %s.",
1045 pds->hk_connect_once_action);
1046 seat_dialog_text_append(
1047 text, SDT_PARA, "If you do not trust this host, %s to abandon the "
1048 "connection.", pds->hk_cancel_action);
1049 seat_dialog_text_append(
1050 text, SDT_PROMPT, "Store key in cache?");
1051 } else {
1052 seat_dialog_text_append(
1053 text, SDT_PARA, "If you were expecting this change and trust the "
1054 "new key, %s to update %s's cache and carry on connecting.",
1055 pds->hk_accept_action, appname);
1056 if (key && ssh_key_alg(key)->is_certificate) {
1057 seat_dialog_text_append(
1058 text, SDT_PARA, "(Storing this certified key in the cache "
1059 "will NOT cause its certification authority to be trusted "
1060 "for any other key or host.)");
1062 seat_dialog_text_append(
1063 text, SDT_PARA, "If you want to carry on connecting but without "
1064 "updating the cache, %s.", pds->hk_connect_once_action);
1065 seat_dialog_text_append(
1066 text, SDT_PARA, "If you want to abandon the connection "
1067 "completely, %s to cancel. %s is the ONLY guaranteed safe choice.",
1068 pds->hk_cancel_action, pds->hk_cancel_action_Participle);
1069 seat_dialog_text_append(
1070 text, SDT_PROMPT, "Update cached key?");
1073 seat_dialog_text_append(text, SDT_MORE_INFO_KEY,
1074 "Full text of host's public key");
1075 seat_dialog_text_append(text, SDT_MORE_INFO_VALUE_BLOB, "%s", keydisp);
1077 if (fingerprints[SSH_FPTYPE_SHA256]) {
1078 seat_dialog_text_append(text, SDT_MORE_INFO_KEY, "SHA256 fingerprint");
1079 seat_dialog_text_append(text, SDT_MORE_INFO_VALUE_SHORT, "%s",
1080 fingerprints[SSH_FPTYPE_SHA256]);
1082 if (fingerprints[SSH_FPTYPE_MD5]) {
1083 seat_dialog_text_append(text, SDT_MORE_INFO_KEY, "MD5 fingerprint");
1084 seat_dialog_text_append(text, SDT_MORE_INFO_VALUE_SHORT, "%s",
1085 fingerprints[SSH_FPTYPE_MD5]);
1088 SeatPromptResult toret = seat_confirm_ssh_host_key(
1089 iseat, host, port, keytype, keystr, text, helpctx, callback, ctx);
1090 seat_dialog_text_free(text);
1091 return toret;
1094 SeatPromptResult confirm_weak_crypto_primitive(
1095 InteractionReadySeat iseat, const char *algtype, const char *algname,
1096 void (*callback)(void *ctx, SeatPromptResult result), void *ctx,
1097 WeakCryptoReason wcr)
1099 SeatDialogText *text = seat_dialog_text_new();
1100 const SeatDialogPromptDescriptions *pds =
1101 seat_prompt_descriptions(iseat.seat);
1103 seat_dialog_text_append(text, SDT_TITLE, "%s Security Alert", appname);
1105 switch (wcr) {
1106 case WCR_BELOW_THRESHOLD:
1107 seat_dialog_text_append(
1108 text, SDT_PARA,
1109 "The first %s supported by the server is %s, "
1110 "which is below the configured warning threshold.",
1111 algtype, algname);
1112 break;
1113 case WCR_TERRAPIN:
1114 case WCR_TERRAPIN_AVOIDABLE:
1115 seat_dialog_text_append(
1116 text, SDT_PARA,
1117 "The %s selected for this session is %s, "
1118 "which, with this server, is vulnerable to the 'Terrapin' attack "
1119 "CVE-2023-48795, potentially allowing an attacker to modify "
1120 "the encrypted session.",
1121 algtype, algname);
1122 seat_dialog_text_append(
1123 text, SDT_PARA,
1124 "Upgrading, patching, or reconfiguring this SSH server is the "
1125 "best way to avoid this vulnerability, if possible.");
1126 if (wcr == WCR_TERRAPIN_AVOIDABLE) {
1127 seat_dialog_text_append(
1128 text, SDT_PARA,
1129 "You can also avoid this vulnerability by abandoning "
1130 "this connection, moving ChaCha20 to below the "
1131 "'warn below here' line in PuTTY's SSH cipher "
1132 "configuration (so that an algorithm without the "
1133 "vulnerability will be selected), and starting a new "
1134 "connection.");
1136 break;
1137 default:
1138 unreachable("bad WeakCryptoReason");
1141 /* In batch mode, we print the above information and then this
1142 * abort message, and stop. */
1143 seat_dialog_text_append(text, SDT_BATCH_ABORT, "Connection abandoned.");
1145 seat_dialog_text_append(
1146 text, SDT_PARA, "To accept the risk and continue, %s. "
1147 "To abandon the connection, %s.",
1148 pds->weak_accept_action, pds->weak_cancel_action);
1150 seat_dialog_text_append(text, SDT_PROMPT, "Continue with connection?");
1152 SeatPromptResult toret = seat_confirm_weak_crypto_primitive(
1153 iseat, text, callback, ctx);
1154 seat_dialog_text_free(text);
1155 return toret;
1158 SeatPromptResult confirm_weak_cached_hostkey(
1159 InteractionReadySeat iseat, const char *algname, const char **betteralgs,
1160 void (*callback)(void *ctx, SeatPromptResult result), void *ctx)
1162 SeatDialogText *text = seat_dialog_text_new();
1163 const SeatDialogPromptDescriptions *pds =
1164 seat_prompt_descriptions(iseat.seat);
1166 seat_dialog_text_append(text, SDT_TITLE, "%s Security Alert", appname);
1168 seat_dialog_text_append(
1169 text, SDT_PARA,
1170 "The first host key type we have stored for this server "
1171 "is %s, which is below the configured warning threshold.", algname);
1173 seat_dialog_text_append(
1174 text, SDT_PARA,
1175 "The server also provides the following types of host key "
1176 "above the threshold, which we do not have stored:");
1178 for (const char **p = betteralgs; *p; p++)
1179 seat_dialog_text_append(text, SDT_DISPLAY, "%s", *p);
1181 /* In batch mode, we print the above information and then this
1182 * abort message, and stop. */
1183 seat_dialog_text_append(text, SDT_BATCH_ABORT, "Connection abandoned.");
1185 seat_dialog_text_append(
1186 text, SDT_PARA, "To accept the risk and continue, %s. "
1187 "To abandon the connection, %s.",
1188 pds->weak_accept_action, pds->weak_cancel_action);
1190 seat_dialog_text_append(text, SDT_PROMPT, "Continue with connection?");
1192 SeatPromptResult toret = seat_confirm_weak_cached_hostkey(
1193 iseat, text, callback, ctx);
1194 seat_dialog_text_free(text);
1195 return toret;
1198 /* ----------------------------------------------------------------------
1199 * Common functions shared between SSH-1 layers.
1202 bool ssh1_common_get_specials(
1203 PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx)
1206 * Don't bother offering IGNORE if we've decided the remote
1207 * won't cope with it, since we wouldn't bother sending it if
1208 * asked anyway.
1210 if (!(ppl->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
1211 add_special(ctx, "IGNORE message", SS_NOP, 0);
1212 return true;
1215 return false;
1218 bool ssh1_common_filter_queue(PacketProtocolLayer *ppl)
1220 PktIn *pktin;
1221 ptrlen msg;
1223 while ((pktin = pq_peek(ppl->in_pq)) != NULL) {
1224 switch (pktin->type) {
1225 case SSH1_MSG_DISCONNECT:
1226 msg = get_string(pktin);
1227 ssh_remote_error(ppl->ssh,
1228 "Remote side sent disconnect message:\n\"%.*s\"",
1229 PTRLEN_PRINTF(msg));
1230 /* don't try to pop the queue, because we've been freed! */
1231 return true; /* indicate that we've been freed */
1233 case SSH1_MSG_DEBUG:
1234 msg = get_string(pktin);
1235 ppl_logevent("Remote debug message: %.*s", PTRLEN_PRINTF(msg));
1236 pq_pop(ppl->in_pq);
1237 break;
1239 case SSH1_MSG_IGNORE:
1240 /* Do nothing, because we're ignoring it! Duhh. */
1241 pq_pop(ppl->in_pq);
1242 break;
1244 default:
1245 return false;
1249 return false;
1252 void ssh1_compute_session_id(
1253 unsigned char *session_id, const unsigned char *cookie,
1254 RSAKey *hostkey, RSAKey *servkey)
1256 ssh_hash *hash = ssh_hash_new(&ssh_md5);
1258 for (size_t i = (mp_get_nbits(hostkey->modulus) + 7) / 8; i-- ;)
1259 put_byte(hash, mp_get_byte(hostkey->modulus, i));
1260 for (size_t i = (mp_get_nbits(servkey->modulus) + 7) / 8; i-- ;)
1261 put_byte(hash, mp_get_byte(servkey->modulus, i));
1262 put_data(hash, cookie, 8);
1263 ssh_hash_final(hash, session_id);
1266 /* ----------------------------------------------------------------------
1267 * Wrapper function to handle the abort-connection modes of a
1268 * SeatPromptResult without a lot of verbiage at every call site.
1270 * Can become ssh_sw_abort or ssh_user_close, depending on the kind of
1271 * negative SeatPromptResult.
1273 void ssh_spr_close(Ssh *ssh, SeatPromptResult spr, const char *context)
1275 if (spr.kind == SPRK_USER_ABORT) {
1276 ssh_user_close(ssh, "User aborted at %s", context);
1277 } else {
1278 assert(spr.kind == SPRK_SW_ABORT);
1279 char *err = spr_get_error_message(spr);
1280 ssh_sw_abort(ssh, "%s", err);
1281 sfree(err);