import.c 71 KB

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