import.c 70 KB

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