import.c 71 KB

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