import.c 82 KB

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