ssh.c 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552
  1. /* $OpenBSD: ssh.c,v 1.536 2020/09/21 07:29:09 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. * Ssh client program. This program can be used to log into a remote machine.
  7. * The software supports strong authentication, encryption, and forwarding
  8. * of X11, TCP/IP, and authentication connections.
  9. *
  10. * As far as I am concerned, the code I have written for this software
  11. * can be used freely for any purpose. Any derived versions of this
  12. * software must be clearly marked as such, and if the derived work is
  13. * incompatible with the protocol description in the RFC file, it must be
  14. * called by a name other than "ssh" or "Secure Shell".
  15. *
  16. * Copyright (c) 1999 Niels Provos. All rights reserved.
  17. * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
  18. *
  19. * Modified to work with SSLeay by Niels Provos <provos@citi.umich.edu>
  20. * in Canada (German citizen).
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the above copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  32. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  34. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  35. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  37. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  38. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  39. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  40. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41. */
  42. #include "includes.h"
  43. #include <sys/types.h>
  44. #ifdef HAVE_SYS_STAT_H
  45. # include <sys/stat.h>
  46. #endif
  47. #include <sys/resource.h>
  48. #include <sys/ioctl.h>
  49. #include <sys/socket.h>
  50. #include <sys/wait.h>
  51. #include <ctype.h>
  52. #include <errno.h>
  53. #include <fcntl.h>
  54. #include <netdb.h>
  55. #ifdef HAVE_PATHS_H
  56. #include <paths.h>
  57. #endif
  58. #include <pwd.h>
  59. #include <signal.h>
  60. #include <stdarg.h>
  61. #include <stddef.h>
  62. #include <stdio.h>
  63. #include <stdlib.h>
  64. #include <string.h>
  65. #include <stdarg.h>
  66. #include <unistd.h>
  67. #include <limits.h>
  68. #include <locale.h>
  69. #include <netinet/in.h>
  70. #include <arpa/inet.h>
  71. #ifdef WITH_OPENSSL
  72. #include <openssl/evp.h>
  73. #include <openssl/err.h>
  74. #endif
  75. #include "openbsd-compat/openssl-compat.h"
  76. #include "openbsd-compat/sys-queue.h"
  77. #include "xmalloc.h"
  78. #include "ssh.h"
  79. #include "ssh2.h"
  80. #include "canohost.h"
  81. #include "compat.h"
  82. #include "cipher.h"
  83. #include "packet.h"
  84. #include "sshbuf.h"
  85. #include "channels.h"
  86. #include "sshkey.h"
  87. #include "authfd.h"
  88. #include "authfile.h"
  89. #include "pathnames.h"
  90. #include "dispatch.h"
  91. #include "clientloop.h"
  92. #include "log.h"
  93. #include "misc.h"
  94. #include "readconf.h"
  95. #include "sshconnect.h"
  96. #include "kex.h"
  97. #include "mac.h"
  98. #include "sshpty.h"
  99. #include "match.h"
  100. #include "msg.h"
  101. #include "version.h"
  102. #include "ssherr.h"
  103. #include "myproposal.h"
  104. #include "utf8.h"
  105. #ifdef ENABLE_PKCS11
  106. #include "ssh-pkcs11.h"
  107. #endif
  108. extern char *__progname;
  109. /* Saves a copy of argv for setproctitle emulation */
  110. #ifndef HAVE_SETPROCTITLE
  111. static char **saved_av;
  112. #endif
  113. /* Flag indicating whether debug mode is on. May be set on the command line. */
  114. int debug_flag = 0;
  115. /* Flag indicating whether a tty should be requested */
  116. int tty_flag = 0;
  117. /*
  118. * Flag indicating that the current process should be backgrounded and
  119. * a new mux-client launched in the foreground for ControlPersist.
  120. */
  121. int need_controlpersist_detach = 0;
  122. /* Copies of flags for ControlPersist foreground mux-client */
  123. int ostdin_null_flag, otty_flag, orequest_tty;
  124. /*
  125. * General data structure for command line options and options configurable
  126. * in configuration files. See readconf.h.
  127. */
  128. Options options;
  129. /* optional user configfile */
  130. char *config = NULL;
  131. /*
  132. * Name of the host we are connecting to. This is the name given on the
  133. * command line, or the Hostname specified for the user-supplied name in a
  134. * configuration file.
  135. */
  136. char *host;
  137. /*
  138. * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is
  139. * not NULL, forward the socket at this path instead.
  140. */
  141. char *forward_agent_sock_path = NULL;
  142. /* socket address the host resolves to */
  143. struct sockaddr_storage hostaddr;
  144. /* Private host keys. */
  145. Sensitive sensitive_data;
  146. /* command to be executed */
  147. struct sshbuf *command;
  148. /* Should we execute a command or invoke a subsystem? */
  149. int subsystem_flag = 0;
  150. /* # of replies received for global requests */
  151. static int forward_confirms_pending = -1;
  152. /* mux.c */
  153. extern int muxserver_sock;
  154. extern u_int muxclient_command;
  155. /* Prints a help message to the user. This function never returns. */
  156. static void
  157. usage(void)
  158. {
  159. fprintf(stderr,
  160. "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]\n"
  161. " [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]\n"
  162. " [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]\n"
  163. " [-i identity_file] [-J [user@]host[:port]] [-L address]\n"
  164. " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
  165. " [-Q query_option] [-R address] [-S ctl_path] [-W host:port]\n"
  166. " [-w local_tun[:remote_tun]] destination [command]\n"
  167. );
  168. exit(255);
  169. }
  170. static int ssh_session2(struct ssh *, const struct ssh_conn_info *);
  171. static void load_public_identity_files(const struct ssh_conn_info *);
  172. static void main_sigchld_handler(int);
  173. /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
  174. static void
  175. tilde_expand_paths(char **paths, u_int num_paths)
  176. {
  177. u_int i;
  178. char *cp;
  179. for (i = 0; i < num_paths; i++) {
  180. cp = tilde_expand_filename(paths[i], getuid());
  181. free(paths[i]);
  182. paths[i] = cp;
  183. }
  184. }
  185. /*
  186. * Expands the set of percent_expand options used by the majority of keywords
  187. * in the client that support percent expansion.
  188. * Caller must free returned string.
  189. */
  190. static char *
  191. default_client_percent_expand(const char *str,
  192. const struct ssh_conn_info *cinfo)
  193. {
  194. return percent_expand(str,
  195. DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
  196. (char *)NULL);
  197. }
  198. /*
  199. * Expands the set of percent_expand options used by the majority of keywords
  200. * AND perform environment variable substitution.
  201. * Caller must free returned string.
  202. */
  203. static char *
  204. default_client_percent_dollar_expand(const char *str,
  205. const struct ssh_conn_info *cinfo)
  206. {
  207. char *ret;
  208. ret = percent_dollar_expand(str,
  209. DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
  210. (char *)NULL);
  211. if (ret == NULL)
  212. fatal("invalid environment variable expansion");
  213. return ret;
  214. }
  215. /*
  216. * Attempt to resolve a host name / port to a set of addresses and
  217. * optionally return any CNAMEs encountered along the way.
  218. * Returns NULL on failure.
  219. * NB. this function must operate with a options having undefined members.
  220. */
  221. static struct addrinfo *
  222. resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
  223. {
  224. char strport[NI_MAXSERV];
  225. struct addrinfo hints, *res;
  226. int gaierr;
  227. LogLevel loglevel = SYSLOG_LEVEL_DEBUG1;
  228. if (port <= 0)
  229. port = default_ssh_port();
  230. if (cname != NULL)
  231. *cname = '\0';
  232. snprintf(strport, sizeof strport, "%d", port);
  233. memset(&hints, 0, sizeof(hints));
  234. hints.ai_family = options.address_family == -1 ?
  235. AF_UNSPEC : options.address_family;
  236. hints.ai_socktype = SOCK_STREAM;
  237. if (cname != NULL)
  238. hints.ai_flags = AI_CANONNAME;
  239. if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
  240. if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
  241. loglevel = SYSLOG_LEVEL_ERROR;
  242. do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
  243. __progname, name, ssh_gai_strerror(gaierr));
  244. return NULL;
  245. }
  246. if (cname != NULL && res->ai_canonname != NULL) {
  247. if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
  248. error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
  249. __func__, name, res->ai_canonname, (u_long)clen);
  250. if (clen > 0)
  251. *cname = '\0';
  252. }
  253. }
  254. return res;
  255. }
  256. /* Returns non-zero if name can only be an address and not a hostname */
  257. static int
  258. is_addr_fast(const char *name)
  259. {
  260. return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
  261. strspn(name, "0123456789.") == strlen(name));
  262. }
  263. /* Returns non-zero if name represents a valid, single address */
  264. static int
  265. is_addr(const char *name)
  266. {
  267. char strport[NI_MAXSERV];
  268. struct addrinfo hints, *res;
  269. if (is_addr_fast(name))
  270. return 1;
  271. snprintf(strport, sizeof strport, "%u", default_ssh_port());
  272. memset(&hints, 0, sizeof(hints));
  273. hints.ai_family = options.address_family == -1 ?
  274. AF_UNSPEC : options.address_family;
  275. hints.ai_socktype = SOCK_STREAM;
  276. hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
  277. if (getaddrinfo(name, strport, &hints, &res) != 0)
  278. return 0;
  279. if (res == NULL || res->ai_next != NULL) {
  280. freeaddrinfo(res);
  281. return 0;
  282. }
  283. freeaddrinfo(res);
  284. return 1;
  285. }
  286. /*
  287. * Attempt to resolve a numeric host address / port to a single address.
  288. * Returns a canonical address string.
  289. * Returns NULL on failure.
  290. * NB. this function must operate with a options having undefined members.
  291. */
  292. static struct addrinfo *
  293. resolve_addr(const char *name, int port, char *caddr, size_t clen)
  294. {
  295. char addr[NI_MAXHOST], strport[NI_MAXSERV];
  296. struct addrinfo hints, *res;
  297. int gaierr;
  298. if (port <= 0)
  299. port = default_ssh_port();
  300. snprintf(strport, sizeof strport, "%u", port);
  301. memset(&hints, 0, sizeof(hints));
  302. hints.ai_family = options.address_family == -1 ?
  303. AF_UNSPEC : options.address_family;
  304. hints.ai_socktype = SOCK_STREAM;
  305. hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
  306. if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
  307. debug2("%s: could not resolve name %.100s as address: %s",
  308. __func__, name, ssh_gai_strerror(gaierr));
  309. return NULL;
  310. }
  311. if (res == NULL) {
  312. debug("%s: getaddrinfo %.100s returned no addresses",
  313. __func__, name);
  314. return NULL;
  315. }
  316. if (res->ai_next != NULL) {
  317. debug("%s: getaddrinfo %.100s returned multiple addresses",
  318. __func__, name);
  319. goto fail;
  320. }
  321. if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
  322. addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
  323. debug("%s: Could not format address for name %.100s: %s",
  324. __func__, name, ssh_gai_strerror(gaierr));
  325. goto fail;
  326. }
  327. if (strlcpy(caddr, addr, clen) >= clen) {
  328. error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
  329. __func__, name, addr, (u_long)clen);
  330. if (clen > 0)
  331. *caddr = '\0';
  332. fail:
  333. freeaddrinfo(res);
  334. return NULL;
  335. }
  336. return res;
  337. }
  338. /*
  339. * Check whether the cname is a permitted replacement for the hostname
  340. * and perform the replacement if it is.
  341. * NB. this function must operate with a options having undefined members.
  342. */
  343. static int
  344. check_follow_cname(int direct, char **namep, const char *cname)
  345. {
  346. int i;
  347. struct allowed_cname *rule;
  348. if (*cname == '\0' || options.num_permitted_cnames == 0 ||
  349. strcmp(*namep, cname) == 0)
  350. return 0;
  351. if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
  352. return 0;
  353. /*
  354. * Don't attempt to canonicalize names that will be interpreted by
  355. * a proxy or jump host unless the user specifically requests so.
  356. */
  357. if (!direct &&
  358. options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
  359. return 0;
  360. debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
  361. for (i = 0; i < options.num_permitted_cnames; i++) {
  362. rule = options.permitted_cnames + i;
  363. if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
  364. match_pattern_list(cname, rule->target_list, 1) != 1)
  365. continue;
  366. verbose("Canonicalized DNS aliased hostname "
  367. "\"%s\" => \"%s\"", *namep, cname);
  368. free(*namep);
  369. *namep = xstrdup(cname);
  370. return 1;
  371. }
  372. return 0;
  373. }
  374. /*
  375. * Attempt to resolve the supplied hostname after applying the user's
  376. * canonicalization rules. Returns the address list for the host or NULL
  377. * if no name was found after canonicalization.
  378. * NB. this function must operate with a options having undefined members.
  379. */
  380. static struct addrinfo *
  381. resolve_canonicalize(char **hostp, int port)
  382. {
  383. int i, direct, ndots;
  384. char *cp, *fullhost, newname[NI_MAXHOST];
  385. struct addrinfo *addrs;
  386. /*
  387. * Attempt to canonicalise addresses, regardless of
  388. * whether hostname canonicalisation was requested
  389. */
  390. if ((addrs = resolve_addr(*hostp, port,
  391. newname, sizeof(newname))) != NULL) {
  392. debug2("%s: hostname %.100s is address", __func__, *hostp);
  393. if (strcasecmp(*hostp, newname) != 0) {
  394. debug2("%s: canonicalised address \"%s\" => \"%s\"",
  395. __func__, *hostp, newname);
  396. free(*hostp);
  397. *hostp = xstrdup(newname);
  398. }
  399. return addrs;
  400. }
  401. /*
  402. * If this looks like an address but didn't parse as one, it might
  403. * be an address with an invalid interface scope. Skip further
  404. * attempts at canonicalisation.
  405. */
  406. if (is_addr_fast(*hostp)) {
  407. debug("%s: hostname %.100s is an unrecognised address",
  408. __func__, *hostp);
  409. return NULL;
  410. }
  411. if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
  412. return NULL;
  413. /*
  414. * Don't attempt to canonicalize names that will be interpreted by
  415. * a proxy unless the user specifically requests so.
  416. */
  417. direct = option_clear_or_none(options.proxy_command) &&
  418. options.jump_host == NULL;
  419. if (!direct &&
  420. options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
  421. return NULL;
  422. /* If domain name is anchored, then resolve it now */
  423. if ((*hostp)[strlen(*hostp) - 1] == '.') {
  424. debug3("%s: name is fully qualified", __func__);
  425. fullhost = xstrdup(*hostp);
  426. if ((addrs = resolve_host(fullhost, port, 0,
  427. newname, sizeof(newname))) != NULL)
  428. goto found;
  429. free(fullhost);
  430. goto notfound;
  431. }
  432. /* Don't apply canonicalization to sufficiently-qualified hostnames */
  433. ndots = 0;
  434. for (cp = *hostp; *cp != '\0'; cp++) {
  435. if (*cp == '.')
  436. ndots++;
  437. }
  438. if (ndots > options.canonicalize_max_dots) {
  439. debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
  440. __func__, *hostp, options.canonicalize_max_dots);
  441. return NULL;
  442. }
  443. /* Attempt each supplied suffix */
  444. for (i = 0; i < options.num_canonical_domains; i++) {
  445. xasprintf(&fullhost, "%s.%s.", *hostp,
  446. options.canonical_domains[i]);
  447. debug3("%s: attempting \"%s\" => \"%s\"", __func__,
  448. *hostp, fullhost);
  449. if ((addrs = resolve_host(fullhost, port, 0,
  450. newname, sizeof(newname))) == NULL) {
  451. free(fullhost);
  452. continue;
  453. }
  454. found:
  455. /* Remove trailing '.' */
  456. fullhost[strlen(fullhost) - 1] = '\0';
  457. /* Follow CNAME if requested */
  458. if (!check_follow_cname(direct, &fullhost, newname)) {
  459. debug("Canonicalized hostname \"%s\" => \"%s\"",
  460. *hostp, fullhost);
  461. }
  462. free(*hostp);
  463. *hostp = fullhost;
  464. return addrs;
  465. }
  466. notfound:
  467. if (!options.canonicalize_fallback_local)
  468. fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
  469. debug2("%s: host %s not found in any suffix", __func__, *hostp);
  470. return NULL;
  471. }
  472. /*
  473. * Check the result of hostkey loading, ignoring some errors and
  474. * fatal()ing for others.
  475. */
  476. static void
  477. check_load(int r, const char *path, const char *message)
  478. {
  479. switch (r) {
  480. case 0:
  481. break;
  482. case SSH_ERR_INTERNAL_ERROR:
  483. case SSH_ERR_ALLOC_FAIL:
  484. fatal("load %s \"%s\": %s", message, path, ssh_err(r));
  485. case SSH_ERR_SYSTEM_ERROR:
  486. /* Ignore missing files */
  487. if (errno == ENOENT)
  488. break;
  489. /* FALLTHROUGH */
  490. default:
  491. error("load %s \"%s\": %s", message, path, ssh_err(r));
  492. break;
  493. }
  494. }
  495. /*
  496. * Read per-user configuration file. Ignore the system wide config
  497. * file if the user specifies a config file on the command line.
  498. */
  499. static void
  500. process_config_files(const char *host_name, struct passwd *pw, int final_pass,
  501. int *want_final_pass)
  502. {
  503. char buf[PATH_MAX];
  504. int r;
  505. if (config != NULL) {
  506. if (strcasecmp(config, "none") != 0 &&
  507. !read_config_file(config, pw, host, host_name, &options,
  508. SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0),
  509. want_final_pass))
  510. fatal("Can't open user config file %.100s: "
  511. "%.100s", config, strerror(errno));
  512. } else {
  513. r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
  514. _PATH_SSH_USER_CONFFILE);
  515. if (r > 0 && (size_t)r < sizeof(buf))
  516. (void)read_config_file(buf, pw, host, host_name,
  517. &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
  518. (final_pass ? SSHCONF_FINAL : 0), want_final_pass);
  519. /* Read systemwide configuration file after user config. */
  520. (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
  521. host, host_name, &options,
  522. final_pass ? SSHCONF_FINAL : 0, want_final_pass);
  523. }
  524. }
  525. /* Rewrite the port number in an addrinfo list of addresses */
  526. static void
  527. set_addrinfo_port(struct addrinfo *addrs, int port)
  528. {
  529. struct addrinfo *addr;
  530. for (addr = addrs; addr != NULL; addr = addr->ai_next) {
  531. switch (addr->ai_family) {
  532. case AF_INET:
  533. ((struct sockaddr_in *)addr->ai_addr)->
  534. sin_port = htons(port);
  535. break;
  536. case AF_INET6:
  537. ((struct sockaddr_in6 *)addr->ai_addr)->
  538. sin6_port = htons(port);
  539. break;
  540. }
  541. }
  542. }
  543. static void
  544. ssh_conn_info_free(struct ssh_conn_info *cinfo)
  545. {
  546. if (cinfo == NULL)
  547. return;
  548. free(cinfo->conn_hash_hex);
  549. free(cinfo->shorthost);
  550. free(cinfo->uidstr);
  551. free(cinfo->keyalias);
  552. free(cinfo->thishost);
  553. free(cinfo->host_arg);
  554. free(cinfo->portstr);
  555. free(cinfo->remhost);
  556. free(cinfo->remuser);
  557. free(cinfo->homedir);
  558. free(cinfo->locuser);
  559. free(cinfo);
  560. }
  561. /*
  562. * Main program for the ssh client.
  563. */
  564. int
  565. main(int ac, char **av)
  566. {
  567. struct ssh *ssh = NULL;
  568. int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
  569. int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
  570. char *p, *cp, *line, *argv0, *logfile, *host_arg;
  571. char cname[NI_MAXHOST], thishost[NI_MAXHOST];
  572. struct stat st;
  573. struct passwd *pw;
  574. extern int optind, optreset;
  575. extern char *optarg;
  576. struct Forward fwd;
  577. struct addrinfo *addrs = NULL;
  578. size_t n, len;
  579. u_int j;
  580. struct ssh_conn_info *cinfo = NULL;
  581. /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
  582. sanitise_stdfd();
  583. __progname = ssh_get_progname(av[0]);
  584. #ifndef HAVE_SETPROCTITLE
  585. /* Prepare for later setproctitle emulation */
  586. /* Save argv so it isn't clobbered by setproctitle() emulation */
  587. saved_av = xcalloc(ac + 1, sizeof(*saved_av));
  588. for (i = 0; i < ac; i++)
  589. saved_av[i] = xstrdup(av[i]);
  590. saved_av[i] = NULL;
  591. compat_init_setproctitle(ac, av);
  592. av = saved_av;
  593. #endif
  594. seed_rng();
  595. /*
  596. * Discard other fds that are hanging around. These can cause problem
  597. * with backgrounded ssh processes started by ControlPersist.
  598. */
  599. closefrom(STDERR_FILENO + 1);
  600. /* Get user data. */
  601. pw = getpwuid(getuid());
  602. if (!pw) {
  603. logit("No user exists for uid %lu", (u_long)getuid());
  604. exit(255);
  605. }
  606. /* Take a copy of the returned structure. */
  607. pw = pwcopy(pw);
  608. /*
  609. * Set our umask to something reasonable, as some files are created
  610. * with the default umask. This will make them world-readable but
  611. * writable only by the owner, which is ok for all files for which we
  612. * don't set the modes explicitly.
  613. */
  614. umask(022);
  615. msetlocale();
  616. /*
  617. * Initialize option structure to indicate that no values have been
  618. * set.
  619. */
  620. initialize_options(&options);
  621. /*
  622. * Prepare main ssh transport/connection structures
  623. */
  624. if ((ssh = ssh_alloc_session_state()) == NULL)
  625. fatal("Couldn't allocate session state");
  626. channel_init_channels(ssh);
  627. /* Parse command-line arguments. */
  628. host = NULL;
  629. use_syslog = 0;
  630. logfile = NULL;
  631. argv0 = av[0];
  632. again:
  633. while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
  634. "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
  635. switch (opt) {
  636. case '1':
  637. fatal("SSH protocol v.1 is no longer supported");
  638. break;
  639. case '2':
  640. /* Ignored */
  641. break;
  642. case '4':
  643. options.address_family = AF_INET;
  644. break;
  645. case '6':
  646. options.address_family = AF_INET6;
  647. break;
  648. case 'n':
  649. options.stdin_null = 1;
  650. break;
  651. case 'f':
  652. options.fork_after_authentication = 1;
  653. options.stdin_null = 1;
  654. break;
  655. case 'x':
  656. options.forward_x11 = 0;
  657. break;
  658. case 'X':
  659. options.forward_x11 = 1;
  660. break;
  661. case 'y':
  662. use_syslog = 1;
  663. break;
  664. case 'E':
  665. logfile = optarg;
  666. break;
  667. case 'G':
  668. config_test = 1;
  669. break;
  670. case 'Y':
  671. options.forward_x11 = 1;
  672. options.forward_x11_trusted = 1;
  673. break;
  674. case 'g':
  675. options.fwd_opts.gateway_ports = 1;
  676. break;
  677. case 'O':
  678. if (options.stdio_forward_host != NULL)
  679. fatal("Cannot specify multiplexing "
  680. "command with -W");
  681. else if (muxclient_command != 0)
  682. fatal("Multiplexing command already specified");
  683. if (strcmp(optarg, "check") == 0)
  684. muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
  685. else if (strcmp(optarg, "forward") == 0)
  686. muxclient_command = SSHMUX_COMMAND_FORWARD;
  687. else if (strcmp(optarg, "exit") == 0)
  688. muxclient_command = SSHMUX_COMMAND_TERMINATE;
  689. else if (strcmp(optarg, "stop") == 0)
  690. muxclient_command = SSHMUX_COMMAND_STOP;
  691. else if (strcmp(optarg, "cancel") == 0)
  692. muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
  693. else if (strcmp(optarg, "proxy") == 0)
  694. muxclient_command = SSHMUX_COMMAND_PROXY;
  695. else
  696. fatal("Invalid multiplex command.");
  697. break;
  698. case 'P': /* deprecated */
  699. break;
  700. case 'Q':
  701. cp = NULL;
  702. if (strcmp(optarg, "cipher") == 0 ||
  703. strcasecmp(optarg, "Ciphers") == 0)
  704. cp = cipher_alg_list('\n', 0);
  705. else if (strcmp(optarg, "cipher-auth") == 0)
  706. cp = cipher_alg_list('\n', 1);
  707. else if (strcmp(optarg, "mac") == 0 ||
  708. strcasecmp(optarg, "MACs") == 0)
  709. cp = mac_alg_list('\n');
  710. else if (strcmp(optarg, "kex") == 0 ||
  711. strcasecmp(optarg, "KexAlgorithms") == 0)
  712. cp = kex_alg_list('\n');
  713. else if (strcmp(optarg, "key") == 0)
  714. cp = sshkey_alg_list(0, 0, 0, '\n');
  715. else if (strcmp(optarg, "key-cert") == 0)
  716. cp = sshkey_alg_list(1, 0, 0, '\n');
  717. else if (strcmp(optarg, "key-plain") == 0)
  718. cp = sshkey_alg_list(0, 1, 0, '\n');
  719. else if (strcmp(optarg, "key-sig") == 0 ||
  720. strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
  721. strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
  722. strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
  723. strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
  724. strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
  725. strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
  726. cp = sshkey_alg_list(0, 0, 1, '\n');
  727. else if (strcmp(optarg, "sig") == 0)
  728. cp = sshkey_alg_list(0, 1, 1, '\n');
  729. else if (strcmp(optarg, "protocol-version") == 0)
  730. cp = xstrdup("2");
  731. else if (strcmp(optarg, "compression") == 0) {
  732. cp = xstrdup(compression_alg_list(0));
  733. len = strlen(cp);
  734. for (n = 0; n < len; n++)
  735. if (cp[n] == ',')
  736. cp[n] = '\n';
  737. } else if (strcmp(optarg, "help") == 0) {
  738. cp = xstrdup(
  739. "cipher\ncipher-auth\ncompression\nkex\n"
  740. "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
  741. "protocol-version\nsig");
  742. }
  743. if (cp == NULL)
  744. fatal("Unsupported query \"%s\"", optarg);
  745. printf("%s\n", cp);
  746. free(cp);
  747. exit(0);
  748. break;
  749. case 'a':
  750. options.forward_agent = 0;
  751. break;
  752. case 'A':
  753. options.forward_agent = 1;
  754. break;
  755. case 'k':
  756. options.gss_deleg_creds = 0;
  757. break;
  758. case 'K':
  759. options.gss_authentication = 1;
  760. options.gss_deleg_creds = 1;
  761. break;
  762. case 'i':
  763. #ifdef ENABLE_PKCS11
  764. if (strlen(optarg) >= strlen(PKCS11_URI_SCHEME) &&
  765. strncmp(optarg, PKCS11_URI_SCHEME,
  766. strlen(PKCS11_URI_SCHEME)) == 0) {
  767. add_identity_file(&options, NULL, optarg, 1);
  768. break;
  769. }
  770. #endif
  771. p = tilde_expand_filename(optarg, getuid());
  772. if (stat(p, &st) == -1)
  773. fprintf(stderr, "Warning: Identity file %s "
  774. "not accessible: %s.\n", p,
  775. strerror(errno));
  776. else
  777. add_identity_file(&options, NULL, p, 1);
  778. free(p);
  779. break;
  780. case 'I':
  781. #ifdef ENABLE_PKCS11
  782. free(options.pkcs11_provider);
  783. options.pkcs11_provider = xstrdup(optarg);
  784. #else
  785. fprintf(stderr, "no support for PKCS#11.\n");
  786. #endif
  787. break;
  788. case 'J':
  789. if (options.jump_host != NULL) {
  790. fatal("Only a single -J option is permitted "
  791. "(use commas to separate multiple "
  792. "jump hops)");
  793. }
  794. if (options.proxy_command != NULL)
  795. fatal("Cannot specify -J with ProxyCommand");
  796. if (parse_jump(optarg, &options, 1) == -1)
  797. fatal("Invalid -J argument");
  798. options.proxy_command = xstrdup("none");
  799. break;
  800. case 't':
  801. if (options.request_tty == REQUEST_TTY_YES)
  802. options.request_tty = REQUEST_TTY_FORCE;
  803. else
  804. options.request_tty = REQUEST_TTY_YES;
  805. break;
  806. case 'v':
  807. if (debug_flag == 0) {
  808. debug_flag = 1;
  809. options.log_level = SYSLOG_LEVEL_DEBUG1;
  810. } else {
  811. if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
  812. debug_flag++;
  813. options.log_level++;
  814. }
  815. }
  816. break;
  817. case 'V':
  818. fprintf(stderr, "%s, %s\n",
  819. SSH_RELEASE,
  820. #ifdef WITH_OPENSSL
  821. OpenSSL_version(OPENSSL_VERSION)
  822. #else
  823. "without OpenSSL"
  824. #endif
  825. );
  826. if (opt == 'V')
  827. exit(0);
  828. break;
  829. case 'w':
  830. if (options.tun_open == -1)
  831. options.tun_open = SSH_TUNMODE_DEFAULT;
  832. options.tun_local = a2tun(optarg, &options.tun_remote);
  833. if (options.tun_local == SSH_TUNID_ERR) {
  834. fprintf(stderr,
  835. "Bad tun device '%s'\n", optarg);
  836. exit(255);
  837. }
  838. break;
  839. case 'W':
  840. if (options.stdio_forward_host != NULL)
  841. fatal("stdio forward already specified");
  842. if (muxclient_command != 0)
  843. fatal("Cannot specify stdio forward with -O");
  844. if (parse_forward(&fwd, optarg, 1, 0)) {
  845. options.stdio_forward_host = fwd.listen_host;
  846. options.stdio_forward_port = fwd.listen_port;
  847. free(fwd.connect_host);
  848. } else {
  849. fprintf(stderr,
  850. "Bad stdio forwarding specification '%s'\n",
  851. optarg);
  852. exit(255);
  853. }
  854. options.request_tty = REQUEST_TTY_NO;
  855. options.no_shell = 1;
  856. break;
  857. case 'q':
  858. options.log_level = SYSLOG_LEVEL_QUIET;
  859. break;
  860. case 'e':
  861. if (optarg[0] == '^' && optarg[2] == 0 &&
  862. (u_char) optarg[1] >= 64 &&
  863. (u_char) optarg[1] < 128)
  864. options.escape_char = (u_char) optarg[1] & 31;
  865. else if (strlen(optarg) == 1)
  866. options.escape_char = (u_char) optarg[0];
  867. else if (strcmp(optarg, "none") == 0)
  868. options.escape_char = SSH_ESCAPECHAR_NONE;
  869. else {
  870. fprintf(stderr, "Bad escape character '%s'.\n",
  871. optarg);
  872. exit(255);
  873. }
  874. break;
  875. case 'c':
  876. if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
  877. optarg + 1 : optarg)) {
  878. fprintf(stderr, "Unknown cipher type '%s'\n",
  879. optarg);
  880. exit(255);
  881. }
  882. free(options.ciphers);
  883. options.ciphers = xstrdup(optarg);
  884. break;
  885. case 'm':
  886. if (mac_valid(optarg)) {
  887. free(options.macs);
  888. options.macs = xstrdup(optarg);
  889. } else {
  890. fprintf(stderr, "Unknown mac type '%s'\n",
  891. optarg);
  892. exit(255);
  893. }
  894. break;
  895. case 'M':
  896. if (options.control_master == SSHCTL_MASTER_YES)
  897. options.control_master = SSHCTL_MASTER_ASK;
  898. else
  899. options.control_master = SSHCTL_MASTER_YES;
  900. break;
  901. case 'p':
  902. if (options.port == -1) {
  903. options.port = a2port(optarg);
  904. if (options.port <= 0) {
  905. fprintf(stderr, "Bad port '%s'\n",
  906. optarg);
  907. exit(255);
  908. }
  909. }
  910. break;
  911. case 'l':
  912. if (options.user == NULL)
  913. options.user = optarg;
  914. break;
  915. case 'L':
  916. if (parse_forward(&fwd, optarg, 0, 0))
  917. add_local_forward(&options, &fwd);
  918. else {
  919. fprintf(stderr,
  920. "Bad local forwarding specification '%s'\n",
  921. optarg);
  922. exit(255);
  923. }
  924. break;
  925. case 'R':
  926. if (parse_forward(&fwd, optarg, 0, 1) ||
  927. parse_forward(&fwd, optarg, 1, 1)) {
  928. add_remote_forward(&options, &fwd);
  929. } else {
  930. fprintf(stderr,
  931. "Bad remote forwarding specification "
  932. "'%s'\n", optarg);
  933. exit(255);
  934. }
  935. break;
  936. case 'D':
  937. if (parse_forward(&fwd, optarg, 1, 0)) {
  938. add_local_forward(&options, &fwd);
  939. } else {
  940. fprintf(stderr,
  941. "Bad dynamic forwarding specification "
  942. "'%s'\n", optarg);
  943. exit(255);
  944. }
  945. break;
  946. case 'C':
  947. #ifdef WITH_ZLIB
  948. options.compression = 1;
  949. #else
  950. error("Compression not supported, disabling.");
  951. #endif
  952. break;
  953. case 'N':
  954. options.no_shell = 1;
  955. options.request_tty = REQUEST_TTY_NO;
  956. break;
  957. case 'T':
  958. options.request_tty = REQUEST_TTY_NO;
  959. /* ensure that the user doesn't try to backdoor a */
  960. /* null cipher switch on an interactive session */
  961. /* so explicitly disable it no matter what */
  962. options.none_switch=0;
  963. break;
  964. case 'o':
  965. line = xstrdup(optarg);
  966. if (process_config_line(&options, pw,
  967. host ? host : "", host ? host : "", line,
  968. "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
  969. exit(255);
  970. free(line);
  971. break;
  972. case 's':
  973. subsystem_flag = 1;
  974. break;
  975. case 'S':
  976. free(options.control_path);
  977. options.control_path = xstrdup(optarg);
  978. break;
  979. case 'b':
  980. options.bind_address = optarg;
  981. break;
  982. case 'B':
  983. options.bind_interface = optarg;
  984. break;
  985. case 'F':
  986. config = optarg;
  987. break;
  988. default:
  989. usage();
  990. }
  991. }
  992. if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
  993. opt_terminated = 1;
  994. ac -= optind;
  995. av += optind;
  996. if (ac > 0 && !host) {
  997. int tport;
  998. char *tuser;
  999. switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
  1000. case -1:
  1001. usage();
  1002. break;
  1003. case 0:
  1004. if (options.user == NULL) {
  1005. options.user = tuser;
  1006. tuser = NULL;
  1007. }
  1008. free(tuser);
  1009. if (options.port == -1 && tport != -1)
  1010. options.port = tport;
  1011. break;
  1012. default:
  1013. p = xstrdup(*av);
  1014. cp = strrchr(p, '@');
  1015. if (cp != NULL) {
  1016. if (cp == p)
  1017. usage();
  1018. if (options.user == NULL) {
  1019. options.user = p;
  1020. p = NULL;
  1021. }
  1022. *cp++ = '\0';
  1023. host = xstrdup(cp);
  1024. free(p);
  1025. } else
  1026. host = p;
  1027. break;
  1028. }
  1029. if (ac > 1 && !opt_terminated) {
  1030. optind = optreset = 1;
  1031. goto again;
  1032. }
  1033. ac--, av++;
  1034. }
  1035. /* Check that we got a host name. */
  1036. if (!host)
  1037. usage();
  1038. host_arg = xstrdup(host);
  1039. /* Initialize the command to execute on remote host. */
  1040. if ((command = sshbuf_new()) == NULL)
  1041. fatal("sshbuf_new failed");
  1042. /*
  1043. * Save the command to execute on the remote host in a buffer. There
  1044. * is no limit on the length of the command, except by the maximum
  1045. * packet size. Also sets the tty flag if there is no command.
  1046. */
  1047. if (!ac) {
  1048. /* No command specified - execute shell on a tty. */
  1049. if (subsystem_flag) {
  1050. fprintf(stderr,
  1051. "You must specify a subsystem to invoke.\n");
  1052. usage();
  1053. }
  1054. } else {
  1055. /* A command has been specified. Store it into the buffer. */
  1056. for (i = 0; i < ac; i++) {
  1057. if ((r = sshbuf_putf(command, "%s%s",
  1058. i ? " " : "", av[i])) != 0)
  1059. fatal("%s: buffer error: %s",
  1060. __func__, ssh_err(r));
  1061. }
  1062. }
  1063. /*
  1064. * Initialize "log" output. Since we are the client all output
  1065. * goes to stderr unless otherwise specified by -y or -E.
  1066. */
  1067. if (use_syslog && logfile != NULL)
  1068. fatal("Can't specify both -y and -E");
  1069. if (logfile != NULL)
  1070. log_redirect_stderr_to(logfile);
  1071. log_init(argv0,
  1072. options.log_level == SYSLOG_LEVEL_NOT_SET ?
  1073. SYSLOG_LEVEL_INFO : options.log_level,
  1074. options.log_facility == SYSLOG_FACILITY_NOT_SET ?
  1075. SYSLOG_FACILITY_USER : options.log_facility,
  1076. !use_syslog);
  1077. if (debug_flag)
  1078. logit("%s, %s", SSH_RELEASE,
  1079. #ifdef WITH_OPENSSL
  1080. OpenSSL_version(OPENSSL_VERSION)
  1081. #else
  1082. "without OpenSSL"
  1083. #endif
  1084. );
  1085. /* Parse the configuration files */
  1086. process_config_files(host_arg, pw, 0, &want_final_pass);
  1087. if (want_final_pass)
  1088. debug("configuration requests final Match pass");
  1089. /* Hostname canonicalisation needs a few options filled. */
  1090. fill_default_options_for_canonicalization(&options);
  1091. /* If the user has replaced the hostname then take it into use now */
  1092. if (options.hostname != NULL) {
  1093. /* NB. Please keep in sync with readconf.c:match_cfg_line() */
  1094. cp = percent_expand(options.hostname,
  1095. "h", host, (char *)NULL);
  1096. free(host);
  1097. host = cp;
  1098. free(options.hostname);
  1099. options.hostname = xstrdup(host);
  1100. }
  1101. /* Don't lowercase addresses, they will be explicitly canonicalised */
  1102. if ((was_addr = is_addr(host)) == 0)
  1103. lowercase(host);
  1104. /*
  1105. * Try to canonicalize if requested by configuration or the
  1106. * hostname is an address.
  1107. */
  1108. if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
  1109. addrs = resolve_canonicalize(&host, options.port);
  1110. /*
  1111. * If CanonicalizePermittedCNAMEs have been specified but
  1112. * other canonicalization did not happen (by not being requested
  1113. * or by failing with fallback) then the hostname may still be changed
  1114. * as a result of CNAME following.
  1115. *
  1116. * Try to resolve the bare hostname name using the system resolver's
  1117. * usual search rules and then apply the CNAME follow rules.
  1118. *
  1119. * Skip the lookup if a ProxyCommand is being used unless the user
  1120. * has specifically requested canonicalisation for this case via
  1121. * CanonicalizeHostname=always
  1122. */
  1123. direct = option_clear_or_none(options.proxy_command) &&
  1124. options.jump_host == NULL;
  1125. if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
  1126. options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
  1127. if ((addrs = resolve_host(host, options.port,
  1128. direct, cname, sizeof(cname))) == NULL) {
  1129. /* Don't fatal proxied host names not in the DNS */
  1130. if (direct)
  1131. cleanup_exit(255); /* logged in resolve_host */
  1132. } else
  1133. check_follow_cname(direct, &host, cname);
  1134. }
  1135. /*
  1136. * If canonicalisation is enabled then re-parse the configuration
  1137. * files as new stanzas may match.
  1138. */
  1139. if (options.canonicalize_hostname != 0 && !want_final_pass) {
  1140. debug("hostname canonicalisation enabled, "
  1141. "will re-parse configuration");
  1142. want_final_pass = 1;
  1143. }
  1144. if (want_final_pass) {
  1145. debug("re-parsing configuration");
  1146. free(options.hostname);
  1147. options.hostname = xstrdup(host);
  1148. process_config_files(host_arg, pw, 1, NULL);
  1149. /*
  1150. * Address resolution happens early with canonicalisation
  1151. * enabled and the port number may have changed since, so
  1152. * reset it in address list
  1153. */
  1154. if (addrs != NULL && options.port > 0)
  1155. set_addrinfo_port(addrs, options.port);
  1156. }
  1157. /* Fill configuration defaults. */
  1158. if (fill_default_options(&options) != 0)
  1159. cleanup_exit(255);
  1160. if (options.user == NULL)
  1161. options.user = xstrdup(pw->pw_name);
  1162. /*
  1163. * If ProxyJump option specified, then construct a ProxyCommand now.
  1164. */
  1165. if (options.jump_host != NULL) {
  1166. char port_s[8];
  1167. const char *jumpuser = options.jump_user, *sshbin = argv0;
  1168. int port = options.port, jumpport = options.jump_port;
  1169. if (port <= 0)
  1170. port = default_ssh_port();
  1171. if (jumpport <= 0)
  1172. jumpport = default_ssh_port();
  1173. if (jumpuser == NULL)
  1174. jumpuser = options.user;
  1175. if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
  1176. strcmp(options.user, jumpuser) == 0)
  1177. fatal("jumphost loop via %s", options.jump_host);
  1178. /*
  1179. * Try to use SSH indicated by argv[0], but fall back to
  1180. * "ssh" if it appears unavailable.
  1181. */
  1182. if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
  1183. sshbin = "ssh";
  1184. /* Consistency check */
  1185. if (options.proxy_command != NULL)
  1186. fatal("inconsistent options: ProxyCommand+ProxyJump");
  1187. /* Never use FD passing for ProxyJump */
  1188. options.proxy_use_fdpass = 0;
  1189. snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
  1190. xasprintf(&options.proxy_command,
  1191. "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
  1192. sshbin,
  1193. /* Optional "-l user" argument if jump_user set */
  1194. options.jump_user == NULL ? "" : " -l ",
  1195. options.jump_user == NULL ? "" : options.jump_user,
  1196. /* Optional "-p port" argument if jump_port set */
  1197. options.jump_port <= 0 ? "" : " -p ",
  1198. options.jump_port <= 0 ? "" : port_s,
  1199. /* Optional additional jump hosts ",..." */
  1200. options.jump_extra == NULL ? "" : " -J ",
  1201. options.jump_extra == NULL ? "" : options.jump_extra,
  1202. /* Optional "-F" argumment if -F specified */
  1203. config == NULL ? "" : " -F ",
  1204. config == NULL ? "" : config,
  1205. /* Optional "-v" arguments if -v set */
  1206. debug_flag ? " -" : "",
  1207. debug_flag, "vvv",
  1208. /* Mandatory hostname */
  1209. options.jump_host);
  1210. debug("Setting implicit ProxyCommand from ProxyJump: %s",
  1211. options.proxy_command);
  1212. }
  1213. if (options.port == 0)
  1214. options.port = default_ssh_port();
  1215. channel_set_af(ssh, options.address_family);
  1216. /* Tidy and check options */
  1217. if (options.host_key_alias != NULL)
  1218. lowercase(options.host_key_alias);
  1219. if (options.proxy_command != NULL &&
  1220. strcmp(options.proxy_command, "-") == 0 &&
  1221. options.proxy_use_fdpass)
  1222. fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
  1223. if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
  1224. if (options.control_persist && options.control_path != NULL) {
  1225. debug("UpdateHostKeys=ask is incompatible with "
  1226. "ControlPersist; disabling");
  1227. options.update_hostkeys = 0;
  1228. } else if (sshbuf_len(command) != 0 ||
  1229. options.remote_command != NULL ||
  1230. options.request_tty == REQUEST_TTY_NO) {
  1231. debug("UpdateHostKeys=ask is incompatible with "
  1232. "remote command execution; disabling");
  1233. options.update_hostkeys = 0;
  1234. } else if (options.log_level < SYSLOG_LEVEL_INFO) {
  1235. /* no point logging anything; user won't see it */
  1236. options.update_hostkeys = 0;
  1237. }
  1238. }
  1239. if (options.connection_attempts <= 0)
  1240. fatal("Invalid number of ConnectionAttempts");
  1241. if (sshbuf_len(command) != 0 && options.remote_command != NULL)
  1242. fatal("Cannot execute command-line and remote command.");
  1243. /* Cannot fork to background if no command. */
  1244. if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
  1245. options.remote_command == NULL && !options.no_shell)
  1246. fatal("Cannot fork into background without a command "
  1247. "to execute.");
  1248. /* reinit */
  1249. log_init(argv0, options.log_level, options.log_facility, !use_syslog);
  1250. if (options.request_tty == REQUEST_TTY_YES ||
  1251. options.request_tty == REQUEST_TTY_FORCE)
  1252. tty_flag = 1;
  1253. /* Allocate a tty by default if no command specified. */
  1254. if (sshbuf_len(command) == 0 && options.remote_command == NULL)
  1255. tty_flag = options.request_tty != REQUEST_TTY_NO;
  1256. /* Force no tty */
  1257. if (options.request_tty == REQUEST_TTY_NO ||
  1258. (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
  1259. tty_flag = 0;
  1260. /* Do not allocate a tty if stdin is not a tty. */
  1261. if ((!isatty(fileno(stdin)) || options.stdin_null) &&
  1262. options.request_tty != REQUEST_TTY_FORCE) {
  1263. if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
  1264. logit("Pseudo-terminal will not be allocated because "
  1265. "stdin is not a terminal.");
  1266. tty_flag = 0;
  1267. }
  1268. /* Set up strings used to percent_expand() arguments */
  1269. cinfo = xcalloc(1, sizeof(*cinfo));
  1270. if (gethostname(thishost, sizeof(thishost)) == -1)
  1271. fatal("gethostname: %s", strerror(errno));
  1272. cinfo->thishost = xstrdup(thishost);
  1273. thishost[strcspn(thishost, ".")] = '\0';
  1274. cinfo->shorthost = xstrdup(thishost);
  1275. xasprintf(&cinfo->portstr, "%d", options.port);
  1276. xasprintf(&cinfo->uidstr, "%llu",
  1277. (unsigned long long)pw->pw_uid);
  1278. cinfo->keyalias = xstrdup(options.host_key_alias ?
  1279. options.host_key_alias : host_arg);
  1280. cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
  1281. cinfo->portstr, options.user);
  1282. cinfo->host_arg = xstrdup(host_arg);
  1283. cinfo->remhost = xstrdup(host);
  1284. cinfo->remuser = xstrdup(options.user);
  1285. cinfo->homedir = xstrdup(pw->pw_dir);
  1286. cinfo->locuser = xstrdup(pw->pw_name);
  1287. /*
  1288. * Expand tokens in arguments. NB. LocalCommand is expanded later,
  1289. * after port-forwarding is set up, so it may pick up any local
  1290. * tunnel interface name allocated.
  1291. */
  1292. if (options.remote_command != NULL) {
  1293. debug3("expanding RemoteCommand: %s", options.remote_command);
  1294. cp = options.remote_command;
  1295. options.remote_command = default_client_percent_expand(cp,
  1296. cinfo);
  1297. debug3("expanded RemoteCommand: %s", options.remote_command);
  1298. free(cp);
  1299. if ((r = sshbuf_put(command, options.remote_command,
  1300. strlen(options.remote_command))) != 0)
  1301. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  1302. }
  1303. if (options.control_path != NULL) {
  1304. cp = tilde_expand_filename(options.control_path, getuid());
  1305. free(options.control_path);
  1306. options.control_path = default_client_percent_dollar_expand(cp,
  1307. cinfo);
  1308. free(cp);
  1309. }
  1310. if (options.identity_agent != NULL) {
  1311. p = tilde_expand_filename(options.identity_agent, getuid());
  1312. cp = default_client_percent_dollar_expand(p, cinfo);
  1313. free(p);
  1314. free(options.identity_agent);
  1315. options.identity_agent = cp;
  1316. }
  1317. if (options.forward_agent_sock_path != NULL) {
  1318. p = tilde_expand_filename(options.forward_agent_sock_path,
  1319. getuid());
  1320. cp = default_client_percent_dollar_expand(p, cinfo);
  1321. free(p);
  1322. free(options.forward_agent_sock_path);
  1323. options.forward_agent_sock_path = cp;
  1324. if (stat(options.forward_agent_sock_path, &st) != 0) {
  1325. error("Cannot forward agent socket path \"%s\": %s",
  1326. options.forward_agent_sock_path, strerror(errno));
  1327. if (options.exit_on_forward_failure)
  1328. cleanup_exit(255);
  1329. }
  1330. }
  1331. if (options.num_system_hostfiles > 0 &&
  1332. strcasecmp(options.system_hostfiles[0], "none") == 0) {
  1333. if (options.num_system_hostfiles > 1)
  1334. fatal("Invalid GlobalKnownHostsFiles: \"none\" "
  1335. "appears with other entries");
  1336. free(options.system_hostfiles[0]);
  1337. options.system_hostfiles[0] = NULL;
  1338. options.num_system_hostfiles = 0;
  1339. }
  1340. if (options.num_user_hostfiles > 0 &&
  1341. strcasecmp(options.user_hostfiles[0], "none") == 0) {
  1342. if (options.num_user_hostfiles > 1)
  1343. fatal("Invalid UserKnownHostsFiles: \"none\" "
  1344. "appears with other entries");
  1345. free(options.user_hostfiles[0]);
  1346. options.user_hostfiles[0] = NULL;
  1347. options.num_user_hostfiles = 0;
  1348. }
  1349. for (j = 0; j < options.num_user_hostfiles; j++) {
  1350. if (options.user_hostfiles[j] == NULL)
  1351. continue;
  1352. cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
  1353. p = default_client_percent_dollar_expand(cp, cinfo);
  1354. if (strcmp(options.user_hostfiles[j], p) != 0)
  1355. debug3("expanded UserKnownHostsFile '%s' -> "
  1356. "'%s'", options.user_hostfiles[j], p);
  1357. free(options.user_hostfiles[j]);
  1358. free(cp);
  1359. options.user_hostfiles[j] = p;
  1360. }
  1361. for (i = 0; i < options.num_local_forwards; i++) {
  1362. if (options.local_forwards[i].listen_path != NULL) {
  1363. cp = options.local_forwards[i].listen_path;
  1364. p = options.local_forwards[i].listen_path =
  1365. default_client_percent_expand(cp, cinfo);
  1366. if (strcmp(cp, p) != 0)
  1367. debug3("expanded LocalForward listen path "
  1368. "'%s' -> '%s'", cp, p);
  1369. free(cp);
  1370. }
  1371. if (options.local_forwards[i].connect_path != NULL) {
  1372. cp = options.local_forwards[i].connect_path;
  1373. p = options.local_forwards[i].connect_path =
  1374. default_client_percent_expand(cp, cinfo);
  1375. if (strcmp(cp, p) != 0)
  1376. debug3("expanded LocalForward connect path "
  1377. "'%s' -> '%s'", cp, p);
  1378. free(cp);
  1379. }
  1380. }
  1381. for (i = 0; i < options.num_remote_forwards; i++) {
  1382. if (options.remote_forwards[i].listen_path != NULL) {
  1383. cp = options.remote_forwards[i].listen_path;
  1384. p = options.remote_forwards[i].listen_path =
  1385. default_client_percent_expand(cp, cinfo);
  1386. if (strcmp(cp, p) != 0)
  1387. debug3("expanded RemoteForward listen path "
  1388. "'%s' -> '%s'", cp, p);
  1389. free(cp);
  1390. }
  1391. if (options.remote_forwards[i].connect_path != NULL) {
  1392. cp = options.remote_forwards[i].connect_path;
  1393. p = options.remote_forwards[i].connect_path =
  1394. default_client_percent_expand(cp, cinfo);
  1395. if (strcmp(cp, p) != 0)
  1396. debug3("expanded RemoteForward connect path "
  1397. "'%s' -> '%s'", cp, p);
  1398. free(cp);
  1399. }
  1400. }
  1401. if (config_test) {
  1402. dump_client_config(&options, host);
  1403. exit(0);
  1404. }
  1405. /* Expand SecurityKeyProvider if it refers to an environment variable */
  1406. if (options.sk_provider != NULL && *options.sk_provider == '$' &&
  1407. strlen(options.sk_provider) > 1) {
  1408. if ((cp = getenv(options.sk_provider + 1)) == NULL) {
  1409. debug("Authenticator provider %s did not resolve; "
  1410. "disabling", options.sk_provider);
  1411. free(options.sk_provider);
  1412. options.sk_provider = NULL;
  1413. } else {
  1414. debug2("resolved SecurityKeyProvider %s => %s",
  1415. options.sk_provider, cp);
  1416. free(options.sk_provider);
  1417. options.sk_provider = xstrdup(cp);
  1418. }
  1419. }
  1420. if (muxclient_command != 0 && options.control_path == NULL)
  1421. fatal("No ControlPath specified for \"-O\" command");
  1422. if (options.control_path != NULL) {
  1423. int sock;
  1424. if ((sock = muxclient(options.control_path)) >= 0) {
  1425. ssh_packet_set_connection(ssh, sock, sock);
  1426. ssh_packet_set_mux(ssh);
  1427. goto skip_connect;
  1428. }
  1429. }
  1430. /*
  1431. * If hostname canonicalisation was not enabled, then we may not
  1432. * have yet resolved the hostname. Do so now.
  1433. */
  1434. if (addrs == NULL && options.proxy_command == NULL) {
  1435. debug2("resolving \"%s\" port %d", host, options.port);
  1436. if ((addrs = resolve_host(host, options.port, 1,
  1437. cname, sizeof(cname))) == NULL)
  1438. cleanup_exit(255); /* resolve_host logs the error */
  1439. }
  1440. if (options.connection_timeout >= INT_MAX/1000)
  1441. timeout_ms = INT_MAX;
  1442. else
  1443. timeout_ms = options.connection_timeout * 1000;
  1444. /* Open a connection to the remote host. */
  1445. if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port,
  1446. options.connection_attempts,
  1447. &timeout_ms, options.tcp_keep_alive) != 0)
  1448. exit(255);
  1449. if (addrs != NULL)
  1450. freeaddrinfo(addrs);
  1451. ssh_packet_set_timeout(ssh, options.server_alive_interval,
  1452. options.server_alive_count_max);
  1453. if (timeout_ms > 0)
  1454. debug3("timeout: %d ms remain after connect", timeout_ms);
  1455. /*
  1456. * If we successfully made the connection and we have hostbased auth
  1457. * enabled, load the public keys so we can later use the ssh-keysign
  1458. * helper to sign challenges.
  1459. */
  1460. sensitive_data.nkeys = 0;
  1461. sensitive_data.keys = NULL;
  1462. if (options.hostbased_authentication) {
  1463. sensitive_data.nkeys = 10;
  1464. sensitive_data.keys = xcalloc(sensitive_data.nkeys,
  1465. sizeof(struct sshkey));
  1466. /* XXX check errors? */
  1467. #define L_PUBKEY(p,o) do { \
  1468. if ((o) >= sensitive_data.nkeys) \
  1469. fatal("%s pubkey out of array bounds", __func__); \
  1470. check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
  1471. p, "pubkey"); \
  1472. } while (0)
  1473. #define L_CERT(p,o) do { \
  1474. if ((o) >= sensitive_data.nkeys) \
  1475. fatal("%s cert out of array bounds", __func__); \
  1476. check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
  1477. } while (0)
  1478. if (options.hostbased_authentication == 1) {
  1479. L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
  1480. L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
  1481. L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
  1482. L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
  1483. L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
  1484. L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
  1485. L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
  1486. L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
  1487. L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
  1488. L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
  1489. }
  1490. }
  1491. /* load options.identity_files */
  1492. load_public_identity_files(cinfo);
  1493. /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
  1494. if (options.identity_agent &&
  1495. strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
  1496. if (strcmp(options.identity_agent, "none") == 0) {
  1497. unsetenv(SSH_AUTHSOCKET_ENV_NAME);
  1498. } else {
  1499. cp = options.identity_agent;
  1500. /* legacy (limited) format */
  1501. if (cp[0] == '$' && cp[1] != '{') {
  1502. if (!valid_env_name(cp + 1)) {
  1503. fatal("Invalid IdentityAgent "
  1504. "environment variable name %s", cp);
  1505. }
  1506. if ((p = getenv(cp + 1)) == NULL)
  1507. unsetenv(SSH_AUTHSOCKET_ENV_NAME);
  1508. else
  1509. setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
  1510. } else {
  1511. /* identity_agent specifies a path directly */
  1512. setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
  1513. }
  1514. }
  1515. }
  1516. if (options.forward_agent && options.forward_agent_sock_path != NULL) {
  1517. cp = options.forward_agent_sock_path;
  1518. if (cp[0] == '$') {
  1519. if (!valid_env_name(cp + 1)) {
  1520. fatal("Invalid ForwardAgent environment variable name %s", cp);
  1521. }
  1522. if ((p = getenv(cp + 1)) != NULL)
  1523. forward_agent_sock_path = p;
  1524. else
  1525. options.forward_agent = 0;
  1526. free(cp);
  1527. } else {
  1528. forward_agent_sock_path = cp;
  1529. }
  1530. }
  1531. /* Expand ~ in known host file names. */
  1532. tilde_expand_paths(options.system_hostfiles,
  1533. options.num_system_hostfiles);
  1534. tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
  1535. ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
  1536. ssh_signal(SIGCHLD, main_sigchld_handler);
  1537. /* Log into the remote system. Never returns if the login fails. */
  1538. ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
  1539. options.port, pw, timeout_ms, cinfo);
  1540. if (ssh_packet_connection_is_on_socket(ssh)) {
  1541. verbose("Authenticated to %s ([%s]:%d).", host,
  1542. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
  1543. } else {
  1544. verbose("Authenticated to %s (via proxy).", host);
  1545. }
  1546. /* We no longer need the private host keys. Clear them now. */
  1547. if (sensitive_data.nkeys != 0) {
  1548. for (i = 0; i < sensitive_data.nkeys; i++) {
  1549. if (sensitive_data.keys[i] != NULL) {
  1550. /* Destroys contents safely */
  1551. debug3("clear hostkey %d", i);
  1552. sshkey_free(sensitive_data.keys[i]);
  1553. sensitive_data.keys[i] = NULL;
  1554. }
  1555. }
  1556. free(sensitive_data.keys);
  1557. }
  1558. for (i = 0; i < options.num_identity_files; i++) {
  1559. free(options.identity_files[i]);
  1560. options.identity_files[i] = NULL;
  1561. if (options.identity_keys[i]) {
  1562. sshkey_free(options.identity_keys[i]);
  1563. options.identity_keys[i] = NULL;
  1564. }
  1565. }
  1566. for (i = 0; i < options.num_certificate_files; i++) {
  1567. free(options.certificate_files[i]);
  1568. options.certificate_files[i] = NULL;
  1569. }
  1570. pkcs11_terminate();
  1571. skip_connect:
  1572. exit_status = ssh_session2(ssh, cinfo);
  1573. ssh_conn_info_free(cinfo);
  1574. ssh_packet_close(ssh);
  1575. if (options.control_path != NULL && muxserver_sock != -1)
  1576. unlink(options.control_path);
  1577. /* Kill ProxyCommand if it is running. */
  1578. ssh_kill_proxy_command();
  1579. return exit_status;
  1580. }
  1581. static void
  1582. control_persist_detach(void)
  1583. {
  1584. pid_t pid;
  1585. int devnull, keep_stderr;
  1586. debug("%s: backgrounding master process", __func__);
  1587. /*
  1588. * master (current process) into the background, and make the
  1589. * foreground process a client of the backgrounded master.
  1590. */
  1591. switch ((pid = fork())) {
  1592. case -1:
  1593. fatal("%s: fork: %s", __func__, strerror(errno));
  1594. case 0:
  1595. /* Child: master process continues mainloop */
  1596. break;
  1597. default:
  1598. /* Parent: set up mux client to connect to backgrounded master */
  1599. debug2("%s: background process is %ld", __func__, (long)pid);
  1600. options.stdin_null = ostdin_null_flag;
  1601. options.request_tty = orequest_tty;
  1602. tty_flag = otty_flag;
  1603. close(muxserver_sock);
  1604. muxserver_sock = -1;
  1605. options.control_master = SSHCTL_MASTER_NO;
  1606. muxclient(options.control_path);
  1607. /* muxclient() doesn't return on success. */
  1608. fatal("Failed to connect to new control master");
  1609. }
  1610. if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
  1611. error("%s: open(\"/dev/null\"): %s", __func__,
  1612. strerror(errno));
  1613. } else {
  1614. keep_stderr = log_is_on_stderr() && debug_flag;
  1615. if (dup2(devnull, STDIN_FILENO) == -1 ||
  1616. dup2(devnull, STDOUT_FILENO) == -1 ||
  1617. (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
  1618. error("%s: dup2: %s", __func__, strerror(errno));
  1619. if (devnull > STDERR_FILENO)
  1620. close(devnull);
  1621. }
  1622. daemon(1, 1);
  1623. setproctitle("%s [mux]", options.control_path);
  1624. }
  1625. extern const EVP_CIPHER *evp_aes_ctr_mt(void);
  1626. /* Do fork() after authentication. Used by "ssh -f" */
  1627. static void
  1628. fork_postauth(void)
  1629. {
  1630. int devnull, keep_stderr;
  1631. if (need_controlpersist_detach)
  1632. control_persist_detach();
  1633. debug("forking to background");
  1634. options.fork_after_authentication = 0;
  1635. if (daemon(1, 1) == -1)
  1636. fatal("daemon() failed: %.200s", strerror(errno));
  1637. if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1)
  1638. error("%s: open %s: %s", __func__,
  1639. _PATH_DEVNULL, strerror(errno));
  1640. else {
  1641. keep_stderr = log_is_on_stderr() && debug_flag;
  1642. if (dup2(devnull, STDIN_FILENO) == -1 ||
  1643. dup2(devnull, STDOUT_FILENO) == -1 ||
  1644. (!keep_stderr && dup2(devnull, STDOUT_FILENO) == -1))
  1645. fatal("%s: dup2() stdio failed", __func__);
  1646. if (devnull > STDERR_FILENO)
  1647. close(devnull);
  1648. }
  1649. }
  1650. static void
  1651. forwarding_success(void)
  1652. {
  1653. if (forward_confirms_pending == -1)
  1654. return;
  1655. if (--forward_confirms_pending == 0) {
  1656. debug("%s: all expected forwarding replies received", __func__);
  1657. if (options.fork_after_authentication)
  1658. fork_postauth();
  1659. } else {
  1660. debug2("%s: %d expected forwarding replies remaining",
  1661. __func__, forward_confirms_pending);
  1662. }
  1663. }
  1664. /* Callback for remote forward global requests */
  1665. static void
  1666. ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
  1667. {
  1668. struct Forward *rfwd = (struct Forward *)ctxt;
  1669. u_int port;
  1670. int r;
  1671. /* XXX verbose() on failure? */
  1672. debug("remote forward %s for: listen %s%s%d, connect %s:%d",
  1673. type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
  1674. rfwd->listen_path ? rfwd->listen_path :
  1675. rfwd->listen_host ? rfwd->listen_host : "",
  1676. (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
  1677. rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
  1678. rfwd->connect_host, rfwd->connect_port);
  1679. if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
  1680. if (type == SSH2_MSG_REQUEST_SUCCESS) {
  1681. if ((r = sshpkt_get_u32(ssh, &port)) != 0)
  1682. fatal("%s: %s", __func__, ssh_err(r));
  1683. if (port > 65535) {
  1684. error("Invalid allocated port %u for remote "
  1685. "forward to %s:%d", port,
  1686. rfwd->connect_host, rfwd->connect_port);
  1687. /* Ensure failure processing runs below */
  1688. type = SSH2_MSG_REQUEST_FAILURE;
  1689. channel_update_permission(ssh,
  1690. rfwd->handle, -1);
  1691. } else {
  1692. rfwd->allocated_port = (int)port;
  1693. logit("Allocated port %u for remote "
  1694. "forward to %s:%d",
  1695. rfwd->allocated_port, rfwd->connect_host,
  1696. rfwd->connect_port);
  1697. channel_update_permission(ssh,
  1698. rfwd->handle, rfwd->allocated_port);
  1699. }
  1700. } else {
  1701. channel_update_permission(ssh, rfwd->handle, -1);
  1702. }
  1703. }
  1704. if (type == SSH2_MSG_REQUEST_FAILURE) {
  1705. if (options.exit_on_forward_failure) {
  1706. if (rfwd->listen_path != NULL)
  1707. fatal("Error: remote port forwarding failed "
  1708. "for listen path %s", rfwd->listen_path);
  1709. else
  1710. fatal("Error: remote port forwarding failed "
  1711. "for listen port %d", rfwd->listen_port);
  1712. } else {
  1713. if (rfwd->listen_path != NULL)
  1714. logit("Warning: remote port forwarding failed "
  1715. "for listen path %s", rfwd->listen_path);
  1716. else
  1717. logit("Warning: remote port forwarding failed "
  1718. "for listen port %d", rfwd->listen_port);
  1719. }
  1720. }
  1721. forwarding_success();
  1722. }
  1723. static void
  1724. client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
  1725. {
  1726. debug("stdio forwarding: done");
  1727. cleanup_exit(0);
  1728. }
  1729. static void
  1730. ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
  1731. {
  1732. if (!success)
  1733. fatal("stdio forwarding failed");
  1734. }
  1735. static void
  1736. ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
  1737. {
  1738. if (!success) {
  1739. error("Tunnel forwarding failed");
  1740. if (options.exit_on_forward_failure)
  1741. cleanup_exit(255);
  1742. }
  1743. debug("%s: tunnel forward established, id=%d", __func__, id);
  1744. forwarding_success();
  1745. }
  1746. static void
  1747. ssh_init_stdio_forwarding(struct ssh *ssh)
  1748. {
  1749. Channel *c;
  1750. int in, out;
  1751. if (options.stdio_forward_host == NULL)
  1752. return;
  1753. debug3("%s: %s:%d", __func__, options.stdio_forward_host,
  1754. options.stdio_forward_port);
  1755. if ((in = dup(STDIN_FILENO)) == -1 ||
  1756. (out = dup(STDOUT_FILENO)) == -1)
  1757. fatal("channel_connect_stdio_fwd: dup() in/out failed");
  1758. if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
  1759. options.stdio_forward_port, in, out)) == NULL)
  1760. fatal("%s: channel_connect_stdio_fwd failed", __func__);
  1761. channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
  1762. channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
  1763. }
  1764. static void
  1765. ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
  1766. u_int num_opens)
  1767. {
  1768. u_int i;
  1769. int port;
  1770. char *addr, *arg, *oarg, ch;
  1771. int where = FORWARD_LOCAL;
  1772. channel_clear_permission(ssh, FORWARD_ADM, where);
  1773. if (num_opens == 0)
  1774. return; /* permit any */
  1775. /* handle keywords: "any" / "none" */
  1776. if (num_opens == 1 && strcmp(opens[0], "any") == 0)
  1777. return;
  1778. if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
  1779. channel_disable_admin(ssh, where);
  1780. return;
  1781. }
  1782. /* Otherwise treat it as a list of permitted host:port */
  1783. for (i = 0; i < num_opens; i++) {
  1784. oarg = arg = xstrdup(opens[i]);
  1785. ch = '\0';
  1786. addr = hpdelim2(&arg, &ch);
  1787. if (addr == NULL || ch == '/')
  1788. fatal("missing host in %s", what);
  1789. addr = cleanhostname(addr);
  1790. if (arg == NULL || ((port = permitopen_port(arg)) < 0))
  1791. fatal("bad port number in %s", what);
  1792. /* Send it to channels layer */
  1793. channel_add_permission(ssh, FORWARD_ADM,
  1794. where, addr, port);
  1795. free(oarg);
  1796. }
  1797. }
  1798. static void
  1799. ssh_init_forwarding(struct ssh *ssh, char **ifname)
  1800. {
  1801. int success = 0;
  1802. int i;
  1803. ssh_init_forward_permissions(ssh, "permitremoteopen",
  1804. options.permitted_remote_opens,
  1805. options.num_permitted_remote_opens);
  1806. if (options.exit_on_forward_failure)
  1807. forward_confirms_pending = 0; /* track pending requests */
  1808. /* Initiate local TCP/IP port forwardings. */
  1809. for (i = 0; i < options.num_local_forwards; i++) {
  1810. debug("Local connections to %.200s:%d forwarded to remote "
  1811. "address %.200s:%d",
  1812. (options.local_forwards[i].listen_path != NULL) ?
  1813. options.local_forwards[i].listen_path :
  1814. (options.local_forwards[i].listen_host == NULL) ?
  1815. (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
  1816. options.local_forwards[i].listen_host,
  1817. options.local_forwards[i].listen_port,
  1818. (options.local_forwards[i].connect_path != NULL) ?
  1819. options.local_forwards[i].connect_path :
  1820. options.local_forwards[i].connect_host,
  1821. options.local_forwards[i].connect_port);
  1822. success += channel_setup_local_fwd_listener(ssh,
  1823. &options.local_forwards[i], &options.fwd_opts);
  1824. }
  1825. if (i > 0 && success != i && options.exit_on_forward_failure)
  1826. fatal("Could not request local forwarding.");
  1827. if (i > 0 && success == 0)
  1828. error("Could not request local forwarding.");
  1829. /* Initiate remote TCP/IP port forwardings. */
  1830. for (i = 0; i < options.num_remote_forwards; i++) {
  1831. debug("Remote connections from %.200s:%d forwarded to "
  1832. "local address %.200s:%d",
  1833. (options.remote_forwards[i].listen_path != NULL) ?
  1834. options.remote_forwards[i].listen_path :
  1835. (options.remote_forwards[i].listen_host == NULL) ?
  1836. "LOCALHOST" : options.remote_forwards[i].listen_host,
  1837. options.remote_forwards[i].listen_port,
  1838. (options.remote_forwards[i].connect_path != NULL) ?
  1839. options.remote_forwards[i].connect_path :
  1840. options.remote_forwards[i].connect_host,
  1841. options.remote_forwards[i].connect_port);
  1842. if ((options.remote_forwards[i].handle =
  1843. channel_request_remote_forwarding(ssh,
  1844. &options.remote_forwards[i])) >= 0) {
  1845. client_register_global_confirm(
  1846. ssh_confirm_remote_forward,
  1847. &options.remote_forwards[i]);
  1848. forward_confirms_pending++;
  1849. } else if (options.exit_on_forward_failure)
  1850. fatal("Could not request remote forwarding.");
  1851. else
  1852. logit("Warning: Could not request remote forwarding.");
  1853. }
  1854. /* Initiate tunnel forwarding. */
  1855. if (options.tun_open != SSH_TUNMODE_NO) {
  1856. if ((*ifname = client_request_tun_fwd(ssh,
  1857. options.tun_open, options.tun_local,
  1858. options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
  1859. forward_confirms_pending++;
  1860. else if (options.exit_on_forward_failure)
  1861. fatal("Could not request tunnel forwarding.");
  1862. else
  1863. error("Could not request tunnel forwarding.");
  1864. }
  1865. if (forward_confirms_pending > 0) {
  1866. debug("%s: expecting replies for %d forwards", __func__,
  1867. forward_confirms_pending);
  1868. }
  1869. }
  1870. static void
  1871. check_agent_present(void)
  1872. {
  1873. int r;
  1874. if (options.forward_agent) {
  1875. /* Clear agent forwarding if we don't have an agent. */
  1876. if ((r = ssh_get_authentication_socket(NULL)) != 0) {
  1877. options.forward_agent = 0;
  1878. if (r != SSH_ERR_AGENT_NOT_PRESENT)
  1879. debug("ssh_get_authentication_socket: %s",
  1880. ssh_err(r));
  1881. }
  1882. }
  1883. }
  1884. static void
  1885. ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
  1886. {
  1887. extern char **environ;
  1888. const char *display;
  1889. int r, interactive = tty_flag;
  1890. char *proto = NULL, *data = NULL;
  1891. if (!success)
  1892. return; /* No need for error message, channels code sens one */
  1893. display = getenv("DISPLAY");
  1894. if (display == NULL && options.forward_x11)
  1895. debug("X11 forwarding requested but DISPLAY not set");
  1896. if (options.forward_x11 && client_x11_get_proto(ssh, display,
  1897. options.xauth_location, options.forward_x11_trusted,
  1898. options.forward_x11_timeout, &proto, &data) == 0) {
  1899. /* Request forwarding with authentication spoofing. */
  1900. debug("Requesting X11 forwarding with authentication "
  1901. "spoofing.");
  1902. x11_request_forwarding_with_spoofing(ssh, id, display, proto,
  1903. data, 1);
  1904. client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
  1905. /* XXX exit_on_forward_failure */
  1906. interactive = 1;
  1907. }
  1908. check_agent_present();
  1909. if (options.forward_agent) {
  1910. debug("Requesting authentication agent forwarding.");
  1911. channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
  1912. if ((r = sshpkt_send(ssh)) != 0)
  1913. fatal("%s: %s", __func__, ssh_err(r));
  1914. }
  1915. /* Tell the packet module whether this is an interactive session. */
  1916. ssh_packet_set_interactive(ssh, interactive,
  1917. options.ip_qos_interactive, options.ip_qos_bulk);
  1918. client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
  1919. NULL, fileno(stdin), command, environ);
  1920. }
  1921. void
  1922. hpn_options_init(struct ssh *ssh)
  1923. {
  1924. /*
  1925. * We need to check to see if what they want to do about buffer
  1926. * sizes here. In a hpn to nonhpn connection we want to limit
  1927. * the window size to something reasonable in case the far side
  1928. * has the large window bug. In hpn to hpn connection we want to
  1929. * use the max window size but allow the user to override it
  1930. * lastly if they disabled hpn then use the ssh std window size.
  1931. *
  1932. * So why don't we just do a getsockopt() here and set the
  1933. * ssh window to that? In the case of a autotuning receive
  1934. * window the window would get stuck at the initial buffer
  1935. * size generally less than 96k. Therefore we need to set the
  1936. * maximum ssh window size to the maximum hpn buffer size
  1937. * unless the user has specifically set the tcprcvbufpoll
  1938. * to no. In which case we *can* just set the window to the
  1939. * minimum of the hpn buffer size and tcp receive buffer size.
  1940. */
  1941. if (tty_flag)
  1942. options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
  1943. else
  1944. options.hpn_buffer_size = 6 * 1024 * 1024;
  1945. if (ssh->compat & SSH_BUG_LARGEWINDOW) {
  1946. debug("HPN to Non-HPN connection");
  1947. } else {
  1948. debug("HPN to HPN connection");
  1949. int sock, socksize;
  1950. socklen_t socksizelen;
  1951. if (options.tcp_rcv_buf_poll <= 0) {
  1952. sock = socket(AF_INET, SOCK_STREAM, 0);
  1953. socksizelen = sizeof(socksize);
  1954. getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  1955. &socksize, &socksizelen);
  1956. close(sock);
  1957. debug("socksize %d", socksize);
  1958. options.hpn_buffer_size = socksize;
  1959. debug("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size);
  1960. } else {
  1961. if (options.tcp_rcv_buf > 0) {
  1962. /*
  1963. * Create a socket but don't connect it:
  1964. * we use that the get the rcv socket size
  1965. */
  1966. sock = socket(AF_INET, SOCK_STREAM, 0);
  1967. /*
  1968. * If they are using the tcp_rcv_buf option,
  1969. * attempt to set the buffer size to that.
  1970. */
  1971. if (options.tcp_rcv_buf) {
  1972. socksizelen = sizeof(options.tcp_rcv_buf);
  1973. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  1974. &options.tcp_rcv_buf, socksizelen);
  1975. }
  1976. socksizelen = sizeof(socksize);
  1977. getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  1978. &socksize, &socksizelen);
  1979. close(sock);
  1980. debug("socksize %d", socksize);
  1981. options.hpn_buffer_size = socksize;
  1982. debug("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size);
  1983. }
  1984. }
  1985. }
  1986. debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
  1987. channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
  1988. }
  1989. /* open new channel for a session */
  1990. static int
  1991. ssh_session2_open(struct ssh *ssh)
  1992. {
  1993. Channel *c;
  1994. int window, packetmax, in, out, err;
  1995. if (options.stdin_null) {
  1996. in = open(_PATH_DEVNULL, O_RDONLY);
  1997. } else {
  1998. in = dup(STDIN_FILENO);
  1999. }
  2000. out = dup(STDOUT_FILENO);
  2001. err = dup(STDERR_FILENO);
  2002. if (in == -1 || out == -1 || err == -1)
  2003. fatal("dup() in/out/err failed");
  2004. /* enable nonblocking unless tty */
  2005. if (!isatty(in))
  2006. set_nonblock(in);
  2007. if (!isatty(out))
  2008. set_nonblock(out);
  2009. if (!isatty(err))
  2010. set_nonblock(err);
  2011. window = options.hpn_buffer_size;
  2012. packetmax = CHAN_SES_PACKET_DEFAULT;
  2013. if (tty_flag) {
  2014. window = CHAN_SES_WINDOW_DEFAULT;
  2015. window >>= 1;
  2016. packetmax >>= 1;
  2017. }
  2018. c = channel_new(ssh,
  2019. "session", SSH_CHANNEL_OPENING, in, out, err,
  2020. window, packetmax, CHAN_EXTENDED_WRITE,
  2021. "client-session", /*nonblock*/0);
  2022. if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
  2023. c->dynamic_window = 1;
  2024. debug("Enabled Dynamic Window Scaling");
  2025. }
  2026. debug3("%s: channel_new: %d", __func__, c->self);
  2027. if (options.tcp_rcv_buf_poll > 0 && !options.hpn_disabled) {
  2028. c->dynamic_window = 1;
  2029. debug("Enabled Dynamic Window Scaling");
  2030. }
  2031. channel_send_open(ssh, c->self);
  2032. if (!options.no_shell)
  2033. channel_register_open_confirm(ssh, c->self,
  2034. ssh_session2_setup, NULL);
  2035. return c->self;
  2036. }
  2037. static int
  2038. ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
  2039. {
  2040. int r, devnull, id = -1;
  2041. char *cp, *tun_fwd_ifname = NULL;
  2042. /*
  2043. * We need to initialize this early because the forwarding logic below
  2044. * might open channels that use the hpn buffer sizes. We can't send a
  2045. * window of -1 (the default) to the server as it breaks things.
  2046. */
  2047. hpn_options_init(ssh);
  2048. /* XXX should be pre-session */
  2049. if (!options.control_persist)
  2050. ssh_init_stdio_forwarding(ssh);
  2051. ssh_init_forwarding(ssh, &tun_fwd_ifname);
  2052. if (options.local_command != NULL) {
  2053. debug3("expanding LocalCommand: %s", options.local_command);
  2054. cp = options.local_command;
  2055. options.local_command = percent_expand(cp,
  2056. DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
  2057. "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
  2058. (char *)NULL);
  2059. debug3("expanded LocalCommand: %s", options.local_command);
  2060. free(cp);
  2061. }
  2062. /* Start listening for multiplex clients */
  2063. if (!ssh_packet_get_mux(ssh))
  2064. muxserver_listen(ssh);
  2065. /*
  2066. * If we are in control persist mode and have a working mux listen
  2067. * socket, then prepare to background ourselves and have a foreground
  2068. * client attach as a control client.
  2069. * NB. we must save copies of the flags that we override for
  2070. * the backgrounding, since we defer attachment of the client until
  2071. * after the connection is fully established (in particular,
  2072. * async rfwd replies have been received for ExitOnForwardFailure).
  2073. */
  2074. if (options.control_persist && muxserver_sock != -1) {
  2075. ostdin_null_flag = options.stdin_null;
  2076. orequest_tty = options.request_tty;
  2077. otty_flag = tty_flag;
  2078. options.stdin_null = 1;
  2079. options.no_shell = 1;
  2080. tty_flag = 0;
  2081. if (!options.fork_after_authentication)
  2082. need_controlpersist_detach = 1;
  2083. options.fork_after_authentication = 1;
  2084. }
  2085. /*
  2086. * ControlPersist mux listen socket setup failed, attempt the
  2087. * stdio forward setup that we skipped earlier.
  2088. */
  2089. if (options.control_persist && muxserver_sock == -1)
  2090. ssh_init_stdio_forwarding(ssh);
  2091. if (!options.no_shell)
  2092. id = ssh_session2_open(ssh);
  2093. else {
  2094. ssh_packet_set_interactive(ssh,
  2095. options.control_master == SSHCTL_MASTER_NO,
  2096. options.ip_qos_interactive, options.ip_qos_bulk);
  2097. }
  2098. /* If we don't expect to open a new session, then disallow it */
  2099. if (options.control_master == SSHCTL_MASTER_NO &&
  2100. (ssh->compat & SSH_NEW_OPENSSH)) {
  2101. debug("Requesting no-more-sessions@openssh.com");
  2102. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  2103. (r = sshpkt_put_cstring(ssh,
  2104. "no-more-sessions@openssh.com")) != 0 ||
  2105. (r = sshpkt_put_u8(ssh, 0)) != 0 ||
  2106. (r = sshpkt_send(ssh)) != 0)
  2107. fatal("%s: %s", __func__, ssh_err(r));
  2108. }
  2109. /* Execute a local command */
  2110. if (options.local_command != NULL &&
  2111. options.permit_local_command)
  2112. ssh_local_cmd(options.local_command);
  2113. /*
  2114. * stdout is now owned by the session channel; clobber it here
  2115. * so future channel closes are propagated to the local fd.
  2116. * NB. this can only happen after LocalCommand has completed,
  2117. * as it may want to write to stdout.
  2118. */
  2119. if (!need_controlpersist_detach) {
  2120. if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1) {
  2121. error("%s: open %s: %s", __func__,
  2122. _PATH_DEVNULL, strerror(errno));
  2123. } else {
  2124. if (dup2(devnull, STDOUT_FILENO) == -1)
  2125. fatal("%s: dup2() stdout failed", __func__);
  2126. if (devnull > STDERR_FILENO)
  2127. close(devnull);
  2128. }
  2129. }
  2130. /*
  2131. * If requested and we are not interested in replies to remote
  2132. * forwarding requests, then let ssh continue in the background.
  2133. */
  2134. if (options.fork_after_authentication) {
  2135. if (options.exit_on_forward_failure &&
  2136. options.num_remote_forwards > 0) {
  2137. debug("deferring postauth fork until remote forward "
  2138. "confirmation received");
  2139. } else
  2140. fork_postauth();
  2141. }
  2142. return client_loop(ssh, tty_flag, tty_flag ?
  2143. options.escape_char : SSH_ESCAPECHAR_NONE, id);
  2144. }
  2145. #ifdef ENABLE_PKCS11
  2146. static void
  2147. load_pkcs11_identity(char *pkcs11_uri, char *identity_files[],
  2148. struct sshkey *identity_keys[], int *n_ids)
  2149. {
  2150. int nkeys, i;
  2151. struct sshkey **keys;
  2152. struct pkcs11_uri *uri;
  2153. debug("identity file '%s' from pkcs#11", pkcs11_uri);
  2154. uri = pkcs11_uri_init();
  2155. if (uri == NULL)
  2156. fatal("Failed to init PKCS#11 URI");
  2157. if (pkcs11_uri_parse(pkcs11_uri, uri) != 0)
  2158. fatal("Failed to parse PKCS#11 URI %s", pkcs11_uri);
  2159. /* we need to merge URI and provider together */
  2160. if (options.pkcs11_provider != NULL && uri->module_path == NULL)
  2161. uri->module_path = strdup(options.pkcs11_provider);
  2162. if (options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
  2163. (nkeys = pkcs11_add_provider_by_uri(uri, NULL, &keys, NULL)) > 0) {
  2164. for (i = 0; i < nkeys; i++) {
  2165. if (*n_ids >= SSH_MAX_IDENTITY_FILES) {
  2166. sshkey_free(keys[i]);
  2167. continue;
  2168. }
  2169. identity_keys[*n_ids] = keys[i];
  2170. identity_files[*n_ids] = pkcs11_uri_get(uri);
  2171. (*n_ids)++;
  2172. }
  2173. free(keys);
  2174. }
  2175. pkcs11_uri_cleanup(uri);
  2176. }
  2177. #endif /* ENABLE_PKCS11 */
  2178. /* Loads all IdentityFile and CertificateFile keys */
  2179. static void
  2180. load_public_identity_files(const struct ssh_conn_info *cinfo)
  2181. {
  2182. char *filename, *cp;
  2183. struct sshkey *public;
  2184. int i;
  2185. u_int n_ids, n_certs;
  2186. char *identity_files[SSH_MAX_IDENTITY_FILES];
  2187. struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
  2188. int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
  2189. char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
  2190. struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
  2191. int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
  2192. n_ids = n_certs = 0;
  2193. memset(identity_files, 0, sizeof(identity_files));
  2194. memset(identity_keys, 0, sizeof(identity_keys));
  2195. memset(identity_file_userprovided, 0,
  2196. sizeof(identity_file_userprovided));
  2197. memset(certificate_files, 0, sizeof(certificate_files));
  2198. memset(certificates, 0, sizeof(certificates));
  2199. memset(certificate_file_userprovided, 0,
  2200. sizeof(certificate_file_userprovided));
  2201. #ifdef ENABLE_PKCS11
  2202. /* handle fallback from PKCS11Provider option */
  2203. pkcs11_init(!options.batch_mode);
  2204. if (options.pkcs11_provider != NULL) {
  2205. struct pkcs11_uri *uri;
  2206. uri = pkcs11_uri_init();
  2207. if (uri == NULL)
  2208. fatal("Failed to init PKCS#11 URI");
  2209. /* Construct simple PKCS#11 URI to simplify access */
  2210. uri->module_path = strdup(options.pkcs11_provider);
  2211. /* Add it as any other IdentityFile */
  2212. cp = pkcs11_uri_get(uri);
  2213. add_identity_file(&options, NULL, cp, 1);
  2214. free(cp);
  2215. pkcs11_uri_cleanup(uri);
  2216. }
  2217. #endif /* ENABLE_PKCS11 */
  2218. for (i = 0; i < options.num_identity_files; i++) {
  2219. char *name = options.identity_files[i];
  2220. if (n_ids >= SSH_MAX_IDENTITY_FILES ||
  2221. strcasecmp(name, "none") == 0) {
  2222. free(options.identity_files[i]);
  2223. options.identity_files[i] = NULL;
  2224. continue;
  2225. }
  2226. #ifdef ENABLE_PKCS11
  2227. if (strlen(name) >= strlen(PKCS11_URI_SCHEME) &&
  2228. strncmp(name, PKCS11_URI_SCHEME,
  2229. strlen(PKCS11_URI_SCHEME)) == 0) {
  2230. load_pkcs11_identity(name, identity_files,
  2231. identity_keys, &n_ids);
  2232. free(options.identity_files[i]);
  2233. continue;
  2234. }
  2235. #endif /* ENABLE_PKCS11 */
  2236. cp = tilde_expand_filename(name, getuid());
  2237. filename = default_client_percent_dollar_expand(cp, cinfo);
  2238. free(cp);
  2239. check_load(sshkey_load_public(filename, &public, NULL),
  2240. filename, "pubkey");
  2241. debug("identity file %s type %d", filename,
  2242. public ? public->type : -1);
  2243. free(options.identity_files[i]);
  2244. identity_files[n_ids] = filename;
  2245. identity_keys[n_ids] = public;
  2246. identity_file_userprovided[n_ids] =
  2247. options.identity_file_userprovided[i];
  2248. if (++n_ids >= SSH_MAX_IDENTITY_FILES)
  2249. continue;
  2250. /*
  2251. * If no certificates have been explicitly listed then try
  2252. * to add the default certificate variant too.
  2253. */
  2254. if (options.num_certificate_files != 0)
  2255. continue;
  2256. xasprintf(&cp, "%s-cert", filename);
  2257. check_load(sshkey_load_public(cp, &public, NULL),
  2258. filename, "pubkey");
  2259. debug("identity file %s type %d", cp,
  2260. public ? public->type : -1);
  2261. if (public == NULL) {
  2262. free(cp);
  2263. continue;
  2264. }
  2265. if (!sshkey_is_cert(public)) {
  2266. debug("%s: key %s type %s is not a certificate",
  2267. __func__, cp, sshkey_type(public));
  2268. sshkey_free(public);
  2269. free(cp);
  2270. continue;
  2271. }
  2272. /* NB. leave filename pointing to private key */
  2273. identity_files[n_ids] = xstrdup(filename);
  2274. identity_keys[n_ids] = public;
  2275. identity_file_userprovided[n_ids] =
  2276. options.identity_file_userprovided[i];
  2277. n_ids++;
  2278. }
  2279. if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
  2280. fatal("%s: too many certificates", __func__);
  2281. for (i = 0; i < options.num_certificate_files; i++) {
  2282. cp = tilde_expand_filename(options.certificate_files[i],
  2283. getuid());
  2284. filename = default_client_percent_dollar_expand(cp, cinfo);
  2285. free(cp);
  2286. check_load(sshkey_load_public(filename, &public, NULL),
  2287. filename, "certificate");
  2288. debug("certificate file %s type %d", filename,
  2289. public ? public->type : -1);
  2290. free(options.certificate_files[i]);
  2291. options.certificate_files[i] = NULL;
  2292. if (public == NULL) {
  2293. free(filename);
  2294. continue;
  2295. }
  2296. if (!sshkey_is_cert(public)) {
  2297. debug("%s: key %s type %s is not a certificate",
  2298. __func__, filename, sshkey_type(public));
  2299. sshkey_free(public);
  2300. free(filename);
  2301. continue;
  2302. }
  2303. certificate_files[n_certs] = filename;
  2304. certificates[n_certs] = public;
  2305. certificate_file_userprovided[n_certs] =
  2306. options.certificate_file_userprovided[i];
  2307. ++n_certs;
  2308. }
  2309. options.num_identity_files = n_ids;
  2310. memcpy(options.identity_files, identity_files, sizeof(identity_files));
  2311. memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
  2312. memcpy(options.identity_file_userprovided,
  2313. identity_file_userprovided, sizeof(identity_file_userprovided));
  2314. options.num_certificate_files = n_certs;
  2315. memcpy(options.certificate_files,
  2316. certificate_files, sizeof(certificate_files));
  2317. memcpy(options.certificates, certificates, sizeof(certificates));
  2318. memcpy(options.certificate_file_userprovided,
  2319. certificate_file_userprovided,
  2320. sizeof(certificate_file_userprovided));
  2321. }
  2322. static void
  2323. main_sigchld_handler(int sig)
  2324. {
  2325. int save_errno = errno;
  2326. pid_t pid;
  2327. int status;
  2328. while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
  2329. (pid == -1 && errno == EINTR))
  2330. ;
  2331. errno = save_errno;
  2332. }