import.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373
  1. /*
  2. * Code for PuTTY to import and export private key files in other
  3. * SSH clients' formats.
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include "putty.h"
  10. #include "ssh.h"
  11. #include "mpint.h"
  12. #include "misc.h"
  13. static bool openssh_pem_encrypted(const Filename *file);
  14. static bool openssh_new_encrypted(const Filename *file);
  15. static struct ssh2_userkey *openssh_pem_read(
  16. const Filename *file, const char *passphrase, const char **errmsg_p);
  17. static struct ssh2_userkey *openssh_new_read(
  18. const Filename *file, const char *passphrase, const char **errmsg_p);
  19. static bool openssh_auto_write(
  20. const Filename *file, struct ssh2_userkey *key, const char *passphrase);
  21. static bool openssh_pem_write(
  22. const Filename *file, struct ssh2_userkey *key, const char *passphrase);
  23. static bool openssh_new_write(
  24. const Filename *file, struct ssh2_userkey *key, const char *passphrase);
  25. static bool sshcom_encrypted(const Filename *file, char **comment);
  26. static struct ssh2_userkey *sshcom_read(
  27. const Filename *file, const char *passphrase, const char **errmsg_p);
  28. static bool sshcom_write(
  29. const Filename *file, struct ssh2_userkey *key, const char *passphrase);
  30. /*
  31. * Given a key type, determine whether we know how to import it.
  32. */
  33. bool import_possible(int type)
  34. {
  35. if (type == SSH_KEYTYPE_OPENSSH_PEM)
  36. return true;
  37. if (type == SSH_KEYTYPE_OPENSSH_NEW)
  38. return true;
  39. if (type == SSH_KEYTYPE_SSHCOM)
  40. return true;
  41. return false;
  42. }
  43. /*
  44. * Given a key type, determine what native key type
  45. * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
  46. * we've imported it.
  47. */
  48. int import_target_type(int type)
  49. {
  50. /*
  51. * There are no known foreign SSH-1 key formats.
  52. */
  53. return SSH_KEYTYPE_SSH2;
  54. }
  55. /*
  56. * Determine whether a foreign key is encrypted.
  57. */
  58. bool import_encrypted(const Filename *filename, int type, char **comment)
  59. {
  60. if (type == SSH_KEYTYPE_OPENSSH_PEM) {
  61. /* OpenSSH PEM format doesn't contain a key comment at all */
  62. *comment = dupstr(filename_to_str(filename));
  63. return openssh_pem_encrypted(filename);
  64. } else if (type == SSH_KEYTYPE_OPENSSH_NEW) {
  65. /* OpenSSH new format does, but it's inside the encrypted
  66. * section for some reason */
  67. *comment = dupstr(filename_to_str(filename));
  68. return openssh_new_encrypted(filename);
  69. } else if (type == SSH_KEYTYPE_SSHCOM) {
  70. return sshcom_encrypted(filename, comment);
  71. }
  72. return false;
  73. }
  74. /*
  75. * Import an SSH-1 key.
  76. */
  77. int import_ssh1(const Filename *filename, int type,
  78. struct RSAKey *key, char *passphrase, const char **errmsg_p)
  79. {
  80. return 0;
  81. }
  82. /*
  83. * Import an SSH-2 key.
  84. */
  85. struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
  86. char *passphrase, const char **errmsg_p)
  87. {
  88. if (type == SSH_KEYTYPE_OPENSSH_PEM)
  89. return openssh_pem_read(filename, passphrase, errmsg_p);
  90. else if (type == SSH_KEYTYPE_OPENSSH_NEW)
  91. return openssh_new_read(filename, passphrase, errmsg_p);
  92. if (type == SSH_KEYTYPE_SSHCOM)
  93. return sshcom_read(filename, passphrase, errmsg_p);
  94. return NULL;
  95. }
  96. /*
  97. * Export an SSH-1 key.
  98. */
  99. bool export_ssh1(const Filename *filename, int type, struct RSAKey *key,
  100. char *passphrase)
  101. {
  102. return false;
  103. }
  104. /*
  105. * Export an SSH-2 key.
  106. */
  107. bool export_ssh2(const Filename *filename, int type,
  108. struct ssh2_userkey *key, char *passphrase)
  109. {
  110. if (type == SSH_KEYTYPE_OPENSSH_AUTO)
  111. return openssh_auto_write(filename, key, passphrase);
  112. if (type == SSH_KEYTYPE_OPENSSH_NEW)
  113. return openssh_new_write(filename, key, passphrase);
  114. if (type == SSH_KEYTYPE_SSHCOM)
  115. return sshcom_write(filename, key, passphrase);
  116. return false;
  117. }
  118. /*
  119. * Strip trailing CRs and LFs at the end of a line of text.
  120. */
  121. void strip_crlf(char *str)
  122. {
  123. char *p = str + strlen(str);
  124. while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
  125. *--p = '\0';
  126. }
  127. /* ----------------------------------------------------------------------
  128. * Helper routines. (The base64 ones are defined in sshpubk.c.)
  129. */
  130. #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
  131. ((c) >= 'a' && (c) <= 'z') || \
  132. ((c) >= '0' && (c) <= '9') || \
  133. (c) == '+' || (c) == '/' || (c) == '=' \
  134. )
  135. /*
  136. * Read an ASN.1/BER identifier and length pair.
  137. *
  138. * Flags are a combination of the #defines listed below.
  139. *
  140. * Returns -1 if unsuccessful; otherwise returns the number of
  141. * bytes used out of the source data.
  142. */
  143. /* ASN.1 tag classes. */
  144. #define ASN1_CLASS_UNIVERSAL (0 << 6)
  145. #define ASN1_CLASS_APPLICATION (1 << 6)
  146. #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
  147. #define ASN1_CLASS_PRIVATE (3 << 6)
  148. #define ASN1_CLASS_MASK (3 << 6)
  149. /* Primitive versus constructed bit. */
  150. #define ASN1_CONSTRUCTED (1 << 5)
  151. /*
  152. * Write an ASN.1/BER identifier and length pair. Returns the
  153. * number of bytes consumed. Assumes dest contains enough space.
  154. * Will avoid writing anything if dest is NULL, but still return
  155. * amount of space required.
  156. */
  157. static void BinarySink_put_ber_id_len(BinarySink *bs,
  158. int id, int length, int flags)
  159. {
  160. if (id <= 30) {
  161. /*
  162. * Identifier is one byte.
  163. */
  164. put_byte(bs, id | flags);
  165. } else {
  166. int n;
  167. /*
  168. * Identifier is multiple bytes: the first byte is 11111
  169. * plus the flags, and subsequent bytes encode the value of
  170. * the identifier, 7 bits at a time, with the top bit of
  171. * each byte 1 except the last one which is 0.
  172. */
  173. put_byte(bs, 0x1F | flags);
  174. for (n = 1; (id >> (7*n)) > 0; n++)
  175. continue; /* count the bytes */
  176. while (n--)
  177. put_byte(bs, (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F));
  178. }
  179. if (length < 128) {
  180. /*
  181. * Length is one byte.
  182. */
  183. put_byte(bs, length);
  184. } else {
  185. int n;
  186. /*
  187. * Length is multiple bytes. The first is 0x80 plus the
  188. * number of subsequent bytes, and the subsequent bytes
  189. * encode the actual length.
  190. */
  191. for (n = 1; (length >> (8*n)) > 0; n++)
  192. continue; /* count the bytes */
  193. put_byte(bs, 0x80 | n);
  194. while (n--)
  195. put_byte(bs, (length >> (8*n)) & 0xFF);
  196. }
  197. }
  198. #define put_ber_id_len(bs, id, len, flags) \
  199. BinarySink_put_ber_id_len(BinarySink_UPCAST(bs), id, len, flags)
  200. typedef struct ber_item {
  201. int id;
  202. int flags;
  203. ptrlen data;
  204. } ber_item;
  205. static ber_item BinarySource_get_ber(BinarySource *src)
  206. {
  207. ber_item toret;
  208. unsigned char leadbyte, lenbyte;
  209. size_t length;
  210. leadbyte = get_byte(src);
  211. toret.flags = (leadbyte & 0xE0);
  212. if ((leadbyte & 0x1F) == 0x1F) {
  213. unsigned char idbyte;
  214. toret.id = 0;
  215. do {
  216. idbyte = get_byte(src);
  217. toret.id = (toret.id << 7) | (idbyte & 0x7F);
  218. } while (idbyte & 0x80);
  219. } else {
  220. toret.id = leadbyte & 0x1F;
  221. }
  222. lenbyte = get_byte(src);
  223. if (lenbyte & 0x80) {
  224. int nbytes = lenbyte & 0x7F;
  225. length = 0;
  226. while (nbytes-- > 0)
  227. length = (length << 8) | get_byte(src);
  228. } else {
  229. length = lenbyte;
  230. }
  231. toret.data = get_data(src, length);
  232. return toret;
  233. }
  234. #define get_ber(bs) BinarySource_get_ber(BinarySource_UPCAST(bs))
  235. /* ----------------------------------------------------------------------
  236. * Code to read and write OpenSSH private keys, in the old-style PEM
  237. * format.
  238. */
  239. typedef enum {
  240. OP_DSA, OP_RSA, OP_ECDSA
  241. } openssh_pem_keytype;
  242. typedef enum {
  243. OP_E_3DES, OP_E_AES
  244. } openssh_pem_enc;
  245. struct openssh_pem_key {
  246. openssh_pem_keytype keytype;
  247. bool encrypted;
  248. openssh_pem_enc encryption;
  249. char iv[32];
  250. strbuf *keyblob;
  251. };
  252. void BinarySink_put_mp_ssh2_from_string(
  253. BinarySink *bs, const void *bytesv, int nbytes)
  254. {
  255. const unsigned char *bytes = (const unsigned char *)bytesv;
  256. while (nbytes > 0 && bytes[0] == 0) {
  257. nbytes--;
  258. bytes++;
  259. }
  260. if (nbytes > 0 && bytes[0] & 0x80) {
  261. put_uint32(bs, nbytes + 1);
  262. put_byte(bs, 0);
  263. } else {
  264. put_uint32(bs, nbytes);
  265. }
  266. put_data(bs, bytes, nbytes);
  267. }
  268. #define put_mp_ssh2_from_string(bs, val, len) \
  269. BinarySink_put_mp_ssh2_from_string(BinarySink_UPCAST(bs), val, len)
  270. static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename,
  271. const char **errmsg_p)
  272. {
  273. struct openssh_pem_key *ret;
  274. FILE *fp = NULL;
  275. char *line = NULL;
  276. const char *errmsg;
  277. char *p;
  278. bool headers_done;
  279. char base64_bit[4];
  280. int base64_chars = 0;
  281. ret = snew(struct openssh_pem_key);
  282. ret->keyblob = strbuf_new();
  283. fp = f_open(filename, "r", false);
  284. if (!fp) {
  285. errmsg = "unable to open key file";
  286. goto error;
  287. }
  288. if (!(line = fgetline(fp))) {
  289. errmsg = "unexpected end of file";
  290. goto error;
  291. }
  292. strip_crlf(line);
  293. if (!strstartswith(line, "-----BEGIN ") ||
  294. !strendswith(line, "PRIVATE KEY-----")) {
  295. errmsg = "file does not begin with OpenSSH key header";
  296. goto error;
  297. }
  298. /*
  299. * Parse the BEGIN line. For old-format keys, this tells us the
  300. * type of the key; for new-format keys, all it tells us is the
  301. * format, and we'll find out the key type once we parse the
  302. * base64.
  303. */
  304. if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----")) {
  305. ret->keytype = OP_RSA;
  306. } else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----")) {
  307. ret->keytype = OP_DSA;
  308. } else if (!strcmp(line, "-----BEGIN EC PRIVATE KEY-----")) {
  309. ret->keytype = OP_ECDSA;
  310. } else if (!strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
  311. errmsg = "this is a new-style OpenSSH key";
  312. goto error;
  313. } else {
  314. errmsg = "unrecognised key type";
  315. goto error;
  316. }
  317. smemclr(line, strlen(line));
  318. sfree(line);
  319. line = NULL;
  320. ret->encrypted = false;
  321. memset(ret->iv, 0, sizeof(ret->iv));
  322. headers_done = false;
  323. while (1) {
  324. if (!(line = fgetline(fp))) {
  325. errmsg = "unexpected end of file";
  326. goto error;
  327. }
  328. strip_crlf(line);
  329. if (strstartswith(line, "-----END ") &&
  330. strendswith(line, "PRIVATE KEY-----")) {
  331. sfree(line);
  332. line = NULL;
  333. break; /* done */
  334. }
  335. if ((p = strchr(line, ':')) != NULL) {
  336. if (headers_done) {
  337. errmsg = "header found in body of key data";
  338. goto error;
  339. }
  340. *p++ = '\0';
  341. while (*p && isspace((unsigned char)*p)) p++;
  342. if (!strcmp(line, "Proc-Type")) {
  343. if (p[0] != '4' || p[1] != ',') {
  344. errmsg = "Proc-Type is not 4 (only 4 is supported)";
  345. goto error;
  346. }
  347. p += 2;
  348. if (!strcmp(p, "ENCRYPTED"))
  349. ret->encrypted = true;
  350. } else if (!strcmp(line, "DEK-Info")) {
  351. int i, ivlen;
  352. if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
  353. ret->encryption = OP_E_3DES;
  354. ivlen = 8;
  355. } else if (!strncmp(p, "AES-128-CBC,", 12)) {
  356. ret->encryption = OP_E_AES;
  357. ivlen = 16;
  358. } else {
  359. errmsg = "unsupported cipher";
  360. goto error;
  361. }
  362. p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
  363. for (i = 0; i < ivlen; i++) {
  364. unsigned j;
  365. if (1 != sscanf(p, "%2x", &j)) {
  366. errmsg = "expected more iv data in DEK-Info";
  367. goto error;
  368. }
  369. ret->iv[i] = j;
  370. p += 2;
  371. }
  372. if (*p) {
  373. errmsg = "more iv data than expected in DEK-Info";
  374. goto error;
  375. }
  376. }
  377. } else {
  378. headers_done = true;
  379. p = line;
  380. while (isbase64(*p)) {
  381. base64_bit[base64_chars++] = *p;
  382. if (base64_chars == 4) {
  383. unsigned char out[3];
  384. int len;
  385. base64_chars = 0;
  386. len = base64_decode_atom(base64_bit, out);
  387. if (len <= 0) {
  388. errmsg = "invalid base64 encoding";
  389. goto error;
  390. }
  391. put_data(ret->keyblob, out, len);
  392. smemclr(out, sizeof(out));
  393. }
  394. p++;
  395. }
  396. }
  397. smemclr(line, strlen(line));
  398. sfree(line);
  399. line = NULL;
  400. }
  401. fclose(fp);
  402. fp = NULL;
  403. if (!ret->keyblob || ret->keyblob->len == 0) {
  404. errmsg = "key body not present";
  405. goto error;
  406. }
  407. if (ret->encrypted && ret->keyblob->len % 8 != 0) {
  408. errmsg = "encrypted key blob is not a multiple of "
  409. "cipher block size";
  410. goto error;
  411. }
  412. smemclr(base64_bit, sizeof(base64_bit));
  413. if (errmsg_p) *errmsg_p = NULL;
  414. return ret;
  415. error:
  416. if (line) {
  417. smemclr(line, strlen(line));
  418. sfree(line);
  419. line = NULL;
  420. }
  421. smemclr(base64_bit, sizeof(base64_bit));
  422. if (ret) {
  423. if (ret->keyblob)
  424. strbuf_free(ret->keyblob);
  425. smemclr(ret, sizeof(*ret));
  426. sfree(ret);
  427. }
  428. if (errmsg_p) *errmsg_p = errmsg;
  429. if (fp) fclose(fp);
  430. return NULL;
  431. }
  432. static bool openssh_pem_encrypted(const Filename *filename)
  433. {
  434. struct openssh_pem_key *key = load_openssh_pem_key(filename, NULL);
  435. bool ret;
  436. if (!key)
  437. return false;
  438. ret = key->encrypted;
  439. strbuf_free(key->keyblob);
  440. smemclr(key, sizeof(*key));
  441. sfree(key);
  442. return ret;
  443. }
  444. static struct ssh2_userkey *openssh_pem_read(
  445. const Filename *filename, const char *passphrase, const char **errmsg_p)
  446. {
  447. struct openssh_pem_key *key = load_openssh_pem_key(filename, errmsg_p);
  448. struct ssh2_userkey *retkey;
  449. const ssh_keyalg *alg;
  450. BinarySource src[1];
  451. int i, num_integers;
  452. struct ssh2_userkey *retval = NULL;
  453. const char *errmsg;
  454. strbuf *blob = strbuf_new();
  455. int privptr = 0, publen;
  456. const char *modptr = NULL;
  457. int modlen = 0;
  458. if (!key)
  459. return NULL;
  460. if (key->encrypted) {
  461. /*
  462. * Derive encryption key from passphrase and iv/salt:
  463. *
  464. * - let block A equal MD5(passphrase || iv)
  465. * - let block B equal MD5(A || passphrase || iv)
  466. * - block C would be MD5(B || passphrase || iv) and so on
  467. * - encryption key is the first N bytes of A || B
  468. *
  469. * (Note that only 8 bytes of the iv are used for key
  470. * derivation, even when the key is encrypted with AES and
  471. * hence there are 16 bytes available.)
  472. */
  473. struct MD5Context md5c;
  474. unsigned char keybuf[32];
  475. MD5Init(&md5c);
  476. put_data(&md5c, passphrase, strlen(passphrase));
  477. put_data(&md5c, key->iv, 8);
  478. MD5Final(keybuf, &md5c);
  479. MD5Init(&md5c);
  480. put_data(&md5c, keybuf, 16);
  481. put_data(&md5c, passphrase, strlen(passphrase));
  482. put_data(&md5c, key->iv, 8);
  483. MD5Final(keybuf+16, &md5c);
  484. /*
  485. * Now decrypt the key blob.
  486. */
  487. if (key->encryption == OP_E_3DES)
  488. des3_decrypt_pubkey_ossh(keybuf, key->iv,
  489. key->keyblob->u, key->keyblob->len);
  490. else {
  491. AESContext *ctx;
  492. assert(key->encryption == OP_E_AES);
  493. ctx = aes_make_context();
  494. aes128_key(ctx, keybuf);
  495. aes_iv(ctx, key->iv);
  496. aes_ssh2_decrypt_blk(ctx, key->keyblob->u, key->keyblob->len);
  497. aes_free_context(ctx);
  498. }
  499. smemclr(&md5c, sizeof(md5c));
  500. smemclr(keybuf, sizeof(keybuf));
  501. }
  502. /*
  503. * Now we have a decrypted key blob, which contains an ASN.1
  504. * encoded private key. We must now untangle the ASN.1.
  505. *
  506. * We expect the whole key blob to be formatted as a SEQUENCE
  507. * (0x30 followed by a length code indicating that the rest of
  508. * the blob is part of the sequence). Within that SEQUENCE we
  509. * expect to see a bunch of INTEGERs. What those integers mean
  510. * depends on the key type:
  511. *
  512. * - For RSA, we expect the integers to be 0, n, e, d, p, q,
  513. * dmp1, dmq1, iqmp in that order. (The last three are d mod
  514. * (p-1), d mod (q-1), inverse of q mod p respectively.)
  515. *
  516. * - For DSA, we expect them to be 0, p, q, g, y, x in that
  517. * order.
  518. *
  519. * - In ECDSA the format is totally different: we see the
  520. * SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv
  521. * EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint
  522. */
  523. BinarySource_BARE_INIT(src, key->keyblob->u, key->keyblob->len);
  524. {
  525. /* Expect the SEQUENCE header. Take its absence as a failure to
  526. * decrypt, if the key was encrypted. */
  527. ber_item seq = get_ber(src);
  528. if (get_err(src) || seq.id != 16) {
  529. errmsg = "ASN.1 decoding failure";
  530. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  531. goto error;
  532. }
  533. /* Reinitialise our BinarySource to parse just the inside of that
  534. * SEQUENCE. */
  535. BinarySource_BARE_INIT(src, seq.data.ptr, seq.data.len);
  536. }
  537. /* Expect a load of INTEGERs. */
  538. if (key->keytype == OP_RSA)
  539. num_integers = 9;
  540. else if (key->keytype == OP_DSA)
  541. num_integers = 6;
  542. else
  543. num_integers = 0; /* placate compiler warnings */
  544. if (key->keytype == OP_ECDSA) {
  545. /* And now for something completely different */
  546. ber_item integer, privkey, sub0, sub1, oid, pubkey;
  547. const ssh_keyalg *alg;
  548. const struct ec_curve *curve;
  549. /* Parse the outer layer of things inside the containing SEQUENCE */
  550. integer = get_ber(src);
  551. privkey = get_ber(src);
  552. sub0 = get_ber(src);
  553. sub1 = get_ber(src);
  554. /* Now look inside sub0 for the curve OID */
  555. BinarySource_BARE_INIT(src, sub0.data.ptr, sub0.data.len);
  556. oid = get_ber(src);
  557. /* And inside sub1 for the public-key BIT STRING */
  558. BinarySource_BARE_INIT(src, sub1.data.ptr, sub1.data.len);
  559. pubkey = get_ber(src);
  560. if (get_err(src) ||
  561. integer.id != 2 ||
  562. integer.data.len != 1 ||
  563. ((const unsigned char *)integer.data.ptr)[0] != 1 ||
  564. privkey.id != 4 ||
  565. sub0.id != 0 ||
  566. sub1.id != 1 ||
  567. oid.id != 6 ||
  568. pubkey.id != 3) {
  569. errmsg = "ASN.1 decoding failure";
  570. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  571. goto error;
  572. }
  573. alg = ec_alg_by_oid(oid.data.len, oid.data.ptr, &curve);
  574. if (!alg) {
  575. errmsg = "Unsupported ECDSA curve.";
  576. retval = NULL;
  577. goto error;
  578. }
  579. if (pubkey.data.len != ((((curve->fieldBits + 7) / 8) * 2) + 2)) {
  580. errmsg = "ASN.1 decoding failure";
  581. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  582. goto error;
  583. }
  584. /* Skip 0x00 before point */
  585. pubkey.data.ptr = (const char *)pubkey.data.ptr + 1;
  586. pubkey.data.len -= 1;
  587. /* Construct the key */
  588. retkey = snew(struct ssh2_userkey);
  589. put_stringz(blob, alg->ssh_id);
  590. put_stringz(blob, curve->name);
  591. put_stringpl(blob, pubkey.data);
  592. publen = blob->len;
  593. put_mp_ssh2_from_string(blob, privkey.data.ptr, privkey.data.len);
  594. retkey->key = ssh_key_new_priv(
  595. alg, make_ptrlen(blob->u, publen),
  596. make_ptrlen(blob->u + publen, blob->len - publen));
  597. if (!retkey->key) {
  598. sfree(retkey);
  599. errmsg = "unable to create key data structure";
  600. goto error;
  601. }
  602. } else if (key->keytype == OP_RSA || key->keytype == OP_DSA) {
  603. put_stringz(blob, key->keytype == OP_DSA ? "ssh-dss" : "ssh-rsa");
  604. for (i = 0; i < num_integers; i++) {
  605. ber_item integer = get_ber(src);
  606. if (get_err(src) || integer.id != 2) {
  607. errmsg = "ASN.1 decoding failure";
  608. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  609. goto error;
  610. }
  611. if (i == 0) {
  612. /*
  613. * The first integer should be zero always (I think
  614. * this is some sort of version indication).
  615. */
  616. if (integer.data.len != 1 ||
  617. ((const unsigned char *)integer.data.ptr)[0] != 0) {
  618. errmsg = "version number mismatch";
  619. goto error;
  620. }
  621. } else if (key->keytype == OP_RSA) {
  622. /*
  623. * Integers 1 and 2 go into the public blob but in the
  624. * opposite order; integers 3, 4, 5 and 8 go into the
  625. * private blob. The other two (6 and 7) are ignored.
  626. */
  627. if (i == 1) {
  628. /* Save the details for after we deal with number 2. */
  629. modptr = integer.data.ptr;
  630. modlen = integer.data.len;
  631. } else if (i != 6 && i != 7) {
  632. put_mp_ssh2_from_string(blob, integer.data.ptr,
  633. integer.data.len);
  634. if (i == 2) {
  635. put_mp_ssh2_from_string(blob, modptr, modlen);
  636. privptr = blob->len;
  637. }
  638. }
  639. } else if (key->keytype == OP_DSA) {
  640. /*
  641. * Integers 1-4 go into the public blob; integer 5 goes
  642. * into the private blob.
  643. */
  644. put_mp_ssh2_from_string(blob, integer.data.ptr,
  645. integer.data.len);
  646. if (i == 4)
  647. privptr = blob->len;
  648. }
  649. }
  650. /*
  651. * Now put together the actual key. Simplest way to do this is
  652. * to assemble our own key blobs and feed them to the createkey
  653. * functions; this is a bit faffy but it does mean we get all
  654. * the sanity checks for free.
  655. */
  656. assert(privptr > 0); /* should have bombed by now if not */
  657. retkey = snew(struct ssh2_userkey);
  658. alg = (key->keytype == OP_RSA ? &ssh_rsa : &ssh_dss);
  659. retkey->key = ssh_key_new_priv(
  660. alg, make_ptrlen(blob->u, privptr),
  661. make_ptrlen(blob->u+privptr, blob->len-privptr));
  662. if (!retkey->key) {
  663. sfree(retkey);
  664. errmsg = "unable to create key data structure";
  665. goto error;
  666. }
  667. } else {
  668. assert(0 && "Bad key type from load_openssh_pem_key");
  669. errmsg = "Bad key type from load_openssh_pem_key";
  670. goto error;
  671. }
  672. /*
  673. * The old key format doesn't include a comment in the private
  674. * key file.
  675. */
  676. retkey->comment = dupstr("imported-openssh-key");
  677. errmsg = NULL; /* no error */
  678. retval = retkey;
  679. error:
  680. strbuf_free(blob);
  681. strbuf_free(key->keyblob);
  682. smemclr(key, sizeof(*key));
  683. sfree(key);
  684. if (errmsg_p) *errmsg_p = errmsg;
  685. return retval;
  686. }
  687. static bool openssh_pem_write(
  688. const Filename *filename, struct ssh2_userkey *key, const char *passphrase)
  689. {
  690. strbuf *pubblob, *privblob, *outblob;
  691. unsigned char *spareblob;
  692. int sparelen = 0;
  693. ptrlen numbers[9];
  694. int nnumbers, i;
  695. const char *header, *footer;
  696. char zero[1];
  697. unsigned char iv[8];
  698. bool ret = false;
  699. FILE *fp;
  700. BinarySource src[1];
  701. /*
  702. * Fetch the key blobs.
  703. */
  704. pubblob = strbuf_new();
  705. ssh_key_public_blob(key->key, BinarySink_UPCAST(pubblob));
  706. privblob = strbuf_new();
  707. ssh_key_private_blob(key->key, BinarySink_UPCAST(privblob));
  708. spareblob = NULL;
  709. outblob = strbuf_new();
  710. /*
  711. * Encode the OpenSSH key blob, and also decide on the header
  712. * line.
  713. */
  714. if (ssh_key_alg(key->key) == &ssh_rsa ||
  715. ssh_key_alg(key->key) == &ssh_dss) {
  716. strbuf *seq;
  717. /*
  718. * The RSA and DSS handlers share some code because the two
  719. * key types have very similar ASN.1 representations, as a
  720. * plain SEQUENCE of big integers. So we set up a list of
  721. * bignums per key type and then construct the actual blob in
  722. * common code after that.
  723. */
  724. if (ssh_key_alg(key->key) == &ssh_rsa) {
  725. ptrlen n, e, d, p, q, iqmp, dmp1, dmq1;
  726. mp_int *bd, *bp, *bq, *bdmp1, *bdmq1;
  727. /*
  728. * These blobs were generated from inside PuTTY, so we needn't
  729. * treat them as untrusted.
  730. */
  731. BinarySource_BARE_INIT(src, pubblob->u, pubblob->len);
  732. get_string(src); /* skip algorithm name */
  733. e = get_string(src);
  734. n = get_string(src);
  735. BinarySource_BARE_INIT(src, privblob->u, privblob->len);
  736. d = get_string(src);
  737. p = get_string(src);
  738. q = get_string(src);
  739. iqmp = get_string(src);
  740. assert(!get_err(src)); /* can't go wrong */
  741. /* We also need d mod (p-1) and d mod (q-1). */
  742. bd = mp_from_bytes_be(d);
  743. bp = mp_from_bytes_be(p);
  744. bq = mp_from_bytes_be(q);
  745. mp_sub_integer_into(bp, bp, 1);
  746. mp_sub_integer_into(bq, bq, 1);
  747. bdmp1 = mp_mod(bd, bp);
  748. bdmq1 = mp_mod(bd, bq);
  749. mp_free(bd);
  750. mp_free(bp);
  751. mp_free(bq);
  752. dmp1.len = (mp_get_nbits(bdmp1)+8)/8;
  753. dmq1.len = (mp_get_nbits(bdmq1)+8)/8;
  754. sparelen = dmp1.len + dmq1.len;
  755. spareblob = snewn(sparelen, unsigned char);
  756. dmp1.ptr = spareblob;
  757. dmq1.ptr = spareblob + dmp1.len;
  758. for (i = 0; i < dmp1.len; i++)
  759. spareblob[i] = mp_get_byte(bdmp1, dmp1.len-1 - i);
  760. for (i = 0; i < dmq1.len; i++)
  761. spareblob[i+dmp1.len] = mp_get_byte(bdmq1, dmq1.len-1 - i);
  762. mp_free(bdmp1);
  763. mp_free(bdmq1);
  764. numbers[0] = make_ptrlen(zero, 1); zero[0] = '\0';
  765. numbers[1] = n;
  766. numbers[2] = e;
  767. numbers[3] = d;
  768. numbers[4] = p;
  769. numbers[5] = q;
  770. numbers[6] = dmp1;
  771. numbers[7] = dmq1;
  772. numbers[8] = iqmp;
  773. nnumbers = 9;
  774. header = "-----BEGIN RSA PRIVATE KEY-----\n";
  775. footer = "-----END RSA PRIVATE KEY-----\n";
  776. } else { /* ssh-dss */
  777. ptrlen p, q, g, y, x;
  778. /*
  779. * These blobs were generated from inside PuTTY, so we needn't
  780. * treat them as untrusted.
  781. */
  782. BinarySource_BARE_INIT(src, pubblob->u, pubblob->len);
  783. get_string(src); /* skip algorithm name */
  784. p = get_string(src);
  785. q = get_string(src);
  786. g = get_string(src);
  787. y = get_string(src);
  788. BinarySource_BARE_INIT(src, privblob->u, privblob->len);
  789. x = get_string(src);
  790. assert(!get_err(src)); /* can't go wrong */
  791. numbers[0].ptr = zero; numbers[0].len = 1; zero[0] = '\0';
  792. numbers[1] = p;
  793. numbers[2] = q;
  794. numbers[3] = g;
  795. numbers[4] = y;
  796. numbers[5] = x;
  797. nnumbers = 6;
  798. header = "-----BEGIN DSA PRIVATE KEY-----\n";
  799. footer = "-----END DSA PRIVATE KEY-----\n";
  800. }
  801. seq = strbuf_new();
  802. for (i = 0; i < nnumbers; i++) {
  803. put_ber_id_len(seq, 2, numbers[i].len, 0);
  804. put_data(seq, numbers[i].ptr, numbers[i].len);
  805. }
  806. put_ber_id_len(outblob, 16, seq->len, ASN1_CONSTRUCTED);
  807. put_data(outblob, seq->s, seq->len);
  808. strbuf_free(seq);
  809. } else if (ssh_key_alg(key->key) == &ssh_ecdsa_nistp256 ||
  810. ssh_key_alg(key->key) == &ssh_ecdsa_nistp384 ||
  811. ssh_key_alg(key->key) == &ssh_ecdsa_nistp521) {
  812. const unsigned char *oid;
  813. struct ecdsa_key *ec = container_of(key->key, struct ecdsa_key, sshk);
  814. int oidlen;
  815. int pointlen;
  816. strbuf *seq, *sub;
  817. /*
  818. * Structure of asn1:
  819. * SEQUENCE
  820. * INTEGER 1
  821. * OCTET STRING (private key)
  822. * [0]
  823. * OID (curve)
  824. * [1]
  825. * BIT STRING (0x00 public key point)
  826. */
  827. oid = ec_alg_oid(ssh_key_alg(key->key), &oidlen);
  828. pointlen = (ec->curve->fieldBits + 7) / 8 * 2;
  829. seq = strbuf_new();
  830. /* INTEGER 1 */
  831. put_ber_id_len(seq, 2, 1, 0);
  832. put_byte(seq, 1);
  833. /* OCTET STRING private key */
  834. put_ber_id_len(seq, 4, privblob->len - 4, 0);
  835. put_data(seq, privblob->s + 4, privblob->len - 4);
  836. /* Subsidiary OID */
  837. sub = strbuf_new();
  838. put_ber_id_len(sub, 6, oidlen, 0);
  839. put_data(sub, oid, oidlen);
  840. /* Append the OID to the sequence */
  841. put_ber_id_len(seq, 0, sub->len,
  842. ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
  843. put_data(seq, sub->s, sub->len);
  844. strbuf_free(sub);
  845. /* Subsidiary BIT STRING */
  846. sub = strbuf_new();
  847. put_ber_id_len(sub, 3, 2 + pointlen, 0);
  848. put_byte(sub, 0);
  849. put_data(sub, pubblob->s+39, 1 + pointlen);
  850. /* Append the BIT STRING to the sequence */
  851. put_ber_id_len(seq, 1, sub->len,
  852. ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
  853. put_data(seq, sub->s, sub->len);
  854. strbuf_free(sub);
  855. /* Write the full sequence with header to the output blob. */
  856. put_ber_id_len(outblob, 16, seq->len, ASN1_CONSTRUCTED);
  857. put_data(outblob, seq->s, seq->len);
  858. strbuf_free(seq);
  859. header = "-----BEGIN EC PRIVATE KEY-----\n";
  860. footer = "-----END EC PRIVATE KEY-----\n";
  861. } else {
  862. assert(0); /* zoinks! */
  863. exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
  864. }
  865. /*
  866. * Encrypt the key.
  867. *
  868. * For the moment, we still encrypt our OpenSSH keys using
  869. * old-style 3DES.
  870. */
  871. if (passphrase) {
  872. struct MD5Context md5c;
  873. unsigned char keybuf[32];
  874. int origlen, outlen, pad, i;
  875. /*
  876. * Padding on OpenSSH keys is deterministic. The number of
  877. * padding bytes is always more than zero, and always at most
  878. * the cipher block length. The value of each padding byte is
  879. * equal to the number of padding bytes. So a plaintext that's
  880. * an exact multiple of the block size will be padded with 08
  881. * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
  882. * plaintext one byte less than a multiple of the block size
  883. * will be padded with just 01.
  884. *
  885. * This enables the OpenSSL key decryption function to strip
  886. * off the padding algorithmically and return the unpadded
  887. * plaintext to the next layer: it looks at the final byte, and
  888. * then expects to find that many bytes at the end of the data
  889. * with the same value. Those are all removed and the rest is
  890. * returned.
  891. */
  892. origlen = outblob->len;
  893. outlen = (origlen + 8) &~ 7;
  894. pad = outlen - origlen;
  895. put_padding(outblob, pad, pad);
  896. /*
  897. * Invent an iv. Then derive encryption key from passphrase
  898. * and iv/salt:
  899. *
  900. * - let block A equal MD5(passphrase || iv)
  901. * - let block B equal MD5(A || passphrase || iv)
  902. * - block C would be MD5(B || passphrase || iv) and so on
  903. * - encryption key is the first N bytes of A || B
  904. */
  905. for (i = 0; i < 8; i++) iv[i] = random_byte();
  906. MD5Init(&md5c);
  907. put_data(&md5c, passphrase, strlen(passphrase));
  908. put_data(&md5c, iv, 8);
  909. MD5Final(keybuf, &md5c);
  910. MD5Init(&md5c);
  911. put_data(&md5c, keybuf, 16);
  912. put_data(&md5c, passphrase, strlen(passphrase));
  913. put_data(&md5c, iv, 8);
  914. MD5Final(keybuf+16, &md5c);
  915. /*
  916. * Now encrypt the key blob.
  917. */
  918. des3_encrypt_pubkey_ossh(keybuf, iv,
  919. outblob->u, outlen);
  920. smemclr(&md5c, sizeof(md5c));
  921. smemclr(keybuf, sizeof(keybuf));
  922. }
  923. /*
  924. * And save it. We'll use Unix line endings just in case it's
  925. * subsequently transferred in binary mode.
  926. */
  927. fp = f_open(filename, "wb", true); /* ensure Unix line endings */
  928. if (!fp)
  929. goto error;
  930. fputs(header, fp);
  931. if (passphrase) {
  932. fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
  933. for (i = 0; i < 8; i++)
  934. fprintf(fp, "%02X", iv[i]);
  935. fprintf(fp, "\n\n");
  936. }
  937. base64_encode(fp, outblob->u, outblob->len, 64);
  938. fputs(footer, fp);
  939. fclose(fp);
  940. ret = true;
  941. error:
  942. if (outblob)
  943. strbuf_free(outblob);
  944. if (spareblob) {
  945. smemclr(spareblob, sparelen);
  946. sfree(spareblob);
  947. }
  948. if (privblob)
  949. strbuf_free(privblob);
  950. if (pubblob)
  951. strbuf_free(pubblob);
  952. return ret;
  953. }
  954. /* ----------------------------------------------------------------------
  955. * Code to read and write OpenSSH private keys in the new-style format.
  956. */
  957. typedef enum {
  958. ON_E_NONE, ON_E_AES256CBC, ON_E_AES256CTR
  959. } openssh_new_cipher;
  960. typedef enum {
  961. ON_K_NONE, ON_K_BCRYPT
  962. } openssh_new_kdf;
  963. struct openssh_new_key {
  964. openssh_new_cipher cipher;
  965. openssh_new_kdf kdf;
  966. union {
  967. struct {
  968. int rounds;
  969. /* This points to a position within keyblob, not a
  970. * separately allocated thing */
  971. ptrlen salt;
  972. } bcrypt;
  973. } kdfopts;
  974. int nkeys, key_wanted;
  975. /* This too points to a position within keyblob */
  976. ptrlen private;
  977. unsigned char *keyblob;
  978. int keyblob_len, keyblob_size;
  979. };
  980. static struct openssh_new_key *load_openssh_new_key(const Filename *filename,
  981. const char **errmsg_p)
  982. {
  983. struct openssh_new_key *ret;
  984. FILE *fp = NULL;
  985. char *line = NULL;
  986. const char *errmsg;
  987. char *p;
  988. char base64_bit[4];
  989. int base64_chars = 0;
  990. BinarySource src[1];
  991. ptrlen str;
  992. unsigned key_index;
  993. ret = snew(struct openssh_new_key);
  994. ret->keyblob = NULL;
  995. ret->keyblob_len = ret->keyblob_size = 0;
  996. fp = f_open(filename, "r", false);
  997. if (!fp) {
  998. errmsg = "unable to open key file";
  999. goto error;
  1000. }
  1001. if (!(line = fgetline(fp))) {
  1002. errmsg = "unexpected end of file";
  1003. goto error;
  1004. }
  1005. strip_crlf(line);
  1006. if (0 != strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
  1007. errmsg = "file does not begin with OpenSSH new-style key header";
  1008. goto error;
  1009. }
  1010. smemclr(line, strlen(line));
  1011. sfree(line);
  1012. line = NULL;
  1013. while (1) {
  1014. if (!(line = fgetline(fp))) {
  1015. errmsg = "unexpected end of file";
  1016. goto error;
  1017. }
  1018. strip_crlf(line);
  1019. if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) {
  1020. sfree(line);
  1021. line = NULL;
  1022. break; /* done */
  1023. }
  1024. p = line;
  1025. while (isbase64(*p)) {
  1026. base64_bit[base64_chars++] = *p;
  1027. if (base64_chars == 4) {
  1028. unsigned char out[3];
  1029. int len;
  1030. base64_chars = 0;
  1031. len = base64_decode_atom(base64_bit, out);
  1032. if (len <= 0) {
  1033. errmsg = "invalid base64 encoding";
  1034. goto error;
  1035. }
  1036. if (ret->keyblob_len + len > ret->keyblob_size) {
  1037. ret->keyblob_size = ret->keyblob_len + len + 256;
  1038. ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
  1039. unsigned char);
  1040. }
  1041. memcpy(ret->keyblob + ret->keyblob_len, out, len);
  1042. ret->keyblob_len += len;
  1043. smemclr(out, sizeof(out));
  1044. }
  1045. p++;
  1046. }
  1047. smemclr(line, strlen(line));
  1048. sfree(line);
  1049. line = NULL;
  1050. }
  1051. fclose(fp);
  1052. fp = NULL;
  1053. if (ret->keyblob_len == 0 || !ret->keyblob) {
  1054. errmsg = "key body not present";
  1055. goto error;
  1056. }
  1057. BinarySource_BARE_INIT(src, ret->keyblob, ret->keyblob_len);
  1058. if (strcmp(get_asciz(src), "openssh-key-v1") != 0) {
  1059. errmsg = "new-style OpenSSH magic number missing\n";
  1060. goto error;
  1061. }
  1062. /* Cipher name */
  1063. str = get_string(src);
  1064. if (ptrlen_eq_string(str, "none")) {
  1065. ret->cipher = ON_E_NONE;
  1066. } else if (ptrlen_eq_string(str, "aes256-cbc")) {
  1067. ret->cipher = ON_E_AES256CBC;
  1068. } else if (ptrlen_eq_string(str, "aes256-ctr")) {
  1069. ret->cipher = ON_E_AES256CTR;
  1070. } else {
  1071. errmsg = get_err(src) ? "no cipher name found" :
  1072. "unrecognised cipher name\n";
  1073. goto error;
  1074. }
  1075. /* Key derivation function name */
  1076. str = get_string(src);
  1077. if (ptrlen_eq_string(str, "none")) {
  1078. ret->kdf = ON_K_NONE;
  1079. } else if (ptrlen_eq_string(str, "bcrypt")) {
  1080. ret->kdf = ON_K_BCRYPT;
  1081. } else {
  1082. errmsg = get_err(src) ? "no kdf name found" :
  1083. "unrecognised kdf name\n";
  1084. goto error;
  1085. }
  1086. /* KDF extra options */
  1087. str = get_string(src);
  1088. switch (ret->kdf) {
  1089. case ON_K_NONE:
  1090. if (str.len != 0) {
  1091. errmsg = "expected empty options string for 'none' kdf";
  1092. goto error;
  1093. }
  1094. break;
  1095. case ON_K_BCRYPT:
  1096. {
  1097. BinarySource opts[1];
  1098. BinarySource_BARE_INIT(opts, str.ptr, str.len);
  1099. ret->kdfopts.bcrypt.salt = get_string(opts);
  1100. ret->kdfopts.bcrypt.rounds = get_uint32(opts);
  1101. if (get_err(opts)) {
  1102. errmsg = "failed to parse bcrypt options string";
  1103. goto error;
  1104. }
  1105. }
  1106. break;
  1107. }
  1108. /*
  1109. * At this point we expect a uint32 saying how many keys are
  1110. * stored in this file. OpenSSH new-style key files can
  1111. * contain more than one. Currently we don't have any user
  1112. * interface to specify which one we're trying to extract, so
  1113. * we just bomb out with an error if more than one is found in
  1114. * the file. However, I've put in all the mechanism here to
  1115. * extract the nth one for a given n, in case we later connect
  1116. * up some UI to that mechanism. Just arrange that the
  1117. * 'key_wanted' field is set to a value in the range [0,
  1118. * nkeys) by some mechanism.
  1119. */
  1120. ret->nkeys = toint(get_uint32(src));
  1121. if (ret->nkeys != 1) {
  1122. errmsg = get_err(src) ? "no key count found" :
  1123. "multiple keys in new-style OpenSSH key file not supported\n";
  1124. goto error;
  1125. }
  1126. ret->key_wanted = 0;
  1127. /* Read and ignore a string per public key. */
  1128. for (key_index = 0; key_index < ret->nkeys; key_index++)
  1129. str = get_string(src);
  1130. /*
  1131. * Now we expect a string containing the encrypted part of the
  1132. * key file.
  1133. */
  1134. ret->private = get_string(src);
  1135. if (get_err(src)) {
  1136. errmsg = "no private key container string found\n";
  1137. goto error;
  1138. }
  1139. /*
  1140. * And now we're done, until asked to actually decrypt.
  1141. */
  1142. smemclr(base64_bit, sizeof(base64_bit));
  1143. if (errmsg_p) *errmsg_p = NULL;
  1144. return ret;
  1145. error:
  1146. if (line) {
  1147. smemclr(line, strlen(line));
  1148. sfree(line);
  1149. line = NULL;
  1150. }
  1151. smemclr(base64_bit, sizeof(base64_bit));
  1152. if (ret) {
  1153. if (ret->keyblob) {
  1154. smemclr(ret->keyblob, ret->keyblob_size);
  1155. sfree(ret->keyblob);
  1156. }
  1157. smemclr(ret, sizeof(*ret));
  1158. sfree(ret);
  1159. }
  1160. if (errmsg_p) *errmsg_p = errmsg;
  1161. if (fp) fclose(fp);
  1162. return NULL;
  1163. }
  1164. static bool openssh_new_encrypted(const Filename *filename)
  1165. {
  1166. struct openssh_new_key *key = load_openssh_new_key(filename, NULL);
  1167. bool ret;
  1168. if (!key)
  1169. return false;
  1170. ret = (key->cipher != ON_E_NONE);
  1171. smemclr(key->keyblob, key->keyblob_size);
  1172. sfree(key->keyblob);
  1173. smemclr(key, sizeof(*key));
  1174. sfree(key);
  1175. return ret;
  1176. }
  1177. static struct ssh2_userkey *openssh_new_read(
  1178. const Filename *filename, const char *passphrase, const char **errmsg_p)
  1179. {
  1180. struct openssh_new_key *key = load_openssh_new_key(filename, errmsg_p);
  1181. struct ssh2_userkey *retkey = NULL;
  1182. struct ssh2_userkey *retval = NULL;
  1183. const char *errmsg;
  1184. unsigned checkint;
  1185. BinarySource src[1];
  1186. int key_index;
  1187. const ssh_keyalg *alg = NULL;
  1188. if (!key)
  1189. return NULL;
  1190. if (key->cipher != ON_E_NONE) {
  1191. unsigned char keybuf[48];
  1192. int keysize;
  1193. /*
  1194. * Construct the decryption key, and decrypt the string.
  1195. */
  1196. switch (key->cipher) {
  1197. case ON_E_NONE:
  1198. keysize = 0;
  1199. break;
  1200. case ON_E_AES256CBC:
  1201. case ON_E_AES256CTR:
  1202. keysize = 48; /* 32 byte key + 16 byte IV */
  1203. break;
  1204. default:
  1205. assert(0 && "Bad cipher enumeration value");
  1206. }
  1207. assert(keysize <= sizeof(keybuf));
  1208. switch (key->kdf) {
  1209. case ON_K_NONE:
  1210. memset(keybuf, 0, keysize);
  1211. break;
  1212. case ON_K_BCRYPT:
  1213. openssh_bcrypt(passphrase,
  1214. key->kdfopts.bcrypt.salt.ptr,
  1215. key->kdfopts.bcrypt.salt.len,
  1216. key->kdfopts.bcrypt.rounds,
  1217. keybuf, keysize);
  1218. break;
  1219. default:
  1220. assert(0 && "Bad kdf enumeration value");
  1221. }
  1222. switch (key->cipher) {
  1223. case ON_E_NONE:
  1224. break;
  1225. case ON_E_AES256CBC:
  1226. case ON_E_AES256CTR:
  1227. if (key->private.len % 16 != 0) {
  1228. errmsg = "private key container length is not a"
  1229. " multiple of AES block size\n";
  1230. goto error;
  1231. }
  1232. {
  1233. void *ctx = aes_make_context();
  1234. aes256_key(ctx, keybuf);
  1235. aes_iv(ctx, keybuf + 32);
  1236. /* Decrypt the private section in place, casting away
  1237. * the const from key->private being a ptrlen */
  1238. if (key->cipher == ON_E_AES256CBC) {
  1239. aes_ssh2_decrypt_blk(ctx, (char *)key->private.ptr,
  1240. key->private.len);
  1241. }
  1242. else {
  1243. aes_ssh2_sdctr(ctx, (char *)key->private.ptr,
  1244. key->private.len);
  1245. }
  1246. aes_free_context(ctx);
  1247. }
  1248. break;
  1249. default:
  1250. assert(0 && "Bad cipher enumeration value");
  1251. }
  1252. }
  1253. /*
  1254. * Now parse the entire encrypted section, and extract the key
  1255. * identified by key_wanted.
  1256. */
  1257. BinarySource_BARE_INIT(src, key->private.ptr, key->private.len);
  1258. checkint = get_uint32(src);
  1259. if (get_uint32(src) != checkint || get_err(src)) {
  1260. errmsg = "decryption check failed";
  1261. goto error;
  1262. }
  1263. retkey = snew(struct ssh2_userkey);
  1264. retkey->key = NULL;
  1265. retkey->comment = NULL;
  1266. for (key_index = 0; key_index < key->nkeys; key_index++) {
  1267. ptrlen comment;
  1268. /*
  1269. * Identify the key type.
  1270. */
  1271. alg = find_pubkey_alg_len(get_string(src));
  1272. if (!alg) {
  1273. errmsg = "private key type not recognised\n";
  1274. goto error;
  1275. }
  1276. /*
  1277. * Read the key. We have to do this even if it's not the one
  1278. * we want, because it's the only way to find out how much
  1279. * data to skip past to get to the next key in the file.
  1280. */
  1281. retkey->key = ssh_key_new_priv_openssh(alg, src);
  1282. if (get_err(src)) {
  1283. errmsg = "unable to read entire private key";
  1284. goto error;
  1285. }
  1286. if (!retkey->key) {
  1287. errmsg = "unable to create key data structure";
  1288. goto error;
  1289. }
  1290. if (key_index != key->key_wanted) {
  1291. /*
  1292. * If this isn't the key we're looking for, throw it away.
  1293. */
  1294. ssh_key_free(retkey->key);
  1295. retkey->key = NULL;
  1296. }
  1297. /*
  1298. * Read the key comment.
  1299. */
  1300. comment = get_string(src);
  1301. if (get_err(src)) {
  1302. errmsg = "unable to read key comment";
  1303. goto error;
  1304. }
  1305. if (key_index == key->key_wanted) {
  1306. assert(retkey);
  1307. retkey->comment = mkstr(comment);
  1308. }
  1309. }
  1310. if (!retkey) {
  1311. errmsg = "key index out of range";
  1312. goto error;
  1313. }
  1314. /*
  1315. * Now we expect nothing left but padding.
  1316. */
  1317. {
  1318. unsigned char expected_pad_byte = 1;
  1319. while (get_avail(src) > 0)
  1320. if (get_byte(src) != expected_pad_byte++) {
  1321. errmsg = "padding at end of private string did not match";
  1322. goto error;
  1323. }
  1324. }
  1325. errmsg = NULL; /* no error */
  1326. retval = retkey;
  1327. retkey = NULL; /* prevent the free */
  1328. error:
  1329. if (retkey) {
  1330. sfree(retkey->comment);
  1331. if (retkey->key)
  1332. ssh_key_free(retkey->key);
  1333. sfree(retkey);
  1334. }
  1335. smemclr(key->keyblob, key->keyblob_size);
  1336. sfree(key->keyblob);
  1337. smemclr(key, sizeof(*key));
  1338. sfree(key);
  1339. if (errmsg_p) *errmsg_p = errmsg;
  1340. return retval;
  1341. }
  1342. static bool openssh_new_write(
  1343. const Filename *filename, struct ssh2_userkey *key, const char *passphrase)
  1344. {
  1345. strbuf *pubblob, *privblob, *cblob;
  1346. int padvalue, i;
  1347. unsigned checkint;
  1348. bool ret = false;
  1349. unsigned char bcrypt_salt[16];
  1350. const int bcrypt_rounds = 16;
  1351. FILE *fp;
  1352. /*
  1353. * Fetch the key blobs and find out the lengths of things.
  1354. */
  1355. pubblob = strbuf_new();
  1356. ssh_key_public_blob(key->key, BinarySink_UPCAST(pubblob));
  1357. privblob = strbuf_new();
  1358. ssh_key_openssh_blob(key->key, BinarySink_UPCAST(privblob));
  1359. /*
  1360. * Construct the cleartext version of the blob.
  1361. */
  1362. cblob = strbuf_new();
  1363. /* Magic number. */
  1364. put_asciz(cblob, "openssh-key-v1");
  1365. /* Cipher and kdf names, and kdf options. */
  1366. if (!passphrase) {
  1367. memset(bcrypt_salt, 0, sizeof(bcrypt_salt)); /* prevent warnings */
  1368. put_stringz(cblob, "none");
  1369. put_stringz(cblob, "none");
  1370. put_stringz(cblob, "");
  1371. } else {
  1372. strbuf *substr;
  1373. for (i = 0; i < (int)sizeof(bcrypt_salt); i++)
  1374. bcrypt_salt[i] = random_byte();
  1375. put_stringz(cblob, "aes256-ctr");
  1376. put_stringz(cblob, "bcrypt");
  1377. substr = strbuf_new();
  1378. put_string(substr, bcrypt_salt, sizeof(bcrypt_salt));
  1379. put_uint32(substr, bcrypt_rounds);
  1380. put_stringsb(cblob, substr);
  1381. }
  1382. /* Number of keys. */
  1383. put_uint32(cblob, 1);
  1384. /* Public blob. */
  1385. put_string(cblob, pubblob->s, pubblob->len);
  1386. /* Private section. */
  1387. {
  1388. strbuf *cpblob = strbuf_new();
  1389. /* checkint. */
  1390. checkint = 0;
  1391. for (i = 0; i < 4; i++)
  1392. checkint = (checkint << 8) + random_byte();
  1393. put_uint32(cpblob, checkint);
  1394. put_uint32(cpblob, checkint);
  1395. /* Private key. The main private blob goes inline, with no string
  1396. * wrapper. */
  1397. put_stringz(cpblob, ssh_key_ssh_id(key->key));
  1398. put_data(cpblob, privblob->s, privblob->len);
  1399. /* Comment. */
  1400. put_stringz(cpblob, key->comment);
  1401. /* Pad out the encrypted section. */
  1402. padvalue = 1;
  1403. do {
  1404. put_byte(cpblob, padvalue++);
  1405. } while (cpblob->len & 15);
  1406. if (passphrase) {
  1407. /*
  1408. * Encrypt the private section. We need 48 bytes of key
  1409. * material: 32 bytes AES key + 16 bytes iv.
  1410. */
  1411. unsigned char keybuf[48];
  1412. void *ctx;
  1413. openssh_bcrypt(passphrase,
  1414. bcrypt_salt, sizeof(bcrypt_salt), bcrypt_rounds,
  1415. keybuf, sizeof(keybuf));
  1416. ctx = aes_make_context();
  1417. aes256_key(ctx, keybuf);
  1418. aes_iv(ctx, keybuf + 32);
  1419. aes_ssh2_sdctr(ctx, cpblob->u,
  1420. cpblob->len);
  1421. aes_free_context(ctx);
  1422. smemclr(keybuf, sizeof(keybuf));
  1423. }
  1424. put_stringsb(cblob, cpblob);
  1425. }
  1426. /*
  1427. * And save it. We'll use Unix line endings just in case it's
  1428. * subsequently transferred in binary mode.
  1429. */
  1430. fp = f_open(filename, "wb", true); /* ensure Unix line endings */
  1431. if (!fp)
  1432. goto error;
  1433. fputs("-----BEGIN OPENSSH PRIVATE KEY-----\n", fp);
  1434. base64_encode(fp, cblob->u, cblob->len, 64);
  1435. fputs("-----END OPENSSH PRIVATE KEY-----\n", fp);
  1436. fclose(fp);
  1437. ret = true;
  1438. error:
  1439. if (cblob)
  1440. strbuf_free(cblob);
  1441. if (privblob)
  1442. strbuf_free(privblob);
  1443. if (pubblob)
  1444. strbuf_free(pubblob);
  1445. return ret;
  1446. }
  1447. /* ----------------------------------------------------------------------
  1448. * The switch function openssh_auto_write(), which chooses one of the
  1449. * concrete OpenSSH output formats based on the key type.
  1450. */
  1451. static bool openssh_auto_write(
  1452. const Filename *filename, struct ssh2_userkey *key, const char *passphrase)
  1453. {
  1454. /*
  1455. * The old OpenSSH format supports a fixed list of key types. We
  1456. * assume that anything not in that fixed list is newer, and hence
  1457. * will use the new format.
  1458. */
  1459. if (ssh_key_alg(key->key) == &ssh_dss ||
  1460. ssh_key_alg(key->key) == &ssh_rsa ||
  1461. ssh_key_alg(key->key) == &ssh_ecdsa_nistp256 ||
  1462. ssh_key_alg(key->key) == &ssh_ecdsa_nistp384 ||
  1463. ssh_key_alg(key->key) == &ssh_ecdsa_nistp521)
  1464. return openssh_pem_write(filename, key, passphrase);
  1465. else
  1466. return openssh_new_write(filename, key, passphrase);
  1467. }
  1468. /* ----------------------------------------------------------------------
  1469. * Code to read ssh.com private keys.
  1470. */
  1471. /*
  1472. * The format of the base64 blob is largely SSH-2-packet-formatted,
  1473. * except that mpints are a bit different: they're more like the
  1474. * old SSH-1 mpint. You have a 32-bit bit count N, followed by
  1475. * (N+7)/8 bytes of data.
  1476. *
  1477. * So. The blob contains:
  1478. *
  1479. * - uint32 0x3f6ff9eb (magic number)
  1480. * - uint32 size (total blob size)
  1481. * - string key-type (see below)
  1482. * - string cipher-type (tells you if key is encrypted)
  1483. * - string encrypted-blob
  1484. *
  1485. * (The first size field includes the size field itself and the
  1486. * magic number before it. All other size fields are ordinary SSH-2
  1487. * strings, so the size field indicates how much data is to
  1488. * _follow_.)
  1489. *
  1490. * The encrypted blob, once decrypted, contains a single string
  1491. * which in turn contains the payload. (This allows padding to be
  1492. * added after that string while still making it clear where the
  1493. * real payload ends. Also it probably makes for a reasonable
  1494. * decryption check.)
  1495. *
  1496. * The payload blob, for an RSA key, contains:
  1497. * - mpint e
  1498. * - mpint d
  1499. * - mpint n (yes, the public and private stuff is intermixed)
  1500. * - mpint u (presumably inverse of p mod q)
  1501. * - mpint p (p is the smaller prime)
  1502. * - mpint q (q is the larger)
  1503. *
  1504. * For a DSA key, the payload blob contains:
  1505. * - uint32 0
  1506. * - mpint p
  1507. * - mpint g
  1508. * - mpint q
  1509. * - mpint y
  1510. * - mpint x
  1511. *
  1512. * Alternatively, if the parameters are `predefined', that
  1513. * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
  1514. * containing some predefined parameter specification. *shudder*,
  1515. * but I doubt we'll encounter this in real life.
  1516. *
  1517. * The key type strings are ghastly. The RSA key I looked at had a
  1518. * type string of
  1519. *
  1520. * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
  1521. *
  1522. * and the DSA key wasn't much better:
  1523. *
  1524. * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
  1525. *
  1526. * It isn't clear that these will always be the same. I think it
  1527. * might be wise just to look at the `if-modn{sign{rsa' and
  1528. * `dl-modp{sign{dsa' prefixes.
  1529. *
  1530. * Finally, the encryption. The cipher-type string appears to be
  1531. * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
  1532. * 3des-cbc (i.e. outer cbc rather than inner). The key is created
  1533. * from the passphrase by means of yet another hashing faff:
  1534. *
  1535. * - first 16 bytes are MD5(passphrase)
  1536. * - next 16 bytes are MD5(passphrase || first 16 bytes)
  1537. * - if there were more, they'd be MD5(passphrase || first 32),
  1538. * and so on.
  1539. */
  1540. #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
  1541. struct sshcom_key {
  1542. char comment[256]; /* allowing any length is overkill */
  1543. unsigned char *keyblob;
  1544. int keyblob_len, keyblob_size;
  1545. };
  1546. static struct sshcom_key *load_sshcom_key(const Filename *filename,
  1547. const char **errmsg_p)
  1548. {
  1549. struct sshcom_key *ret;
  1550. FILE *fp;
  1551. char *line = NULL;
  1552. int hdrstart, len;
  1553. const char *errmsg;
  1554. char *p;
  1555. bool headers_done;
  1556. char base64_bit[4];
  1557. int base64_chars = 0;
  1558. ret = snew(struct sshcom_key);
  1559. ret->comment[0] = '\0';
  1560. ret->keyblob = NULL;
  1561. ret->keyblob_len = ret->keyblob_size = 0;
  1562. fp = f_open(filename, "r", false);
  1563. if (!fp) {
  1564. errmsg = "unable to open key file";
  1565. goto error;
  1566. }
  1567. if (!(line = fgetline(fp))) {
  1568. errmsg = "unexpected end of file";
  1569. goto error;
  1570. }
  1571. strip_crlf(line);
  1572. if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
  1573. errmsg = "file does not begin with ssh.com key header";
  1574. goto error;
  1575. }
  1576. smemclr(line, strlen(line));
  1577. sfree(line);
  1578. line = NULL;
  1579. headers_done = false;
  1580. while (1) {
  1581. if (!(line = fgetline(fp))) {
  1582. errmsg = "unexpected end of file";
  1583. goto error;
  1584. }
  1585. strip_crlf(line);
  1586. if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
  1587. sfree(line);
  1588. line = NULL;
  1589. break; /* done */
  1590. }
  1591. if ((p = strchr(line, ':')) != NULL) {
  1592. if (headers_done) {
  1593. errmsg = "header found in body of key data";
  1594. goto error;
  1595. }
  1596. *p++ = '\0';
  1597. while (*p && isspace((unsigned char)*p)) p++;
  1598. hdrstart = p - line;
  1599. /*
  1600. * Header lines can end in a trailing backslash for
  1601. * continuation.
  1602. */
  1603. len = hdrstart + strlen(line+hdrstart);
  1604. assert(!line[len]);
  1605. while (line[len-1] == '\\') {
  1606. char *line2;
  1607. int line2len;
  1608. line2 = fgetline(fp);
  1609. if (!line2) {
  1610. errmsg = "unexpected end of file";
  1611. goto error;
  1612. }
  1613. strip_crlf(line2);
  1614. line2len = strlen(line2);
  1615. line = sresize(line, len + line2len + 1, char);
  1616. strcpy(line + len - 1, line2);
  1617. len += line2len - 1;
  1618. assert(!line[len]);
  1619. smemclr(line2, strlen(line2));
  1620. sfree(line2);
  1621. line2 = NULL;
  1622. }
  1623. p = line + hdrstart;
  1624. strip_crlf(p);
  1625. if (!strcmp(line, "Comment")) {
  1626. /* Strip quotes in comment if present. */
  1627. if (p[0] == '"' && p[strlen(p)-1] == '"') {
  1628. p++;
  1629. p[strlen(p)-1] = '\0';
  1630. }
  1631. strncpy(ret->comment, p, sizeof(ret->comment));
  1632. ret->comment[sizeof(ret->comment)-1] = '\0';
  1633. }
  1634. } else {
  1635. headers_done = true;
  1636. p = line;
  1637. while (isbase64(*p)) {
  1638. base64_bit[base64_chars++] = *p;
  1639. if (base64_chars == 4) {
  1640. unsigned char out[3];
  1641. base64_chars = 0;
  1642. len = base64_decode_atom(base64_bit, out);
  1643. if (len <= 0) {
  1644. errmsg = "invalid base64 encoding";
  1645. goto error;
  1646. }
  1647. if (ret->keyblob_len + len > ret->keyblob_size) {
  1648. ret->keyblob_size = ret->keyblob_len + len + 256;
  1649. ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
  1650. unsigned char);
  1651. }
  1652. memcpy(ret->keyblob + ret->keyblob_len, out, len);
  1653. ret->keyblob_len += len;
  1654. }
  1655. p++;
  1656. }
  1657. }
  1658. smemclr(line, strlen(line));
  1659. sfree(line);
  1660. line = NULL;
  1661. }
  1662. if (ret->keyblob_len == 0 || !ret->keyblob) {
  1663. errmsg = "key body not present";
  1664. goto error;
  1665. }
  1666. fclose(fp);
  1667. if (errmsg_p) *errmsg_p = NULL;
  1668. return ret;
  1669. error:
  1670. if (fp)
  1671. fclose(fp);
  1672. if (line) {
  1673. smemclr(line, strlen(line));
  1674. sfree(line);
  1675. line = NULL;
  1676. }
  1677. if (ret) {
  1678. if (ret->keyblob) {
  1679. smemclr(ret->keyblob, ret->keyblob_size);
  1680. sfree(ret->keyblob);
  1681. }
  1682. smemclr(ret, sizeof(*ret));
  1683. sfree(ret);
  1684. }
  1685. if (errmsg_p) *errmsg_p = errmsg;
  1686. return NULL;
  1687. }
  1688. static bool sshcom_encrypted(const Filename *filename, char **comment)
  1689. {
  1690. struct sshcom_key *key = load_sshcom_key(filename, NULL);
  1691. BinarySource src[1];
  1692. ptrlen str;
  1693. bool answer = false;
  1694. *comment = NULL;
  1695. if (!key)
  1696. goto done;
  1697. BinarySource_BARE_INIT(src, key->keyblob, key->keyblob_len);
  1698. if (get_uint32(src) != SSHCOM_MAGIC_NUMBER)
  1699. goto done; /* key is invalid */
  1700. get_uint32(src); /* skip length field */
  1701. get_string(src); /* skip key type */
  1702. str = get_string(src); /* cipher type */
  1703. if (get_err(src))
  1704. goto done; /* key is invalid */
  1705. if (!ptrlen_eq_string(str, "none"))
  1706. answer = true;
  1707. done:
  1708. if (key) {
  1709. *comment = dupstr(key->comment);
  1710. smemclr(key->keyblob, key->keyblob_size);
  1711. sfree(key->keyblob);
  1712. smemclr(key, sizeof(*key));
  1713. sfree(key);
  1714. } else {
  1715. *comment = dupstr("");
  1716. }
  1717. return answer;
  1718. }
  1719. void BinarySink_put_mp_sshcom_from_string(
  1720. BinarySink *bs, const void *bytesv, int nbytes)
  1721. {
  1722. const unsigned char *bytes = (const unsigned char *)bytesv;
  1723. int bits = nbytes * 8 - 1;
  1724. while (bits > 0) {
  1725. if (*bytes & (1 << (bits & 7)))
  1726. break;
  1727. if (!(bits-- & 7))
  1728. bytes++, nbytes--;
  1729. }
  1730. put_uint32(bs, bits+1);
  1731. put_data(bs, bytes, nbytes);
  1732. }
  1733. #define put_mp_sshcom_from_string(bs, val, len) \
  1734. BinarySink_put_mp_sshcom_from_string(BinarySink_UPCAST(bs), val, len)
  1735. static ptrlen BinarySource_get_mp_sshcom_as_string(BinarySource *src)
  1736. {
  1737. unsigned bits = get_uint32(src);
  1738. return get_data(src, (bits + 7) / 8);
  1739. }
  1740. #define get_mp_sshcom_as_string(bs) \
  1741. BinarySource_get_mp_sshcom_as_string(BinarySource_UPCAST(bs))
  1742. static struct ssh2_userkey *sshcom_read(
  1743. const Filename *filename, const char *passphrase, const char **errmsg_p)
  1744. {
  1745. struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
  1746. const char *errmsg;
  1747. BinarySource src[1];
  1748. ptrlen str, ciphertext;
  1749. int publen;
  1750. const char prefix_rsa[] = "if-modn{sign{rsa";
  1751. const char prefix_dsa[] = "dl-modp{sign{dsa";
  1752. enum { RSA, DSA } type;
  1753. bool encrypted;
  1754. struct ssh2_userkey *ret = NULL, *retkey;
  1755. const ssh_keyalg *alg;
  1756. strbuf *blob = NULL;
  1757. if (!key)
  1758. return NULL;
  1759. BinarySource_BARE_INIT(src, key->keyblob, key->keyblob_len);
  1760. if (get_uint32(src) != SSHCOM_MAGIC_NUMBER) {
  1761. errmsg = "key does not begin with magic number";
  1762. goto error;
  1763. }
  1764. get_uint32(src); /* skip length field */
  1765. /*
  1766. * Determine the key type.
  1767. */
  1768. str = get_string(src);
  1769. if (str.len > sizeof(prefix_rsa) - 1 &&
  1770. !memcmp(str.ptr, prefix_rsa, sizeof(prefix_rsa) - 1)) {
  1771. type = RSA;
  1772. } else if (str.len > sizeof(prefix_dsa) - 1 &&
  1773. !memcmp(str.ptr, prefix_dsa, sizeof(prefix_dsa) - 1)) {
  1774. type = DSA;
  1775. } else {
  1776. errmsg = "key is of unknown type";
  1777. goto error;
  1778. }
  1779. /*
  1780. * Determine the cipher type.
  1781. */
  1782. str = get_string(src);
  1783. if (ptrlen_eq_string(str, "none"))
  1784. encrypted = false;
  1785. else if (ptrlen_eq_string(str, "3des-cbc"))
  1786. encrypted = true;
  1787. else {
  1788. errmsg = "key encryption is of unknown type";
  1789. goto error;
  1790. }
  1791. /*
  1792. * Get hold of the encrypted part of the key.
  1793. */
  1794. ciphertext = get_string(src);
  1795. if (ciphertext.len == 0) {
  1796. errmsg = "no key data found";
  1797. goto error;
  1798. }
  1799. /*
  1800. * Decrypt it if necessary.
  1801. */
  1802. if (encrypted) {
  1803. /*
  1804. * Derive encryption key from passphrase and iv/salt:
  1805. *
  1806. * - let block A equal MD5(passphrase)
  1807. * - let block B equal MD5(passphrase || A)
  1808. * - block C would be MD5(passphrase || A || B) and so on
  1809. * - encryption key is the first N bytes of A || B
  1810. */
  1811. struct MD5Context md5c;
  1812. unsigned char keybuf[32], iv[8];
  1813. if (ciphertext.len % 8 != 0) {
  1814. errmsg = "encrypted part of key is not a multiple of cipher block"
  1815. " size";
  1816. goto error;
  1817. }
  1818. MD5Init(&md5c);
  1819. put_data(&md5c, passphrase, strlen(passphrase));
  1820. MD5Final(keybuf, &md5c);
  1821. MD5Init(&md5c);
  1822. put_data(&md5c, passphrase, strlen(passphrase));
  1823. put_data(&md5c, keybuf, 16);
  1824. MD5Final(keybuf+16, &md5c);
  1825. /*
  1826. * Now decrypt the key blob in place (casting away const from
  1827. * ciphertext being a ptrlen).
  1828. */
  1829. memset(iv, 0, sizeof(iv));
  1830. des3_decrypt_pubkey_ossh(keybuf, iv,
  1831. (char *)ciphertext.ptr, ciphertext.len);
  1832. smemclr(&md5c, sizeof(md5c));
  1833. smemclr(keybuf, sizeof(keybuf));
  1834. /*
  1835. * Hereafter we return WRONG_PASSPHRASE for any parsing
  1836. * error. (But only if we've just tried to decrypt it!
  1837. * Returning WRONG_PASSPHRASE for an unencrypted key is
  1838. * automatic doom.)
  1839. */
  1840. if (encrypted)
  1841. ret = SSH2_WRONG_PASSPHRASE;
  1842. }
  1843. /*
  1844. * Expect the ciphertext to be formatted as a containing string,
  1845. * and reinitialise src to start parsing the inside of that string.
  1846. */
  1847. BinarySource_BARE_INIT(src, ciphertext.ptr, ciphertext.len);
  1848. str = get_string(src);
  1849. if (get_err(src)) {
  1850. errmsg = "containing string was ill-formed";
  1851. goto error;
  1852. }
  1853. BinarySource_BARE_INIT(src, str.ptr, str.len);
  1854. /*
  1855. * Now we break down into RSA versus DSA. In either case we'll
  1856. * construct public and private blobs in our own format, and
  1857. * end up feeding them to ssh_key_new_priv().
  1858. */
  1859. blob = strbuf_new();
  1860. if (type == RSA) {
  1861. ptrlen n, e, d, u, p, q;
  1862. e = get_mp_sshcom_as_string(src);
  1863. d = get_mp_sshcom_as_string(src);
  1864. n = get_mp_sshcom_as_string(src);
  1865. u = get_mp_sshcom_as_string(src);
  1866. p = get_mp_sshcom_as_string(src);
  1867. q = get_mp_sshcom_as_string(src);
  1868. if (get_err(src)) {
  1869. errmsg = "key data did not contain six integers";
  1870. goto error;
  1871. }
  1872. alg = &ssh_rsa;
  1873. put_stringz(blob, "ssh-rsa");
  1874. put_mp_ssh2_from_string(blob, e.ptr, e.len);
  1875. put_mp_ssh2_from_string(blob, n.ptr, n.len);
  1876. publen = blob->len;
  1877. put_mp_ssh2_from_string(blob, d.ptr, d.len);
  1878. put_mp_ssh2_from_string(blob, q.ptr, q.len);
  1879. put_mp_ssh2_from_string(blob, p.ptr, p.len);
  1880. put_mp_ssh2_from_string(blob, u.ptr, u.len);
  1881. } else {
  1882. ptrlen p, q, g, x, y;
  1883. assert(type == DSA); /* the only other option from the if above */
  1884. if (get_uint32(src) != 0) {
  1885. errmsg = "predefined DSA parameters not supported";
  1886. goto error;
  1887. }
  1888. p = get_mp_sshcom_as_string(src);
  1889. g = get_mp_sshcom_as_string(src);
  1890. q = get_mp_sshcom_as_string(src);
  1891. y = get_mp_sshcom_as_string(src);
  1892. x = get_mp_sshcom_as_string(src);
  1893. if (get_err(src)) {
  1894. errmsg = "key data did not contain five integers";
  1895. goto error;
  1896. }
  1897. alg = &ssh_dss;
  1898. put_stringz(blob, "ssh-dss");
  1899. put_mp_ssh2_from_string(blob, p.ptr, p.len);
  1900. put_mp_ssh2_from_string(blob, q.ptr, q.len);
  1901. put_mp_ssh2_from_string(blob, g.ptr, g.len);
  1902. put_mp_ssh2_from_string(blob, y.ptr, y.len);
  1903. publen = blob->len;
  1904. put_mp_ssh2_from_string(blob, x.ptr, x.len);
  1905. }
  1906. retkey = snew(struct ssh2_userkey);
  1907. retkey->key = ssh_key_new_priv(
  1908. alg, make_ptrlen(blob->u, publen),
  1909. make_ptrlen(blob->u + publen, blob->len - publen));
  1910. if (!retkey->key) {
  1911. sfree(retkey);
  1912. errmsg = "unable to create key data structure";
  1913. goto error;
  1914. }
  1915. retkey->comment = dupstr(key->comment);
  1916. errmsg = NULL; /* no error */
  1917. ret = retkey;
  1918. error:
  1919. if (blob) {
  1920. strbuf_free(blob);
  1921. }
  1922. smemclr(key->keyblob, key->keyblob_size);
  1923. sfree(key->keyblob);
  1924. smemclr(key, sizeof(*key));
  1925. sfree(key);
  1926. if (errmsg_p) *errmsg_p = errmsg;
  1927. return ret;
  1928. }
  1929. static bool sshcom_write(
  1930. const Filename *filename, struct ssh2_userkey *key, const char *passphrase)
  1931. {
  1932. strbuf *pubblob, *privblob, *outblob;
  1933. ptrlen numbers[6];
  1934. int nnumbers, lenpos, i;
  1935. bool initial_zero;
  1936. BinarySource src[1];
  1937. const char *type;
  1938. char *ciphertext;
  1939. int cipherlen;
  1940. bool ret = false;
  1941. FILE *fp;
  1942. /*
  1943. * Fetch the key blobs.
  1944. */
  1945. pubblob = strbuf_new();
  1946. ssh_key_public_blob(key->key, BinarySink_UPCAST(pubblob));
  1947. privblob = strbuf_new();
  1948. ssh_key_private_blob(key->key, BinarySink_UPCAST(privblob));
  1949. outblob = NULL;
  1950. /*
  1951. * Find the sequence of integers to be encoded into the OpenSSH
  1952. * key blob, and also decide on the header line.
  1953. */
  1954. if (ssh_key_alg(key->key) == &ssh_rsa) {
  1955. ptrlen n, e, d, p, q, iqmp;
  1956. /*
  1957. * These blobs were generated from inside PuTTY, so we needn't
  1958. * treat them as untrusted.
  1959. */
  1960. BinarySource_BARE_INIT(src, pubblob->u, pubblob->len);
  1961. get_string(src); /* skip algorithm name */
  1962. e = get_string(src);
  1963. n = get_string(src);
  1964. BinarySource_BARE_INIT(src, privblob->u, privblob->len);
  1965. d = get_string(src);
  1966. p = get_string(src);
  1967. q = get_string(src);
  1968. iqmp = get_string(src);
  1969. assert(!get_err(src)); /* can't go wrong */
  1970. numbers[0] = e;
  1971. numbers[1] = d;
  1972. numbers[2] = n;
  1973. numbers[3] = iqmp;
  1974. numbers[4] = q;
  1975. numbers[5] = p;
  1976. nnumbers = 6;
  1977. initial_zero = false;
  1978. type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
  1979. } else if (ssh_key_alg(key->key) == &ssh_dss) {
  1980. ptrlen p, q, g, y, x;
  1981. /*
  1982. * These blobs were generated from inside PuTTY, so we needn't
  1983. * treat them as untrusted.
  1984. */
  1985. BinarySource_BARE_INIT(src, pubblob->u, pubblob->len);
  1986. get_string(src); /* skip algorithm name */
  1987. p = get_string(src);
  1988. q = get_string(src);
  1989. g = get_string(src);
  1990. y = get_string(src);
  1991. BinarySource_BARE_INIT(src, privblob->u, privblob->len);
  1992. x = get_string(src);
  1993. assert(!get_err(src)); /* can't go wrong */
  1994. numbers[0] = p;
  1995. numbers[1] = g;
  1996. numbers[2] = q;
  1997. numbers[3] = y;
  1998. numbers[4] = x;
  1999. nnumbers = 5;
  2000. initial_zero = true;
  2001. type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
  2002. } else {
  2003. goto error; /* unsupported key type */
  2004. }
  2005. outblob = strbuf_new();
  2006. /*
  2007. * Create the unencrypted key blob.
  2008. */
  2009. put_uint32(outblob, SSHCOM_MAGIC_NUMBER);
  2010. put_uint32(outblob, 0); /* length field, fill in later */
  2011. put_stringz(outblob, type);
  2012. put_stringz(outblob, passphrase ? "3des-cbc" : "none");
  2013. lenpos = outblob->len; /* remember this position */
  2014. put_uint32(outblob, 0); /* encrypted-blob size */
  2015. put_uint32(outblob, 0); /* encrypted-payload size */
  2016. if (initial_zero)
  2017. put_uint32(outblob, 0);
  2018. for (i = 0; i < nnumbers; i++)
  2019. put_mp_sshcom_from_string(outblob, numbers[i].ptr, numbers[i].len);
  2020. /* Now wrap up the encrypted payload. */
  2021. PUT_32BIT(outblob->s + lenpos + 4,
  2022. outblob->len - (lenpos + 8));
  2023. /* Pad encrypted blob to a multiple of cipher block size. */
  2024. if (passphrase) {
  2025. int padding = -(outblob->len - (lenpos+4)) & 7;
  2026. while (padding--)
  2027. put_byte(outblob, random_byte());
  2028. }
  2029. ciphertext = outblob->s + lenpos + 4;
  2030. cipherlen = outblob->len - (lenpos + 4);
  2031. assert(!passphrase || cipherlen % 8 == 0);
  2032. /* Wrap up the encrypted blob string. */
  2033. PUT_32BIT(outblob->s + lenpos, cipherlen);
  2034. /* And finally fill in the total length field. */
  2035. PUT_32BIT(outblob->s + 4, outblob->len);
  2036. /*
  2037. * Encrypt the key.
  2038. */
  2039. if (passphrase) {
  2040. /*
  2041. * Derive encryption key from passphrase and iv/salt:
  2042. *
  2043. * - let block A equal MD5(passphrase)
  2044. * - let block B equal MD5(passphrase || A)
  2045. * - block C would be MD5(passphrase || A || B) and so on
  2046. * - encryption key is the first N bytes of A || B
  2047. */
  2048. struct MD5Context md5c;
  2049. unsigned char keybuf[32], iv[8];
  2050. MD5Init(&md5c);
  2051. put_data(&md5c, passphrase, strlen(passphrase));
  2052. MD5Final(keybuf, &md5c);
  2053. MD5Init(&md5c);
  2054. put_data(&md5c, passphrase, strlen(passphrase));
  2055. put_data(&md5c, keybuf, 16);
  2056. MD5Final(keybuf+16, &md5c);
  2057. /*
  2058. * Now decrypt the key blob.
  2059. */
  2060. memset(iv, 0, sizeof(iv));
  2061. des3_encrypt_pubkey_ossh(keybuf, iv, ciphertext, cipherlen);
  2062. smemclr(&md5c, sizeof(md5c));
  2063. smemclr(keybuf, sizeof(keybuf));
  2064. }
  2065. /*
  2066. * And save it. We'll use Unix line endings just in case it's
  2067. * subsequently transferred in binary mode.
  2068. */
  2069. fp = f_open(filename, "wb", true); /* ensure Unix line endings */
  2070. if (!fp)
  2071. goto error;
  2072. fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
  2073. fprintf(fp, "Comment: \"");
  2074. /*
  2075. * Comment header is broken with backslash-newline if it goes
  2076. * over 70 chars. Although it's surrounded by quotes, it
  2077. * _doesn't_ escape backslashes or quotes within the string.
  2078. * Don't ask me, I didn't design it.
  2079. */
  2080. {
  2081. int slen = 60; /* starts at 60 due to "Comment: " */
  2082. char *c = key->comment;
  2083. while ((int)strlen(c) > slen) {
  2084. fprintf(fp, "%.*s\\\n", slen, c);
  2085. c += slen;
  2086. slen = 70; /* allow 70 chars on subsequent lines */
  2087. }
  2088. fprintf(fp, "%s\"\n", c);
  2089. }
  2090. base64_encode(fp, outblob->u, outblob->len, 70);
  2091. fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
  2092. fclose(fp);
  2093. ret = true;
  2094. error:
  2095. if (outblob)
  2096. strbuf_free(outblob);
  2097. if (privblob)
  2098. strbuf_free(privblob);
  2099. if (pubblob)
  2100. strbuf_free(pubblob);
  2101. return ret;
  2102. }