import.c 71 KB

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