import.c 71 KB

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