ssh-keygen.c 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754
  1. /* $OpenBSD: ssh-keygen.c,v 1.420 2020/09/09 03:08:01 djm Exp $ */
  2. /*
  3. * Author: Tatu Ylonen <ylo@cs.hut.fi>
  4. * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
  5. * All rights reserved
  6. * Identity and host key generation and maintenance.
  7. *
  8. * As far as I am concerned, the code I have written for this software
  9. * can be used freely for any purpose. Any derived versions of this
  10. * software must be clearly marked as such, and if the derived work is
  11. * incompatible with the protocol description in the RFC file, it must be
  12. * called by a name other than "ssh" or "Secure Shell".
  13. */
  14. #include "includes.h"
  15. #include <sys/types.h>
  16. #include <sys/socket.h>
  17. #include <sys/stat.h>
  18. #ifdef WITH_OPENSSL
  19. #include <openssl/evp.h>
  20. #include <openssl/pem.h>
  21. #include "openbsd-compat/openssl-compat.h"
  22. #endif
  23. #ifdef HAVE_STDINT_H
  24. # include <stdint.h>
  25. #endif
  26. #include <errno.h>
  27. #include <fcntl.h>
  28. #include <netdb.h>
  29. #ifdef HAVE_PATHS_H
  30. # include <paths.h>
  31. #endif
  32. #include <pwd.h>
  33. #include <stdarg.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <unistd.h>
  38. #include <limits.h>
  39. #include <locale.h>
  40. #include <time.h>
  41. #include "xmalloc.h"
  42. #include "sshkey.h"
  43. #include "authfile.h"
  44. #include "sshbuf.h"
  45. #include "pathnames.h"
  46. #include "log.h"
  47. #include "misc.h"
  48. #include "match.h"
  49. #include "hostfile.h"
  50. #include "dns.h"
  51. #include "ssh.h"
  52. #include "ssh2.h"
  53. #include "ssherr.h"
  54. #include "ssh-pkcs11.h"
  55. #include "atomicio.h"
  56. #include "krl.h"
  57. #include "digest.h"
  58. #include "utf8.h"
  59. #include "authfd.h"
  60. #include "sshsig.h"
  61. #include "ssh-sk.h"
  62. #include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */
  63. #include "cipher.h"
  64. #ifdef WITH_OPENSSL
  65. # define DEFAULT_KEY_TYPE_NAME "rsa"
  66. #else
  67. # define DEFAULT_KEY_TYPE_NAME "ed25519"
  68. #endif
  69. /*
  70. * Default number of bits in the RSA, DSA and ECDSA keys. These value can be
  71. * overridden on the command line.
  72. *
  73. * These values, with the exception of DSA, provide security equivalent to at
  74. * least 128 bits of security according to NIST Special Publication 800-57:
  75. * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
  76. * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
  77. * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
  78. * SHA1 we limit the DSA key size 1k bits.
  79. */
  80. #define DEFAULT_BITS 3072
  81. #define DEFAULT_BITS_DSA 1024
  82. #define DEFAULT_BITS_ECDSA 256
  83. static int quiet = 0;
  84. /* Flag indicating that we just want to see the key fingerprint */
  85. static int print_fingerprint = 0;
  86. static int print_bubblebabble = 0;
  87. /* Hash algorithm to use for fingerprints. */
  88. static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
  89. /* The identity file name, given on the command line or entered by the user. */
  90. static char identity_file[PATH_MAX];
  91. static int have_identity = 0;
  92. /* This is set to the passphrase if given on the command line. */
  93. static char *identity_passphrase = NULL;
  94. /* This is set to the new passphrase if given on the command line. */
  95. static char *identity_new_passphrase = NULL;
  96. /* Key type when certifying */
  97. static u_int cert_key_type = SSH2_CERT_TYPE_USER;
  98. /* "key ID" of signed key */
  99. static char *cert_key_id = NULL;
  100. /* Comma-separated list of principal names for certifying keys */
  101. static char *cert_principals = NULL;
  102. /* Validity period for certificates */
  103. static u_int64_t cert_valid_from = 0;
  104. static u_int64_t cert_valid_to = ~0ULL;
  105. /* Certificate options */
  106. #define CERTOPT_X_FWD (1)
  107. #define CERTOPT_AGENT_FWD (1<<1)
  108. #define CERTOPT_PORT_FWD (1<<2)
  109. #define CERTOPT_PTY (1<<3)
  110. #define CERTOPT_USER_RC (1<<4)
  111. #define CERTOPT_NO_REQUIRE_USER_PRESENCE (1<<5)
  112. #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
  113. CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
  114. static u_int32_t certflags_flags = CERTOPT_DEFAULT;
  115. static char *certflags_command = NULL;
  116. static char *certflags_src_addr = NULL;
  117. /* Arbitrary extensions specified by user */
  118. struct cert_ext {
  119. char *key;
  120. char *val;
  121. int crit;
  122. };
  123. static struct cert_ext *cert_ext;
  124. static size_t ncert_ext;
  125. /* Conversion to/from various formats */
  126. enum {
  127. FMT_RFC4716,
  128. FMT_PKCS8,
  129. FMT_PEM
  130. } convert_format = FMT_RFC4716;
  131. static char *key_type_name = NULL;
  132. /* Load key from this PKCS#11 provider */
  133. static char *pkcs11provider = NULL;
  134. /* FIDO/U2F provider to use */
  135. static char *sk_provider = NULL;
  136. /* Format for writing private keys */
  137. static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
  138. /* Cipher for new-format private keys */
  139. static char *openssh_format_cipher = NULL;
  140. /* Number of KDF rounds to derive new format keys. */
  141. static int rounds = 0;
  142. /* argv0 */
  143. extern char *__progname;
  144. static char hostname[NI_MAXHOST];
  145. #ifdef WITH_OPENSSL
  146. /* moduli.c */
  147. int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
  148. int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
  149. unsigned long);
  150. #endif
  151. static void
  152. type_bits_valid(int type, const char *name, u_int32_t *bitsp)
  153. {
  154. if (type == KEY_UNSPEC)
  155. fatal("unknown key type %s", key_type_name);
  156. if (*bitsp == 0) {
  157. #ifdef WITH_OPENSSL
  158. int nid;
  159. switch(type) {
  160. case KEY_DSA:
  161. *bitsp = DEFAULT_BITS_DSA;
  162. break;
  163. case KEY_ECDSA:
  164. if (name != NULL &&
  165. (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
  166. *bitsp = sshkey_curve_nid_to_bits(nid);
  167. if (*bitsp == 0)
  168. *bitsp = DEFAULT_BITS_ECDSA;
  169. break;
  170. case KEY_RSA:
  171. *bitsp = DEFAULT_BITS;
  172. break;
  173. }
  174. #endif
  175. }
  176. #ifdef WITH_OPENSSL
  177. switch (type) {
  178. case KEY_DSA:
  179. if (*bitsp != 1024)
  180. fatal("Invalid DSA key length: must be 1024 bits");
  181. break;
  182. case KEY_RSA:
  183. if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
  184. fatal("Invalid RSA key length: minimum is %d bits",
  185. SSH_RSA_MINIMUM_MODULUS_SIZE);
  186. else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
  187. fatal("Invalid RSA key length: maximum is %d bits",
  188. OPENSSL_RSA_MAX_MODULUS_BITS);
  189. break;
  190. case KEY_ECDSA:
  191. if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
  192. fatal("Invalid ECDSA key length: valid lengths are "
  193. #ifdef OPENSSL_HAS_NISTP521
  194. "256, 384 or 521 bits");
  195. #else
  196. "256 or 384 bits");
  197. #endif
  198. }
  199. #endif
  200. }
  201. /*
  202. * Checks whether a file exists and, if so, asks the user whether they wish
  203. * to overwrite it.
  204. * Returns nonzero if the file does not already exist or if the user agrees to
  205. * overwrite, or zero otherwise.
  206. */
  207. static int
  208. confirm_overwrite(const char *filename)
  209. {
  210. char yesno[3];
  211. struct stat st;
  212. if (stat(filename, &st) != 0)
  213. return 1;
  214. printf("%s already exists.\n", filename);
  215. printf("Overwrite (y/n)? ");
  216. fflush(stdout);
  217. if (fgets(yesno, sizeof(yesno), stdin) == NULL)
  218. return 0;
  219. if (yesno[0] != 'y' && yesno[0] != 'Y')
  220. return 0;
  221. return 1;
  222. }
  223. static void
  224. ask_filename(struct passwd *pw, const char *prompt)
  225. {
  226. char buf[1024];
  227. char *name = NULL;
  228. if (key_type_name == NULL)
  229. name = _PATH_SSH_CLIENT_ID_RSA;
  230. else {
  231. switch (sshkey_type_from_name(key_type_name)) {
  232. case KEY_DSA_CERT:
  233. case KEY_DSA:
  234. name = _PATH_SSH_CLIENT_ID_DSA;
  235. break;
  236. #ifdef OPENSSL_HAS_ECC
  237. case KEY_ECDSA_CERT:
  238. case KEY_ECDSA:
  239. name = _PATH_SSH_CLIENT_ID_ECDSA;
  240. break;
  241. case KEY_ECDSA_SK_CERT:
  242. case KEY_ECDSA_SK:
  243. name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
  244. break;
  245. #endif
  246. case KEY_RSA_CERT:
  247. case KEY_RSA:
  248. name = _PATH_SSH_CLIENT_ID_RSA;
  249. break;
  250. case KEY_ED25519:
  251. case KEY_ED25519_CERT:
  252. name = _PATH_SSH_CLIENT_ID_ED25519;
  253. break;
  254. case KEY_ED25519_SK:
  255. case KEY_ED25519_SK_CERT:
  256. name = _PATH_SSH_CLIENT_ID_ED25519_SK;
  257. break;
  258. case KEY_XMSS:
  259. case KEY_XMSS_CERT:
  260. name = _PATH_SSH_CLIENT_ID_XMSS;
  261. break;
  262. default:
  263. fatal("bad key type");
  264. }
  265. }
  266. snprintf(identity_file, sizeof(identity_file),
  267. "%s/%s", pw->pw_dir, name);
  268. printf("%s (%s): ", prompt, identity_file);
  269. fflush(stdout);
  270. if (fgets(buf, sizeof(buf), stdin) == NULL)
  271. exit(1);
  272. buf[strcspn(buf, "\n")] = '\0';
  273. if (strcmp(buf, "") != 0)
  274. strlcpy(identity_file, buf, sizeof(identity_file));
  275. have_identity = 1;
  276. }
  277. static struct sshkey *
  278. load_identity(const char *filename, char **commentp)
  279. {
  280. char *pass;
  281. struct sshkey *prv;
  282. int r;
  283. if (commentp != NULL)
  284. *commentp = NULL;
  285. if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
  286. return prv;
  287. if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
  288. fatal("Load key \"%s\": %s", filename, ssh_err(r));
  289. if (identity_passphrase)
  290. pass = xstrdup(identity_passphrase);
  291. else
  292. pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
  293. r = sshkey_load_private(filename, pass, &prv, commentp);
  294. freezero(pass, strlen(pass));
  295. if (r != 0)
  296. fatal("Load key \"%s\": %s", filename, ssh_err(r));
  297. return prv;
  298. }
  299. #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
  300. #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
  301. #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
  302. #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
  303. #ifdef WITH_OPENSSL
  304. static void
  305. do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
  306. {
  307. struct sshbuf *b;
  308. char comment[61], *b64;
  309. int r;
  310. if ((b = sshbuf_new()) == NULL)
  311. fatal("%s: sshbuf_new failed", __func__);
  312. if ((r = sshkey_putb(k, b)) != 0)
  313. fatal("key_to_blob failed: %s", ssh_err(r));
  314. if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
  315. fatal("%s: sshbuf_dtob64_string failed", __func__);
  316. /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
  317. snprintf(comment, sizeof(comment),
  318. "%u-bit %s, converted by %s@%s from OpenSSH",
  319. sshkey_size(k), sshkey_type(k),
  320. pw->pw_name, hostname);
  321. sshkey_free(k);
  322. sshbuf_free(b);
  323. fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
  324. fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
  325. fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
  326. free(b64);
  327. exit(0);
  328. }
  329. static void
  330. do_convert_to_pkcs8(struct sshkey *k)
  331. {
  332. switch (sshkey_type_plain(k->type)) {
  333. case KEY_RSA:
  334. if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
  335. fatal("PEM_write_RSA_PUBKEY failed");
  336. break;
  337. case KEY_DSA:
  338. if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
  339. fatal("PEM_write_DSA_PUBKEY failed");
  340. break;
  341. #ifdef OPENSSL_HAS_ECC
  342. case KEY_ECDSA:
  343. if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
  344. fatal("PEM_write_EC_PUBKEY failed");
  345. break;
  346. #endif
  347. default:
  348. fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
  349. }
  350. exit(0);
  351. }
  352. static void
  353. do_convert_to_pem(struct sshkey *k)
  354. {
  355. switch (sshkey_type_plain(k->type)) {
  356. case KEY_RSA:
  357. if (!PEM_write_RSAPublicKey(stdout, k->rsa))
  358. fatal("PEM_write_RSAPublicKey failed");
  359. break;
  360. case KEY_DSA:
  361. if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
  362. fatal("PEM_write_DSA_PUBKEY failed");
  363. break;
  364. #ifdef OPENSSL_HAS_ECC
  365. case KEY_ECDSA:
  366. if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
  367. fatal("PEM_write_EC_PUBKEY failed");
  368. break;
  369. #endif
  370. default:
  371. fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
  372. }
  373. exit(0);
  374. }
  375. static void
  376. do_convert_to(struct passwd *pw)
  377. {
  378. struct sshkey *k;
  379. struct stat st;
  380. int r;
  381. if (!have_identity)
  382. ask_filename(pw, "Enter file in which the key is");
  383. if (stat(identity_file, &st) == -1)
  384. fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
  385. if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
  386. k = load_identity(identity_file, NULL);
  387. switch (convert_format) {
  388. case FMT_RFC4716:
  389. do_convert_to_ssh2(pw, k);
  390. break;
  391. case FMT_PKCS8:
  392. do_convert_to_pkcs8(k);
  393. break;
  394. case FMT_PEM:
  395. do_convert_to_pem(k);
  396. break;
  397. default:
  398. fatal("%s: unknown key format %d", __func__, convert_format);
  399. }
  400. exit(0);
  401. }
  402. /*
  403. * This is almost exactly the bignum1 encoding, but with 32 bit for length
  404. * instead of 16.
  405. */
  406. static void
  407. buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
  408. {
  409. u_int bytes, bignum_bits;
  410. int r;
  411. if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
  412. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  413. bytes = (bignum_bits + 7) / 8;
  414. if (sshbuf_len(b) < bytes)
  415. fatal("%s: input buffer too small: need %d have %zu",
  416. __func__, bytes, sshbuf_len(b));
  417. if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
  418. fatal("%s: BN_bin2bn failed", __func__);
  419. if ((r = sshbuf_consume(b, bytes)) != 0)
  420. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  421. }
  422. static struct sshkey *
  423. do_convert_private_ssh2(struct sshbuf *b)
  424. {
  425. struct sshkey *key = NULL;
  426. char *type, *cipher;
  427. u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
  428. int r, rlen, ktype;
  429. u_int magic, i1, i2, i3, i4;
  430. size_t slen;
  431. u_long e;
  432. BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
  433. BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
  434. BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
  435. BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
  436. if ((r = sshbuf_get_u32(b, &magic)) != 0)
  437. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  438. if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
  439. error("bad magic 0x%x != 0x%x", magic,
  440. SSH_COM_PRIVATE_KEY_MAGIC);
  441. return NULL;
  442. }
  443. if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
  444. (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
  445. (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
  446. (r = sshbuf_get_u32(b, &i2)) != 0 ||
  447. (r = sshbuf_get_u32(b, &i3)) != 0 ||
  448. (r = sshbuf_get_u32(b, &i4)) != 0)
  449. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  450. debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
  451. if (strcmp(cipher, "none") != 0) {
  452. error("unsupported cipher %s", cipher);
  453. free(cipher);
  454. free(type);
  455. return NULL;
  456. }
  457. free(cipher);
  458. if (strstr(type, "dsa")) {
  459. ktype = KEY_DSA;
  460. } else if (strstr(type, "rsa")) {
  461. ktype = KEY_RSA;
  462. } else {
  463. free(type);
  464. return NULL;
  465. }
  466. if ((key = sshkey_new(ktype)) == NULL)
  467. fatal("sshkey_new failed");
  468. free(type);
  469. switch (key->type) {
  470. case KEY_DSA:
  471. if ((dsa_p = BN_new()) == NULL ||
  472. (dsa_q = BN_new()) == NULL ||
  473. (dsa_g = BN_new()) == NULL ||
  474. (dsa_pub_key = BN_new()) == NULL ||
  475. (dsa_priv_key = BN_new()) == NULL)
  476. fatal("%s: BN_new", __func__);
  477. buffer_get_bignum_bits(b, dsa_p);
  478. buffer_get_bignum_bits(b, dsa_g);
  479. buffer_get_bignum_bits(b, dsa_q);
  480. buffer_get_bignum_bits(b, dsa_pub_key);
  481. buffer_get_bignum_bits(b, dsa_priv_key);
  482. if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
  483. fatal("%s: DSA_set0_pqg failed", __func__);
  484. dsa_p = dsa_q = dsa_g = NULL; /* transferred */
  485. if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
  486. fatal("%s: DSA_set0_key failed", __func__);
  487. dsa_pub_key = dsa_priv_key = NULL; /* transferred */
  488. break;
  489. case KEY_RSA:
  490. if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
  491. (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
  492. (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
  493. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  494. e = e1;
  495. debug("e %lx", e);
  496. if (e < 30) {
  497. e <<= 8;
  498. e += e2;
  499. debug("e %lx", e);
  500. e <<= 8;
  501. e += e3;
  502. debug("e %lx", e);
  503. }
  504. if ((rsa_e = BN_new()) == NULL)
  505. fatal("%s: BN_new", __func__);
  506. if (!BN_set_word(rsa_e, e)) {
  507. BN_clear_free(rsa_e);
  508. sshkey_free(key);
  509. return NULL;
  510. }
  511. if ((rsa_n = BN_new()) == NULL ||
  512. (rsa_d = BN_new()) == NULL ||
  513. (rsa_p = BN_new()) == NULL ||
  514. (rsa_q = BN_new()) == NULL ||
  515. (rsa_iqmp = BN_new()) == NULL)
  516. fatal("%s: BN_new", __func__);
  517. buffer_get_bignum_bits(b, rsa_d);
  518. buffer_get_bignum_bits(b, rsa_n);
  519. buffer_get_bignum_bits(b, rsa_iqmp);
  520. buffer_get_bignum_bits(b, rsa_q);
  521. buffer_get_bignum_bits(b, rsa_p);
  522. if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
  523. fatal("%s: RSA_set0_key failed", __func__);
  524. rsa_n = rsa_e = rsa_d = NULL; /* transferred */
  525. if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
  526. fatal("%s: RSA_set0_factors failed", __func__);
  527. rsa_p = rsa_q = NULL; /* transferred */
  528. if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
  529. fatal("generate RSA parameters failed: %s", ssh_err(r));
  530. BN_clear_free(rsa_iqmp);
  531. break;
  532. }
  533. rlen = sshbuf_len(b);
  534. if (rlen != 0)
  535. error("%s: remaining bytes in key blob %d", __func__, rlen);
  536. /* try the key */
  537. if (sshkey_sign(key, &sig, &slen, data, sizeof(data),
  538. NULL, NULL, NULL, 0) != 0 ||
  539. sshkey_verify(key, sig, slen, data, sizeof(data),
  540. NULL, 0, NULL) != 0) {
  541. sshkey_free(key);
  542. free(sig);
  543. return NULL;
  544. }
  545. free(sig);
  546. return key;
  547. }
  548. static int
  549. get_line(FILE *fp, char *line, size_t len)
  550. {
  551. int c;
  552. size_t pos = 0;
  553. line[0] = '\0';
  554. while ((c = fgetc(fp)) != EOF) {
  555. if (pos >= len - 1)
  556. fatal("input line too long.");
  557. switch (c) {
  558. case '\r':
  559. c = fgetc(fp);
  560. if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
  561. fatal("unget: %s", strerror(errno));
  562. return pos;
  563. case '\n':
  564. return pos;
  565. }
  566. line[pos++] = c;
  567. line[pos] = '\0';
  568. }
  569. /* We reached EOF */
  570. return -1;
  571. }
  572. static void
  573. do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
  574. {
  575. int r, blen, escaped = 0;
  576. u_int len;
  577. char line[1024];
  578. struct sshbuf *buf;
  579. char encoded[8096];
  580. FILE *fp;
  581. if ((buf = sshbuf_new()) == NULL)
  582. fatal("sshbuf_new failed");
  583. if ((fp = fopen(identity_file, "r")) == NULL)
  584. fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
  585. encoded[0] = '\0';
  586. while ((blen = get_line(fp, line, sizeof(line))) != -1) {
  587. if (blen > 0 && line[blen - 1] == '\\')
  588. escaped++;
  589. if (strncmp(line, "----", 4) == 0 ||
  590. strstr(line, ": ") != NULL) {
  591. if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
  592. *private = 1;
  593. if (strstr(line, " END ") != NULL) {
  594. break;
  595. }
  596. /* fprintf(stderr, "ignore: %s", line); */
  597. continue;
  598. }
  599. if (escaped) {
  600. escaped--;
  601. /* fprintf(stderr, "escaped: %s", line); */
  602. continue;
  603. }
  604. strlcat(encoded, line, sizeof(encoded));
  605. }
  606. len = strlen(encoded);
  607. if (((len % 4) == 3) &&
  608. (encoded[len-1] == '=') &&
  609. (encoded[len-2] == '=') &&
  610. (encoded[len-3] == '='))
  611. encoded[len-3] = '\0';
  612. if ((r = sshbuf_b64tod(buf, encoded)) != 0)
  613. fatal("%s: base64 decoding failed: %s", __func__, ssh_err(r));
  614. if (*private) {
  615. if ((*k = do_convert_private_ssh2(buf)) == NULL)
  616. fatal("%s: private key conversion failed", __func__);
  617. } else if ((r = sshkey_fromb(buf, k)) != 0)
  618. fatal("decode blob failed: %s", ssh_err(r));
  619. sshbuf_free(buf);
  620. fclose(fp);
  621. }
  622. static void
  623. do_convert_from_pkcs8(struct sshkey **k, int *private)
  624. {
  625. EVP_PKEY *pubkey;
  626. FILE *fp;
  627. if ((fp = fopen(identity_file, "r")) == NULL)
  628. fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
  629. if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
  630. fatal("%s: %s is not a recognised public key format", __func__,
  631. identity_file);
  632. }
  633. fclose(fp);
  634. switch (EVP_PKEY_base_id(pubkey)) {
  635. case EVP_PKEY_RSA:
  636. if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
  637. fatal("sshkey_new failed");
  638. (*k)->type = KEY_RSA;
  639. (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
  640. break;
  641. case EVP_PKEY_DSA:
  642. if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
  643. fatal("sshkey_new failed");
  644. (*k)->type = KEY_DSA;
  645. (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
  646. break;
  647. #ifdef OPENSSL_HAS_ECC
  648. case EVP_PKEY_EC:
  649. if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
  650. fatal("sshkey_new failed");
  651. (*k)->type = KEY_ECDSA;
  652. (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
  653. (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
  654. break;
  655. #endif
  656. default:
  657. fatal("%s: unsupported pubkey type %d", __func__,
  658. EVP_PKEY_base_id(pubkey));
  659. }
  660. EVP_PKEY_free(pubkey);
  661. return;
  662. }
  663. static void
  664. do_convert_from_pem(struct sshkey **k, int *private)
  665. {
  666. FILE *fp;
  667. RSA *rsa;
  668. if ((fp = fopen(identity_file, "r")) == NULL)
  669. fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
  670. if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
  671. if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
  672. fatal("sshkey_new failed");
  673. (*k)->type = KEY_RSA;
  674. (*k)->rsa = rsa;
  675. fclose(fp);
  676. return;
  677. }
  678. fatal("%s: unrecognised raw private key format", __func__);
  679. }
  680. static void
  681. do_convert_from(struct passwd *pw)
  682. {
  683. struct sshkey *k = NULL;
  684. int r, private = 0, ok = 0;
  685. struct stat st;
  686. if (!have_identity)
  687. ask_filename(pw, "Enter file in which the key is");
  688. if (stat(identity_file, &st) == -1)
  689. fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
  690. switch (convert_format) {
  691. case FMT_RFC4716:
  692. do_convert_from_ssh2(pw, &k, &private);
  693. break;
  694. case FMT_PKCS8:
  695. do_convert_from_pkcs8(&k, &private);
  696. break;
  697. case FMT_PEM:
  698. do_convert_from_pem(&k, &private);
  699. break;
  700. default:
  701. fatal("%s: unknown key format %d", __func__, convert_format);
  702. }
  703. if (!private) {
  704. if ((r = sshkey_write(k, stdout)) == 0)
  705. ok = 1;
  706. if (ok)
  707. fprintf(stdout, "\n");
  708. } else {
  709. switch (k->type) {
  710. case KEY_DSA:
  711. ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
  712. NULL, 0, NULL, NULL);
  713. break;
  714. #ifdef OPENSSL_HAS_ECC
  715. case KEY_ECDSA:
  716. ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
  717. NULL, 0, NULL, NULL);
  718. break;
  719. #endif
  720. case KEY_RSA:
  721. ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
  722. NULL, 0, NULL, NULL);
  723. break;
  724. default:
  725. fatal("%s: unsupported key type %s", __func__,
  726. sshkey_type(k));
  727. }
  728. }
  729. if (!ok)
  730. fatal("key write failed");
  731. sshkey_free(k);
  732. exit(0);
  733. }
  734. #endif
  735. static void
  736. do_print_public(struct passwd *pw)
  737. {
  738. struct sshkey *prv;
  739. struct stat st;
  740. int r;
  741. char *comment = NULL;
  742. if (!have_identity)
  743. ask_filename(pw, "Enter file in which the key is");
  744. if (stat(identity_file, &st) == -1)
  745. fatal("%s: %s", identity_file, strerror(errno));
  746. prv = load_identity(identity_file, &comment);
  747. if ((r = sshkey_write(prv, stdout)) != 0)
  748. error("sshkey_write failed: %s", ssh_err(r));
  749. if (comment != NULL && *comment != '\0')
  750. fprintf(stdout, " %s", comment);
  751. fprintf(stdout, "\n");
  752. if (sshkey_is_sk(prv)) {
  753. debug("sk_application: \"%s\", sk_flags 0x%02x",
  754. prv->sk_application, prv->sk_flags);
  755. }
  756. sshkey_free(prv);
  757. free(comment);
  758. exit(0);
  759. }
  760. static void
  761. do_download(struct passwd *pw)
  762. {
  763. #ifdef ENABLE_PKCS11
  764. struct sshkey **keys = NULL;
  765. int i, nkeys;
  766. enum sshkey_fp_rep rep;
  767. int fptype;
  768. char *fp, *ra, **comments = NULL;
  769. fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
  770. rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
  771. pkcs11_init(1);
  772. nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
  773. if (nkeys <= 0)
  774. fatal("cannot read public key from pkcs11");
  775. for (i = 0; i < nkeys; i++) {
  776. if (print_fingerprint) {
  777. fp = sshkey_fingerprint(keys[i], fptype, rep);
  778. ra = sshkey_fingerprint(keys[i], fingerprint_hash,
  779. SSH_FP_RANDOMART);
  780. if (fp == NULL || ra == NULL)
  781. fatal("%s: sshkey_fingerprint fail", __func__);
  782. printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
  783. fp, sshkey_type(keys[i]));
  784. if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
  785. printf("%s\n", ra);
  786. free(ra);
  787. free(fp);
  788. } else {
  789. (void) sshkey_write(keys[i], stdout); /* XXX check */
  790. if (*(comments[i]) != '\0') {
  791. fprintf(stdout, " %s", comments[i]);
  792. }
  793. (void) pkcs11_uri_write(keys[i], stdout);
  794. fprintf(stdout, "\n");
  795. }
  796. free(comments[i]);
  797. sshkey_free(keys[i]);
  798. }
  799. free(comments);
  800. free(keys);
  801. pkcs11_terminate();
  802. exit(0);
  803. #else
  804. fatal("no pkcs11 support");
  805. #endif /* ENABLE_PKCS11 */
  806. }
  807. static struct sshkey *
  808. try_read_key(char **cpp)
  809. {
  810. struct sshkey *ret;
  811. int r;
  812. if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
  813. fatal("sshkey_new failed");
  814. if ((r = sshkey_read(ret, cpp)) == 0)
  815. return ret;
  816. /* Not a key */
  817. sshkey_free(ret);
  818. return NULL;
  819. }
  820. static void
  821. fingerprint_one_key(const struct sshkey *public, const char *comment)
  822. {
  823. char *fp = NULL, *ra = NULL;
  824. enum sshkey_fp_rep rep;
  825. int fptype;
  826. fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
  827. rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
  828. fp = sshkey_fingerprint(public, fptype, rep);
  829. ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
  830. if (fp == NULL || ra == NULL)
  831. fatal("%s: sshkey_fingerprint failed", __func__);
  832. mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
  833. comment ? comment : "no comment", sshkey_type(public));
  834. if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
  835. printf("%s\n", ra);
  836. free(ra);
  837. free(fp);
  838. }
  839. static void
  840. fingerprint_private(const char *path)
  841. {
  842. struct stat st;
  843. char *comment = NULL;
  844. struct sshkey *privkey = NULL, *pubkey = NULL;
  845. int r;
  846. if (stat(identity_file, &st) == -1)
  847. fatal("%s: %s", path, strerror(errno));
  848. if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
  849. debug("load public \"%s\": %s", path, ssh_err(r));
  850. if (pubkey == NULL || comment == NULL || *comment == '\0') {
  851. free(comment);
  852. if ((r = sshkey_load_private(path, NULL,
  853. &privkey, &comment)) != 0)
  854. debug("load private \"%s\": %s", path, ssh_err(r));
  855. }
  856. if (pubkey == NULL && privkey == NULL)
  857. fatal("%s is not a key file.", path);
  858. fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
  859. sshkey_free(pubkey);
  860. sshkey_free(privkey);
  861. free(comment);
  862. }
  863. static void
  864. do_fingerprint(struct passwd *pw)
  865. {
  866. FILE *f;
  867. struct sshkey *public = NULL;
  868. char *comment = NULL, *cp, *ep, *line = NULL;
  869. size_t linesize = 0;
  870. int i, invalid = 1;
  871. const char *path;
  872. u_long lnum = 0;
  873. if (!have_identity)
  874. ask_filename(pw, "Enter file in which the key is");
  875. path = identity_file;
  876. if (strcmp(identity_file, "-") == 0) {
  877. f = stdin;
  878. path = "(stdin)";
  879. } else if ((f = fopen(path, "r")) == NULL)
  880. fatal("%s: %s: %s", __progname, path, strerror(errno));
  881. while (getline(&line, &linesize, f) != -1) {
  882. lnum++;
  883. cp = line;
  884. cp[strcspn(cp, "\n")] = '\0';
  885. /* Trim leading space and comments */
  886. cp = line + strspn(line, " \t");
  887. if (*cp == '#' || *cp == '\0')
  888. continue;
  889. /*
  890. * Input may be plain keys, private keys, authorized_keys
  891. * or known_hosts.
  892. */
  893. /*
  894. * Try private keys first. Assume a key is private if
  895. * "SSH PRIVATE KEY" appears on the first line and we're
  896. * not reading from stdin (XXX support private keys on stdin).
  897. */
  898. if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
  899. strstr(cp, "PRIVATE KEY") != NULL) {
  900. free(line);
  901. fclose(f);
  902. fingerprint_private(path);
  903. exit(0);
  904. }
  905. /*
  906. * If it's not a private key, then this must be prepared to
  907. * accept a public key prefixed with a hostname or options.
  908. * Try a bare key first, otherwise skip the leading stuff.
  909. */
  910. if ((public = try_read_key(&cp)) == NULL) {
  911. i = strtol(cp, &ep, 10);
  912. if (i == 0 || ep == NULL ||
  913. (*ep != ' ' && *ep != '\t')) {
  914. int quoted = 0;
  915. comment = cp;
  916. for (; *cp && (quoted || (*cp != ' ' &&
  917. *cp != '\t')); cp++) {
  918. if (*cp == '\\' && cp[1] == '"')
  919. cp++; /* Skip both */
  920. else if (*cp == '"')
  921. quoted = !quoted;
  922. }
  923. if (!*cp)
  924. continue;
  925. *cp++ = '\0';
  926. }
  927. }
  928. /* Retry after parsing leading hostname/key options */
  929. if (public == NULL && (public = try_read_key(&cp)) == NULL) {
  930. debug("%s:%lu: not a public key", path, lnum);
  931. continue;
  932. }
  933. /* Find trailing comment, if any */
  934. for (; *cp == ' ' || *cp == '\t'; cp++)
  935. ;
  936. if (*cp != '\0' && *cp != '#')
  937. comment = cp;
  938. fingerprint_one_key(public, comment);
  939. sshkey_free(public);
  940. invalid = 0; /* One good key in the file is sufficient */
  941. }
  942. fclose(f);
  943. free(line);
  944. if (invalid)
  945. fatal("%s is not a public key file.", path);
  946. exit(0);
  947. }
  948. static void
  949. do_gen_all_hostkeys(struct passwd *pw)
  950. {
  951. struct {
  952. char *key_type;
  953. char *key_type_display;
  954. char *path;
  955. } key_types[] = {
  956. #ifdef WITH_OPENSSL
  957. { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
  958. { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
  959. #ifdef OPENSSL_HAS_ECC
  960. { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
  961. #endif /* OPENSSL_HAS_ECC */
  962. #endif /* WITH_OPENSSL */
  963. { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
  964. #ifdef WITH_XMSS
  965. { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
  966. #endif /* WITH_XMSS */
  967. { NULL, NULL, NULL }
  968. };
  969. u_int32_t bits = 0;
  970. int first = 0;
  971. struct stat st;
  972. struct sshkey *private, *public;
  973. char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
  974. int i, type, fd, r;
  975. for (i = 0; key_types[i].key_type; i++) {
  976. public = private = NULL;
  977. prv_tmp = pub_tmp = prv_file = pub_file = NULL;
  978. xasprintf(&prv_file, "%s%s",
  979. identity_file, key_types[i].path);
  980. /* Check whether private key exists and is not zero-length */
  981. if (stat(prv_file, &st) == 0) {
  982. if (st.st_size != 0)
  983. goto next;
  984. } else if (errno != ENOENT) {
  985. error("Could not stat %s: %s", key_types[i].path,
  986. strerror(errno));
  987. goto failnext;
  988. }
  989. /*
  990. * Private key doesn't exist or is invalid; proceed with
  991. * key generation.
  992. */
  993. xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
  994. identity_file, key_types[i].path);
  995. xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
  996. identity_file, key_types[i].path);
  997. xasprintf(&pub_file, "%s%s.pub",
  998. identity_file, key_types[i].path);
  999. if (first == 0) {
  1000. first = 1;
  1001. printf("%s: generating new host keys: ", __progname);
  1002. }
  1003. printf("%s ", key_types[i].key_type_display);
  1004. fflush(stdout);
  1005. type = sshkey_type_from_name(key_types[i].key_type);
  1006. if ((fd = mkstemp(prv_tmp)) == -1) {
  1007. error("Could not save your private key in %s: %s",
  1008. prv_tmp, strerror(errno));
  1009. goto failnext;
  1010. }
  1011. (void)close(fd); /* just using mkstemp() to reserve a name */
  1012. bits = 0;
  1013. type_bits_valid(type, NULL, &bits);
  1014. if ((r = sshkey_generate(type, bits, &private)) != 0) {
  1015. error("sshkey_generate failed: %s", ssh_err(r));
  1016. goto failnext;
  1017. }
  1018. if ((r = sshkey_from_private(private, &public)) != 0)
  1019. fatal("sshkey_from_private failed: %s", ssh_err(r));
  1020. snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
  1021. hostname);
  1022. if ((r = sshkey_save_private(private, prv_tmp, "",
  1023. comment, private_key_format, openssh_format_cipher,
  1024. rounds)) != 0) {
  1025. error("Saving key \"%s\" failed: %s",
  1026. prv_tmp, ssh_err(r));
  1027. goto failnext;
  1028. }
  1029. if ((fd = mkstemp(pub_tmp)) == -1) {
  1030. error("Could not save your public key in %s: %s",
  1031. pub_tmp, strerror(errno));
  1032. goto failnext;
  1033. }
  1034. (void)fchmod(fd, 0644);
  1035. (void)close(fd);
  1036. if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
  1037. fatal("Unable to save public key to %s: %s",
  1038. identity_file, ssh_err(r));
  1039. goto failnext;
  1040. }
  1041. /* Rename temporary files to their permanent locations. */
  1042. if (rename(pub_tmp, pub_file) != 0) {
  1043. error("Unable to move %s into position: %s",
  1044. pub_file, strerror(errno));
  1045. goto failnext;
  1046. }
  1047. if (rename(prv_tmp, prv_file) != 0) {
  1048. error("Unable to move %s into position: %s",
  1049. key_types[i].path, strerror(errno));
  1050. failnext:
  1051. first = 0;
  1052. goto next;
  1053. }
  1054. next:
  1055. sshkey_free(private);
  1056. sshkey_free(public);
  1057. free(prv_tmp);
  1058. free(pub_tmp);
  1059. free(prv_file);
  1060. free(pub_file);
  1061. }
  1062. if (first != 0)
  1063. printf("\n");
  1064. }
  1065. struct known_hosts_ctx {
  1066. const char *host; /* Hostname searched for in find/delete case */
  1067. FILE *out; /* Output file, stdout for find_hosts case */
  1068. int has_unhashed; /* When hashing, original had unhashed hosts */
  1069. int found_key; /* For find/delete, host was found */
  1070. int invalid; /* File contained invalid items; don't delete */
  1071. int hash_hosts; /* Hash hostnames as we go */
  1072. int find_host; /* Search for specific hostname */
  1073. int delete_host; /* Delete host from known_hosts */
  1074. };
  1075. static int
  1076. known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
  1077. {
  1078. struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
  1079. char *hashed, *cp, *hosts, *ohosts;
  1080. int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
  1081. int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
  1082. switch (l->status) {
  1083. case HKF_STATUS_OK:
  1084. case HKF_STATUS_MATCHED:
  1085. /*
  1086. * Don't hash hosts already already hashed, with wildcard
  1087. * characters or a CA/revocation marker.
  1088. */
  1089. if (was_hashed || has_wild || l->marker != MRK_NONE) {
  1090. fprintf(ctx->out, "%s\n", l->line);
  1091. if (has_wild && !ctx->find_host) {
  1092. logit("%s:%lu: ignoring host name "
  1093. "with wildcard: %.64s", l->path,
  1094. l->linenum, l->hosts);
  1095. }
  1096. return 0;
  1097. }
  1098. /*
  1099. * Split any comma-separated hostnames from the host list,
  1100. * hash and store separately.
  1101. */
  1102. ohosts = hosts = xstrdup(l->hosts);
  1103. while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
  1104. lowercase(cp);
  1105. if ((hashed = host_hash(cp, NULL, 0)) == NULL)
  1106. fatal("hash_host failed");
  1107. fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
  1108. ctx->has_unhashed = 1;
  1109. }
  1110. free(ohosts);
  1111. return 0;
  1112. case HKF_STATUS_INVALID:
  1113. /* Retain invalid lines, but mark file as invalid. */
  1114. ctx->invalid = 1;
  1115. logit("%s:%lu: invalid line", l->path, l->linenum);
  1116. /* FALLTHROUGH */
  1117. default:
  1118. fprintf(ctx->out, "%s\n", l->line);
  1119. return 0;
  1120. }
  1121. /* NOTREACHED */
  1122. return -1;
  1123. }
  1124. static int
  1125. known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
  1126. {
  1127. struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
  1128. enum sshkey_fp_rep rep;
  1129. int fptype;
  1130. char *fp = NULL, *ra = NULL;
  1131. fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
  1132. rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
  1133. if (l->status == HKF_STATUS_MATCHED) {
  1134. if (ctx->delete_host) {
  1135. if (l->marker != MRK_NONE) {
  1136. /* Don't remove CA and revocation lines */
  1137. fprintf(ctx->out, "%s\n", l->line);
  1138. } else {
  1139. /*
  1140. * Hostname matches and has no CA/revoke
  1141. * marker, delete it by *not* writing the
  1142. * line to ctx->out.
  1143. */
  1144. ctx->found_key = 1;
  1145. if (!quiet)
  1146. printf("# Host %s found: line %lu\n",
  1147. ctx->host, l->linenum);
  1148. }
  1149. return 0;
  1150. } else if (ctx->find_host) {
  1151. ctx->found_key = 1;
  1152. if (!quiet) {
  1153. printf("# Host %s found: line %lu %s\n",
  1154. ctx->host,
  1155. l->linenum, l->marker == MRK_CA ? "CA" :
  1156. (l->marker == MRK_REVOKE ? "REVOKED" : ""));
  1157. }
  1158. if (ctx->hash_hosts)
  1159. known_hosts_hash(l, ctx);
  1160. else if (print_fingerprint) {
  1161. fp = sshkey_fingerprint(l->key, fptype, rep);
  1162. ra = sshkey_fingerprint(l->key,
  1163. fingerprint_hash, SSH_FP_RANDOMART);
  1164. if (fp == NULL || ra == NULL)
  1165. fatal("%s: sshkey_fingerprint failed",
  1166. __func__);
  1167. mprintf("%s %s %s%s%s\n", ctx->host,
  1168. sshkey_type(l->key), fp,
  1169. l->comment[0] ? " " : "",
  1170. l->comment);
  1171. if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
  1172. printf("%s\n", ra);
  1173. free(ra);
  1174. free(fp);
  1175. } else
  1176. fprintf(ctx->out, "%s\n", l->line);
  1177. return 0;
  1178. }
  1179. } else if (ctx->delete_host) {
  1180. /* Retain non-matching hosts when deleting */
  1181. if (l->status == HKF_STATUS_INVALID) {
  1182. ctx->invalid = 1;
  1183. logit("%s:%lu: invalid line", l->path, l->linenum);
  1184. }
  1185. fprintf(ctx->out, "%s\n", l->line);
  1186. }
  1187. return 0;
  1188. }
  1189. static void
  1190. do_known_hosts(struct passwd *pw, const char *name, int find_host,
  1191. int delete_host, int hash_hosts)
  1192. {
  1193. char *cp, tmp[PATH_MAX], old[PATH_MAX];
  1194. int r, fd, oerrno, inplace = 0;
  1195. struct known_hosts_ctx ctx;
  1196. u_int foreach_options;
  1197. struct stat sb;
  1198. if (!have_identity) {
  1199. cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
  1200. if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
  1201. sizeof(identity_file))
  1202. fatal("Specified known hosts path too long");
  1203. free(cp);
  1204. have_identity = 1;
  1205. }
  1206. if (stat(identity_file, &sb) != 0)
  1207. fatal("Cannot stat %s: %s", identity_file, strerror(errno));
  1208. memset(&ctx, 0, sizeof(ctx));
  1209. ctx.out = stdout;
  1210. ctx.host = name;
  1211. ctx.hash_hosts = hash_hosts;
  1212. ctx.find_host = find_host;
  1213. ctx.delete_host = delete_host;
  1214. /*
  1215. * Find hosts goes to stdout, hash and deletions happen in-place
  1216. * A corner case is ssh-keygen -HF foo, which should go to stdout
  1217. */
  1218. if (!find_host && (hash_hosts || delete_host)) {
  1219. if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
  1220. strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
  1221. strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
  1222. strlcat(old, ".old", sizeof(old)) >= sizeof(old))
  1223. fatal("known_hosts path too long");
  1224. umask(077);
  1225. if ((fd = mkstemp(tmp)) == -1)
  1226. fatal("mkstemp: %s", strerror(errno));
  1227. if ((ctx.out = fdopen(fd, "w")) == NULL) {
  1228. oerrno = errno;
  1229. unlink(tmp);
  1230. fatal("fdopen: %s", strerror(oerrno));
  1231. }
  1232. fchmod(fd, sb.st_mode & 0644);
  1233. inplace = 1;
  1234. }
  1235. /* XXX support identity_file == "-" for stdin */
  1236. foreach_options = find_host ? HKF_WANT_MATCH : 0;
  1237. foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
  1238. if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
  1239. known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
  1240. foreach_options)) != 0) {
  1241. if (inplace)
  1242. unlink(tmp);
  1243. fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
  1244. }
  1245. if (inplace)
  1246. fclose(ctx.out);
  1247. if (ctx.invalid) {
  1248. error("%s is not a valid known_hosts file.", identity_file);
  1249. if (inplace) {
  1250. error("Not replacing existing known_hosts "
  1251. "file because of errors");
  1252. unlink(tmp);
  1253. }
  1254. exit(1);
  1255. } else if (delete_host && !ctx.found_key) {
  1256. logit("Host %s not found in %s", name, identity_file);
  1257. if (inplace)
  1258. unlink(tmp);
  1259. } else if (inplace) {
  1260. /* Backup existing file */
  1261. if (unlink(old) == -1 && errno != ENOENT)
  1262. fatal("unlink %.100s: %s", old, strerror(errno));
  1263. if (link(identity_file, old) == -1)
  1264. fatal("link %.100s to %.100s: %s", identity_file, old,
  1265. strerror(errno));
  1266. /* Move new one into place */
  1267. if (rename(tmp, identity_file) == -1) {
  1268. error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
  1269. strerror(errno));
  1270. unlink(tmp);
  1271. unlink(old);
  1272. exit(1);
  1273. }
  1274. printf("%s updated.\n", identity_file);
  1275. printf("Original contents retained as %s\n", old);
  1276. if (ctx.has_unhashed) {
  1277. logit("WARNING: %s contains unhashed entries", old);
  1278. logit("Delete this file to ensure privacy "
  1279. "of hostnames");
  1280. }
  1281. }
  1282. exit (find_host && !ctx.found_key);
  1283. }
  1284. /*
  1285. * Perform changing a passphrase. The argument is the passwd structure
  1286. * for the current user.
  1287. */
  1288. static void
  1289. do_change_passphrase(struct passwd *pw)
  1290. {
  1291. char *comment;
  1292. char *old_passphrase, *passphrase1, *passphrase2;
  1293. struct stat st;
  1294. struct sshkey *private;
  1295. int r;
  1296. if (!have_identity)
  1297. ask_filename(pw, "Enter file in which the key is");
  1298. if (stat(identity_file, &st) == -1)
  1299. fatal("%s: %s", identity_file, strerror(errno));
  1300. /* Try to load the file with empty passphrase. */
  1301. r = sshkey_load_private(identity_file, "", &private, &comment);
  1302. if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
  1303. if (identity_passphrase)
  1304. old_passphrase = xstrdup(identity_passphrase);
  1305. else
  1306. old_passphrase =
  1307. read_passphrase("Enter old passphrase: ",
  1308. RP_ALLOW_STDIN);
  1309. r = sshkey_load_private(identity_file, old_passphrase,
  1310. &private, &comment);
  1311. freezero(old_passphrase, strlen(old_passphrase));
  1312. if (r != 0)
  1313. goto badkey;
  1314. } else if (r != 0) {
  1315. badkey:
  1316. fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
  1317. }
  1318. if (comment)
  1319. mprintf("Key has comment '%s'\n", comment);
  1320. /* Ask the new passphrase (twice). */
  1321. if (identity_new_passphrase) {
  1322. passphrase1 = xstrdup(identity_new_passphrase);
  1323. passphrase2 = NULL;
  1324. } else {
  1325. passphrase1 =
  1326. read_passphrase("Enter new passphrase (empty for no "
  1327. "passphrase): ", RP_ALLOW_STDIN);
  1328. passphrase2 = read_passphrase("Enter same passphrase again: ",
  1329. RP_ALLOW_STDIN);
  1330. /* Verify that they are the same. */
  1331. if (strcmp(passphrase1, passphrase2) != 0) {
  1332. explicit_bzero(passphrase1, strlen(passphrase1));
  1333. explicit_bzero(passphrase2, strlen(passphrase2));
  1334. free(passphrase1);
  1335. free(passphrase2);
  1336. printf("Pass phrases do not match. Try again.\n");
  1337. exit(1);
  1338. }
  1339. /* Destroy the other copy. */
  1340. freezero(passphrase2, strlen(passphrase2));
  1341. }
  1342. /* Save the file using the new passphrase. */
  1343. if ((r = sshkey_save_private(private, identity_file, passphrase1,
  1344. comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
  1345. error("Saving key \"%s\" failed: %s.",
  1346. identity_file, ssh_err(r));
  1347. freezero(passphrase1, strlen(passphrase1));
  1348. sshkey_free(private);
  1349. free(comment);
  1350. exit(1);
  1351. }
  1352. /* Destroy the passphrase and the copy of the key in memory. */
  1353. freezero(passphrase1, strlen(passphrase1));
  1354. sshkey_free(private); /* Destroys contents */
  1355. free(comment);
  1356. printf("Your identification has been saved with the new passphrase.\n");
  1357. exit(0);
  1358. }
  1359. /*
  1360. * Print the SSHFP RR.
  1361. */
  1362. static int
  1363. do_print_resource_record(struct passwd *pw, char *fname, char *hname,
  1364. int print_generic)
  1365. {
  1366. struct sshkey *public;
  1367. char *comment = NULL;
  1368. struct stat st;
  1369. int r;
  1370. if (fname == NULL)
  1371. fatal("%s: no filename", __func__);
  1372. if (stat(fname, &st) == -1) {
  1373. if (errno == ENOENT)
  1374. return 0;
  1375. fatal("%s: %s", fname, strerror(errno));
  1376. }
  1377. if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
  1378. fatal("Failed to read v2 public key from \"%s\": %s.",
  1379. fname, ssh_err(r));
  1380. export_dns_rr(hname, public, stdout, print_generic);
  1381. sshkey_free(public);
  1382. free(comment);
  1383. return 1;
  1384. }
  1385. /*
  1386. * Change the comment of a private key file.
  1387. */
  1388. static void
  1389. do_change_comment(struct passwd *pw, const char *identity_comment)
  1390. {
  1391. char new_comment[1024], *comment, *passphrase;
  1392. struct sshkey *private;
  1393. struct sshkey *public;
  1394. struct stat st;
  1395. int r;
  1396. if (!have_identity)
  1397. ask_filename(pw, "Enter file in which the key is");
  1398. if (stat(identity_file, &st) == -1)
  1399. fatal("%s: %s", identity_file, strerror(errno));
  1400. if ((r = sshkey_load_private(identity_file, "",
  1401. &private, &comment)) == 0)
  1402. passphrase = xstrdup("");
  1403. else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
  1404. fatal("Cannot load private key \"%s\": %s.",
  1405. identity_file, ssh_err(r));
  1406. else {
  1407. if (identity_passphrase)
  1408. passphrase = xstrdup(identity_passphrase);
  1409. else if (identity_new_passphrase)
  1410. passphrase = xstrdup(identity_new_passphrase);
  1411. else
  1412. passphrase = read_passphrase("Enter passphrase: ",
  1413. RP_ALLOW_STDIN);
  1414. /* Try to load using the passphrase. */
  1415. if ((r = sshkey_load_private(identity_file, passphrase,
  1416. &private, &comment)) != 0) {
  1417. freezero(passphrase, strlen(passphrase));
  1418. fatal("Cannot load private key \"%s\": %s.",
  1419. identity_file, ssh_err(r));
  1420. }
  1421. }
  1422. if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
  1423. private_key_format != SSHKEY_PRIVATE_OPENSSH) {
  1424. error("Comments are only supported for keys stored in "
  1425. "the new format (-o).");
  1426. explicit_bzero(passphrase, strlen(passphrase));
  1427. sshkey_free(private);
  1428. exit(1);
  1429. }
  1430. if (comment)
  1431. printf("Old comment: %s\n", comment);
  1432. else
  1433. printf("No existing comment\n");
  1434. if (identity_comment) {
  1435. strlcpy(new_comment, identity_comment, sizeof(new_comment));
  1436. } else {
  1437. printf("New comment: ");
  1438. fflush(stdout);
  1439. if (!fgets(new_comment, sizeof(new_comment), stdin)) {
  1440. explicit_bzero(passphrase, strlen(passphrase));
  1441. sshkey_free(private);
  1442. exit(1);
  1443. }
  1444. new_comment[strcspn(new_comment, "\n")] = '\0';
  1445. }
  1446. if (comment != NULL && strcmp(comment, new_comment) == 0) {
  1447. printf("No change to comment\n");
  1448. free(passphrase);
  1449. sshkey_free(private);
  1450. free(comment);
  1451. exit(0);
  1452. }
  1453. /* Save the file using the new passphrase. */
  1454. if ((r = sshkey_save_private(private, identity_file, passphrase,
  1455. new_comment, private_key_format, openssh_format_cipher,
  1456. rounds)) != 0) {
  1457. error("Saving key \"%s\" failed: %s",
  1458. identity_file, ssh_err(r));
  1459. freezero(passphrase, strlen(passphrase));
  1460. sshkey_free(private);
  1461. free(comment);
  1462. exit(1);
  1463. }
  1464. freezero(passphrase, strlen(passphrase));
  1465. if ((r = sshkey_from_private(private, &public)) != 0)
  1466. fatal("sshkey_from_private failed: %s", ssh_err(r));
  1467. sshkey_free(private);
  1468. strlcat(identity_file, ".pub", sizeof(identity_file));
  1469. if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0) {
  1470. fatal("Unable to save public key to %s: %s",
  1471. identity_file, ssh_err(r));
  1472. }
  1473. sshkey_free(public);
  1474. free(comment);
  1475. if (strlen(new_comment) > 0)
  1476. printf("Comment '%s' applied\n", new_comment);
  1477. else
  1478. printf("Comment removed\n");
  1479. exit(0);
  1480. }
  1481. static void
  1482. cert_ext_add(const char *key, const char *value, int iscrit)
  1483. {
  1484. cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
  1485. cert_ext[ncert_ext].key = xstrdup(key);
  1486. cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
  1487. cert_ext[ncert_ext].crit = iscrit;
  1488. ncert_ext++;
  1489. }
  1490. /* qsort(3) comparison function for certificate extensions */
  1491. static int
  1492. cert_ext_cmp(const void *_a, const void *_b)
  1493. {
  1494. const struct cert_ext *a = (const struct cert_ext *)_a;
  1495. const struct cert_ext *b = (const struct cert_ext *)_b;
  1496. int r;
  1497. if (a->crit != b->crit)
  1498. return (a->crit < b->crit) ? -1 : 1;
  1499. if ((r = strcmp(a->key, b->key)) != 0)
  1500. return r;
  1501. if ((a->val == NULL) != (b->val == NULL))
  1502. return (a->val == NULL) ? -1 : 1;
  1503. if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
  1504. return r;
  1505. return 0;
  1506. }
  1507. #define OPTIONS_CRITICAL 1
  1508. #define OPTIONS_EXTENSIONS 2
  1509. static void
  1510. prepare_options_buf(struct sshbuf *c, int which)
  1511. {
  1512. struct sshbuf *b;
  1513. size_t i;
  1514. int r;
  1515. const struct cert_ext *ext;
  1516. if ((b = sshbuf_new()) == NULL)
  1517. fatal("%s: sshbuf_new failed", __func__);
  1518. sshbuf_reset(c);
  1519. for (i = 0; i < ncert_ext; i++) {
  1520. ext = &cert_ext[i];
  1521. if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
  1522. (!ext->crit && (which & OPTIONS_CRITICAL)))
  1523. continue;
  1524. if (ext->val == NULL) {
  1525. /* flag option */
  1526. debug3("%s: %s", __func__, ext->key);
  1527. if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
  1528. (r = sshbuf_put_string(c, NULL, 0)) != 0)
  1529. fatal("%s: buffer: %s", __func__, ssh_err(r));
  1530. } else {
  1531. /* key/value option */
  1532. debug3("%s: %s=%s", __func__, ext->key, ext->val);
  1533. sshbuf_reset(b);
  1534. if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
  1535. (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
  1536. (r = sshbuf_put_stringb(c, b)) != 0)
  1537. fatal("%s: buffer: %s", __func__, ssh_err(r));
  1538. }
  1539. }
  1540. sshbuf_free(b);
  1541. }
  1542. static void
  1543. finalise_cert_exts(void)
  1544. {
  1545. /* critical options */
  1546. if (certflags_command != NULL)
  1547. cert_ext_add("force-command", certflags_command, 1);
  1548. if (certflags_src_addr != NULL)
  1549. cert_ext_add("source-address", certflags_src_addr, 1);
  1550. /* extensions */
  1551. if ((certflags_flags & CERTOPT_X_FWD) != 0)
  1552. cert_ext_add("permit-X11-forwarding", NULL, 0);
  1553. if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
  1554. cert_ext_add("permit-agent-forwarding", NULL, 0);
  1555. if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
  1556. cert_ext_add("permit-port-forwarding", NULL, 0);
  1557. if ((certflags_flags & CERTOPT_PTY) != 0)
  1558. cert_ext_add("permit-pty", NULL, 0);
  1559. if ((certflags_flags & CERTOPT_USER_RC) != 0)
  1560. cert_ext_add("permit-user-rc", NULL, 0);
  1561. if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
  1562. cert_ext_add("no-touch-required", NULL, 0);
  1563. /* order lexically by key */
  1564. if (ncert_ext > 0)
  1565. qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
  1566. }
  1567. static struct sshkey *
  1568. load_pkcs11_key(char *path)
  1569. {
  1570. #ifdef ENABLE_PKCS11
  1571. struct sshkey **keys = NULL, *public, *private = NULL;
  1572. int r, i, nkeys;
  1573. if ((r = sshkey_load_public(path, &public, NULL)) != 0)
  1574. fatal("Couldn't load CA public key \"%s\": %s",
  1575. path, ssh_err(r));
  1576. nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
  1577. &keys, NULL);
  1578. debug3("%s: %d keys", __func__, nkeys);
  1579. if (nkeys <= 0)
  1580. fatal("cannot read public key from pkcs11");
  1581. for (i = 0; i < nkeys; i++) {
  1582. if (sshkey_equal_public(public, keys[i])) {
  1583. private = keys[i];
  1584. continue;
  1585. }
  1586. sshkey_free(keys[i]);
  1587. }
  1588. free(keys);
  1589. sshkey_free(public);
  1590. return private;
  1591. #else
  1592. fatal("no pkcs11 support");
  1593. #endif /* ENABLE_PKCS11 */
  1594. }
  1595. /* Signer for sshkey_certify_custom that uses the agent */
  1596. static int
  1597. agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
  1598. const u_char *data, size_t datalen,
  1599. const char *alg, const char *provider, const char *pin,
  1600. u_int compat, void *ctx)
  1601. {
  1602. int *agent_fdp = (int *)ctx;
  1603. return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
  1604. data, datalen, alg, compat);
  1605. }
  1606. static void
  1607. do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
  1608. unsigned long long cert_serial, int cert_serial_autoinc,
  1609. int argc, char **argv)
  1610. {
  1611. int r, i, found, agent_fd = -1;
  1612. u_int n;
  1613. struct sshkey *ca, *public;
  1614. char valid[64], *otmp, *tmp, *cp, *out, *comment;
  1615. char *ca_fp = NULL, **plist = NULL, *pin = NULL;
  1616. struct ssh_identitylist *agent_ids;
  1617. size_t j;
  1618. struct notifier_ctx *notifier = NULL;
  1619. #ifdef ENABLE_PKCS11
  1620. pkcs11_init(1);
  1621. #endif
  1622. tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
  1623. if (pkcs11provider != NULL) {
  1624. /* If a PKCS#11 token was specified then try to use it */
  1625. if ((ca = load_pkcs11_key(tmp)) == NULL)
  1626. fatal("No PKCS#11 key matching %s found", ca_key_path);
  1627. } else if (prefer_agent) {
  1628. /*
  1629. * Agent signature requested. Try to use agent after making
  1630. * sure the public key specified is actually present in the
  1631. * agent.
  1632. */
  1633. if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
  1634. fatal("Cannot load CA public key %s: %s",
  1635. tmp, ssh_err(r));
  1636. if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
  1637. fatal("Cannot use public key for CA signature: %s",
  1638. ssh_err(r));
  1639. if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
  1640. fatal("Retrieve agent key list: %s", ssh_err(r));
  1641. found = 0;
  1642. for (j = 0; j < agent_ids->nkeys; j++) {
  1643. if (sshkey_equal(ca, agent_ids->keys[j])) {
  1644. found = 1;
  1645. break;
  1646. }
  1647. }
  1648. if (!found)
  1649. fatal("CA key %s not found in agent", tmp);
  1650. ssh_free_identitylist(agent_ids);
  1651. ca->flags |= SSHKEY_FLAG_EXT;
  1652. } else {
  1653. /* CA key is assumed to be a private key on the filesystem */
  1654. ca = load_identity(tmp, NULL);
  1655. if (sshkey_is_sk(ca) &&
  1656. (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
  1657. if ((pin = read_passphrase("Enter PIN for CA key: ",
  1658. RP_ALLOW_STDIN)) == NULL)
  1659. fatal("%s: couldn't read PIN", __func__);
  1660. }
  1661. }
  1662. free(tmp);
  1663. if (key_type_name != NULL) {
  1664. if (sshkey_type_from_name(key_type_name) != ca->type) {
  1665. fatal("CA key type %s doesn't match specified %s",
  1666. sshkey_ssh_name(ca), key_type_name);
  1667. }
  1668. } else if (ca->type == KEY_RSA) {
  1669. /* Default to a good signature algorithm */
  1670. key_type_name = "rsa-sha2-512";
  1671. }
  1672. ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
  1673. finalise_cert_exts();
  1674. for (i = 0; i < argc; i++) {
  1675. /* Split list of principals */
  1676. n = 0;
  1677. if (cert_principals != NULL) {
  1678. otmp = tmp = xstrdup(cert_principals);
  1679. plist = NULL;
  1680. for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
  1681. plist = xreallocarray(plist, n + 1, sizeof(*plist));
  1682. if (*(plist[n] = xstrdup(cp)) == '\0')
  1683. fatal("Empty principal name");
  1684. }
  1685. free(otmp);
  1686. }
  1687. if (n > SSHKEY_CERT_MAX_PRINCIPALS)
  1688. fatal("Too many certificate principals specified");
  1689. tmp = tilde_expand_filename(argv[i], pw->pw_uid);
  1690. if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
  1691. fatal("%s: unable to open \"%s\": %s",
  1692. __func__, tmp, ssh_err(r));
  1693. if (sshkey_is_cert(public))
  1694. fatal("%s: key \"%s\" type %s cannot be certified",
  1695. __func__, tmp, sshkey_type(public));
  1696. /* Prepare certificate to sign */
  1697. if ((r = sshkey_to_certified(public)) != 0)
  1698. fatal("Could not upgrade key %s to certificate: %s",
  1699. tmp, ssh_err(r));
  1700. public->cert->type = cert_key_type;
  1701. public->cert->serial = (u_int64_t)cert_serial;
  1702. public->cert->key_id = xstrdup(cert_key_id);
  1703. public->cert->nprincipals = n;
  1704. public->cert->principals = plist;
  1705. public->cert->valid_after = cert_valid_from;
  1706. public->cert->valid_before = cert_valid_to;
  1707. prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
  1708. prepare_options_buf(public->cert->extensions,
  1709. OPTIONS_EXTENSIONS);
  1710. if ((r = sshkey_from_private(ca,
  1711. &public->cert->signature_key)) != 0)
  1712. fatal("sshkey_from_private (ca key): %s", ssh_err(r));
  1713. if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
  1714. if ((r = sshkey_certify_custom(public, ca,
  1715. key_type_name, sk_provider, NULL, agent_signer,
  1716. &agent_fd)) != 0)
  1717. fatal("Couldn't certify key %s via agent: %s",
  1718. tmp, ssh_err(r));
  1719. } else {
  1720. if (sshkey_is_sk(ca) &&
  1721. (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
  1722. notifier = notify_start(0,
  1723. "Confirm user presence for key %s %s",
  1724. sshkey_type(ca), ca_fp);
  1725. }
  1726. r = sshkey_certify(public, ca, key_type_name,
  1727. sk_provider, pin);
  1728. //notify_complete(notifier, "User presence confirmed");
  1729. if (r != 0)
  1730. fatal("Couldn't certify key %s: %s",
  1731. tmp, ssh_err(r));
  1732. }
  1733. if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
  1734. *cp = '\0';
  1735. xasprintf(&out, "%s-cert.pub", tmp);
  1736. free(tmp);
  1737. if ((r = sshkey_save_public(public, out, comment)) != 0) {
  1738. fatal("Unable to save public key to %s: %s",
  1739. identity_file, ssh_err(r));
  1740. }
  1741. if (!quiet) {
  1742. sshkey_format_cert_validity(public->cert,
  1743. valid, sizeof(valid));
  1744. logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
  1745. "valid %s", sshkey_cert_type(public),
  1746. out, public->cert->key_id,
  1747. (unsigned long long)public->cert->serial,
  1748. cert_principals != NULL ? " for " : "",
  1749. cert_principals != NULL ? cert_principals : "",
  1750. valid);
  1751. }
  1752. sshkey_free(public);
  1753. free(out);
  1754. if (cert_serial_autoinc)
  1755. cert_serial++;
  1756. }
  1757. if (pin != NULL)
  1758. freezero(pin, strlen(pin));
  1759. free(ca_fp);
  1760. #ifdef ENABLE_PKCS11
  1761. pkcs11_terminate();
  1762. #endif
  1763. exit(0);
  1764. }
  1765. static u_int64_t
  1766. parse_relative_time(const char *s, time_t now)
  1767. {
  1768. int64_t mul, secs;
  1769. mul = *s == '-' ? -1 : 1;
  1770. if ((secs = convtime(s + 1)) == -1)
  1771. fatal("Invalid relative certificate time %s", s);
  1772. if (mul == -1 && secs > now)
  1773. fatal("Certificate time %s cannot be represented", s);
  1774. return now + (u_int64_t)(secs * mul);
  1775. }
  1776. static void
  1777. parse_cert_times(char *timespec)
  1778. {
  1779. char *from, *to;
  1780. time_t now = time(NULL);
  1781. int64_t secs;
  1782. /* +timespec relative to now */
  1783. if (*timespec == '+' && strchr(timespec, ':') == NULL) {
  1784. if ((secs = convtime(timespec + 1)) == -1)
  1785. fatal("Invalid relative certificate life %s", timespec);
  1786. cert_valid_to = now + secs;
  1787. /*
  1788. * Backdate certificate one minute to avoid problems on hosts
  1789. * with poorly-synchronised clocks.
  1790. */
  1791. cert_valid_from = ((now - 59)/ 60) * 60;
  1792. return;
  1793. }
  1794. /*
  1795. * from:to, where
  1796. * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
  1797. * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
  1798. */
  1799. from = xstrdup(timespec);
  1800. to = strchr(from, ':');
  1801. if (to == NULL || from == to || *(to + 1) == '\0')
  1802. fatal("Invalid certificate life specification %s", timespec);
  1803. *to++ = '\0';
  1804. if (*from == '-' || *from == '+')
  1805. cert_valid_from = parse_relative_time(from, now);
  1806. else if (strcmp(from, "always") == 0)
  1807. cert_valid_from = 0;
  1808. else if (parse_absolute_time(from, &cert_valid_from) != 0)
  1809. fatal("Invalid from time \"%s\"", from);
  1810. if (*to == '-' || *to == '+')
  1811. cert_valid_to = parse_relative_time(to, now);
  1812. else if (strcmp(to, "forever") == 0)
  1813. cert_valid_to = ~(u_int64_t)0;
  1814. else if (parse_absolute_time(to, &cert_valid_to) != 0)
  1815. fatal("Invalid to time \"%s\"", to);
  1816. if (cert_valid_to <= cert_valid_from)
  1817. fatal("Empty certificate validity interval");
  1818. free(from);
  1819. }
  1820. static void
  1821. add_cert_option(char *opt)
  1822. {
  1823. char *val, *cp;
  1824. int iscrit = 0;
  1825. if (strcasecmp(opt, "clear") == 0)
  1826. certflags_flags = 0;
  1827. else if (strcasecmp(opt, "no-x11-forwarding") == 0)
  1828. certflags_flags &= ~CERTOPT_X_FWD;
  1829. else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
  1830. certflags_flags |= CERTOPT_X_FWD;
  1831. else if (strcasecmp(opt, "no-agent-forwarding") == 0)
  1832. certflags_flags &= ~CERTOPT_AGENT_FWD;
  1833. else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
  1834. certflags_flags |= CERTOPT_AGENT_FWD;
  1835. else if (strcasecmp(opt, "no-port-forwarding") == 0)
  1836. certflags_flags &= ~CERTOPT_PORT_FWD;
  1837. else if (strcasecmp(opt, "permit-port-forwarding") == 0)
  1838. certflags_flags |= CERTOPT_PORT_FWD;
  1839. else if (strcasecmp(opt, "no-pty") == 0)
  1840. certflags_flags &= ~CERTOPT_PTY;
  1841. else if (strcasecmp(opt, "permit-pty") == 0)
  1842. certflags_flags |= CERTOPT_PTY;
  1843. else if (strcasecmp(opt, "no-user-rc") == 0)
  1844. certflags_flags &= ~CERTOPT_USER_RC;
  1845. else if (strcasecmp(opt, "permit-user-rc") == 0)
  1846. certflags_flags |= CERTOPT_USER_RC;
  1847. else if (strcasecmp(opt, "touch-required") == 0)
  1848. certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
  1849. else if (strcasecmp(opt, "no-touch-required") == 0)
  1850. certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
  1851. else if (strncasecmp(opt, "force-command=", 14) == 0) {
  1852. val = opt + 14;
  1853. if (*val == '\0')
  1854. fatal("Empty force-command option");
  1855. if (certflags_command != NULL)
  1856. fatal("force-command already specified");
  1857. certflags_command = xstrdup(val);
  1858. } else if (strncasecmp(opt, "source-address=", 15) == 0) {
  1859. val = opt + 15;
  1860. if (*val == '\0')
  1861. fatal("Empty source-address option");
  1862. if (certflags_src_addr != NULL)
  1863. fatal("source-address already specified");
  1864. if (addr_match_cidr_list(NULL, val) != 0)
  1865. fatal("Invalid source-address list");
  1866. certflags_src_addr = xstrdup(val);
  1867. } else if (strncasecmp(opt, "extension:", 10) == 0 ||
  1868. (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
  1869. val = xstrdup(strchr(opt, ':') + 1);
  1870. if ((cp = strchr(val, '=')) != NULL)
  1871. *cp++ = '\0';
  1872. cert_ext_add(val, cp, iscrit);
  1873. free(val);
  1874. } else
  1875. fatal("Unsupported certificate option \"%s\"", opt);
  1876. }
  1877. static void
  1878. show_options(struct sshbuf *optbuf, int in_critical)
  1879. {
  1880. char *name, *arg, *hex;
  1881. struct sshbuf *options, *option = NULL;
  1882. int r;
  1883. if ((options = sshbuf_fromb(optbuf)) == NULL)
  1884. fatal("%s: sshbuf_fromb failed", __func__);
  1885. while (sshbuf_len(options) != 0) {
  1886. sshbuf_free(option);
  1887. option = NULL;
  1888. if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
  1889. (r = sshbuf_froms(options, &option)) != 0)
  1890. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  1891. printf(" %s", name);
  1892. if (!in_critical &&
  1893. (strcmp(name, "permit-X11-forwarding") == 0 ||
  1894. strcmp(name, "permit-agent-forwarding") == 0 ||
  1895. strcmp(name, "permit-port-forwarding") == 0 ||
  1896. strcmp(name, "permit-pty") == 0 ||
  1897. strcmp(name, "permit-user-rc") == 0 ||
  1898. strcmp(name, "no-touch-required") == 0)) {
  1899. printf("\n");
  1900. } else if (in_critical &&
  1901. (strcmp(name, "force-command") == 0 ||
  1902. strcmp(name, "source-address") == 0)) {
  1903. if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
  1904. fatal("%s: buffer error: %s",
  1905. __func__, ssh_err(r));
  1906. printf(" %s\n", arg);
  1907. free(arg);
  1908. } else if (sshbuf_len(option) > 0) {
  1909. hex = sshbuf_dtob16(option);
  1910. printf(" UNKNOWN OPTION: %s (len %zu)\n",
  1911. hex, sshbuf_len(option));
  1912. sshbuf_reset(option);
  1913. free(hex);
  1914. } else
  1915. printf(" UNKNOWN FLAG OPTION\n");
  1916. free(name);
  1917. if (sshbuf_len(option) != 0)
  1918. fatal("Option corrupt: extra data at end");
  1919. }
  1920. sshbuf_free(option);
  1921. sshbuf_free(options);
  1922. }
  1923. static void
  1924. print_cert(struct sshkey *key)
  1925. {
  1926. char valid[64], *key_fp, *ca_fp;
  1927. u_int i;
  1928. key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
  1929. ca_fp = sshkey_fingerprint(key->cert->signature_key,
  1930. fingerprint_hash, SSH_FP_DEFAULT);
  1931. if (key_fp == NULL || ca_fp == NULL)
  1932. fatal("%s: sshkey_fingerprint fail", __func__);
  1933. sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
  1934. printf(" Type: %s %s certificate\n", sshkey_ssh_name(key),
  1935. sshkey_cert_type(key));
  1936. printf(" Public key: %s %s\n", sshkey_type(key), key_fp);
  1937. printf(" Signing CA: %s %s (using %s)\n",
  1938. sshkey_type(key->cert->signature_key), ca_fp,
  1939. key->cert->signature_type);
  1940. printf(" Key ID: \"%s\"\n", key->cert->key_id);
  1941. printf(" Serial: %llu\n", (unsigned long long)key->cert->serial);
  1942. printf(" Valid: %s\n", valid);
  1943. printf(" Principals: ");
  1944. if (key->cert->nprincipals == 0)
  1945. printf("(none)\n");
  1946. else {
  1947. for (i = 0; i < key->cert->nprincipals; i++)
  1948. printf("\n %s",
  1949. key->cert->principals[i]);
  1950. printf("\n");
  1951. }
  1952. printf(" Critical Options: ");
  1953. if (sshbuf_len(key->cert->critical) == 0)
  1954. printf("(none)\n");
  1955. else {
  1956. printf("\n");
  1957. show_options(key->cert->critical, 1);
  1958. }
  1959. printf(" Extensions: ");
  1960. if (sshbuf_len(key->cert->extensions) == 0)
  1961. printf("(none)\n");
  1962. else {
  1963. printf("\n");
  1964. show_options(key->cert->extensions, 0);
  1965. }
  1966. }
  1967. static void
  1968. do_show_cert(struct passwd *pw)
  1969. {
  1970. struct sshkey *key = NULL;
  1971. struct stat st;
  1972. int r, is_stdin = 0, ok = 0;
  1973. FILE *f;
  1974. char *cp, *line = NULL;
  1975. const char *path;
  1976. size_t linesize = 0;
  1977. u_long lnum = 0;
  1978. if (!have_identity)
  1979. ask_filename(pw, "Enter file in which the key is");
  1980. if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
  1981. fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
  1982. path = identity_file;
  1983. if (strcmp(path, "-") == 0) {
  1984. f = stdin;
  1985. path = "(stdin)";
  1986. is_stdin = 1;
  1987. } else if ((f = fopen(identity_file, "r")) == NULL)
  1988. fatal("fopen %s: %s", identity_file, strerror(errno));
  1989. while (getline(&line, &linesize, f) != -1) {
  1990. lnum++;
  1991. sshkey_free(key);
  1992. key = NULL;
  1993. /* Trim leading space and comments */
  1994. cp = line + strspn(line, " \t");
  1995. if (*cp == '#' || *cp == '\0')
  1996. continue;
  1997. if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
  1998. fatal("sshkey_new");
  1999. if ((r = sshkey_read(key, &cp)) != 0) {
  2000. error("%s:%lu: invalid key: %s", path,
  2001. lnum, ssh_err(r));
  2002. continue;
  2003. }
  2004. if (!sshkey_is_cert(key)) {
  2005. error("%s:%lu is not a certificate", path, lnum);
  2006. continue;
  2007. }
  2008. ok = 1;
  2009. if (!is_stdin && lnum == 1)
  2010. printf("%s:\n", path);
  2011. else
  2012. printf("%s:%lu:\n", path, lnum);
  2013. print_cert(key);
  2014. }
  2015. free(line);
  2016. sshkey_free(key);
  2017. fclose(f);
  2018. exit(ok ? 0 : 1);
  2019. }
  2020. static void
  2021. load_krl(const char *path, struct ssh_krl **krlp)
  2022. {
  2023. struct sshbuf *krlbuf;
  2024. int r;
  2025. if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
  2026. fatal("Unable to load KRL: %s", ssh_err(r));
  2027. /* XXX check sigs */
  2028. if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
  2029. *krlp == NULL)
  2030. fatal("Invalid KRL file: %s", ssh_err(r));
  2031. sshbuf_free(krlbuf);
  2032. }
  2033. static void
  2034. hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
  2035. const char *file, u_long lnum)
  2036. {
  2037. char *tmp;
  2038. size_t tlen;
  2039. struct sshbuf *b;
  2040. int r;
  2041. if (strncmp(cp, "SHA256:", 7) != 0)
  2042. fatal("%s:%lu: unsupported hash algorithm", file, lnum);
  2043. cp += 7;
  2044. /*
  2045. * OpenSSH base64 hashes omit trailing '='
  2046. * characters; put them back for decode.
  2047. */
  2048. tlen = strlen(cp);
  2049. tmp = xmalloc(tlen + 4 + 1);
  2050. strlcpy(tmp, cp, tlen + 1);
  2051. while ((tlen % 4) != 0) {
  2052. tmp[tlen++] = '=';
  2053. tmp[tlen] = '\0';
  2054. }
  2055. if ((b = sshbuf_new()) == NULL)
  2056. fatal("%s: sshbuf_new failed", __func__);
  2057. if ((r = sshbuf_b64tod(b, tmp)) != 0)
  2058. fatal("%s:%lu: decode hash failed: %s", file, lnum, ssh_err(r));
  2059. free(tmp);
  2060. *lenp = sshbuf_len(b);
  2061. *blobp = xmalloc(*lenp);
  2062. memcpy(*blobp, sshbuf_ptr(b), *lenp);
  2063. sshbuf_free(b);
  2064. }
  2065. static void
  2066. update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
  2067. const struct sshkey *ca, struct ssh_krl *krl)
  2068. {
  2069. struct sshkey *key = NULL;
  2070. u_long lnum = 0;
  2071. char *path, *cp, *ep, *line = NULL;
  2072. u_char *blob = NULL;
  2073. size_t blen = 0, linesize = 0;
  2074. unsigned long long serial, serial2;
  2075. int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
  2076. FILE *krl_spec;
  2077. path = tilde_expand_filename(file, pw->pw_uid);
  2078. if (strcmp(path, "-") == 0) {
  2079. krl_spec = stdin;
  2080. free(path);
  2081. path = xstrdup("(standard input)");
  2082. } else if ((krl_spec = fopen(path, "r")) == NULL)
  2083. fatal("fopen %s: %s", path, strerror(errno));
  2084. if (!quiet)
  2085. printf("Revoking from %s\n", path);
  2086. while (getline(&line, &linesize, krl_spec) != -1) {
  2087. lnum++;
  2088. was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
  2089. cp = line + strspn(line, " \t");
  2090. /* Trim trailing space, comments and strip \n */
  2091. for (i = 0, r = -1; cp[i] != '\0'; i++) {
  2092. if (cp[i] == '#' || cp[i] == '\n') {
  2093. cp[i] = '\0';
  2094. break;
  2095. }
  2096. if (cp[i] == ' ' || cp[i] == '\t') {
  2097. /* Remember the start of a span of whitespace */
  2098. if (r == -1)
  2099. r = i;
  2100. } else
  2101. r = -1;
  2102. }
  2103. if (r != -1)
  2104. cp[r] = '\0';
  2105. if (*cp == '\0')
  2106. continue;
  2107. if (strncasecmp(cp, "serial:", 7) == 0) {
  2108. if (ca == NULL && !wild_ca) {
  2109. fatal("revoking certificates by serial number "
  2110. "requires specification of a CA key");
  2111. }
  2112. cp += 7;
  2113. cp = cp + strspn(cp, " \t");
  2114. errno = 0;
  2115. serial = strtoull(cp, &ep, 0);
  2116. if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
  2117. fatal("%s:%lu: invalid serial \"%s\"",
  2118. path, lnum, cp);
  2119. if (errno == ERANGE && serial == ULLONG_MAX)
  2120. fatal("%s:%lu: serial out of range",
  2121. path, lnum);
  2122. serial2 = serial;
  2123. if (*ep == '-') {
  2124. cp = ep + 1;
  2125. errno = 0;
  2126. serial2 = strtoull(cp, &ep, 0);
  2127. if (*cp == '\0' || *ep != '\0')
  2128. fatal("%s:%lu: invalid serial \"%s\"",
  2129. path, lnum, cp);
  2130. if (errno == ERANGE && serial2 == ULLONG_MAX)
  2131. fatal("%s:%lu: serial out of range",
  2132. path, lnum);
  2133. if (serial2 <= serial)
  2134. fatal("%s:%lu: invalid serial range "
  2135. "%llu:%llu", path, lnum,
  2136. (unsigned long long)serial,
  2137. (unsigned long long)serial2);
  2138. }
  2139. if (ssh_krl_revoke_cert_by_serial_range(krl,
  2140. ca, serial, serial2) != 0) {
  2141. fatal("%s: revoke serial failed",
  2142. __func__);
  2143. }
  2144. } else if (strncasecmp(cp, "id:", 3) == 0) {
  2145. if (ca == NULL && !wild_ca) {
  2146. fatal("revoking certificates by key ID "
  2147. "requires specification of a CA key");
  2148. }
  2149. cp += 3;
  2150. cp = cp + strspn(cp, " \t");
  2151. if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
  2152. fatal("%s: revoke key ID failed", __func__);
  2153. } else if (strncasecmp(cp, "hash:", 5) == 0) {
  2154. cp += 5;
  2155. cp = cp + strspn(cp, " \t");
  2156. hash_to_blob(cp, &blob, &blen, file, lnum);
  2157. r = ssh_krl_revoke_key_sha256(krl, blob, blen);
  2158. if (r != 0)
  2159. fatal("%s: revoke key failed: %s",
  2160. __func__, ssh_err(r));
  2161. } else {
  2162. if (strncasecmp(cp, "key:", 4) == 0) {
  2163. cp += 4;
  2164. cp = cp + strspn(cp, " \t");
  2165. was_explicit_key = 1;
  2166. } else if (strncasecmp(cp, "sha1:", 5) == 0) {
  2167. cp += 5;
  2168. cp = cp + strspn(cp, " \t");
  2169. was_sha1 = 1;
  2170. } else if (strncasecmp(cp, "sha256:", 7) == 0) {
  2171. cp += 7;
  2172. cp = cp + strspn(cp, " \t");
  2173. was_sha256 = 1;
  2174. /*
  2175. * Just try to process the line as a key.
  2176. * Parsing will fail if it isn't.
  2177. */
  2178. }
  2179. if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
  2180. fatal("sshkey_new");
  2181. if ((r = sshkey_read(key, &cp)) != 0)
  2182. fatal("%s:%lu: invalid key: %s",
  2183. path, lnum, ssh_err(r));
  2184. if (was_explicit_key)
  2185. r = ssh_krl_revoke_key_explicit(krl, key);
  2186. else if (was_sha1) {
  2187. if (sshkey_fingerprint_raw(key,
  2188. SSH_DIGEST_SHA1, &blob, &blen) != 0) {
  2189. fatal("%s:%lu: fingerprint failed",
  2190. file, lnum);
  2191. }
  2192. r = ssh_krl_revoke_key_sha1(krl, blob, blen);
  2193. } else if (was_sha256) {
  2194. if (sshkey_fingerprint_raw(key,
  2195. SSH_DIGEST_SHA256, &blob, &blen) != 0) {
  2196. fatal("%s:%lu: fingerprint failed",
  2197. file, lnum);
  2198. }
  2199. r = ssh_krl_revoke_key_sha256(krl, blob, blen);
  2200. } else
  2201. r = ssh_krl_revoke_key(krl, key);
  2202. if (r != 0)
  2203. fatal("%s: revoke key failed: %s",
  2204. __func__, ssh_err(r));
  2205. freezero(blob, blen);
  2206. blob = NULL;
  2207. blen = 0;
  2208. sshkey_free(key);
  2209. }
  2210. }
  2211. if (strcmp(path, "-") != 0)
  2212. fclose(krl_spec);
  2213. free(line);
  2214. free(path);
  2215. }
  2216. static void
  2217. do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
  2218. unsigned long long krl_version, const char *krl_comment,
  2219. int argc, char **argv)
  2220. {
  2221. struct ssh_krl *krl;
  2222. struct stat sb;
  2223. struct sshkey *ca = NULL;
  2224. int i, r, wild_ca = 0;
  2225. char *tmp;
  2226. struct sshbuf *kbuf;
  2227. if (*identity_file == '\0')
  2228. fatal("KRL generation requires an output file");
  2229. if (stat(identity_file, &sb) == -1) {
  2230. if (errno != ENOENT)
  2231. fatal("Cannot access KRL \"%s\": %s",
  2232. identity_file, strerror(errno));
  2233. if (updating)
  2234. fatal("KRL \"%s\" does not exist", identity_file);
  2235. }
  2236. if (ca_key_path != NULL) {
  2237. if (strcasecmp(ca_key_path, "none") == 0)
  2238. wild_ca = 1;
  2239. else {
  2240. tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
  2241. if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
  2242. fatal("Cannot load CA public key %s: %s",
  2243. tmp, ssh_err(r));
  2244. free(tmp);
  2245. }
  2246. }
  2247. if (updating)
  2248. load_krl(identity_file, &krl);
  2249. else if ((krl = ssh_krl_init()) == NULL)
  2250. fatal("couldn't create KRL");
  2251. if (krl_version != 0)
  2252. ssh_krl_set_version(krl, krl_version);
  2253. if (krl_comment != NULL)
  2254. ssh_krl_set_comment(krl, krl_comment);
  2255. for (i = 0; i < argc; i++)
  2256. update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
  2257. if ((kbuf = sshbuf_new()) == NULL)
  2258. fatal("sshbuf_new failed");
  2259. if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
  2260. fatal("Couldn't generate KRL");
  2261. if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
  2262. fatal("write %s: %s", identity_file, strerror(errno));
  2263. sshbuf_free(kbuf);
  2264. ssh_krl_free(krl);
  2265. sshkey_free(ca);
  2266. }
  2267. static void
  2268. do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
  2269. {
  2270. int i, r, ret = 0;
  2271. char *comment;
  2272. struct ssh_krl *krl;
  2273. struct sshkey *k;
  2274. if (*identity_file == '\0')
  2275. fatal("KRL checking requires an input file");
  2276. load_krl(identity_file, &krl);
  2277. if (print_krl)
  2278. krl_dump(krl, stdout);
  2279. for (i = 0; i < argc; i++) {
  2280. if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
  2281. fatal("Cannot load public key %s: %s",
  2282. argv[i], ssh_err(r));
  2283. r = ssh_krl_check_key(krl, k);
  2284. printf("%s%s%s%s: %s\n", argv[i],
  2285. *comment ? " (" : "", comment, *comment ? ")" : "",
  2286. r == 0 ? "ok" : "REVOKED");
  2287. if (r != 0)
  2288. ret = 1;
  2289. sshkey_free(k);
  2290. free(comment);
  2291. }
  2292. ssh_krl_free(krl);
  2293. exit(ret);
  2294. }
  2295. static struct sshkey *
  2296. load_sign_key(const char *keypath, const struct sshkey *pubkey)
  2297. {
  2298. size_t i, slen, plen = strlen(keypath);
  2299. char *privpath = xstrdup(keypath);
  2300. const char *suffixes[] = { "-cert.pub", ".pub", NULL };
  2301. struct sshkey *ret = NULL, *privkey = NULL;
  2302. int r;
  2303. /*
  2304. * If passed a public key filename, then try to locate the corresponding
  2305. * private key. This lets us specify certificates on the command-line
  2306. * and have ssh-keygen find the appropriate private key.
  2307. */
  2308. for (i = 0; suffixes[i]; i++) {
  2309. slen = strlen(suffixes[i]);
  2310. if (plen <= slen ||
  2311. strcmp(privpath + plen - slen, suffixes[i]) != 0)
  2312. continue;
  2313. privpath[plen - slen] = '\0';
  2314. debug("%s: %s looks like a public key, using private key "
  2315. "path %s instead", __func__, keypath, privpath);
  2316. }
  2317. if ((privkey = load_identity(privpath, NULL)) == NULL) {
  2318. error("Couldn't load identity %s", keypath);
  2319. goto done;
  2320. }
  2321. if (!sshkey_equal_public(pubkey, privkey)) {
  2322. error("Public key %s doesn't match private %s",
  2323. keypath, privpath);
  2324. goto done;
  2325. }
  2326. if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
  2327. /*
  2328. * Graft the certificate onto the private key to make
  2329. * it capable of signing.
  2330. */
  2331. if ((r = sshkey_to_certified(privkey)) != 0) {
  2332. error("%s: sshkey_to_certified: %s", __func__,
  2333. ssh_err(r));
  2334. goto done;
  2335. }
  2336. if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
  2337. error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r));
  2338. goto done;
  2339. }
  2340. }
  2341. /* success */
  2342. ret = privkey;
  2343. privkey = NULL;
  2344. done:
  2345. sshkey_free(privkey);
  2346. free(privpath);
  2347. return ret;
  2348. }
  2349. static int
  2350. sign_one(struct sshkey *signkey, const char *filename, int fd,
  2351. const char *sig_namespace, sshsig_signer *signer, void *signer_ctx)
  2352. {
  2353. struct sshbuf *sigbuf = NULL, *abuf = NULL;
  2354. int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
  2355. char *wfile = NULL, *asig = NULL, *fp = NULL;
  2356. char *pin = NULL, *prompt = NULL;
  2357. if (!quiet) {
  2358. if (fd == STDIN_FILENO)
  2359. fprintf(stderr, "Signing data on standard input\n");
  2360. else
  2361. fprintf(stderr, "Signing file %s\n", filename);
  2362. }
  2363. if (signer == NULL && sshkey_is_sk(signkey)) {
  2364. if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
  2365. xasprintf(&prompt, "Enter PIN for %s key: ",
  2366. sshkey_type(signkey));
  2367. if ((pin = read_passphrase(prompt,
  2368. RP_ALLOW_STDIN)) == NULL)
  2369. fatal("%s: couldn't read PIN", __func__);
  2370. }
  2371. if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
  2372. if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
  2373. SSH_FP_DEFAULT)) == NULL)
  2374. fatal("%s: fingerprint failed", __func__);
  2375. fprintf(stderr, "Confirm user presence for key %s %s\n",
  2376. sshkey_type(signkey), fp);
  2377. free(fp);
  2378. }
  2379. }
  2380. if ((r = sshsig_sign_fd(signkey, NULL, sk_provider, pin,
  2381. fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) {
  2382. error("Signing %s failed: %s", filename, ssh_err(r));
  2383. goto out;
  2384. }
  2385. if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
  2386. error("%s: sshsig_armor: %s", __func__, ssh_err(r));
  2387. goto out;
  2388. }
  2389. if ((asig = sshbuf_dup_string(abuf)) == NULL) {
  2390. error("%s: buffer error", __func__);
  2391. r = SSH_ERR_ALLOC_FAIL;
  2392. goto out;
  2393. }
  2394. if (fd == STDIN_FILENO) {
  2395. fputs(asig, stdout);
  2396. fflush(stdout);
  2397. } else {
  2398. xasprintf(&wfile, "%s.sig", filename);
  2399. if (confirm_overwrite(wfile)) {
  2400. if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
  2401. 0666)) == -1) {
  2402. oerrno = errno;
  2403. error("Cannot open %s: %s",
  2404. wfile, strerror(errno));
  2405. errno = oerrno;
  2406. r = SSH_ERR_SYSTEM_ERROR;
  2407. goto out;
  2408. }
  2409. if (atomicio(vwrite, wfd, asig,
  2410. strlen(asig)) != strlen(asig)) {
  2411. oerrno = errno;
  2412. error("Cannot write to %s: %s",
  2413. wfile, strerror(errno));
  2414. errno = oerrno;
  2415. r = SSH_ERR_SYSTEM_ERROR;
  2416. goto out;
  2417. }
  2418. if (!quiet) {
  2419. fprintf(stderr, "Write signature to %s\n",
  2420. wfile);
  2421. }
  2422. }
  2423. }
  2424. /* success */
  2425. r = 0;
  2426. out:
  2427. free(wfile);
  2428. free(prompt);
  2429. free(asig);
  2430. if (pin != NULL)
  2431. freezero(pin, strlen(pin));
  2432. sshbuf_free(abuf);
  2433. sshbuf_free(sigbuf);
  2434. if (wfd != -1)
  2435. close(wfd);
  2436. return r;
  2437. }
  2438. static int
  2439. sig_sign(const char *keypath, const char *sig_namespace, int argc, char **argv)
  2440. {
  2441. int i, fd = -1, r, ret = -1;
  2442. int agent_fd = -1;
  2443. struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
  2444. sshsig_signer *signer = NULL;
  2445. /* Check file arguments. */
  2446. for (i = 0; i < argc; i++) {
  2447. if (strcmp(argv[i], "-") != 0)
  2448. continue;
  2449. if (i > 0 || argc > 1)
  2450. fatal("Cannot sign mix of paths and standard input");
  2451. }
  2452. if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
  2453. error("Couldn't load public key %s: %s", keypath, ssh_err(r));
  2454. goto done;
  2455. }
  2456. if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
  2457. debug("Couldn't get agent socket: %s", ssh_err(r));
  2458. else {
  2459. if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
  2460. signer = agent_signer;
  2461. else
  2462. debug("Couldn't find key in agent: %s", ssh_err(r));
  2463. }
  2464. if (signer == NULL) {
  2465. /* Not using agent - try to load private key */
  2466. if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
  2467. goto done;
  2468. signkey = privkey;
  2469. } else {
  2470. /* Will use key in agent */
  2471. signkey = pubkey;
  2472. }
  2473. if (argc == 0) {
  2474. if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
  2475. sig_namespace, signer, &agent_fd)) != 0)
  2476. goto done;
  2477. } else {
  2478. for (i = 0; i < argc; i++) {
  2479. if (strcmp(argv[i], "-") == 0)
  2480. fd = STDIN_FILENO;
  2481. else if ((fd = open(argv[i], O_RDONLY)) == -1) {
  2482. error("Cannot open %s for signing: %s",
  2483. argv[i], strerror(errno));
  2484. goto done;
  2485. }
  2486. if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
  2487. signer, &agent_fd)) != 0)
  2488. goto done;
  2489. if (fd != STDIN_FILENO)
  2490. close(fd);
  2491. fd = -1;
  2492. }
  2493. }
  2494. ret = 0;
  2495. done:
  2496. if (fd != -1 && fd != STDIN_FILENO)
  2497. close(fd);
  2498. sshkey_free(pubkey);
  2499. sshkey_free(privkey);
  2500. return ret;
  2501. }
  2502. static int
  2503. sig_verify(const char *signature, const char *sig_namespace,
  2504. const char *principal, const char *allowed_keys, const char *revoked_keys)
  2505. {
  2506. int r, ret = -1;
  2507. struct sshbuf *sigbuf = NULL, *abuf = NULL;
  2508. struct sshkey *sign_key = NULL;
  2509. char *fp = NULL;
  2510. struct sshkey_sig_details *sig_details = NULL;
  2511. memset(&sig_details, 0, sizeof(sig_details));
  2512. if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
  2513. error("Couldn't read signature file: %s", ssh_err(r));
  2514. goto done;
  2515. }
  2516. if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
  2517. error("%s: sshsig_armor: %s", __func__, ssh_err(r));
  2518. goto done;
  2519. }
  2520. if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
  2521. &sign_key, &sig_details)) != 0)
  2522. goto done; /* sshsig_verify() prints error */
  2523. if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
  2524. SSH_FP_DEFAULT)) == NULL)
  2525. fatal("%s: sshkey_fingerprint failed", __func__);
  2526. debug("Valid (unverified) signature from key %s", fp);
  2527. if (sig_details != NULL) {
  2528. debug2("%s: signature details: counter = %u, flags = 0x%02x",
  2529. __func__, sig_details->sk_counter, sig_details->sk_flags);
  2530. }
  2531. free(fp);
  2532. fp = NULL;
  2533. if (revoked_keys != NULL) {
  2534. if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
  2535. debug3("sshkey_check_revoked failed: %s", ssh_err(r));
  2536. goto done;
  2537. }
  2538. }
  2539. if (allowed_keys != NULL &&
  2540. (r = sshsig_check_allowed_keys(allowed_keys, sign_key,
  2541. principal, sig_namespace)) != 0) {
  2542. debug3("sshsig_check_allowed_keys failed: %s", ssh_err(r));
  2543. goto done;
  2544. }
  2545. /* success */
  2546. ret = 0;
  2547. done:
  2548. if (!quiet) {
  2549. if (ret == 0) {
  2550. if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
  2551. SSH_FP_DEFAULT)) == NULL) {
  2552. fatal("%s: sshkey_fingerprint failed",
  2553. __func__);
  2554. }
  2555. if (principal == NULL) {
  2556. printf("Good \"%s\" signature with %s key %s\n",
  2557. sig_namespace, sshkey_type(sign_key), fp);
  2558. } else {
  2559. printf("Good \"%s\" signature for %s with %s key %s\n",
  2560. sig_namespace, principal,
  2561. sshkey_type(sign_key), fp);
  2562. }
  2563. } else {
  2564. printf("Could not verify signature.\n");
  2565. }
  2566. }
  2567. sshbuf_free(sigbuf);
  2568. sshbuf_free(abuf);
  2569. sshkey_free(sign_key);
  2570. sshkey_sig_details_free(sig_details);
  2571. free(fp);
  2572. return ret;
  2573. }
  2574. static int
  2575. sig_find_principals(const char *signature, const char *allowed_keys) {
  2576. int r, ret = -1;
  2577. struct sshbuf *sigbuf = NULL, *abuf = NULL;
  2578. struct sshkey *sign_key = NULL;
  2579. char *principals = NULL, *cp, *tmp;
  2580. if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
  2581. error("Couldn't read signature file: %s", ssh_err(r));
  2582. goto done;
  2583. }
  2584. if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
  2585. error("%s: sshsig_armor: %s", __func__, ssh_err(r));
  2586. goto done;
  2587. }
  2588. if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
  2589. error("%s: sshsig_get_pubkey: %s",
  2590. __func__, ssh_err(r));
  2591. goto done;
  2592. }
  2593. if ((r = sshsig_find_principals(allowed_keys, sign_key,
  2594. &principals)) != 0) {
  2595. error("%s: sshsig_get_principal: %s",
  2596. __func__, ssh_err(r));
  2597. goto done;
  2598. }
  2599. ret = 0;
  2600. done:
  2601. if (ret == 0 ) {
  2602. /* Emit matching principals one per line */
  2603. tmp = principals;
  2604. while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
  2605. puts(cp);
  2606. } else {
  2607. fprintf(stderr, "No principal matched.\n");
  2608. }
  2609. sshbuf_free(sigbuf);
  2610. sshbuf_free(abuf);
  2611. sshkey_free(sign_key);
  2612. free(principals);
  2613. return ret;
  2614. }
  2615. static void
  2616. do_moduli_gen(const char *out_file, char **opts, size_t nopts)
  2617. {
  2618. #ifdef WITH_OPENSSL
  2619. /* Moduli generation/screening */
  2620. u_int32_t memory = 0;
  2621. BIGNUM *start = NULL;
  2622. int moduli_bits = 0;
  2623. FILE *out;
  2624. size_t i;
  2625. const char *errstr;
  2626. /* Parse options */
  2627. for (i = 0; i < nopts; i++) {
  2628. if (strncmp(opts[i], "memory=", 7) == 0) {
  2629. memory = (u_int32_t)strtonum(opts[i]+7, 1,
  2630. UINT_MAX, &errstr);
  2631. if (errstr) {
  2632. fatal("Memory limit is %s: %s",
  2633. errstr, opts[i]+7);
  2634. }
  2635. } else if (strncmp(opts[i], "start=", 6) == 0) {
  2636. /* XXX - also compare length against bits */
  2637. if (BN_hex2bn(&start, opts[i]+6) == 0)
  2638. fatal("Invalid start point.");
  2639. } else if (strncmp(opts[i], "bits=", 5) == 0) {
  2640. moduli_bits = (int)strtonum(opts[i]+5, 1,
  2641. INT_MAX, &errstr);
  2642. if (errstr) {
  2643. fatal("Invalid number: %s (%s)",
  2644. opts[i]+12, errstr);
  2645. }
  2646. } else {
  2647. fatal("Option \"%s\" is unsupported for moduli "
  2648. "generation", opts[i]);
  2649. }
  2650. }
  2651. if ((out = fopen(out_file, "w")) == NULL) {
  2652. fatal("Couldn't open modulus candidate file \"%s\": %s",
  2653. out_file, strerror(errno));
  2654. }
  2655. setvbuf(out, NULL, _IOLBF, 0);
  2656. if (moduli_bits == 0)
  2657. moduli_bits = DEFAULT_BITS;
  2658. if (gen_candidates(out, memory, moduli_bits, start) != 0)
  2659. fatal("modulus candidate generation failed");
  2660. #else /* WITH_OPENSSL */
  2661. fatal("Moduli generation is not supported");
  2662. #endif /* WITH_OPENSSL */
  2663. }
  2664. static void
  2665. do_moduli_screen(const char *out_file, char **opts, size_t nopts)
  2666. {
  2667. #ifdef WITH_OPENSSL
  2668. /* Moduli generation/screening */
  2669. char *checkpoint = NULL;
  2670. u_int32_t generator_wanted = 0;
  2671. unsigned long start_lineno = 0, lines_to_process = 0;
  2672. int prime_tests = 0;
  2673. FILE *out, *in = stdin;
  2674. size_t i;
  2675. const char *errstr;
  2676. /* Parse options */
  2677. for (i = 0; i < nopts; i++) {
  2678. if (strncmp(opts[i], "lines=", 6) == 0) {
  2679. lines_to_process = strtoul(opts[i]+6, NULL, 10);
  2680. } else if (strncmp(opts[i], "start-line=", 11) == 0) {
  2681. start_lineno = strtoul(opts[i]+11, NULL, 10);
  2682. } else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
  2683. checkpoint = xstrdup(opts[i]+11);
  2684. } else if (strncmp(opts[i], "generator=", 10) == 0) {
  2685. generator_wanted = (u_int32_t)strtonum(
  2686. opts[i]+10, 1, UINT_MAX, &errstr);
  2687. if (errstr != NULL) {
  2688. fatal("Generator invalid: %s (%s)",
  2689. opts[i]+10, errstr);
  2690. }
  2691. } else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
  2692. prime_tests = (int)strtonum(opts[i]+12, 1,
  2693. INT_MAX, &errstr);
  2694. if (errstr) {
  2695. fatal("Invalid number: %s (%s)",
  2696. opts[i]+12, errstr);
  2697. }
  2698. } else {
  2699. fatal("Option \"%s\" is unsupported for moduli "
  2700. "screening", opts[i]);
  2701. }
  2702. }
  2703. if (have_identity && strcmp(identity_file, "-") != 0) {
  2704. if ((in = fopen(identity_file, "r")) == NULL) {
  2705. fatal("Couldn't open modulus candidate "
  2706. "file \"%s\": %s", identity_file,
  2707. strerror(errno));
  2708. }
  2709. }
  2710. if ((out = fopen(out_file, "a")) == NULL) {
  2711. fatal("Couldn't open moduli file \"%s\": %s",
  2712. out_file, strerror(errno));
  2713. }
  2714. setvbuf(out, NULL, _IOLBF, 0);
  2715. if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
  2716. generator_wanted, checkpoint,
  2717. start_lineno, lines_to_process) != 0)
  2718. fatal("modulus screening failed");
  2719. #else /* WITH_OPENSSL */
  2720. fatal("Moduli screening is not supported");
  2721. #endif /* WITH_OPENSSL */
  2722. }
  2723. static char *
  2724. private_key_passphrase(void)
  2725. {
  2726. char *passphrase1, *passphrase2;
  2727. /* Ask for a passphrase (twice). */
  2728. if (identity_passphrase)
  2729. passphrase1 = xstrdup(identity_passphrase);
  2730. else if (identity_new_passphrase)
  2731. passphrase1 = xstrdup(identity_new_passphrase);
  2732. else {
  2733. passphrase_again:
  2734. passphrase1 =
  2735. read_passphrase("Enter passphrase (empty for no "
  2736. "passphrase): ", RP_ALLOW_STDIN);
  2737. passphrase2 = read_passphrase("Enter same passphrase again: ",
  2738. RP_ALLOW_STDIN);
  2739. if (strcmp(passphrase1, passphrase2) != 0) {
  2740. /*
  2741. * The passphrases do not match. Clear them and
  2742. * retry.
  2743. */
  2744. freezero(passphrase1, strlen(passphrase1));
  2745. freezero(passphrase2, strlen(passphrase2));
  2746. printf("Passphrases do not match. Try again.\n");
  2747. goto passphrase_again;
  2748. }
  2749. /* Clear the other copy of the passphrase. */
  2750. freezero(passphrase2, strlen(passphrase2));
  2751. }
  2752. return passphrase1;
  2753. }
  2754. static const char *
  2755. skip_ssh_url_preamble(const char *s)
  2756. {
  2757. if (strncmp(s, "ssh://", 6) == 0)
  2758. return s + 6;
  2759. else if (strncmp(s, "ssh:", 4) == 0)
  2760. return s + 4;
  2761. return s;
  2762. }
  2763. static int
  2764. do_download_sk(const char *skprovider, const char *device)
  2765. {
  2766. struct sshkey **keys;
  2767. size_t nkeys, i;
  2768. int r, ret = -1;
  2769. char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
  2770. const char *ext;
  2771. if (skprovider == NULL)
  2772. fatal("Cannot download keys without provider");
  2773. pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
  2774. if (!quiet) {
  2775. printf("You may need to touch your authenticator "
  2776. "to authorize key download.\n");
  2777. }
  2778. if ((r = sshsk_load_resident(skprovider, device, pin,
  2779. &keys, &nkeys)) != 0) {
  2780. if (pin != NULL)
  2781. freezero(pin, strlen(pin));
  2782. error("Unable to load resident keys: %s", ssh_err(r));
  2783. return -1;
  2784. }
  2785. if (nkeys == 0)
  2786. logit("No keys to download");
  2787. if (pin != NULL)
  2788. freezero(pin, strlen(pin));
  2789. for (i = 0; i < nkeys; i++) {
  2790. if (keys[i]->type != KEY_ECDSA_SK &&
  2791. keys[i]->type != KEY_ED25519_SK) {
  2792. error("Unsupported key type %s (%d)",
  2793. sshkey_type(keys[i]), keys[i]->type);
  2794. continue;
  2795. }
  2796. if ((fp = sshkey_fingerprint(keys[i],
  2797. fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
  2798. fatal("%s: sshkey_fingerprint failed", __func__);
  2799. debug("%s: key %zu: %s %s %s (flags 0x%02x)", __func__, i,
  2800. sshkey_type(keys[i]), fp, keys[i]->sk_application,
  2801. keys[i]->sk_flags);
  2802. ext = skip_ssh_url_preamble(keys[i]->sk_application);
  2803. xasprintf(&path, "id_%s_rk%s%s",
  2804. keys[i]->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
  2805. *ext == '\0' ? "" : "_", ext);
  2806. /* If the file already exists, ask the user to confirm. */
  2807. if (!confirm_overwrite(path)) {
  2808. free(path);
  2809. break;
  2810. }
  2811. /* Save the key with the application string as the comment */
  2812. if (pass == NULL)
  2813. pass = private_key_passphrase();
  2814. if ((r = sshkey_save_private(keys[i], path, pass,
  2815. keys[i]->sk_application, private_key_format,
  2816. openssh_format_cipher, rounds)) != 0) {
  2817. error("Saving key \"%s\" failed: %s",
  2818. path, ssh_err(r));
  2819. free(path);
  2820. break;
  2821. }
  2822. if (!quiet) {
  2823. printf("Saved %s key%s%s to %s\n",
  2824. sshkey_type(keys[i]),
  2825. *ext != '\0' ? " " : "",
  2826. *ext != '\0' ? keys[i]->sk_application : "",
  2827. path);
  2828. }
  2829. /* Save public key too */
  2830. xasprintf(&pubpath, "%s.pub", path);
  2831. free(path);
  2832. if ((r = sshkey_save_public(keys[i], pubpath,
  2833. keys[i]->sk_application)) != 0) {
  2834. error("Saving public key \"%s\" failed: %s",
  2835. pubpath, ssh_err(r));
  2836. free(pubpath);
  2837. break;
  2838. }
  2839. free(pubpath);
  2840. }
  2841. if (i >= nkeys)
  2842. ret = 0; /* success */
  2843. if (pass != NULL)
  2844. freezero(pass, strlen(pass));
  2845. for (i = 0; i < nkeys; i++)
  2846. sshkey_free(keys[i]);
  2847. free(keys);
  2848. return ret;
  2849. }
  2850. static void
  2851. save_attestation(struct sshbuf *attest, const char *path)
  2852. {
  2853. mode_t omask;
  2854. int r;
  2855. if (path == NULL)
  2856. return; /* nothing to do */
  2857. if (attest == NULL || sshbuf_len(attest) == 0)
  2858. fatal("Enrollment did not return attestation data");
  2859. omask = umask(077);
  2860. r = sshbuf_write_file(path, attest);
  2861. umask(omask);
  2862. if (r != 0)
  2863. fatal("Unable to write attestation data \"%s\": %s", path,
  2864. ssh_err(r));
  2865. if (!quiet)
  2866. printf("Your FIDO attestation certificate has been saved in "
  2867. "%s\n", path);
  2868. }
  2869. static void
  2870. usage(void)
  2871. {
  2872. fprintf(stderr,
  2873. "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
  2874. " [-m format] [-N new_passphrase] [-O option]\n"
  2875. " [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
  2876. " [-w provider] [-Z cipher]\n"
  2877. " ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
  2878. " [-P old_passphrase] [-Z cipher]\n"
  2879. " ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
  2880. " ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
  2881. " ssh-keygen -y [-f input_keyfile]\n"
  2882. " ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
  2883. " ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
  2884. " ssh-keygen -B [-f input_keyfile]\n");
  2885. #ifdef ENABLE_PKCS11
  2886. fprintf(stderr,
  2887. " ssh-keygen -D pkcs11\n");
  2888. #endif
  2889. fprintf(stderr,
  2890. " ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
  2891. " ssh-keygen -H [-f known_hosts_file]\n"
  2892. " ssh-keygen -K [-a rounds] [-w provider]\n"
  2893. " ssh-keygen -R hostname [-f known_hosts_file]\n"
  2894. " ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
  2895. #ifdef WITH_OPENSSL
  2896. " ssh-keygen -M generate [-O option] output_file\n"
  2897. " ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
  2898. #endif
  2899. " ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
  2900. " [-n principals] [-O option] [-V validity_interval]\n"
  2901. " [-z serial_number] file ...\n"
  2902. " ssh-keygen -L [-f input_keyfile]\n"
  2903. " ssh-keygen -A [-a rounds] [-f prefix_path]\n"
  2904. " ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
  2905. " file ...\n"
  2906. " ssh-keygen -Q [-l] -f krl_file [file ...]\n"
  2907. " ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
  2908. " ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
  2909. " ssh-keygen -Y sign -f key_file -n namespace file ...\n"
  2910. " ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
  2911. " -n namespace -s signature_file [-r revocation_file]\n");
  2912. exit(1);
  2913. }
  2914. /*
  2915. * Main program for key management.
  2916. */
  2917. int
  2918. main(int argc, char **argv)
  2919. {
  2920. char comment[1024], *passphrase;
  2921. char *rr_hostname = NULL, *ep, *fp, *ra;
  2922. struct sshkey *private, *public;
  2923. struct passwd *pw;
  2924. int r, opt, type;
  2925. int change_passphrase = 0, change_comment = 0, show_cert = 0;
  2926. int find_host = 0, delete_host = 0, hash_hosts = 0;
  2927. int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
  2928. int prefer_agent = 0, convert_to = 0, convert_from = 0;
  2929. int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
  2930. int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
  2931. unsigned long long cert_serial = 0;
  2932. char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
  2933. char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
  2934. char *sk_attestation_path = NULL;
  2935. struct sshbuf *challenge = NULL, *attest = NULL;
  2936. size_t i, nopts = 0;
  2937. u_int32_t bits = 0;
  2938. uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
  2939. const char *errstr;
  2940. int log_level = SYSLOG_LEVEL_INFO;
  2941. char *sign_op = NULL;
  2942. extern int optind;
  2943. extern char *optarg;
  2944. /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
  2945. sanitise_stdfd();
  2946. __progname = ssh_get_progname(argv[0]);
  2947. seed_rng();
  2948. log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
  2949. msetlocale();
  2950. /* we need this for the home * directory. */
  2951. pw = getpwuid(getuid());
  2952. if (!pw)
  2953. fatal("No user exists for uid %lu", (u_long)getuid());
  2954. if (gethostname(hostname, sizeof(hostname)) == -1)
  2955. fatal("gethostname: %s", strerror(errno));
  2956. sk_provider = getenv("SSH_SK_PROVIDER");
  2957. /* Remaining characters: dGjJSTWx */
  2958. while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
  2959. "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
  2960. "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
  2961. switch (opt) {
  2962. case 'A':
  2963. gen_all_hostkeys = 1;
  2964. break;
  2965. case 'b':
  2966. bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
  2967. &errstr);
  2968. if (errstr)
  2969. fatal("Bits has bad value %s (%s)",
  2970. optarg, errstr);
  2971. break;
  2972. case 'E':
  2973. fingerprint_hash = ssh_digest_alg_by_name(optarg);
  2974. if (fingerprint_hash == -1)
  2975. fatal("Invalid hash algorithm \"%s\"", optarg);
  2976. break;
  2977. case 'F':
  2978. find_host = 1;
  2979. rr_hostname = optarg;
  2980. break;
  2981. case 'H':
  2982. hash_hosts = 1;
  2983. break;
  2984. case 'I':
  2985. cert_key_id = optarg;
  2986. break;
  2987. case 'R':
  2988. delete_host = 1;
  2989. rr_hostname = optarg;
  2990. break;
  2991. case 'L':
  2992. show_cert = 1;
  2993. break;
  2994. case 'l':
  2995. print_fingerprint = 1;
  2996. break;
  2997. case 'B':
  2998. print_bubblebabble = 1;
  2999. break;
  3000. case 'm':
  3001. if (strcasecmp(optarg, "RFC4716") == 0 ||
  3002. strcasecmp(optarg, "ssh2") == 0) {
  3003. convert_format = FMT_RFC4716;
  3004. break;
  3005. }
  3006. if (strcasecmp(optarg, "PKCS8") == 0) {
  3007. convert_format = FMT_PKCS8;
  3008. private_key_format = SSHKEY_PRIVATE_PKCS8;
  3009. break;
  3010. }
  3011. if (strcasecmp(optarg, "PEM") == 0) {
  3012. convert_format = FMT_PEM;
  3013. private_key_format = SSHKEY_PRIVATE_PEM;
  3014. break;
  3015. }
  3016. fatal("Unsupported conversion format \"%s\"", optarg);
  3017. case 'n':
  3018. cert_principals = optarg;
  3019. break;
  3020. case 'o':
  3021. /* no-op; new format is already the default */
  3022. break;
  3023. case 'p':
  3024. change_passphrase = 1;
  3025. break;
  3026. case 'c':
  3027. change_comment = 1;
  3028. break;
  3029. case 'f':
  3030. if (strlcpy(identity_file, optarg,
  3031. sizeof(identity_file)) >= sizeof(identity_file))
  3032. fatal("Identity filename too long");
  3033. have_identity = 1;
  3034. break;
  3035. case 'g':
  3036. print_generic = 1;
  3037. break;
  3038. case 'K':
  3039. download_sk = 1;
  3040. break;
  3041. case 'P':
  3042. identity_passphrase = optarg;
  3043. break;
  3044. case 'N':
  3045. identity_new_passphrase = optarg;
  3046. break;
  3047. case 'Q':
  3048. check_krl = 1;
  3049. break;
  3050. case 'O':
  3051. opts = xrecallocarray(opts, nopts, nopts + 1,
  3052. sizeof(*opts));
  3053. opts[nopts++] = xstrdup(optarg);
  3054. break;
  3055. case 'Z':
  3056. openssh_format_cipher = optarg;
  3057. if (cipher_by_name(openssh_format_cipher) == NULL)
  3058. fatal("Invalid OpenSSH-format cipher '%s'",
  3059. openssh_format_cipher);
  3060. break;
  3061. case 'C':
  3062. identity_comment = optarg;
  3063. break;
  3064. case 'q':
  3065. quiet = 1;
  3066. break;
  3067. case 'e':
  3068. /* export key */
  3069. convert_to = 1;
  3070. break;
  3071. case 'h':
  3072. cert_key_type = SSH2_CERT_TYPE_HOST;
  3073. certflags_flags = 0;
  3074. break;
  3075. case 'k':
  3076. gen_krl = 1;
  3077. break;
  3078. case 'i':
  3079. case 'X':
  3080. /* import key */
  3081. convert_from = 1;
  3082. break;
  3083. case 'y':
  3084. print_public = 1;
  3085. break;
  3086. case 's':
  3087. ca_key_path = optarg;
  3088. break;
  3089. case 't':
  3090. key_type_name = optarg;
  3091. break;
  3092. case 'D':
  3093. pkcs11provider = optarg;
  3094. break;
  3095. case 'U':
  3096. prefer_agent = 1;
  3097. break;
  3098. case 'u':
  3099. update_krl = 1;
  3100. break;
  3101. case 'v':
  3102. if (log_level == SYSLOG_LEVEL_INFO)
  3103. log_level = SYSLOG_LEVEL_DEBUG1;
  3104. else {
  3105. if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
  3106. log_level < SYSLOG_LEVEL_DEBUG3)
  3107. log_level++;
  3108. }
  3109. break;
  3110. case 'r':
  3111. rr_hostname = optarg;
  3112. break;
  3113. case 'a':
  3114. rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
  3115. if (errstr)
  3116. fatal("Invalid number: %s (%s)",
  3117. optarg, errstr);
  3118. break;
  3119. case 'V':
  3120. parse_cert_times(optarg);
  3121. break;
  3122. case 'Y':
  3123. sign_op = optarg;
  3124. break;
  3125. case 'w':
  3126. sk_provider = optarg;
  3127. break;
  3128. case 'z':
  3129. errno = 0;
  3130. if (*optarg == '+') {
  3131. cert_serial_autoinc = 1;
  3132. optarg++;
  3133. }
  3134. cert_serial = strtoull(optarg, &ep, 10);
  3135. if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
  3136. (errno == ERANGE && cert_serial == ULLONG_MAX))
  3137. fatal("Invalid serial number \"%s\"", optarg);
  3138. break;
  3139. case 'M':
  3140. if (strcmp(optarg, "generate") == 0)
  3141. do_gen_candidates = 1;
  3142. else if (strcmp(optarg, "screen") == 0)
  3143. do_screen_candidates = 1;
  3144. else
  3145. fatal("Unsupported moduli option %s", optarg);
  3146. break;
  3147. case '?':
  3148. default:
  3149. usage();
  3150. }
  3151. }
  3152. #ifdef ENABLE_SK_INTERNAL
  3153. if (sk_provider == NULL)
  3154. sk_provider = "internal";
  3155. #endif
  3156. /* reinit */
  3157. log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
  3158. argv += optind;
  3159. argc -= optind;
  3160. if (sign_op != NULL) {
  3161. if (strncmp(sign_op, "find-principals", 15) == 0) {
  3162. if (ca_key_path == NULL) {
  3163. error("Too few arguments for find-principals:"
  3164. "missing signature file");
  3165. exit(1);
  3166. }
  3167. if (!have_identity) {
  3168. error("Too few arguments for find-principals:"
  3169. "missing allowed keys file");
  3170. exit(1);
  3171. }
  3172. return sig_find_principals(ca_key_path, identity_file);
  3173. } else if (strncmp(sign_op, "sign", 4) == 0) {
  3174. if (cert_principals == NULL ||
  3175. *cert_principals == '\0') {
  3176. error("Too few arguments for sign: "
  3177. "missing namespace");
  3178. exit(1);
  3179. }
  3180. if (!have_identity) {
  3181. error("Too few arguments for sign: "
  3182. "missing key");
  3183. exit(1);
  3184. }
  3185. return sig_sign(identity_file, cert_principals,
  3186. argc, argv);
  3187. } else if (strncmp(sign_op, "check-novalidate", 16) == 0) {
  3188. if (ca_key_path == NULL) {
  3189. error("Too few arguments for check-novalidate: "
  3190. "missing signature file");
  3191. exit(1);
  3192. }
  3193. return sig_verify(ca_key_path, cert_principals,
  3194. NULL, NULL, NULL);
  3195. } else if (strncmp(sign_op, "verify", 6) == 0) {
  3196. if (cert_principals == NULL ||
  3197. *cert_principals == '\0') {
  3198. error("Too few arguments for verify: "
  3199. "missing namespace");
  3200. exit(1);
  3201. }
  3202. if (ca_key_path == NULL) {
  3203. error("Too few arguments for verify: "
  3204. "missing signature file");
  3205. exit(1);
  3206. }
  3207. if (!have_identity) {
  3208. error("Too few arguments for sign: "
  3209. "missing allowed keys file");
  3210. exit(1);
  3211. }
  3212. if (cert_key_id == NULL) {
  3213. error("Too few arguments for verify: "
  3214. "missing principal ID");
  3215. exit(1);
  3216. }
  3217. return sig_verify(ca_key_path, cert_principals,
  3218. cert_key_id, identity_file, rr_hostname);
  3219. }
  3220. error("Unsupported operation for -Y: \"%s\"", sign_op);
  3221. usage();
  3222. /* NOTREACHED */
  3223. }
  3224. if (ca_key_path != NULL) {
  3225. if (argc < 1 && !gen_krl) {
  3226. error("Too few arguments.");
  3227. usage();
  3228. }
  3229. } else if (argc > 0 && !gen_krl && !check_krl &&
  3230. !do_gen_candidates && !do_screen_candidates) {
  3231. error("Too many arguments.");
  3232. usage();
  3233. }
  3234. if (change_passphrase && change_comment) {
  3235. error("Can only have one of -p and -c.");
  3236. usage();
  3237. }
  3238. if (print_fingerprint && (delete_host || hash_hosts)) {
  3239. error("Cannot use -l with -H or -R.");
  3240. usage();
  3241. }
  3242. if (gen_krl) {
  3243. do_gen_krl(pw, update_krl, ca_key_path,
  3244. cert_serial, identity_comment, argc, argv);
  3245. return (0);
  3246. }
  3247. if (check_krl) {
  3248. do_check_krl(pw, print_fingerprint, argc, argv);
  3249. return (0);
  3250. }
  3251. if (ca_key_path != NULL) {
  3252. if (cert_key_id == NULL)
  3253. fatal("Must specify key id (-I) when certifying");
  3254. for (i = 0; i < nopts; i++)
  3255. add_cert_option(opts[i]);
  3256. do_ca_sign(pw, ca_key_path, prefer_agent,
  3257. cert_serial, cert_serial_autoinc, argc, argv);
  3258. }
  3259. if (show_cert)
  3260. do_show_cert(pw);
  3261. if (delete_host || hash_hosts || find_host) {
  3262. do_known_hosts(pw, rr_hostname, find_host,
  3263. delete_host, hash_hosts);
  3264. }
  3265. if (pkcs11provider != NULL)
  3266. do_download(pw);
  3267. if (download_sk) {
  3268. for (i = 0; i < nopts; i++) {
  3269. if (strncasecmp(opts[i], "device=", 7) == 0) {
  3270. sk_device = xstrdup(opts[i] + 7);
  3271. } else {
  3272. fatal("Option \"%s\" is unsupported for "
  3273. "FIDO authenticator download", opts[i]);
  3274. }
  3275. }
  3276. return do_download_sk(sk_provider, sk_device);
  3277. }
  3278. if (print_fingerprint || print_bubblebabble)
  3279. do_fingerprint(pw);
  3280. if (change_passphrase)
  3281. do_change_passphrase(pw);
  3282. if (change_comment)
  3283. do_change_comment(pw, identity_comment);
  3284. #ifdef WITH_OPENSSL
  3285. if (convert_to)
  3286. do_convert_to(pw);
  3287. if (convert_from)
  3288. do_convert_from(pw);
  3289. #else /* WITH_OPENSSL */
  3290. if (convert_to || convert_from)
  3291. fatal("key conversion disabled at compile time");
  3292. #endif /* WITH_OPENSSL */
  3293. if (print_public)
  3294. do_print_public(pw);
  3295. if (rr_hostname != NULL) {
  3296. unsigned int n = 0;
  3297. if (have_identity) {
  3298. n = do_print_resource_record(pw, identity_file,
  3299. rr_hostname, print_generic);
  3300. if (n == 0)
  3301. fatal("%s: %s", identity_file, strerror(errno));
  3302. exit(0);
  3303. } else {
  3304. n += do_print_resource_record(pw,
  3305. _PATH_HOST_RSA_KEY_FILE, rr_hostname,
  3306. print_generic);
  3307. n += do_print_resource_record(pw,
  3308. _PATH_HOST_DSA_KEY_FILE, rr_hostname,
  3309. print_generic);
  3310. n += do_print_resource_record(pw,
  3311. _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
  3312. print_generic);
  3313. n += do_print_resource_record(pw,
  3314. _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
  3315. print_generic);
  3316. n += do_print_resource_record(pw,
  3317. _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
  3318. print_generic);
  3319. if (n == 0)
  3320. fatal("no keys found.");
  3321. exit(0);
  3322. }
  3323. }
  3324. if (do_gen_candidates || do_screen_candidates) {
  3325. if (argc <= 0)
  3326. fatal("No output file specified");
  3327. else if (argc > 1)
  3328. fatal("Too many output files specified");
  3329. }
  3330. if (do_gen_candidates) {
  3331. do_moduli_gen(argv[0], opts, nopts);
  3332. return 0;
  3333. }
  3334. if (do_screen_candidates) {
  3335. do_moduli_screen(argv[0], opts, nopts);
  3336. return 0;
  3337. }
  3338. if (gen_all_hostkeys) {
  3339. do_gen_all_hostkeys(pw);
  3340. return (0);
  3341. }
  3342. if (key_type_name == NULL)
  3343. key_type_name = DEFAULT_KEY_TYPE_NAME;
  3344. type = sshkey_type_from_name(key_type_name);
  3345. type_bits_valid(type, key_type_name, &bits);
  3346. if (!quiet)
  3347. printf("Generating public/private %s key pair.\n",
  3348. key_type_name);
  3349. switch (type) {
  3350. case KEY_ECDSA_SK:
  3351. case KEY_ED25519_SK:
  3352. for (i = 0; i < nopts; i++) {
  3353. if (strcasecmp(opts[i], "no-touch-required") == 0) {
  3354. sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
  3355. } else if (strcasecmp(opts[i], "verify-required") == 0) {
  3356. sk_flags |= SSH_SK_USER_VERIFICATION_REQD;
  3357. } else if (strcasecmp(opts[i], "resident") == 0) {
  3358. sk_flags |= SSH_SK_RESIDENT_KEY;
  3359. } else if (strncasecmp(opts[i], "device=", 7) == 0) {
  3360. sk_device = xstrdup(opts[i] + 7);
  3361. } else if (strncasecmp(opts[i], "user=", 5) == 0) {
  3362. sk_user = xstrdup(opts[i] + 5);
  3363. } else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
  3364. if ((r = sshbuf_load_file(opts[i] + 10,
  3365. &challenge)) != 0) {
  3366. fatal("Unable to load FIDO enrollment "
  3367. "challenge \"%s\": %s",
  3368. opts[i] + 10, ssh_err(r));
  3369. }
  3370. } else if (strncasecmp(opts[i],
  3371. "write-attestation=", 18) == 0) {
  3372. sk_attestation_path = opts[i] + 18;
  3373. } else if (strncasecmp(opts[i],
  3374. "application=", 12) == 0) {
  3375. sk_application = xstrdup(opts[i] + 12);
  3376. if (strncmp(sk_application, "ssh:", 4) != 0) {
  3377. fatal("FIDO application string must "
  3378. "begin with \"ssh:\"");
  3379. }
  3380. } else {
  3381. fatal("Option \"%s\" is unsupported for "
  3382. "FIDO authenticator enrollment", opts[i]);
  3383. }
  3384. }
  3385. if (!quiet) {
  3386. printf("You may need to touch your authenticator "
  3387. "to authorize key generation.\n");
  3388. }
  3389. if ((attest = sshbuf_new()) == NULL)
  3390. fatal("sshbuf_new failed");
  3391. if ((sk_flags &
  3392. (SSH_SK_USER_VERIFICATION_REQD|SSH_SK_RESIDENT_KEY))) {
  3393. passphrase = read_passphrase("Enter PIN for "
  3394. "authenticator: ", RP_ALLOW_STDIN);
  3395. } else {
  3396. passphrase = NULL;
  3397. }
  3398. for (i = 0 ; ; i++) {
  3399. fflush(stdout);
  3400. r = sshsk_enroll(type, sk_provider, sk_device,
  3401. sk_application == NULL ? "ssh:" : sk_application,
  3402. sk_user, sk_flags, passphrase, challenge,
  3403. &private, attest);
  3404. if (r == 0)
  3405. break;
  3406. if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
  3407. fatal("Key enrollment failed: %s", ssh_err(r));
  3408. else if (passphrase != NULL) {
  3409. error("PIN incorrect");
  3410. freezero(passphrase, strlen(passphrase));
  3411. passphrase = NULL;
  3412. }
  3413. if (i >= 3)
  3414. fatal("Too many incorrect PINs");
  3415. passphrase = read_passphrase("Enter PIN for "
  3416. "authenticator: ", RP_ALLOW_STDIN);
  3417. if (!quiet) {
  3418. printf("You may need to touch your "
  3419. "authenticator (again) to authorize "
  3420. "key generation.\n");
  3421. }
  3422. }
  3423. if (passphrase != NULL) {
  3424. freezero(passphrase, strlen(passphrase));
  3425. passphrase = NULL;
  3426. }
  3427. break;
  3428. default:
  3429. if ((r = sshkey_generate(type, bits, &private)) != 0)
  3430. fatal("sshkey_generate failed");
  3431. break;
  3432. }
  3433. if ((r = sshkey_from_private(private, &public)) != 0)
  3434. fatal("sshkey_from_private failed: %s\n", ssh_err(r));
  3435. if (!have_identity)
  3436. ask_filename(pw, "Enter file in which to save the key");
  3437. /* Create ~/.ssh directory if it doesn't already exist. */
  3438. hostfile_create_user_ssh_dir(identity_file, !quiet);
  3439. /* If the file already exists, ask the user to confirm. */
  3440. if (!confirm_overwrite(identity_file))
  3441. exit(1);
  3442. /* Determine the passphrase for the private key */
  3443. passphrase = private_key_passphrase();
  3444. if (identity_comment) {
  3445. strlcpy(comment, identity_comment, sizeof(comment));
  3446. } else {
  3447. /* Create default comment field for the passphrase. */
  3448. snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
  3449. }
  3450. /* Save the key with the given passphrase and comment. */
  3451. if ((r = sshkey_save_private(private, identity_file, passphrase,
  3452. comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
  3453. error("Saving key \"%s\" failed: %s",
  3454. identity_file, ssh_err(r));
  3455. freezero(passphrase, strlen(passphrase));
  3456. exit(1);
  3457. }
  3458. freezero(passphrase, strlen(passphrase));
  3459. sshkey_free(private);
  3460. if (!quiet) {
  3461. printf("Your identification has been saved in %s\n",
  3462. identity_file);
  3463. }
  3464. strlcat(identity_file, ".pub", sizeof(identity_file));
  3465. if ((r = sshkey_save_public(public, identity_file, comment)) != 0) {
  3466. fatal("Unable to save public key to %s: %s",
  3467. identity_file, ssh_err(r));
  3468. }
  3469. if (!quiet) {
  3470. fp = sshkey_fingerprint(public, fingerprint_hash,
  3471. SSH_FP_DEFAULT);
  3472. ra = sshkey_fingerprint(public, fingerprint_hash,
  3473. SSH_FP_RANDOMART);
  3474. if (fp == NULL || ra == NULL)
  3475. fatal("sshkey_fingerprint failed");
  3476. printf("Your public key has been saved in %s\n",
  3477. identity_file);
  3478. printf("The key fingerprint is:\n");
  3479. printf("%s %s\n", fp, comment);
  3480. printf("The key's randomart image is:\n");
  3481. printf("%s\n", ra);
  3482. free(ra);
  3483. free(fp);
  3484. }
  3485. if (sk_attestation_path != NULL)
  3486. save_attestation(attest, sk_attestation_path);
  3487. sshbuf_free(attest);
  3488. sshkey_free(public);
  3489. exit(0);
  3490. }