import.c 71 KB

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