sshd.c 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664
  1. /* $OpenBSD: sshd.c,v 1.561 2020/08/27 01:06:19 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 program is the ssh daemon. It listens for connections from clients,
  7. * and performs authentication, executes use commands or shell, and forwards
  8. * information to/from the application to the user client over an encrypted
  9. * connection. This can also handle forwarding of X11, TCP/IP, and
  10. * authentication agent connections.
  11. *
  12. * As far as I am concerned, the code I have written for this software
  13. * can be used freely for any purpose. Any derived versions of this
  14. * software must be clearly marked as such, and if the derived work is
  15. * incompatible with the protocol description in the RFC file, it must be
  16. * called by a name other than "ssh" or "Secure Shell".
  17. *
  18. * SSH2 implementation:
  19. * Privilege Separation:
  20. *
  21. * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
  22. * Copyright (c) 2002 Niels Provos. All rights reserved.
  23. *
  24. * Redistribution and use in source and binary forms, with or without
  25. * modification, are permitted provided that the following conditions
  26. * are met:
  27. * 1. Redistributions of source code must retain the above copyright
  28. * notice, this list of conditions and the following disclaimer.
  29. * 2. Redistributions in binary form must reproduce the above copyright
  30. * notice, this list of conditions and the following disclaimer in the
  31. * documentation and/or other materials provided with the distribution.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  34. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  36. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  37. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  39. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  40. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  41. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  42. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. #include "includes.h"
  45. #include <sys/types.h>
  46. #include <sys/ioctl.h>
  47. #include <sys/socket.h>
  48. #ifdef HAVE_SYS_STAT_H
  49. # include <sys/stat.h>
  50. #endif
  51. #ifdef HAVE_SYS_TIME_H
  52. # include <sys/time.h>
  53. #endif
  54. #include "openbsd-compat/sys-tree.h"
  55. #include "openbsd-compat/sys-queue.h"
  56. #include <sys/wait.h>
  57. #include <errno.h>
  58. #include <fcntl.h>
  59. #include <netdb.h>
  60. #ifdef HAVE_PATHS_H
  61. #include <paths.h>
  62. #endif
  63. #include <grp.h>
  64. #include <pwd.h>
  65. #include <signal.h>
  66. #include <stdarg.h>
  67. #include <stdio.h>
  68. #include <stdlib.h>
  69. #include <string.h>
  70. #include <unistd.h>
  71. #include <limits.h>
  72. #ifdef WITH_OPENSSL
  73. #include <openssl/dh.h>
  74. #include <openssl/bn.h>
  75. #include <openssl/rand.h>
  76. #include "openbsd-compat/openssl-compat.h"
  77. #endif
  78. #ifdef HAVE_SECUREWARE
  79. #include <sys/security.h>
  80. #include <prot.h>
  81. #endif
  82. #ifdef HAVE_SYSTEMD
  83. #include <systemd/sd-daemon.h>
  84. #endif
  85. #include "xmalloc.h"
  86. #include "ssh.h"
  87. #include "ssh2.h"
  88. #include "sshpty.h"
  89. #include "packet.h"
  90. #include "log.h"
  91. #include "sshbuf.h"
  92. #include "misc.h"
  93. #include "match.h"
  94. #include "servconf.h"
  95. #include "uidswap.h"
  96. #include "compat.h"
  97. #include "cipher.h"
  98. #include "digest.h"
  99. #include "sshkey.h"
  100. #include "kex.h"
  101. #include "myproposal.h"
  102. #include "authfile.h"
  103. #include "pathnames.h"
  104. #include "atomicio.h"
  105. #include "canohost.h"
  106. #include "hostfile.h"
  107. #include "auth.h"
  108. #include "authfd.h"
  109. #include "msg.h"
  110. #include "dispatch.h"
  111. #include "channels.h"
  112. #include "session.h"
  113. #include "monitor.h"
  114. #ifdef GSSAPI
  115. #include "ssh-gss.h"
  116. #endif
  117. #include "monitor_wrap.h"
  118. #include "audit.h"
  119. #include "ssh-sandbox.h"
  120. #include "auth-options.h"
  121. #include "version.h"
  122. #include "ssherr.h"
  123. #include "sk-api.h"
  124. #include "srclimit.h"
  125. #ifdef LIBWRAP
  126. #include <tcpd.h>
  127. #include <syslog.h>
  128. int allow_severity;
  129. int deny_severity;
  130. #endif /* LIBWRAP */
  131. /* Re-exec fds */
  132. #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
  133. #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
  134. #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
  135. #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
  136. extern char *__progname;
  137. /* Server configuration options. */
  138. ServerOptions options;
  139. /* Name of the server configuration file. */
  140. char *config_file_name = _PATH_SERVER_CONFIG_FILE;
  141. /*
  142. * Debug mode flag. This can be set on the command line. If debug
  143. * mode is enabled, extra debugging output will be sent to the system
  144. * log, the daemon will not go to background, and will exit after processing
  145. * the first connection.
  146. */
  147. int debug_flag = 0;
  148. /*
  149. * Indicating that the daemon should only test the configuration and keys.
  150. * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
  151. * configuration, optionally using connection information provided by the
  152. * "-C" flag.
  153. */
  154. static int test_flag = 0;
  155. /* Flag indicating that the daemon is being started from inetd. */
  156. static int inetd_flag = 0;
  157. /* Flag indicating that sshd should not detach and become a daemon. */
  158. static int no_daemon_flag = 0;
  159. /* debug goes to stderr unless inetd_flag is set */
  160. static int log_stderr = 0;
  161. /* Saved arguments to main(). */
  162. static char **saved_argv;
  163. static int saved_argc;
  164. /* re-exec */
  165. static int rexeced_flag = 0;
  166. static int rexec_flag = 1;
  167. static int rexec_argc = 0;
  168. static char **rexec_argv;
  169. /*
  170. * The sockets that the server is listening; this is used in the SIGHUP
  171. * signal handler.
  172. */
  173. #define MAX_LISTEN_SOCKS 16
  174. static int listen_socks[MAX_LISTEN_SOCKS];
  175. static int num_listen_socks = 0;
  176. /* Daemon's agent connection */
  177. int auth_sock = -1;
  178. static int have_agent = 0;
  179. /*
  180. * Any really sensitive data in the application is contained in this
  181. * structure. The idea is that this structure could be locked into memory so
  182. * that the pages do not get written into swap. However, there are some
  183. * problems. The private key contains BIGNUMs, and we do not (in principle)
  184. * have access to the internals of them, and locking just the structure is
  185. * not very useful. Currently, memory locking is not implemented.
  186. */
  187. struct {
  188. struct sshkey **host_keys; /* all private host keys */
  189. struct sshkey **host_pubkeys; /* all public host keys */
  190. struct sshkey **host_certificates; /* all public host certificates */
  191. int have_ssh2_key;
  192. } sensitive_data;
  193. /* This is set to true when a signal is received. */
  194. static volatile sig_atomic_t received_sighup = 0;
  195. static volatile sig_atomic_t received_sigterm = 0;
  196. /* record remote hostname or ip */
  197. u_int utmp_len = HOST_NAME_MAX+1;
  198. /*
  199. * startup_pipes/flags are used for tracking children of the listening sshd
  200. * process early in their lifespans. This tracking is needed for three things:
  201. *
  202. * 1) Implementing the MaxStartups limit of concurrent unauthenticated
  203. * connections.
  204. * 2) Avoiding a race condition for SIGHUP processing, where child processes
  205. * may have listen_socks open that could collide with main listener process
  206. * after it restarts.
  207. * 3) Ensuring that rexec'd sshd processes have received their initial state
  208. * from the parent listen process before handling SIGHUP.
  209. *
  210. * Child processes signal that they have completed closure of the listen_socks
  211. * and (if applicable) received their rexec state by sending a char over their
  212. * sock. Child processes signal that authentication has completed by closing
  213. * the sock (or by exiting).
  214. */
  215. static int *startup_pipes = NULL;
  216. static int *startup_flags = NULL; /* Indicates child closed listener */
  217. static int startup_pipe = -1; /* in child */
  218. /* variables used for privilege separation */
  219. int use_privsep = -1;
  220. struct monitor *pmonitor = NULL;
  221. int privsep_is_preauth = 1;
  222. static int privsep_chroot = 1;
  223. /* global connection state and authentication contexts */
  224. Authctxt *the_authctxt = NULL;
  225. struct ssh *the_active_state;
  226. /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
  227. struct sshauthopt *auth_opts = NULL;
  228. /* sshd_config buffer */
  229. struct sshbuf *cfg;
  230. /* Included files from the configuration file */
  231. struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
  232. /* message to be displayed after login */
  233. struct sshbuf *loginmsg;
  234. /* Unprivileged user */
  235. struct passwd *privsep_pw = NULL;
  236. /* Prototypes for various functions defined later in this file. */
  237. void destroy_sensitive_data(struct ssh *, int);
  238. void demote_sensitive_data(struct ssh *);
  239. static void do_ssh2_kex(struct ssh *);
  240. static char *listener_proctitle;
  241. /*
  242. * Close all listening sockets
  243. */
  244. static void
  245. close_listen_socks(void)
  246. {
  247. int i;
  248. for (i = 0; i < num_listen_socks; i++)
  249. close(listen_socks[i]);
  250. num_listen_socks = -1;
  251. }
  252. /*
  253. * Is this process listening for clients (i.e. not specific to any specific
  254. * client connection?)
  255. */
  256. int listening_for_clients(void)
  257. {
  258. return num_listen_socks >= 0;
  259. }
  260. static void
  261. close_startup_pipes(void)
  262. {
  263. int i;
  264. if (startup_pipes)
  265. for (i = 0; i < options.max_startups; i++)
  266. if (startup_pipes[i] != -1)
  267. close(startup_pipes[i]);
  268. }
  269. /*
  270. * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
  271. * the effect is to reread the configuration file (and to regenerate
  272. * the server key).
  273. */
  274. /*ARGSUSED*/
  275. static void
  276. sighup_handler(int sig)
  277. {
  278. received_sighup = 1;
  279. }
  280. /*
  281. * Called from the main program after receiving SIGHUP.
  282. * Restarts the server.
  283. */
  284. static void
  285. sighup_restart(void)
  286. {
  287. logit("Received SIGHUP; restarting.");
  288. if (options.pid_file != NULL)
  289. unlink(options.pid_file);
  290. platform_pre_restart();
  291. close_listen_socks();
  292. close_startup_pipes();
  293. ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
  294. execv(saved_argv[0], saved_argv);
  295. logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
  296. strerror(errno));
  297. exit(1);
  298. }
  299. /*
  300. * Generic signal handler for terminating signals in the master daemon.
  301. */
  302. /*ARGSUSED*/
  303. static void
  304. sigterm_handler(int sig)
  305. {
  306. received_sigterm = sig;
  307. }
  308. /*
  309. * SIGCHLD handler. This is called whenever a child dies. This will then
  310. * reap any zombies left by exited children.
  311. */
  312. /*ARGSUSED*/
  313. static void
  314. main_sigchld_handler(int sig)
  315. {
  316. int save_errno = errno;
  317. pid_t pid;
  318. int status;
  319. while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
  320. (pid == -1 && errno == EINTR))
  321. ;
  322. errno = save_errno;
  323. }
  324. /*
  325. * Signal handler for the alarm after the login grace period has expired.
  326. */
  327. /*ARGSUSED*/
  328. static void
  329. grace_alarm_handler(int sig)
  330. {
  331. if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
  332. kill(pmonitor->m_pid, SIGALRM);
  333. /*
  334. * Try to kill any processes that we have spawned, E.g. authorized
  335. * keys command helpers.
  336. */
  337. if (getpgid(0) == getpid()) {
  338. ssh_signal(SIGTERM, SIG_IGN);
  339. kill(0, SIGTERM);
  340. }
  341. /* XXX pre-format ipaddr/port so we don't need to access active_state */
  342. /* Log error and exit. */
  343. sigdie("Timeout before authentication for %s port %d",
  344. ssh_remote_ipaddr(the_active_state),
  345. ssh_remote_port(the_active_state));
  346. }
  347. /*
  348. * Destroy the host and server keys. They will no longer be needed. Careful,
  349. * this can be called from cleanup_exit() - i.e. from just about anywhere.
  350. */
  351. void
  352. destroy_sensitive_data(struct ssh *ssh, int privsep)
  353. {
  354. u_int i;
  355. #ifdef SSH_AUDIT_EVENTS
  356. pid_t pid;
  357. uid_t uid;
  358. pid = getpid();
  359. uid = getuid();
  360. #endif
  361. for (i = 0; i < options.num_host_key_files; i++) {
  362. if (sensitive_data.host_keys[i]) {
  363. char *fp;
  364. if (sshkey_is_private(sensitive_data.host_keys[i]))
  365. fp = sshkey_fingerprint(sensitive_data.host_keys[i], options.fingerprint_hash, SSH_FP_HEX);
  366. else
  367. fp = NULL;
  368. sshkey_free(sensitive_data.host_keys[i]);
  369. sensitive_data.host_keys[i] = NULL;
  370. if (fp != NULL) {
  371. #ifdef SSH_AUDIT_EVENTS
  372. if (privsep)
  373. PRIVSEP(audit_destroy_sensitive_data(ssh, fp,
  374. pid, uid));
  375. else
  376. audit_destroy_sensitive_data(ssh, fp,
  377. pid, uid);
  378. #endif
  379. free(fp);
  380. }
  381. }
  382. if (sensitive_data.host_certificates
  383. && sensitive_data.host_certificates[i]) {
  384. sshkey_free(sensitive_data.host_certificates[i]);
  385. sensitive_data.host_certificates[i] = NULL;
  386. }
  387. }
  388. }
  389. /* Demote private to public keys for network child */
  390. void
  391. demote_sensitive_data(struct ssh *ssh)
  392. {
  393. struct sshkey *tmp;
  394. u_int i;
  395. int r;
  396. #ifdef SSH_AUDIT_EVENTS
  397. pid_t pid;
  398. uid_t uid;
  399. pid = getpid();
  400. uid = getuid();
  401. #endif
  402. for (i = 0; i < options.num_host_key_files; i++) {
  403. if (sensitive_data.host_keys[i]) {
  404. char *fp;
  405. if (sshkey_is_private(sensitive_data.host_keys[i]))
  406. fp = sshkey_fingerprint(sensitive_data.host_keys[i], options.fingerprint_hash, SSH_FP_HEX);
  407. else
  408. fp = NULL;
  409. if ((r = sshkey_from_private(
  410. sensitive_data.host_keys[i], &tmp)) != 0)
  411. fatal("could not demote host %s key: %s",
  412. sshkey_type(sensitive_data.host_keys[i]),
  413. ssh_err(r));
  414. sshkey_free(sensitive_data.host_keys[i]);
  415. sensitive_data.host_keys[i] = tmp;
  416. if (fp != NULL) {
  417. #ifdef SSH_AUDIT_EVENTS
  418. audit_destroy_sensitive_data(ssh, fp, pid, uid);
  419. #endif
  420. free(fp);
  421. }
  422. }
  423. /* Certs do not need demotion */
  424. }
  425. }
  426. static void
  427. reseed_prngs(void)
  428. {
  429. u_int32_t rnd[256];
  430. #ifdef WITH_OPENSSL
  431. RAND_poll();
  432. #endif
  433. arc4random_stir(); /* noop on recent arc4random() implementations */
  434. arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
  435. #ifdef WITH_OPENSSL
  436. RAND_seed(rnd, sizeof(rnd));
  437. /* give libcrypto a chance to notice the PID change */
  438. if ((RAND_bytes((u_char *)rnd, 1)) != 1)
  439. fatal("%s: RAND_bytes failed", __func__);
  440. #endif
  441. explicit_bzero(rnd, sizeof(rnd));
  442. }
  443. static void
  444. privsep_preauth_child(struct ssh *ssh)
  445. {
  446. gid_t gidset[1];
  447. /* Enable challenge-response authentication for privilege separation */
  448. privsep_challenge_enable();
  449. #ifdef GSSAPI
  450. /* Cache supported mechanism OIDs for later use */
  451. ssh_gssapi_prepare_supported_oids();
  452. #endif
  453. reseed_prngs();
  454. /* Demote the private keys to public keys. */
  455. demote_sensitive_data(ssh);
  456. #ifdef WITH_SELINUX
  457. ssh_selinux_change_context("sshd_net_t");
  458. #endif
  459. /* Demote the child */
  460. if (privsep_chroot) {
  461. /* Change our root directory */
  462. if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
  463. fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
  464. strerror(errno));
  465. if (chdir("/") == -1)
  466. fatal("chdir(\"/\"): %s", strerror(errno));
  467. /* Drop our privileges */
  468. debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
  469. (u_int)privsep_pw->pw_gid);
  470. gidset[0] = privsep_pw->pw_gid;
  471. if (setgroups(1, gidset) == -1)
  472. fatal("setgroups: %.100s", strerror(errno));
  473. permanently_set_uid(privsep_pw);
  474. }
  475. }
  476. static int
  477. privsep_preauth(struct ssh *ssh)
  478. {
  479. int status, r;
  480. pid_t pid;
  481. struct ssh_sandbox *box = NULL;
  482. /* Set up unprivileged child process to deal with network data */
  483. pmonitor = monitor_init();
  484. /* Store a pointer to the kex for later rekeying */
  485. pmonitor->m_pkex = &ssh->kex;
  486. if (use_privsep == PRIVSEP_ON)
  487. box = ssh_sandbox_init(pmonitor);
  488. pmonitor->m_pid = pid = fork();
  489. if (pid == -1) {
  490. fatal("fork of unprivileged child failed");
  491. } else if (pid != 0) {
  492. debug2("Network child is on pid %ld", (long)pid);
  493. pmonitor->m_pid = pid;
  494. if (have_agent) {
  495. r = ssh_get_authentication_socket(&auth_sock);
  496. if (r != 0) {
  497. error("Could not get agent socket: %s",
  498. ssh_err(r));
  499. have_agent = 0;
  500. }
  501. }
  502. if (box != NULL)
  503. ssh_sandbox_parent_preauth(box, pid);
  504. monitor_child_preauth(ssh, pmonitor);
  505. /* Wait for the child's exit status */
  506. while (waitpid(pid, &status, 0) == -1) {
  507. if (errno == EINTR)
  508. continue;
  509. pmonitor->m_pid = -1;
  510. fatal("%s: waitpid: %s", __func__, strerror(errno));
  511. }
  512. privsep_is_preauth = 0;
  513. pmonitor->m_pid = -1;
  514. if (WIFEXITED(status)) {
  515. if (WEXITSTATUS(status) != 0)
  516. fatal("%s: preauth child exited with status %d",
  517. __func__, WEXITSTATUS(status));
  518. } else if (WIFSIGNALED(status))
  519. fatal("%s: preauth child terminated by signal %d",
  520. __func__, WTERMSIG(status));
  521. if (box != NULL)
  522. ssh_sandbox_parent_finish(box);
  523. return 1;
  524. } else {
  525. /* child */
  526. close(pmonitor->m_sendfd);
  527. close(pmonitor->m_log_recvfd);
  528. /* Arrange for logging to be sent to the monitor */
  529. set_log_handler(mm_log_handler, pmonitor);
  530. privsep_preauth_child(ssh);
  531. setproctitle("%s", "[net]");
  532. if (box != NULL) {
  533. ssh_sandbox_child(box);
  534. free(box);
  535. }
  536. return 0;
  537. }
  538. }
  539. static void
  540. privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
  541. {
  542. #ifdef DISABLE_FD_PASSING
  543. if (1) {
  544. #elif defined(WITH_SELINUX)
  545. if (0) {
  546. /* even root user can be confined by SELinux */
  547. #else
  548. if (authctxt->pw->pw_uid == 0) {
  549. #endif
  550. /* File descriptor passing is broken or root login */
  551. use_privsep = 0;
  552. goto skip;
  553. }
  554. /* New socket pair */
  555. monitor_reinit(pmonitor, options.chroot_directory);
  556. pmonitor->m_pid = fork();
  557. if (pmonitor->m_pid == -1)
  558. fatal("fork of unprivileged child failed");
  559. else if (pmonitor->m_pid != 0) {
  560. verbose("User child is on pid %ld", (long)pmonitor->m_pid);
  561. sshbuf_reset(loginmsg);
  562. monitor_clear_keystate(ssh, pmonitor);
  563. monitor_child_postauth(ssh, pmonitor);
  564. /* NEVERREACHED */
  565. exit(0);
  566. }
  567. /* child */
  568. close(pmonitor->m_sendfd);
  569. pmonitor->m_sendfd = -1;
  570. close(pmonitor->m_log_recvfd);
  571. pmonitor->m_log_recvfd = -1;
  572. if (pmonitor->m_log_sendfd != -1)
  573. set_log_handler(mm_log_handler, pmonitor);
  574. /* Demote the private keys to public keys. */
  575. demote_sensitive_data(ssh);
  576. reseed_prngs();
  577. /* Drop privileges */
  578. do_setusercontext(authctxt->pw);
  579. skip:
  580. /* It is safe now to apply the key state */
  581. monitor_apply_keystate(ssh, pmonitor);
  582. /*
  583. * Tell the packet layer that authentication was successful, since
  584. * this information is not part of the key state.
  585. */
  586. ssh_packet_set_authenticated(ssh);
  587. }
  588. static void
  589. append_hostkey_type(struct sshbuf *b, const char *s)
  590. {
  591. int r;
  592. if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
  593. debug3("%s: %s key not permitted by HostkeyAlgorithms",
  594. __func__, s);
  595. return;
  596. }
  597. if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
  598. fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
  599. }
  600. static char *
  601. list_hostkey_types(void)
  602. {
  603. struct sshbuf *b;
  604. struct sshkey *key;
  605. char *ret;
  606. u_int i;
  607. if ((b = sshbuf_new()) == NULL)
  608. fatal("%s: sshbuf_new failed", __func__);
  609. for (i = 0; i < options.num_host_key_files; i++) {
  610. key = sensitive_data.host_keys[i];
  611. if (key == NULL)
  612. key = sensitive_data.host_pubkeys[i];
  613. if (key == NULL)
  614. continue;
  615. switch (key->type) {
  616. case KEY_RSA:
  617. /* for RSA we also support SHA2 signatures */
  618. append_hostkey_type(b, "rsa-sha2-512");
  619. append_hostkey_type(b, "rsa-sha2-256");
  620. /* FALLTHROUGH */
  621. case KEY_DSA:
  622. case KEY_ECDSA:
  623. case KEY_ED25519:
  624. case KEY_ECDSA_SK:
  625. case KEY_ED25519_SK:
  626. case KEY_XMSS:
  627. append_hostkey_type(b, sshkey_ssh_name(key));
  628. break;
  629. }
  630. /* If the private key has a cert peer, then list that too */
  631. key = sensitive_data.host_certificates[i];
  632. if (key == NULL)
  633. continue;
  634. switch (key->type) {
  635. case KEY_RSA_CERT:
  636. /* for RSA we also support SHA2 signatures */
  637. append_hostkey_type(b,
  638. "rsa-sha2-512-cert-v01@openssh.com");
  639. append_hostkey_type(b,
  640. "rsa-sha2-256-cert-v01@openssh.com");
  641. /* FALLTHROUGH */
  642. case KEY_DSA_CERT:
  643. case KEY_ECDSA_CERT:
  644. case KEY_ED25519_CERT:
  645. case KEY_ECDSA_SK_CERT:
  646. case KEY_ED25519_SK_CERT:
  647. case KEY_XMSS_CERT:
  648. append_hostkey_type(b, sshkey_ssh_name(key));
  649. break;
  650. }
  651. }
  652. if ((ret = sshbuf_dup_string(b)) == NULL)
  653. fatal("%s: sshbuf_dup_string failed", __func__);
  654. sshbuf_free(b);
  655. debug("%s: %s", __func__, ret);
  656. return ret;
  657. }
  658. static struct sshkey *
  659. get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
  660. {
  661. u_int i;
  662. struct sshkey *key;
  663. for (i = 0; i < options.num_host_key_files; i++) {
  664. switch (type) {
  665. case KEY_RSA_CERT:
  666. case KEY_DSA_CERT:
  667. case KEY_ECDSA_CERT:
  668. case KEY_ED25519_CERT:
  669. case KEY_ECDSA_SK_CERT:
  670. case KEY_ED25519_SK_CERT:
  671. case KEY_XMSS_CERT:
  672. key = sensitive_data.host_certificates[i];
  673. break;
  674. default:
  675. key = sensitive_data.host_keys[i];
  676. if (key == NULL && !need_private)
  677. key = sensitive_data.host_pubkeys[i];
  678. break;
  679. }
  680. if (key == NULL || key->type != type)
  681. continue;
  682. switch (type) {
  683. case KEY_ECDSA:
  684. case KEY_ECDSA_SK:
  685. case KEY_ECDSA_CERT:
  686. case KEY_ECDSA_SK_CERT:
  687. if (key->ecdsa_nid != nid)
  688. continue;
  689. /* FALLTHROUGH */
  690. default:
  691. return need_private ?
  692. sensitive_data.host_keys[i] : key;
  693. }
  694. }
  695. return NULL;
  696. }
  697. struct sshkey *
  698. get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
  699. {
  700. return get_hostkey_by_type(type, nid, 0, ssh);
  701. }
  702. struct sshkey *
  703. get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
  704. {
  705. return get_hostkey_by_type(type, nid, 1, ssh);
  706. }
  707. struct sshkey *
  708. get_hostkey_by_index(int ind)
  709. {
  710. if (ind < 0 || (u_int)ind >= options.num_host_key_files)
  711. return (NULL);
  712. return (sensitive_data.host_keys[ind]);
  713. }
  714. struct sshkey *
  715. get_hostkey_public_by_index(int ind, struct ssh *ssh)
  716. {
  717. if (ind < 0 || (u_int)ind >= options.num_host_key_files)
  718. return (NULL);
  719. return (sensitive_data.host_pubkeys[ind]);
  720. }
  721. int
  722. get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
  723. {
  724. u_int i;
  725. for (i = 0; i < options.num_host_key_files; i++) {
  726. if (sshkey_is_cert(key)) {
  727. if (key == sensitive_data.host_certificates[i] ||
  728. (compare && sensitive_data.host_certificates[i] &&
  729. sshkey_equal(key,
  730. sensitive_data.host_certificates[i])))
  731. return (i);
  732. } else {
  733. if (key == sensitive_data.host_keys[i] ||
  734. (compare && sensitive_data.host_keys[i] &&
  735. sshkey_equal(key, sensitive_data.host_keys[i])))
  736. return (i);
  737. if (key == sensitive_data.host_pubkeys[i] ||
  738. (compare && sensitive_data.host_pubkeys[i] &&
  739. sshkey_equal(key, sensitive_data.host_pubkeys[i])))
  740. return (i);
  741. }
  742. }
  743. return (-1);
  744. }
  745. /* Inform the client of all hostkeys */
  746. static void
  747. notify_hostkeys(struct ssh *ssh)
  748. {
  749. struct sshbuf *buf;
  750. struct sshkey *key;
  751. u_int i, nkeys;
  752. int r;
  753. char *fp;
  754. /* Some clients cannot cope with the hostkeys message, skip those. */
  755. if (ssh->compat & SSH_BUG_HOSTKEYS)
  756. return;
  757. if ((buf = sshbuf_new()) == NULL)
  758. fatal("%s: sshbuf_new", __func__);
  759. for (i = nkeys = 0; i < options.num_host_key_files; i++) {
  760. key = get_hostkey_public_by_index(i, ssh);
  761. if (key == NULL || key->type == KEY_UNSPEC ||
  762. sshkey_is_cert(key))
  763. continue;
  764. fp = sshkey_fingerprint(key, options.fingerprint_hash,
  765. SSH_FP_DEFAULT);
  766. debug3("%s: key %d: %s %s", __func__, i,
  767. sshkey_ssh_name(key), fp);
  768. free(fp);
  769. if (nkeys == 0) {
  770. /*
  771. * Start building the request when we find the
  772. * first usable key.
  773. */
  774. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  775. (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
  776. (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
  777. sshpkt_fatal(ssh, r, "%s: start request", __func__);
  778. }
  779. /* Append the key to the request */
  780. sshbuf_reset(buf);
  781. if ((r = sshkey_putb(key, buf)) != 0)
  782. fatal("%s: couldn't put hostkey %d: %s",
  783. __func__, i, ssh_err(r));
  784. if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
  785. sshpkt_fatal(ssh, r, "%s: append key", __func__);
  786. nkeys++;
  787. }
  788. debug3("%s: sent %u hostkeys", __func__, nkeys);
  789. if (nkeys == 0)
  790. fatal("%s: no hostkeys", __func__);
  791. if ((r = sshpkt_send(ssh)) != 0)
  792. sshpkt_fatal(ssh, r, "%s: send", __func__);
  793. sshbuf_free(buf);
  794. }
  795. /*
  796. * returns 1 if connection should be dropped, 0 otherwise.
  797. * dropping starts at connection #max_startups_begin with a probability
  798. * of (max_startups_rate/100). the probability increases linearly until
  799. * all connections are dropped for startups > max_startups
  800. */
  801. static int
  802. should_drop_connection(int startups)
  803. {
  804. int p, r;
  805. if (startups < options.max_startups_begin)
  806. return 0;
  807. if (startups >= options.max_startups)
  808. return 1;
  809. if (options.max_startups_rate == 100)
  810. return 1;
  811. p = 100 - options.max_startups_rate;
  812. p *= startups - options.max_startups_begin;
  813. p /= options.max_startups - options.max_startups_begin;
  814. p += options.max_startups_rate;
  815. r = arc4random_uniform(100);
  816. debug("%s: p %d, r %d", __func__, p, r);
  817. return (r < p) ? 1 : 0;
  818. }
  819. /*
  820. * Check whether connection should be accepted by MaxStartups.
  821. * Returns 0 if the connection is accepted. If the connection is refused,
  822. * returns 1 and attempts to send notification to client.
  823. * Logs when the MaxStartups condition is entered or exited, and periodically
  824. * while in that state.
  825. */
  826. static int
  827. drop_connection(int sock, int startups, int notify_pipe)
  828. {
  829. char *laddr, *raddr;
  830. const char msg[] = "Exceeded MaxStartups\r\n";
  831. static time_t last_drop, first_drop;
  832. static u_int ndropped;
  833. LogLevel drop_level = SYSLOG_LEVEL_VERBOSE;
  834. time_t now;
  835. now = monotime();
  836. if (!should_drop_connection(startups) &&
  837. srclimit_check_allow(sock, notify_pipe) == 1) {
  838. if (last_drop != 0 &&
  839. startups < options.max_startups_begin - 1) {
  840. /* XXX maybe need better hysteresis here */
  841. logit("exited MaxStartups throttling after %s, "
  842. "%u connections dropped",
  843. fmt_timeframe(now - first_drop), ndropped);
  844. last_drop = 0;
  845. }
  846. return 0;
  847. }
  848. #define SSHD_MAXSTARTUPS_LOG_INTERVAL (5 * 60)
  849. if (last_drop == 0) {
  850. error("beginning MaxStartups throttling");
  851. drop_level = SYSLOG_LEVEL_INFO;
  852. first_drop = now;
  853. ndropped = 0;
  854. } else if (last_drop + SSHD_MAXSTARTUPS_LOG_INTERVAL < now) {
  855. /* Periodic logs */
  856. error("in MaxStartups throttling for %s, "
  857. "%u connections dropped",
  858. fmt_timeframe(now - first_drop), ndropped + 1);
  859. drop_level = SYSLOG_LEVEL_INFO;
  860. }
  861. last_drop = now;
  862. ndropped++;
  863. laddr = get_local_ipaddr(sock);
  864. raddr = get_peer_ipaddr(sock);
  865. do_log2(drop_level, "drop connection #%d from [%s]:%d on [%s]:%d "
  866. "past MaxStartups", startups, raddr, get_peer_port(sock),
  867. laddr, get_local_port(sock));
  868. free(laddr);
  869. free(raddr);
  870. /* best-effort notification to client */
  871. (void)write(sock, msg, sizeof(msg) - 1);
  872. return 1;
  873. }
  874. static void
  875. usage(void)
  876. {
  877. fprintf(stderr, "%s, %s\n",
  878. SSH_RELEASE,
  879. #ifdef WITH_OPENSSL
  880. OpenSSL_version(OPENSSL_VERSION)
  881. #else
  882. "without OpenSSL"
  883. #endif
  884. );
  885. fprintf(stderr,
  886. "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
  887. " [-E log_file] [-f config_file] [-g login_grace_time]\n"
  888. " [-h host_key_file] [-o option] [-p port] [-u len]\n"
  889. );
  890. exit(1);
  891. }
  892. static void
  893. send_rexec_state(int fd, struct sshbuf *conf)
  894. {
  895. struct sshbuf *m = NULL, *inc = NULL;
  896. struct include_item *item = NULL;
  897. int r;
  898. debug3("%s: entering fd = %d config len %zu", __func__, fd,
  899. sshbuf_len(conf));
  900. if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
  901. fatal("%s: sshbuf_new failed", __func__);
  902. /* pack includes into a string */
  903. TAILQ_FOREACH(item, &includes, entry) {
  904. if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
  905. (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
  906. (r = sshbuf_put_stringb(inc, item->contents)) != 0)
  907. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  908. }
  909. /*
  910. * Protocol from reexec master to child:
  911. * string configuration
  912. * string included_files[] {
  913. * string selector
  914. * string filename
  915. * string contents
  916. * }
  917. * string rng_seed (if required)
  918. */
  919. if ((r = sshbuf_put_stringb(m, conf)) != 0 ||
  920. (r = sshbuf_put_stringb(m, inc)) != 0)
  921. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  922. #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
  923. rexec_send_rng_seed(m);
  924. #endif
  925. if (ssh_msg_send(fd, 0, m) == -1)
  926. error("%s: ssh_msg_send failed", __func__);
  927. sshbuf_free(m);
  928. sshbuf_free(inc);
  929. debug3("%s: done", __func__);
  930. }
  931. static void
  932. recv_rexec_state(int fd, struct sshbuf *conf)
  933. {
  934. struct sshbuf *m, *inc;
  935. u_char *cp, ver;
  936. size_t len;
  937. int r;
  938. struct include_item *item;
  939. debug3("%s: entering fd = %d", __func__, fd);
  940. if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
  941. fatal("%s: sshbuf_new failed", __func__);
  942. if (ssh_msg_recv(fd, m) == -1)
  943. fatal("%s: ssh_msg_recv failed", __func__);
  944. if ((r = sshbuf_get_u8(m, &ver)) != 0)
  945. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  946. if (ver != 0)
  947. fatal("%s: rexec version mismatch", __func__);
  948. if ((r = sshbuf_get_string(m, &cp, &len)) != 0 ||
  949. (r = sshbuf_get_stringb(m, inc)) != 0)
  950. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  951. #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
  952. rexec_recv_rng_seed(m);
  953. #endif
  954. if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
  955. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  956. while (sshbuf_len(inc) != 0) {
  957. item = xcalloc(1, sizeof(*item));
  958. if ((item->contents = sshbuf_new()) == NULL)
  959. fatal("%s: sshbuf_new failed", __func__);
  960. if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 ||
  961. (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 ||
  962. (r = sshbuf_get_stringb(inc, item->contents)) != 0)
  963. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  964. TAILQ_INSERT_TAIL(&includes, item, entry);
  965. }
  966. free(cp);
  967. sshbuf_free(m);
  968. debug3("%s: done", __func__);
  969. }
  970. /* Accept a connection from inetd */
  971. static void
  972. server_accept_inetd(int *sock_in, int *sock_out)
  973. {
  974. int fd;
  975. if (rexeced_flag) {
  976. close(REEXEC_CONFIG_PASS_FD);
  977. *sock_in = *sock_out = dup(STDIN_FILENO);
  978. } else {
  979. *sock_in = dup(STDIN_FILENO);
  980. *sock_out = dup(STDOUT_FILENO);
  981. }
  982. /*
  983. * We intentionally do not close the descriptors 0, 1, and 2
  984. * as our code for setting the descriptors won't work if
  985. * ttyfd happens to be one of those.
  986. */
  987. if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
  988. dup2(fd, STDIN_FILENO);
  989. dup2(fd, STDOUT_FILENO);
  990. if (!log_stderr)
  991. dup2(fd, STDERR_FILENO);
  992. if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
  993. close(fd);
  994. }
  995. debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
  996. }
  997. /*
  998. * Listen for TCP connections
  999. */
  1000. static void
  1001. listen_on_addrs(struct listenaddr *la)
  1002. {
  1003. int ret, listen_sock;
  1004. struct addrinfo *ai;
  1005. char ntop[NI_MAXHOST], strport[NI_MAXSERV];
  1006. int socksize;
  1007. int socksizelen = sizeof(int);
  1008. for (ai = la->addrs; ai; ai = ai->ai_next) {
  1009. if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
  1010. continue;
  1011. if (num_listen_socks >= MAX_LISTEN_SOCKS)
  1012. fatal("Too many listen sockets. "
  1013. "Enlarge MAX_LISTEN_SOCKS");
  1014. if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
  1015. ntop, sizeof(ntop), strport, sizeof(strport),
  1016. NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
  1017. error("getnameinfo failed: %.100s",
  1018. ssh_gai_strerror(ret));
  1019. continue;
  1020. }
  1021. /* Create socket for listening. */
  1022. listen_sock = socket(ai->ai_family, ai->ai_socktype,
  1023. ai->ai_protocol);
  1024. if (listen_sock == -1) {
  1025. /* kernel may not support ipv6 */
  1026. verbose("socket: %.100s", strerror(errno));
  1027. continue;
  1028. }
  1029. if (set_nonblock(listen_sock) == -1) {
  1030. close(listen_sock);
  1031. continue;
  1032. }
  1033. if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
  1034. verbose("socket: CLOEXEC: %s", strerror(errno));
  1035. close(listen_sock);
  1036. continue;
  1037. }
  1038. /* Socket options */
  1039. set_reuseaddr(listen_sock);
  1040. if (la->rdomain != NULL &&
  1041. set_rdomain(listen_sock, la->rdomain) == -1) {
  1042. close(listen_sock);
  1043. continue;
  1044. }
  1045. /* Only communicate in IPv6 over AF_INET6 sockets. */
  1046. if (ai->ai_family == AF_INET6)
  1047. sock_set_v6only(listen_sock);
  1048. debug("Bind to port %s on %s.", strport, ntop);
  1049. getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF,
  1050. &socksize, &socksizelen);
  1051. debug("Server TCP RWIN socket size: %d", socksize);
  1052. debug("HPN Buffer Size: %d", options.hpn_buffer_size);
  1053. /* Bind the socket to the desired port. */
  1054. if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
  1055. error("Bind to port %s on %s failed: %.200s.",
  1056. strport, ntop, strerror(errno));
  1057. close(listen_sock);
  1058. continue;
  1059. }
  1060. listen_socks[num_listen_socks] = listen_sock;
  1061. num_listen_socks++;
  1062. /* Start listening on the port. */
  1063. if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
  1064. fatal("listen on [%s]:%s: %.100s",
  1065. ntop, strport, strerror(errno));
  1066. logit("Server listening on %s port %s%s%s.",
  1067. ntop, strport,
  1068. la->rdomain == NULL ? "" : " rdomain ",
  1069. la->rdomain == NULL ? "" : la->rdomain);
  1070. }
  1071. }
  1072. static void
  1073. server_listen(void)
  1074. {
  1075. u_int i;
  1076. /* Initialise per-source limit tracking. */
  1077. srclimit_init(options.max_startups, options.per_source_max_startups,
  1078. options.per_source_masklen_ipv4, options.per_source_masklen_ipv6);
  1079. for (i = 0; i < options.num_listen_addrs; i++) {
  1080. listen_on_addrs(&options.listen_addrs[i]);
  1081. freeaddrinfo(options.listen_addrs[i].addrs);
  1082. free(options.listen_addrs[i].rdomain);
  1083. memset(&options.listen_addrs[i], 0,
  1084. sizeof(options.listen_addrs[i]));
  1085. }
  1086. free(options.listen_addrs);
  1087. options.listen_addrs = NULL;
  1088. options.num_listen_addrs = 0;
  1089. if (!num_listen_socks)
  1090. fatal("Cannot bind any address.");
  1091. }
  1092. /*
  1093. * The main TCP accept loop. Note that, for the non-debug case, returns
  1094. * from this function are in a forked subprocess.
  1095. */
  1096. static void
  1097. server_accept_loop(struct ssh *ssh, int *sock_in, int *sock_out, int *newsock, int *config_s)
  1098. {
  1099. fd_set *fdset;
  1100. int i, j, ret, maxfd;
  1101. int ostartups = -1, startups = 0, listening = 0, lameduck = 0;
  1102. int startup_p[2] = { -1 , -1 };
  1103. char c = 0;
  1104. struct sockaddr_storage from;
  1105. socklen_t fromlen;
  1106. pid_t pid;
  1107. u_char rnd[256];
  1108. /* setup fd set for accept */
  1109. fdset = NULL;
  1110. maxfd = 0;
  1111. for (i = 0; i < num_listen_socks; i++)
  1112. if (listen_socks[i] > maxfd)
  1113. maxfd = listen_socks[i];
  1114. /* pipes connected to unauthenticated child sshd processes */
  1115. startup_pipes = xcalloc(options.max_startups, sizeof(int));
  1116. startup_flags = xcalloc(options.max_startups, sizeof(int));
  1117. for (i = 0; i < options.max_startups; i++)
  1118. startup_pipes[i] = -1;
  1119. /*
  1120. * Stay listening for connections until the system crashes or
  1121. * the daemon is killed with a signal.
  1122. */
  1123. for (;;) {
  1124. if (ostartups != startups) {
  1125. setproctitle("%s [listener] %d of %d-%d startups",
  1126. listener_proctitle, startups,
  1127. options.max_startups_begin, options.max_startups);
  1128. ostartups = startups;
  1129. }
  1130. if (received_sighup) {
  1131. if (!lameduck) {
  1132. debug("Received SIGHUP; waiting for children");
  1133. close_listen_socks();
  1134. lameduck = 1;
  1135. }
  1136. if (listening <= 0)
  1137. sighup_restart();
  1138. }
  1139. free(fdset);
  1140. fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
  1141. sizeof(fd_mask));
  1142. for (i = 0; i < num_listen_socks; i++)
  1143. FD_SET(listen_socks[i], fdset);
  1144. for (i = 0; i < options.max_startups; i++)
  1145. if (startup_pipes[i] != -1)
  1146. FD_SET(startup_pipes[i], fdset);
  1147. /* Wait in select until there is a connection. */
  1148. ret = select(maxfd+1, fdset, NULL, NULL, NULL);
  1149. if (ret == -1 && errno != EINTR)
  1150. error("select: %.100s", strerror(errno));
  1151. if (received_sigterm) {
  1152. logit("Received signal %d; terminating.",
  1153. (int) received_sigterm);
  1154. destroy_sensitive_data(ssh, 0);
  1155. close_listen_socks();
  1156. if (options.pid_file != NULL)
  1157. unlink(options.pid_file);
  1158. exit(received_sigterm == SIGTERM ? 0 : 255);
  1159. }
  1160. if (ret == -1)
  1161. continue;
  1162. for (i = 0; i < options.max_startups; i++) {
  1163. if (startup_pipes[i] == -1 ||
  1164. !FD_ISSET(startup_pipes[i], fdset))
  1165. continue;
  1166. switch (read(startup_pipes[i], &c, sizeof(c))) {
  1167. case -1:
  1168. if (errno == EINTR || errno == EAGAIN)
  1169. continue;
  1170. if (errno != EPIPE) {
  1171. error("%s: startup pipe %d (fd=%d): "
  1172. "read %s", __func__, i,
  1173. startup_pipes[i], strerror(errno));
  1174. }
  1175. /* FALLTHROUGH */
  1176. case 0:
  1177. /* child exited or completed auth */
  1178. close(startup_pipes[i]);
  1179. srclimit_done(startup_pipes[i]);
  1180. startup_pipes[i] = -1;
  1181. startups--;
  1182. if (startup_flags[i])
  1183. listening--;
  1184. break;
  1185. case 1:
  1186. /* child has finished preliminaries */
  1187. if (startup_flags[i]) {
  1188. listening--;
  1189. startup_flags[i] = 0;
  1190. }
  1191. break;
  1192. }
  1193. }
  1194. for (i = 0; i < num_listen_socks; i++) {
  1195. if (!FD_ISSET(listen_socks[i], fdset))
  1196. continue;
  1197. fromlen = sizeof(from);
  1198. *newsock = accept(listen_socks[i],
  1199. (struct sockaddr *)&from, &fromlen);
  1200. if (*newsock == -1) {
  1201. if (errno != EINTR && errno != EWOULDBLOCK &&
  1202. errno != ECONNABORTED && errno != EAGAIN)
  1203. error("accept: %.100s",
  1204. strerror(errno));
  1205. if (errno == EMFILE || errno == ENFILE)
  1206. usleep(100 * 1000);
  1207. continue;
  1208. }
  1209. if (unset_nonblock(*newsock) == -1 ||
  1210. pipe(startup_p) == -1)
  1211. continue;
  1212. if (drop_connection(*newsock, startups, startup_p[0])) {
  1213. close(*newsock);
  1214. close(startup_p[0]);
  1215. close(startup_p[1]);
  1216. continue;
  1217. }
  1218. if (rexec_flag && socketpair(AF_UNIX,
  1219. SOCK_STREAM, 0, config_s) == -1) {
  1220. error("reexec socketpair: %s",
  1221. strerror(errno));
  1222. close(*newsock);
  1223. close(startup_p[0]);
  1224. close(startup_p[1]);
  1225. continue;
  1226. }
  1227. for (j = 0; j < options.max_startups; j++)
  1228. if (startup_pipes[j] == -1) {
  1229. startup_pipes[j] = startup_p[0];
  1230. if (maxfd < startup_p[0])
  1231. maxfd = startup_p[0];
  1232. startups++;
  1233. startup_flags[j] = 1;
  1234. break;
  1235. }
  1236. /*
  1237. * Got connection. Fork a child to handle it, unless
  1238. * we are in debugging mode.
  1239. */
  1240. if (debug_flag) {
  1241. /*
  1242. * In debugging mode. Close the listening
  1243. * socket, and start processing the
  1244. * connection without forking.
  1245. */
  1246. debug("Server will not fork when running in debugging mode.");
  1247. close_listen_socks();
  1248. *sock_in = *newsock;
  1249. *sock_out = *newsock;
  1250. close(startup_p[0]);
  1251. close(startup_p[1]);
  1252. startup_pipe = -1;
  1253. pid = getpid();
  1254. if (rexec_flag) {
  1255. send_rexec_state(config_s[0], cfg);
  1256. close(config_s[0]);
  1257. }
  1258. return;
  1259. }
  1260. /*
  1261. * Normal production daemon. Fork, and have
  1262. * the child process the connection. The
  1263. * parent continues listening.
  1264. */
  1265. platform_pre_fork();
  1266. listening++;
  1267. if ((pid = fork()) == 0) {
  1268. /*
  1269. * Child. Close the listening and
  1270. * max_startup sockets. Start using
  1271. * the accepted socket. Reinitialize
  1272. * logging (since our pid has changed).
  1273. * We return from this function to handle
  1274. * the connection.
  1275. */
  1276. platform_post_fork_child();
  1277. startup_pipe = startup_p[1];
  1278. close_startup_pipes();
  1279. close_listen_socks();
  1280. *sock_in = *newsock;
  1281. *sock_out = *newsock;
  1282. log_init(__progname,
  1283. options.log_level,
  1284. options.log_facility,
  1285. log_stderr);
  1286. if (rexec_flag)
  1287. close(config_s[0]);
  1288. else {
  1289. /*
  1290. * Signal parent that the preliminaries
  1291. * for this child are complete. For the
  1292. * re-exec case, this happens after the
  1293. * child has received the rexec state
  1294. * from the server.
  1295. */
  1296. (void)atomicio(vwrite, startup_pipe,
  1297. "\0", 1);
  1298. }
  1299. return;
  1300. }
  1301. /* Parent. Stay in the loop. */
  1302. platform_post_fork_parent(pid);
  1303. if (pid == -1)
  1304. error("fork: %.100s", strerror(errno));
  1305. else
  1306. debug("Forked child %ld.", (long)pid);
  1307. close(startup_p[1]);
  1308. if (rexec_flag) {
  1309. close(config_s[1]);
  1310. send_rexec_state(config_s[0], cfg);
  1311. close(config_s[0]);
  1312. }
  1313. close(*newsock);
  1314. /*
  1315. * Ensure that our random state differs
  1316. * from that of the child
  1317. */
  1318. arc4random_stir();
  1319. arc4random_buf(rnd, sizeof(rnd));
  1320. #ifdef WITH_OPENSSL
  1321. RAND_seed(rnd, sizeof(rnd));
  1322. if ((RAND_bytes((u_char *)rnd, 1)) != 1)
  1323. fatal("%s: RAND_bytes failed", __func__);
  1324. #endif
  1325. explicit_bzero(rnd, sizeof(rnd));
  1326. }
  1327. }
  1328. if (fdset != NULL)
  1329. free(fdset);
  1330. }
  1331. /*
  1332. * If IP options are supported, make sure there are none (log and
  1333. * return an error if any are found). Basically we are worried about
  1334. * source routing; it can be used to pretend you are somebody
  1335. * (ip-address) you are not. That itself may be "almost acceptable"
  1336. * under certain circumstances, but rhosts authentication is useless
  1337. * if source routing is accepted. Notice also that if we just dropped
  1338. * source routing here, the other side could use IP spoofing to do
  1339. * rest of the interaction and could still bypass security. So we
  1340. * exit here if we detect any IP options.
  1341. */
  1342. static void
  1343. check_ip_options(struct ssh *ssh)
  1344. {
  1345. #ifdef IP_OPTIONS
  1346. int sock_in = ssh_packet_get_connection_in(ssh);
  1347. struct sockaddr_storage from;
  1348. u_char opts[200];
  1349. socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
  1350. char text[sizeof(opts) * 3 + 1];
  1351. memset(&from, 0, sizeof(from));
  1352. if (getpeername(sock_in, (struct sockaddr *)&from,
  1353. &fromlen) == -1)
  1354. return;
  1355. if (from.ss_family != AF_INET)
  1356. return;
  1357. /* XXX IPv6 options? */
  1358. if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
  1359. &option_size) >= 0 && option_size != 0) {
  1360. i = 0;
  1361. do {
  1362. switch (opts[i]) {
  1363. case 0:
  1364. case 1:
  1365. ++i;
  1366. break;
  1367. case 130:
  1368. case 133:
  1369. case 134:
  1370. i += opts[i + 1];
  1371. break;
  1372. default:
  1373. /* Fail, fatally, if we detect either loose or strict
  1374. * source routing options. */
  1375. text[0] = '\0';
  1376. for (i = 0; i < option_size; i++)
  1377. snprintf(text + i*3, sizeof(text) - i*3,
  1378. " %2.2x", opts[i]);
  1379. fatal("Connection from %.100s port %d with IP options:%.800s",
  1380. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
  1381. }
  1382. } while (i < option_size);
  1383. }
  1384. return;
  1385. #endif /* IP_OPTIONS */
  1386. }
  1387. /* Set the routing domain for this process */
  1388. static void
  1389. set_process_rdomain(struct ssh *ssh, const char *name)
  1390. {
  1391. #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
  1392. if (name == NULL)
  1393. return; /* default */
  1394. if (strcmp(name, "%D") == 0) {
  1395. /* "expands" to routing domain of connection */
  1396. if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
  1397. return;
  1398. }
  1399. /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
  1400. return sys_set_process_rdomain(name);
  1401. #elif defined(__OpenBSD__)
  1402. int rtable, ortable = getrtable();
  1403. const char *errstr;
  1404. if (name == NULL)
  1405. return; /* default */
  1406. if (strcmp(name, "%D") == 0) {
  1407. /* "expands" to routing domain of connection */
  1408. if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
  1409. return;
  1410. }
  1411. rtable = (int)strtonum(name, 0, 255, &errstr);
  1412. if (errstr != NULL) /* Shouldn't happen */
  1413. fatal("Invalid routing domain \"%s\": %s", name, errstr);
  1414. if (rtable != ortable && setrtable(rtable) != 0)
  1415. fatal("Unable to set routing domain %d: %s",
  1416. rtable, strerror(errno));
  1417. debug("%s: set routing domain %d (was %d)", __func__, rtable, ortable);
  1418. #else /* defined(__OpenBSD__) */
  1419. fatal("Unable to set routing domain: not supported in this platform");
  1420. #endif
  1421. }
  1422. static void
  1423. accumulate_host_timing_secret(struct sshbuf *server_cfg,
  1424. struct sshkey *key)
  1425. {
  1426. static struct ssh_digest_ctx *ctx;
  1427. u_char *hash;
  1428. size_t len;
  1429. struct sshbuf *buf;
  1430. int r;
  1431. if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
  1432. fatal("%s: ssh_digest_start", __func__);
  1433. if (key == NULL) { /* finalize */
  1434. /* add server config in case we are using agent for host keys */
  1435. if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
  1436. sshbuf_len(server_cfg)) != 0)
  1437. fatal("%s: ssh_digest_update", __func__);
  1438. len = ssh_digest_bytes(SSH_DIGEST_SHA512);
  1439. hash = xmalloc(len);
  1440. if (ssh_digest_final(ctx, hash, len) != 0)
  1441. fatal("%s: ssh_digest_final", __func__);
  1442. options.timing_secret = PEEK_U64(hash);
  1443. freezero(hash, len);
  1444. ssh_digest_free(ctx);
  1445. ctx = NULL;
  1446. return;
  1447. }
  1448. if ((buf = sshbuf_new()) == NULL)
  1449. fatal("%s could not allocate buffer", __func__);
  1450. if ((r = sshkey_private_serialize(key, buf)) != 0)
  1451. fatal("sshkey_private_serialize: %s", ssh_err(r));
  1452. if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
  1453. fatal("%s: ssh_digest_update", __func__);
  1454. sshbuf_reset(buf);
  1455. sshbuf_free(buf);
  1456. }
  1457. static char *
  1458. prepare_proctitle(int ac, char **av)
  1459. {
  1460. char *ret = NULL;
  1461. int i;
  1462. for (i = 0; i < ac; i++)
  1463. xextendf(&ret, " ", "%s", av[i]);
  1464. return ret;
  1465. }
  1466. /*
  1467. * Main program for the daemon.
  1468. */
  1469. int
  1470. main(int ac, char **av)
  1471. {
  1472. struct ssh *ssh = NULL;
  1473. extern char *optarg;
  1474. extern int optind;
  1475. int r, opt, on = 1, already_daemon, remote_port;
  1476. int sock_in = -1, sock_out = -1, newsock = -1;
  1477. const char *remote_ip, *rdomain;
  1478. char *fp, *line, *laddr, *logfile = NULL;
  1479. int config_s[2] = { -1 , -1 };
  1480. u_int i, j;
  1481. u_int64_t ibytes, obytes;
  1482. mode_t new_umask;
  1483. struct sshkey *key;
  1484. struct sshkey *pubkey;
  1485. int keytype;
  1486. Authctxt *authctxt;
  1487. struct connection_info *connection_info = NULL;
  1488. struct passwd *newpw;
  1489. #ifdef HAVE_SECUREWARE
  1490. (void)set_auth_parameters(ac, av);
  1491. #endif
  1492. __progname = ssh_get_progname(av[0]);
  1493. /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
  1494. saved_argc = ac;
  1495. rexec_argc = ac;
  1496. saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
  1497. for (i = 0; (int)i < ac; i++)
  1498. saved_argv[i] = xstrdup(av[i]);
  1499. saved_argv[i] = NULL;
  1500. #ifndef HAVE_SETPROCTITLE
  1501. /* Prepare for later setproctitle emulation */
  1502. compat_init_setproctitle(ac, av);
  1503. av = saved_argv;
  1504. #endif
  1505. if (geteuid() == 0 && setgroups(0, NULL) == -1)
  1506. debug("setgroups(): %.200s", strerror(errno));
  1507. /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
  1508. sanitise_stdfd();
  1509. seed_rng();
  1510. /* Initialize configuration options to their default values. */
  1511. initialize_server_options(&options);
  1512. /* Parse command-line arguments. */
  1513. while ((opt = getopt(ac, av,
  1514. "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
  1515. switch (opt) {
  1516. case '4':
  1517. options.address_family = AF_INET;
  1518. break;
  1519. case '6':
  1520. options.address_family = AF_INET6;
  1521. break;
  1522. case 'f':
  1523. config_file_name = optarg;
  1524. break;
  1525. case 'c':
  1526. servconf_add_hostcert("[command-line]", 0,
  1527. &options, optarg);
  1528. break;
  1529. case 'd':
  1530. if (debug_flag == 0) {
  1531. debug_flag = 1;
  1532. options.log_level = SYSLOG_LEVEL_DEBUG1;
  1533. } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
  1534. options.log_level++;
  1535. break;
  1536. case 'D':
  1537. no_daemon_flag = 1;
  1538. break;
  1539. case 'E':
  1540. logfile = optarg;
  1541. /* FALLTHROUGH */
  1542. case 'e':
  1543. log_stderr = 1;
  1544. break;
  1545. case 'i':
  1546. inetd_flag = 1;
  1547. break;
  1548. case 'r':
  1549. rexec_flag = 0;
  1550. break;
  1551. case 'R':
  1552. rexeced_flag = 1;
  1553. inetd_flag = 1;
  1554. break;
  1555. case 'Q':
  1556. /* ignored */
  1557. break;
  1558. case 'q':
  1559. options.log_level = SYSLOG_LEVEL_QUIET;
  1560. break;
  1561. case 'b':
  1562. /* protocol 1, ignored */
  1563. break;
  1564. case 'p':
  1565. options.ports_from_cmdline = 1;
  1566. if (options.num_ports >= MAX_PORTS) {
  1567. fprintf(stderr, "too many ports.\n");
  1568. exit(1);
  1569. }
  1570. options.ports[options.num_ports++] = a2port(optarg);
  1571. if (options.ports[options.num_ports-1] <= 0) {
  1572. fprintf(stderr, "Bad port number.\n");
  1573. exit(1);
  1574. }
  1575. break;
  1576. case 'g':
  1577. if ((options.login_grace_time = convtime(optarg)) == -1) {
  1578. fprintf(stderr, "Invalid login grace time.\n");
  1579. exit(1);
  1580. }
  1581. break;
  1582. case 'k':
  1583. /* protocol 1, ignored */
  1584. break;
  1585. case 'h':
  1586. servconf_add_hostkey("[command-line]", 0,
  1587. &options, optarg, 1);
  1588. break;
  1589. case 't':
  1590. test_flag = 1;
  1591. break;
  1592. case 'T':
  1593. test_flag = 2;
  1594. break;
  1595. case 'C':
  1596. connection_info = get_connection_info(ssh, 0, 0);
  1597. if (parse_server_match_testspec(connection_info,
  1598. optarg) == -1)
  1599. exit(1);
  1600. break;
  1601. case 'u':
  1602. utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
  1603. if (utmp_len > HOST_NAME_MAX+1) {
  1604. fprintf(stderr, "Invalid utmp length.\n");
  1605. exit(1);
  1606. }
  1607. break;
  1608. case 'o':
  1609. line = xstrdup(optarg);
  1610. if (process_server_config_line(&options, line,
  1611. "command-line", 0, NULL, NULL, &includes) != 0)
  1612. exit(1);
  1613. free(line);
  1614. break;
  1615. case '?':
  1616. default:
  1617. usage();
  1618. break;
  1619. }
  1620. }
  1621. if (rexeced_flag || inetd_flag)
  1622. rexec_flag = 0;
  1623. if (!test_flag && rexec_flag && !path_absolute(av[0]))
  1624. fatal("sshd re-exec requires execution with an absolute path");
  1625. if (rexeced_flag)
  1626. closefrom(REEXEC_MIN_FREE_FD);
  1627. else
  1628. closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
  1629. /* If requested, redirect the logs to the specified logfile. */
  1630. if (logfile != NULL)
  1631. log_redirect_stderr_to(logfile);
  1632. /*
  1633. * Force logging to stderr until we have loaded the private host
  1634. * key (unless started from inetd)
  1635. */
  1636. log_init(__progname,
  1637. options.log_level == SYSLOG_LEVEL_NOT_SET ?
  1638. SYSLOG_LEVEL_INFO : options.log_level,
  1639. options.log_facility == SYSLOG_FACILITY_NOT_SET ?
  1640. SYSLOG_FACILITY_AUTH : options.log_facility,
  1641. log_stderr || !inetd_flag || debug_flag);
  1642. /*
  1643. * Unset KRB5CCNAME, otherwise the user's session may inherit it from
  1644. * root's environment
  1645. */
  1646. if (getenv("KRB5CCNAME") != NULL)
  1647. (void) unsetenv("KRB5CCNAME");
  1648. sensitive_data.have_ssh2_key = 0;
  1649. /*
  1650. * If we're not doing an extended test do not silently ignore connection
  1651. * test params.
  1652. */
  1653. if (test_flag < 2 && connection_info != NULL)
  1654. fatal("Config test connection parameter (-C) provided without "
  1655. "test mode (-T)");
  1656. /* Fetch our configuration */
  1657. if ((cfg = sshbuf_new()) == NULL)
  1658. fatal("%s: sshbuf_new failed", __func__);
  1659. if (rexeced_flag) {
  1660. setproctitle("%s", "[rexeced]");
  1661. recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
  1662. if (!debug_flag) {
  1663. startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
  1664. close(REEXEC_STARTUP_PIPE_FD);
  1665. /*
  1666. * Signal parent that this child is at a point where
  1667. * they can go away if they have a SIGHUP pending.
  1668. */
  1669. (void)atomicio(vwrite, startup_pipe, "\0", 1);
  1670. }
  1671. } else if (strcasecmp(config_file_name, "none") != 0)
  1672. load_server_config(config_file_name, cfg);
  1673. parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
  1674. cfg, &includes, NULL);
  1675. /* 'UsePAM no' is not supported in Fedora */
  1676. if (! options.use_pam)
  1677. logit("WARNING: 'UsePAM no' is not supported in Fedora and may cause several problems.");
  1678. /* Fill in default values for those options not explicitly set. */
  1679. fill_default_server_options(&options);
  1680. if (options.none_enabled == 1) {
  1681. char *old_ciphers = options.ciphers;
  1682. xasprintf(&options.ciphers, "%s,none", old_ciphers);
  1683. free(old_ciphers);
  1684. /* only enable the none MAC in context of the none cipher -cjr */
  1685. if (options.nonemac_enabled == 1) {
  1686. char *old_macs = options.macs;
  1687. xasprintf(&options.macs, "%s,none", old_macs);
  1688. free(old_macs);
  1689. }
  1690. }
  1691. /* challenge-response is implemented via keyboard interactive */
  1692. if (options.challenge_response_authentication)
  1693. options.kbd_interactive_authentication = 1;
  1694. /* Check that options are sensible */
  1695. if (options.authorized_keys_command_user == NULL &&
  1696. (options.authorized_keys_command != NULL &&
  1697. strcasecmp(options.authorized_keys_command, "none") != 0))
  1698. fatal("AuthorizedKeysCommand set without "
  1699. "AuthorizedKeysCommandUser");
  1700. if (options.authorized_principals_command_user == NULL &&
  1701. (options.authorized_principals_command != NULL &&
  1702. strcasecmp(options.authorized_principals_command, "none") != 0))
  1703. fatal("AuthorizedPrincipalsCommand set without "
  1704. "AuthorizedPrincipalsCommandUser");
  1705. /*
  1706. * Check whether there is any path through configured auth methods.
  1707. * Unfortunately it is not possible to verify this generally before
  1708. * daemonisation in the presence of Match block, but this catches
  1709. * and warns for trivial misconfigurations that could break login.
  1710. */
  1711. if (options.num_auth_methods != 0) {
  1712. for (i = 0; i < options.num_auth_methods; i++) {
  1713. if (auth2_methods_valid(options.auth_methods[i],
  1714. 1) == 0)
  1715. break;
  1716. }
  1717. if (i >= options.num_auth_methods)
  1718. fatal("AuthenticationMethods cannot be satisfied by "
  1719. "enabled authentication methods");
  1720. }
  1721. /* Check that there are no remaining arguments. */
  1722. if (optind < ac) {
  1723. fprintf(stderr, "Extra argument %s.\n", av[optind]);
  1724. exit(1);
  1725. }
  1726. debug("sshd version %s, %s", SSH_VERSION,
  1727. #ifdef WITH_OPENSSL
  1728. OpenSSL_version(OPENSSL_VERSION)
  1729. #else
  1730. "without OpenSSL"
  1731. #endif
  1732. );
  1733. /* Store privilege separation user for later use if required. */
  1734. privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
  1735. if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
  1736. if (privsep_chroot || options.kerberos_authentication)
  1737. fatal("Privilege separation user %s does not exist",
  1738. SSH_PRIVSEP_USER);
  1739. } else {
  1740. privsep_pw = pwcopy(privsep_pw);
  1741. freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
  1742. privsep_pw->pw_passwd = xstrdup("*");
  1743. }
  1744. endpwent();
  1745. /* load host keys */
  1746. sensitive_data.host_keys = xcalloc(options.num_host_key_files,
  1747. sizeof(struct sshkey *));
  1748. sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
  1749. sizeof(struct sshkey *));
  1750. if (options.host_key_agent) {
  1751. if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
  1752. setenv(SSH_AUTHSOCKET_ENV_NAME,
  1753. options.host_key_agent, 1);
  1754. if ((r = ssh_get_authentication_socket(NULL)) == 0)
  1755. have_agent = 1;
  1756. else
  1757. error("Could not connect to agent \"%s\": %s",
  1758. options.host_key_agent, ssh_err(r));
  1759. }
  1760. for (i = 0; i < options.num_host_key_files; i++) {
  1761. int ll = options.host_key_file_userprovided[i] ?
  1762. SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
  1763. if (options.host_key_files[i] == NULL)
  1764. continue;
  1765. if ((r = sshkey_load_private(options.host_key_files[i], "",
  1766. &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
  1767. do_log2(ll, "Unable to load host key \"%s\": %s",
  1768. options.host_key_files[i], ssh_err(r));
  1769. if (sshkey_is_sk(key) &&
  1770. key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
  1771. debug("host key %s requires user presence, ignoring",
  1772. options.host_key_files[i]);
  1773. key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
  1774. }
  1775. if (r == 0 && key != NULL &&
  1776. (r = sshkey_shield_private(key)) != 0) {
  1777. do_log2(ll, "Unable to shield host key \"%s\": %s",
  1778. options.host_key_files[i], ssh_err(r));
  1779. sshkey_free(key);
  1780. key = NULL;
  1781. }
  1782. if ((r = sshkey_load_public(options.host_key_files[i],
  1783. &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
  1784. do_log2(ll, "Unable to load host key \"%s\": %s",
  1785. options.host_key_files[i], ssh_err(r));
  1786. if (pubkey != NULL && key != NULL) {
  1787. if (!sshkey_equal(pubkey, key)) {
  1788. error("Public key for %s does not match "
  1789. "private key", options.host_key_files[i]);
  1790. sshkey_free(pubkey);
  1791. pubkey = NULL;
  1792. }
  1793. }
  1794. if (pubkey == NULL && key != NULL) {
  1795. if ((r = sshkey_from_private(key, &pubkey)) != 0)
  1796. fatal("Could not demote key: \"%s\": %s",
  1797. options.host_key_files[i], ssh_err(r));
  1798. }
  1799. sensitive_data.host_keys[i] = key;
  1800. sensitive_data.host_pubkeys[i] = pubkey;
  1801. if (key == NULL && pubkey != NULL && have_agent) {
  1802. debug("will rely on agent for hostkey %s",
  1803. options.host_key_files[i]);
  1804. keytype = pubkey->type;
  1805. } else if (key != NULL) {
  1806. keytype = key->type;
  1807. accumulate_host_timing_secret(cfg, key);
  1808. } else {
  1809. do_log2(ll, "Unable to load host key: %s",
  1810. options.host_key_files[i]);
  1811. sensitive_data.host_keys[i] = NULL;
  1812. sensitive_data.host_pubkeys[i] = NULL;
  1813. continue;
  1814. }
  1815. switch (keytype) {
  1816. case KEY_RSA:
  1817. case KEY_DSA:
  1818. case KEY_ECDSA:
  1819. case KEY_ED25519:
  1820. case KEY_ECDSA_SK:
  1821. case KEY_ED25519_SK:
  1822. case KEY_XMSS:
  1823. if (have_agent || key != NULL)
  1824. sensitive_data.have_ssh2_key = 1;
  1825. break;
  1826. }
  1827. if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
  1828. SSH_FP_DEFAULT)) == NULL)
  1829. fatal("sshkey_fingerprint failed");
  1830. debug("%s host key #%d: %s %s",
  1831. key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
  1832. free(fp);
  1833. }
  1834. accumulate_host_timing_secret(cfg, NULL);
  1835. if (!sensitive_data.have_ssh2_key) {
  1836. logit("sshd: no hostkeys available -- exiting.");
  1837. exit(1);
  1838. }
  1839. /*
  1840. * Load certificates. They are stored in an array at identical
  1841. * indices to the public keys that they relate to.
  1842. */
  1843. sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
  1844. sizeof(struct sshkey *));
  1845. for (i = 0; i < options.num_host_key_files; i++)
  1846. sensitive_data.host_certificates[i] = NULL;
  1847. for (i = 0; i < options.num_host_cert_files; i++) {
  1848. if (options.host_cert_files[i] == NULL)
  1849. continue;
  1850. if ((r = sshkey_load_public(options.host_cert_files[i],
  1851. &key, NULL)) != 0) {
  1852. error("Could not load host certificate \"%s\": %s",
  1853. options.host_cert_files[i], ssh_err(r));
  1854. continue;
  1855. }
  1856. if (!sshkey_is_cert(key)) {
  1857. error("Certificate file is not a certificate: %s",
  1858. options.host_cert_files[i]);
  1859. sshkey_free(key);
  1860. continue;
  1861. }
  1862. /* Find matching private key */
  1863. for (j = 0; j < options.num_host_key_files; j++) {
  1864. if (sshkey_equal_public(key,
  1865. sensitive_data.host_keys[j])) {
  1866. sensitive_data.host_certificates[j] = key;
  1867. break;
  1868. }
  1869. }
  1870. if (j >= options.num_host_key_files) {
  1871. error("No matching private key for certificate: %s",
  1872. options.host_cert_files[i]);
  1873. sshkey_free(key);
  1874. continue;
  1875. }
  1876. sensitive_data.host_certificates[j] = key;
  1877. debug("host certificate: #%u type %d %s", j, key->type,
  1878. sshkey_type(key));
  1879. }
  1880. if (privsep_chroot) {
  1881. struct stat st;
  1882. if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
  1883. (S_ISDIR(st.st_mode) == 0))
  1884. fatal("Missing privilege separation directory: %s",
  1885. _PATH_PRIVSEP_CHROOT_DIR);
  1886. #ifdef HAVE_CYGWIN
  1887. if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
  1888. (st.st_uid != getuid () ||
  1889. (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
  1890. #else
  1891. if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
  1892. #endif
  1893. fatal("%s must be owned by root and not group or "
  1894. "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
  1895. }
  1896. if (test_flag > 1) {
  1897. /*
  1898. * If no connection info was provided by -C then use
  1899. * use a blank one that will cause no predicate to match.
  1900. */
  1901. if (connection_info == NULL)
  1902. connection_info = get_connection_info(ssh, 0, 0);
  1903. connection_info->test = 1;
  1904. parse_server_match_config(&options, &includes, connection_info);
  1905. dump_config(&options);
  1906. }
  1907. /* Configuration looks good, so exit if in test mode. */
  1908. if (test_flag)
  1909. exit(0);
  1910. /*
  1911. * Clear out any supplemental groups we may have inherited. This
  1912. * prevents inadvertent creation of files with bad modes (in the
  1913. * portable version at least, it's certainly possible for PAM
  1914. * to create a file, and we can't control the code in every
  1915. * module which might be used).
  1916. */
  1917. if (setgroups(0, NULL) < 0)
  1918. debug("setgroups() failed: %.200s", strerror(errno));
  1919. if (rexec_flag) {
  1920. if (rexec_argc < 0)
  1921. fatal("rexec_argc %d < 0", rexec_argc);
  1922. rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
  1923. for (i = 0; i < (u_int)rexec_argc; i++) {
  1924. debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
  1925. rexec_argv[i] = saved_argv[i];
  1926. }
  1927. rexec_argv[rexec_argc] = "-R";
  1928. rexec_argv[rexec_argc + 1] = NULL;
  1929. }
  1930. listener_proctitle = prepare_proctitle(ac, av);
  1931. /* Ensure that umask disallows at least group and world write */
  1932. new_umask = umask(0077) | 0022;
  1933. (void) umask(new_umask);
  1934. /* Initialize the log (it is reinitialized below in case we forked). */
  1935. if (debug_flag && (!inetd_flag || rexeced_flag))
  1936. log_stderr = 1;
  1937. log_init(__progname, options.log_level, options.log_facility, log_stderr);
  1938. /*
  1939. * If not in debugging mode, not started from inetd and not already
  1940. * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
  1941. * terminal, and fork. The original process exits.
  1942. */
  1943. already_daemon = daemonized();
  1944. if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
  1945. if (daemon(0, 0) == -1)
  1946. fatal("daemon() failed: %.200s", strerror(errno));
  1947. disconnect_controlling_tty();
  1948. }
  1949. /* Reinitialize the log (because of the fork above). */
  1950. log_init(__progname, options.log_level, options.log_facility, log_stderr);
  1951. /* Chdir to the root directory so that the current disk can be
  1952. unmounted if desired. */
  1953. if (chdir("/") == -1)
  1954. error("chdir(\"/\"): %s", strerror(errno));
  1955. /* ignore SIGPIPE */
  1956. ssh_signal(SIGPIPE, SIG_IGN);
  1957. /* Get a connection, either from inetd or a listening TCP socket */
  1958. if (inetd_flag) {
  1959. server_accept_inetd(&sock_in, &sock_out);
  1960. } else {
  1961. platform_pre_listen();
  1962. server_listen();
  1963. ssh_signal(SIGHUP, sighup_handler);
  1964. ssh_signal(SIGCHLD, main_sigchld_handler);
  1965. ssh_signal(SIGTERM, sigterm_handler);
  1966. ssh_signal(SIGQUIT, sigterm_handler);
  1967. /*
  1968. * Write out the pid file after the sigterm handler
  1969. * is setup and the listen sockets are bound
  1970. */
  1971. if (options.pid_file != NULL && !debug_flag) {
  1972. FILE *f = fopen(options.pid_file, "w");
  1973. if (f == NULL) {
  1974. error("Couldn't create pid file \"%s\": %s",
  1975. options.pid_file, strerror(errno));
  1976. } else {
  1977. fprintf(f, "%ld\n", (long) getpid());
  1978. fclose(f);
  1979. }
  1980. }
  1981. #ifdef HAVE_SYSTEMD
  1982. /* Signal systemd that we are ready to accept connections */
  1983. sd_notify(0, "READY=1");
  1984. #endif
  1985. /* Accept a connection and return in a forked child */
  1986. server_accept_loop(ssh, &sock_in, &sock_out,
  1987. &newsock, config_s);
  1988. }
  1989. /* This is the child processing a new connection. */
  1990. setproctitle("%s", "[accepted]");
  1991. /*
  1992. * Create a new session and process group since the 4.4BSD
  1993. * setlogin() affects the entire process group. We don't
  1994. * want the child to be able to affect the parent.
  1995. */
  1996. #if !defined(SSHD_ACQUIRES_CTTY)
  1997. /*
  1998. * If setsid is called, on some platforms sshd will later acquire a
  1999. * controlling terminal which will result in "could not set
  2000. * controlling tty" errors.
  2001. */
  2002. if (!debug_flag && !inetd_flag && setsid() == -1)
  2003. error("setsid: %.100s", strerror(errno));
  2004. #endif
  2005. if (rexec_flag) {
  2006. int fd;
  2007. debug("rexec start in %d out %d newsock %d pipe %d sock %d",
  2008. sock_in, sock_out, newsock, startup_pipe, config_s[0]);
  2009. dup2(newsock, STDIN_FILENO);
  2010. dup2(STDIN_FILENO, STDOUT_FILENO);
  2011. if (startup_pipe == -1)
  2012. close(REEXEC_STARTUP_PIPE_FD);
  2013. else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
  2014. dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
  2015. close(startup_pipe);
  2016. startup_pipe = REEXEC_STARTUP_PIPE_FD;
  2017. }
  2018. dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
  2019. close(config_s[1]);
  2020. ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
  2021. execv(rexec_argv[0], rexec_argv);
  2022. /* Reexec has failed, fall back and continue */
  2023. error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
  2024. recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
  2025. log_init(__progname, options.log_level,
  2026. options.log_facility, log_stderr);
  2027. /* Clean up fds */
  2028. close(REEXEC_CONFIG_PASS_FD);
  2029. newsock = sock_out = sock_in = dup(STDIN_FILENO);
  2030. if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
  2031. dup2(fd, STDIN_FILENO);
  2032. dup2(fd, STDOUT_FILENO);
  2033. if (fd > STDERR_FILENO)
  2034. close(fd);
  2035. }
  2036. debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
  2037. sock_in, sock_out, newsock, startup_pipe, config_s[0]);
  2038. }
  2039. /* Executed child processes don't need these. */
  2040. fcntl(sock_out, F_SETFD, FD_CLOEXEC);
  2041. fcntl(sock_in, F_SETFD, FD_CLOEXEC);
  2042. /* We will not restart on SIGHUP since it no longer makes sense. */
  2043. ssh_signal(SIGALRM, SIG_DFL);
  2044. ssh_signal(SIGHUP, SIG_DFL);
  2045. ssh_signal(SIGTERM, SIG_DFL);
  2046. ssh_signal(SIGQUIT, SIG_DFL);
  2047. ssh_signal(SIGCHLD, SIG_DFL);
  2048. ssh_signal(SIGINT, SIG_DFL);
  2049. /*
  2050. * Register our connection. This turns encryption off because we do
  2051. * not have a key.
  2052. */
  2053. if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
  2054. fatal("Unable to create connection");
  2055. the_active_state = ssh;
  2056. ssh_packet_set_server(ssh);
  2057. check_ip_options(ssh);
  2058. /* Prepare the channels layer */
  2059. channel_init_channels(ssh);
  2060. channel_set_af(ssh, options.address_family);
  2061. process_permitopen(ssh, &options);
  2062. /* Set SO_KEEPALIVE if requested. */
  2063. if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
  2064. setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
  2065. error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
  2066. if ((remote_port = ssh_remote_port(ssh)) < 0) {
  2067. debug("ssh_remote_port failed");
  2068. cleanup_exit(255);
  2069. }
  2070. if (options.routing_domain != NULL)
  2071. set_process_rdomain(ssh, options.routing_domain);
  2072. /*
  2073. * The rest of the code depends on the fact that
  2074. * ssh_remote_ipaddr() caches the remote ip, even if
  2075. * the socket goes away.
  2076. */
  2077. remote_ip = ssh_remote_ipaddr(ssh);
  2078. #ifdef SSH_AUDIT_EVENTS
  2079. audit_connection_from(remote_ip, remote_port);
  2080. #endif
  2081. #ifdef LIBWRAP
  2082. allow_severity = options.log_facility|LOG_INFO;
  2083. deny_severity = options.log_facility|LOG_WARNING;
  2084. /* Check whether logins are denied from this host. */
  2085. if (ssh_packet_connection_is_on_socket(ssh)) {
  2086. struct request_info req;
  2087. request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
  2088. fromhost(&req);
  2089. if (!hosts_access(&req)) {
  2090. debug("Connection refused by tcp wrapper");
  2091. refuse(&req);
  2092. /* NOTREACHED */
  2093. fatal("libwrap refuse returns");
  2094. }
  2095. }
  2096. #endif /* LIBWRAP */
  2097. rdomain = ssh_packet_rdomain_in(ssh);
  2098. /* Log the connection. */
  2099. laddr = get_local_ipaddr(sock_in);
  2100. verbose("Connection from %s port %d on %s port %d%s%s%s",
  2101. remote_ip, remote_port, laddr, ssh_local_port(ssh),
  2102. rdomain == NULL ? "" : " rdomain \"",
  2103. rdomain == NULL ? "" : rdomain,
  2104. rdomain == NULL ? "" : "\"");
  2105. free(laddr);
  2106. /* set the HPN options for the child */
  2107. channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
  2108. /*
  2109. * We don't want to listen forever unless the other side
  2110. * successfully authenticates itself. So we set up an alarm which is
  2111. * cleared after successful authentication. A limit of zero
  2112. * indicates no limit. Note that we don't set the alarm in debugging
  2113. * mode; it is just annoying to have the server exit just when you
  2114. * are about to discover the bug.
  2115. */
  2116. ssh_signal(SIGALRM, grace_alarm_handler);
  2117. if (!debug_flag)
  2118. alarm(options.login_grace_time);
  2119. if ((r = kex_exchange_identification(ssh, -1,
  2120. options.version_addendum)) != 0)
  2121. sshpkt_fatal(ssh, r, "banner exchange");
  2122. ssh_packet_set_nonblocking(ssh);
  2123. /* allocate authentication context */
  2124. authctxt = xcalloc(1, sizeof(*authctxt));
  2125. ssh->authctxt = authctxt;
  2126. authctxt->loginmsg = loginmsg;
  2127. /* XXX global for cleanup, access from other modules */
  2128. the_authctxt = authctxt;
  2129. /* Set default key authentication options */
  2130. if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
  2131. fatal("allocation failed");
  2132. /* prepare buffer to collect messages to display to user after login */
  2133. if ((loginmsg = sshbuf_new()) == NULL)
  2134. fatal("%s: sshbuf_new failed", __func__);
  2135. auth_debug_reset();
  2136. if (use_privsep) {
  2137. if (privsep_preauth(ssh) == 1)
  2138. goto authenticated;
  2139. } else if (have_agent) {
  2140. if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
  2141. error("Unable to get agent socket: %s", ssh_err(r));
  2142. have_agent = 0;
  2143. }
  2144. }
  2145. /* perform the key exchange */
  2146. /* authenticate user and start session */
  2147. do_ssh2_kex(ssh);
  2148. do_authentication2(ssh);
  2149. /*
  2150. * If we use privilege separation, the unprivileged child transfers
  2151. * the current keystate and exits
  2152. */
  2153. if (use_privsep) {
  2154. mm_send_keystate(ssh, pmonitor);
  2155. ssh_packet_clear_keys(ssh);
  2156. exit(0);
  2157. }
  2158. authenticated:
  2159. /*
  2160. * Cancel the alarm we set to limit the time taken for
  2161. * authentication.
  2162. */
  2163. alarm(0);
  2164. ssh_signal(SIGALRM, SIG_DFL);
  2165. authctxt->authenticated = 1;
  2166. if (startup_pipe != -1) {
  2167. close(startup_pipe);
  2168. startup_pipe = -1;
  2169. }
  2170. /* Refresh GID; The correct primary group ID may not be available until
  2171. * after successful authentication. */
  2172. newpw = getpwnam(authctxt->user);
  2173. if (newpw != NULL) {
  2174. debug ("GID refresh: old=%d, new=%d",
  2175. (int) authctxt->pw->pw_gid, (int) newpw->pw_gid);
  2176. authctxt->pw->pw_gid = newpw->pw_gid;
  2177. }
  2178. #ifdef SSH_AUDIT_EVENTS
  2179. audit_event(ssh, SSH_AUTH_SUCCESS);
  2180. #endif
  2181. #ifdef GSSAPI
  2182. if (options.gss_authentication) {
  2183. temporarily_use_uid(authctxt->pw);
  2184. ssh_gssapi_storecreds();
  2185. restore_uid();
  2186. }
  2187. #endif
  2188. #ifdef WITH_SELINUX
  2189. sshd_selinux_setup_exec_context(authctxt->pw->pw_name);
  2190. #endif
  2191. #ifdef USE_PAM
  2192. if (options.use_pam) {
  2193. do_pam_setcred(1);
  2194. do_pam_session(ssh);
  2195. }
  2196. #endif
  2197. /*
  2198. * In privilege separation, we fork another child and prepare
  2199. * file descriptor passing.
  2200. */
  2201. if (use_privsep) {
  2202. privsep_postauth(ssh, authctxt);
  2203. /* the monitor process [priv] will not return */
  2204. }
  2205. ssh_packet_set_timeout(ssh, options.client_alive_interval,
  2206. options.client_alive_count_max);
  2207. /* Try to send all our hostkeys to the client */
  2208. notify_hostkeys(ssh);
  2209. #ifdef WITH_OPENSSL
  2210. if (options.disable_multithreaded == 0) {
  2211. /* if we are using aes-ctr there can be issues in either a fork or sandbox
  2212. * so the initial aes-ctr is defined to point ot the original single process
  2213. * evp. After authentication we'll be past the fork and the sandboxed privsep
  2214. * so we repoint the define to the multithreaded evp. To start the threads we
  2215. * then force a rekey
  2216. */
  2217. const void *cc = ssh_packet_get_send_context(the_active_state);
  2218. /* only rekey if necessary. If we don't do this gcm mode cipher breaks */
  2219. if (strstr(cipher_ctx_name(cc), "ctr")) {
  2220. debug("Single to Multithreaded CTR cipher swap - server request");
  2221. cipher_reset_multithreaded();
  2222. packet_request_rekeying();
  2223. }
  2224. }
  2225. #endif
  2226. /* Start session. */
  2227. do_authenticated(ssh, authctxt);
  2228. /* The connection has been terminated. */
  2229. packet_destroy_all(ssh, 1, 1);
  2230. destroy_sensitive_data(ssh, 1);
  2231. ssh_packet_get_bytes(ssh, &ibytes, &obytes);
  2232. verbose("Transferred: sent %llu, received %llu bytes",
  2233. (unsigned long long)obytes, (unsigned long long)ibytes);
  2234. verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
  2235. #ifdef USE_PAM
  2236. if (options.use_pam)
  2237. finish_pam();
  2238. #endif /* USE_PAM */
  2239. #ifdef SSH_AUDIT_EVENTS
  2240. PRIVSEP(audit_event(ssh, SSH_CONNECTION_CLOSE));
  2241. #endif
  2242. ssh_packet_close(ssh);
  2243. if (use_privsep)
  2244. mm_terminate();
  2245. exit(0);
  2246. }
  2247. int
  2248. sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
  2249. struct sshkey *pubkey, u_char **signature, size_t *slenp,
  2250. const u_char *data, size_t dlen, const char *alg)
  2251. {
  2252. int r;
  2253. if (use_privsep) {
  2254. if (privkey) {
  2255. if (mm_sshkey_sign(ssh, privkey, signature, slenp,
  2256. data, dlen, alg, options.sk_provider, NULL,
  2257. ssh->compat) < 0)
  2258. fatal("%s: privkey sign failed", __func__);
  2259. } else {
  2260. if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
  2261. data, dlen, alg, options.sk_provider, NULL,
  2262. ssh->compat) < 0)
  2263. fatal("%s: pubkey sign failed", __func__);
  2264. }
  2265. } else {
  2266. if (privkey) {
  2267. if (sshkey_sign(privkey, signature, slenp, data, dlen,
  2268. alg, options.sk_provider, NULL, ssh->compat) < 0)
  2269. fatal("%s: privkey sign failed", __func__);
  2270. } else {
  2271. if ((r = ssh_agent_sign(auth_sock, pubkey,
  2272. signature, slenp, data, dlen, alg,
  2273. ssh->compat)) != 0) {
  2274. fatal("%s: agent sign failed: %s",
  2275. __func__, ssh_err(r));
  2276. }
  2277. }
  2278. }
  2279. return 0;
  2280. }
  2281. /* SSH2 key exchange */
  2282. static void
  2283. do_ssh2_kex(struct ssh *ssh)
  2284. {
  2285. char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
  2286. struct kex *kex;
  2287. int r;
  2288. if (options.none_enabled == 1)
  2289. debug("WARNING: None cipher enabled");
  2290. if (options.nonemac_enabled == 1)
  2291. debug("WARNING: None MAC enabled");
  2292. myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(ssh,
  2293. options.kex_algorithms);
  2294. myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(ssh,
  2295. options.ciphers);
  2296. myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(ssh,
  2297. options.ciphers);
  2298. myproposal[PROPOSAL_MAC_ALGS_CTOS] =
  2299. myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
  2300. if (options.compression == COMP_NONE) {
  2301. myproposal[PROPOSAL_COMP_ALGS_CTOS] =
  2302. myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
  2303. }
  2304. if (options.rekey_limit || options.rekey_interval)
  2305. ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
  2306. options.rekey_interval);
  2307. myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
  2308. ssh, list_hostkey_types());
  2309. /* start key exchange */
  2310. if ((r = kex_setup(ssh, myproposal)) != 0)
  2311. fatal("kex_setup: %s", ssh_err(r));
  2312. kex = ssh->kex;
  2313. #ifdef WITH_OPENSSL
  2314. kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
  2315. kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
  2316. kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
  2317. kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
  2318. kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
  2319. kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
  2320. kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
  2321. # ifdef OPENSSL_HAS_ECC
  2322. kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
  2323. # endif
  2324. #endif
  2325. kex->kex[KEX_C25519_SHA256] = kex_gen_server;
  2326. kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
  2327. kex->load_host_public_key=&get_hostkey_public_by_type;
  2328. kex->load_host_private_key=&get_hostkey_private_by_type;
  2329. kex->host_key_index=&get_hostkey_index;
  2330. kex->sign = sshd_hostkey_sign;
  2331. ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
  2332. #ifdef DEBUG_KEXDH
  2333. /* send 1st encrypted/maced/compressed message */
  2334. if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
  2335. (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
  2336. (r = sshpkt_send(ssh)) != 0 ||
  2337. (r = ssh_packet_write_wait(ssh)) != 0)
  2338. fatal("%s: send test: %s", __func__, ssh_err(r));
  2339. #endif
  2340. debug("KEX done");
  2341. }
  2342. /* server specific fatal cleanup */
  2343. void
  2344. cleanup_exit(int i)
  2345. {
  2346. static int in_cleanup = 0;
  2347. int is_privsep_child;
  2348. /* cleanup_exit can be called at the very least from the privsep
  2349. wrappers used for auditing. Make sure we don't recurse
  2350. indefinitely. */
  2351. if (in_cleanup)
  2352. _exit(i);
  2353. in_cleanup = 1;
  2354. if (the_active_state != NULL && the_authctxt != NULL) {
  2355. do_cleanup(the_active_state, the_authctxt);
  2356. if (use_privsep && privsep_is_preauth &&
  2357. pmonitor != NULL && pmonitor->m_pid > 1) {
  2358. debug("Killing privsep child %d", pmonitor->m_pid);
  2359. if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
  2360. errno != ESRCH)
  2361. error("%s: kill(%d): %s", __func__,
  2362. pmonitor->m_pid, strerror(errno));
  2363. }
  2364. }
  2365. is_privsep_child = use_privsep && pmonitor != NULL && pmonitor->m_pid == 0;
  2366. if (sensitive_data.host_keys != NULL && the_active_state != NULL)
  2367. destroy_sensitive_data(the_active_state, is_privsep_child);
  2368. if (the_active_state != NULL)
  2369. packet_destroy_all(the_active_state, 1, is_privsep_child);
  2370. #ifdef SSH_AUDIT_EVENTS
  2371. /* done after do_cleanup so it can cancel the PAM auth 'thread' */
  2372. if (the_active_state != NULL &&
  2373. (the_authctxt == NULL || !the_authctxt->authenticated) &&
  2374. (!use_privsep || mm_is_monitor()))
  2375. audit_event(the_active_state, SSH_CONNECTION_ABANDON);
  2376. #endif
  2377. _exit(i);
  2378. }