import.c 69 KB

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