import.c 68 KB

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