import.c 71 KB

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