1 /*
2  * packet.c - packet building functions
3  *
4  * This file is part of the SSH Library
5  *
6  * Copyright (c) 2003-2013 by Aris Adamantiadis
7  *
8  * The SSH Library is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published by
10  * the Free Software Foundation; either version 2.1 of the License, or (at your
11  * option) any later version.
12  *
13  * The SSH Library is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16  * License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with the SSH Library; see the file COPYING.  If not, write to
20  * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21  * MA 02111-1307, USA.
22  */
23 
24 #include "config.h"
25 
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <errno.h>
30 
31 #ifndef _WIN32
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #endif
35 
36 #include "libssh/priv.h"
37 #include "libssh/ssh2.h"
38 #include "libssh/crypto.h"
39 #include "libssh/buffer.h"
40 #include "libssh/packet.h"
41 #include "libssh/socket.h"
42 #include "libssh/channels.h"
43 #include "libssh/misc.h"
44 #include "libssh/session.h"
45 #include "libssh/messages.h"
46 #include "libssh/pcap.h"
47 #include "libssh/kex.h"
48 #include "libssh/auth.h"
49 #include "libssh/gssapi.h"
50 #include "libssh/bytearray.h"
51 #include "libssh/dh.h"
52 
53 static ssh_packet_callback default_packet_handlers[]= {
54   ssh_packet_disconnect_callback,          // SSH2_MSG_DISCONNECT                 1
55   ssh_packet_ignore_callback,              // SSH2_MSG_IGNORE	                    2
56   ssh_packet_unimplemented,                // SSH2_MSG_UNIMPLEMENTED              3
57   ssh_packet_ignore_callback,              // SSH2_MSG_DEBUG	                    4
58 #if WITH_SERVER
59   ssh_packet_service_request,              // SSH2_MSG_SERVICE_REQUEST	          5
60 #else
61   NULL,
62 #endif
63   ssh_packet_service_accept,               // SSH2_MSG_SERVICE_ACCEPT             6
64   ssh_packet_ext_info,                     // SSH2_MSG_EXT_INFO                   7
65   NULL, NULL, NULL, NULL, NULL, NULL,
66   NULL, NULL, NULL, NULL, NULL, NULL,      //                                     8-19
67   ssh_packet_kexinit,                      // SSH2_MSG_KEXINIT	                  20
68   ssh_packet_newkeys,                      // SSH2_MSG_NEWKEYS                    21
69   NULL, NULL, NULL, NULL, NULL, NULL, NULL,
70   NULL,                                    //                                     22-29
71 #if WITH_SERVER
72   ssh_packet_kexdh_init,                   // SSH2_MSG_KEXDH_INIT                 30
73                                            // SSH2_MSG_KEX_DH_GEX_REQUEST_OLD     30
74 #else
75   NULL,
76 #endif
77   NULL,                                    // SSH2_MSG_KEXDH_REPLY                31
78                                            // SSH2_MSG_KEX_DH_GEX_GROUP           31
79   NULL,                                    // SSH2_MSG_KEX_DH_GEX_INIT            32
80   NULL,                                    // SSH2_MSG_KEX_DH_GEX_REPLY           33
81   NULL,                                    // SSH2_MSG_KEX_DH_GEX_REQUEST         34
82   NULL, NULL, NULL, NULL, NULL, NULL,	NULL,
83   NULL, NULL, NULL, NULL, NULL, NULL, NULL,
84   NULL,                                    //                                     35-49
85 #if WITH_SERVER
86   ssh_packet_userauth_request,             // SSH2_MSG_USERAUTH_REQUEST           50
87 #else
88   NULL,
89 #endif
90   ssh_packet_userauth_failure,             // SSH2_MSG_USERAUTH_FAILURE           51
91   ssh_packet_userauth_success,             // SSH2_MSG_USERAUTH_SUCCESS           52
92   ssh_packet_userauth_banner,              // SSH2_MSG_USERAUTH_BANNER            53
93   NULL,NULL,NULL,NULL,NULL,NULL,           //                                     54-59
94   ssh_packet_userauth_pk_ok,               // SSH2_MSG_USERAUTH_PK_OK             60
95                                            // SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ  60
96                                            // SSH2_MSG_USERAUTH_INFO_REQUEST	  60
97                                            // SSH2_MSG_USERAUTH_GSSAPI_RESPONSE   60
98   ssh_packet_userauth_info_response,       // SSH2_MSG_USERAUTH_INFO_RESPONSE     61
99                                            // SSH2_MSG_USERAUTH_GSSAPI_TOKEN      61
100   NULL,                                    //                                     62
101   NULL,                             // SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
102   NULL,                                    // SSH2_MSG_USERAUTH_GSSAPI_ERROR      64
103   NULL,                                    // SSH2_MSG_USERAUTH_GSSAPI_ERRTOK     65
104 #if defined(WITH_GSSAPI) && defined(WITH_SERVER)
105   ssh_packet_userauth_gssapi_mic,          // SSH2_MSG_USERAUTH_GSSAPI_MIC        66
106 #else /* WITH_GSSAPI && WITH_SERVER */
107   NULL,
108 #endif /* WITH_GSSAPI && WITH_SERVER */
109   NULL, NULL,
110   NULL, NULL, NULL, NULL, NULL, NULL, NULL,
111   NULL, NULL, NULL, NULL,                  //                                     67-79
112 #ifdef WITH_SERVER
113   ssh_packet_global_request,               // SSH2_MSG_GLOBAL_REQUEST             80
114 #else /* WITH_SERVER */
115   NULL,
116 #endif /* WITH_SERVER */
117   ssh_request_success,                     // SSH2_MSG_REQUEST_SUCCESS            81
118   ssh_request_denied,                      // SSH2_MSG_REQUEST_FAILURE            82
119   NULL, NULL, NULL, NULL, NULL, NULL, NULL,//                                     83-89
120   ssh_packet_channel_open,                 // SSH2_MSG_CHANNEL_OPEN               90
121   ssh_packet_channel_open_conf,            // SSH2_MSG_CHANNEL_OPEN_CONFIRMATION  91
122   ssh_packet_channel_open_fail,            // SSH2_MSG_CHANNEL_OPEN_FAILURE       92
123   channel_rcv_change_window,               // SSH2_MSG_CHANNEL_WINDOW_ADJUST      93
124   channel_rcv_data,                        // SSH2_MSG_CHANNEL_DATA               94
125   channel_rcv_data,                        // SSH2_MSG_CHANNEL_EXTENDED_DATA      95
126   channel_rcv_eof,                         // SSH2_MSG_CHANNEL_EOF	              96
127   channel_rcv_close,                       // SSH2_MSG_CHANNEL_CLOSE              97
128   channel_rcv_request,                     // SSH2_MSG_CHANNEL_REQUEST            98
129   ssh_packet_channel_success,              // SSH2_MSG_CHANNEL_SUCCESS            99
130   ssh_packet_channel_failure,              // SSH2_MSG_CHANNEL_FAILURE            100
131 };
132 
133 /** @internal
134  * @brief check if the received packet is allowed for the current session state
135  * @param session current ssh_session
136  * @returns SSH_PACKET_ALLOWED if the packet is allowed; SSH_PACKET_DENIED
137  * if the packet arrived in wrong state; SSH_PACKET_UNKNOWN if the packet type
138  * is unknown
139  */
ssh_packet_incoming_filter(ssh_session session)140 static enum ssh_packet_filter_result_e ssh_packet_incoming_filter(ssh_session session)
141 {
142     enum ssh_packet_filter_result_e rc;
143 
144 #ifdef DEBUG_PACKET
145     SSH_LOG(SSH_LOG_PACKET, "Filtering packet type %d",
146             session->in_packet.type);
147 #endif
148 
149     switch(session->in_packet.type) {
150     case SSH2_MSG_DISCONNECT:                         // 1
151         /*
152          * States required:
153          * - None
154          *
155          * Transitions:
156          * - session->socket->state = SSH_SOCKET_CLOSED
157          * - session->session_state = SSH_SESSION_STATE_ERROR
158          * */
159 
160         /* Always allowed */
161         rc = SSH_PACKET_ALLOWED;
162         break;
163     case SSH2_MSG_IGNORE:                             // 2
164         /*
165          * States required:
166          * - None
167          *
168          * Transitions:
169          * - None
170          * */
171 
172         /* Always allowed */
173         rc = SSH_PACKET_ALLOWED;
174         break;
175     case SSH2_MSG_UNIMPLEMENTED:                      // 3
176         /*
177          * States required:
178          * - None
179          *
180          * Transitions:
181          * - None
182          * */
183 
184         /* Always allowed */
185         rc = SSH_PACKET_ALLOWED;
186         break;
187     case SSH2_MSG_DEBUG:                              // 4
188         /*
189          * States required:
190          * - None
191          *
192          * Transitions:
193          * - None
194          * */
195 
196         /* Always allowed */
197         rc = SSH_PACKET_ALLOWED;
198         break;
199     case SSH2_MSG_SERVICE_REQUEST:                    // 5
200         /* Server only */
201 
202         /*
203          * States required:
204          * - session->session_state == SSH_SESSION_STATE_AUTHENTICATING
205          *   or session->session_state == SSH_SESSION_STATE_AUTHENTICATED
206          * - session->dh_handshake_state == DH_STATE_FINISHED
207          *
208          * Transitions:
209          * - None
210          * */
211 
212         /* If this is a client, reject the message */
213         if (session->client) {
214             rc = SSH_PACKET_DENIED;
215             break;
216         }
217 
218         if ((session->session_state != SSH_SESSION_STATE_AUTHENTICATING) &&
219             (session->session_state != SSH_SESSION_STATE_AUTHENTICATED))
220         {
221             rc = SSH_PACKET_DENIED;
222             break;
223         }
224 
225         if (session->dh_handshake_state != DH_STATE_FINISHED) {
226             rc = SSH_PACKET_DENIED;
227             break;
228         }
229 
230         rc = SSH_PACKET_ALLOWED;
231         break;
232     case SSH2_MSG_SERVICE_ACCEPT:                     // 6
233         /*
234          * States required:
235          * - session->session_state == SSH_SESSION_STATE_AUTHENTICATING
236          *   or session->session_state == SSH_SESSION_STATE_AUTHENTICATED
237          * - session->dh_handshake_state == DH_STATE_FINISHED
238          * - session->auth.service_state == SSH_AUTH_SERVICE_SENT
239          *
240          * Transitions:
241          * - auth.service_state = SSH_AUTH_SERVICE_ACCEPTED
242          * */
243 
244         if ((session->session_state != SSH_SESSION_STATE_AUTHENTICATING) &&
245             (session->session_state != SSH_SESSION_STATE_AUTHENTICATED))
246         {
247             rc = SSH_PACKET_DENIED;
248             break;
249         }
250 
251         if (session->dh_handshake_state != DH_STATE_FINISHED) {
252             rc = SSH_PACKET_DENIED;
253             break;
254         }
255 
256         /* TODO check if only auth service can be requested */
257         if (session->auth.service_state != SSH_AUTH_SERVICE_SENT) {
258             rc = SSH_PACKET_DENIED;
259             break;
260         }
261 
262         rc = SSH_PACKET_ALLOWED;
263         break;
264     case SSH2_MSG_EXT_INFO:                           // 7
265         /*
266          * States required:
267          * - session_state == SSH_SESSION_STATE_AUTHENTICATING
268          *   or session->session_state == SSH_SESSION_STATE_AUTHENTICATED
269          *   (re-exchange)
270          * - dh_handshake_state == DH_STATE_FINISHED
271          *
272          * Transitions:
273          * - None
274          * */
275 
276         if ((session->session_state != SSH_SESSION_STATE_AUTHENTICATING) &&
277             (session->session_state != SSH_SESSION_STATE_AUTHENTICATED))
278         {
279             rc = SSH_PACKET_DENIED;
280             break;
281         }
282 
283         if (session->dh_handshake_state != DH_STATE_FINISHED) {
284             rc = SSH_PACKET_DENIED;
285             break;
286         }
287 
288         rc = SSH_PACKET_ALLOWED;
289         break;
290     case SSH2_MSG_KEXINIT:                            // 20
291         /*
292          * States required:
293          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
294          *   or session_state == SSH_SESSION_STATE_INITIAL_KEX
295          * - dh_handshake_state == DH_STATE_INIT
296          *   or dh_handshake_state == DH_STATE_INIT_SENT (re-exchange)
297          *   or dh_handshake_state == DH_STATE_FINISHED (re-exchange)
298          *
299          * Transitions:
300          * - session->dh_handshake_state = DH_STATE_INIT
301          * - session->session_state = SSH_SESSION_STATE_KEXINIT_RECEIVED
302          *
303          * On server:
304          * - session->session_state = SSH_SESSION_STATE_DH
305          * */
306 
307         if ((session->session_state != SSH_SESSION_STATE_AUTHENTICATED) &&
308             (session->session_state != SSH_SESSION_STATE_INITIAL_KEX))
309         {
310             rc = SSH_PACKET_DENIED;
311             break;
312         }
313 
314         if ((session->dh_handshake_state != DH_STATE_INIT) &&
315             (session->dh_handshake_state != DH_STATE_INIT_SENT) &&
316             (session->dh_handshake_state != DH_STATE_FINISHED))
317         {
318             rc = SSH_PACKET_DENIED;
319             break;
320         }
321 
322         rc = SSH_PACKET_ALLOWED;
323         break;
324     case SSH2_MSG_NEWKEYS:                            // 21
325         /*
326          * States required:
327          * - session_state == SSH_SESSION_STATE_DH
328          * - dh_handshake_state == DH_STATE_NEWKEYS_SENT
329          *
330          * Transitions:
331          * - session->dh_handshake_state = DH_STATE_FINISHED
332          * - session->session_state = SSH_SESSION_STATE_AUTHENTICATING
333          * if session->flags & SSH_SESSION_FLAG_AUTHENTICATED
334          * - session->session_state = SSH_SESSION_STATE_AUTHENTICATED
335          * */
336 
337         /* If DH has not been started, reject message */
338         if (session->session_state != SSH_SESSION_STATE_DH) {
339             rc = SSH_PACKET_DENIED;
340             break;
341         }
342 
343         /* Only allowed if dh_handshake_state is in NEWKEYS_SENT state */
344         if (session->dh_handshake_state != DH_STATE_NEWKEYS_SENT) {
345             rc = SSH_PACKET_DENIED;
346             break;
347         }
348 
349         rc = SSH_PACKET_ALLOWED;
350         break;
351     case SSH2_MSG_KEXDH_INIT:                         // 30
352       // SSH2_MSG_KEX_ECDH_INIT:                      // 30
353       // SSH2_MSG_ECMQV_INIT:                         // 30
354       // SSH2_MSG_KEX_DH_GEX_REQUEST_OLD:             // 30
355 
356         /* Server only */
357 
358         /*
359          * States required:
360          * - session_state == SSH_SESSION_STATE_DH
361          * - dh_handshake_state == DH_STATE_INIT
362          *
363          * Transitions:
364          * - session->dh_handshake_state = DH_STATE_INIT_SENT
365          * then calls dh_handshake_server which triggers:
366          * - session->dh_handhsake_state = DH_STATE_NEWKEYS_SENT
367          * */
368 
369         if (session->session_state != SSH_SESSION_STATE_DH) {
370             rc = SSH_PACKET_DENIED;
371             break;
372         }
373 
374         /* Only allowed if dh_handshake_state is in initial state */
375         if (session->dh_handshake_state != DH_STATE_INIT) {
376             rc = SSH_PACKET_DENIED;
377             break;
378         }
379 
380         rc = SSH_PACKET_ALLOWED;
381         break;
382     case SSH2_MSG_KEXDH_REPLY:                        // 31
383       // SSH2_MSG_KEX_ECDH_REPLY:                     // 31
384       // SSH2_MSG_ECMQV_REPLY:                        // 31
385       // SSH2_MSG_KEX_DH_GEX_GROUP:                   // 31
386 
387         /*
388          * States required:
389          * - session_state == SSH_SESSION_STATE_DH
390          * - dh_handshake_state == DH_STATE_INIT_SENT
391          *   or dh_handshake_state == DH_STATE_REQUEST_SENT (dh-gex)
392          *
393          * Transitions:
394          * - session->dh_handhsake_state = DH_STATE_NEWKEYS_SENT
395          * */
396 
397         if (session->session_state != SSH_SESSION_STATE_DH) {
398             rc = SSH_PACKET_DENIED;
399             break;
400         }
401 
402         if (session->dh_handshake_state != DH_STATE_INIT_SENT &&
403             session->dh_handshake_state != DH_STATE_REQUEST_SENT) {
404             rc = SSH_PACKET_DENIED;
405             break;
406         }
407 
408         rc = SSH_PACKET_ALLOWED;
409         break;
410     case SSH2_MSG_KEX_DH_GEX_INIT:                    // 32
411         /* TODO Not filtered */
412         rc = SSH_PACKET_ALLOWED;
413         break;
414     case SSH2_MSG_KEX_DH_GEX_REPLY:                   // 33
415         /* TODO Not filtered */
416         rc = SSH_PACKET_ALLOWED;
417         break;
418     case SSH2_MSG_KEX_DH_GEX_REQUEST:                 // 34
419         /* TODO Not filtered */
420         rc = SSH_PACKET_ALLOWED;
421         break;
422     case SSH2_MSG_USERAUTH_REQUEST:                   // 50
423         /* Server only */
424 
425         /*
426          * States required:
427          * - session_state == SSH_SESSION_STATE_AUTHENTICATING
428          * - dh_hanshake_state == DH_STATE_FINISHED
429          *
430          * Transitions:
431          * - if authentication was successful:
432          *   - session_state = SSH_SESSION_STATE_AUTHENTICATED
433          * */
434 
435         /* If this is a client, reject the message */
436         if (session->client) {
437             rc = SSH_PACKET_DENIED;
438             break;
439         }
440 
441         if (session->dh_handshake_state != DH_STATE_FINISHED) {
442             rc = SSH_PACKET_DENIED;
443             break;
444         }
445 
446         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATING) {
447             rc = SSH_PACKET_DENIED;
448             break;
449         }
450 
451         rc = SSH_PACKET_ALLOWED;
452         break;
453     case SSH2_MSG_USERAUTH_FAILURE:                   // 51
454         /*
455          * States required:
456          * - session_state == SSH_SESSION_STATE_AUTHENTICATING
457          * - dh_hanshake_state == DH_STATE_FINISHED
458          * - session->auth.state == SSH_AUTH_STATE_KBDINT_SENT
459          *   or session->auth.state == SSH_AUTH_STATE_PUBKEY_OFFER_SENT
460          *   or session->auth.state == SSH_AUTH_STATE_PUBKEY_AUTH_SENT
461          *   or session->auth.state == SSH_AUTH_STATE_PASSWORD_AUTH_SENT
462          *   or session->auth.state == SSH_AUTH_STATE_GSSAPI_MIC_SENT
463          *
464          * Transitions:
465          * - if unpacking failed:
466          *   - session->auth.state = SSH_AUTH_ERROR
467          * - if failure was partial:
468          *   - session->auth.state = SSH_AUTH_PARTIAL
469          * - else:
470          *   - session->auth.state = SSH_AUTH_STATE_FAILED
471          * */
472 
473         /* If this is a server, reject the message */
474         if (session->server) {
475             rc = SSH_PACKET_DENIED;
476             break;
477         }
478 
479         if (session->dh_handshake_state != DH_STATE_FINISHED) {
480             rc = SSH_PACKET_DENIED;
481             break;
482         }
483 
484         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATING) {
485             rc = SSH_PACKET_DENIED;
486             break;
487         }
488 
489         rc = SSH_PACKET_ALLOWED;
490         break;
491     case SSH2_MSG_USERAUTH_SUCCESS:                   // 52
492         /*
493          * States required:
494          * - session_state == SSH_SESSION_STATE_AUTHENTICATING
495          * - dh_hanshake_state == DH_STATE_FINISHED
496          * - session->auth.state == SSH_AUTH_STATE_KBDINT_SENT
497          *   or session->auth.state == SSH_AUTH_STATE_PUBKEY_AUTH_SENT
498          *   or session->auth.state == SSH_AUTH_STATE_PASSWORD_AUTH_SENT
499          *   or session->auth.state == SSH_AUTH_STATE_GSSAPI_MIC_SENT
500          *   or session->auth.state == SSH_AUTH_STATE_AUTH_NONE_SENT
501          *
502          * Transitions:
503          * - session->auth.state = SSH_AUTH_STATE_SUCCESS
504          * - session->session_state = SSH_SESSION_STATE_AUTHENTICATED
505          * - session->flags |= SSH_SESSION_FLAG_AUTHENTICATED
506          * - sessions->auth.current_method = SSH_AUTH_METHOD_UNKNOWN
507          * */
508 
509         /* If this is a server, reject the message */
510         if (session->server) {
511             rc = SSH_PACKET_DENIED;
512             break;
513         }
514 
515         if (session->dh_handshake_state != DH_STATE_FINISHED) {
516             rc = SSH_PACKET_DENIED;
517             break;
518         }
519 
520         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATING) {
521             rc = SSH_PACKET_DENIED;
522             break;
523         }
524 
525         if ((session->auth.state != SSH_AUTH_STATE_KBDINT_SENT) &&
526             (session->auth.state != SSH_AUTH_STATE_PUBKEY_AUTH_SENT) &&
527             (session->auth.state != SSH_AUTH_STATE_PASSWORD_AUTH_SENT) &&
528             (session->auth.state != SSH_AUTH_STATE_GSSAPI_MIC_SENT) &&
529             (session->auth.state != SSH_AUTH_STATE_AUTH_NONE_SENT))
530         {
531             rc = SSH_PACKET_DENIED;
532             break;
533         }
534 
535         rc = SSH_PACKET_ALLOWED;
536         break;
537     case SSH2_MSG_USERAUTH_BANNER:                    // 53
538         /*
539          * States required:
540          * - session_state == SSH_SESSION_STATE_AUTHENTICATING
541          *
542          * Transitions:
543          * - None
544          * */
545 
546         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATING) {
547             rc = SSH_PACKET_DENIED;
548             break;
549         }
550 
551         rc = SSH_PACKET_ALLOWED;
552         break;
553     case SSH2_MSG_USERAUTH_PK_OK:                     // 60
554       // SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ:          // 60
555       // SSH2_MSG_USERAUTH_INFO_REQUEST:              // 60
556       // SSH2_MSG_USERAUTH_GSSAPI_RESPONSE:           // 60
557 
558         /*
559          * States required:
560          * - session_state == SSH_SESSION_STATE_AUTHENTICATING
561          * - session->auth.state == SSH_AUTH_STATE_KBDINT_SENT
562          *   or
563          *   session->auth.state == SSH_AUTH_STATE_GSSAPI_REQUEST_SENT
564          *   or
565          *   session->auth.state == SSH_AUTH_STATE_PUBKEY_OFFER_SENT
566          *
567          * Transitions:
568          * Depending on the current state, the message is treated
569          * differently:
570          * - session->auth.state == SSH_AUTH_STATE_KBDINT_SENT
571          *   - session->auth.state = SSH_AUTH_STATE_INFO
572          * - session->auth.state == SSH_AUTH_STATE_GSSAPI_REQUEST_SENT
573          *   - session->auth.state = SSH_AUTH_STATE_GSSAPI_TOKEN
574          * - session->auth.state == SSH_AUTH_STATE_PUBKEY_OFFER_SENT
575          *   - session->auth.state = SSH_AUTH_STATE_PK_OK
576          * */
577 
578         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATING) {
579             rc = SSH_PACKET_DENIED;
580             break;
581         }
582 
583         if ((session->auth.state != SSH_AUTH_STATE_KBDINT_SENT) &&
584             (session->auth.state != SSH_AUTH_STATE_PUBKEY_OFFER_SENT) &&
585             (session->auth.state != SSH_AUTH_STATE_GSSAPI_REQUEST_SENT))
586         {
587             rc = SSH_PACKET_DENIED;
588             break;
589         }
590 
591         rc = SSH_PACKET_ALLOWED;
592         break;
593     case SSH2_MSG_USERAUTH_INFO_RESPONSE:             // 61
594       // SSH2_MSG_USERAUTH_GSSAPI_TOKEN:              // 61
595 
596         /*
597          * States required:
598          * - session_state == SSH_SESSION_STATE_AUTHENTICATING
599          * - session_state->auth.state == SSH_SESSION_STATE_GSSAPI_TOKEN
600          *   or
601          *   session_state->auth.state == SSH_SESSION_STATE_INFO
602          *
603          * Transitions:
604          * - None
605          * */
606 
607         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATING) {
608             rc = SSH_PACKET_DENIED;
609             break;
610         }
611 
612         if ((session->auth.state != SSH_AUTH_STATE_INFO) &&
613             (session->auth.state != SSH_AUTH_STATE_GSSAPI_TOKEN))
614         {
615             rc = SSH_PACKET_DENIED;
616             break;
617         }
618 
619         rc = SSH_PACKET_ALLOWED;
620         break;
621     case SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE:  // 63
622         /* TODO Not filtered */
623         rc = SSH_PACKET_ALLOWED;
624         break;
625     case SSH2_MSG_USERAUTH_GSSAPI_ERROR:              // 64
626         /* TODO Not filtered */
627         rc = SSH_PACKET_ALLOWED;
628         break;
629     case SSH2_MSG_USERAUTH_GSSAPI_ERRTOK:             // 65
630         /* TODO Not filtered */
631         rc = SSH_PACKET_ALLOWED;
632         break;
633     case SSH2_MSG_USERAUTH_GSSAPI_MIC:                // 66
634         /* Server only */
635 
636         /*
637          * States required:
638          * - session_state == SSH_SESSION_STATE_AUTHENTICATING
639          * - session->gssapi->state == SSH_GSSAPI_STATE_RCV_MIC
640          *
641          * Transitions:
642          * Depending on the result of the verification, the states are
643          * changed:
644          * - SSH_AUTH_SUCCESS:
645          *   - session->session_state = SSH_SESSION_STATE_AUTHENTICATED
646          *   - session->flags != SSH_SESSION_FLAG_AUTHENTICATED
647          * - SSH_AUTH_PARTIAL:
648          *   - None
649          * - any other case:
650          *   - None
651          * */
652 
653         /* If this is a client, reject the message */
654         if (session->client) {
655             rc = SSH_PACKET_DENIED;
656             break;
657         }
658 
659         if (session->dh_handshake_state != DH_STATE_FINISHED) {
660             rc = SSH_PACKET_DENIED;
661             break;
662         }
663 
664         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATING) {
665             rc = SSH_PACKET_DENIED;
666             break;
667         }
668 
669         rc = SSH_PACKET_ALLOWED;
670         break;
671     case SSH2_MSG_GLOBAL_REQUEST:                     // 80
672         /*
673          * States required:
674          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
675          *
676          * Transitions:
677          * - None
678          * */
679 
680         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
681             rc = SSH_PACKET_DENIED;
682             break;
683         }
684 
685         rc = SSH_PACKET_ALLOWED;
686         break;
687     case SSH2_MSG_REQUEST_SUCCESS:                    // 81
688         /*
689          * States required:
690          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
691          *
692          * Transitions:
693          * - From channel->request_state == SSH_CHANNEL_REQ_STATE_PENDING
694          * - To   channel->request_state = SSH_CHANNEL_REQ_STATE_ACCEPTED
695          *
696          * If not in a pending state, message is ignored in the callback handler.
697          * */
698 
699         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
700             rc = SSH_PACKET_DENIED;
701             break;
702         }
703 
704         rc = SSH_PACKET_ALLOWED;
705         break;
706     case SSH2_MSG_REQUEST_FAILURE:                    // 82
707         /*
708          * States required:
709          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
710          *
711          * Transitions:
712          * - From channel->request_state == SSH_CHANNEL_REQ_STATE_PENDING
713          * - To   channel->request_state = SSH_CHANNEL_REQ_STATE_ACCEPTED
714          *
715          * If not in a pending state, message is ignored in the callback handler.
716          * */
717 
718         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
719             rc = SSH_PACKET_DENIED;
720             break;
721         }
722 
723         rc = SSH_PACKET_ALLOWED;
724         break;
725     case SSH2_MSG_CHANNEL_OPEN:                       // 90
726         /*
727          * States required:
728          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
729          *
730          * Transitions:
731          * - None
732          * */
733 
734         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
735             rc = SSH_PACKET_DENIED;
736             break;
737         }
738 
739         rc = SSH_PACKET_ALLOWED;
740         break;
741     case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:          // 91
742         /*
743          * States required:
744          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
745          *
746          * Transitions:
747          * - channel->state = SSH_CHANNEL_STATE_OPEN
748          * - channel->flags &= ~SSH_CHANNEL_FLAG_NOT_BOUND
749          * */
750 
751         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
752             rc = SSH_PACKET_DENIED;
753             break;
754         }
755 
756         rc = SSH_PACKET_ALLOWED;
757         break;
758     case SSH2_MSG_CHANNEL_OPEN_FAILURE:               // 92
759         /*
760          * States required:
761          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
762          *
763          * Transitions:
764          * - channel->state = SSH_CHANNEL_STATE_OPEN_DENIED
765          * */
766 
767         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
768             rc = SSH_PACKET_DENIED;
769             break;
770         }
771 
772         rc = SSH_PACKET_ALLOWED;
773         break;
774     case SSH2_MSG_CHANNEL_WINDOW_ADJUST:              // 93
775         /*
776          * States required:
777          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
778          *
779          * Transitions:
780          * - None
781          * */
782 
783         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
784             rc = SSH_PACKET_DENIED;
785             break;
786         }
787 
788         rc = SSH_PACKET_ALLOWED;
789         break;
790     case SSH2_MSG_CHANNEL_DATA:                       // 94
791         /*
792          * States required:
793          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
794          *
795          * Transitions:
796          * - None
797          * */
798 
799         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
800             rc = SSH_PACKET_DENIED;
801             break;
802         }
803 
804         rc = SSH_PACKET_ALLOWED;
805         break;
806     case SSH2_MSG_CHANNEL_EXTENDED_DATA:              // 95
807         /*
808          * States required:
809          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
810          *
811          * Transitions:
812          * - None
813          * */
814 
815         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
816             rc = SSH_PACKET_DENIED;
817             break;
818         }
819 
820         rc = SSH_PACKET_ALLOWED;
821         break;
822     case SSH2_MSG_CHANNEL_EOF:                        // 96
823         /*
824          * States required:
825          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
826          *
827          * Transitions:
828          * - None
829          * */
830 
831         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
832             rc = SSH_PACKET_DENIED;
833             break;
834         }
835 
836         rc = SSH_PACKET_ALLOWED;
837         break;
838     case SSH2_MSG_CHANNEL_CLOSE:                      // 97
839         /*
840          * States required:
841          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
842          *
843          * Transitions:
844          * - channel->state = SSH_CHANNEL_STATE_CLOSED
845          * - channel->flags |= SSH_CHANNEL_FLAG_CLOSED_REMOTE
846          * */
847 
848         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
849             rc = SSH_PACKET_DENIED;
850             break;
851         }
852 
853         rc = SSH_PACKET_ALLOWED;
854         break;
855     case SSH2_MSG_CHANNEL_REQUEST:                    // 98
856         /*
857          * States required:
858          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
859          *
860          * Transitions:
861          * - Depends on the request
862          * */
863 
864         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
865             rc = SSH_PACKET_DENIED;
866             break;
867         }
868 
869         rc = SSH_PACKET_ALLOWED;
870         break;
871     case SSH2_MSG_CHANNEL_SUCCESS:                    // 99
872         /*
873          * States required:
874          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
875          *
876          * Transitions:
877          * - From channel->request_state == SSH_CHANNEL_REQ_STATE_PENDING
878          * - To   channel->request_state = SSH_CHANNEL_REQ_STATE_ACCEPTED
879          *
880          * If not in a pending state, message is ignored in the callback handler.
881          * */
882 
883         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
884             rc = SSH_PACKET_DENIED;
885             break;
886         }
887 
888         rc = SSH_PACKET_ALLOWED;
889         break;
890     case SSH2_MSG_CHANNEL_FAILURE:                    // 100
891         /*
892          * States required:
893          * - session_state == SSH_SESSION_STATE_AUTHENTICATED
894          *
895          * Transitions:
896          * - From channel->request_state == SSH_CHANNEL_REQ_STATE_PENDING
897          * - To   channel->request_state = SSH_CHANNEL_REQ_STATE_ACCEPTED
898          *
899          * If not in a pending state, message is ignored in the callback handler.
900          * */
901 
902         if (session->session_state != SSH_SESSION_STATE_AUTHENTICATED) {
903             rc = SSH_PACKET_DENIED;
904             break;
905         }
906 
907         rc = SSH_PACKET_ALLOWED;
908         break;
909     default:
910         /* Unknown message, do not filter */
911         rc = SSH_PACKET_UNKNOWN;
912         goto end;
913     }
914 
915 end:
916 #ifdef DEBUG_PACKET
917     if (rc == SSH_PACKET_DENIED) {
918         SSH_LOG(SSH_LOG_PACKET, "REJECTED packet type %d: ",
919                 session->in_packet.type);
920     }
921 
922     if (rc == SSH_PACKET_UNKNOWN) {
923         SSH_LOG(SSH_LOG_PACKET, "UNKNOWN packet type %d",
924                 session->in_packet.type);
925     }
926 #endif
927 
928     return rc;
929 }
930 
931 /* Returns current_crypto structure from the session.
932  * During key exchange (or rekey), after one of the sides
933  * sending NEWKEYS packet, this might return next_crypto for one
934  * of the directions that is ahead to send already queued packets
935  */
936 struct ssh_crypto_struct *
ssh_packet_get_current_crypto(ssh_session session,enum ssh_crypto_direction_e direction)937 ssh_packet_get_current_crypto(ssh_session session,
938                               enum ssh_crypto_direction_e direction)
939 {
940     struct ssh_crypto_struct *crypto = NULL;
941 
942     if (session == NULL) {
943         return NULL;
944     }
945 
946     if (session->current_crypto != NULL &&
947         session->current_crypto->used & direction) {
948         crypto = session->current_crypto;
949     } else if (session->next_crypto != NULL &&
950                session->next_crypto->used & direction) {
951         crypto = session->next_crypto;
952     } else {
953         return NULL;
954     }
955 
956     switch (direction) {
957     case SSH_DIRECTION_IN:
958         if (crypto->in_cipher != NULL) {
959             return crypto;
960         }
961         break;
962     case SSH_DIRECTION_OUT:
963         if (crypto->out_cipher != NULL) {
964             return crypto;
965         }
966         break;
967     case SSH_DIRECTION_BOTH:
968         if (crypto->in_cipher != NULL &&
969             crypto->out_cipher != NULL) {
970             return crypto;
971         }
972     }
973 
974     return NULL;
975 }
976 
977 #define MAX_PACKETS    (1UL<<31)
978 
ssh_packet_need_rekey(ssh_session session,const uint32_t payloadsize)979 static bool ssh_packet_need_rekey(ssh_session session,
980                                   const uint32_t payloadsize)
981 {
982     bool data_rekey_needed = false;
983     struct ssh_crypto_struct *crypto = NULL;
984     struct ssh_cipher_struct *out_cipher = NULL, *in_cipher = NULL;
985     uint32_t next_blocks;
986 
987     /* We can safely rekey only in authenticated state */
988     if ((session->flags & SSH_SESSION_FLAG_AUTHENTICATED) == 0) {
989         return false;
990     }
991 
992     /* Do not rekey if the rekey/key-exchange is in progress */
993     if (session->dh_handshake_state != DH_STATE_FINISHED) {
994         return false;
995     }
996 
997     crypto = ssh_packet_get_current_crypto(session, SSH_DIRECTION_BOTH);
998     if (crypto == NULL) {
999         return false;
1000     }
1001 
1002     out_cipher = crypto->out_cipher;
1003     in_cipher = crypto->in_cipher;
1004 
1005     /* Make sure we can send at least something for very small limits */
1006     if ((out_cipher->packets == 0) && (in_cipher->packets == 0)) {
1007         return false;
1008     }
1009 
1010     /* Time based rekeying */
1011     if (session->opts.rekey_time != 0 &&
1012         ssh_timeout_elapsed(&session->last_rekey_time,
1013                             session->opts.rekey_time)) {
1014         return true;
1015     }
1016 
1017     /* RFC4344, Section 3.1 Recommends rekeying after 2^31 packets in either
1018      * direction to avoid possible information leakage through the MAC tag
1019      */
1020     if (out_cipher->packets > MAX_PACKETS ||
1021         in_cipher->packets > MAX_PACKETS) {
1022         return true;
1023     }
1024 
1025     /* Data-based rekeying:
1026      *  * For outgoing packets we can still delay them
1027      *  * Incoming packets need to be processed anyway, but we can
1028      *    signalize our intention to rekey
1029      */
1030     next_blocks = payloadsize / out_cipher->blocksize;
1031     data_rekey_needed = (out_cipher->max_blocks != 0 &&
1032                          out_cipher->blocks + next_blocks > out_cipher->max_blocks) ||
1033                          (in_cipher->max_blocks != 0 &&
1034                          in_cipher->blocks + next_blocks > in_cipher->max_blocks);
1035 
1036     SSH_LOG(SSH_LOG_PACKET,
1037             "packet: [data_rekey_needed=%d, out_blocks=%" PRIu64 ", in_blocks=%" PRIu64,
1038             data_rekey_needed,
1039             out_cipher->blocks + next_blocks,
1040             in_cipher->blocks + next_blocks);
1041 
1042     return data_rekey_needed;
1043 }
1044 
1045 /* in nonblocking mode, socket_read will read as much as it can, and return */
1046 /* SSH_OK if it has read at least len bytes, otherwise, SSH_AGAIN. */
1047 /* in blocking mode, it will read at least len bytes and will block until it's ok. */
1048 
1049 /** @internal
1050  * @handles a data received event. It then calls the handlers for the different packet types
1051  * or and exception handler callback.
1052  * @param user pointer to current ssh_session
1053  * @param data pointer to the data received
1054  * @len length of data received. It might not be enough for a complete packet
1055  * @returns number of bytes read and processed.
1056  */
ssh_packet_socket_callback(const void * data,size_t receivedlen,void * user)1057 int ssh_packet_socket_callback(const void *data, size_t receivedlen, void *user)
1058 {
1059     ssh_session session = (ssh_session)user;
1060     uint32_t blocksize = 8;
1061     uint32_t lenfield_blocksize = 8;
1062     size_t current_macsize = 0;
1063     uint8_t *ptr = NULL;
1064     int to_be_read;
1065     int rc;
1066     uint8_t *cleartext_packet = NULL;
1067     uint8_t *packet_second_block = NULL;
1068     uint8_t *mac = NULL;
1069     size_t packet_remaining;
1070     uint32_t packet_len, compsize, payloadsize;
1071     uint8_t padding;
1072     size_t processed = 0; /* number of byte processed from the callback */
1073     enum ssh_packet_filter_result_e filter_result;
1074     struct ssh_crypto_struct *crypto = NULL;
1075     bool etm = false;
1076     uint32_t etm_packet_offset = 0;
1077     bool ok;
1078 
1079     crypto = ssh_packet_get_current_crypto(session, SSH_DIRECTION_IN);
1080     if (crypto != NULL) {
1081         current_macsize = hmac_digest_len(crypto->in_hmac);
1082         blocksize = crypto->in_cipher->blocksize;
1083         lenfield_blocksize = crypto->in_cipher->lenfield_blocksize;
1084         etm = crypto->in_hmac_etm;
1085     }
1086 
1087     if (etm) {
1088         /* In EtM mode packet size is unencrypted. This means
1089          * we need to use this offset and set the block size
1090          * that is part of the encrypted part to 0.
1091          */
1092         etm_packet_offset = sizeof(uint32_t);
1093         lenfield_blocksize = 0;
1094     } else if (lenfield_blocksize == 0) {
1095         lenfield_blocksize = blocksize;
1096     }
1097     if (data == NULL) {
1098         goto error;
1099     }
1100 
1101     if (session->session_state == SSH_SESSION_STATE_ERROR) {
1102         goto error;
1103     }
1104 #ifdef DEBUG_PACKET
1105     SSH_LOG(SSH_LOG_PACKET,
1106             "rcv packet cb (len=%zu, state=%s)",
1107             receivedlen,
1108             session->packet_state == PACKET_STATE_INIT ?
1109                 "INIT" :
1110                 session->packet_state == PACKET_STATE_SIZEREAD ?
1111                     "SIZE_READ" :
1112                     session->packet_state == PACKET_STATE_PROCESSING ?
1113                     "PROCESSING" : "unknown");
1114 #endif
1115     switch(session->packet_state) {
1116         case PACKET_STATE_INIT:
1117             if (receivedlen < lenfield_blocksize + etm_packet_offset) {
1118                 /*
1119                  * We didn't receive enough data to read either at least one
1120                  * block size or the unencrypted length in EtM mode.
1121                  */
1122 #ifdef DEBUG_PACKET
1123                 SSH_LOG(SSH_LOG_PACKET,
1124                         "Waiting for more data (%zu < %u)",
1125                         receivedlen,
1126                         lenfield_blocksize);
1127 #endif
1128                 return 0;
1129             }
1130 
1131             session->in_packet = (struct packet_struct) {
1132                 .type = 0,
1133             };
1134 
1135             if (session->in_buffer) {
1136                 rc = ssh_buffer_reinit(session->in_buffer);
1137                 if (rc < 0) {
1138                     goto error;
1139                 }
1140             } else {
1141                 session->in_buffer = ssh_buffer_new();
1142                 if (session->in_buffer == NULL) {
1143                     goto error;
1144                 }
1145             }
1146 
1147             if (!etm) {
1148                 ptr = ssh_buffer_allocate(session->in_buffer, lenfield_blocksize);
1149                 if (ptr == NULL) {
1150                     goto error;
1151                 }
1152                 packet_len = ssh_packet_decrypt_len(session, ptr, (uint8_t *)data);
1153                 to_be_read = packet_len - lenfield_blocksize + sizeof(uint32_t);
1154             } else {
1155                 /* Length is unencrypted in case of Encrypt-then-MAC */
1156                 packet_len = PULL_BE_U32(data, 0);
1157                 to_be_read = packet_len - etm_packet_offset;
1158             }
1159 
1160             processed += lenfield_blocksize + etm_packet_offset;
1161             if (packet_len > MAX_PACKET_LEN) {
1162                 ssh_set_error(session,
1163                               SSH_FATAL,
1164                               "read_packet(): Packet len too high(%u %.4x)",
1165                               packet_len, packet_len);
1166                 goto error;
1167             }
1168             if (to_be_read < 0) {
1169                 /* remote sshd sends invalid sizes? */
1170                 ssh_set_error(session,
1171                               SSH_FATAL,
1172                               "Given numbers of bytes left to be read < 0 (%d)!",
1173                               to_be_read);
1174                 goto error;
1175             }
1176 
1177             session->in_packet.len = packet_len;
1178             session->packet_state = PACKET_STATE_SIZEREAD;
1179             FALL_THROUGH;
1180         case PACKET_STATE_SIZEREAD:
1181             packet_len = session->in_packet.len;
1182             processed = lenfield_blocksize + etm_packet_offset;
1183             to_be_read = packet_len + sizeof(uint32_t) + current_macsize;
1184             /* if to_be_read is zero, the whole packet was blocksize bytes. */
1185             if (to_be_read != 0) {
1186                 if (receivedlen  < (unsigned int)to_be_read) {
1187                     /* give up, not enough data in buffer */
1188                     SSH_LOG(SSH_LOG_PACKET,
1189                             "packet: partial packet (read len) "
1190                             "[len=%d, receivedlen=%d, to_be_read=%d]",
1191                             packet_len,
1192                             (int)receivedlen,
1193                             to_be_read);
1194                     return 0;
1195                 }
1196 
1197                 packet_second_block = (uint8_t*)data + lenfield_blocksize + etm_packet_offset;
1198                 processed = to_be_read - current_macsize;
1199             }
1200 
1201             /* remaining encrypted bytes from the packet, MAC not included */
1202             packet_remaining =
1203                 packet_len - (lenfield_blocksize - sizeof(uint32_t) + etm_packet_offset);
1204             cleartext_packet = ssh_buffer_allocate(session->in_buffer,
1205                                                    packet_remaining);
1206             if (cleartext_packet == NULL) {
1207                 goto error;
1208             }
1209 
1210             if (packet_second_block != NULL) {
1211                 if (crypto != NULL) {
1212                     mac = packet_second_block + packet_remaining;
1213 
1214                     if (etm) {
1215                         rc = ssh_packet_hmac_verify(session,
1216                                                     data,
1217                                                     processed,
1218                                                     mac,
1219                                                     crypto->in_hmac);
1220                         if (rc < 0) {
1221                             ssh_set_error(session, SSH_FATAL, "HMAC error");
1222                             goto error;
1223                         }
1224                     }
1225                     /*
1226                      * Decrypt the packet. In case of EtM mode, the length is already
1227                      * known as it's unencrypted. In the other case, lenfield_blocksize bytes
1228                      * already have been decrypted.
1229                      */
1230                     if (packet_remaining > 0) {
1231                         rc = ssh_packet_decrypt(session,
1232                                                 cleartext_packet,
1233                                                 (uint8_t *)data,
1234                                                 lenfield_blocksize + etm_packet_offset,
1235                                                 processed - (lenfield_blocksize + etm_packet_offset));
1236                         if (rc < 0) {
1237                             ssh_set_error(session,
1238                                           SSH_FATAL,
1239                                           "Decryption error");
1240                             goto error;
1241                         }
1242                     }
1243 
1244                     if (!etm) {
1245                         rc = ssh_packet_hmac_verify(session,
1246                                                     ssh_buffer_get(session->in_buffer),
1247                                                     ssh_buffer_get_len(session->in_buffer),
1248                                                     mac,
1249                                                     crypto->in_hmac);
1250                         if (rc < 0) {
1251                             ssh_set_error(session, SSH_FATAL, "HMAC error");
1252                             goto error;
1253                         }
1254                     }
1255                     processed += current_macsize;
1256                 } else {
1257                     memcpy(cleartext_packet,
1258                            packet_second_block,
1259                            packet_remaining);
1260                 }
1261             }
1262 
1263 #ifdef WITH_PCAP
1264             if (session->pcap_ctx != NULL) {
1265                 ssh_pcap_context_write(session->pcap_ctx,
1266                                        SSH_PCAP_DIR_IN,
1267                                        ssh_buffer_get(session->in_buffer),
1268                                        ssh_buffer_get_len(session->in_buffer),
1269                                        ssh_buffer_get_len(session->in_buffer));
1270             }
1271 #endif
1272 
1273             if (!etm) {
1274                 /* skip the size field which has been processed before */
1275                 ssh_buffer_pass_bytes(session->in_buffer, sizeof(uint32_t));
1276             }
1277 
1278             rc = ssh_buffer_get_u8(session->in_buffer, &padding);
1279             if (rc == 0) {
1280                 ssh_set_error(session,
1281                               SSH_FATAL,
1282                               "Packet too short to read padding");
1283                 goto error;
1284             }
1285 
1286             if (padding > ssh_buffer_get_len(session->in_buffer)) {
1287                 ssh_set_error(session,
1288                               SSH_FATAL,
1289                               "Invalid padding: %d (%d left)",
1290                               padding,
1291                               ssh_buffer_get_len(session->in_buffer));
1292                 goto error;
1293             }
1294             ssh_buffer_pass_bytes_end(session->in_buffer, padding);
1295             compsize = ssh_buffer_get_len(session->in_buffer);
1296 
1297 #ifdef WITH_ZLIB
1298             if (crypto && crypto->do_compress_in
1299                 && ssh_buffer_get_len(session->in_buffer) > 0) {
1300                 rc = decompress_buffer(session, session->in_buffer,MAX_PACKET_LEN);
1301                 if (rc < 0) {
1302                     goto error;
1303                 }
1304             }
1305 #endif /* WITH_ZLIB */
1306             payloadsize = ssh_buffer_get_len(session->in_buffer);
1307             session->recv_seq++;
1308             if (crypto != NULL) {
1309                 struct ssh_cipher_struct *cipher = NULL;
1310 
1311                 cipher = crypto->in_cipher;
1312                 cipher->packets++;
1313                 cipher->blocks += payloadsize / cipher->blocksize;
1314             }
1315             if (session->raw_counter != NULL) {
1316                 session->raw_counter->in_bytes += payloadsize;
1317                 session->raw_counter->in_packets++;
1318             }
1319 
1320             /*
1321              * We don't want to rewrite a new packet while still executing the
1322              * packet callbacks
1323              */
1324             session->packet_state = PACKET_STATE_PROCESSING;
1325             ssh_packet_parse_type(session);
1326             SSH_LOG(SSH_LOG_PACKET,
1327                     "packet: read type %hhd [len=%d,padding=%hhd,comp=%d,payload=%d]",
1328                     session->in_packet.type, packet_len, padding, compsize, payloadsize);
1329 
1330             /* Check if the packet is expected */
1331             filter_result = ssh_packet_incoming_filter(session);
1332 
1333             switch(filter_result) {
1334             case SSH_PACKET_ALLOWED:
1335                 /* Execute callbacks */
1336                 ssh_packet_process(session, session->in_packet.type);
1337                 break;
1338             case SSH_PACKET_DENIED:
1339                 ssh_set_error(session,
1340                               SSH_FATAL,
1341                               "Packet filter: rejected packet (type %d)",
1342                               session->in_packet.type);
1343                 goto error;
1344             case SSH_PACKET_UNKNOWN:
1345                 ssh_packet_send_unimplemented(session, session->recv_seq - 1);
1346                 break;
1347             }
1348 
1349             session->packet_state = PACKET_STATE_INIT;
1350             if (processed < receivedlen) {
1351                 /* Handle a potential packet left in socket buffer */
1352                 SSH_LOG(SSH_LOG_PACKET,
1353                         "Processing %" PRIdS " bytes left in socket buffer",
1354                         receivedlen-processed);
1355 
1356                 ptr = ((uint8_t*)data) + processed;
1357 
1358                 rc = ssh_packet_socket_callback(ptr, receivedlen - processed,user);
1359                 processed += rc;
1360             }
1361 
1362             ok = ssh_packet_need_rekey(session, 0);
1363             if (ok) {
1364                 SSH_LOG(SSH_LOG_PACKET, "Incoming packet triggered rekey");
1365                 rc = ssh_send_rekex(session);
1366                 if (rc != SSH_OK) {
1367                     SSH_LOG(SSH_LOG_PACKET, "Rekey failed: rc = %d", rc);
1368                     return rc;
1369                 }
1370             }
1371 
1372             return processed;
1373         case PACKET_STATE_PROCESSING:
1374             SSH_LOG(SSH_LOG_PACKET, "Nested packet processing. Delaying.");
1375             return 0;
1376     }
1377 
1378     ssh_set_error(session,
1379                   SSH_FATAL,
1380                   "Invalid state into packet_read2(): %d",
1381                   session->packet_state);
1382 
1383 error:
1384     session->session_state= SSH_SESSION_STATE_ERROR;
1385     SSH_LOG(SSH_LOG_PACKET,"Packet: processed %" PRIdS " bytes", processed);
1386     return processed;
1387 }
1388 
ssh_packet_socket_controlflow_callback(int code,void * userdata)1389 static void ssh_packet_socket_controlflow_callback(int code, void *userdata)
1390 {
1391     ssh_session session = userdata;
1392     struct ssh_iterator *it;
1393     ssh_channel channel;
1394 
1395     if (code == SSH_SOCKET_FLOW_WRITEWONTBLOCK) {
1396         SSH_LOG(SSH_LOG_TRACE, "sending channel_write_wontblock callback");
1397 
1398         /* the out pipe is empty so we can forward this to channels */
1399         it = ssh_list_get_iterator(session->channels);
1400         while (it != NULL) {
1401             channel = ssh_iterator_value(ssh_channel, it);
1402             ssh_callbacks_execute_list(channel->callbacks,
1403                                        ssh_channel_callbacks,
1404                                        channel_write_wontblock_function,
1405                                        session,
1406                                        channel,
1407                                        channel->remote_window);
1408             it = it->next;
1409         }
1410     }
1411 }
1412 
ssh_packet_register_socket_callback(ssh_session session,ssh_socket s)1413 void ssh_packet_register_socket_callback(ssh_session session, ssh_socket s){
1414 	session->socket_callbacks.data=ssh_packet_socket_callback;
1415 	session->socket_callbacks.connected=NULL;
1416     session->socket_callbacks.controlflow = ssh_packet_socket_controlflow_callback;
1417 	session->socket_callbacks.userdata=session;
1418 	ssh_socket_set_callbacks(s,&session->socket_callbacks);
1419 }
1420 
1421 /** @internal
1422  * @brief sets the callbacks for the packet layer
1423  */
ssh_packet_set_callbacks(ssh_session session,ssh_packet_callbacks callbacks)1424 void ssh_packet_set_callbacks(ssh_session session, ssh_packet_callbacks callbacks){
1425     if (session->packet_callbacks == NULL) {
1426         session->packet_callbacks = ssh_list_new();
1427         if (session->packet_callbacks == NULL) {
1428             ssh_set_error_oom(session);
1429             return;
1430         }
1431     }
1432     ssh_list_append(session->packet_callbacks, callbacks);
1433 }
1434 
1435 /** @internal
1436  * @brief remove the callbacks from the packet layer
1437  */
ssh_packet_remove_callbacks(ssh_session session,ssh_packet_callbacks callbacks)1438 void ssh_packet_remove_callbacks(ssh_session session, ssh_packet_callbacks callbacks){
1439     struct ssh_iterator *it = NULL;
1440     it = ssh_list_find(session->packet_callbacks, callbacks);
1441     if (it != NULL) {
1442         ssh_list_remove(session->packet_callbacks, it);
1443     }
1444 }
1445 
1446 /** @internal
1447  * @brief sets the default packet handlers
1448  */
ssh_packet_set_default_callbacks(ssh_session session)1449 void ssh_packet_set_default_callbacks(ssh_session session){
1450 	session->default_packet_callbacks.start=1;
1451 	session->default_packet_callbacks.n_callbacks=sizeof(default_packet_handlers)/sizeof(ssh_packet_callback);
1452 	session->default_packet_callbacks.user=session;
1453 	session->default_packet_callbacks.callbacks=default_packet_handlers;
1454 	ssh_packet_set_callbacks(session, &session->default_packet_callbacks);
1455 }
1456 
1457 /** @internal
1458  * @brief dispatch the call of packet handlers callbacks for a received packet
1459  * @param type type of packet
1460  */
ssh_packet_process(ssh_session session,uint8_t type)1461 void ssh_packet_process(ssh_session session, uint8_t type)
1462 {
1463     struct ssh_iterator *i = NULL;
1464     int rc = SSH_PACKET_NOT_USED;
1465     ssh_packet_callbacks cb;
1466 
1467     SSH_LOG(SSH_LOG_PACKET, "Dispatching handler for packet type %d", type);
1468     if (session->packet_callbacks == NULL) {
1469         SSH_LOG(SSH_LOG_RARE, "Packet callback is not initialized !");
1470         return;
1471     }
1472 
1473     i = ssh_list_get_iterator(session->packet_callbacks);
1474     while (i != NULL) {
1475         cb = ssh_iterator_value(ssh_packet_callbacks, i);
1476         i = i->next;
1477 
1478         if (!cb) {
1479             continue;
1480         }
1481 
1482         if (cb->start > type) {
1483             continue;
1484         }
1485 
1486         if (cb->start + cb->n_callbacks <= type) {
1487             continue;
1488         }
1489 
1490         if (cb->callbacks[type - cb->start] == NULL) {
1491             continue;
1492         }
1493 
1494         rc = cb->callbacks[type - cb->start](session, type, session->in_buffer,
1495                                              cb->user);
1496         if (rc == SSH_PACKET_USED) {
1497             break;
1498         }
1499     }
1500 
1501     if (rc == SSH_PACKET_NOT_USED) {
1502         SSH_LOG(SSH_LOG_RARE, "Couldn't do anything with packet type %d", type);
1503         rc = ssh_packet_send_unimplemented(session, session->recv_seq - 1);
1504         if (rc != SSH_OK) {
1505             SSH_LOG(SSH_LOG_RARE, "Failed to send unimplemented: %s",
1506                     ssh_get_error(session));
1507         }
1508     }
1509 }
1510 
1511 /** @internal
1512  * @brief sends a SSH_MSG_UNIMPLEMENTED answer to an unhandled packet
1513  * @param session the SSH session
1514  * @param seqnum the sequence number of the unknown packet
1515  * @return SSH_ERROR on error, else SSH_OK
1516  */
ssh_packet_send_unimplemented(ssh_session session,uint32_t seqnum)1517 int ssh_packet_send_unimplemented(ssh_session session, uint32_t seqnum){
1518     int rc;
1519 
1520     rc = ssh_buffer_pack(session->out_buffer,
1521                          "bd",
1522                          SSH2_MSG_UNIMPLEMENTED,
1523                          seqnum);
1524     if (rc != SSH_OK) {
1525         ssh_set_error_oom(session);
1526         return SSH_ERROR;
1527     }
1528     rc = ssh_packet_send(session);
1529 
1530     return rc;
1531 }
1532 
1533 /** @internal
1534  * @brief handles a SSH_MSG_UNIMPLEMENTED packet
1535  */
SSH_PACKET_CALLBACK(ssh_packet_unimplemented)1536 SSH_PACKET_CALLBACK(ssh_packet_unimplemented){
1537     uint32_t seq;
1538     int rc;
1539 
1540     (void)session; /* unused */
1541     (void)type;
1542     (void)user;
1543 
1544     rc = ssh_buffer_unpack(packet, "d", &seq);
1545     if (rc != SSH_OK) {
1546         SSH_LOG(SSH_LOG_WARNING,
1547                 "Could not unpack SSH_MSG_UNIMPLEMENTED packet");
1548     }
1549 
1550     SSH_LOG(SSH_LOG_RARE,
1551             "Received SSH_MSG_UNIMPLEMENTED (sequence number %d)",seq);
1552 
1553     return SSH_PACKET_USED;
1554 }
1555 
1556 /** @internal
1557  * @parse the "Type" header field of a packet and updates the session
1558  */
ssh_packet_parse_type(struct ssh_session_struct * session)1559 int ssh_packet_parse_type(struct ssh_session_struct *session)
1560 {
1561     session->in_packet = (struct packet_struct) {
1562         .type = 0,
1563     };
1564 
1565     if (session->in_buffer == NULL) {
1566         return SSH_ERROR;
1567     }
1568 
1569     if (ssh_buffer_get_u8(session->in_buffer, &session->in_packet.type) == 0) {
1570         ssh_set_error(session, SSH_FATAL, "Packet too short to read type");
1571         return SSH_ERROR;
1572     }
1573 
1574     session->in_packet.valid = 1;
1575 
1576     return SSH_OK;
1577 }
1578 
1579 /*
1580  * This function places the outgoing packet buffer into an outgoing
1581  * socket buffer
1582  */
ssh_packet_write(ssh_session session)1583 static int ssh_packet_write(ssh_session session) {
1584   int rc = SSH_ERROR;
1585 
1586   rc=ssh_socket_write(session->socket,
1587       ssh_buffer_get(session->out_buffer),
1588       ssh_buffer_get_len(session->out_buffer));
1589 
1590   return rc;
1591 }
1592 
packet_send2(ssh_session session)1593 static int packet_send2(ssh_session session)
1594 {
1595     unsigned int blocksize = 8;
1596     unsigned int lenfield_blocksize = 0;
1597     enum ssh_hmac_e hmac_type;
1598     uint32_t currentlen = ssh_buffer_get_len(session->out_buffer);
1599     struct ssh_crypto_struct *crypto = NULL;
1600     unsigned char *hmac = NULL;
1601     uint8_t padding_data[32] = { 0 };
1602     uint8_t padding_size;
1603     uint32_t finallen, payloadsize, compsize;
1604     uint8_t header[5] = {0};
1605     uint8_t type, *payload;
1606     int rc = SSH_ERROR;
1607     bool etm = false;
1608     int etm_packet_offset = 0;
1609 
1610     crypto = ssh_packet_get_current_crypto(session, SSH_DIRECTION_OUT);
1611     if (crypto) {
1612         blocksize = crypto->out_cipher->blocksize;
1613         lenfield_blocksize = crypto->out_cipher->lenfield_blocksize;
1614         hmac_type = crypto->out_hmac;
1615         etm = crypto->out_hmac_etm;
1616     } else {
1617         hmac_type = session->next_crypto->out_hmac;
1618     }
1619 
1620     payload = (uint8_t *)ssh_buffer_get(session->out_buffer);
1621     type = payload[0]; /* type is the first byte of the packet now */
1622 
1623     payloadsize = currentlen;
1624     if (etm) {
1625         etm_packet_offset = sizeof(uint32_t);
1626         lenfield_blocksize = 0;
1627     }
1628 
1629 #ifdef WITH_ZLIB
1630     if (crypto != NULL && crypto->do_compress_out &&
1631         ssh_buffer_get_len(session->out_buffer) > 0) {
1632         rc = compress_buffer(session,session->out_buffer);
1633         if (rc < 0) {
1634             goto error;
1635         }
1636         currentlen = ssh_buffer_get_len(session->out_buffer);
1637     }
1638 #endif /* WITH_ZLIB */
1639     compsize = currentlen;
1640     /* compressed payload + packet len (4) + padding_size len (1) */
1641     /* totallen - lenfield_blocksize - etm_packet_offset must be equal to 0 (mod blocksize) */
1642     padding_size = (blocksize - ((blocksize - lenfield_blocksize - etm_packet_offset + currentlen + 5) % blocksize));
1643     if (padding_size < 4) {
1644         padding_size += blocksize;
1645     }
1646 
1647     if (crypto != NULL) {
1648         int ok;
1649 
1650         ok = ssh_get_random(padding_data, padding_size, 0);
1651         if (!ok) {
1652             ssh_set_error(session, SSH_FATAL, "PRNG error");
1653             goto error;
1654         }
1655     }
1656 
1657     finallen = currentlen - etm_packet_offset + padding_size + 1;
1658 
1659     PUSH_BE_U32(header, 0, finallen);
1660     PUSH_BE_U8(header, 4, padding_size);
1661 
1662     rc = ssh_buffer_prepend_data(session->out_buffer,
1663                                  header,
1664                                  sizeof(header));
1665     if (rc < 0) {
1666         goto error;
1667     }
1668 
1669     rc = ssh_buffer_add_data(session->out_buffer, padding_data, padding_size);
1670     if (rc < 0) {
1671         goto error;
1672     }
1673 
1674 #ifdef WITH_PCAP
1675     if (session->pcap_ctx != NULL) {
1676         ssh_pcap_context_write(session->pcap_ctx,
1677                                SSH_PCAP_DIR_OUT,
1678                                ssh_buffer_get(session->out_buffer),
1679                                ssh_buffer_get_len(session->out_buffer),
1680                                ssh_buffer_get_len(session->out_buffer));
1681     }
1682 #endif
1683 
1684     hmac = ssh_packet_encrypt(session,
1685                               ssh_buffer_get(session->out_buffer),
1686                               ssh_buffer_get_len(session->out_buffer));
1687     if (hmac != NULL) {
1688         rc = ssh_buffer_add_data(session->out_buffer,
1689                                  hmac,
1690                                  hmac_digest_len(hmac_type));
1691         if (rc < 0) {
1692             goto error;
1693         }
1694     }
1695 
1696     rc = ssh_packet_write(session);
1697     if (rc == SSH_ERROR) {
1698         goto error;
1699     }
1700     session->send_seq++;
1701     if (crypto != NULL) {
1702         struct ssh_cipher_struct *cipher = NULL;
1703 
1704         cipher = crypto->out_cipher;
1705         cipher->packets++;
1706         cipher->blocks += payloadsize / cipher->blocksize;
1707     }
1708     if (session->raw_counter != NULL) {
1709         session->raw_counter->out_bytes += payloadsize;
1710         session->raw_counter->out_packets++;
1711     }
1712 
1713     SSH_LOG(SSH_LOG_PACKET,
1714             "packet: wrote [type=%u, len=%u, padding_size=%hhd, comp=%u, "
1715             "payload=%u]",
1716             type,
1717             finallen,
1718             padding_size,
1719             compsize,
1720             payloadsize);
1721 
1722     rc = ssh_buffer_reinit(session->out_buffer);
1723     if (rc < 0) {
1724         rc = SSH_ERROR;
1725         goto error;
1726     }
1727 
1728     /* We sent the NEWKEYS so any further packet needs to be encrypted
1729      * with the new keys. We can not switch both directions (need to decrypt
1730      * peer NEWKEYS) and we do not want to wait for the peer NEWKEYS
1731      * too, so we will switch only the OUT direction now.
1732      */
1733     if (type == SSH2_MSG_NEWKEYS) {
1734         rc = ssh_packet_set_newkeys(session, SSH_DIRECTION_OUT);
1735     }
1736 error:
1737     return rc; /* SSH_OK, AGAIN or ERROR */
1738 }
1739 
1740 static bool
ssh_packet_is_kex(unsigned char type)1741 ssh_packet_is_kex(unsigned char type)
1742 {
1743     return type >= SSH2_MSG_DISCONNECT &&
1744            type <= SSH2_MSG_KEX_DH_GEX_REQUEST &&
1745            type != SSH2_MSG_SERVICE_REQUEST &&
1746            type != SSH2_MSG_SERVICE_ACCEPT &&
1747            type != SSH2_MSG_IGNORE &&
1748            type != SSH2_MSG_EXT_INFO;
1749 }
1750 
1751 static bool
ssh_packet_in_rekey(ssh_session session)1752 ssh_packet_in_rekey(ssh_session session)
1753 {
1754     /* We know we are rekeying if we are authenticated and the DH
1755      * status is not finished
1756      */
1757     return (session->flags & SSH_SESSION_FLAG_AUTHENTICATED) &&
1758            (session->dh_handshake_state != DH_STATE_FINISHED);
1759 }
1760 
ssh_packet_send(ssh_session session)1761 int ssh_packet_send(ssh_session session)
1762 {
1763     uint32_t payloadsize;
1764     uint8_t type, *payload;
1765     bool need_rekey, in_rekey;
1766     int rc;
1767 
1768     payloadsize = ssh_buffer_get_len(session->out_buffer);
1769     if (payloadsize < 1) {
1770         return SSH_ERROR;
1771     }
1772 
1773     payload = (uint8_t *)ssh_buffer_get(session->out_buffer);
1774     type = payload[0]; /* type is the first byte of the packet now */
1775     need_rekey = ssh_packet_need_rekey(session, payloadsize);
1776     in_rekey = ssh_packet_in_rekey(session);
1777 
1778     /* The rekey is triggered here. After that, only the key exchange
1779      * packets can be sent, until we send our NEWKEYS.
1780      */
1781     if (need_rekey || (in_rekey && !ssh_packet_is_kex(type))) {
1782         if (need_rekey) {
1783             SSH_LOG(SSH_LOG_PACKET, "Outgoing packet triggered rekey");
1784         }
1785         /* Queue the current packet -- we will send it after the rekey */
1786         SSH_LOG(SSH_LOG_PACKET, "Queuing packet type %d", type);
1787         rc = ssh_list_append(session->out_queue, session->out_buffer);
1788         if (rc != SSH_OK) {
1789             return SSH_ERROR;
1790         }
1791         session->out_buffer = ssh_buffer_new();
1792         if (session->out_buffer == NULL) {
1793             ssh_set_error_oom(session);
1794             return SSH_ERROR;
1795         }
1796 
1797         if (need_rekey) {
1798             /* Send the KEXINIT packet instead.
1799              * This recursivelly calls the packet_send(), but it should
1800              * not get into rekeying again.
1801              * After that we need to handle the key exchange responses
1802              * up to the point where we can send the rest of the queue.
1803              */
1804             return ssh_send_rekex(session);
1805         }
1806         return SSH_OK;
1807     }
1808 
1809     /* Send the packet normally */
1810     rc = packet_send2(session);
1811 
1812     /* We finished the key exchange so we can try to send our queue now */
1813     if (rc == SSH_OK && type == SSH2_MSG_NEWKEYS) {
1814         struct ssh_iterator *it;
1815 
1816         for (it = ssh_list_get_iterator(session->out_queue);
1817              it != NULL;
1818              it = ssh_list_get_iterator(session->out_queue)) {
1819             struct ssh_buffer_struct *next_buffer = NULL;
1820 
1821             /* Peek only -- do not remove from queue yet */
1822             next_buffer = (struct ssh_buffer_struct *)it->data;
1823             payloadsize = ssh_buffer_get_len(next_buffer);
1824             if (ssh_packet_need_rekey(session, payloadsize)) {
1825                 /* Sigh ... we still can not send this packet. Repeat. */
1826                 SSH_LOG(SSH_LOG_PACKET, "Queued packet triggered rekey");
1827                 return ssh_send_rekex(session);
1828             }
1829             SSH_BUFFER_FREE(session->out_buffer);
1830             session->out_buffer = ssh_list_pop_head(struct ssh_buffer_struct *,
1831                                                     session->out_queue);
1832             payload = (uint8_t *)ssh_buffer_get(session->out_buffer);
1833             type = payload[0];
1834             SSH_LOG(SSH_LOG_PACKET, "Dequeue packet type %d", type);
1835             rc = packet_send2(session);
1836             if (rc != SSH_OK) {
1837                 return rc;
1838             }
1839         }
1840     }
1841 
1842     return rc;
1843 }
1844 
1845 static void
ssh_init_rekey_state(struct ssh_session_struct * session,struct ssh_cipher_struct * cipher)1846 ssh_init_rekey_state(struct ssh_session_struct *session,
1847                      struct ssh_cipher_struct *cipher)
1848 {
1849     /* Reset the counters: should be NOOP */
1850     cipher->packets = 0;
1851     cipher->blocks = 0;
1852 
1853     /* Default rekey limits for ciphers as specified in RFC4344, Section 3.2 */
1854     if (cipher->blocksize >= 16) {
1855         /* For larger block size (L bits) use maximum of 2**(L/4) blocks */
1856         cipher->max_blocks = (uint64_t)1 << (cipher->blocksize*2);
1857     } else {
1858         /* For smaller blocks use limit of 1 GB as recommended in RFC4253 */
1859         cipher->max_blocks = ((uint64_t)1 << 30) / cipher->blocksize;
1860     }
1861     /* If we have limit provided by user, use the smaller one */
1862     if (session->opts.rekey_data != 0) {
1863         cipher->max_blocks = MIN(cipher->max_blocks,
1864                                  session->opts.rekey_data / cipher->blocksize);
1865     }
1866 
1867     SSH_LOG(SSH_LOG_PROTOCOL,
1868             "Set rekey after %" PRIu64 " blocks",
1869             cipher->max_blocks);
1870 }
1871 
1872 /*
1873  * Once we got SSH2_MSG_NEWKEYS we can switch next_crypto and
1874  * current_crypto for our desired direction
1875  */
1876 int
ssh_packet_set_newkeys(ssh_session session,enum ssh_crypto_direction_e direction)1877 ssh_packet_set_newkeys(ssh_session session,
1878                        enum ssh_crypto_direction_e direction)
1879 {
1880     int rc;
1881 
1882     SSH_LOG(SSH_LOG_TRACE,
1883             "called, direction =%s%s",
1884             direction & SSH_DIRECTION_IN ? " IN " : "",
1885             direction & SSH_DIRECTION_OUT ? " OUT " : "");
1886 
1887     if (session->next_crypto == NULL) {
1888         return SSH_ERROR;
1889     }
1890 
1891     session->next_crypto->used |= direction;
1892     if (session->current_crypto != NULL) {
1893         if (session->current_crypto->used & direction) {
1894             SSH_LOG(SSH_LOG_WARNING, "This direction isn't used anymore.");
1895         }
1896         /* Mark the current requested direction unused */
1897         session->current_crypto->used &= ~direction;
1898     }
1899 
1900     /* Both sides switched: do the actual switch now */
1901     if (session->next_crypto->used == SSH_DIRECTION_BOTH) {
1902         size_t session_id_len;
1903 
1904         if (session->current_crypto != NULL) {
1905             crypto_free(session->current_crypto);
1906             session->current_crypto = NULL;
1907         }
1908 
1909         session->current_crypto = session->next_crypto;
1910         session->current_crypto->used = SSH_DIRECTION_BOTH;
1911 
1912         /* Initialize the next_crypto structure */
1913         session->next_crypto = crypto_new();
1914         if (session->next_crypto == NULL) {
1915             ssh_set_error_oom(session);
1916             return SSH_ERROR;
1917         }
1918 
1919         session_id_len = session->current_crypto->session_id_len;
1920         session->next_crypto->session_id = malloc(session_id_len);
1921         if (session->next_crypto->session_id == NULL) {
1922             ssh_set_error_oom(session);
1923             return SSH_ERROR;
1924         }
1925 
1926         memcpy(session->next_crypto->session_id,
1927                session->current_crypto->session_id,
1928                session_id_len);
1929 	session->next_crypto->session_id_len = session_id_len;
1930 
1931         return SSH_OK;
1932     }
1933 
1934     /* Initialize common structures so the next context can be used in
1935      * either direction */
1936     if (session->client) {
1937         /* The server has this part already done */
1938         rc = ssh_make_sessionid(session);
1939         if (rc != SSH_OK) {
1940             return SSH_ERROR;
1941         }
1942 
1943         /*
1944          * Set the cryptographic functions for the next crypto
1945          * (it is needed for ssh_generate_session_keys for key lengths)
1946          */
1947         rc = crypt_set_algorithms_client(session);
1948         if (rc < 0) {
1949             return SSH_ERROR;
1950         }
1951     }
1952 
1953     if (ssh_generate_session_keys(session) < 0) {
1954         return SSH_ERROR;
1955     }
1956 
1957     if (session->next_crypto->in_cipher == NULL ||
1958         session->next_crypto->out_cipher == NULL) {
1959         return SSH_ERROR;
1960     }
1961 
1962     /* Initialize rekeying states */
1963     ssh_init_rekey_state(session,
1964                          session->next_crypto->out_cipher);
1965     ssh_init_rekey_state(session,
1966                          session->next_crypto->in_cipher);
1967     if (session->opts.rekey_time != 0) {
1968         ssh_timestamp_init(&session->last_rekey_time);
1969         SSH_LOG(SSH_LOG_PROTOCOL, "Set rekey after %" PRIu32 " seconds",
1970                 session->opts.rekey_time/1000);
1971     }
1972 
1973     /* Initialize the encryption and decryption keys in next_crypto */
1974     rc = session->next_crypto->in_cipher->set_decrypt_key(
1975         session->next_crypto->in_cipher,
1976         session->next_crypto->decryptkey,
1977         session->next_crypto->decryptIV);
1978     if (rc < 0) {
1979         /* On error, make sure it is not used */
1980         session->next_crypto->used = 0;
1981         return SSH_ERROR;
1982     }
1983 
1984     rc = session->next_crypto->out_cipher->set_encrypt_key(
1985         session->next_crypto->out_cipher,
1986         session->next_crypto->encryptkey,
1987         session->next_crypto->encryptIV);
1988     if (rc < 0) {
1989         /* On error, make sure it is not used */
1990         session->next_crypto->used = 0;
1991         return SSH_ERROR;
1992     }
1993 
1994     return SSH_OK;
1995 }
1996