import.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  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_encrypted(const Filename *filename);
  13. struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
  14. const char **errmsg_p);
  15. int openssh_write(const Filename *filename, struct ssh2_userkey *key,
  16. char *passphrase);
  17. int sshcom_encrypted(const Filename *filename, char **comment);
  18. struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
  19. const char **errmsg_p);
  20. int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
  21. char *passphrase);
  22. /*
  23. * Given a key type, determine whether we know how to import it.
  24. */
  25. int import_possible(int type)
  26. {
  27. if (type == SSH_KEYTYPE_OPENSSH)
  28. return 1;
  29. if (type == SSH_KEYTYPE_SSHCOM)
  30. return 1;
  31. return 0;
  32. }
  33. /*
  34. * Given a key type, determine what native key type
  35. * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
  36. * we've imported it.
  37. */
  38. int import_target_type(int type)
  39. {
  40. /*
  41. * There are no known foreign SSH-1 key formats.
  42. */
  43. return SSH_KEYTYPE_SSH2;
  44. }
  45. /*
  46. * Determine whether a foreign key is encrypted.
  47. */
  48. int import_encrypted(const Filename *filename, int type, char **comment)
  49. {
  50. if (type == SSH_KEYTYPE_OPENSSH) {
  51. /* OpenSSH doesn't do key comments */
  52. *comment = dupstr(filename_to_str(filename));
  53. return openssh_encrypted(filename);
  54. }
  55. if (type == SSH_KEYTYPE_SSHCOM) {
  56. return sshcom_encrypted(filename, comment);
  57. }
  58. return 0;
  59. }
  60. /*
  61. * Import an SSH-1 key.
  62. */
  63. int import_ssh1(const Filename *filename, int type,
  64. struct RSAKey *key, char *passphrase, const char **errmsg_p)
  65. {
  66. return 0;
  67. }
  68. /*
  69. * Import an SSH-2 key.
  70. */
  71. struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
  72. char *passphrase, const char **errmsg_p)
  73. {
  74. if (type == SSH_KEYTYPE_OPENSSH)
  75. return openssh_read(filename, passphrase, errmsg_p);
  76. if (type == SSH_KEYTYPE_SSHCOM)
  77. return sshcom_read(filename, passphrase, errmsg_p);
  78. return NULL;
  79. }
  80. /*
  81. * Export an SSH-1 key.
  82. */
  83. int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
  84. char *passphrase)
  85. {
  86. return 0;
  87. }
  88. /*
  89. * Export an SSH-2 key.
  90. */
  91. int export_ssh2(const Filename *filename, int type,
  92. struct ssh2_userkey *key, char *passphrase)
  93. {
  94. if (type == SSH_KEYTYPE_OPENSSH)
  95. return openssh_write(filename, key, passphrase);
  96. if (type == SSH_KEYTYPE_SSHCOM)
  97. return sshcom_write(filename, key, passphrase);
  98. return 0;
  99. }
  100. /*
  101. * Strip trailing CRs and LFs at the end of a line of text.
  102. */
  103. void strip_crlf(char *str)
  104. {
  105. char *p = str + strlen(str);
  106. while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
  107. *--p = '\0';
  108. }
  109. /* ----------------------------------------------------------------------
  110. * Helper routines. (The base64 ones are defined in sshpubk.c.)
  111. */
  112. #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
  113. ((c) >= 'a' && (c) <= 'z') || \
  114. ((c) >= '0' && (c) <= '9') || \
  115. (c) == '+' || (c) == '/' || (c) == '=' \
  116. )
  117. /*
  118. * Read an ASN.1/BER identifier and length pair.
  119. *
  120. * Flags are a combination of the #defines listed below.
  121. *
  122. * Returns -1 if unsuccessful; otherwise returns the number of
  123. * bytes used out of the source data.
  124. */
  125. /* ASN.1 tag classes. */
  126. #define ASN1_CLASS_UNIVERSAL (0 << 6)
  127. #define ASN1_CLASS_APPLICATION (1 << 6)
  128. #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
  129. #define ASN1_CLASS_PRIVATE (3 << 6)
  130. #define ASN1_CLASS_MASK (3 << 6)
  131. /* Primitive versus constructed bit. */
  132. #define ASN1_CONSTRUCTED (1 << 5)
  133. static int ber_read_id_len(void *source, int sourcelen,
  134. int *id, int *length, int *flags)
  135. {
  136. unsigned char *p = (unsigned char *) source;
  137. if (sourcelen == 0)
  138. return -1;
  139. *flags = (*p & 0xE0);
  140. if ((*p & 0x1F) == 0x1F) {
  141. *id = 0;
  142. while (*p & 0x80) {
  143. p++, sourcelen--;
  144. if (sourcelen == 0)
  145. return -1;
  146. *id = (*id << 7) | (*p & 0x7F);
  147. }
  148. p++, sourcelen--;
  149. } else {
  150. *id = *p & 0x1F;
  151. p++, sourcelen--;
  152. }
  153. if (sourcelen == 0)
  154. return -1;
  155. if (*p & 0x80) {
  156. int n = *p & 0x7F;
  157. p++, sourcelen--;
  158. if (sourcelen < n)
  159. return -1;
  160. *length = 0;
  161. while (n--)
  162. *length = (*length << 8) | (*p++);
  163. sourcelen -= n;
  164. } else {
  165. *length = *p;
  166. p++, sourcelen--;
  167. }
  168. return p - (unsigned char *) source;
  169. }
  170. /*
  171. * Write an ASN.1/BER identifier and length pair. Returns the
  172. * number of bytes consumed. Assumes dest contains enough space.
  173. * Will avoid writing anything if dest is NULL, but still return
  174. * amount of space required.
  175. */
  176. static int ber_write_id_len(void *dest, int id, int length, int flags)
  177. {
  178. unsigned char *d = (unsigned char *)dest;
  179. int len = 0;
  180. if (id <= 30) {
  181. /*
  182. * Identifier is one byte.
  183. */
  184. len++;
  185. if (d) *d++ = id | flags;
  186. } else {
  187. int n;
  188. /*
  189. * Identifier is multiple bytes: the first byte is 11111
  190. * plus the flags, and subsequent bytes encode the value of
  191. * the identifier, 7 bits at a time, with the top bit of
  192. * each byte 1 except the last one which is 0.
  193. */
  194. len++;
  195. if (d) *d++ = 0x1F | flags;
  196. for (n = 1; (id >> (7*n)) > 0; n++)
  197. continue; /* count the bytes */
  198. while (n--) {
  199. len++;
  200. if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
  201. }
  202. }
  203. if (length < 128) {
  204. /*
  205. * Length is one byte.
  206. */
  207. len++;
  208. if (d) *d++ = length;
  209. } else {
  210. int n;
  211. /*
  212. * Length is multiple bytes. The first is 0x80 plus the
  213. * number of subsequent bytes, and the subsequent bytes
  214. * encode the actual length.
  215. */
  216. for (n = 1; (length >> (8*n)) > 0; n++)
  217. continue; /* count the bytes */
  218. len++;
  219. if (d) *d++ = 0x80 | n;
  220. while (n--) {
  221. len++;
  222. if (d) *d++ = (length >> (8*n)) & 0xFF;
  223. }
  224. }
  225. return len;
  226. }
  227. static int put_string(void *target, void *data, int len)
  228. {
  229. unsigned char *d = (unsigned char *)target;
  230. PUT_32BIT(d, len);
  231. memcpy(d+4, data, len);
  232. return len+4;
  233. }
  234. static int put_mp(void *target, void *data, int len)
  235. {
  236. unsigned char *d = (unsigned char *)target;
  237. unsigned char *i = (unsigned char *)data;
  238. if (*i & 0x80) {
  239. PUT_32BIT(d, len+1);
  240. d[4] = 0;
  241. memcpy(d+5, data, len);
  242. return len+5;
  243. } else {
  244. PUT_32BIT(d, len);
  245. memcpy(d+4, data, len);
  246. return len+4;
  247. }
  248. }
  249. /* Simple structure to point to an mp-int within a blob. */
  250. struct mpint_pos { void *start; int bytes; };
  251. static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
  252. {
  253. int bytes;
  254. unsigned char *d = (unsigned char *) data;
  255. if (len < 4)
  256. goto error;
  257. bytes = toint(GET_32BIT(d));
  258. if (bytes < 0 || len-4 < bytes)
  259. goto error;
  260. ret->start = d + 4;
  261. ret->bytes = bytes;
  262. return bytes+4;
  263. error:
  264. ret->start = NULL;
  265. ret->bytes = -1;
  266. return len; /* ensure further calls fail as well */
  267. }
  268. /* ----------------------------------------------------------------------
  269. * Code to read and write OpenSSH private keys.
  270. */
  271. enum { OSSH_DSA, OSSH_RSA };
  272. enum { OSSH_ENC_3DES, OSSH_ENC_AES };
  273. struct openssh_key {
  274. int type;
  275. int encrypted, encryption;
  276. char iv[32];
  277. unsigned char *keyblob;
  278. int keyblob_len, keyblob_size;
  279. };
  280. static struct openssh_key *load_openssh_key(const Filename *filename,
  281. const char **errmsg_p)
  282. {
  283. struct openssh_key *ret;
  284. FILE *fp = NULL;
  285. char *line = NULL;
  286. char *errmsg, *p;
  287. int headers_done;
  288. char base64_bit[4];
  289. int base64_chars = 0;
  290. ret = snew(struct openssh_key);
  291. ret->keyblob = NULL;
  292. ret->keyblob_len = ret->keyblob_size = 0;
  293. ret->encrypted = 0;
  294. memset(ret->iv, 0, sizeof(ret->iv));
  295. fp = f_open(filename, "r", FALSE);
  296. if (!fp) {
  297. errmsg = "unable to open key file";
  298. goto error;
  299. }
  300. if (!(line = fgetline(fp))) {
  301. errmsg = "unexpected end of file";
  302. goto error;
  303. }
  304. strip_crlf(line);
  305. if (0 != strncmp(line, "-----BEGIN ", 11) ||
  306. 0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
  307. errmsg = "file does not begin with OpenSSH key header";
  308. goto error;
  309. }
  310. if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----"))
  311. ret->type = OSSH_RSA;
  312. else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----"))
  313. ret->type = OSSH_DSA;
  314. else {
  315. errmsg = "unrecognised key type";
  316. goto error;
  317. }
  318. smemclr(line, strlen(line));
  319. sfree(line);
  320. line = NULL;
  321. headers_done = 0;
  322. while (1) {
  323. if (!(line = fgetline(fp))) {
  324. errmsg = "unexpected end of file";
  325. goto error;
  326. }
  327. strip_crlf(line);
  328. if (0 == strncmp(line, "-----END ", 9) &&
  329. 0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
  330. sfree(line);
  331. line = NULL;
  332. break; /* done */
  333. }
  334. if ((p = strchr(line, ':')) != NULL) {
  335. if (headers_done) {
  336. errmsg = "header found in body of key data";
  337. goto error;
  338. }
  339. *p++ = '\0';
  340. while (*p && isspace((unsigned char)*p)) p++;
  341. if (!strcmp(line, "Proc-Type")) {
  342. if (p[0] != '4' || p[1] != ',') {
  343. errmsg = "Proc-Type is not 4 (only 4 is supported)";
  344. goto error;
  345. }
  346. p += 2;
  347. if (!strcmp(p, "ENCRYPTED"))
  348. ret->encrypted = 1;
  349. } else if (!strcmp(line, "DEK-Info")) {
  350. int i, j, ivlen;
  351. if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
  352. ret->encryption = OSSH_ENC_3DES;
  353. ivlen = 8;
  354. } else if (!strncmp(p, "AES-128-CBC,", 12)) {
  355. ret->encryption = OSSH_ENC_AES;
  356. ivlen = 16;
  357. } else {
  358. errmsg = "unsupported cipher";
  359. goto error;
  360. }
  361. p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
  362. for (i = 0; i < ivlen; i++) {
  363. if (1 != sscanf(p, "%2x", &j)) {
  364. errmsg = "expected more iv data in DEK-Info";
  365. goto error;
  366. }
  367. ret->iv[i] = j;
  368. p += 2;
  369. }
  370. if (*p) {
  371. errmsg = "more iv data than expected in DEK-Info";
  372. goto error;
  373. }
  374. }
  375. } else {
  376. headers_done = 1;
  377. p = line;
  378. while (isbase64(*p)) {
  379. base64_bit[base64_chars++] = *p;
  380. if (base64_chars == 4) {
  381. unsigned char out[3];
  382. int len;
  383. base64_chars = 0;
  384. len = base64_decode_atom(base64_bit, out);
  385. if (len <= 0) {
  386. errmsg = "invalid base64 encoding";
  387. goto error;
  388. }
  389. if (ret->keyblob_len + len > ret->keyblob_size) {
  390. ret->keyblob_size = ret->keyblob_len + len + 256;
  391. ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
  392. unsigned char);
  393. }
  394. memcpy(ret->keyblob + ret->keyblob_len, out, len);
  395. ret->keyblob_len += len;
  396. smemclr(out, sizeof(out));
  397. }
  398. p++;
  399. }
  400. }
  401. smemclr(line, strlen(line));
  402. sfree(line);
  403. line = NULL;
  404. }
  405. fclose(fp);
  406. fp = NULL;
  407. if (ret->keyblob_len == 0 || !ret->keyblob) {
  408. errmsg = "key body not present";
  409. goto error;
  410. }
  411. if (ret->encrypted && ret->keyblob_len % 8 != 0) {
  412. errmsg = "encrypted key blob is not a multiple of cipher block size";
  413. goto error;
  414. }
  415. smemclr(base64_bit, sizeof(base64_bit));
  416. if (errmsg_p) *errmsg_p = NULL;
  417. return ret;
  418. error:
  419. if (line) {
  420. smemclr(line, strlen(line));
  421. sfree(line);
  422. line = NULL;
  423. }
  424. smemclr(base64_bit, sizeof(base64_bit));
  425. if (ret) {
  426. if (ret->keyblob) {
  427. smemclr(ret->keyblob, ret->keyblob_size);
  428. sfree(ret->keyblob);
  429. }
  430. smemclr(ret, sizeof(*ret));
  431. sfree(ret);
  432. }
  433. if (errmsg_p) *errmsg_p = errmsg;
  434. if (fp) fclose(fp);
  435. return NULL;
  436. }
  437. int openssh_encrypted(const Filename *filename)
  438. {
  439. struct openssh_key *key = load_openssh_key(filename, NULL);
  440. int ret;
  441. if (!key)
  442. return 0;
  443. ret = key->encrypted;
  444. smemclr(key->keyblob, key->keyblob_size);
  445. sfree(key->keyblob);
  446. smemclr(key, sizeof(*key));
  447. sfree(key);
  448. return ret;
  449. }
  450. struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
  451. const char **errmsg_p)
  452. {
  453. struct openssh_key *key = load_openssh_key(filename, errmsg_p);
  454. struct ssh2_userkey *retkey;
  455. unsigned char *p;
  456. int ret, id, len, flags;
  457. int i, num_integers;
  458. struct ssh2_userkey *retval = NULL;
  459. char *errmsg;
  460. unsigned char *blob;
  461. int blobsize = 0, blobptr, privptr;
  462. char *modptr = NULL;
  463. int modlen = 0;
  464. blob = NULL;
  465. if (!key)
  466. return NULL;
  467. if (key->encrypted) {
  468. /*
  469. * Derive encryption key from passphrase and iv/salt:
  470. *
  471. * - let block A equal MD5(passphrase || iv)
  472. * - let block B equal MD5(A || passphrase || iv)
  473. * - block C would be MD5(B || passphrase || iv) and so on
  474. * - encryption key is the first N bytes of A || B
  475. *
  476. * (Note that only 8 bytes of the iv are used for key
  477. * derivation, even when the key is encrypted with AES and
  478. * hence there are 16 bytes available.)
  479. */
  480. struct MD5Context md5c;
  481. unsigned char keybuf[32];
  482. MD5Init(&md5c);
  483. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  484. MD5Update(&md5c, (unsigned char *)key->iv, 8);
  485. MD5Final(keybuf, &md5c);
  486. MD5Init(&md5c);
  487. MD5Update(&md5c, keybuf, 16);
  488. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  489. MD5Update(&md5c, (unsigned char *)key->iv, 8);
  490. MD5Final(keybuf+16, &md5c);
  491. /*
  492. * Now decrypt the key blob.
  493. */
  494. if (key->encryption == OSSH_ENC_3DES)
  495. des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
  496. key->keyblob, key->keyblob_len);
  497. else {
  498. void *ctx;
  499. assert(key->encryption == OSSH_ENC_AES);
  500. ctx = aes_make_context();
  501. aes128_key(ctx, keybuf);
  502. aes_iv(ctx, (unsigned char *)key->iv);
  503. aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
  504. aes_free_context(ctx);
  505. }
  506. smemclr(&md5c, sizeof(md5c));
  507. smemclr(keybuf, sizeof(keybuf));
  508. }
  509. /*
  510. * Now we have a decrypted key blob, which contains an ASN.1
  511. * encoded private key. We must now untangle the ASN.1.
  512. *
  513. * We expect the whole key blob to be formatted as a SEQUENCE
  514. * (0x30 followed by a length code indicating that the rest of
  515. * the blob is part of the sequence). Within that SEQUENCE we
  516. * expect to see a bunch of INTEGERs. What those integers mean
  517. * depends on the key type:
  518. *
  519. * - For RSA, we expect the integers to be 0, n, e, d, p, q,
  520. * dmp1, dmq1, iqmp in that order. (The last three are d mod
  521. * (p-1), d mod (q-1), inverse of q mod p respectively.)
  522. *
  523. * - For DSA, we expect them to be 0, p, q, g, y, x in that
  524. * order.
  525. */
  526. p = key->keyblob;
  527. /* Expect the SEQUENCE header. Take its absence as a failure to
  528. * decrypt, if the key was encrypted. */
  529. ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
  530. p += ret;
  531. if (ret < 0 || id != 16) {
  532. errmsg = "ASN.1 decoding failure";
  533. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  534. goto error;
  535. }
  536. /* Expect a load of INTEGERs. */
  537. if (key->type == OSSH_RSA)
  538. num_integers = 9;
  539. else if (key->type == OSSH_DSA)
  540. num_integers = 6;
  541. else
  542. num_integers = 0; /* placate compiler warnings */
  543. /*
  544. * Space to create key blob in.
  545. */
  546. blobsize = 256+key->keyblob_len;
  547. blob = snewn(blobsize, unsigned char);
  548. PUT_32BIT(blob, 7);
  549. if (key->type == OSSH_DSA)
  550. memcpy(blob+4, "ssh-dss", 7);
  551. else if (key->type == OSSH_RSA)
  552. memcpy(blob+4, "ssh-rsa", 7);
  553. blobptr = 4+7;
  554. privptr = -1;
  555. for (i = 0; i < num_integers; i++) {
  556. ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
  557. &id, &len, &flags);
  558. p += ret;
  559. if (ret < 0 || id != 2 ||
  560. key->keyblob+key->keyblob_len-p < len) {
  561. errmsg = "ASN.1 decoding failure";
  562. retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
  563. goto error;
  564. }
  565. if (i == 0) {
  566. /*
  567. * The first integer should be zero always (I think
  568. * this is some sort of version indication).
  569. */
  570. if (len != 1 || p[0] != 0) {
  571. errmsg = "version number mismatch";
  572. goto error;
  573. }
  574. } else if (key->type == OSSH_RSA) {
  575. /*
  576. * Integers 1 and 2 go into the public blob but in the
  577. * opposite order; integers 3, 4, 5 and 8 go into the
  578. * private blob. The other two (6 and 7) are ignored.
  579. */
  580. if (i == 1) {
  581. /* Save the details for after we deal with number 2. */
  582. modptr = (char *)p;
  583. modlen = len;
  584. } else if (i != 6 && i != 7) {
  585. PUT_32BIT(blob+blobptr, len);
  586. memcpy(blob+blobptr+4, p, len);
  587. blobptr += 4+len;
  588. if (i == 2) {
  589. PUT_32BIT(blob+blobptr, modlen);
  590. memcpy(blob+blobptr+4, modptr, modlen);
  591. blobptr += 4+modlen;
  592. privptr = blobptr;
  593. }
  594. }
  595. } else if (key->type == OSSH_DSA) {
  596. /*
  597. * Integers 1-4 go into the public blob; integer 5 goes
  598. * into the private blob.
  599. */
  600. PUT_32BIT(blob+blobptr, len);
  601. memcpy(blob+blobptr+4, p, len);
  602. blobptr += 4+len;
  603. if (i == 4)
  604. privptr = blobptr;
  605. }
  606. /* Skip past the number. */
  607. p += len;
  608. }
  609. /*
  610. * Now put together the actual key. Simplest way to do this is
  611. * to assemble our own key blobs and feed them to the createkey
  612. * functions; this is a bit faffy but it does mean we get all
  613. * the sanity checks for free.
  614. */
  615. assert(privptr > 0); /* should have bombed by now if not */
  616. retkey = snew(struct ssh2_userkey);
  617. retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
  618. retkey->data = retkey->alg->createkey(blob, privptr,
  619. blob+privptr, blobptr-privptr);
  620. if (!retkey->data) {
  621. sfree(retkey);
  622. errmsg = "unable to create key data structure";
  623. goto error;
  624. }
  625. retkey->comment = dupstr("imported-openssh-key");
  626. errmsg = NULL; /* no error */
  627. retval = retkey;
  628. error:
  629. if (blob) {
  630. smemclr(blob, blobsize);
  631. sfree(blob);
  632. }
  633. smemclr(key->keyblob, key->keyblob_size);
  634. sfree(key->keyblob);
  635. smemclr(key, sizeof(*key));
  636. sfree(key);
  637. if (errmsg_p) *errmsg_p = errmsg;
  638. return retval;
  639. }
  640. int openssh_write(const Filename *filename, struct ssh2_userkey *key,
  641. char *passphrase)
  642. {
  643. unsigned char *pubblob, *privblob, *spareblob;
  644. int publen, privlen, sparelen = 0;
  645. unsigned char *outblob;
  646. int outlen;
  647. struct mpint_pos numbers[9];
  648. int nnumbers, pos, len, seqlen, i;
  649. char *header, *footer;
  650. char zero[1];
  651. unsigned char iv[8];
  652. int ret = 0;
  653. FILE *fp;
  654. /*
  655. * Fetch the key blobs.
  656. */
  657. pubblob = key->alg->public_blob(key->data, &publen);
  658. privblob = key->alg->private_blob(key->data, &privlen);
  659. spareblob = outblob = NULL;
  660. /*
  661. * Find the sequence of integers to be encoded into the OpenSSH
  662. * key blob, and also decide on the header line.
  663. */
  664. if (key->alg == &ssh_rsa) {
  665. int pos;
  666. struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
  667. Bignum bd, bp, bq, bdmp1, bdmq1;
  668. /*
  669. * These blobs were generated from inside PuTTY, so we needn't
  670. * treat them as untrusted.
  671. */
  672. pos = 4 + GET_32BIT(pubblob);
  673. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
  674. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
  675. pos = 0;
  676. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
  677. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
  678. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
  679. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
  680. assert(e.start && iqmp.start); /* can't go wrong */
  681. /* We also need d mod (p-1) and d mod (q-1). */
  682. bd = bignum_from_bytes(d.start, d.bytes);
  683. bp = bignum_from_bytes(p.start, p.bytes);
  684. bq = bignum_from_bytes(q.start, q.bytes);
  685. decbn(bp);
  686. decbn(bq);
  687. bdmp1 = bigmod(bd, bp);
  688. bdmq1 = bigmod(bd, bq);
  689. freebn(bd);
  690. freebn(bp);
  691. freebn(bq);
  692. dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
  693. dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
  694. sparelen = dmp1.bytes + dmq1.bytes;
  695. spareblob = snewn(sparelen, unsigned char);
  696. dmp1.start = spareblob;
  697. dmq1.start = spareblob + dmp1.bytes;
  698. for (i = 0; i < dmp1.bytes; i++)
  699. spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
  700. for (i = 0; i < dmq1.bytes; i++)
  701. spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
  702. freebn(bdmp1);
  703. freebn(bdmq1);
  704. numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
  705. numbers[1] = n;
  706. numbers[2] = e;
  707. numbers[3] = d;
  708. numbers[4] = p;
  709. numbers[5] = q;
  710. numbers[6] = dmp1;
  711. numbers[7] = dmq1;
  712. numbers[8] = iqmp;
  713. nnumbers = 9;
  714. header = "-----BEGIN RSA PRIVATE KEY-----\n";
  715. footer = "-----END RSA PRIVATE KEY-----\n";
  716. } else if (key->alg == &ssh_dss) {
  717. int pos;
  718. struct mpint_pos p, q, g, y, x;
  719. /*
  720. * These blobs were generated from inside PuTTY, so we needn't
  721. * treat them as untrusted.
  722. */
  723. pos = 4 + GET_32BIT(pubblob);
  724. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
  725. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
  726. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
  727. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
  728. pos = 0;
  729. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
  730. assert(y.start && x.start); /* can't go wrong */
  731. numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
  732. numbers[1] = p;
  733. numbers[2] = q;
  734. numbers[3] = g;
  735. numbers[4] = y;
  736. numbers[5] = x;
  737. nnumbers = 6;
  738. header = "-----BEGIN DSA PRIVATE KEY-----\n";
  739. footer = "-----END DSA PRIVATE KEY-----\n";
  740. } else {
  741. assert(0); /* zoinks! */
  742. exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
  743. }
  744. /*
  745. * Now count up the total size of the ASN.1 encoded integers,
  746. * so as to determine the length of the containing SEQUENCE.
  747. */
  748. len = 0;
  749. for (i = 0; i < nnumbers; i++) {
  750. len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
  751. len += numbers[i].bytes;
  752. }
  753. seqlen = len;
  754. /* Now add on the SEQUENCE header. */
  755. len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
  756. /* Round up to the cipher block size, ensuring we have at least one
  757. * byte of padding (see below). */
  758. outlen = len;
  759. if (passphrase)
  760. outlen = (outlen+8) &~ 7;
  761. /*
  762. * Now we know how big outblob needs to be. Allocate it.
  763. */
  764. outblob = snewn(outlen, unsigned char);
  765. /*
  766. * And write the data into it.
  767. */
  768. pos = 0;
  769. pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
  770. for (i = 0; i < nnumbers; i++) {
  771. pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
  772. memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
  773. pos += numbers[i].bytes;
  774. }
  775. /*
  776. * Padding on OpenSSH keys is deterministic. The number of
  777. * padding bytes is always more than zero, and always at most
  778. * the cipher block length. The value of each padding byte is
  779. * equal to the number of padding bytes. So a plaintext that's
  780. * an exact multiple of the block size will be padded with 08
  781. * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
  782. * plaintext one byte less than a multiple of the block size
  783. * will be padded with just 01.
  784. *
  785. * This enables the OpenSSL key decryption function to strip
  786. * off the padding algorithmically and return the unpadded
  787. * plaintext to the next layer: it looks at the final byte, and
  788. * then expects to find that many bytes at the end of the data
  789. * with the same value. Those are all removed and the rest is
  790. * returned.
  791. */
  792. assert(pos == len);
  793. while (pos < outlen) {
  794. outblob[pos++] = outlen - len;
  795. }
  796. /*
  797. * Encrypt the key.
  798. *
  799. * For the moment, we still encrypt our OpenSSH keys using
  800. * old-style 3DES.
  801. */
  802. if (passphrase) {
  803. /*
  804. * Invent an iv. Then derive encryption key from passphrase
  805. * and iv/salt:
  806. *
  807. * - let block A equal MD5(passphrase || iv)
  808. * - let block B equal MD5(A || passphrase || iv)
  809. * - block C would be MD5(B || passphrase || iv) and so on
  810. * - encryption key is the first N bytes of A || B
  811. */
  812. struct MD5Context md5c;
  813. unsigned char keybuf[32];
  814. for (i = 0; i < 8; i++) iv[i] = random_byte();
  815. MD5Init(&md5c);
  816. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  817. MD5Update(&md5c, iv, 8);
  818. MD5Final(keybuf, &md5c);
  819. MD5Init(&md5c);
  820. MD5Update(&md5c, keybuf, 16);
  821. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  822. MD5Update(&md5c, iv, 8);
  823. MD5Final(keybuf+16, &md5c);
  824. /*
  825. * Now encrypt the key blob.
  826. */
  827. des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
  828. smemclr(&md5c, sizeof(md5c));
  829. smemclr(keybuf, sizeof(keybuf));
  830. }
  831. /*
  832. * And save it. We'll use Unix line endings just in case it's
  833. * subsequently transferred in binary mode.
  834. */
  835. fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
  836. if (!fp)
  837. goto error;
  838. fputs(header, fp);
  839. if (passphrase) {
  840. fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
  841. for (i = 0; i < 8; i++)
  842. fprintf(fp, "%02X", iv[i]);
  843. fprintf(fp, "\n\n");
  844. }
  845. base64_encode(fp, outblob, outlen, 64);
  846. fputs(footer, fp);
  847. fclose(fp);
  848. ret = 1;
  849. error:
  850. if (outblob) {
  851. smemclr(outblob, outlen);
  852. sfree(outblob);
  853. }
  854. if (spareblob) {
  855. smemclr(spareblob, sparelen);
  856. sfree(spareblob);
  857. }
  858. if (privblob) {
  859. smemclr(privblob, privlen);
  860. sfree(privblob);
  861. }
  862. if (pubblob) {
  863. smemclr(pubblob, publen);
  864. sfree(pubblob);
  865. }
  866. return ret;
  867. }
  868. /* ----------------------------------------------------------------------
  869. * Code to read ssh.com private keys.
  870. */
  871. /*
  872. * The format of the base64 blob is largely SSH-2-packet-formatted,
  873. * except that mpints are a bit different: they're more like the
  874. * old SSH-1 mpint. You have a 32-bit bit count N, followed by
  875. * (N+7)/8 bytes of data.
  876. *
  877. * So. The blob contains:
  878. *
  879. * - uint32 0x3f6ff9eb (magic number)
  880. * - uint32 size (total blob size)
  881. * - string key-type (see below)
  882. * - string cipher-type (tells you if key is encrypted)
  883. * - string encrypted-blob
  884. *
  885. * (The first size field includes the size field itself and the
  886. * magic number before it. All other size fields are ordinary SSH-2
  887. * strings, so the size field indicates how much data is to
  888. * _follow_.)
  889. *
  890. * The encrypted blob, once decrypted, contains a single string
  891. * which in turn contains the payload. (This allows padding to be
  892. * added after that string while still making it clear where the
  893. * real payload ends. Also it probably makes for a reasonable
  894. * decryption check.)
  895. *
  896. * The payload blob, for an RSA key, contains:
  897. * - mpint e
  898. * - mpint d
  899. * - mpint n (yes, the public and private stuff is intermixed)
  900. * - mpint u (presumably inverse of p mod q)
  901. * - mpint p (p is the smaller prime)
  902. * - mpint q (q is the larger)
  903. *
  904. * For a DSA key, the payload blob contains:
  905. * - uint32 0
  906. * - mpint p
  907. * - mpint g
  908. * - mpint q
  909. * - mpint y
  910. * - mpint x
  911. *
  912. * Alternatively, if the parameters are `predefined', that
  913. * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
  914. * containing some predefined parameter specification. *shudder*,
  915. * but I doubt we'll encounter this in real life.
  916. *
  917. * The key type strings are ghastly. The RSA key I looked at had a
  918. * type string of
  919. *
  920. * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
  921. *
  922. * and the DSA key wasn't much better:
  923. *
  924. * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
  925. *
  926. * It isn't clear that these will always be the same. I think it
  927. * might be wise just to look at the `if-modn{sign{rsa' and
  928. * `dl-modp{sign{dsa' prefixes.
  929. *
  930. * Finally, the encryption. The cipher-type string appears to be
  931. * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
  932. * 3des-cbc (i.e. outer cbc rather than inner). The key is created
  933. * from the passphrase by means of yet another hashing faff:
  934. *
  935. * - first 16 bytes are MD5(passphrase)
  936. * - next 16 bytes are MD5(passphrase || first 16 bytes)
  937. * - if there were more, they'd be MD5(passphrase || first 32),
  938. * and so on.
  939. */
  940. #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
  941. struct sshcom_key {
  942. char comment[256]; /* allowing any length is overkill */
  943. unsigned char *keyblob;
  944. int keyblob_len, keyblob_size;
  945. };
  946. static struct sshcom_key *load_sshcom_key(const Filename *filename,
  947. const char **errmsg_p)
  948. {
  949. struct sshcom_key *ret;
  950. FILE *fp;
  951. char *line = NULL;
  952. int hdrstart, len;
  953. char *errmsg, *p;
  954. int headers_done;
  955. char base64_bit[4];
  956. int base64_chars = 0;
  957. ret = snew(struct sshcom_key);
  958. ret->comment[0] = '\0';
  959. ret->keyblob = NULL;
  960. ret->keyblob_len = ret->keyblob_size = 0;
  961. fp = f_open(filename, "r", FALSE);
  962. if (!fp) {
  963. errmsg = "unable to open key file";
  964. goto error;
  965. }
  966. if (!(line = fgetline(fp))) {
  967. errmsg = "unexpected end of file";
  968. goto error;
  969. }
  970. strip_crlf(line);
  971. if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
  972. errmsg = "file does not begin with ssh.com key header";
  973. goto error;
  974. }
  975. smemclr(line, strlen(line));
  976. sfree(line);
  977. line = NULL;
  978. headers_done = 0;
  979. while (1) {
  980. if (!(line = fgetline(fp))) {
  981. errmsg = "unexpected end of file";
  982. goto error;
  983. }
  984. strip_crlf(line);
  985. if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
  986. sfree(line);
  987. line = NULL;
  988. break; /* done */
  989. }
  990. if ((p = strchr(line, ':')) != NULL) {
  991. if (headers_done) {
  992. errmsg = "header found in body of key data";
  993. goto error;
  994. }
  995. *p++ = '\0';
  996. while (*p && isspace((unsigned char)*p)) p++;
  997. hdrstart = p - line;
  998. /*
  999. * Header lines can end in a trailing backslash for
  1000. * continuation.
  1001. */
  1002. len = hdrstart + strlen(line+hdrstart);
  1003. assert(!line[len]);
  1004. while (line[len-1] == '\\') {
  1005. char *line2;
  1006. int line2len;
  1007. line2 = fgetline(fp);
  1008. if (!line2) {
  1009. errmsg = "unexpected end of file";
  1010. goto error;
  1011. }
  1012. strip_crlf(line2);
  1013. line2len = strlen(line2);
  1014. line = sresize(line, len + line2len + 1, char);
  1015. strcpy(line + len - 1, line2);
  1016. len += line2len - 1;
  1017. assert(!line[len]);
  1018. smemclr(line2, strlen(line2));
  1019. sfree(line2);
  1020. line2 = NULL;
  1021. }
  1022. p = line + hdrstart;
  1023. strip_crlf(p);
  1024. if (!strcmp(line, "Comment")) {
  1025. /* Strip quotes in comment if present. */
  1026. if (p[0] == '"' && p[strlen(p)-1] == '"') {
  1027. p++;
  1028. p[strlen(p)-1] = '\0';
  1029. }
  1030. strncpy(ret->comment, p, sizeof(ret->comment));
  1031. ret->comment[sizeof(ret->comment)-1] = '\0';
  1032. }
  1033. } else {
  1034. headers_done = 1;
  1035. p = line;
  1036. while (isbase64(*p)) {
  1037. base64_bit[base64_chars++] = *p;
  1038. if (base64_chars == 4) {
  1039. unsigned char out[3];
  1040. base64_chars = 0;
  1041. len = base64_decode_atom(base64_bit, out);
  1042. if (len <= 0) {
  1043. errmsg = "invalid base64 encoding";
  1044. goto error;
  1045. }
  1046. if (ret->keyblob_len + len > ret->keyblob_size) {
  1047. ret->keyblob_size = ret->keyblob_len + len + 256;
  1048. ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
  1049. unsigned char);
  1050. }
  1051. memcpy(ret->keyblob + ret->keyblob_len, out, len);
  1052. ret->keyblob_len += len;
  1053. }
  1054. p++;
  1055. }
  1056. }
  1057. smemclr(line, strlen(line));
  1058. sfree(line);
  1059. line = NULL;
  1060. }
  1061. if (ret->keyblob_len == 0 || !ret->keyblob) {
  1062. errmsg = "key body not present";
  1063. goto error;
  1064. }
  1065. fclose(fp);
  1066. if (errmsg_p) *errmsg_p = NULL;
  1067. return ret;
  1068. error:
  1069. if (fp)
  1070. fclose(fp);
  1071. if (line) {
  1072. smemclr(line, strlen(line));
  1073. sfree(line);
  1074. line = NULL;
  1075. }
  1076. if (ret) {
  1077. if (ret->keyblob) {
  1078. smemclr(ret->keyblob, ret->keyblob_size);
  1079. sfree(ret->keyblob);
  1080. }
  1081. smemclr(ret, sizeof(*ret));
  1082. sfree(ret);
  1083. }
  1084. if (errmsg_p) *errmsg_p = errmsg;
  1085. return NULL;
  1086. }
  1087. int sshcom_encrypted(const Filename *filename, char **comment)
  1088. {
  1089. struct sshcom_key *key = load_sshcom_key(filename, NULL);
  1090. int pos, len, answer;
  1091. answer = 0;
  1092. *comment = NULL;
  1093. if (!key)
  1094. goto done;
  1095. /*
  1096. * Check magic number.
  1097. */
  1098. if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
  1099. goto done; /* key is invalid */
  1100. }
  1101. /*
  1102. * Find the cipher-type string.
  1103. */
  1104. pos = 8;
  1105. if (key->keyblob_len < pos+4)
  1106. goto done; /* key is far too short */
  1107. len = toint(GET_32BIT(key->keyblob + pos));
  1108. if (len < 0 || len > key->keyblob_len - pos - 4)
  1109. goto done; /* key is far too short */
  1110. pos += 4 + len; /* skip key type */
  1111. len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
  1112. if (len < 0 || len > key->keyblob_len - pos - 4)
  1113. goto done; /* cipher type string is incomplete */
  1114. if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
  1115. answer = 1;
  1116. done:
  1117. if (key) {
  1118. *comment = dupstr(key->comment);
  1119. smemclr(key->keyblob, key->keyblob_size);
  1120. sfree(key->keyblob);
  1121. smemclr(key, sizeof(*key));
  1122. sfree(key);
  1123. } else {
  1124. *comment = dupstr("");
  1125. }
  1126. return answer;
  1127. }
  1128. static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
  1129. {
  1130. unsigned bits, bytes;
  1131. unsigned char *d = (unsigned char *) data;
  1132. if (len < 4)
  1133. goto error;
  1134. bits = GET_32BIT(d);
  1135. bytes = (bits + 7) / 8;
  1136. if (len < 4+bytes)
  1137. goto error;
  1138. ret->start = d + 4;
  1139. ret->bytes = bytes;
  1140. return bytes+4;
  1141. error:
  1142. ret->start = NULL;
  1143. ret->bytes = -1;
  1144. return len; /* ensure further calls fail as well */
  1145. }
  1146. static int sshcom_put_mpint(void *target, void *data, int len)
  1147. {
  1148. unsigned char *d = (unsigned char *)target;
  1149. unsigned char *i = (unsigned char *)data;
  1150. int bits = len * 8 - 1;
  1151. while (bits > 0) {
  1152. if (*i & (1 << (bits & 7)))
  1153. break;
  1154. if (!(bits-- & 7))
  1155. i++, len--;
  1156. }
  1157. PUT_32BIT(d, bits+1);
  1158. memcpy(d+4, i, len);
  1159. return len+4;
  1160. }
  1161. struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
  1162. const char **errmsg_p)
  1163. {
  1164. struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
  1165. char *errmsg;
  1166. int pos, len;
  1167. const char prefix_rsa[] = "if-modn{sign{rsa";
  1168. const char prefix_dsa[] = "dl-modp{sign{dsa";
  1169. enum { RSA, DSA } type;
  1170. int encrypted;
  1171. char *ciphertext;
  1172. int cipherlen;
  1173. struct ssh2_userkey *ret = NULL, *retkey;
  1174. const struct ssh_signkey *alg;
  1175. unsigned char *blob = NULL;
  1176. int blobsize = 0, publen, privlen;
  1177. if (!key)
  1178. return NULL;
  1179. /*
  1180. * Check magic number.
  1181. */
  1182. if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
  1183. errmsg = "key does not begin with magic number";
  1184. goto error;
  1185. }
  1186. /*
  1187. * Determine the key type.
  1188. */
  1189. pos = 8;
  1190. if (key->keyblob_len < pos+4 ||
  1191. (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
  1192. len > key->keyblob_len - pos - 4) {
  1193. errmsg = "key blob does not contain a key type string";
  1194. goto error;
  1195. }
  1196. if (len > sizeof(prefix_rsa) - 1 &&
  1197. !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
  1198. type = RSA;
  1199. } else if (len > sizeof(prefix_dsa) - 1 &&
  1200. !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
  1201. type = DSA;
  1202. } else {
  1203. errmsg = "key is of unknown type";
  1204. goto error;
  1205. }
  1206. pos += 4+len;
  1207. /*
  1208. * Determine the cipher type.
  1209. */
  1210. if (key->keyblob_len < pos+4 ||
  1211. (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
  1212. len > key->keyblob_len - pos - 4) {
  1213. errmsg = "key blob does not contain a cipher type string";
  1214. goto error;
  1215. }
  1216. if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
  1217. encrypted = 0;
  1218. else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
  1219. encrypted = 1;
  1220. else {
  1221. errmsg = "key encryption is of unknown type";
  1222. goto error;
  1223. }
  1224. pos += 4+len;
  1225. /*
  1226. * Get hold of the encrypted part of the key.
  1227. */
  1228. if (key->keyblob_len < pos+4 ||
  1229. (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
  1230. len > key->keyblob_len - pos - 4) {
  1231. errmsg = "key blob does not contain actual key data";
  1232. goto error;
  1233. }
  1234. ciphertext = (char *)key->keyblob + pos + 4;
  1235. cipherlen = len;
  1236. if (cipherlen == 0) {
  1237. errmsg = "length of key data is zero";
  1238. goto error;
  1239. }
  1240. /*
  1241. * Decrypt it if necessary.
  1242. */
  1243. if (encrypted) {
  1244. /*
  1245. * Derive encryption key from passphrase and iv/salt:
  1246. *
  1247. * - let block A equal MD5(passphrase)
  1248. * - let block B equal MD5(passphrase || A)
  1249. * - block C would be MD5(passphrase || A || B) and so on
  1250. * - encryption key is the first N bytes of A || B
  1251. */
  1252. struct MD5Context md5c;
  1253. unsigned char keybuf[32], iv[8];
  1254. if (cipherlen % 8 != 0) {
  1255. errmsg = "encrypted part of key is not a multiple of cipher block"
  1256. " size";
  1257. goto error;
  1258. }
  1259. MD5Init(&md5c);
  1260. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  1261. MD5Final(keybuf, &md5c);
  1262. MD5Init(&md5c);
  1263. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  1264. MD5Update(&md5c, keybuf, 16);
  1265. MD5Final(keybuf+16, &md5c);
  1266. /*
  1267. * Now decrypt the key blob.
  1268. */
  1269. memset(iv, 0, sizeof(iv));
  1270. des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
  1271. cipherlen);
  1272. smemclr(&md5c, sizeof(md5c));
  1273. smemclr(keybuf, sizeof(keybuf));
  1274. /*
  1275. * Hereafter we return WRONG_PASSPHRASE for any parsing
  1276. * error. (But only if we've just tried to decrypt it!
  1277. * Returning WRONG_PASSPHRASE for an unencrypted key is
  1278. * automatic doom.)
  1279. */
  1280. if (encrypted)
  1281. ret = SSH2_WRONG_PASSPHRASE;
  1282. }
  1283. /*
  1284. * Strip away the containing string to get to the real meat.
  1285. */
  1286. len = toint(GET_32BIT(ciphertext));
  1287. if (len < 0 || len > cipherlen-4) {
  1288. errmsg = "containing string was ill-formed";
  1289. goto error;
  1290. }
  1291. ciphertext += 4;
  1292. cipherlen = len;
  1293. /*
  1294. * Now we break down into RSA versus DSA. In either case we'll
  1295. * construct public and private blobs in our own format, and
  1296. * end up feeding them to alg->createkey().
  1297. */
  1298. blobsize = cipherlen + 256;
  1299. blob = snewn(blobsize, unsigned char);
  1300. privlen = 0;
  1301. if (type == RSA) {
  1302. struct mpint_pos n, e, d, u, p, q;
  1303. int pos = 0;
  1304. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
  1305. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
  1306. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
  1307. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
  1308. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
  1309. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
  1310. if (!q.start) {
  1311. errmsg = "key data did not contain six integers";
  1312. goto error;
  1313. }
  1314. alg = &ssh_rsa;
  1315. pos = 0;
  1316. pos += put_string(blob+pos, "ssh-rsa", 7);
  1317. pos += put_mp(blob+pos, e.start, e.bytes);
  1318. pos += put_mp(blob+pos, n.start, n.bytes);
  1319. publen = pos;
  1320. pos += put_string(blob+pos, d.start, d.bytes);
  1321. pos += put_mp(blob+pos, q.start, q.bytes);
  1322. pos += put_mp(blob+pos, p.start, p.bytes);
  1323. pos += put_mp(blob+pos, u.start, u.bytes);
  1324. privlen = pos - publen;
  1325. } else {
  1326. struct mpint_pos p, q, g, x, y;
  1327. int pos = 4;
  1328. assert(type == DSA); /* the only other option from the if above */
  1329. if (GET_32BIT(ciphertext) != 0) {
  1330. errmsg = "predefined DSA parameters not supported";
  1331. goto error;
  1332. }
  1333. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
  1334. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
  1335. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
  1336. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
  1337. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
  1338. if (!x.start) {
  1339. errmsg = "key data did not contain five integers";
  1340. goto error;
  1341. }
  1342. alg = &ssh_dss;
  1343. pos = 0;
  1344. pos += put_string(blob+pos, "ssh-dss", 7);
  1345. pos += put_mp(blob+pos, p.start, p.bytes);
  1346. pos += put_mp(blob+pos, q.start, q.bytes);
  1347. pos += put_mp(blob+pos, g.start, g.bytes);
  1348. pos += put_mp(blob+pos, y.start, y.bytes);
  1349. publen = pos;
  1350. pos += put_mp(blob+pos, x.start, x.bytes);
  1351. privlen = pos - publen;
  1352. }
  1353. assert(privlen > 0); /* should have bombed by now if not */
  1354. retkey = snew(struct ssh2_userkey);
  1355. retkey->alg = alg;
  1356. retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
  1357. if (!retkey->data) {
  1358. sfree(retkey);
  1359. errmsg = "unable to create key data structure";
  1360. goto error;
  1361. }
  1362. retkey->comment = dupstr(key->comment);
  1363. errmsg = NULL; /* no error */
  1364. ret = retkey;
  1365. error:
  1366. if (blob) {
  1367. smemclr(blob, blobsize);
  1368. sfree(blob);
  1369. }
  1370. smemclr(key->keyblob, key->keyblob_size);
  1371. sfree(key->keyblob);
  1372. smemclr(key, sizeof(*key));
  1373. sfree(key);
  1374. if (errmsg_p) *errmsg_p = errmsg;
  1375. return ret;
  1376. }
  1377. int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
  1378. char *passphrase)
  1379. {
  1380. unsigned char *pubblob, *privblob;
  1381. int publen, privlen;
  1382. unsigned char *outblob;
  1383. int outlen;
  1384. struct mpint_pos numbers[6];
  1385. int nnumbers, initial_zero, pos, lenpos, i;
  1386. char *type;
  1387. char *ciphertext;
  1388. int cipherlen;
  1389. int ret = 0;
  1390. FILE *fp;
  1391. /*
  1392. * Fetch the key blobs.
  1393. */
  1394. pubblob = key->alg->public_blob(key->data, &publen);
  1395. privblob = key->alg->private_blob(key->data, &privlen);
  1396. outblob = NULL;
  1397. /*
  1398. * Find the sequence of integers to be encoded into the OpenSSH
  1399. * key blob, and also decide on the header line.
  1400. */
  1401. if (key->alg == &ssh_rsa) {
  1402. int pos;
  1403. struct mpint_pos n, e, d, p, q, iqmp;
  1404. /*
  1405. * These blobs were generated from inside PuTTY, so we needn't
  1406. * treat them as untrusted.
  1407. */
  1408. pos = 4 + GET_32BIT(pubblob);
  1409. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
  1410. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
  1411. pos = 0;
  1412. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
  1413. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
  1414. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
  1415. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
  1416. assert(e.start && iqmp.start); /* can't go wrong */
  1417. numbers[0] = e;
  1418. numbers[1] = d;
  1419. numbers[2] = n;
  1420. numbers[3] = iqmp;
  1421. numbers[4] = q;
  1422. numbers[5] = p;
  1423. nnumbers = 6;
  1424. initial_zero = 0;
  1425. type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
  1426. } else if (key->alg == &ssh_dss) {
  1427. int pos;
  1428. struct mpint_pos p, q, g, y, x;
  1429. /*
  1430. * These blobs were generated from inside PuTTY, so we needn't
  1431. * treat them as untrusted.
  1432. */
  1433. pos = 4 + GET_32BIT(pubblob);
  1434. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
  1435. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
  1436. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
  1437. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
  1438. pos = 0;
  1439. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
  1440. assert(y.start && x.start); /* can't go wrong */
  1441. numbers[0] = p;
  1442. numbers[1] = g;
  1443. numbers[2] = q;
  1444. numbers[3] = y;
  1445. numbers[4] = x;
  1446. nnumbers = 5;
  1447. initial_zero = 1;
  1448. type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
  1449. } else {
  1450. assert(0); /* zoinks! */
  1451. exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
  1452. }
  1453. /*
  1454. * Total size of key blob will be somewhere under 512 plus
  1455. * combined length of integers. We'll calculate the more
  1456. * precise size as we construct the blob.
  1457. */
  1458. outlen = 512;
  1459. for (i = 0; i < nnumbers; i++)
  1460. outlen += 4 + numbers[i].bytes;
  1461. outblob = snewn(outlen, unsigned char);
  1462. /*
  1463. * Create the unencrypted key blob.
  1464. */
  1465. pos = 0;
  1466. PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
  1467. pos += 4; /* length field, fill in later */
  1468. pos += put_string(outblob+pos, type, strlen(type));
  1469. {
  1470. char *ciphertype = passphrase ? "3des-cbc" : "none";
  1471. pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
  1472. }
  1473. lenpos = pos; /* remember this position */
  1474. pos += 4; /* encrypted-blob size */
  1475. pos += 4; /* encrypted-payload size */
  1476. if (initial_zero) {
  1477. PUT_32BIT(outblob+pos, 0);
  1478. pos += 4;
  1479. }
  1480. for (i = 0; i < nnumbers; i++)
  1481. pos += sshcom_put_mpint(outblob+pos,
  1482. numbers[i].start, numbers[i].bytes);
  1483. /* Now wrap up the encrypted payload. */
  1484. PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
  1485. /* Pad encrypted blob to a multiple of cipher block size. */
  1486. if (passphrase) {
  1487. int padding = -(pos - (lenpos+4)) & 7;
  1488. while (padding--)
  1489. outblob[pos++] = random_byte();
  1490. }
  1491. ciphertext = (char *)outblob+lenpos+4;
  1492. cipherlen = pos - (lenpos+4);
  1493. assert(!passphrase || cipherlen % 8 == 0);
  1494. /* Wrap up the encrypted blob string. */
  1495. PUT_32BIT(outblob+lenpos, cipherlen);
  1496. /* And finally fill in the total length field. */
  1497. PUT_32BIT(outblob+4, pos);
  1498. assert(pos < outlen);
  1499. /*
  1500. * Encrypt the key.
  1501. */
  1502. if (passphrase) {
  1503. /*
  1504. * Derive encryption key from passphrase and iv/salt:
  1505. *
  1506. * - let block A equal MD5(passphrase)
  1507. * - let block B equal MD5(passphrase || A)
  1508. * - block C would be MD5(passphrase || A || B) and so on
  1509. * - encryption key is the first N bytes of A || B
  1510. */
  1511. struct MD5Context md5c;
  1512. unsigned char keybuf[32], iv[8];
  1513. MD5Init(&md5c);
  1514. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  1515. MD5Final(keybuf, &md5c);
  1516. MD5Init(&md5c);
  1517. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  1518. MD5Update(&md5c, keybuf, 16);
  1519. MD5Final(keybuf+16, &md5c);
  1520. /*
  1521. * Now decrypt the key blob.
  1522. */
  1523. memset(iv, 0, sizeof(iv));
  1524. des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
  1525. cipherlen);
  1526. smemclr(&md5c, sizeof(md5c));
  1527. smemclr(keybuf, sizeof(keybuf));
  1528. }
  1529. /*
  1530. * And save it. We'll use Unix line endings just in case it's
  1531. * subsequently transferred in binary mode.
  1532. */
  1533. fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
  1534. if (!fp)
  1535. goto error;
  1536. fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
  1537. fprintf(fp, "Comment: \"");
  1538. /*
  1539. * Comment header is broken with backslash-newline if it goes
  1540. * over 70 chars. Although it's surrounded by quotes, it
  1541. * _doesn't_ escape backslashes or quotes within the string.
  1542. * Don't ask me, I didn't design it.
  1543. */
  1544. {
  1545. int slen = 60; /* starts at 60 due to "Comment: " */
  1546. char *c = key->comment;
  1547. while ((int)strlen(c) > slen) {
  1548. fprintf(fp, "%.*s\\\n", slen, c);
  1549. c += slen;
  1550. slen = 70; /* allow 70 chars on subsequent lines */
  1551. }
  1552. fprintf(fp, "%s\"\n", c);
  1553. }
  1554. base64_encode(fp, outblob, pos, 70);
  1555. fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
  1556. fclose(fp);
  1557. ret = 1;
  1558. error:
  1559. if (outblob) {
  1560. smemclr(outblob, outlen);
  1561. sfree(outblob);
  1562. }
  1563. if (privblob) {
  1564. smemclr(privblob, privlen);
  1565. sfree(privblob);
  1566. }
  1567. if (pubblob) {
  1568. smemclr(pubblob, publen);
  1569. sfree(pubblob);
  1570. }
  1571. return ret;
  1572. }