packet.c 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892
  1. /* $OpenBSD: packet.c,v 1.296 2020/07/05 23:59:45 djm Exp $ */
  2. /*
  3. * Author: Tatu Ylonen <ylo@cs.hut.fi>
  4. * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
  5. * All rights reserved
  6. * This file contains code implementing the packet protocol and communication
  7. * with the other side. This same code is used both on client and server side.
  8. *
  9. * As far as I am concerned, the code I have written for this software
  10. * can be used freely for any purpose. Any derived versions of this
  11. * software must be clearly marked as such, and if the derived work is
  12. * incompatible with the protocol description in the RFC file, it must be
  13. * called by a name other than "ssh" or "Secure Shell".
  14. *
  15. *
  16. * SSH2 packet format added by Markus Friedl.
  17. * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
  18. *
  19. * Redistribution and use in source and binary forms, with or without
  20. * modification, are permitted provided that the following conditions
  21. * are met:
  22. * 1. Redistributions of source code must retain the above copyright
  23. * notice, this list of conditions and the following disclaimer.
  24. * 2. Redistributions in binary form must reproduce the above copyright
  25. * notice, this list of conditions and the following disclaimer in the
  26. * documentation and/or other materials provided with the distribution.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  29. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  31. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  32. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  33. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  34. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  35. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  36. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  37. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. */
  39. #include "includes.h"
  40. #include <sys/types.h>
  41. #include "openbsd-compat/sys-queue.h"
  42. #include <sys/socket.h>
  43. #ifdef HAVE_SYS_TIME_H
  44. # include <sys/time.h>
  45. #endif
  46. #include <netinet/in.h>
  47. #include <netinet/ip.h>
  48. #include <arpa/inet.h>
  49. #include <errno.h>
  50. #include <netdb.h>
  51. #include <stdarg.h>
  52. #include <stdio.h>
  53. #include <stdlib.h>
  54. #include <string.h>
  55. #include <unistd.h>
  56. #include <limits.h>
  57. #ifdef HAVE_POLL_H
  58. #include <poll.h>
  59. #endif
  60. #include <signal.h>
  61. #include <time.h>
  62. /*
  63. * Explicitly include OpenSSL before zlib as some versions of OpenSSL have
  64. * "free_func" in their headers, which zlib typedefs.
  65. */
  66. #ifdef WITH_OPENSSL
  67. # include <openssl/bn.h>
  68. # include <openssl/evp.h>
  69. # ifdef OPENSSL_HAS_ECC
  70. # include <openssl/ec.h>
  71. # endif
  72. #endif
  73. #ifdef WITH_ZLIB
  74. #include <zlib.h>
  75. #endif
  76. #include "xmalloc.h"
  77. #include "audit.h"
  78. #include "compat.h"
  79. #include "ssh2.h"
  80. #include "cipher.h"
  81. #include "sshkey.h"
  82. #include "kex.h"
  83. #include "digest.h"
  84. #include "mac.h"
  85. #include "log.h"
  86. #include "canohost.h"
  87. #include "misc.h"
  88. #include "channels.h"
  89. #include "ssh.h"
  90. #include "packet.h"
  91. #include "ssherr.h"
  92. #include "sshbuf.h"
  93. #ifdef PACKET_DEBUG
  94. #define DBG(x) x
  95. #else
  96. #define DBG(x)
  97. #endif
  98. #define PACKET_MAX_SIZE (256 * 1024)
  99. struct packet_state {
  100. u_int32_t seqnr;
  101. u_int32_t packets;
  102. u_int64_t blocks;
  103. u_int64_t bytes;
  104. };
  105. struct packet {
  106. TAILQ_ENTRY(packet) next;
  107. u_char type;
  108. struct sshbuf *payload;
  109. };
  110. struct session_state {
  111. /*
  112. * This variable contains the file descriptors used for
  113. * communicating with the other side. connection_in is used for
  114. * reading; connection_out for writing. These can be the same
  115. * descriptor, in which case it is assumed to be a socket.
  116. */
  117. int connection_in;
  118. int connection_out;
  119. /* Protocol flags for the remote side. */
  120. u_int remote_protocol_flags;
  121. /* Encryption context for receiving data. Only used for decryption. */
  122. struct sshcipher_ctx *receive_context;
  123. /* Encryption context for sending data. Only used for encryption. */
  124. struct sshcipher_ctx *send_context;
  125. /* Buffer for raw input data from the socket. */
  126. struct sshbuf *input;
  127. /* Buffer for raw output data going to the socket. */
  128. struct sshbuf *output;
  129. /* Buffer for the partial outgoing packet being constructed. */
  130. struct sshbuf *outgoing_packet;
  131. /* Buffer for the incoming packet currently being processed. */
  132. struct sshbuf *incoming_packet;
  133. /* Scratch buffer for packet compression/decompression. */
  134. struct sshbuf *compression_buffer;
  135. #ifdef WITH_ZLIB
  136. /* Incoming/outgoing compression dictionaries */
  137. z_stream compression_in_stream;
  138. z_stream compression_out_stream;
  139. #endif
  140. int compression_in_started;
  141. int compression_out_started;
  142. int compression_in_failures;
  143. int compression_out_failures;
  144. /* default maximum packet size */
  145. u_int max_packet_size;
  146. /* Flag indicating whether this module has been initialized. */
  147. int initialized;
  148. /* Set to true if the connection is interactive. */
  149. int interactive_mode;
  150. /* Set to true if we are the server side. */
  151. int server_side;
  152. /* Set to true if we are authenticated. */
  153. int after_authentication;
  154. int keep_alive_timeouts;
  155. /* The maximum time that we will wait to send or receive a packet */
  156. int packet_timeout_ms;
  157. /* Session key information for Encryption and MAC */
  158. struct newkeys *newkeys[MODE_MAX];
  159. struct packet_state p_read, p_send;
  160. /* Volume-based rekeying */
  161. u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
  162. /* Time-based rekeying */
  163. u_int32_t rekey_interval; /* how often in seconds */
  164. time_t rekey_time; /* time of last rekeying */
  165. /* roundup current message to extra_pad bytes */
  166. u_char extra_pad;
  167. /* XXX discard incoming data after MAC error */
  168. u_int packet_discard;
  169. size_t packet_discard_mac_already;
  170. struct sshmac *packet_discard_mac;
  171. /* Used in packet_read_poll2() */
  172. u_int packlen;
  173. /* Used in packet_send2 */
  174. int rekeying;
  175. /* Used in ssh_packet_send_mux() */
  176. int mux;
  177. /* Used in packet_set_interactive */
  178. int set_interactive_called;
  179. /* Used in packet_set_maxsize */
  180. int set_maxsize_called;
  181. /* One-off warning about weak ciphers */
  182. int cipher_warning_done;
  183. /* Hook for fuzzing inbound packets */
  184. ssh_packet_hook_fn *hook_in;
  185. void *hook_in_ctx;
  186. TAILQ_HEAD(, packet) outgoing;
  187. };
  188. struct ssh *
  189. ssh_alloc_session_state(void)
  190. {
  191. struct ssh *ssh = NULL;
  192. struct session_state *state = NULL;
  193. if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
  194. (state = calloc(1, sizeof(*state))) == NULL ||
  195. (ssh->kex = kex_new()) == NULL ||
  196. (state->input = sshbuf_new()) == NULL ||
  197. (state->output = sshbuf_new()) == NULL ||
  198. (state->outgoing_packet = sshbuf_new()) == NULL ||
  199. (state->incoming_packet = sshbuf_new()) == NULL)
  200. goto fail;
  201. TAILQ_INIT(&state->outgoing);
  202. TAILQ_INIT(&ssh->private_keys);
  203. TAILQ_INIT(&ssh->public_keys);
  204. state->connection_in = -1;
  205. state->connection_out = -1;
  206. state->max_packet_size = CHAN_SES_PACKET_DEFAULT;
  207. state->packet_timeout_ms = -1;
  208. state->p_send.packets = state->p_read.packets = 0;
  209. state->initialized = 1;
  210. /*
  211. * ssh_packet_send2() needs to queue packets until
  212. * we've done the initial key exchange.
  213. */
  214. state->rekeying = 1;
  215. ssh->state = state;
  216. return ssh;
  217. fail:
  218. if (ssh) {
  219. kex_free(ssh->kex);
  220. free(ssh);
  221. }
  222. if (state) {
  223. sshbuf_free(state->input);
  224. sshbuf_free(state->output);
  225. sshbuf_free(state->incoming_packet);
  226. sshbuf_free(state->outgoing_packet);
  227. free(state);
  228. }
  229. return NULL;
  230. }
  231. void
  232. ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
  233. {
  234. ssh->state->hook_in = hook;
  235. ssh->state->hook_in_ctx = ctx;
  236. }
  237. /* Returns nonzero if rekeying is in progress */
  238. int
  239. ssh_packet_is_rekeying(struct ssh *ssh)
  240. {
  241. return ssh->state->rekeying ||
  242. (ssh->kex != NULL && ssh->kex->done == 0);
  243. }
  244. /*
  245. * Sets the descriptors used for communication.
  246. */
  247. struct ssh *
  248. ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
  249. {
  250. struct session_state *state;
  251. struct sshcipher *none = cipher_by_name("none");
  252. int r;
  253. if (none == NULL) {
  254. error("%s: cannot load cipher 'none'", __func__);
  255. return NULL;
  256. }
  257. if (ssh == NULL)
  258. ssh = ssh_alloc_session_state();
  259. if (ssh == NULL) {
  260. error("%s: could not allocate state", __func__);
  261. return NULL;
  262. }
  263. state = ssh->state;
  264. state->connection_in = fd_in;
  265. state->connection_out = fd_out;
  266. if ((r = cipher_init(&state->send_context, none,
  267. (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
  268. (r = cipher_init(&state->receive_context, none,
  269. (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
  270. error("%s: cipher_init failed: %s", __func__, ssh_err(r));
  271. free(ssh); /* XXX need ssh_free_session_state? */
  272. return NULL;
  273. }
  274. state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
  275. /*
  276. * Cache the IP address of the remote connection for use in error
  277. * messages that might be generated after the connection has closed.
  278. */
  279. (void)ssh_remote_ipaddr(ssh);
  280. return ssh;
  281. }
  282. void
  283. ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
  284. {
  285. struct session_state *state = ssh->state;
  286. if (timeout <= 0 || count <= 0) {
  287. state->packet_timeout_ms = -1;
  288. return;
  289. }
  290. if ((INT_MAX / 1000) / count < timeout)
  291. state->packet_timeout_ms = INT_MAX;
  292. else
  293. state->packet_timeout_ms = timeout * count * 1000;
  294. }
  295. void
  296. ssh_packet_set_mux(struct ssh *ssh)
  297. {
  298. ssh->state->mux = 1;
  299. ssh->state->rekeying = 0;
  300. kex_free(ssh->kex);
  301. ssh->kex = NULL;
  302. }
  303. int
  304. ssh_packet_get_mux(struct ssh *ssh)
  305. {
  306. return ssh->state->mux;
  307. }
  308. int
  309. ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
  310. {
  311. va_list args;
  312. int r;
  313. free(ssh->log_preamble);
  314. if (fmt == NULL)
  315. ssh->log_preamble = NULL;
  316. else {
  317. va_start(args, fmt);
  318. r = vasprintf(&ssh->log_preamble, fmt, args);
  319. va_end(args);
  320. if (r < 0 || ssh->log_preamble == NULL)
  321. return SSH_ERR_ALLOC_FAIL;
  322. }
  323. return 0;
  324. }
  325. int
  326. ssh_packet_stop_discard(struct ssh *ssh)
  327. {
  328. struct session_state *state = ssh->state;
  329. int r;
  330. if (state->packet_discard_mac) {
  331. char buf[1024];
  332. size_t dlen = PACKET_MAX_SIZE;
  333. if (dlen > state->packet_discard_mac_already)
  334. dlen -= state->packet_discard_mac_already;
  335. memset(buf, 'a', sizeof(buf));
  336. while (sshbuf_len(state->incoming_packet) < dlen)
  337. if ((r = sshbuf_put(state->incoming_packet, buf,
  338. sizeof(buf))) != 0)
  339. return r;
  340. (void) mac_compute(state->packet_discard_mac,
  341. state->p_read.seqnr,
  342. sshbuf_ptr(state->incoming_packet), dlen,
  343. NULL, 0);
  344. }
  345. logit("Finished discarding for %.200s port %d",
  346. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
  347. return SSH_ERR_MAC_INVALID;
  348. }
  349. static int
  350. ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
  351. struct sshmac *mac, size_t mac_already, u_int discard)
  352. {
  353. struct session_state *state = ssh->state;
  354. int r;
  355. if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
  356. if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
  357. return r;
  358. return SSH_ERR_MAC_INVALID;
  359. }
  360. /*
  361. * Record number of bytes over which the mac has already
  362. * been computed in order to minimize timing attacks.
  363. */
  364. if (mac && mac->enabled) {
  365. state->packet_discard_mac = mac;
  366. state->packet_discard_mac_already = mac_already;
  367. }
  368. if (sshbuf_len(state->input) >= discard)
  369. return ssh_packet_stop_discard(ssh);
  370. state->packet_discard = discard - sshbuf_len(state->input);
  371. return 0;
  372. }
  373. /* Returns 1 if remote host is connected via socket, 0 if not. */
  374. int
  375. ssh_packet_connection_is_on_socket(struct ssh *ssh)
  376. {
  377. struct session_state *state;
  378. struct sockaddr_storage from, to;
  379. socklen_t fromlen, tolen;
  380. if (ssh == NULL || ssh->state == NULL)
  381. return 0;
  382. state = ssh->state;
  383. if (state->connection_in == -1 || state->connection_out == -1)
  384. return 0;
  385. /* filedescriptors in and out are the same, so it's a socket */
  386. if (state->connection_in == state->connection_out)
  387. return 1;
  388. fromlen = sizeof(from);
  389. memset(&from, 0, sizeof(from));
  390. if (getpeername(state->connection_in, (struct sockaddr *)&from,
  391. &fromlen) == -1)
  392. return 0;
  393. tolen = sizeof(to);
  394. memset(&to, 0, sizeof(to));
  395. if (getpeername(state->connection_out, (struct sockaddr *)&to,
  396. &tolen) == -1)
  397. return 0;
  398. if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
  399. return 0;
  400. if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
  401. return 0;
  402. return 1;
  403. }
  404. void
  405. ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
  406. {
  407. if (ibytes)
  408. *ibytes = ssh->state->p_read.bytes;
  409. if (obytes)
  410. *obytes = ssh->state->p_send.bytes;
  411. }
  412. int
  413. ssh_packet_connection_af(struct ssh *ssh)
  414. {
  415. struct sockaddr_storage to;
  416. socklen_t tolen = sizeof(to);
  417. memset(&to, 0, sizeof(to));
  418. if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
  419. &tolen) == -1)
  420. return 0;
  421. #ifdef IPV4_IN_IPV6
  422. if (to.ss_family == AF_INET6 &&
  423. IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
  424. return AF_INET;
  425. #endif
  426. return to.ss_family;
  427. }
  428. /* Sets the connection into non-blocking mode. */
  429. void
  430. ssh_packet_set_nonblocking(struct ssh *ssh)
  431. {
  432. /* Set the socket into non-blocking mode. */
  433. set_nonblock(ssh->state->connection_in);
  434. if (ssh->state->connection_out != ssh->state->connection_in)
  435. set_nonblock(ssh->state->connection_out);
  436. }
  437. /* Returns the socket used for reading. */
  438. int
  439. ssh_packet_get_connection_in(struct ssh *ssh)
  440. {
  441. return ssh->state->connection_in;
  442. }
  443. /* Returns the descriptor used for writing. */
  444. int
  445. ssh_packet_get_connection_out(struct ssh *ssh)
  446. {
  447. return ssh->state->connection_out;
  448. }
  449. static int
  450. packet_state_has_keys (const struct session_state *state)
  451. {
  452. return state != NULL &&
  453. (state->newkeys[MODE_IN] != NULL || state->newkeys[MODE_OUT] != NULL);
  454. }
  455. /*
  456. * Returns the IP-address of the remote host as a string. The returned
  457. * string must not be freed.
  458. */
  459. const char *
  460. ssh_remote_ipaddr(struct ssh *ssh)
  461. {
  462. int sock;
  463. /* Check whether we have cached the ipaddr. */
  464. if (ssh->remote_ipaddr == NULL) {
  465. if (ssh_packet_connection_is_on_socket(ssh)) {
  466. sock = ssh->state->connection_in;
  467. ssh->remote_ipaddr = get_peer_ipaddr(sock);
  468. ssh->remote_port = get_peer_port(sock);
  469. ssh->local_ipaddr = get_local_ipaddr(sock);
  470. ssh->local_port = get_local_port(sock);
  471. } else {
  472. ssh->remote_ipaddr = xstrdup("UNKNOWN");
  473. ssh->remote_port = 65535;
  474. ssh->local_ipaddr = xstrdup("UNKNOWN");
  475. ssh->local_port = 65535;
  476. }
  477. }
  478. return ssh->remote_ipaddr;
  479. }
  480. /* Returns the port number of the remote host. */
  481. int
  482. ssh_remote_port(struct ssh *ssh)
  483. {
  484. (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
  485. return ssh->remote_port;
  486. }
  487. /*
  488. * Returns the IP-address of the local host as a string. The returned
  489. * string must not be freed.
  490. */
  491. const char *
  492. ssh_local_ipaddr(struct ssh *ssh)
  493. {
  494. (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
  495. return ssh->local_ipaddr;
  496. }
  497. /* Returns the port number of the local host. */
  498. int
  499. ssh_local_port(struct ssh *ssh)
  500. {
  501. (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
  502. return ssh->local_port;
  503. }
  504. /* Returns the routing domain of the input socket, or NULL if unavailable */
  505. const char *
  506. ssh_packet_rdomain_in(struct ssh *ssh)
  507. {
  508. if (ssh->rdomain_in != NULL)
  509. return ssh->rdomain_in;
  510. if (!ssh_packet_connection_is_on_socket(ssh))
  511. return NULL;
  512. ssh->rdomain_in = get_rdomain(ssh->state->connection_in);
  513. return ssh->rdomain_in;
  514. }
  515. /* Closes the connection and clears and frees internal data structures. */
  516. static void
  517. ssh_packet_close_internal(struct ssh *ssh, int do_close)
  518. {
  519. struct session_state *state = ssh->state;
  520. u_int mode;
  521. u_int had_keys = packet_state_has_keys(state);
  522. if (!state->initialized)
  523. return;
  524. state->initialized = 0;
  525. sshbuf_free(state->input);
  526. state->input = NULL;
  527. sshbuf_free(state->output);
  528. state->output = NULL;
  529. sshbuf_free(state->outgoing_packet);
  530. state->outgoing_packet = NULL;
  531. sshbuf_free(state->incoming_packet);
  532. state->incoming_packet = NULL;
  533. for (mode = 0; mode < MODE_MAX; mode++) {
  534. kex_free_newkeys(state->newkeys[mode]); /* current keys */
  535. state->newkeys[mode] = NULL;
  536. ssh_clear_newkeys(ssh, mode); /* next keys */
  537. }
  538. #ifdef WITH_ZLIB
  539. /* compression state is in shared mem, so we can only release it once */
  540. if (do_close && state->compression_buffer) {
  541. sshbuf_free(state->compression_buffer);
  542. if (state->compression_out_started) {
  543. z_streamp stream = &state->compression_out_stream;
  544. debug("compress outgoing: "
  545. "raw data %llu, compressed %llu, factor %.2f",
  546. (unsigned long long)stream->total_in,
  547. (unsigned long long)stream->total_out,
  548. stream->total_in == 0 ? 0.0 :
  549. (double) stream->total_out / stream->total_in);
  550. if (state->compression_out_failures == 0)
  551. deflateEnd(stream);
  552. }
  553. if (state->compression_in_started) {
  554. z_streamp stream = &state->compression_in_stream;
  555. debug("compress incoming: "
  556. "raw data %llu, compressed %llu, factor %.2f",
  557. (unsigned long long)stream->total_out,
  558. (unsigned long long)stream->total_in,
  559. stream->total_out == 0 ? 0.0 :
  560. (double) stream->total_in / stream->total_out);
  561. if (state->compression_in_failures == 0)
  562. inflateEnd(stream);
  563. }
  564. }
  565. #endif /* WITH_ZLIB */
  566. cipher_free(state->send_context);
  567. cipher_free(state->receive_context);
  568. if (had_keys && state->server_side) {
  569. /* Assuming this is called only from privsep child */
  570. audit_session_key_free(ssh, MODE_MAX);
  571. }
  572. state->send_context = state->receive_context = NULL;
  573. if (do_close) {
  574. if (state->connection_in == state->connection_out) {
  575. close(state->connection_out);
  576. } else {
  577. close(state->connection_in);
  578. close(state->connection_out);
  579. }
  580. free(ssh->local_ipaddr);
  581. ssh->local_ipaddr = NULL;
  582. free(ssh->remote_ipaddr);
  583. ssh->remote_ipaddr = NULL;
  584. free(ssh->state);
  585. ssh->state = NULL;
  586. kex_free(ssh->kex);
  587. ssh->kex = NULL;
  588. }
  589. }
  590. void
  591. ssh_packet_close(struct ssh *ssh)
  592. {
  593. ssh_packet_close_internal(ssh, 1);
  594. }
  595. void
  596. ssh_packet_clear_keys(struct ssh *ssh)
  597. {
  598. ssh_packet_close_internal(ssh, 0);
  599. }
  600. /* Sets remote side protocol flags. */
  601. void
  602. ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
  603. {
  604. ssh->state->remote_protocol_flags = protocol_flags;
  605. }
  606. /* Returns the remote protocol flags set earlier by the above function. */
  607. u_int
  608. ssh_packet_get_protocol_flags(struct ssh *ssh)
  609. {
  610. return ssh->state->remote_protocol_flags;
  611. }
  612. /*
  613. * Starts packet compression from the next packet on in both directions.
  614. * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
  615. */
  616. static int
  617. ssh_packet_init_compression(struct ssh *ssh)
  618. {
  619. if (!ssh->state->compression_buffer &&
  620. ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
  621. return SSH_ERR_ALLOC_FAIL;
  622. return 0;
  623. }
  624. #ifdef WITH_ZLIB
  625. static int
  626. start_compression_out(struct ssh *ssh, int level)
  627. {
  628. if (level < 1 || level > 9)
  629. return SSH_ERR_INVALID_ARGUMENT;
  630. debug("Enabling compression at level %d.", level);
  631. if (ssh->state->compression_out_started == 1)
  632. deflateEnd(&ssh->state->compression_out_stream);
  633. switch (deflateInit(&ssh->state->compression_out_stream, level)) {
  634. case Z_OK:
  635. ssh->state->compression_out_started = 1;
  636. break;
  637. case Z_MEM_ERROR:
  638. return SSH_ERR_ALLOC_FAIL;
  639. default:
  640. return SSH_ERR_INTERNAL_ERROR;
  641. }
  642. return 0;
  643. }
  644. static int
  645. start_compression_in(struct ssh *ssh)
  646. {
  647. if (ssh->state->compression_in_started == 1)
  648. inflateEnd(&ssh->state->compression_in_stream);
  649. switch (inflateInit(&ssh->state->compression_in_stream)) {
  650. case Z_OK:
  651. ssh->state->compression_in_started = 1;
  652. break;
  653. case Z_MEM_ERROR:
  654. return SSH_ERR_ALLOC_FAIL;
  655. default:
  656. return SSH_ERR_INTERNAL_ERROR;
  657. }
  658. return 0;
  659. }
  660. /* XXX remove need for separate compression buffer */
  661. static int
  662. compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
  663. {
  664. u_char buf[4096];
  665. int r, status;
  666. if (ssh->state->compression_out_started != 1)
  667. return SSH_ERR_INTERNAL_ERROR;
  668. /* This case is not handled below. */
  669. if (sshbuf_len(in) == 0)
  670. return 0;
  671. /* Input is the contents of the input buffer. */
  672. if ((ssh->state->compression_out_stream.next_in =
  673. sshbuf_mutable_ptr(in)) == NULL)
  674. return SSH_ERR_INTERNAL_ERROR;
  675. ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
  676. /* Loop compressing until deflate() returns with avail_out != 0. */
  677. do {
  678. /* Set up fixed-size output buffer. */
  679. ssh->state->compression_out_stream.next_out = buf;
  680. ssh->state->compression_out_stream.avail_out = sizeof(buf);
  681. /* Compress as much data into the buffer as possible. */
  682. status = deflate(&ssh->state->compression_out_stream,
  683. Z_PARTIAL_FLUSH);
  684. switch (status) {
  685. case Z_MEM_ERROR:
  686. return SSH_ERR_ALLOC_FAIL;
  687. case Z_OK:
  688. /* Append compressed data to output_buffer. */
  689. if ((r = sshbuf_put(out, buf, sizeof(buf) -
  690. ssh->state->compression_out_stream.avail_out)) != 0)
  691. return r;
  692. break;
  693. case Z_STREAM_ERROR:
  694. default:
  695. ssh->state->compression_out_failures++;
  696. return SSH_ERR_INVALID_FORMAT;
  697. }
  698. } while (ssh->state->compression_out_stream.avail_out == 0);
  699. return 0;
  700. }
  701. static int
  702. uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
  703. {
  704. u_char buf[4096];
  705. int r, status;
  706. if (ssh->state->compression_in_started != 1)
  707. return SSH_ERR_INTERNAL_ERROR;
  708. if ((ssh->state->compression_in_stream.next_in =
  709. sshbuf_mutable_ptr(in)) == NULL)
  710. return SSH_ERR_INTERNAL_ERROR;
  711. ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
  712. for (;;) {
  713. /* Set up fixed-size output buffer. */
  714. ssh->state->compression_in_stream.next_out = buf;
  715. ssh->state->compression_in_stream.avail_out = sizeof(buf);
  716. status = inflate(&ssh->state->compression_in_stream,
  717. Z_PARTIAL_FLUSH);
  718. switch (status) {
  719. case Z_OK:
  720. if ((r = sshbuf_put(out, buf, sizeof(buf) -
  721. ssh->state->compression_in_stream.avail_out)) != 0)
  722. return r;
  723. break;
  724. case Z_BUF_ERROR:
  725. /*
  726. * Comments in zlib.h say that we should keep calling
  727. * inflate() until we get an error. This appears to
  728. * be the error that we get.
  729. */
  730. return 0;
  731. case Z_DATA_ERROR:
  732. return SSH_ERR_INVALID_FORMAT;
  733. case Z_MEM_ERROR:
  734. return SSH_ERR_ALLOC_FAIL;
  735. case Z_STREAM_ERROR:
  736. default:
  737. ssh->state->compression_in_failures++;
  738. return SSH_ERR_INTERNAL_ERROR;
  739. }
  740. }
  741. /* NOTREACHED */
  742. }
  743. #else /* WITH_ZLIB */
  744. static int
  745. start_compression_out(struct ssh *ssh, int level)
  746. {
  747. return SSH_ERR_INTERNAL_ERROR;
  748. }
  749. static int
  750. start_compression_in(struct ssh *ssh)
  751. {
  752. return SSH_ERR_INTERNAL_ERROR;
  753. }
  754. static int
  755. compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
  756. {
  757. return SSH_ERR_INTERNAL_ERROR;
  758. }
  759. static int
  760. uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
  761. {
  762. return SSH_ERR_INTERNAL_ERROR;
  763. }
  764. #endif /* WITH_ZLIB */
  765. void
  766. ssh_clear_newkeys(struct ssh *ssh, int mode)
  767. {
  768. if (ssh->kex && ssh->kex->newkeys[mode]) {
  769. kex_free_newkeys(ssh->kex->newkeys[mode]);
  770. ssh->kex->newkeys[mode] = NULL;
  771. }
  772. }
  773. int
  774. ssh_set_newkeys(struct ssh *ssh, int mode)
  775. {
  776. struct session_state *state = ssh->state;
  777. struct sshenc *enc;
  778. struct sshmac *mac;
  779. struct sshcomp *comp;
  780. struct sshcipher_ctx **ccp;
  781. struct packet_state *ps;
  782. u_int64_t *max_blocks;
  783. const char *wmsg;
  784. int r, crypt_type;
  785. const char *dir = mode == MODE_OUT ? "out" : "in";
  786. debug2("set_newkeys: mode %d", mode);
  787. if (mode == MODE_OUT) {
  788. ccp = &state->send_context;
  789. crypt_type = CIPHER_ENCRYPT;
  790. ps = &state->p_send;
  791. max_blocks = &state->max_blocks_out;
  792. } else {
  793. ccp = &state->receive_context;
  794. crypt_type = CIPHER_DECRYPT;
  795. ps = &state->p_read;
  796. max_blocks = &state->max_blocks_in;
  797. }
  798. if (state->newkeys[mode] != NULL) {
  799. debug("%s: rekeying %s, input %llu bytes %llu blocks, "
  800. "output %llu bytes %llu blocks", __func__, dir,
  801. (unsigned long long)state->p_read.bytes,
  802. (unsigned long long)state->p_read.blocks,
  803. (unsigned long long)state->p_send.bytes,
  804. (unsigned long long)state->p_send.blocks);
  805. kex_free_newkeys(state->newkeys[mode]);
  806. audit_session_key_free(ssh, mode);
  807. state->newkeys[mode] = NULL;
  808. }
  809. /* note that both bytes and the seqnr are not reset */
  810. ps->packets = ps->blocks = 0;
  811. /* move newkeys from kex to state */
  812. if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
  813. return SSH_ERR_INTERNAL_ERROR;
  814. ssh->kex->newkeys[mode] = NULL;
  815. enc = &state->newkeys[mode]->enc;
  816. mac = &state->newkeys[mode]->mac;
  817. comp = &state->newkeys[mode]->comp;
  818. if (cipher_authlen(enc->cipher) == 0) {
  819. if ((r = mac_init(mac)) != 0)
  820. return r;
  821. }
  822. mac->enabled = 1;
  823. DBG(debug("%s: cipher_init_context: %s", __func__, dir));
  824. cipher_free(*ccp);
  825. *ccp = NULL;
  826. if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
  827. enc->iv, enc->iv_len, crypt_type)) != 0)
  828. return r;
  829. if (!state->cipher_warning_done &&
  830. (wmsg = cipher_warning_message(*ccp)) != NULL) {
  831. error("Warning: %s", wmsg);
  832. state->cipher_warning_done = 1;
  833. }
  834. /* Deleting the keys does not gain extra security */
  835. /* explicit_bzero(enc->iv, enc->block_size);
  836. explicit_bzero(enc->key, enc->key_len);
  837. explicit_bzero(mac->key, mac->key_len); */
  838. if ((comp->type == COMP_ZLIB ||
  839. (comp->type == COMP_DELAYED &&
  840. state->after_authentication)) && comp->enabled == 0) {
  841. if ((r = ssh_packet_init_compression(ssh)) < 0)
  842. return r;
  843. if (mode == MODE_OUT) {
  844. if ((r = start_compression_out(ssh, 6)) != 0)
  845. return r;
  846. } else {
  847. if ((r = start_compression_in(ssh)) != 0)
  848. return r;
  849. }
  850. comp->enabled = 1;
  851. }
  852. /*
  853. * The 2^(blocksize*2) limit is too expensive for 3DES,
  854. * so enforce a 1GB limit for small blocksizes.
  855. * See RFC4344 section 3.2.
  856. */
  857. /* we really don't need to rekey if we are using the none cipher
  858. * but there isn't a good way to disable it entirely that I can find
  859. * and using a blocksize larger that 16 doesn't work (dunno why)
  860. * so this seems to be a good limit for now - CJR 10/16/2020*/
  861. if (ssh->none == 1) {
  862. *max_blocks = (u_int64_t)1 << (16*2);
  863. } else {
  864. if (enc->block_size >= 16)
  865. *max_blocks = (u_int64_t)1 << (enc->block_size*2);
  866. else
  867. *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
  868. }
  869. if (state->rekey_limit)
  870. *max_blocks = MINIMUM(*max_blocks,
  871. state->rekey_limit / enc->block_size);
  872. debug("rekey %s after %llu blocks", dir,
  873. (unsigned long long)*max_blocks);
  874. return 0;
  875. }
  876. /* this supports the forced rekeying required for the NONE cipher */
  877. int rekey_requested = 0;
  878. void
  879. packet_request_rekeying(void)
  880. {
  881. rekey_requested = 1;
  882. }
  883. /* used to determine if pre or post auth when rekeying for aes-ctr
  884. * and none cipher switch */
  885. int
  886. packet_authentication_state(const struct ssh *ssh)
  887. {
  888. struct session_state *state = ssh->state;
  889. return state->after_authentication;
  890. }
  891. #define MAX_PACKETS (1U<<31)
  892. static int
  893. ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
  894. {
  895. struct session_state *state = ssh->state;
  896. u_int32_t out_blocks;
  897. /* XXX client can't cope with rekeying pre-auth */
  898. if (!state->after_authentication)
  899. return 0;
  900. /* Haven't keyed yet or KEX in progress. */
  901. if (ssh_packet_is_rekeying(ssh))
  902. return 0;
  903. /* Peer can't rekey */
  904. if (ssh->compat & SSH_BUG_NOREKEY)
  905. return 0;
  906. /*
  907. * Permit one packet in or out per rekey - this allows us to
  908. * make progress when rekey limits are very small.
  909. */
  910. if (state->p_send.packets == 0 && state->p_read.packets == 0)
  911. return 0;
  912. /* used to force rekeying when called for by the none
  913. * cipher switch and aes-mt-ctr methods -cjr */
  914. if (rekey_requested == 1) {
  915. rekey_requested = 0;
  916. return 1;
  917. }
  918. /* Time-based rekeying */
  919. if (state->rekey_interval != 0 &&
  920. (int64_t)state->rekey_time + state->rekey_interval <= monotime())
  921. return 1;
  922. /*
  923. * Always rekey when MAX_PACKETS sent in either direction
  924. * As per RFC4344 section 3.1 we do this after 2^31 packets.
  925. */
  926. if (state->p_send.packets > MAX_PACKETS ||
  927. state->p_read.packets > MAX_PACKETS)
  928. return 1;
  929. /* Rekey after (cipher-specific) maximum blocks */
  930. out_blocks = ROUNDUP(outbound_packet_len,
  931. state->newkeys[MODE_OUT]->enc.block_size);
  932. return (state->max_blocks_out &&
  933. (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
  934. (state->max_blocks_in &&
  935. (state->p_read.blocks > state->max_blocks_in));
  936. }
  937. /*
  938. * Delayed compression for SSH2 is enabled after authentication:
  939. * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
  940. * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
  941. */
  942. static int
  943. ssh_packet_enable_delayed_compress(struct ssh *ssh)
  944. {
  945. struct session_state *state = ssh->state;
  946. struct sshcomp *comp = NULL;
  947. int r, mode;
  948. /*
  949. * Remember that we are past the authentication step, so rekeying
  950. * with COMP_DELAYED will turn on compression immediately.
  951. */
  952. state->after_authentication = 1;
  953. for (mode = 0; mode < MODE_MAX; mode++) {
  954. /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
  955. if (state->newkeys[mode] == NULL)
  956. continue;
  957. comp = &state->newkeys[mode]->comp;
  958. if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
  959. if ((r = ssh_packet_init_compression(ssh)) != 0)
  960. return r;
  961. if (mode == MODE_OUT) {
  962. if ((r = start_compression_out(ssh, 6)) != 0)
  963. return r;
  964. } else {
  965. if ((r = start_compression_in(ssh)) != 0)
  966. return r;
  967. }
  968. comp->enabled = 1;
  969. }
  970. }
  971. return 0;
  972. }
  973. /* Used to mute debug logging for noisy packet types */
  974. int
  975. ssh_packet_log_type(u_char type)
  976. {
  977. switch (type) {
  978. case SSH2_MSG_CHANNEL_DATA:
  979. case SSH2_MSG_CHANNEL_EXTENDED_DATA:
  980. case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
  981. return 0;
  982. default:
  983. return 1;
  984. }
  985. }
  986. /*
  987. * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
  988. */
  989. int
  990. ssh_packet_send2_wrapped(struct ssh *ssh)
  991. {
  992. struct session_state *state = ssh->state;
  993. u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
  994. u_char tmp, padlen, pad = 0;
  995. u_int authlen = 0, aadlen = 0;
  996. u_int len;
  997. struct sshenc *enc = NULL;
  998. struct sshmac *mac = NULL;
  999. struct sshcomp *comp = NULL;
  1000. int r, block_size;
  1001. if (state->newkeys[MODE_OUT] != NULL) {
  1002. enc = &state->newkeys[MODE_OUT]->enc;
  1003. mac = &state->newkeys[MODE_OUT]->mac;
  1004. comp = &state->newkeys[MODE_OUT]->comp;
  1005. /* disable mac for authenticated encryption */
  1006. if ((authlen = cipher_authlen(enc->cipher)) != 0)
  1007. mac = NULL;
  1008. }
  1009. block_size = enc ? enc->block_size : 8;
  1010. aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
  1011. type = (sshbuf_ptr(state->outgoing_packet))[5];
  1012. if (ssh_packet_log_type(type))
  1013. debug3("send packet: type %u", type);
  1014. #ifdef PACKET_DEBUG
  1015. fprintf(stderr, "plain: ");
  1016. sshbuf_dump(state->outgoing_packet, stderr);
  1017. #endif
  1018. if (comp && comp->enabled) {
  1019. len = sshbuf_len(state->outgoing_packet);
  1020. /* skip header, compress only payload */
  1021. if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
  1022. goto out;
  1023. sshbuf_reset(state->compression_buffer);
  1024. if ((r = compress_buffer(ssh, state->outgoing_packet,
  1025. state->compression_buffer)) != 0)
  1026. goto out;
  1027. sshbuf_reset(state->outgoing_packet);
  1028. if ((r = sshbuf_put(state->outgoing_packet,
  1029. "\0\0\0\0\0", 5)) != 0 ||
  1030. (r = sshbuf_putb(state->outgoing_packet,
  1031. state->compression_buffer)) != 0)
  1032. goto out;
  1033. DBG(debug("compression: raw %d compressed %zd", len,
  1034. sshbuf_len(state->outgoing_packet)));
  1035. }
  1036. /* sizeof (packet_len + pad_len + payload) */
  1037. len = sshbuf_len(state->outgoing_packet);
  1038. /*
  1039. * calc size of padding, alloc space, get random data,
  1040. * minimum padding is 4 bytes
  1041. */
  1042. len -= aadlen; /* packet length is not encrypted for EtM modes */
  1043. padlen = block_size - (len % block_size);
  1044. if (padlen < 4)
  1045. padlen += block_size;
  1046. if (state->extra_pad) {
  1047. tmp = state->extra_pad;
  1048. state->extra_pad =
  1049. ROUNDUP(state->extra_pad, block_size);
  1050. /* check if roundup overflowed */
  1051. if (state->extra_pad < tmp)
  1052. return SSH_ERR_INVALID_ARGUMENT;
  1053. tmp = (len + padlen) % state->extra_pad;
  1054. /* Check whether pad calculation below will underflow */
  1055. if (tmp > state->extra_pad)
  1056. return SSH_ERR_INVALID_ARGUMENT;
  1057. pad = state->extra_pad - tmp;
  1058. DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
  1059. __func__, pad, len, padlen, state->extra_pad));
  1060. tmp = padlen;
  1061. padlen += pad;
  1062. /* Check whether padlen calculation overflowed */
  1063. if (padlen < tmp)
  1064. return SSH_ERR_INVALID_ARGUMENT; /* overflow */
  1065. state->extra_pad = 0;
  1066. }
  1067. if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
  1068. goto out;
  1069. if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
  1070. /* random padding */
  1071. arc4random_buf(cp, padlen);
  1072. } else {
  1073. /* clear padding */
  1074. explicit_bzero(cp, padlen);
  1075. }
  1076. /* sizeof (packet_len + pad_len + payload + padding) */
  1077. len = sshbuf_len(state->outgoing_packet);
  1078. cp = sshbuf_mutable_ptr(state->outgoing_packet);
  1079. if (cp == NULL) {
  1080. r = SSH_ERR_INTERNAL_ERROR;
  1081. goto out;
  1082. }
  1083. /* packet_length includes payload, padding and padding length field */
  1084. POKE_U32(cp, len - 4);
  1085. cp[4] = padlen;
  1086. DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
  1087. len, padlen, aadlen));
  1088. /* compute MAC over seqnr and packet(length fields, payload, padding) */
  1089. if (mac && mac->enabled && !mac->etm) {
  1090. if ((r = mac_compute(mac, state->p_send.seqnr,
  1091. sshbuf_ptr(state->outgoing_packet), len,
  1092. macbuf, sizeof(macbuf))) != 0)
  1093. goto out;
  1094. DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
  1095. }
  1096. /* encrypt packet and append to output buffer. */
  1097. if ((r = sshbuf_reserve(state->output,
  1098. sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
  1099. goto out;
  1100. if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
  1101. sshbuf_ptr(state->outgoing_packet),
  1102. len - aadlen, aadlen, authlen)) != 0)
  1103. goto out;
  1104. /* append unencrypted MAC */
  1105. if (mac && mac->enabled) {
  1106. if (mac->etm) {
  1107. /* EtM: compute mac over aadlen + cipher text */
  1108. if ((r = mac_compute(mac, state->p_send.seqnr,
  1109. cp, len, macbuf, sizeof(macbuf))) != 0)
  1110. goto out;
  1111. DBG(debug("done calc MAC(EtM) out #%d",
  1112. state->p_send.seqnr));
  1113. }
  1114. if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
  1115. goto out;
  1116. }
  1117. #ifdef PACKET_DEBUG
  1118. fprintf(stderr, "encrypted: ");
  1119. sshbuf_dump(state->output, stderr);
  1120. #endif
  1121. /* increment sequence number for outgoing packets */
  1122. if (++state->p_send.seqnr == 0)
  1123. logit("outgoing seqnr wraps around");
  1124. if (++state->p_send.packets == 0)
  1125. if (!(ssh->compat & SSH_BUG_NOREKEY))
  1126. return SSH_ERR_NEED_REKEY;
  1127. state->p_send.blocks += len / block_size;
  1128. state->p_send.bytes += len;
  1129. sshbuf_reset(state->outgoing_packet);
  1130. if (type == SSH2_MSG_NEWKEYS)
  1131. r = ssh_set_newkeys(ssh, MODE_OUT);
  1132. else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
  1133. r = ssh_packet_enable_delayed_compress(ssh);
  1134. else
  1135. r = 0;
  1136. out:
  1137. return r;
  1138. }
  1139. /* returns non-zero if the specified packet type is usec by KEX */
  1140. static int
  1141. ssh_packet_type_is_kex(u_char type)
  1142. {
  1143. return
  1144. type >= SSH2_MSG_TRANSPORT_MIN &&
  1145. type <= SSH2_MSG_TRANSPORT_MAX &&
  1146. type != SSH2_MSG_SERVICE_REQUEST &&
  1147. type != SSH2_MSG_SERVICE_ACCEPT &&
  1148. type != SSH2_MSG_EXT_INFO;
  1149. }
  1150. int
  1151. ssh_packet_send2(struct ssh *ssh)
  1152. {
  1153. struct session_state *state = ssh->state;
  1154. struct packet *p;
  1155. u_char type;
  1156. int r, need_rekey;
  1157. if (sshbuf_len(state->outgoing_packet) < 6)
  1158. return SSH_ERR_INTERNAL_ERROR;
  1159. type = sshbuf_ptr(state->outgoing_packet)[5];
  1160. need_rekey = !ssh_packet_type_is_kex(type) &&
  1161. ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
  1162. /*
  1163. * During rekeying we can only send key exchange messages.
  1164. * Queue everything else.
  1165. */
  1166. if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
  1167. if (need_rekey)
  1168. debug3("%s: rekex triggered", __func__);
  1169. debug("enqueue packet: %u", type);
  1170. p = calloc(1, sizeof(*p));
  1171. if (p == NULL)
  1172. return SSH_ERR_ALLOC_FAIL;
  1173. p->type = type;
  1174. p->payload = state->outgoing_packet;
  1175. TAILQ_INSERT_TAIL(&state->outgoing, p, next);
  1176. state->outgoing_packet = sshbuf_new();
  1177. if (state->outgoing_packet == NULL)
  1178. return SSH_ERR_ALLOC_FAIL;
  1179. if (need_rekey) {
  1180. /*
  1181. * This packet triggered a rekey, so send the
  1182. * KEXINIT now.
  1183. * NB. reenters this function via kex_start_rekex().
  1184. */
  1185. return kex_start_rekex(ssh);
  1186. }
  1187. return 0;
  1188. }
  1189. /* rekeying starts with sending KEXINIT */
  1190. if (type == SSH2_MSG_KEXINIT)
  1191. state->rekeying = 1;
  1192. if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
  1193. return r;
  1194. /* after a NEWKEYS message we can send the complete queue */
  1195. if (type == SSH2_MSG_NEWKEYS) {
  1196. state->rekeying = 0;
  1197. state->rekey_time = monotime();
  1198. while ((p = TAILQ_FIRST(&state->outgoing))) {
  1199. type = p->type;
  1200. /*
  1201. * If this packet triggers a rekex, then skip the
  1202. * remaining packets in the queue for now.
  1203. * NB. re-enters this function via kex_start_rekex.
  1204. */
  1205. if (ssh_packet_need_rekeying(ssh,
  1206. sshbuf_len(p->payload))) {
  1207. debug3("%s: queued packet triggered rekex",
  1208. __func__);
  1209. return kex_start_rekex(ssh);
  1210. }
  1211. debug("dequeue packet: %u", type);
  1212. sshbuf_free(state->outgoing_packet);
  1213. state->outgoing_packet = p->payload;
  1214. TAILQ_REMOVE(&state->outgoing, p, next);
  1215. memset(p, 0, sizeof(*p));
  1216. free(p);
  1217. if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
  1218. return r;
  1219. }
  1220. }
  1221. return 0;
  1222. }
  1223. /*
  1224. * Waits until a packet has been received, and returns its type. Note that
  1225. * no other data is processed until this returns, so this function should not
  1226. * be used during the interactive session.
  1227. */
  1228. int
  1229. ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
  1230. {
  1231. struct session_state *state = ssh->state;
  1232. int len, r, ms_remain;
  1233. fd_set *setp;
  1234. char buf[SSH_IOBUFSZ];
  1235. struct timeval timeout, start, *timeoutp = NULL;
  1236. DBG(debug("packet_read()"));
  1237. setp = calloc(howmany(state->connection_in + 1,
  1238. NFDBITS), sizeof(fd_mask));
  1239. if (setp == NULL)
  1240. return SSH_ERR_ALLOC_FAIL;
  1241. /*
  1242. * Since we are blocking, ensure that all written packets have
  1243. * been sent.
  1244. */
  1245. if ((r = ssh_packet_write_wait(ssh)) != 0)
  1246. goto out;
  1247. /* Stay in the loop until we have received a complete packet. */
  1248. for (;;) {
  1249. /* Try to read a packet from the buffer. */
  1250. r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
  1251. if (r != 0)
  1252. break;
  1253. /* If we got a packet, return it. */
  1254. if (*typep != SSH_MSG_NONE)
  1255. break;
  1256. /*
  1257. * Otherwise, wait for some data to arrive, add it to the
  1258. * buffer, and try again.
  1259. */
  1260. memset(setp, 0, howmany(state->connection_in + 1,
  1261. NFDBITS) * sizeof(fd_mask));
  1262. FD_SET(state->connection_in, setp);
  1263. if (state->packet_timeout_ms > 0) {
  1264. ms_remain = state->packet_timeout_ms;
  1265. timeoutp = &timeout;
  1266. }
  1267. /* Wait for some data to arrive. */
  1268. for (;;) {
  1269. if (state->packet_timeout_ms > 0) {
  1270. ms_to_timeval(&timeout, ms_remain);
  1271. monotime_tv(&start);
  1272. }
  1273. if ((r = select(state->connection_in + 1, setp,
  1274. NULL, NULL, timeoutp)) >= 0)
  1275. break;
  1276. if (errno != EAGAIN && errno != EINTR &&
  1277. errno != EWOULDBLOCK) {
  1278. r = SSH_ERR_SYSTEM_ERROR;
  1279. goto out;
  1280. }
  1281. if (state->packet_timeout_ms <= 0)
  1282. continue;
  1283. ms_subtract_diff(&start, &ms_remain);
  1284. if (ms_remain <= 0) {
  1285. r = 0;
  1286. break;
  1287. }
  1288. }
  1289. if (r == 0) {
  1290. r = SSH_ERR_CONN_TIMEOUT;
  1291. goto out;
  1292. }
  1293. /* Read data from the socket. */
  1294. len = read(state->connection_in, buf, sizeof(buf));
  1295. if (len == 0) {
  1296. r = SSH_ERR_CONN_CLOSED;
  1297. goto out;
  1298. }
  1299. if (len == -1) {
  1300. r = SSH_ERR_SYSTEM_ERROR;
  1301. goto out;
  1302. }
  1303. /* Append it to the buffer. */
  1304. if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
  1305. goto out;
  1306. }
  1307. out:
  1308. free(setp);
  1309. return r;
  1310. }
  1311. int
  1312. ssh_packet_read(struct ssh *ssh)
  1313. {
  1314. u_char type;
  1315. int r;
  1316. if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
  1317. fatal("%s: %s", __func__, ssh_err(r));
  1318. return type;
  1319. }
  1320. /*
  1321. * Waits until a packet has been received, verifies that its type matches
  1322. * that given, and gives a fatal error and exits if there is a mismatch.
  1323. */
  1324. int
  1325. ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
  1326. {
  1327. int r;
  1328. u_char type;
  1329. if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
  1330. return r;
  1331. if (type != expected_type) {
  1332. if ((r = sshpkt_disconnect(ssh,
  1333. "Protocol error: expected packet type %d, got %d",
  1334. expected_type, type)) != 0)
  1335. return r;
  1336. return SSH_ERR_PROTOCOL_ERROR;
  1337. }
  1338. return 0;
  1339. }
  1340. static int
  1341. ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
  1342. {
  1343. struct session_state *state = ssh->state;
  1344. const u_char *cp;
  1345. size_t need;
  1346. int r;
  1347. if (ssh->kex)
  1348. return SSH_ERR_INTERNAL_ERROR;
  1349. *typep = SSH_MSG_NONE;
  1350. cp = sshbuf_ptr(state->input);
  1351. if (state->packlen == 0) {
  1352. if (sshbuf_len(state->input) < 4 + 1)
  1353. return 0; /* packet is incomplete */
  1354. state->packlen = PEEK_U32(cp);
  1355. if (state->packlen < 4 + 1 ||
  1356. state->packlen > PACKET_MAX_SIZE)
  1357. return SSH_ERR_MESSAGE_INCOMPLETE;
  1358. }
  1359. need = state->packlen + 4;
  1360. if (sshbuf_len(state->input) < need)
  1361. return 0; /* packet is incomplete */
  1362. sshbuf_reset(state->incoming_packet);
  1363. if ((r = sshbuf_put(state->incoming_packet, cp + 4,
  1364. state->packlen)) != 0 ||
  1365. (r = sshbuf_consume(state->input, need)) != 0 ||
  1366. (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
  1367. (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
  1368. return r;
  1369. if (ssh_packet_log_type(*typep))
  1370. debug3("%s: type %u", __func__, *typep);
  1371. /* sshbuf_dump(state->incoming_packet, stderr); */
  1372. /* reset for next packet */
  1373. state->packlen = 0;
  1374. return r;
  1375. }
  1376. int
  1377. ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
  1378. {
  1379. struct session_state *state = ssh->state;
  1380. u_int padlen, need;
  1381. u_char *cp;
  1382. u_int maclen, aadlen = 0, authlen = 0, block_size;
  1383. struct sshenc *enc = NULL;
  1384. struct sshmac *mac = NULL;
  1385. struct sshcomp *comp = NULL;
  1386. int r;
  1387. if (state->mux)
  1388. return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
  1389. *typep = SSH_MSG_NONE;
  1390. if (state->packet_discard)
  1391. return 0;
  1392. if (state->newkeys[MODE_IN] != NULL) {
  1393. enc = &state->newkeys[MODE_IN]->enc;
  1394. mac = &state->newkeys[MODE_IN]->mac;
  1395. comp = &state->newkeys[MODE_IN]->comp;
  1396. /* disable mac for authenticated encryption */
  1397. if ((authlen = cipher_authlen(enc->cipher)) != 0)
  1398. mac = NULL;
  1399. }
  1400. maclen = mac && mac->enabled ? mac->mac_len : 0;
  1401. block_size = enc ? enc->block_size : 8;
  1402. aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
  1403. if (aadlen && state->packlen == 0) {
  1404. if (cipher_get_length(state->receive_context,
  1405. &state->packlen, state->p_read.seqnr,
  1406. sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
  1407. return 0;
  1408. if (state->packlen < 1 + 4 ||
  1409. state->packlen > PACKET_MAX_SIZE) {
  1410. #ifdef PACKET_DEBUG
  1411. sshbuf_dump(state->input, stderr);
  1412. #endif
  1413. logit("Bad packet length %u.", state->packlen);
  1414. if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
  1415. return r;
  1416. return SSH_ERR_CONN_CORRUPT;
  1417. }
  1418. sshbuf_reset(state->incoming_packet);
  1419. } else if (state->packlen == 0) {
  1420. /*
  1421. * check if input size is less than the cipher block size,
  1422. * decrypt first block and extract length of incoming packet
  1423. */
  1424. if (sshbuf_len(state->input) < block_size)
  1425. return 0;
  1426. sshbuf_reset(state->incoming_packet);
  1427. if ((r = sshbuf_reserve(state->incoming_packet, block_size,
  1428. &cp)) != 0)
  1429. goto out;
  1430. if ((r = cipher_crypt(state->receive_context,
  1431. state->p_send.seqnr, cp, sshbuf_ptr(state->input),
  1432. block_size, 0, 0)) != 0)
  1433. goto out;
  1434. state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
  1435. if (state->packlen < 1 + 4 ||
  1436. state->packlen > PACKET_MAX_SIZE) {
  1437. #ifdef PACKET_DEBUG
  1438. fprintf(stderr, "input: \n");
  1439. sshbuf_dump(state->input, stderr);
  1440. fprintf(stderr, "incoming_packet: \n");
  1441. sshbuf_dump(state->incoming_packet, stderr);
  1442. #endif
  1443. logit("Bad packet length %u.", state->packlen);
  1444. return ssh_packet_start_discard(ssh, enc, mac, 0,
  1445. PACKET_MAX_SIZE);
  1446. }
  1447. if ((r = sshbuf_consume(state->input, block_size)) != 0)
  1448. goto out;
  1449. }
  1450. DBG(debug("input: packet len %u", state->packlen+4));
  1451. if (aadlen) {
  1452. /* only the payload is encrypted */
  1453. need = state->packlen;
  1454. } else {
  1455. /*
  1456. * the payload size and the payload are encrypted, but we
  1457. * have a partial packet of block_size bytes
  1458. */
  1459. need = 4 + state->packlen - block_size;
  1460. }
  1461. DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
  1462. " aadlen %d", block_size, need, maclen, authlen, aadlen));
  1463. if (need % block_size != 0) {
  1464. logit("padding error: need %d block %d mod %d",
  1465. need, block_size, need % block_size);
  1466. return ssh_packet_start_discard(ssh, enc, mac, 0,
  1467. PACKET_MAX_SIZE - block_size);
  1468. }
  1469. /*
  1470. * check if the entire packet has been received and
  1471. * decrypt into incoming_packet:
  1472. * 'aadlen' bytes are unencrypted, but authenticated.
  1473. * 'need' bytes are encrypted, followed by either
  1474. * 'authlen' bytes of authentication tag or
  1475. * 'maclen' bytes of message authentication code.
  1476. */
  1477. if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
  1478. return 0; /* packet is incomplete */
  1479. #ifdef PACKET_DEBUG
  1480. fprintf(stderr, "read_poll enc/full: ");
  1481. sshbuf_dump(state->input, stderr);
  1482. #endif
  1483. /* EtM: check mac over encrypted input */
  1484. if (mac && mac->enabled && mac->etm) {
  1485. if ((r = mac_check(mac, state->p_read.seqnr,
  1486. sshbuf_ptr(state->input), aadlen + need,
  1487. sshbuf_ptr(state->input) + aadlen + need + authlen,
  1488. maclen)) != 0) {
  1489. if (r == SSH_ERR_MAC_INVALID)
  1490. logit("Corrupted MAC on input.");
  1491. goto out;
  1492. }
  1493. }
  1494. if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
  1495. &cp)) != 0)
  1496. goto out;
  1497. if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
  1498. sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
  1499. goto out;
  1500. if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
  1501. goto out;
  1502. if (mac && mac->enabled) {
  1503. /* Not EtM: check MAC over cleartext */
  1504. if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
  1505. sshbuf_ptr(state->incoming_packet),
  1506. sshbuf_len(state->incoming_packet),
  1507. sshbuf_ptr(state->input), maclen)) != 0) {
  1508. if (r != SSH_ERR_MAC_INVALID)
  1509. goto out;
  1510. logit("Corrupted MAC on input.");
  1511. if (need + block_size > PACKET_MAX_SIZE)
  1512. return SSH_ERR_INTERNAL_ERROR;
  1513. return ssh_packet_start_discard(ssh, enc, mac,
  1514. sshbuf_len(state->incoming_packet),
  1515. PACKET_MAX_SIZE - need - block_size);
  1516. }
  1517. /* Remove MAC from input buffer */
  1518. DBG(debug("MAC #%d ok", state->p_read.seqnr));
  1519. if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
  1520. goto out;
  1521. }
  1522. if (seqnr_p != NULL)
  1523. *seqnr_p = state->p_read.seqnr;
  1524. if (++state->p_read.seqnr == 0)
  1525. logit("incoming seqnr wraps around");
  1526. if (++state->p_read.packets == 0)
  1527. if (!(ssh->compat & SSH_BUG_NOREKEY))
  1528. return SSH_ERR_NEED_REKEY;
  1529. state->p_read.blocks += (state->packlen + 4) / block_size;
  1530. state->p_read.bytes += state->packlen + 4;
  1531. /* get padlen */
  1532. padlen = sshbuf_ptr(state->incoming_packet)[4];
  1533. DBG(debug("input: padlen %d", padlen));
  1534. if (padlen < 4) {
  1535. if ((r = sshpkt_disconnect(ssh,
  1536. "Corrupted padlen %d on input.", padlen)) != 0 ||
  1537. (r = ssh_packet_write_wait(ssh)) != 0)
  1538. return r;
  1539. return SSH_ERR_CONN_CORRUPT;
  1540. }
  1541. /* skip packet size + padlen, discard padding */
  1542. if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
  1543. ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
  1544. goto out;
  1545. DBG(debug("input: len before de-compress %zd",
  1546. sshbuf_len(state->incoming_packet)));
  1547. if (comp && comp->enabled) {
  1548. sshbuf_reset(state->compression_buffer);
  1549. if ((r = uncompress_buffer(ssh, state->incoming_packet,
  1550. state->compression_buffer)) != 0)
  1551. goto out;
  1552. sshbuf_reset(state->incoming_packet);
  1553. if ((r = sshbuf_putb(state->incoming_packet,
  1554. state->compression_buffer)) != 0)
  1555. goto out;
  1556. DBG(debug("input: len after de-compress %zd",
  1557. sshbuf_len(state->incoming_packet)));
  1558. }
  1559. /*
  1560. * get packet type, implies consume.
  1561. * return length of payload (without type field)
  1562. */
  1563. if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
  1564. goto out;
  1565. if (ssh_packet_log_type(*typep))
  1566. debug3("receive packet: type %u", *typep);
  1567. if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
  1568. if ((r = sshpkt_disconnect(ssh,
  1569. "Invalid ssh2 packet type: %d", *typep)) != 0 ||
  1570. (r = ssh_packet_write_wait(ssh)) != 0)
  1571. return r;
  1572. return SSH_ERR_PROTOCOL_ERROR;
  1573. }
  1574. if (state->hook_in != NULL &&
  1575. (r = state->hook_in(ssh, state->incoming_packet, typep,
  1576. state->hook_in_ctx)) != 0)
  1577. return r;
  1578. if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
  1579. r = ssh_packet_enable_delayed_compress(ssh);
  1580. else
  1581. r = 0;
  1582. #ifdef PACKET_DEBUG
  1583. fprintf(stderr, "read/plain[%d]:\r\n", *typep);
  1584. sshbuf_dump(state->incoming_packet, stderr);
  1585. #endif
  1586. /* reset for next packet */
  1587. state->packlen = 0;
  1588. /* do we need to rekey? */
  1589. if (ssh_packet_need_rekeying(ssh, 0)) {
  1590. debug3("%s: rekex triggered", __func__);
  1591. if ((r = kex_start_rekex(ssh)) != 0)
  1592. return r;
  1593. }
  1594. out:
  1595. return r;
  1596. }
  1597. int
  1598. ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
  1599. {
  1600. struct session_state *state = ssh->state;
  1601. u_int reason, seqnr;
  1602. int r;
  1603. u_char *msg;
  1604. for (;;) {
  1605. msg = NULL;
  1606. r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
  1607. if (r != 0)
  1608. return r;
  1609. if (*typep) {
  1610. state->keep_alive_timeouts = 0;
  1611. DBG(debug("received packet type %d", *typep));
  1612. }
  1613. switch (*typep) {
  1614. case SSH2_MSG_IGNORE:
  1615. debug3("Received SSH2_MSG_IGNORE");
  1616. break;
  1617. case SSH2_MSG_DEBUG:
  1618. if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
  1619. (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
  1620. (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
  1621. free(msg);
  1622. return r;
  1623. }
  1624. debug("Remote: %.900s", msg);
  1625. free(msg);
  1626. break;
  1627. case SSH2_MSG_DISCONNECT:
  1628. if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
  1629. (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
  1630. return r;
  1631. /* Ignore normal client exit notifications */
  1632. do_log2(ssh->state->server_side &&
  1633. reason == SSH2_DISCONNECT_BY_APPLICATION ?
  1634. SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
  1635. "Received disconnect from %s port %d:"
  1636. "%u: %.400s", ssh_remote_ipaddr(ssh),
  1637. ssh_remote_port(ssh), reason, msg);
  1638. free(msg);
  1639. return SSH_ERR_DISCONNECTED;
  1640. case SSH2_MSG_UNIMPLEMENTED:
  1641. if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
  1642. return r;
  1643. debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
  1644. seqnr);
  1645. break;
  1646. default:
  1647. return 0;
  1648. }
  1649. }
  1650. }
  1651. /*
  1652. * Buffers the given amount of input characters. This is intended to be used
  1653. * together with packet_read_poll.
  1654. */
  1655. int
  1656. ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
  1657. {
  1658. struct session_state *state = ssh->state;
  1659. int r;
  1660. if (state->packet_discard) {
  1661. state->keep_alive_timeouts = 0; /* ?? */
  1662. if (len >= state->packet_discard) {
  1663. if ((r = ssh_packet_stop_discard(ssh)) != 0)
  1664. return r;
  1665. }
  1666. state->packet_discard -= len;
  1667. return 0;
  1668. }
  1669. if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
  1670. return r;
  1671. return 0;
  1672. }
  1673. int
  1674. ssh_packet_remaining(struct ssh *ssh)
  1675. {
  1676. return sshbuf_len(ssh->state->incoming_packet);
  1677. }
  1678. /*
  1679. * Sends a diagnostic message from the server to the client. This message
  1680. * can be sent at any time (but not while constructing another message). The
  1681. * message is printed immediately, but only if the client is being executed
  1682. * in verbose mode. These messages are primarily intended to ease debugging
  1683. * authentication problems. The length of the formatted message must not
  1684. * exceed 1024 bytes. This will automatically call ssh_packet_write_wait.
  1685. */
  1686. void
  1687. ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
  1688. {
  1689. char buf[1024];
  1690. va_list args;
  1691. int r;
  1692. if ((ssh->compat & SSH_BUG_DEBUG))
  1693. return;
  1694. va_start(args, fmt);
  1695. vsnprintf(buf, sizeof(buf), fmt, args);
  1696. va_end(args);
  1697. debug3("sending debug message: %s", buf);
  1698. if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
  1699. (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
  1700. (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
  1701. (r = sshpkt_put_cstring(ssh, "")) != 0 ||
  1702. (r = sshpkt_send(ssh)) != 0 ||
  1703. (r = ssh_packet_write_wait(ssh)) != 0)
  1704. fatal("%s: %s", __func__, ssh_err(r));
  1705. }
  1706. void
  1707. sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
  1708. {
  1709. snprintf(s, l, "%.200s%s%s port %d",
  1710. ssh->log_preamble ? ssh->log_preamble : "",
  1711. ssh->log_preamble ? " " : "",
  1712. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
  1713. }
  1714. /*
  1715. * Pretty-print connection-terminating errors and exit.
  1716. */
  1717. static void
  1718. sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
  1719. {
  1720. char *tag = NULL, remote_id[512];
  1721. int oerrno = errno;
  1722. sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
  1723. switch (r) {
  1724. case SSH_ERR_CONN_CLOSED:
  1725. ssh_packet_clear_keys(ssh);
  1726. sshpkt_final_log_entry(ssh);
  1727. logdie("Connection closed by %s", remote_id);
  1728. case SSH_ERR_CONN_TIMEOUT:
  1729. ssh_packet_clear_keys(ssh);
  1730. sshpkt_final_log_entry(ssh);
  1731. logdie("Connection %s %s timed out",
  1732. ssh->state->server_side ? "from" : "to", remote_id);
  1733. case SSH_ERR_DISCONNECTED:
  1734. ssh_packet_clear_keys(ssh);
  1735. sshpkt_final_log_entry(ssh);
  1736. logdie("Disconnected from %s", remote_id);
  1737. case SSH_ERR_SYSTEM_ERROR:
  1738. if (errno == ECONNRESET) {
  1739. ssh_packet_clear_keys(ssh);
  1740. sshpkt_final_log_entry(ssh);
  1741. logdie("Connection reset by %s", remote_id);
  1742. }
  1743. /* FALLTHROUGH */
  1744. case SSH_ERR_NO_CIPHER_ALG_MATCH:
  1745. case SSH_ERR_NO_MAC_ALG_MATCH:
  1746. case SSH_ERR_NO_COMPRESS_ALG_MATCH:
  1747. case SSH_ERR_NO_KEX_ALG_MATCH:
  1748. case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
  1749. if (ssh && ssh->kex && ssh->kex->failed_choice) {
  1750. ssh_packet_clear_keys(ssh);
  1751. errno = oerrno;
  1752. logdie("Unable to negotiate with %s: %s. "
  1753. "Their offer: %s", remote_id, ssh_err(r),
  1754. ssh->kex->failed_choice);
  1755. }
  1756. /* FALLTHROUGH */
  1757. default:
  1758. if (vasprintf(&tag, fmt, ap) == -1) {
  1759. ssh_packet_clear_keys(ssh);
  1760. logdie("%s: could not allocate failure message",
  1761. __func__);
  1762. }
  1763. ssh_packet_clear_keys(ssh);
  1764. errno = oerrno;
  1765. logdie("%s%sConnection %s %s: %s",
  1766. tag != NULL ? tag : "", tag != NULL ? ": " : "",
  1767. ssh->state->server_side ? "from" : "to",
  1768. remote_id, ssh_err(r));
  1769. }
  1770. }
  1771. void
  1772. sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
  1773. {
  1774. va_list ap;
  1775. va_start(ap, fmt);
  1776. sshpkt_vfatal(ssh, r, fmt, ap);
  1777. /* NOTREACHED */
  1778. va_end(ap);
  1779. logdie("%s: should have exited", __func__);
  1780. }
  1781. /* this prints out the final log entry */
  1782. void
  1783. sshpkt_final_log_entry (struct ssh *ssh) {
  1784. double total_time;
  1785. if (ssh->start_time < 1)
  1786. /* this will produce a NaN in the output. -cjr */
  1787. total_time = 0;
  1788. else
  1789. total_time = monotime_double() - ssh->start_time;
  1790. logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
  1791. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
  1792. ssh->stdin_bytes, ssh->fdout_bytes, total_time,
  1793. ssh->stdin_bytes / total_time,
  1794. ssh->fdout_bytes / total_time);
  1795. }
  1796. /*
  1797. * Logs the error plus constructs and sends a disconnect packet, closes the
  1798. * connection, and exits. This function never returns. The error message
  1799. * should not contain a newline. The length of the formatted message must
  1800. * not exceed 1024 bytes.
  1801. */
  1802. void
  1803. ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
  1804. {
  1805. char buf[1024], remote_id[512];
  1806. va_list args;
  1807. static int disconnecting = 0;
  1808. int r;
  1809. if (disconnecting) /* Guard against recursive invocations. */
  1810. fatal("packet_disconnect called recursively.");
  1811. disconnecting = 1;
  1812. /*
  1813. * Format the message. Note that the caller must make sure the
  1814. * message is of limited size.
  1815. */
  1816. sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
  1817. va_start(args, fmt);
  1818. vsnprintf(buf, sizeof(buf), fmt, args);
  1819. va_end(args);
  1820. /* Display the error locally */
  1821. logit("Disconnecting %s: %.100s", remote_id, buf);
  1822. /*
  1823. * Send the disconnect message to the other side, and wait
  1824. * for it to get sent.
  1825. */
  1826. if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
  1827. sshpkt_fatal(ssh, r, "%s", __func__);
  1828. if ((r = ssh_packet_write_wait(ssh)) != 0)
  1829. sshpkt_fatal(ssh, r, "%s", __func__);
  1830. /* Close the connection. */
  1831. ssh_packet_close(ssh);
  1832. cleanup_exit(255);
  1833. }
  1834. /*
  1835. * Checks if there is any buffered output, and tries to write some of
  1836. * the output.
  1837. */
  1838. int
  1839. ssh_packet_write_poll(struct ssh *ssh)
  1840. {
  1841. struct session_state *state = ssh->state;
  1842. int len = sshbuf_len(state->output);
  1843. int r;
  1844. if (len > 0) {
  1845. len = write(state->connection_out,
  1846. sshbuf_ptr(state->output), len);
  1847. if (len == -1) {
  1848. if (errno == EINTR || errno == EAGAIN ||
  1849. errno == EWOULDBLOCK)
  1850. return 0;
  1851. return SSH_ERR_SYSTEM_ERROR;
  1852. }
  1853. if (len == 0)
  1854. return SSH_ERR_CONN_CLOSED;
  1855. if ((r = sshbuf_consume(state->output, len)) != 0)
  1856. return r;
  1857. }
  1858. return 0;
  1859. }
  1860. /*
  1861. * Calls packet_write_poll repeatedly until all pending output data has been
  1862. * written.
  1863. */
  1864. int
  1865. ssh_packet_write_wait(struct ssh *ssh)
  1866. {
  1867. fd_set *setp;
  1868. int ret, r, ms_remain = 0;
  1869. struct timeval start, timeout, *timeoutp = NULL;
  1870. struct session_state *state = ssh->state;
  1871. setp = calloc(howmany(state->connection_out + 1,
  1872. NFDBITS), sizeof(fd_mask));
  1873. if (setp == NULL)
  1874. return SSH_ERR_ALLOC_FAIL;
  1875. if ((r = ssh_packet_write_poll(ssh)) != 0) {
  1876. free(setp);
  1877. return r;
  1878. }
  1879. while (ssh_packet_have_data_to_write(ssh)) {
  1880. memset(setp, 0, howmany(state->connection_out + 1,
  1881. NFDBITS) * sizeof(fd_mask));
  1882. FD_SET(state->connection_out, setp);
  1883. if (state->packet_timeout_ms > 0) {
  1884. ms_remain = state->packet_timeout_ms;
  1885. timeoutp = &timeout;
  1886. }
  1887. for (;;) {
  1888. if (state->packet_timeout_ms > 0) {
  1889. ms_to_timeval(&timeout, ms_remain);
  1890. monotime_tv(&start);
  1891. }
  1892. if ((ret = select(state->connection_out + 1,
  1893. NULL, setp, NULL, timeoutp)) >= 0)
  1894. break;
  1895. if (errno != EAGAIN && errno != EINTR &&
  1896. errno != EWOULDBLOCK)
  1897. break;
  1898. if (state->packet_timeout_ms <= 0)
  1899. continue;
  1900. ms_subtract_diff(&start, &ms_remain);
  1901. if (ms_remain <= 0) {
  1902. ret = 0;
  1903. break;
  1904. }
  1905. }
  1906. if (ret == 0) {
  1907. free(setp);
  1908. return SSH_ERR_CONN_TIMEOUT;
  1909. }
  1910. if ((r = ssh_packet_write_poll(ssh)) != 0) {
  1911. free(setp);
  1912. return r;
  1913. }
  1914. }
  1915. free(setp);
  1916. return 0;
  1917. }
  1918. /* Returns true if there is buffered data to write to the connection. */
  1919. int
  1920. ssh_packet_have_data_to_write(struct ssh *ssh)
  1921. {
  1922. return sshbuf_len(ssh->state->output) != 0;
  1923. }
  1924. /* Returns true if there is not too much data to write to the connection. */
  1925. int
  1926. ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
  1927. {
  1928. if (ssh->state->interactive_mode)
  1929. return sshbuf_len(ssh->state->output) < 16384;
  1930. else
  1931. return sshbuf_len(ssh->state->output) < 128 * 1024;
  1932. }
  1933. void
  1934. ssh_packet_set_tos(struct ssh *ssh, int tos)
  1935. {
  1936. #ifndef IP_TOS_IS_BROKEN
  1937. if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
  1938. return;
  1939. switch (ssh_packet_connection_af(ssh)) {
  1940. # ifdef IP_TOS
  1941. case AF_INET:
  1942. debug3("%s: set IP_TOS 0x%02x", __func__, tos);
  1943. if (setsockopt(ssh->state->connection_in,
  1944. IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) == -1)
  1945. error("setsockopt IP_TOS %d: %.100s:",
  1946. tos, strerror(errno));
  1947. break;
  1948. # endif /* IP_TOS */
  1949. # ifdef IPV6_TCLASS
  1950. case AF_INET6:
  1951. debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
  1952. if (setsockopt(ssh->state->connection_in,
  1953. IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) == -1)
  1954. error("setsockopt IPV6_TCLASS %d: %.100s:",
  1955. tos, strerror(errno));
  1956. break;
  1957. # endif /* IPV6_TCLASS */
  1958. }
  1959. #endif /* IP_TOS_IS_BROKEN */
  1960. }
  1961. /* Informs that the current session is interactive. Sets IP flags for that. */
  1962. void
  1963. ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
  1964. {
  1965. struct session_state *state = ssh->state;
  1966. if (state->set_interactive_called)
  1967. return;
  1968. state->set_interactive_called = 1;
  1969. /* Record that we are in interactive mode. */
  1970. state->interactive_mode = interactive;
  1971. /* Only set socket options if using a socket. */
  1972. if (!ssh_packet_connection_is_on_socket(ssh))
  1973. return;
  1974. set_nodelay(state->connection_in);
  1975. ssh_packet_set_tos(ssh, interactive ? qos_interactive :
  1976. qos_bulk);
  1977. }
  1978. /* Returns true if the current connection is interactive. */
  1979. int
  1980. ssh_packet_is_interactive(struct ssh *ssh)
  1981. {
  1982. return ssh->state->interactive_mode;
  1983. }
  1984. int
  1985. ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
  1986. {
  1987. struct session_state *state = ssh->state;
  1988. if (state->set_maxsize_called) {
  1989. logit("packet_set_maxsize: called twice: old %d new %d",
  1990. state->max_packet_size, s);
  1991. return -1;
  1992. }
  1993. if (s < 4 * 1024 || s > 1024 * 1024) {
  1994. logit("packet_set_maxsize: bad size %d", s);
  1995. return -1;
  1996. }
  1997. state->set_maxsize_called = 1;
  1998. debug("packet_set_maxsize: setting to %d", s);
  1999. state->max_packet_size = s;
  2000. return s;
  2001. }
  2002. int
  2003. ssh_packet_inc_alive_timeouts(struct ssh *ssh)
  2004. {
  2005. return ++ssh->state->keep_alive_timeouts;
  2006. }
  2007. void
  2008. ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
  2009. {
  2010. ssh->state->keep_alive_timeouts = ka;
  2011. }
  2012. u_int
  2013. ssh_packet_get_maxsize(struct ssh *ssh)
  2014. {
  2015. return ssh->state->max_packet_size;
  2016. }
  2017. void
  2018. ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
  2019. {
  2020. debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
  2021. (unsigned int)seconds);
  2022. ssh->state->rekey_limit = bytes;
  2023. ssh->state->rekey_interval = seconds;
  2024. }
  2025. time_t
  2026. ssh_packet_get_rekey_timeout(struct ssh *ssh)
  2027. {
  2028. time_t seconds;
  2029. seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
  2030. monotime();
  2031. return (seconds <= 0 ? 1 : seconds);
  2032. }
  2033. void
  2034. ssh_packet_set_server(struct ssh *ssh)
  2035. {
  2036. ssh->state->server_side = 1;
  2037. ssh->kex->server = 1; /* XXX unify? */
  2038. }
  2039. void
  2040. ssh_packet_set_authenticated(struct ssh *ssh)
  2041. {
  2042. ssh->state->after_authentication = 1;
  2043. }
  2044. void *
  2045. ssh_packet_get_input(struct ssh *ssh)
  2046. {
  2047. return (void *)ssh->state->input;
  2048. }
  2049. void *
  2050. ssh_packet_get_output(struct ssh *ssh)
  2051. {
  2052. return (void *)ssh->state->output;
  2053. }
  2054. static void
  2055. newkeys_destroy_and_free(struct newkeys *newkeys)
  2056. {
  2057. if (newkeys == NULL)
  2058. return;
  2059. free(newkeys->enc.name);
  2060. if (newkeys->mac.enabled) {
  2061. mac_clear(&newkeys->mac);
  2062. free(newkeys->mac.name);
  2063. }
  2064. free(newkeys->comp.name);
  2065. newkeys_destroy(newkeys);
  2066. free(newkeys);
  2067. }
  2068. static void
  2069. packet_destroy_state(struct session_state *state)
  2070. {
  2071. if (state == NULL)
  2072. return;
  2073. cipher_free(state->receive_context);
  2074. cipher_free(state->send_context);
  2075. state->send_context = state->receive_context = NULL;
  2076. sshbuf_free(state->input);
  2077. state->input = NULL;
  2078. sshbuf_free(state->output);
  2079. state->output = NULL;
  2080. sshbuf_free(state->outgoing_packet);
  2081. state->outgoing_packet = NULL;
  2082. sshbuf_free(state->incoming_packet);
  2083. state->incoming_packet = NULL;
  2084. if (state->compression_buffer) {
  2085. sshbuf_free(state->compression_buffer);
  2086. state->compression_buffer = NULL;
  2087. }
  2088. newkeys_destroy_and_free(state->newkeys[MODE_IN]);
  2089. state->newkeys[MODE_IN] = NULL;
  2090. newkeys_destroy_and_free(state->newkeys[MODE_OUT]);
  2091. state->newkeys[MODE_OUT] = NULL;
  2092. mac_destroy(state->packet_discard_mac);
  2093. // TAILQ_HEAD(, packet) outgoing;
  2094. // memset(state, 0, sizeof(state));
  2095. }
  2096. void
  2097. packet_destroy_all(struct ssh *ssh, int audit_it, int privsep)
  2098. {
  2099. if (audit_it)
  2100. audit_it = packet_state_has_keys(ssh->state);
  2101. packet_destroy_state(ssh->state);
  2102. if (audit_it) {
  2103. #ifdef SSH_AUDIT_EVENTS
  2104. if (privsep)
  2105. audit_session_key_free(ssh, MODE_MAX);
  2106. else
  2107. audit_session_key_free_body(ssh, MODE_MAX, getpid(), getuid());
  2108. #endif
  2109. }
  2110. }
  2111. /* Reset after_authentication and reset compression in post-auth privsep */
  2112. static int
  2113. ssh_packet_set_postauth(struct ssh *ssh)
  2114. {
  2115. int r;
  2116. debug("%s: called", __func__);
  2117. /* This was set in net child, but is not visible in user child */
  2118. ssh->state->after_authentication = 1;
  2119. ssh->state->rekeying = 0;
  2120. if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
  2121. return r;
  2122. return 0;
  2123. }
  2124. /* Packet state (de-)serialization for privsep */
  2125. /* turn kex into a blob for packet state serialization */
  2126. static int
  2127. kex_to_blob(struct sshbuf *m, struct kex *kex)
  2128. {
  2129. int r;
  2130. if ((r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
  2131. (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
  2132. (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
  2133. (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
  2134. (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
  2135. (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
  2136. (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
  2137. (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
  2138. (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
  2139. (r = sshbuf_put_stringb(m, kex->session_id)) != 0 ||
  2140. (r = sshbuf_put_u32(m, kex->flags)) != 0)
  2141. return r;
  2142. return 0;
  2143. }
  2144. /* turn key exchange results into a blob for packet state serialization */
  2145. static int
  2146. newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
  2147. {
  2148. struct sshbuf *b;
  2149. struct sshcipher_ctx *cc;
  2150. struct sshcomp *comp;
  2151. struct sshenc *enc;
  2152. struct sshmac *mac;
  2153. struct newkeys *newkey;
  2154. int r;
  2155. if ((newkey = ssh->state->newkeys[mode]) == NULL)
  2156. return SSH_ERR_INTERNAL_ERROR;
  2157. enc = &newkey->enc;
  2158. mac = &newkey->mac;
  2159. comp = &newkey->comp;
  2160. cc = (mode == MODE_OUT) ? ssh->state->send_context :
  2161. ssh->state->receive_context;
  2162. if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
  2163. return r;
  2164. if ((b = sshbuf_new()) == NULL)
  2165. return SSH_ERR_ALLOC_FAIL;
  2166. if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
  2167. (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
  2168. (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
  2169. (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
  2170. (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
  2171. goto out;
  2172. if (cipher_authlen(enc->cipher) == 0) {
  2173. if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
  2174. (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
  2175. (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
  2176. goto out;
  2177. }
  2178. if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
  2179. (r = sshbuf_put_cstring(b, comp->name)) != 0)
  2180. goto out;
  2181. r = sshbuf_put_stringb(m, b);
  2182. out:
  2183. sshbuf_free(b);
  2184. return r;
  2185. }
  2186. /* serialize packet state into a blob */
  2187. int
  2188. ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
  2189. {
  2190. struct session_state *state = ssh->state;
  2191. int r;
  2192. if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
  2193. (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
  2194. (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
  2195. (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
  2196. (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
  2197. (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
  2198. (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
  2199. (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
  2200. (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
  2201. (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
  2202. (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
  2203. (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
  2204. (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
  2205. (r = sshbuf_put_stringb(m, state->input)) != 0 ||
  2206. (r = sshbuf_put_stringb(m, state->output)) != 0)
  2207. return r;
  2208. return 0;
  2209. }
  2210. /* restore key exchange results from blob for packet state de-serialization */
  2211. static int
  2212. newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
  2213. {
  2214. struct sshbuf *b = NULL;
  2215. struct sshcomp *comp;
  2216. struct sshenc *enc;
  2217. struct sshmac *mac;
  2218. struct newkeys *newkey = NULL;
  2219. size_t keylen, ivlen, maclen;
  2220. int r;
  2221. if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
  2222. r = SSH_ERR_ALLOC_FAIL;
  2223. goto out;
  2224. }
  2225. if ((r = sshbuf_froms(m, &b)) != 0)
  2226. goto out;
  2227. #ifdef DEBUG_PK
  2228. sshbuf_dump(b, stderr);
  2229. #endif
  2230. enc = &newkey->enc;
  2231. mac = &newkey->mac;
  2232. comp = &newkey->comp;
  2233. if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
  2234. (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
  2235. (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
  2236. (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
  2237. (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
  2238. goto out;
  2239. if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
  2240. r = SSH_ERR_INVALID_FORMAT;
  2241. goto out;
  2242. }
  2243. if (cipher_authlen(enc->cipher) == 0) {
  2244. if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
  2245. goto out;
  2246. if ((r = mac_setup(mac, mac->name)) != 0)
  2247. goto out;
  2248. if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
  2249. (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
  2250. goto out;
  2251. if (maclen > mac->key_len) {
  2252. r = SSH_ERR_INVALID_FORMAT;
  2253. goto out;
  2254. }
  2255. mac->key_len = maclen;
  2256. }
  2257. if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
  2258. (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
  2259. goto out;
  2260. if (sshbuf_len(b) != 0) {
  2261. r = SSH_ERR_INVALID_FORMAT;
  2262. goto out;
  2263. }
  2264. enc->key_len = keylen;
  2265. enc->iv_len = ivlen;
  2266. ssh->kex->newkeys[mode] = newkey;
  2267. newkey = NULL;
  2268. r = 0;
  2269. out:
  2270. free(newkey);
  2271. sshbuf_free(b);
  2272. return r;
  2273. }
  2274. /* restore kex from blob for packet state de-serialization */
  2275. static int
  2276. kex_from_blob(struct sshbuf *m, struct kex **kexp)
  2277. {
  2278. struct kex *kex;
  2279. int r;
  2280. if ((kex = kex_new()) == NULL)
  2281. return SSH_ERR_ALLOC_FAIL;
  2282. if ((r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
  2283. (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
  2284. (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
  2285. (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
  2286. (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
  2287. (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
  2288. (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
  2289. (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
  2290. (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
  2291. (r = sshbuf_get_stringb(m, kex->session_id)) != 0 ||
  2292. (r = sshbuf_get_u32(m, &kex->flags)) != 0)
  2293. goto out;
  2294. kex->server = 1;
  2295. kex->done = 1;
  2296. r = 0;
  2297. out:
  2298. if (r != 0 || kexp == NULL) {
  2299. kex_free(kex);
  2300. if (kexp != NULL)
  2301. *kexp = NULL;
  2302. } else {
  2303. kex_free(*kexp);
  2304. *kexp = kex;
  2305. }
  2306. return r;
  2307. }
  2308. /*
  2309. * Restore packet state from content of blob 'm' (de-serialization).
  2310. * Note that 'm' will be partially consumed on parsing or any other errors.
  2311. */
  2312. int
  2313. ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
  2314. {
  2315. struct session_state *state = ssh->state;
  2316. const u_char *input, *output;
  2317. size_t ilen, olen;
  2318. int r;
  2319. if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
  2320. (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
  2321. (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
  2322. (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
  2323. (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
  2324. (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
  2325. (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
  2326. (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
  2327. (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
  2328. (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
  2329. (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
  2330. (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
  2331. (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
  2332. return r;
  2333. /*
  2334. * We set the time here so that in post-auth privsep child we
  2335. * count from the completion of the authentication.
  2336. */
  2337. state->rekey_time = monotime();
  2338. /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
  2339. if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
  2340. (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
  2341. return r;
  2342. if ((r = ssh_packet_set_postauth(ssh)) != 0)
  2343. return r;
  2344. sshbuf_reset(state->input);
  2345. sshbuf_reset(state->output);
  2346. if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
  2347. (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
  2348. (r = sshbuf_put(state->input, input, ilen)) != 0 ||
  2349. (r = sshbuf_put(state->output, output, olen)) != 0)
  2350. return r;
  2351. if (sshbuf_len(m))
  2352. return SSH_ERR_INVALID_FORMAT;
  2353. debug3("%s: done", __func__);
  2354. return 0;
  2355. }
  2356. /* NEW API */
  2357. /* put data to the outgoing packet */
  2358. int
  2359. sshpkt_put(struct ssh *ssh, const void *v, size_t len)
  2360. {
  2361. return sshbuf_put(ssh->state->outgoing_packet, v, len);
  2362. }
  2363. int
  2364. sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
  2365. {
  2366. return sshbuf_putb(ssh->state->outgoing_packet, b);
  2367. }
  2368. int
  2369. sshpkt_put_u8(struct ssh *ssh, u_char val)
  2370. {
  2371. return sshbuf_put_u8(ssh->state->outgoing_packet, val);
  2372. }
  2373. int
  2374. sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
  2375. {
  2376. return sshbuf_put_u32(ssh->state->outgoing_packet, val);
  2377. }
  2378. int
  2379. sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
  2380. {
  2381. return sshbuf_put_u64(ssh->state->outgoing_packet, val);
  2382. }
  2383. int
  2384. sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
  2385. {
  2386. return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
  2387. }
  2388. int
  2389. sshpkt_put_cstring(struct ssh *ssh, const void *v)
  2390. {
  2391. return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
  2392. }
  2393. int
  2394. sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
  2395. {
  2396. return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
  2397. }
  2398. int
  2399. sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
  2400. {
  2401. return sshbuf_froms(ssh->state->incoming_packet, valp);
  2402. }
  2403. #ifdef WITH_OPENSSL
  2404. #ifdef OPENSSL_HAS_ECC
  2405. int
  2406. sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
  2407. {
  2408. return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
  2409. }
  2410. #endif /* OPENSSL_HAS_ECC */
  2411. int
  2412. sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
  2413. {
  2414. return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
  2415. }
  2416. #endif /* WITH_OPENSSL */
  2417. /* fetch data from the incoming packet */
  2418. int
  2419. sshpkt_get(struct ssh *ssh, void *valp, size_t len)
  2420. {
  2421. return sshbuf_get(ssh->state->incoming_packet, valp, len);
  2422. }
  2423. int
  2424. sshpkt_get_u8(struct ssh *ssh, u_char *valp)
  2425. {
  2426. return sshbuf_get_u8(ssh->state->incoming_packet, valp);
  2427. }
  2428. int
  2429. sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
  2430. {
  2431. return sshbuf_get_u32(ssh->state->incoming_packet, valp);
  2432. }
  2433. int
  2434. sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
  2435. {
  2436. return sshbuf_get_u64(ssh->state->incoming_packet, valp);
  2437. }
  2438. int
  2439. sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
  2440. {
  2441. return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
  2442. }
  2443. int
  2444. sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
  2445. {
  2446. return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
  2447. }
  2448. int
  2449. sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
  2450. {
  2451. return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
  2452. }
  2453. int
  2454. sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
  2455. {
  2456. return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
  2457. }
  2458. #ifdef WITH_OPENSSL
  2459. #ifdef OPENSSL_HAS_ECC
  2460. int
  2461. sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
  2462. {
  2463. return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
  2464. }
  2465. #endif /* OPENSSL_HAS_ECC */
  2466. int
  2467. sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
  2468. {
  2469. return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
  2470. }
  2471. #endif /* WITH_OPENSSL */
  2472. int
  2473. sshpkt_get_end(struct ssh *ssh)
  2474. {
  2475. if (sshbuf_len(ssh->state->incoming_packet) > 0)
  2476. return SSH_ERR_UNEXPECTED_TRAILING_DATA;
  2477. return 0;
  2478. }
  2479. const u_char *
  2480. sshpkt_ptr(struct ssh *ssh, size_t *lenp)
  2481. {
  2482. if (lenp != NULL)
  2483. *lenp = sshbuf_len(ssh->state->incoming_packet);
  2484. return sshbuf_ptr(ssh->state->incoming_packet);
  2485. }
  2486. /* start a new packet */
  2487. int
  2488. sshpkt_start(struct ssh *ssh, u_char type)
  2489. {
  2490. u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
  2491. DBG(debug("packet_start[%d]", type));
  2492. memset(buf, 0, sizeof(buf));
  2493. buf[sizeof(buf) - 1] = type;
  2494. sshbuf_reset(ssh->state->outgoing_packet);
  2495. return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
  2496. }
  2497. static int
  2498. ssh_packet_send_mux(struct ssh *ssh)
  2499. {
  2500. struct session_state *state = ssh->state;
  2501. u_char type, *cp;
  2502. size_t len;
  2503. int r;
  2504. if (ssh->kex)
  2505. return SSH_ERR_INTERNAL_ERROR;
  2506. len = sshbuf_len(state->outgoing_packet);
  2507. if (len < 6)
  2508. return SSH_ERR_INTERNAL_ERROR;
  2509. cp = sshbuf_mutable_ptr(state->outgoing_packet);
  2510. type = cp[5];
  2511. if (ssh_packet_log_type(type))
  2512. debug3("%s: type %u", __func__, type);
  2513. /* drop everything, but the connection protocol */
  2514. if (type >= SSH2_MSG_CONNECTION_MIN &&
  2515. type <= SSH2_MSG_CONNECTION_MAX) {
  2516. POKE_U32(cp, len - 4);
  2517. if ((r = sshbuf_putb(state->output,
  2518. state->outgoing_packet)) != 0)
  2519. return r;
  2520. /* sshbuf_dump(state->output, stderr); */
  2521. }
  2522. sshbuf_reset(state->outgoing_packet);
  2523. return 0;
  2524. }
  2525. /*
  2526. * 9.2. Ignored Data Message
  2527. *
  2528. * byte SSH_MSG_IGNORE
  2529. * string data
  2530. *
  2531. * All implementations MUST understand (and ignore) this message at any
  2532. * time (after receiving the protocol version). No implementation is
  2533. * required to send them. This message can be used as an additional
  2534. * protection measure against advanced traffic analysis techniques.
  2535. */
  2536. int
  2537. sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
  2538. {
  2539. u_int32_t rnd = 0;
  2540. int r;
  2541. u_int i;
  2542. if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
  2543. (r = sshpkt_put_u32(ssh, nbytes)) != 0)
  2544. return r;
  2545. for (i = 0; i < nbytes; i++) {
  2546. if (i % 4 == 0)
  2547. rnd = arc4random();
  2548. if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
  2549. return r;
  2550. rnd >>= 8;
  2551. }
  2552. return 0;
  2553. }
  2554. /* send it */
  2555. int
  2556. sshpkt_send(struct ssh *ssh)
  2557. {
  2558. if (ssh->state && ssh->state->mux)
  2559. return ssh_packet_send_mux(ssh);
  2560. return ssh_packet_send2(ssh);
  2561. }
  2562. int
  2563. sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
  2564. {
  2565. char buf[1024];
  2566. va_list args;
  2567. int r;
  2568. va_start(args, fmt);
  2569. vsnprintf(buf, sizeof(buf), fmt, args);
  2570. va_end(args);
  2571. if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
  2572. (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
  2573. (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
  2574. (r = sshpkt_put_cstring(ssh, "")) != 0 ||
  2575. (r = sshpkt_send(ssh)) != 0)
  2576. return r;
  2577. return 0;
  2578. }
  2579. /* roundup current message to pad bytes */
  2580. int
  2581. sshpkt_add_padding(struct ssh *ssh, u_char pad)
  2582. {
  2583. ssh->state->extra_pad = pad;
  2584. return 0;
  2585. }
  2586. /* need this for the moment for the aes-ctr cipher */
  2587. void *
  2588. ssh_packet_get_send_context(struct ssh *ssh)
  2589. {
  2590. return ssh->state->send_context;
  2591. }