import.c 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319
  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 ssh2_userkey *openssh_pem_read(
  16. const Filename *file, const char *passphrase, const char **errmsg_p);
  17. static 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, ssh2_userkey *key, const char *passphrase);
  21. static bool openssh_pem_write(
  22. const Filename *file, ssh2_userkey *key, const char *passphrase);
  23. static bool openssh_new_write(
  24. const Filename *file, ssh2_userkey *key, const char *passphrase);
  25. static bool sshcom_encrypted(const Filename *file, char **comment);
  26. static ssh2_userkey *sshcom_read(
  27. const Filename *file, const char *passphrase, const char **errmsg_p);
  28. static bool sshcom_write(
  29. const Filename *file, 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. RSAKey *key, char *passphrase, const char **errmsg_p)
  79. {
  80. return 0;
  81. }
  82. /*
  83. * Import an SSH-2 key.
  84. */
  85. 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, 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. 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(BinarySink *bs, ptrlen str)
  253. {
  254. const unsigned char *bytes = (const unsigned char *)str.ptr;
  255. size_t nbytes = str.len;
  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, str) \
  269. BinarySink_put_mp_ssh2_from_string(BinarySink_UPCAST(bs), str)
  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_nm();
  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 void openssh_pem_derivekey(
  445. ptrlen passphrase, const void *iv, uint8_t *keybuf)
  446. {
  447. /*
  448. * Derive the encryption key for a PEM key file from the
  449. * passphrase and iv/salt:
  450. *
  451. * - let block A equal MD5(passphrase || iv)
  452. * - let block B equal MD5(A || passphrase || iv)
  453. * - block C would be MD5(B || passphrase || iv) and so on
  454. * - encryption key is the first N bytes of A || B
  455. *
  456. * (Note that only 8 bytes of the iv are used for key
  457. * derivation, even when the key is encrypted with AES and
  458. * hence there are 16 bytes available.)
  459. */
  460. ssh_hash *h;
  461. h = ssh_hash_new(&ssh_md5);
  462. put_datapl(h, passphrase);
  463. put_data(h, iv, 8);
  464. ssh_hash_final(h, keybuf);
  465. h = ssh_hash_new(&ssh_md5);
  466. put_data(h, keybuf, 16);
  467. put_datapl(h, passphrase);
  468. put_data(h, iv, 8);
  469. ssh_hash_final(h, keybuf + 16);
  470. }
  471. static ssh2_userkey *openssh_pem_read(
  472. const Filename *filename, const char *passphrase, const char **errmsg_p)
  473. {
  474. struct openssh_pem_key *key = load_openssh_pem_key(filename, errmsg_p);
  475. ssh2_userkey *retkey;
  476. const ssh_keyalg *alg;
  477. BinarySource src[1];
  478. int i, num_integers;
  479. ssh2_userkey *retval = NULL;
  480. const char *errmsg;
  481. strbuf *blob = strbuf_new_nm();
  482. int privptr = 0, publen;
  483. if (!key)
  484. return NULL;
  485. if (key->encrypted) {
  486. unsigned char keybuf[32];
  487. openssh_pem_derivekey(ptrlen_from_asciz(passphrase), key->iv, keybuf);
  488. /*
  489. * Decrypt the key blob.
  490. */
  491. if (key->encryption == OP_E_3DES)
  492. des3_decrypt_pubkey_ossh(keybuf, key->iv,
  493. key->keyblob->u, key->keyblob->len);
  494. else {
  495. ssh_cipher *cipher = ssh_cipher_new(&ssh_aes128_cbc);
  496. ssh_cipher_setkey(cipher, keybuf);
  497. ssh_cipher_setiv(cipher, key->iv);
  498. ssh_cipher_decrypt(cipher, key->keyblob->u, key->keyblob->len);
  499. ssh_cipher_free(cipher);
  500. }
  501. smemclr(keybuf, sizeof(keybuf));
  502. }
  503. /*
  504. * Now we have a decrypted key blob, which contains an ASN.1
  505. * encoded private key. We must now untangle the ASN.1.
  506. *
  507. * We expect the whole key blob to be formatted as a SEQUENCE
  508. * (0x30 followed by a length code indicating that the rest of
  509. * the blob is part of the sequence). Within that SEQUENCE we
  510. * expect to see a bunch of INTEGERs. What those integers mean
  511. * depends on the key type:
  512. *
  513. * - For RSA, we expect the integers to be 0, n, e, d, p, q,
  514. * dmp1, dmq1, iqmp in that order. (The last three are d mod
  515. * (p-1), d mod (q-1), inverse of q mod p respectively.)
  516. *
  517. * - For DSA, we expect them to be 0, p, q, g, y, x in that
  518. * order.
  519. *
  520. * - In ECDSA the format is totally different: we see the
  521. * SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv
  522. * EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint
  523. */
  524. BinarySource_BARE_INIT(src, key->keyblob->u, key->keyblob->len);
  525. {
  526. /* Expect the SEQUENCE header. Take its absence as a failure to
  527. * decrypt, if the key was encrypted. */
  528. ber_item seq = get_ber(src);
  529. if (get_err(src) || seq.id != 16) {
  530. errmsg = "ASN.1 decoding failure";
  531. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  532. goto error;
  533. }
  534. /* Reinitialise our BinarySource to parse just the inside of that
  535. * SEQUENCE. */
  536. BinarySource_BARE_INIT_PL(src, seq.data);
  537. }
  538. /* Expect a load of INTEGERs. */
  539. if (key->keytype == OP_RSA)
  540. num_integers = 9;
  541. else if (key->keytype == OP_DSA)
  542. num_integers = 6;
  543. else
  544. num_integers = 0; /* placate compiler warnings */
  545. if (key->keytype == OP_ECDSA) {
  546. /* And now for something completely different */
  547. ber_item integer, privkey, sub0, sub1, oid, pubkey;
  548. const ssh_keyalg *alg;
  549. const struct ec_curve *curve;
  550. /* Parse the outer layer of things inside the containing SEQUENCE */
  551. integer = get_ber(src);
  552. privkey = get_ber(src);
  553. sub0 = get_ber(src);
  554. sub1 = get_ber(src);
  555. /* Now look inside sub0 for the curve OID */
  556. BinarySource_BARE_INIT_PL(src, sub0.data);
  557. oid = get_ber(src);
  558. /* And inside sub1 for the public-key BIT STRING */
  559. BinarySource_BARE_INIT_PL(src, sub1.data);
  560. pubkey = get_ber(src);
  561. if (get_err(src) ||
  562. integer.id != 2 ||
  563. integer.data.len != 1 ||
  564. ((const unsigned char *)integer.data.ptr)[0] != 1 ||
  565. privkey.id != 4 ||
  566. sub0.id != 0 ||
  567. sub1.id != 1 ||
  568. oid.id != 6 ||
  569. pubkey.id != 3) {
  570. errmsg = "ASN.1 decoding failure";
  571. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  572. goto error;
  573. }
  574. alg = ec_alg_by_oid(oid.data.len, oid.data.ptr, &curve);
  575. if (!alg) {
  576. errmsg = "Unsupported ECDSA curve.";
  577. retval = NULL;
  578. goto error;
  579. }
  580. if (pubkey.data.len != ((((curve->fieldBits + 7) / 8) * 2) + 2)) {
  581. errmsg = "ASN.1 decoding failure";
  582. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  583. goto error;
  584. }
  585. /* Skip 0x00 before point */
  586. pubkey.data.ptr = (const char *)pubkey.data.ptr + 1;
  587. pubkey.data.len -= 1;
  588. /* Construct the key */
  589. retkey = snew(ssh2_userkey);
  590. put_stringz(blob, alg->ssh_id);
  591. put_stringz(blob, curve->name);
  592. put_stringpl(blob, pubkey.data);
  593. publen = blob->len;
  594. put_mp_ssh2_from_string(blob, privkey.data);
  595. retkey->key = ssh_key_new_priv(
  596. alg, make_ptrlen(blob->u, publen),
  597. make_ptrlen(blob->u + publen, blob->len - publen));
  598. if (!retkey->key) {
  599. sfree(retkey);
  600. errmsg = "unable to create key data structure";
  601. goto error;
  602. }
  603. } else if (key->keytype == OP_RSA || key->keytype == OP_DSA) {
  604. put_stringz(blob, key->keytype == OP_DSA ? "ssh-dss" : "ssh-rsa");
  605. { // WINSCP
  606. ptrlen rsa_modulus = PTRLEN_LITERAL("");
  607. for (i = 0; i < num_integers; i++) {
  608. ber_item integer = get_ber(src);
  609. if (get_err(src) || integer.id != 2) {
  610. errmsg = "ASN.1 decoding failure";
  611. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  612. goto error;
  613. }
  614. if (i == 0) {
  615. /*
  616. * The first integer should be zero always (I think
  617. * this is some sort of version indication).
  618. */
  619. if (integer.data.len != 1 ||
  620. ((const unsigned char *)integer.data.ptr)[0] != 0) {
  621. errmsg = "version number mismatch";
  622. goto error;
  623. }
  624. } else if (key->keytype == OP_RSA) {
  625. /*
  626. * Integers 1 and 2 go into the public blob but in the
  627. * opposite order; integers 3, 4, 5 and 8 go into the
  628. * private blob. The other two (6 and 7) are ignored.
  629. */
  630. if (i == 1) {
  631. /* Save the details for after we deal with number 2. */
  632. rsa_modulus = integer.data;
  633. } else if (i != 6 && i != 7) {
  634. put_mp_ssh2_from_string(blob, integer.data);
  635. if (i == 2) {
  636. put_mp_ssh2_from_string(blob, rsa_modulus);
  637. privptr = blob->len;
  638. }
  639. }
  640. } else if (key->keytype == OP_DSA) {
  641. /*
  642. * Integers 1-4 go into the public blob; integer 5 goes
  643. * into the private blob.
  644. */
  645. put_mp_ssh2_from_string(blob, integer.data);
  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(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. } // WINSCP
  668. } else {
  669. unreachable("Bad key type from load_openssh_pem_key");
  670. errmsg = "Bad key type from load_openssh_pem_key";
  671. goto error;
  672. }
  673. /*
  674. * The old key format doesn't include a comment in the private
  675. * key file.
  676. */
  677. retkey->comment = dupstr("imported-openssh-key");
  678. errmsg = NULL; /* no error */
  679. retval = retkey;
  680. error:
  681. strbuf_free(blob);
  682. strbuf_free(key->keyblob);
  683. smemclr(key, sizeof(*key));
  684. sfree(key);
  685. if (errmsg_p) *errmsg_p = errmsg;
  686. return retval;
  687. }
  688. static bool openssh_pem_write(
  689. const Filename *filename, ssh2_userkey *key, const char *passphrase)
  690. {
  691. strbuf *pubblob, *privblob, *outblob;
  692. unsigned char *spareblob;
  693. int sparelen = 0;
  694. ptrlen numbers[9];
  695. int nnumbers, i;
  696. const char *header, *footer;
  697. char zero[1];
  698. unsigned char iv[8];
  699. bool ret = false;
  700. FILE *fp;
  701. BinarySource src[1];
  702. /*
  703. * Fetch the key blobs.
  704. */
  705. pubblob = strbuf_new();
  706. ssh_key_public_blob(key->key, BinarySink_UPCAST(pubblob));
  707. privblob = strbuf_new_nm();
  708. ssh_key_private_blob(key->key, BinarySink_UPCAST(privblob));
  709. spareblob = NULL;
  710. outblob = strbuf_new_nm();
  711. /*
  712. * Encode the OpenSSH key blob, and also decide on the header
  713. * line.
  714. */
  715. if (ssh_key_alg(key->key) == &ssh_rsa ||
  716. ssh_key_alg(key->key) == &ssh_dss) {
  717. strbuf *seq;
  718. /*
  719. * The RSA and DSS handlers share some code because the two
  720. * key types have very similar ASN.1 representations, as a
  721. * plain SEQUENCE of big integers. So we set up a list of
  722. * bignums per key type and then construct the actual blob in
  723. * common code after that.
  724. */
  725. if (ssh_key_alg(key->key) == &ssh_rsa) {
  726. ptrlen n, e, d, p, q, iqmp, dmp1, dmq1;
  727. mp_int *bd, *bp, *bq, *bdmp1, *bdmq1;
  728. /*
  729. * These blobs were generated from inside PuTTY, so we needn't
  730. * treat them as untrusted.
  731. */
  732. BinarySource_BARE_INIT(src, pubblob->u, pubblob->len);
  733. get_string(src); /* skip algorithm name */
  734. e = get_string(src);
  735. n = get_string(src);
  736. BinarySource_BARE_INIT(src, privblob->u, privblob->len);
  737. d = get_string(src);
  738. p = get_string(src);
  739. q = get_string(src);
  740. iqmp = get_string(src);
  741. assert(!get_err(src)); /* can't go wrong */
  742. /* We also need d mod (p-1) and d mod (q-1). */
  743. bd = mp_from_bytes_be(d);
  744. bp = mp_from_bytes_be(p);
  745. bq = mp_from_bytes_be(q);
  746. mp_sub_integer_into(bp, bp, 1);
  747. mp_sub_integer_into(bq, bq, 1);
  748. bdmp1 = mp_mod(bd, bp);
  749. bdmq1 = mp_mod(bd, bq);
  750. mp_free(bd);
  751. mp_free(bp);
  752. mp_free(bq);
  753. dmp1.len = (mp_get_nbits(bdmp1)+8)/8;
  754. dmq1.len = (mp_get_nbits(bdmq1)+8)/8;
  755. sparelen = dmp1.len + dmq1.len;
  756. spareblob = snewn(sparelen, unsigned char);
  757. dmp1.ptr = spareblob;
  758. dmq1.ptr = spareblob + dmp1.len;
  759. for (i = 0; i < dmp1.len; i++)
  760. spareblob[i] = mp_get_byte(bdmp1, dmp1.len-1 - i);
  761. for (i = 0; i < dmq1.len; i++)
  762. spareblob[i+dmp1.len] = mp_get_byte(bdmq1, dmq1.len-1 - i);
  763. mp_free(bdmp1);
  764. mp_free(bdmq1);
  765. numbers[0] = make_ptrlen(zero, 1); zero[0] = '\0';
  766. numbers[1] = n;
  767. numbers[2] = e;
  768. numbers[3] = d;
  769. numbers[4] = p;
  770. numbers[5] = q;
  771. numbers[6] = dmp1;
  772. numbers[7] = dmq1;
  773. numbers[8] = iqmp;
  774. nnumbers = 9;
  775. header = "-----BEGIN RSA PRIVATE KEY-----\n";
  776. footer = "-----END RSA PRIVATE KEY-----\n";
  777. } else { /* ssh-dss */
  778. ptrlen p, q, g, y, x;
  779. /*
  780. * These blobs were generated from inside PuTTY, so we needn't
  781. * treat them as untrusted.
  782. */
  783. BinarySource_BARE_INIT(src, pubblob->u, pubblob->len);
  784. get_string(src); /* skip algorithm name */
  785. p = get_string(src);
  786. q = get_string(src);
  787. g = get_string(src);
  788. y = get_string(src);
  789. BinarySource_BARE_INIT(src, privblob->u, privblob->len);
  790. x = get_string(src);
  791. assert(!get_err(src)); /* can't go wrong */
  792. numbers[0].ptr = zero; numbers[0].len = 1; zero[0] = '\0';
  793. numbers[1] = p;
  794. numbers[2] = q;
  795. numbers[3] = g;
  796. numbers[4] = y;
  797. numbers[5] = x;
  798. nnumbers = 6;
  799. header = "-----BEGIN DSA PRIVATE KEY-----\n";
  800. footer = "-----END DSA PRIVATE KEY-----\n";
  801. }
  802. seq = strbuf_new_nm();
  803. for (i = 0; i < nnumbers; i++) {
  804. put_ber_id_len(seq, 2, numbers[i].len, 0);
  805. put_datapl(seq, numbers[i]);
  806. }
  807. put_ber_id_len(outblob, 16, seq->len, ASN1_CONSTRUCTED);
  808. put_data(outblob, seq->s, seq->len);
  809. strbuf_free(seq);
  810. } else if (ssh_key_alg(key->key) == &ssh_ecdsa_nistp256 ||
  811. ssh_key_alg(key->key) == &ssh_ecdsa_nistp384 ||
  812. ssh_key_alg(key->key) == &ssh_ecdsa_nistp521) {
  813. const unsigned char *oid;
  814. struct ecdsa_key *ec = container_of(key->key, struct ecdsa_key, sshk);
  815. int oidlen;
  816. int pointlen;
  817. strbuf *seq, *sub;
  818. /*
  819. * Structure of asn1:
  820. * SEQUENCE
  821. * INTEGER 1
  822. * OCTET STRING (private key)
  823. * [0]
  824. * OID (curve)
  825. * [1]
  826. * BIT STRING (0x00 public key point)
  827. */
  828. oid = ec_alg_oid(ssh_key_alg(key->key), &oidlen);
  829. pointlen = (ec->curve->fieldBits + 7) / 8 * 2;
  830. seq = strbuf_new_nm();
  831. /* INTEGER 1 */
  832. put_ber_id_len(seq, 2, 1, 0);
  833. put_byte(seq, 1);
  834. /* OCTET STRING private key */
  835. put_ber_id_len(seq, 4, privblob->len - 4, 0);
  836. put_data(seq, privblob->s + 4, privblob->len - 4);
  837. /* Subsidiary OID */
  838. sub = strbuf_new();
  839. put_ber_id_len(sub, 6, oidlen, 0);
  840. put_data(sub, oid, oidlen);
  841. /* Append the OID to the sequence */
  842. put_ber_id_len(seq, 0, sub->len,
  843. ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
  844. put_data(seq, sub->s, sub->len);
  845. strbuf_free(sub);
  846. /* Subsidiary BIT STRING */
  847. sub = strbuf_new();
  848. put_ber_id_len(sub, 3, 2 + pointlen, 0);
  849. put_byte(sub, 0);
  850. put_data(sub, pubblob->s+39, 1 + pointlen);
  851. /* Append the BIT STRING to the sequence */
  852. put_ber_id_len(seq, 1, sub->len,
  853. ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
  854. put_data(seq, sub->s, sub->len);
  855. strbuf_free(sub);
  856. /* Write the full sequence with header to the output blob. */
  857. put_ber_id_len(outblob, 16, seq->len, ASN1_CONSTRUCTED);
  858. put_data(outblob, seq->s, seq->len);
  859. strbuf_free(seq);
  860. header = "-----BEGIN EC PRIVATE KEY-----\n";
  861. footer = "-----END EC PRIVATE KEY-----\n";
  862. } else {
  863. unreachable("bad key alg in openssh_pem_write");
  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. unsigned char keybuf[32];
  873. int origlen, outlen, pad;
  874. /*
  875. * Padding on OpenSSH keys is deterministic. The number of
  876. * padding bytes is always more than zero, and always at most
  877. * the cipher block length. The value of each padding byte is
  878. * equal to the number of padding bytes. So a plaintext that's
  879. * an exact multiple of the block size will be padded with 08
  880. * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
  881. * plaintext one byte less than a multiple of the block size
  882. * will be padded with just 01.
  883. *
  884. * This enables the OpenSSL key decryption function to strip
  885. * off the padding algorithmically and return the unpadded
  886. * plaintext to the next layer: it looks at the final byte, and
  887. * then expects to find that many bytes at the end of the data
  888. * with the same value. Those are all removed and the rest is
  889. * returned.
  890. */
  891. origlen = outblob->len;
  892. outlen = (origlen + 8) &~ 7;
  893. pad = outlen - origlen;
  894. put_padding(outblob, pad, pad);
  895. /*
  896. * Invent an iv, and derive the encryption key.
  897. */
  898. random_read(iv, 8);
  899. openssh_pem_derivekey(ptrlen_from_asciz(passphrase), iv, keybuf);
  900. /*
  901. * Now encrypt the key blob.
  902. */
  903. des3_encrypt_pubkey_ossh(keybuf, iv,
  904. outblob->u, outlen);
  905. smemclr(keybuf, sizeof(keybuf));
  906. }
  907. /*
  908. * And save it. We'll use Unix line endings just in case it's
  909. * subsequently transferred in binary mode.
  910. */
  911. fp = f_open(filename, "wb", true); /* ensure Unix line endings */
  912. if (!fp)
  913. goto error;
  914. fputs(header, fp);
  915. if (passphrase) {
  916. fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
  917. for (i = 0; i < 8; i++)
  918. fprintf(fp, "%02X", iv[i]);
  919. fprintf(fp, "\n\n");
  920. }
  921. base64_encode(fp, outblob->u, outblob->len, 64);
  922. fputs(footer, fp);
  923. fclose(fp);
  924. ret = true;
  925. error:
  926. if (outblob)
  927. strbuf_free(outblob);
  928. if (spareblob) {
  929. smemclr(spareblob, sparelen);
  930. sfree(spareblob);
  931. }
  932. if (privblob)
  933. strbuf_free(privblob);
  934. if (pubblob)
  935. strbuf_free(pubblob);
  936. return ret;
  937. }
  938. /* ----------------------------------------------------------------------
  939. * Code to read and write OpenSSH private keys in the new-style format.
  940. */
  941. typedef enum {
  942. ON_E_NONE, ON_E_AES256CBC, ON_E_AES256CTR
  943. } openssh_new_cipher;
  944. typedef enum {
  945. ON_K_NONE, ON_K_BCRYPT
  946. } openssh_new_kdf;
  947. struct openssh_new_key {
  948. openssh_new_cipher cipher;
  949. openssh_new_kdf kdf;
  950. union {
  951. struct {
  952. int rounds;
  953. /* This points to a position within keyblob, not a
  954. * separately allocated thing */
  955. ptrlen salt;
  956. } bcrypt;
  957. } kdfopts;
  958. int nkeys, key_wanted;
  959. /* This too points to a position within keyblob */
  960. ptrlen private;
  961. strbuf *keyblob;
  962. };
  963. static struct openssh_new_key *load_openssh_new_key(const Filename *filename,
  964. const char **errmsg_p)
  965. {
  966. struct openssh_new_key *ret;
  967. FILE *fp = NULL;
  968. char *line = NULL;
  969. const char *errmsg;
  970. char *p;
  971. char base64_bit[4];
  972. int base64_chars = 0;
  973. BinarySource src[1];
  974. ptrlen str;
  975. unsigned key_index;
  976. ret = snew(struct openssh_new_key);
  977. ret->keyblob = strbuf_new_nm();
  978. fp = f_open(filename, "r", false);
  979. if (!fp) {
  980. errmsg = "unable to open key file";
  981. goto error;
  982. }
  983. if (!(line = fgetline(fp))) {
  984. errmsg = "unexpected end of file";
  985. goto error;
  986. }
  987. strip_crlf(line);
  988. if (0 != strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
  989. errmsg = "file does not begin with OpenSSH new-style key header";
  990. goto error;
  991. }
  992. smemclr(line, strlen(line));
  993. sfree(line);
  994. line = NULL;
  995. while (1) {
  996. if (!(line = fgetline(fp))) {
  997. errmsg = "unexpected end of file";
  998. goto error;
  999. }
  1000. strip_crlf(line);
  1001. if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) {
  1002. sfree(line);
  1003. line = NULL;
  1004. break; /* done */
  1005. }
  1006. p = line;
  1007. while (isbase64(*p)) {
  1008. base64_bit[base64_chars++] = *p;
  1009. if (base64_chars == 4) {
  1010. unsigned char out[3];
  1011. int len;
  1012. base64_chars = 0;
  1013. len = base64_decode_atom(base64_bit, out);
  1014. if (len <= 0) {
  1015. errmsg = "invalid base64 encoding";
  1016. goto error;
  1017. }
  1018. put_data(ret->keyblob, out, len);
  1019. smemclr(out, sizeof(out));
  1020. }
  1021. p++;
  1022. }
  1023. smemclr(line, strlen(line));
  1024. sfree(line);
  1025. line = NULL;
  1026. }
  1027. fclose(fp);
  1028. fp = NULL;
  1029. if (ret->keyblob->len == 0 || !ret->keyblob) {
  1030. errmsg = "key body not present";
  1031. goto error;
  1032. }
  1033. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(ret->keyblob));
  1034. if (strcmp(get_asciz(src), "openssh-key-v1") != 0) {
  1035. errmsg = "new-style OpenSSH magic number missing\n";
  1036. goto error;
  1037. }
  1038. /* Cipher name */
  1039. str = get_string(src);
  1040. if (ptrlen_eq_string(str, "none")) {
  1041. ret->cipher = ON_E_NONE;
  1042. } else if (ptrlen_eq_string(str, "aes256-cbc")) {
  1043. ret->cipher = ON_E_AES256CBC;
  1044. } else if (ptrlen_eq_string(str, "aes256-ctr")) {
  1045. ret->cipher = ON_E_AES256CTR;
  1046. } else {
  1047. errmsg = get_err(src) ? "no cipher name found" :
  1048. "unrecognised cipher name\n";
  1049. goto error;
  1050. }
  1051. /* Key derivation function name */
  1052. str = get_string(src);
  1053. if (ptrlen_eq_string(str, "none")) {
  1054. ret->kdf = ON_K_NONE;
  1055. } else if (ptrlen_eq_string(str, "bcrypt")) {
  1056. ret->kdf = ON_K_BCRYPT;
  1057. } else {
  1058. errmsg = get_err(src) ? "no kdf name found" :
  1059. "unrecognised kdf name\n";
  1060. goto error;
  1061. }
  1062. /* KDF extra options */
  1063. str = get_string(src);
  1064. switch (ret->kdf) {
  1065. case ON_K_NONE:
  1066. if (str.len != 0) {
  1067. errmsg = "expected empty options string for 'none' kdf";
  1068. goto error;
  1069. }
  1070. break;
  1071. case ON_K_BCRYPT:
  1072. {
  1073. BinarySource opts[1];
  1074. BinarySource_BARE_INIT_PL(opts, str);
  1075. ret->kdfopts.bcrypt.salt = get_string(opts);
  1076. ret->kdfopts.bcrypt.rounds = get_uint32(opts);
  1077. if (get_err(opts)) {
  1078. errmsg = "failed to parse bcrypt options string";
  1079. goto error;
  1080. }
  1081. }
  1082. break;
  1083. }
  1084. /*
  1085. * At this point we expect a uint32 saying how many keys are
  1086. * stored in this file. OpenSSH new-style key files can
  1087. * contain more than one. Currently we don't have any user
  1088. * interface to specify which one we're trying to extract, so
  1089. * we just bomb out with an error if more than one is found in
  1090. * the file. However, I've put in all the mechanism here to
  1091. * extract the nth one for a given n, in case we later connect
  1092. * up some UI to that mechanism. Just arrange that the
  1093. * 'key_wanted' field is set to a value in the range [0,
  1094. * nkeys) by some mechanism.
  1095. */
  1096. ret->nkeys = toint(get_uint32(src));
  1097. if (ret->nkeys != 1) {
  1098. errmsg = get_err(src) ? "no key count found" :
  1099. "multiple keys in new-style OpenSSH key file not supported\n";
  1100. goto error;
  1101. }
  1102. ret->key_wanted = 0;
  1103. /* Read and ignore a string per public key. */
  1104. for (key_index = 0; key_index < ret->nkeys; key_index++)
  1105. str = get_string(src);
  1106. /*
  1107. * Now we expect a string containing the encrypted part of the
  1108. * key file.
  1109. */
  1110. ret->private = get_string(src);
  1111. if (get_err(src)) {
  1112. errmsg = "no private key container string found\n";
  1113. goto error;
  1114. }
  1115. /*
  1116. * And now we're done, until asked to actually decrypt.
  1117. */
  1118. smemclr(base64_bit, sizeof(base64_bit));
  1119. if (errmsg_p) *errmsg_p = NULL;
  1120. return ret;
  1121. error:
  1122. if (line) {
  1123. smemclr(line, strlen(line));
  1124. sfree(line);
  1125. line = NULL;
  1126. }
  1127. smemclr(base64_bit, sizeof(base64_bit));
  1128. if (ret) {
  1129. strbuf_free(ret->keyblob);
  1130. smemclr(ret, sizeof(*ret));
  1131. sfree(ret);
  1132. }
  1133. if (errmsg_p) *errmsg_p = errmsg;
  1134. if (fp) fclose(fp);
  1135. return NULL;
  1136. }
  1137. static bool openssh_new_encrypted(const Filename *filename)
  1138. {
  1139. struct openssh_new_key *key = load_openssh_new_key(filename, NULL);
  1140. bool ret;
  1141. if (!key)
  1142. return false;
  1143. ret = (key->cipher != ON_E_NONE);
  1144. strbuf_free(key->keyblob);
  1145. smemclr(key, sizeof(*key));
  1146. sfree(key);
  1147. return ret;
  1148. }
  1149. static ssh2_userkey *openssh_new_read(
  1150. const Filename *filename, const char *passphrase, const char **errmsg_p)
  1151. {
  1152. struct openssh_new_key *key = load_openssh_new_key(filename, errmsg_p);
  1153. ssh2_userkey *retkey = NULL;
  1154. ssh2_userkey *retval = NULL;
  1155. const char *errmsg;
  1156. unsigned checkint;
  1157. BinarySource src[1];
  1158. int key_index;
  1159. const ssh_keyalg *alg = NULL;
  1160. if (!key)
  1161. return NULL;
  1162. if (key->cipher != ON_E_NONE) {
  1163. unsigned char keybuf[48];
  1164. int keysize;
  1165. /*
  1166. * Construct the decryption key, and decrypt the string.
  1167. */
  1168. switch (key->cipher) {
  1169. case ON_E_NONE:
  1170. keysize = 0;
  1171. break;
  1172. case ON_E_AES256CBC:
  1173. case ON_E_AES256CTR:
  1174. keysize = 48; /* 32 byte key + 16 byte IV */
  1175. break;
  1176. default:
  1177. unreachable("Bad cipher enumeration value");
  1178. }
  1179. assert(keysize <= sizeof(keybuf));
  1180. switch (key->kdf) {
  1181. case ON_K_NONE:
  1182. memset(keybuf, 0, keysize);
  1183. break;
  1184. case ON_K_BCRYPT:
  1185. openssh_bcrypt(passphrase,
  1186. key->kdfopts.bcrypt.salt.ptr,
  1187. key->kdfopts.bcrypt.salt.len,
  1188. key->kdfopts.bcrypt.rounds,
  1189. keybuf, keysize);
  1190. break;
  1191. default:
  1192. unreachable("Bad kdf enumeration value");
  1193. }
  1194. switch (key->cipher) {
  1195. case ON_E_NONE:
  1196. break;
  1197. case ON_E_AES256CBC:
  1198. case ON_E_AES256CTR:
  1199. if (key->private.len % 16 != 0) {
  1200. errmsg = "private key container length is not a"
  1201. " multiple of AES block size\n";
  1202. goto error;
  1203. }
  1204. {
  1205. ssh_cipher *cipher = ssh_cipher_new(
  1206. key->cipher == ON_E_AES256CBC ?
  1207. &ssh_aes256_cbc : &ssh_aes256_sdctr);
  1208. ssh_cipher_setkey(cipher, keybuf);
  1209. ssh_cipher_setiv(cipher, keybuf + 32);
  1210. /* Decrypt the private section in place, casting away
  1211. * the const from key->private being a ptrlen */
  1212. ssh_cipher_decrypt(cipher, (char *)key->private.ptr,
  1213. key->private.len);
  1214. ssh_cipher_free(cipher);
  1215. }
  1216. break;
  1217. default:
  1218. unreachable("Bad cipher enumeration value");
  1219. }
  1220. }
  1221. /*
  1222. * Now parse the entire encrypted section, and extract the key
  1223. * identified by key_wanted.
  1224. */
  1225. BinarySource_BARE_INIT_PL(src, key->private);
  1226. checkint = get_uint32(src);
  1227. if (get_uint32(src) != checkint || get_err(src)) {
  1228. errmsg = "decryption check failed";
  1229. goto error;
  1230. }
  1231. retkey = snew(ssh2_userkey);
  1232. retkey->key = NULL;
  1233. retkey->comment = NULL;
  1234. for (key_index = 0; key_index < key->nkeys; key_index++) {
  1235. ptrlen comment;
  1236. /*
  1237. * Identify the key type.
  1238. */
  1239. alg = find_pubkey_alg_len(get_string(src));
  1240. if (!alg) {
  1241. errmsg = "private key type not recognised\n";
  1242. goto error;
  1243. }
  1244. /*
  1245. * Read the key. We have to do this even if it's not the one
  1246. * we want, because it's the only way to find out how much
  1247. * data to skip past to get to the next key in the file.
  1248. */
  1249. retkey->key = ssh_key_new_priv_openssh(alg, src);
  1250. if (get_err(src)) {
  1251. errmsg = "unable to read entire private key";
  1252. goto error;
  1253. }
  1254. if (!retkey->key) {
  1255. errmsg = "unable to create key data structure";
  1256. goto error;
  1257. }
  1258. if (key_index != key->key_wanted) {
  1259. /*
  1260. * If this isn't the key we're looking for, throw it away.
  1261. */
  1262. ssh_key_free(retkey->key);
  1263. retkey->key = NULL;
  1264. }
  1265. /*
  1266. * Read the key comment.
  1267. */
  1268. comment = get_string(src);
  1269. if (get_err(src)) {
  1270. errmsg = "unable to read key comment";
  1271. goto error;
  1272. }
  1273. if (key_index == key->key_wanted) {
  1274. assert(retkey);
  1275. retkey->comment = mkstr(comment);
  1276. }
  1277. }
  1278. if (!retkey) {
  1279. errmsg = "key index out of range";
  1280. goto error;
  1281. }
  1282. /*
  1283. * Now we expect nothing left but padding.
  1284. */
  1285. {
  1286. unsigned char expected_pad_byte = 1;
  1287. while (get_avail(src) > 0)
  1288. if (get_byte(src) != expected_pad_byte++) {
  1289. errmsg = "padding at end of private string did not match";
  1290. goto error;
  1291. }
  1292. }
  1293. errmsg = NULL; /* no error */
  1294. retval = retkey;
  1295. retkey = NULL; /* prevent the free */
  1296. error:
  1297. if (retkey) {
  1298. sfree(retkey->comment);
  1299. if (retkey->key)
  1300. ssh_key_free(retkey->key);
  1301. sfree(retkey);
  1302. }
  1303. strbuf_free(key->keyblob);
  1304. smemclr(key, sizeof(*key));
  1305. sfree(key);
  1306. if (errmsg_p) *errmsg_p = errmsg;
  1307. return retval;
  1308. }
  1309. static bool openssh_new_write(
  1310. const Filename *filename, ssh2_userkey *key, const char *passphrase)
  1311. {
  1312. strbuf *pubblob, *privblob, *cblob;
  1313. int padvalue;
  1314. unsigned checkint;
  1315. bool ret = false;
  1316. unsigned char bcrypt_salt[16];
  1317. const int bcrypt_rounds = 16;
  1318. FILE *fp;
  1319. /*
  1320. * Fetch the key blobs and find out the lengths of things.
  1321. */
  1322. pubblob = strbuf_new();
  1323. ssh_key_public_blob(key->key, BinarySink_UPCAST(pubblob));
  1324. privblob = strbuf_new_nm();
  1325. ssh_key_openssh_blob(key->key, BinarySink_UPCAST(privblob));
  1326. /*
  1327. * Construct the cleartext version of the blob.
  1328. */
  1329. cblob = strbuf_new_nm();
  1330. /* Magic number. */
  1331. put_asciz(cblob, "openssh-key-v1");
  1332. /* Cipher and kdf names, and kdf options. */
  1333. if (!passphrase) {
  1334. memset(bcrypt_salt, 0, sizeof(bcrypt_salt)); /* prevent warnings */
  1335. put_stringz(cblob, "none");
  1336. put_stringz(cblob, "none");
  1337. put_stringz(cblob, "");
  1338. } else {
  1339. strbuf *substr;
  1340. random_read(bcrypt_salt, sizeof(bcrypt_salt));
  1341. put_stringz(cblob, "aes256-ctr");
  1342. put_stringz(cblob, "bcrypt");
  1343. substr = strbuf_new_nm();
  1344. put_string(substr, bcrypt_salt, sizeof(bcrypt_salt));
  1345. put_uint32(substr, bcrypt_rounds);
  1346. put_stringsb(cblob, substr);
  1347. }
  1348. /* Number of keys. */
  1349. put_uint32(cblob, 1);
  1350. /* Public blob. */
  1351. put_string(cblob, pubblob->s, pubblob->len);
  1352. /* Private section. */
  1353. {
  1354. strbuf *cpblob = strbuf_new_nm();
  1355. /* checkint. */
  1356. uint8_t checkint_buf[4];
  1357. random_read(checkint_buf, 4);
  1358. checkint = GET_32BIT_MSB_FIRST(checkint_buf);
  1359. put_uint32(cpblob, checkint);
  1360. put_uint32(cpblob, checkint);
  1361. /* Private key. The main private blob goes inline, with no string
  1362. * wrapper. */
  1363. put_stringz(cpblob, ssh_key_ssh_id(key->key));
  1364. put_data(cpblob, privblob->s, privblob->len);
  1365. /* Comment. */
  1366. put_stringz(cpblob, key->comment);
  1367. /* Pad out the encrypted section. */
  1368. padvalue = 1;
  1369. do {
  1370. put_byte(cpblob, padvalue++);
  1371. } while (cpblob->len & 15);
  1372. if (passphrase) {
  1373. /*
  1374. * Encrypt the private section. We need 48 bytes of key
  1375. * material: 32 bytes AES key + 16 bytes iv.
  1376. */
  1377. unsigned char keybuf[48];
  1378. ssh_cipher *cipher;
  1379. openssh_bcrypt(passphrase,
  1380. bcrypt_salt, sizeof(bcrypt_salt), bcrypt_rounds,
  1381. keybuf, sizeof(keybuf));
  1382. cipher = ssh_cipher_new(&ssh_aes256_sdctr);
  1383. ssh_cipher_setkey(cipher, keybuf);
  1384. ssh_cipher_setiv(cipher, keybuf + 32);
  1385. ssh_cipher_encrypt(cipher, cpblob->u, cpblob->len);
  1386. ssh_cipher_free(cipher);
  1387. smemclr(keybuf, sizeof(keybuf));
  1388. }
  1389. put_stringsb(cblob, cpblob);
  1390. }
  1391. /*
  1392. * And save it. We'll use Unix line endings just in case it's
  1393. * subsequently transferred in binary mode.
  1394. */
  1395. fp = f_open(filename, "wb", true); /* ensure Unix line endings */
  1396. if (!fp)
  1397. goto error;
  1398. fputs("-----BEGIN OPENSSH PRIVATE KEY-----\n", fp);
  1399. base64_encode(fp, cblob->u, cblob->len, 64);
  1400. fputs("-----END OPENSSH PRIVATE KEY-----\n", fp);
  1401. fclose(fp);
  1402. ret = true;
  1403. error:
  1404. if (cblob)
  1405. strbuf_free(cblob);
  1406. if (privblob)
  1407. strbuf_free(privblob);
  1408. if (pubblob)
  1409. strbuf_free(pubblob);
  1410. return ret;
  1411. }
  1412. /* ----------------------------------------------------------------------
  1413. * The switch function openssh_auto_write(), which chooses one of the
  1414. * concrete OpenSSH output formats based on the key type.
  1415. */
  1416. static bool openssh_auto_write(
  1417. const Filename *filename, ssh2_userkey *key, const char *passphrase)
  1418. {
  1419. /*
  1420. * The old OpenSSH format supports a fixed list of key types. We
  1421. * assume that anything not in that fixed list is newer, and hence
  1422. * will use the new format.
  1423. */
  1424. if (ssh_key_alg(key->key) == &ssh_dss ||
  1425. ssh_key_alg(key->key) == &ssh_rsa ||
  1426. ssh_key_alg(key->key) == &ssh_ecdsa_nistp256 ||
  1427. ssh_key_alg(key->key) == &ssh_ecdsa_nistp384 ||
  1428. ssh_key_alg(key->key) == &ssh_ecdsa_nistp521)
  1429. return openssh_pem_write(filename, key, passphrase);
  1430. else
  1431. return openssh_new_write(filename, key, passphrase);
  1432. }
  1433. /* ----------------------------------------------------------------------
  1434. * Code to read ssh.com private keys.
  1435. */
  1436. /*
  1437. * The format of the base64 blob is largely SSH-2-packet-formatted,
  1438. * except that mpints are a bit different: they're more like the
  1439. * old SSH-1 mpint. You have a 32-bit bit count N, followed by
  1440. * (N+7)/8 bytes of data.
  1441. *
  1442. * So. The blob contains:
  1443. *
  1444. * - uint32 0x3f6ff9eb (magic number)
  1445. * - uint32 size (total blob size)
  1446. * - string key-type (see below)
  1447. * - string cipher-type (tells you if key is encrypted)
  1448. * - string encrypted-blob
  1449. *
  1450. * (The first size field includes the size field itself and the
  1451. * magic number before it. All other size fields are ordinary SSH-2
  1452. * strings, so the size field indicates how much data is to
  1453. * _follow_.)
  1454. *
  1455. * The encrypted blob, once decrypted, contains a single string
  1456. * which in turn contains the payload. (This allows padding to be
  1457. * added after that string while still making it clear where the
  1458. * real payload ends. Also it probably makes for a reasonable
  1459. * decryption check.)
  1460. *
  1461. * The payload blob, for an RSA key, contains:
  1462. * - mpint e
  1463. * - mpint d
  1464. * - mpint n (yes, the public and private stuff is intermixed)
  1465. * - mpint u (presumably inverse of p mod q)
  1466. * - mpint p (p is the smaller prime)
  1467. * - mpint q (q is the larger)
  1468. *
  1469. * For a DSA key, the payload blob contains:
  1470. * - uint32 0
  1471. * - mpint p
  1472. * - mpint g
  1473. * - mpint q
  1474. * - mpint y
  1475. * - mpint x
  1476. *
  1477. * Alternatively, if the parameters are `predefined', that
  1478. * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
  1479. * containing some predefined parameter specification. *shudder*,
  1480. * but I doubt we'll encounter this in real life.
  1481. *
  1482. * The key type strings are ghastly. The RSA key I looked at had a
  1483. * type string of
  1484. *
  1485. * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
  1486. *
  1487. * and the DSA key wasn't much better:
  1488. *
  1489. * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
  1490. *
  1491. * It isn't clear that these will always be the same. I think it
  1492. * might be wise just to look at the `if-modn{sign{rsa' and
  1493. * `dl-modp{sign{dsa' prefixes.
  1494. *
  1495. * Finally, the encryption. The cipher-type string appears to be
  1496. * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
  1497. * 3des-cbc (i.e. outer cbc rather than inner). The key is created
  1498. * from the passphrase by means of yet another hashing faff:
  1499. *
  1500. * - first 16 bytes are MD5(passphrase)
  1501. * - next 16 bytes are MD5(passphrase || first 16 bytes)
  1502. * - if there were more, they'd be MD5(passphrase || first 32),
  1503. * and so on.
  1504. */
  1505. #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
  1506. struct sshcom_key {
  1507. char comment[256]; /* allowing any length is overkill */
  1508. strbuf *keyblob;
  1509. };
  1510. static struct sshcom_key *load_sshcom_key(const Filename *filename,
  1511. const char **errmsg_p)
  1512. {
  1513. struct sshcom_key *ret;
  1514. FILE *fp;
  1515. char *line = NULL;
  1516. int hdrstart, len;
  1517. const char *errmsg;
  1518. char *p;
  1519. bool headers_done;
  1520. char base64_bit[4];
  1521. int base64_chars = 0;
  1522. ret = snew(struct sshcom_key);
  1523. ret->comment[0] = '\0';
  1524. ret->keyblob = strbuf_new_nm();
  1525. fp = f_open(filename, "r", false);
  1526. if (!fp) {
  1527. errmsg = "unable to open key file";
  1528. goto error;
  1529. }
  1530. if (!(line = fgetline(fp))) {
  1531. errmsg = "unexpected end of file";
  1532. goto error;
  1533. }
  1534. strip_crlf(line);
  1535. if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
  1536. errmsg = "file does not begin with ssh.com key header";
  1537. goto error;
  1538. }
  1539. smemclr(line, strlen(line));
  1540. sfree(line);
  1541. line = NULL;
  1542. headers_done = false;
  1543. while (1) {
  1544. if (!(line = fgetline(fp))) {
  1545. errmsg = "unexpected end of file";
  1546. goto error;
  1547. }
  1548. strip_crlf(line);
  1549. if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
  1550. sfree(line);
  1551. line = NULL;
  1552. break; /* done */
  1553. }
  1554. if ((p = strchr(line, ':')) != NULL) {
  1555. if (headers_done) {
  1556. errmsg = "header found in body of key data";
  1557. goto error;
  1558. }
  1559. *p++ = '\0';
  1560. while (*p && isspace((unsigned char)*p)) p++;
  1561. hdrstart = p - line;
  1562. /*
  1563. * Header lines can end in a trailing backslash for
  1564. * continuation.
  1565. */
  1566. len = hdrstart + strlen(line+hdrstart);
  1567. assert(!line[len]);
  1568. while (line[len-1] == '\\') {
  1569. char *line2;
  1570. int line2len;
  1571. line2 = fgetline(fp);
  1572. if (!line2) {
  1573. errmsg = "unexpected end of file";
  1574. goto error;
  1575. }
  1576. strip_crlf(line2);
  1577. line2len = strlen(line2);
  1578. line = sresize(line, len + line2len + 1, char);
  1579. strcpy(line + len - 1, line2);
  1580. len += line2len - 1;
  1581. assert(!line[len]);
  1582. smemclr(line2, strlen(line2));
  1583. sfree(line2);
  1584. line2 = NULL;
  1585. }
  1586. p = line + hdrstart;
  1587. strip_crlf(p);
  1588. if (!strcmp(line, "Comment")) {
  1589. /* Strip quotes in comment if present. */
  1590. if (p[0] == '"' && p[strlen(p)-1] == '"') {
  1591. p++;
  1592. p[strlen(p)-1] = '\0';
  1593. }
  1594. strncpy(ret->comment, p, sizeof(ret->comment));
  1595. ret->comment[sizeof(ret->comment)-1] = '\0';
  1596. }
  1597. } else {
  1598. headers_done = true;
  1599. p = line;
  1600. while (isbase64(*p)) {
  1601. base64_bit[base64_chars++] = *p;
  1602. if (base64_chars == 4) {
  1603. unsigned char out[3];
  1604. base64_chars = 0;
  1605. len = base64_decode_atom(base64_bit, out);
  1606. if (len <= 0) {
  1607. errmsg = "invalid base64 encoding";
  1608. goto error;
  1609. }
  1610. put_data(ret->keyblob, out, len);
  1611. }
  1612. p++;
  1613. }
  1614. }
  1615. smemclr(line, strlen(line));
  1616. sfree(line);
  1617. line = NULL;
  1618. }
  1619. if (ret->keyblob->len == 0) {
  1620. errmsg = "key body not present";
  1621. goto error;
  1622. }
  1623. fclose(fp);
  1624. if (errmsg_p) *errmsg_p = NULL;
  1625. return ret;
  1626. error:
  1627. if (fp)
  1628. fclose(fp);
  1629. if (line) {
  1630. smemclr(line, strlen(line));
  1631. sfree(line);
  1632. line = NULL;
  1633. }
  1634. if (ret) {
  1635. strbuf_free(ret->keyblob);
  1636. smemclr(ret, sizeof(*ret));
  1637. sfree(ret);
  1638. }
  1639. if (errmsg_p) *errmsg_p = errmsg;
  1640. return NULL;
  1641. }
  1642. static bool sshcom_encrypted(const Filename *filename, char **comment)
  1643. {
  1644. struct sshcom_key *key = load_sshcom_key(filename, NULL);
  1645. BinarySource src[1];
  1646. ptrlen str;
  1647. bool answer = false;
  1648. *comment = NULL;
  1649. if (!key)
  1650. goto done;
  1651. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(key->keyblob));
  1652. if (get_uint32(src) != SSHCOM_MAGIC_NUMBER)
  1653. goto done; /* key is invalid */
  1654. get_uint32(src); /* skip length field */
  1655. get_string(src); /* skip key type */
  1656. str = get_string(src); /* cipher type */
  1657. if (get_err(src))
  1658. goto done; /* key is invalid */
  1659. if (!ptrlen_eq_string(str, "none"))
  1660. answer = true;
  1661. done:
  1662. if (key) {
  1663. *comment = dupstr(key->comment);
  1664. strbuf_free(key->keyblob);
  1665. smemclr(key, sizeof(*key));
  1666. sfree(key);
  1667. } else {
  1668. *comment = dupstr("");
  1669. }
  1670. return answer;
  1671. }
  1672. void BinarySink_put_mp_sshcom_from_string(BinarySink *bs, ptrlen str)
  1673. {
  1674. const unsigned char *bytes = (const unsigned char *)str.ptr;
  1675. size_t nbytes = str.len;
  1676. int bits = nbytes * 8 - 1;
  1677. while (bits > 0) {
  1678. if (*bytes & (1 << (bits & 7)))
  1679. break;
  1680. if (!(bits-- & 7))
  1681. bytes++, nbytes--;
  1682. }
  1683. put_uint32(bs, bits+1);
  1684. put_data(bs, bytes, nbytes);
  1685. }
  1686. #define put_mp_sshcom_from_string(bs, str) \
  1687. BinarySink_put_mp_sshcom_from_string(BinarySink_UPCAST(bs), str)
  1688. static ptrlen BinarySource_get_mp_sshcom_as_string(BinarySource *src)
  1689. {
  1690. unsigned bits = get_uint32(src);
  1691. return get_data(src, (bits + 7) / 8);
  1692. }
  1693. #define get_mp_sshcom_as_string(bs) \
  1694. BinarySource_get_mp_sshcom_as_string(BinarySource_UPCAST(bs))
  1695. static void sshcom_derivekey(ptrlen passphrase, uint8_t *keybuf)
  1696. {
  1697. /*
  1698. * Derive the encryption key for an ssh.com key file from the
  1699. * passphrase and iv/salt:
  1700. *
  1701. * - let block A equal MD5(passphrase)
  1702. * - let block B equal MD5(passphrase || A)
  1703. * - block C would be MD5(passphrase || A || B) and so on
  1704. * - encryption key is the first N bytes of A || B
  1705. */
  1706. ssh_hash *h;
  1707. h = ssh_hash_new(&ssh_md5);
  1708. put_datapl(h, passphrase);
  1709. ssh_hash_final(ssh_hash_copy(h), keybuf);
  1710. put_data(h, keybuf, 16);
  1711. ssh_hash_final(h, keybuf + 16);
  1712. }
  1713. static ssh2_userkey *sshcom_read(
  1714. const Filename *filename, const char *passphrase, const char **errmsg_p)
  1715. {
  1716. struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
  1717. const char *errmsg;
  1718. BinarySource src[1];
  1719. ptrlen str, ciphertext;
  1720. int publen;
  1721. const char prefix_rsa[] = "if-modn{sign{rsa";
  1722. const char prefix_dsa[] = "dl-modp{sign{dsa";
  1723. enum { RSA, DSA } type;
  1724. bool encrypted;
  1725. ssh2_userkey *ret = NULL, *retkey;
  1726. const ssh_keyalg *alg;
  1727. strbuf *blob = NULL;
  1728. if (!key)
  1729. return NULL;
  1730. BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(key->keyblob));
  1731. if (get_uint32(src) != SSHCOM_MAGIC_NUMBER) {
  1732. errmsg = "key does not begin with magic number";
  1733. goto error;
  1734. }
  1735. get_uint32(src); /* skip length field */
  1736. /*
  1737. * Determine the key type.
  1738. */
  1739. str = get_string(src);
  1740. if (str.len > sizeof(prefix_rsa) - 1 &&
  1741. !memcmp(str.ptr, prefix_rsa, sizeof(prefix_rsa) - 1)) {
  1742. type = RSA;
  1743. } else if (str.len > sizeof(prefix_dsa) - 1 &&
  1744. !memcmp(str.ptr, prefix_dsa, sizeof(prefix_dsa) - 1)) {
  1745. type = DSA;
  1746. } else {
  1747. errmsg = "key is of unknown type";
  1748. goto error;
  1749. }
  1750. /*
  1751. * Determine the cipher type.
  1752. */
  1753. str = get_string(src);
  1754. if (ptrlen_eq_string(str, "none"))
  1755. encrypted = false;
  1756. else if (ptrlen_eq_string(str, "3des-cbc"))
  1757. encrypted = true;
  1758. else {
  1759. errmsg = "key encryption is of unknown type";
  1760. goto error;
  1761. }
  1762. /*
  1763. * Get hold of the encrypted part of the key.
  1764. */
  1765. ciphertext = get_string(src);
  1766. if (ciphertext.len == 0) {
  1767. errmsg = "no key data found";
  1768. goto error;
  1769. }
  1770. /*
  1771. * Decrypt it if necessary.
  1772. */
  1773. if (encrypted) {
  1774. /*
  1775. * Derive encryption key from passphrase and iv/salt:
  1776. *
  1777. * - let block A equal MD5(passphrase)
  1778. * - let block B equal MD5(passphrase || A)
  1779. * - block C would be MD5(passphrase || A || B) and so on
  1780. * - encryption key is the first N bytes of A || B
  1781. */
  1782. unsigned char keybuf[32], iv[8];
  1783. if (ciphertext.len % 8 != 0) {
  1784. errmsg = "encrypted part of key is not a multiple of cipher block"
  1785. " size";
  1786. goto error;
  1787. }
  1788. sshcom_derivekey(ptrlen_from_asciz(passphrase), keybuf);
  1789. /*
  1790. * Now decrypt the key blob in place (casting away const from
  1791. * ciphertext being a ptrlen).
  1792. */
  1793. memset(iv, 0, sizeof(iv));
  1794. des3_decrypt_pubkey_ossh(keybuf, iv,
  1795. (char *)ciphertext.ptr, ciphertext.len);
  1796. smemclr(keybuf, sizeof(keybuf));
  1797. /*
  1798. * Hereafter we return WRONG_PASSPHRASE for any parsing
  1799. * error. (But only if we've just tried to decrypt it!
  1800. * Returning WRONG_PASSPHRASE for an unencrypted key is
  1801. * automatic doom.)
  1802. */
  1803. if (encrypted)
  1804. ret = SSH2_WRONG_PASSPHRASE;
  1805. }
  1806. /*
  1807. * Expect the ciphertext to be formatted as a containing string,
  1808. * and reinitialise src to start parsing the inside of that string.
  1809. */
  1810. BinarySource_BARE_INIT_PL(src, ciphertext);
  1811. str = get_string(src);
  1812. if (get_err(src)) {
  1813. errmsg = "containing string was ill-formed";
  1814. goto error;
  1815. }
  1816. BinarySource_BARE_INIT_PL(src, str);
  1817. /*
  1818. * Now we break down into RSA versus DSA. In either case we'll
  1819. * construct public and private blobs in our own format, and
  1820. * end up feeding them to ssh_key_new_priv().
  1821. */
  1822. blob = strbuf_new_nm();
  1823. if (type == RSA) {
  1824. ptrlen n, e, d, u, p, q;
  1825. e = get_mp_sshcom_as_string(src);
  1826. d = get_mp_sshcom_as_string(src);
  1827. n = get_mp_sshcom_as_string(src);
  1828. u = get_mp_sshcom_as_string(src);
  1829. p = get_mp_sshcom_as_string(src);
  1830. q = get_mp_sshcom_as_string(src);
  1831. if (get_err(src)) {
  1832. errmsg = "key data did not contain six integers";
  1833. goto error;
  1834. }
  1835. alg = &ssh_rsa;
  1836. put_stringz(blob, "ssh-rsa");
  1837. put_mp_ssh2_from_string(blob, e);
  1838. put_mp_ssh2_from_string(blob, n);
  1839. publen = blob->len;
  1840. put_mp_ssh2_from_string(blob, d);
  1841. put_mp_ssh2_from_string(blob, q);
  1842. put_mp_ssh2_from_string(blob, p);
  1843. put_mp_ssh2_from_string(blob, u);
  1844. } else {
  1845. ptrlen p, q, g, x, y;
  1846. assert(type == DSA); /* the only other option from the if above */
  1847. if (get_uint32(src) != 0) {
  1848. errmsg = "predefined DSA parameters not supported";
  1849. goto error;
  1850. }
  1851. p = get_mp_sshcom_as_string(src);
  1852. g = get_mp_sshcom_as_string(src);
  1853. q = get_mp_sshcom_as_string(src);
  1854. y = get_mp_sshcom_as_string(src);
  1855. x = get_mp_sshcom_as_string(src);
  1856. if (get_err(src)) {
  1857. errmsg = "key data did not contain five integers";
  1858. goto error;
  1859. }
  1860. alg = &ssh_dss;
  1861. put_stringz(blob, "ssh-dss");
  1862. put_mp_ssh2_from_string(blob, p);
  1863. put_mp_ssh2_from_string(blob, q);
  1864. put_mp_ssh2_from_string(blob, g);
  1865. put_mp_ssh2_from_string(blob, y);
  1866. publen = blob->len;
  1867. put_mp_ssh2_from_string(blob, x);
  1868. }
  1869. retkey = snew(ssh2_userkey);
  1870. retkey->key = ssh_key_new_priv(
  1871. alg, make_ptrlen(blob->u, publen),
  1872. make_ptrlen(blob->u + publen, blob->len - publen));
  1873. if (!retkey->key) {
  1874. sfree(retkey);
  1875. errmsg = "unable to create key data structure";
  1876. goto error;
  1877. }
  1878. retkey->comment = dupstr(key->comment);
  1879. errmsg = NULL; /* no error */
  1880. ret = retkey;
  1881. error:
  1882. if (blob) {
  1883. strbuf_free(blob);
  1884. }
  1885. strbuf_free(key->keyblob);
  1886. smemclr(key, sizeof(*key));
  1887. sfree(key);
  1888. if (errmsg_p) *errmsg_p = errmsg;
  1889. return ret;
  1890. }
  1891. static bool sshcom_write(
  1892. const Filename *filename, ssh2_userkey *key, const char *passphrase)
  1893. {
  1894. strbuf *pubblob, *privblob, *outblob;
  1895. ptrlen numbers[6];
  1896. int nnumbers, lenpos, i;
  1897. bool initial_zero;
  1898. BinarySource src[1];
  1899. const char *type;
  1900. char *ciphertext;
  1901. int cipherlen;
  1902. bool ret = false;
  1903. FILE *fp;
  1904. /*
  1905. * Fetch the key blobs.
  1906. */
  1907. pubblob = strbuf_new();
  1908. ssh_key_public_blob(key->key, BinarySink_UPCAST(pubblob));
  1909. privblob = strbuf_new_nm();
  1910. ssh_key_private_blob(key->key, BinarySink_UPCAST(privblob));
  1911. outblob = NULL;
  1912. /*
  1913. * Find the sequence of integers to be encoded into the OpenSSH
  1914. * key blob, and also decide on the header line.
  1915. */
  1916. if (ssh_key_alg(key->key) == &ssh_rsa) {
  1917. ptrlen n, e, d, p, q, iqmp;
  1918. /*
  1919. * These blobs were generated from inside PuTTY, so we needn't
  1920. * treat them as untrusted.
  1921. */
  1922. BinarySource_BARE_INIT(src, pubblob->u, pubblob->len);
  1923. get_string(src); /* skip algorithm name */
  1924. e = get_string(src);
  1925. n = get_string(src);
  1926. BinarySource_BARE_INIT(src, privblob->u, privblob->len);
  1927. d = get_string(src);
  1928. p = get_string(src);
  1929. q = get_string(src);
  1930. iqmp = get_string(src);
  1931. assert(!get_err(src)); /* can't go wrong */
  1932. numbers[0] = e;
  1933. numbers[1] = d;
  1934. numbers[2] = n;
  1935. numbers[3] = iqmp;
  1936. numbers[4] = q;
  1937. numbers[5] = p;
  1938. nnumbers = 6;
  1939. initial_zero = false;
  1940. type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
  1941. } else if (ssh_key_alg(key->key) == &ssh_dss) {
  1942. ptrlen p, q, g, y, x;
  1943. /*
  1944. * These blobs were generated from inside PuTTY, so we needn't
  1945. * treat them as untrusted.
  1946. */
  1947. BinarySource_BARE_INIT(src, pubblob->u, pubblob->len);
  1948. get_string(src); /* skip algorithm name */
  1949. p = get_string(src);
  1950. q = get_string(src);
  1951. g = get_string(src);
  1952. y = get_string(src);
  1953. BinarySource_BARE_INIT(src, privblob->u, privblob->len);
  1954. x = get_string(src);
  1955. assert(!get_err(src)); /* can't go wrong */
  1956. numbers[0] = p;
  1957. numbers[1] = g;
  1958. numbers[2] = q;
  1959. numbers[3] = y;
  1960. numbers[4] = x;
  1961. nnumbers = 5;
  1962. initial_zero = true;
  1963. type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
  1964. } else {
  1965. goto error; /* unsupported key type */
  1966. }
  1967. outblob = strbuf_new_nm();
  1968. /*
  1969. * Create the unencrypted key blob.
  1970. */
  1971. put_uint32(outblob, SSHCOM_MAGIC_NUMBER);
  1972. put_uint32(outblob, 0); /* length field, fill in later */
  1973. put_stringz(outblob, type);
  1974. put_stringz(outblob, passphrase ? "3des-cbc" : "none");
  1975. lenpos = outblob->len; /* remember this position */
  1976. put_uint32(outblob, 0); /* encrypted-blob size */
  1977. put_uint32(outblob, 0); /* encrypted-payload size */
  1978. if (initial_zero)
  1979. put_uint32(outblob, 0);
  1980. for (i = 0; i < nnumbers; i++)
  1981. put_mp_sshcom_from_string(outblob, numbers[i]);
  1982. /* Now wrap up the encrypted payload. */
  1983. PUT_32BIT_MSB_FIRST(outblob->s + lenpos + 4,
  1984. outblob->len - (lenpos + 8));
  1985. /* Pad encrypted blob to a multiple of cipher block size. */
  1986. if (passphrase) {
  1987. int padding = -(ssize_t)(outblob->len - (lenpos+4)) & 7; // WINSCP
  1988. uint8_t padding_buf[8];
  1989. random_read(padding_buf, padding);
  1990. put_data(outblob, padding_buf, padding);
  1991. }
  1992. ciphertext = outblob->s + lenpos + 4;
  1993. cipherlen = outblob->len - (lenpos + 4);
  1994. assert(!passphrase || cipherlen % 8 == 0);
  1995. /* Wrap up the encrypted blob string. */
  1996. PUT_32BIT_MSB_FIRST(outblob->s + lenpos, cipherlen);
  1997. /* And finally fill in the total length field. */
  1998. PUT_32BIT_MSB_FIRST(outblob->s + 4, outblob->len);
  1999. /*
  2000. * Encrypt the key.
  2001. */
  2002. if (passphrase) {
  2003. unsigned char keybuf[32], iv[8];
  2004. sshcom_derivekey(ptrlen_from_asciz(passphrase), keybuf);
  2005. /*
  2006. * Now decrypt the key blob.
  2007. */
  2008. memset(iv, 0, sizeof(iv));
  2009. des3_encrypt_pubkey_ossh(keybuf, iv, ciphertext, cipherlen);
  2010. smemclr(keybuf, sizeof(keybuf));
  2011. }
  2012. /*
  2013. * And save it. We'll use Unix line endings just in case it's
  2014. * subsequently transferred in binary mode.
  2015. */
  2016. fp = f_open(filename, "wb", true); /* ensure Unix line endings */
  2017. if (!fp)
  2018. goto error;
  2019. fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
  2020. fprintf(fp, "Comment: \"");
  2021. /*
  2022. * Comment header is broken with backslash-newline if it goes
  2023. * over 70 chars. Although it's surrounded by quotes, it
  2024. * _doesn't_ escape backslashes or quotes within the string.
  2025. * Don't ask me, I didn't design it.
  2026. */
  2027. {
  2028. int slen = 60; /* starts at 60 due to "Comment: " */
  2029. char *c = key->comment;
  2030. while ((int)strlen(c) > slen) {
  2031. fprintf(fp, "%.*s\\\n", slen, c);
  2032. c += slen;
  2033. slen = 70; /* allow 70 chars on subsequent lines */
  2034. }
  2035. fprintf(fp, "%s\"\n", c);
  2036. }
  2037. base64_encode(fp, outblob->u, outblob->len, 70);
  2038. fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
  2039. fclose(fp);
  2040. ret = true;
  2041. error:
  2042. if (outblob)
  2043. strbuf_free(outblob);
  2044. if (privblob)
  2045. strbuf_free(privblob);
  2046. if (pubblob)
  2047. strbuf_free(pubblob);
  2048. return ret;
  2049. }