keyimport.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  1. /*
  2. * Based on PuTTY's import.c for importing/exporting OpenSSH and SSH.com
  3. * keyfiles.
  4. *
  5. * Modifications copyright 2003 Matt Johnston
  6. *
  7. * PuTTY is copyright 1997-2003 Simon Tatham.
  8. *
  9. * Portions copyright Robert de Bath, Joris van Rantwijk, Delian
  10. * Delchev, Andreas Schultz, Jeroen Massar, Wez Furlong, Nicolas Barry,
  11. * Justin Bradford, and CORE SDI S.A.
  12. *
  13. * Permission is hereby granted, free of charge, to any person
  14. * obtaining a copy of this software and associated documentation files
  15. * (the "Software"), to deal in the Software without restriction,
  16. * including without limitation the rights to use, copy, modify, merge,
  17. * publish, distribute, sublicense, and/or sell copies of the Software,
  18. * and to permit persons to whom the Software is furnished to do so,
  19. * subject to the following conditions:
  20. *
  21. * The above copyright notice and this permission notice shall be
  22. * included in all copies or substantial portions of the Software.
  23. *
  24. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. * NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
  28. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  29. * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. */
  32. #include "keyimport.h"
  33. #include "bignum.h"
  34. #include "buffer.h"
  35. #include "dbutil.h"
  36. #include "ecc.h"
  37. static const unsigned char OID_SEC256R1_BLOB[] = {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07};
  38. static const unsigned char OID_SEC384R1_BLOB[] = {0x2b, 0x81, 0x04, 0x00, 0x22};
  39. static const unsigned char OID_SEC521R1_BLOB[] = {0x2b, 0x81, 0x04, 0x00, 0x23};
  40. #define PUT_32BIT(cp, value) do { \
  41. (cp)[3] = (unsigned char)(value); \
  42. (cp)[2] = (unsigned char)((value) >> 8); \
  43. (cp)[1] = (unsigned char)((value) >> 16); \
  44. (cp)[0] = (unsigned char)((value) >> 24); } while (0)
  45. #define GET_32BIT(cp) \
  46. (((unsigned long)(unsigned char)(cp)[0] << 24) | \
  47. ((unsigned long)(unsigned char)(cp)[1] << 16) | \
  48. ((unsigned long)(unsigned char)(cp)[2] << 8) | \
  49. ((unsigned long)(unsigned char)(cp)[3]))
  50. static int openssh_encrypted(const char *filename);
  51. static sign_key *openssh_read(const char *filename, char *passphrase);
  52. static int openssh_write(const char *filename, sign_key *key,
  53. char *passphrase);
  54. static int dropbear_write(const char*filename, sign_key * key);
  55. static sign_key *dropbear_read(const char* filename);
  56. static int toint(unsigned u);
  57. #if 0
  58. static int sshcom_encrypted(const char *filename, char **comment);
  59. static struct ssh2_userkey *sshcom_read(const char *filename, char *passphrase);
  60. static int sshcom_write(const char *filename, struct ssh2_userkey *key,
  61. char *passphrase);
  62. #endif
  63. int import_encrypted(const char* filename, int filetype) {
  64. if (filetype == KEYFILE_OPENSSH) {
  65. return openssh_encrypted(filename);
  66. #if 0
  67. } else if (filetype == KEYFILE_SSHCOM) {
  68. return sshcom_encrypted(filename, NULL);
  69. #endif
  70. }
  71. return 0;
  72. }
  73. sign_key *import_read(const char *filename, char *passphrase, int filetype) {
  74. if (filetype == KEYFILE_OPENSSH) {
  75. return openssh_read(filename, passphrase);
  76. } else if (filetype == KEYFILE_DROPBEAR) {
  77. return dropbear_read(filename);
  78. #if 0
  79. } else if (filetype == KEYFILE_SSHCOM) {
  80. return sshcom_read(filename, passphrase);
  81. #endif
  82. }
  83. return NULL;
  84. }
  85. int import_write(const char *filename, sign_key *key, char *passphrase,
  86. int filetype) {
  87. if (filetype == KEYFILE_OPENSSH) {
  88. return openssh_write(filename, key, passphrase);
  89. } else if (filetype == KEYFILE_DROPBEAR) {
  90. return dropbear_write(filename, key);
  91. #if 0
  92. } else if (filetype == KEYFILE_SSHCOM) {
  93. return sshcom_write(filename, key, passphrase);
  94. #endif
  95. }
  96. return 0;
  97. }
  98. static sign_key *dropbear_read(const char* filename) {
  99. buffer * buf = NULL;
  100. sign_key *ret = NULL;
  101. enum signkey_type type;
  102. buf = buf_new(MAX_PRIVKEY_SIZE);
  103. if (buf_readfile(buf, filename) == DROPBEAR_FAILURE) {
  104. goto error;
  105. }
  106. buf_setpos(buf, 0);
  107. ret = new_sign_key();
  108. type = DROPBEAR_SIGNKEY_ANY;
  109. if (buf_get_priv_key(buf, ret, &type) == DROPBEAR_FAILURE){
  110. goto error;
  111. }
  112. buf_free(buf);
  113. ret->type = type;
  114. return ret;
  115. error:
  116. if (buf) {
  117. buf_free(buf);
  118. }
  119. if (ret) {
  120. sign_key_free(ret);
  121. }
  122. return NULL;
  123. }
  124. /* returns 0 on fail, 1 on success */
  125. static int dropbear_write(const char*filename, sign_key * key) {
  126. buffer * buf;
  127. FILE*fp;
  128. int len;
  129. int ret;
  130. buf = buf_new(MAX_PRIVKEY_SIZE);
  131. buf_put_priv_key(buf, key, key->type);
  132. fp = fopen(filename, "w");
  133. if (!fp) {
  134. ret = 0;
  135. goto out;
  136. }
  137. buf_setpos(buf, 0);
  138. do {
  139. len = fwrite(buf_getptr(buf, buf->len - buf->pos),
  140. 1, buf->len - buf->pos, fp);
  141. buf_incrpos(buf, len);
  142. } while (len > 0 && buf->len != buf->pos);
  143. fclose(fp);
  144. if (buf->pos != buf->len) {
  145. ret = 0;
  146. } else {
  147. ret = 1;
  148. }
  149. out:
  150. buf_free(buf);
  151. return ret;
  152. }
  153. /* ----------------------------------------------------------------------
  154. * Helper routines. (The base64 ones are defined in sshpubk.c.)
  155. */
  156. #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
  157. ((c) >= 'a' && (c) <= 'z') || \
  158. ((c) >= '0' && (c) <= '9') || \
  159. (c) == '+' || (c) == '/' || (c) == '=' \
  160. )
  161. /* cpl has to be less than 100 */
  162. static void base64_encode_fp(FILE * fp, unsigned char *data,
  163. int datalen, int cpl)
  164. {
  165. unsigned char out[100];
  166. int n;
  167. unsigned long outlen;
  168. int rawcpl;
  169. rawcpl = cpl * 3 / 4;
  170. dropbear_assert((unsigned int)cpl < sizeof(out));
  171. while (datalen > 0) {
  172. n = (datalen < rawcpl ? datalen : rawcpl);
  173. outlen = sizeof(out);
  174. base64_encode(data, n, out, &outlen);
  175. data += n;
  176. datalen -= n;
  177. fwrite(out, 1, outlen, fp);
  178. fputc('\n', fp);
  179. }
  180. }
  181. /*
  182. * Read an ASN.1/BER identifier and length pair.
  183. *
  184. * Flags are a combination of the #defines listed below.
  185. *
  186. * Returns -1 if unsuccessful; otherwise returns the number of
  187. * bytes used out of the source data.
  188. */
  189. /* ASN.1 tag classes. */
  190. #define ASN1_CLASS_UNIVERSAL (0 << 6)
  191. #define ASN1_CLASS_APPLICATION (1 << 6)
  192. #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
  193. #define ASN1_CLASS_PRIVATE (3 << 6)
  194. #define ASN1_CLASS_MASK (3 << 6)
  195. /* Primitive versus constructed bit. */
  196. #define ASN1_CONSTRUCTED (1 << 5)
  197. static int ber_read_id_len(void *source, int sourcelen,
  198. int *id, int *length, int *flags)
  199. {
  200. unsigned char *p = (unsigned char *) source;
  201. if (sourcelen == 0)
  202. return -1;
  203. *flags = (*p & 0xE0);
  204. if ((*p & 0x1F) == 0x1F) {
  205. *id = 0;
  206. while (*p & 0x80) {
  207. p++, sourcelen--;
  208. if (sourcelen == 0)
  209. return -1;
  210. *id = (*id << 7) | (*p & 0x7F);
  211. }
  212. p++, sourcelen--;
  213. } else {
  214. *id = *p & 0x1F;
  215. p++, sourcelen--;
  216. }
  217. if (sourcelen == 0)
  218. return -1;
  219. if (*p & 0x80) {
  220. unsigned len;
  221. int n = *p & 0x7F;
  222. p++, sourcelen--;
  223. if (sourcelen < n)
  224. return -1;
  225. len = 0;
  226. while (n--)
  227. len = (len << 8) | (*p++);
  228. sourcelen -= n;
  229. *length = toint(len);
  230. } else {
  231. *length = *p;
  232. p++, sourcelen--;
  233. }
  234. if (*length < 0) {
  235. printf("Negative ASN.1 length\n");
  236. return -1;
  237. }
  238. return p - (unsigned char *) source;
  239. }
  240. /*
  241. * Write an ASN.1/BER identifier and length pair. Returns the
  242. * number of bytes consumed. Assumes dest contains enough space.
  243. * Will avoid writing anything if dest is NULL, but still return
  244. * amount of space required.
  245. */
  246. static int ber_write_id_len(void *dest, int id, int length, int flags)
  247. {
  248. unsigned char *d = (unsigned char *)dest;
  249. int len = 0;
  250. if (id <= 30) {
  251. /*
  252. * Identifier is one byte.
  253. */
  254. len++;
  255. if (d) *d++ = id | flags;
  256. } else {
  257. int n;
  258. /*
  259. * Identifier is multiple bytes: the first byte is 11111
  260. * plus the flags, and subsequent bytes encode the value of
  261. * the identifier, 7 bits at a time, with the top bit of
  262. * each byte 1 except the last one which is 0.
  263. */
  264. len++;
  265. if (d) *d++ = 0x1F | flags;
  266. for (n = 1; (id >> (7*n)) > 0; n++)
  267. continue; /* count the bytes */
  268. while (n--) {
  269. len++;
  270. if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
  271. }
  272. }
  273. if (length < 128) {
  274. /*
  275. * Length is one byte.
  276. */
  277. len++;
  278. if (d) *d++ = length;
  279. } else {
  280. int n;
  281. /*
  282. * Length is multiple bytes. The first is 0x80 plus the
  283. * number of subsequent bytes, and the subsequent bytes
  284. * encode the actual length.
  285. */
  286. for (n = 1; (length >> (8*n)) > 0; n++)
  287. continue; /* count the bytes */
  288. len++;
  289. if (d) *d++ = 0x80 | n;
  290. while (n--) {
  291. len++;
  292. if (d) *d++ = (length >> (8*n)) & 0xFF;
  293. }
  294. }
  295. return len;
  296. }
  297. /* Simple structure to point to an mp-int within a blob. */
  298. struct mpint_pos { void *start; int bytes; };
  299. /* ----------------------------------------------------------------------
  300. * Code to read and write OpenSSH private keys.
  301. */
  302. enum { OSSH_DSA, OSSH_RSA, OSSH_EC };
  303. struct openssh_key {
  304. int type;
  305. int encrypted;
  306. char iv[32];
  307. unsigned char *keyblob;
  308. unsigned int keyblob_len, keyblob_size;
  309. };
  310. static struct openssh_key *load_openssh_key(const char *filename)
  311. {
  312. struct openssh_key *ret;
  313. FILE *fp = NULL;
  314. char buffer[256];
  315. char *errmsg = NULL, *p = NULL;
  316. int headers_done;
  317. unsigned long len, outlen;
  318. ret = (struct openssh_key*)m_malloc(sizeof(struct openssh_key));
  319. ret->keyblob = NULL;
  320. ret->keyblob_len = ret->keyblob_size = 0;
  321. ret->encrypted = 0;
  322. memset(ret->iv, 0, sizeof(ret->iv));
  323. if (strlen(filename) == 1 && filename[0] == '-') {
  324. fp = stdin;
  325. } else {
  326. fp = fopen(filename, "r");
  327. }
  328. if (!fp) {
  329. errmsg = "Unable to open key file";
  330. goto error;
  331. }
  332. if (!fgets(buffer, sizeof(buffer), fp) ||
  333. 0 != strncmp(buffer, "-----BEGIN ", 11) ||
  334. 0 != strcmp(buffer+strlen(buffer)-17, "PRIVATE KEY-----\n")) {
  335. errmsg = "File does not begin with OpenSSH key header";
  336. goto error;
  337. }
  338. if (!strcmp(buffer, "-----BEGIN RSA PRIVATE KEY-----\n"))
  339. ret->type = OSSH_RSA;
  340. else if (!strcmp(buffer, "-----BEGIN DSA PRIVATE KEY-----\n"))
  341. ret->type = OSSH_DSA;
  342. else if (!strcmp(buffer, "-----BEGIN EC PRIVATE KEY-----\n"))
  343. ret->type = OSSH_EC;
  344. else {
  345. errmsg = "Unrecognised key type";
  346. goto error;
  347. }
  348. headers_done = 0;
  349. while (1) {
  350. if (!fgets(buffer, sizeof(buffer), fp)) {
  351. errmsg = "Unexpected end of file";
  352. goto error;
  353. }
  354. if (0 == strncmp(buffer, "-----END ", 9) &&
  355. 0 == strcmp(buffer+strlen(buffer)-17, "PRIVATE KEY-----\n"))
  356. break; /* done */
  357. if ((p = strchr(buffer, ':')) != NULL) {
  358. if (headers_done) {
  359. errmsg = "Header found in body of key data";
  360. goto error;
  361. }
  362. *p++ = '\0';
  363. while (*p && isspace((unsigned char)*p)) p++;
  364. if (!strcmp(buffer, "Proc-Type")) {
  365. if (p[0] != '4' || p[1] != ',') {
  366. errmsg = "Proc-Type is not 4 (only 4 is supported)";
  367. goto error;
  368. }
  369. p += 2;
  370. if (!strcmp(p, "ENCRYPTED\n"))
  371. ret->encrypted = 1;
  372. } else if (!strcmp(buffer, "DEK-Info")) {
  373. int i, j;
  374. if (strncmp(p, "DES-EDE3-CBC,", 13)) {
  375. errmsg = "Ciphers other than DES-EDE3-CBC not supported";
  376. goto error;
  377. }
  378. p += 13;
  379. for (i = 0; i < 8; i++) {
  380. if (1 != sscanf(p, "%2x", &j))
  381. break;
  382. ret->iv[i] = j;
  383. p += 2;
  384. }
  385. if (i < 8) {
  386. errmsg = "Expected 16-digit iv in DEK-Info";
  387. goto error;
  388. }
  389. }
  390. } else {
  391. headers_done = 1;
  392. len = strlen(buffer);
  393. outlen = len*4/3;
  394. if (ret->keyblob_len + outlen > ret->keyblob_size) {
  395. ret->keyblob_size = ret->keyblob_len + outlen + 256;
  396. ret->keyblob = (unsigned char*)m_realloc(ret->keyblob,
  397. ret->keyblob_size);
  398. }
  399. outlen = ret->keyblob_size - ret->keyblob_len;
  400. if (base64_decode((const unsigned char *)buffer, len,
  401. ret->keyblob + ret->keyblob_len, &outlen) != CRYPT_OK){
  402. errmsg = "Error decoding base64";
  403. goto error;
  404. }
  405. ret->keyblob_len += outlen;
  406. }
  407. }
  408. if (ret->keyblob_len == 0 || !ret->keyblob) {
  409. errmsg = "Key body not present";
  410. goto error;
  411. }
  412. if (ret->encrypted && ret->keyblob_len % 8 != 0) {
  413. errmsg = "Encrypted key blob is not a multiple of cipher block size";
  414. goto error;
  415. }
  416. m_burn(buffer, sizeof(buffer));
  417. return ret;
  418. error:
  419. m_burn(buffer, sizeof(buffer));
  420. if (ret) {
  421. if (ret->keyblob) {
  422. m_burn(ret->keyblob, ret->keyblob_size);
  423. m_free(ret->keyblob);
  424. }
  425. m_free(ret);
  426. }
  427. if (fp) {
  428. fclose(fp);
  429. }
  430. if (errmsg) {
  431. fprintf(stderr, "Error: %s\n", errmsg);
  432. }
  433. return NULL;
  434. }
  435. static int openssh_encrypted(const char *filename)
  436. {
  437. struct openssh_key *key = load_openssh_key(filename);
  438. int ret;
  439. if (!key)
  440. return 0;
  441. ret = key->encrypted;
  442. m_burn(key->keyblob, key->keyblob_size);
  443. m_free(key->keyblob);
  444. m_free(key);
  445. return ret;
  446. }
  447. static sign_key *openssh_read(const char *filename, char * UNUSED(passphrase))
  448. {
  449. struct openssh_key *key;
  450. unsigned char *p;
  451. int ret, id, len, flags;
  452. int i, num_integers = 0;
  453. sign_key *retval = NULL;
  454. char *errmsg;
  455. unsigned char *modptr = NULL;
  456. int modlen = -9999;
  457. enum signkey_type type;
  458. sign_key *retkey;
  459. buffer * blobbuf = NULL;
  460. retkey = new_sign_key();
  461. key = load_openssh_key(filename);
  462. if (!key)
  463. return NULL;
  464. if (key->encrypted) {
  465. errmsg = "encrypted keys not supported currently";
  466. goto error;
  467. #if 0
  468. /* matt TODO */
  469. /*
  470. * Derive encryption key from passphrase and iv/salt:
  471. *
  472. * - let block A equal MD5(passphrase || iv)
  473. * - let block B equal MD5(A || passphrase || iv)
  474. * - block C would be MD5(B || passphrase || iv) and so on
  475. * - encryption key is the first N bytes of A || B
  476. */
  477. struct MD5Context md5c;
  478. unsigned char keybuf[32];
  479. MD5Init(&md5c);
  480. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  481. MD5Update(&md5c, (unsigned char *)key->iv, 8);
  482. MD5Final(keybuf, &md5c);
  483. MD5Init(&md5c);
  484. MD5Update(&md5c, keybuf, 16);
  485. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  486. MD5Update(&md5c, (unsigned char *)key->iv, 8);
  487. MD5Final(keybuf+16, &md5c);
  488. /*
  489. * Now decrypt the key blob.
  490. */
  491. des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
  492. key->keyblob, key->keyblob_len);
  493. memset(&md5c, 0, sizeof(md5c));
  494. memset(keybuf, 0, sizeof(keybuf));
  495. #endif
  496. }
  497. /*
  498. * Now we have a decrypted key blob, which contains an ASN.1
  499. * encoded private key. We must now untangle the ASN.1.
  500. *
  501. * We expect the whole key blob to be formatted as a SEQUENCE
  502. * (0x30 followed by a length code indicating that the rest of
  503. * the blob is part of the sequence). Within that SEQUENCE we
  504. * expect to see a bunch of INTEGERs. What those integers mean
  505. * depends on the key type:
  506. *
  507. * - For RSA, we expect the integers to be 0, n, e, d, p, q,
  508. * dmp1, dmq1, iqmp in that order. (The last three are d mod
  509. * (p-1), d mod (q-1), inverse of q mod p respectively.)
  510. *
  511. * - For DSA, we expect them to be 0, p, q, g, y, x in that
  512. * order.
  513. */
  514. p = key->keyblob;
  515. /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
  516. ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
  517. p += ret;
  518. if (ret < 0 || id != 16 || len < 0 ||
  519. key->keyblob+key->keyblob_len-p < len) {
  520. errmsg = "ASN.1 decoding failure";
  521. goto error;
  522. }
  523. /* Expect a load of INTEGERs. */
  524. if (key->type == OSSH_RSA)
  525. num_integers = 9;
  526. else if (key->type == OSSH_DSA)
  527. num_integers = 6;
  528. else if (key->type == OSSH_EC)
  529. num_integers = 1;
  530. /*
  531. * Space to create key blob in.
  532. */
  533. blobbuf = buf_new(3000);
  534. #ifdef DROPBEAR_DSS
  535. if (key->type == OSSH_DSA) {
  536. buf_putstring(blobbuf, "ssh-dss", 7);
  537. retkey->type = DROPBEAR_SIGNKEY_DSS;
  538. }
  539. #endif
  540. #ifdef DROPBEAR_RSA
  541. if (key->type == OSSH_RSA) {
  542. buf_putstring(blobbuf, "ssh-rsa", 7);
  543. retkey->type = DROPBEAR_SIGNKEY_RSA;
  544. }
  545. #endif
  546. for (i = 0; i < num_integers; i++) {
  547. ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
  548. &id, &len, &flags);
  549. p += ret;
  550. if (ret < 0 || id != 2 || len < 0 ||
  551. key->keyblob+key->keyblob_len-p < len) {
  552. errmsg = "ASN.1 decoding failure";
  553. goto error;
  554. }
  555. if (i == 0) {
  556. /* First integer is a version indicator */
  557. int expected = -1;
  558. switch (key->type) {
  559. case OSSH_RSA:
  560. case OSSH_DSA:
  561. expected = 0;
  562. break;
  563. case OSSH_EC:
  564. expected = 1;
  565. break;
  566. }
  567. if (len != 1 || p[0] != expected) {
  568. errmsg = "Version number mismatch";
  569. goto error;
  570. }
  571. } else if (key->type == OSSH_RSA) {
  572. /*
  573. * OpenSSH key order is n, e, d, p, q, dmp1, dmq1, iqmp
  574. * but we want e, n, d, p, q
  575. */
  576. if (i == 1) {
  577. /* Save the details for after we deal with number 2. */
  578. modptr = p;
  579. modlen = len;
  580. } else if (i >= 2 && i <= 5) {
  581. buf_putstring(blobbuf, (const char*)p, len);
  582. if (i == 2) {
  583. buf_putstring(blobbuf, (const char*)modptr, modlen);
  584. }
  585. }
  586. } else if (key->type == OSSH_DSA) {
  587. /*
  588. * OpenSSH key order is p, q, g, y, x,
  589. * we want the same.
  590. */
  591. buf_putstring(blobbuf, (const char*)p, len);
  592. }
  593. /* Skip past the number. */
  594. p += len;
  595. }
  596. #ifdef DROPBEAR_ECDSA
  597. if (key->type == OSSH_EC) {
  598. unsigned char* private_key_bytes = NULL;
  599. int private_key_len = 0;
  600. unsigned char* public_key_bytes = NULL;
  601. int public_key_len = 0;
  602. ecc_key *ecc = NULL;
  603. const struct dropbear_ecc_curve *curve = NULL;
  604. /* See SEC1 v2, Appendix C.4 */
  605. /* OpenSSL (so OpenSSH) seems to include the optional parts. */
  606. /* privateKey OCTET STRING, */
  607. ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
  608. &id, &len, &flags);
  609. p += ret;
  610. /* id==4 for octet string */
  611. if (ret < 0 || id != 4 || len < 0 ||
  612. key->keyblob+key->keyblob_len-p < len) {
  613. errmsg = "ASN.1 decoding failure";
  614. goto error;
  615. }
  616. private_key_bytes = p;
  617. private_key_len = len;
  618. p += len;
  619. /* parameters [0] ECDomainParameters {{ SECGCurveNames }} OPTIONAL, */
  620. ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
  621. &id, &len, &flags);
  622. p += ret;
  623. /* id==0 */
  624. if (ret < 0 || id != 0 || len < 0) {
  625. errmsg = "ASN.1 decoding failure";
  626. goto error;
  627. }
  628. ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
  629. &id, &len, &flags);
  630. p += ret;
  631. /* id==6 for object */
  632. if (ret < 0 || id != 6 || len < 0 ||
  633. key->keyblob+key->keyblob_len-p < len) {
  634. errmsg = "ASN.1 decoding failure";
  635. goto error;
  636. }
  637. if (0) {}
  638. #ifdef DROPBEAR_ECC_256
  639. else if (len == sizeof(OID_SEC256R1_BLOB)
  640. && memcmp(p, OID_SEC256R1_BLOB, len) == 0) {
  641. retkey->type = DROPBEAR_SIGNKEY_ECDSA_NISTP256;
  642. curve = &ecc_curve_nistp256;
  643. }
  644. #endif
  645. #ifdef DROPBEAR_ECC_384
  646. else if (len == sizeof(OID_SEC384R1_BLOB)
  647. && memcmp(p, OID_SEC384R1_BLOB, len) == 0) {
  648. retkey->type = DROPBEAR_SIGNKEY_ECDSA_NISTP384;
  649. curve = &ecc_curve_nistp384;
  650. }
  651. #endif
  652. #ifdef DROPBEAR_ECC_521
  653. else if (len == sizeof(OID_SEC521R1_BLOB)
  654. && memcmp(p, OID_SEC521R1_BLOB, len) == 0) {
  655. retkey->type = DROPBEAR_SIGNKEY_ECDSA_NISTP521;
  656. curve = &ecc_curve_nistp521;
  657. }
  658. #endif
  659. else {
  660. errmsg = "Unknown ECC key type";
  661. goto error;
  662. }
  663. p += len;
  664. /* publicKey [1] BIT STRING OPTIONAL */
  665. ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
  666. &id, &len, &flags);
  667. p += ret;
  668. /* id==1 */
  669. if (ret < 0 || id != 1 || len < 0) {
  670. errmsg = "ASN.1 decoding failure";
  671. goto error;
  672. }
  673. ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
  674. &id, &len, &flags);
  675. p += ret;
  676. /* id==3 for bit string */
  677. if (ret < 0 || id != 3 || len < 0 ||
  678. key->keyblob+key->keyblob_len-p < len) {
  679. errmsg = "ASN.1 decoding failure";
  680. goto error;
  681. }
  682. public_key_bytes = p+1;
  683. public_key_len = len-1;
  684. p += len;
  685. buf_putbytes(blobbuf, public_key_bytes, public_key_len);
  686. ecc = buf_get_ecc_raw_pubkey(blobbuf, curve);
  687. if (!ecc) {
  688. errmsg = "Error parsing ECC key";
  689. goto error;
  690. }
  691. m_mp_alloc_init_multi((mp_int**)&ecc->k, NULL);
  692. if (mp_read_unsigned_bin(ecc->k, private_key_bytes, private_key_len)
  693. != MP_OKAY) {
  694. errmsg = "Error parsing ECC key";
  695. goto error;
  696. }
  697. *signkey_key_ptr(retkey, retkey->type) = ecc;
  698. }
  699. #endif /* DROPBEAR_ECDSA */
  700. /*
  701. * Now put together the actual key. Simplest way to do this is
  702. * to assemble our own key blobs and feed them to the createkey
  703. * functions; this is a bit faffy but it does mean we get all
  704. * the sanity checks for free.
  705. */
  706. if (key->type == OSSH_RSA || key->type == OSSH_DSA) {
  707. buf_setpos(blobbuf, 0);
  708. type = DROPBEAR_SIGNKEY_ANY;
  709. if (buf_get_priv_key(blobbuf, retkey, &type)
  710. != DROPBEAR_SUCCESS) {
  711. errmsg = "unable to create key structure";
  712. sign_key_free(retkey);
  713. retkey = NULL;
  714. goto error;
  715. }
  716. }
  717. errmsg = NULL; /* no error */
  718. retval = retkey;
  719. error:
  720. if (blobbuf) {
  721. buf_burn(blobbuf);
  722. buf_free(blobbuf);
  723. }
  724. m_burn(key->keyblob, key->keyblob_size);
  725. m_free(key->keyblob);
  726. m_burn(key, sizeof(*key));
  727. m_free(key);
  728. if (errmsg) {
  729. fprintf(stderr, "Error: %s\n", errmsg);
  730. }
  731. return retval;
  732. }
  733. static int openssh_write(const char *filename, sign_key *key,
  734. char *passphrase)
  735. {
  736. buffer * keyblob = NULL;
  737. buffer * extrablob = NULL; /* used for calculated values to write */
  738. unsigned char *outblob = NULL;
  739. int outlen = -9999;
  740. struct mpint_pos numbers[9];
  741. int nnumbers = -1, pos = 0, len = 0, seqlen, i;
  742. char *header = NULL, *footer = NULL;
  743. char zero[1];
  744. int ret = 0;
  745. FILE *fp;
  746. #ifdef DROPBEAR_RSA
  747. mp_int dmp1, dmq1, iqmp, tmpval; /* for rsa */
  748. #endif
  749. if (
  750. #ifdef DROPBEAR_RSA
  751. key->type == DROPBEAR_SIGNKEY_RSA ||
  752. #endif
  753. #ifdef DROPBEAR_DSS
  754. key->type == DROPBEAR_SIGNKEY_DSS ||
  755. #endif
  756. 0)
  757. {
  758. /*
  759. * Fetch the key blobs.
  760. */
  761. keyblob = buf_new(3000);
  762. buf_put_priv_key(keyblob, key, key->type);
  763. buf_setpos(keyblob, 0);
  764. /* skip the "ssh-rsa" or "ssh-dss" header */
  765. buf_incrpos(keyblob, buf_getint(keyblob));
  766. /*
  767. * Find the sequence of integers to be encoded into the OpenSSH
  768. * key blob, and also decide on the header line.
  769. */
  770. numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
  771. #ifdef DROPBEAR_RSA
  772. if (key->type == DROPBEAR_SIGNKEY_RSA) {
  773. if (key->rsakey->p == NULL || key->rsakey->q == NULL) {
  774. fprintf(stderr, "Pre-0.33 Dropbear keys cannot be converted to OpenSSH keys.\n");
  775. goto error;
  776. }
  777. /* e */
  778. numbers[2].bytes = buf_getint(keyblob);
  779. numbers[2].start = buf_getptr(keyblob, numbers[2].bytes);
  780. buf_incrpos(keyblob, numbers[2].bytes);
  781. /* n */
  782. numbers[1].bytes = buf_getint(keyblob);
  783. numbers[1].start = buf_getptr(keyblob, numbers[1].bytes);
  784. buf_incrpos(keyblob, numbers[1].bytes);
  785. /* d */
  786. numbers[3].bytes = buf_getint(keyblob);
  787. numbers[3].start = buf_getptr(keyblob, numbers[3].bytes);
  788. buf_incrpos(keyblob, numbers[3].bytes);
  789. /* p */
  790. numbers[4].bytes = buf_getint(keyblob);
  791. numbers[4].start = buf_getptr(keyblob, numbers[4].bytes);
  792. buf_incrpos(keyblob, numbers[4].bytes);
  793. /* q */
  794. numbers[5].bytes = buf_getint(keyblob);
  795. numbers[5].start = buf_getptr(keyblob, numbers[5].bytes);
  796. buf_incrpos(keyblob, numbers[5].bytes);
  797. /* now calculate some extra parameters: */
  798. m_mp_init(&tmpval);
  799. m_mp_init(&dmp1);
  800. m_mp_init(&dmq1);
  801. m_mp_init(&iqmp);
  802. /* dmp1 = d mod (p-1) */
  803. if (mp_sub_d(key->rsakey->p, 1, &tmpval) != MP_OKAY) {
  804. fprintf(stderr, "Bignum error for p-1\n");
  805. goto error;
  806. }
  807. if (mp_mod(key->rsakey->d, &tmpval, &dmp1) != MP_OKAY) {
  808. fprintf(stderr, "Bignum error for dmp1\n");
  809. goto error;
  810. }
  811. /* dmq1 = d mod (q-1) */
  812. if (mp_sub_d(key->rsakey->q, 1, &tmpval) != MP_OKAY) {
  813. fprintf(stderr, "Bignum error for q-1\n");
  814. goto error;
  815. }
  816. if (mp_mod(key->rsakey->d, &tmpval, &dmq1) != MP_OKAY) {
  817. fprintf(stderr, "Bignum error for dmq1\n");
  818. goto error;
  819. }
  820. /* iqmp = (q^-1) mod p */
  821. if (mp_invmod(key->rsakey->q, key->rsakey->p, &iqmp) != MP_OKAY) {
  822. fprintf(stderr, "Bignum error for iqmp\n");
  823. goto error;
  824. }
  825. extrablob = buf_new(2000);
  826. buf_putmpint(extrablob, &dmp1);
  827. buf_putmpint(extrablob, &dmq1);
  828. buf_putmpint(extrablob, &iqmp);
  829. buf_setpos(extrablob, 0);
  830. mp_clear(&dmp1);
  831. mp_clear(&dmq1);
  832. mp_clear(&iqmp);
  833. mp_clear(&tmpval);
  834. /* dmp1 */
  835. numbers[6].bytes = buf_getint(extrablob);
  836. numbers[6].start = buf_getptr(extrablob, numbers[6].bytes);
  837. buf_incrpos(extrablob, numbers[6].bytes);
  838. /* dmq1 */
  839. numbers[7].bytes = buf_getint(extrablob);
  840. numbers[7].start = buf_getptr(extrablob, numbers[7].bytes);
  841. buf_incrpos(extrablob, numbers[7].bytes);
  842. /* iqmp */
  843. numbers[8].bytes = buf_getint(extrablob);
  844. numbers[8].start = buf_getptr(extrablob, numbers[8].bytes);
  845. buf_incrpos(extrablob, numbers[8].bytes);
  846. nnumbers = 9;
  847. header = "-----BEGIN RSA PRIVATE KEY-----\n";
  848. footer = "-----END RSA PRIVATE KEY-----\n";
  849. }
  850. #endif /* DROPBEAR_RSA */
  851. #ifdef DROPBEAR_DSS
  852. if (key->type == DROPBEAR_SIGNKEY_DSS) {
  853. /* p */
  854. numbers[1].bytes = buf_getint(keyblob);
  855. numbers[1].start = buf_getptr(keyblob, numbers[1].bytes);
  856. buf_incrpos(keyblob, numbers[1].bytes);
  857. /* q */
  858. numbers[2].bytes = buf_getint(keyblob);
  859. numbers[2].start = buf_getptr(keyblob, numbers[2].bytes);
  860. buf_incrpos(keyblob, numbers[2].bytes);
  861. /* g */
  862. numbers[3].bytes = buf_getint(keyblob);
  863. numbers[3].start = buf_getptr(keyblob, numbers[3].bytes);
  864. buf_incrpos(keyblob, numbers[3].bytes);
  865. /* y */
  866. numbers[4].bytes = buf_getint(keyblob);
  867. numbers[4].start = buf_getptr(keyblob, numbers[4].bytes);
  868. buf_incrpos(keyblob, numbers[4].bytes);
  869. /* x */
  870. numbers[5].bytes = buf_getint(keyblob);
  871. numbers[5].start = buf_getptr(keyblob, numbers[5].bytes);
  872. buf_incrpos(keyblob, numbers[5].bytes);
  873. nnumbers = 6;
  874. header = "-----BEGIN DSA PRIVATE KEY-----\n";
  875. footer = "-----END DSA PRIVATE KEY-----\n";
  876. }
  877. #endif /* DROPBEAR_DSS */
  878. /*
  879. * Now count up the total size of the ASN.1 encoded integers,
  880. * so as to determine the length of the containing SEQUENCE.
  881. */
  882. len = 0;
  883. for (i = 0; i < nnumbers; i++) {
  884. len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
  885. len += numbers[i].bytes;
  886. }
  887. seqlen = len;
  888. /* Now add on the SEQUENCE header. */
  889. len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
  890. /* Round up to the cipher block size, ensuring we have at least one
  891. * byte of padding (see below). */
  892. outlen = len;
  893. if (passphrase)
  894. outlen = (outlen+8) &~ 7;
  895. /*
  896. * Now we know how big outblob needs to be. Allocate it.
  897. */
  898. outblob = (unsigned char*)m_malloc(outlen);
  899. /*
  900. * And write the data into it.
  901. */
  902. pos = 0;
  903. pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
  904. for (i = 0; i < nnumbers; i++) {
  905. pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
  906. memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
  907. pos += numbers[i].bytes;
  908. }
  909. } /* end RSA and DSS handling */
  910. #ifdef DROPBEAR_ECDSA
  911. if (key->type == DROPBEAR_SIGNKEY_ECDSA_NISTP256
  912. || key->type == DROPBEAR_SIGNKEY_ECDSA_NISTP384
  913. || key->type == DROPBEAR_SIGNKEY_ECDSA_NISTP521) {
  914. /* SEC1 V2 appendix c.4
  915. ECPrivateKey ::= SEQUENCE {
  916. version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
  917. privateKey OCTET STRING,
  918. parameters [0] ECDomainParameters {{ SECGCurveNames }} OPTIONAL,
  919. publicKey [1] BIT STRING OPTIONAL
  920. }
  921. */
  922. buffer *seq_buf = buf_new(400);
  923. ecc_key **eck = (ecc_key**)signkey_key_ptr(key, key->type);
  924. const long curve_size = (*eck)->dp->size;
  925. int curve_oid_len = 0;
  926. const void* curve_oid = NULL;
  927. unsigned long pubkey_size = 2*curve_size+1;
  928. int k_size;
  929. int err = 0;
  930. /* version. less than 10 bytes */
  931. buf_incrwritepos(seq_buf,
  932. ber_write_id_len(buf_getwriteptr(seq_buf, 10), 2, 1, 0));
  933. buf_putbyte(seq_buf, 1);
  934. /* privateKey */
  935. k_size = mp_unsigned_bin_size((*eck)->k);
  936. dropbear_assert(k_size <= curve_size);
  937. buf_incrwritepos(seq_buf,
  938. ber_write_id_len(buf_getwriteptr(seq_buf, 10), 4, k_size, 0));
  939. mp_to_unsigned_bin((*eck)->k, buf_getwriteptr(seq_buf, k_size));
  940. buf_incrwritepos(seq_buf, k_size);
  941. /* SECGCurveNames */
  942. switch (key->type)
  943. {
  944. case DROPBEAR_SIGNKEY_ECDSA_NISTP256:
  945. curve_oid_len = sizeof(OID_SEC256R1_BLOB);
  946. curve_oid = OID_SEC256R1_BLOB;
  947. break;
  948. case DROPBEAR_SIGNKEY_ECDSA_NISTP384:
  949. curve_oid_len = sizeof(OID_SEC384R1_BLOB);
  950. curve_oid = OID_SEC384R1_BLOB;
  951. break;
  952. case DROPBEAR_SIGNKEY_ECDSA_NISTP521:
  953. curve_oid_len = sizeof(OID_SEC521R1_BLOB);
  954. curve_oid = OID_SEC521R1_BLOB;
  955. break;
  956. default:
  957. dropbear_exit("Internal error");
  958. }
  959. buf_incrwritepos(seq_buf,
  960. ber_write_id_len(buf_getwriteptr(seq_buf, 10), 0, 2+curve_oid_len, 0xa0));
  961. /* object == 6 */
  962. buf_incrwritepos(seq_buf,
  963. ber_write_id_len(buf_getwriteptr(seq_buf, 10), 6, curve_oid_len, 0));
  964. buf_putbytes(seq_buf, curve_oid, curve_oid_len);
  965. buf_incrwritepos(seq_buf,
  966. ber_write_id_len(buf_getwriteptr(seq_buf, 10), 1, 2+1+pubkey_size, 0xa0));
  967. buf_incrwritepos(seq_buf,
  968. ber_write_id_len(buf_getwriteptr(seq_buf, 10), 3, 1+pubkey_size, 0));
  969. buf_putbyte(seq_buf, 0);
  970. err = ecc_ansi_x963_export(*eck, buf_getwriteptr(seq_buf, pubkey_size), &pubkey_size);
  971. if (err != CRYPT_OK) {
  972. dropbear_exit("ECC error");
  973. }
  974. buf_incrwritepos(seq_buf, pubkey_size);
  975. buf_setpos(seq_buf, 0);
  976. outblob = (unsigned char*)m_malloc(1000);
  977. pos = 0;
  978. pos += ber_write_id_len(outblob+pos, 16, seq_buf->len, ASN1_CONSTRUCTED);
  979. memcpy(&outblob[pos], seq_buf->data, seq_buf->len);
  980. pos += seq_buf->len;
  981. len = pos;
  982. outlen = len;
  983. buf_burn(seq_buf);
  984. buf_free(seq_buf);
  985. seq_buf = NULL;
  986. header = "-----BEGIN EC PRIVATE KEY-----\n";
  987. footer = "-----END EC PRIVATE KEY-----\n";
  988. }
  989. #endif
  990. /*
  991. * Padding on OpenSSH keys is deterministic. The number of
  992. * padding bytes is always more than zero, and always at most
  993. * the cipher block length. The value of each padding byte is
  994. * equal to the number of padding bytes. So a plaintext that's
  995. * an exact multiple of the block size will be padded with 08
  996. * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
  997. * plaintext one byte less than a multiple of the block size
  998. * will be padded with just 01.
  999. *
  1000. * This enables the OpenSSL key decryption function to strip
  1001. * off the padding algorithmically and return the unpadded
  1002. * plaintext to the next layer: it looks at the final byte, and
  1003. * then expects to find that many bytes at the end of the data
  1004. * with the same value. Those are all removed and the rest is
  1005. * returned.
  1006. */
  1007. dropbear_assert(pos == len);
  1008. while (pos < outlen) {
  1009. outblob[pos++] = outlen - len;
  1010. }
  1011. /*
  1012. * Encrypt the key.
  1013. */
  1014. if (passphrase) {
  1015. fprintf(stderr, "Encrypted keys aren't supported currently\n");
  1016. goto error;
  1017. }
  1018. /*
  1019. * And save it. We'll use Unix line endings just in case it's
  1020. * subsequently transferred in binary mode.
  1021. */
  1022. if (strlen(filename) == 1 && filename[0] == '-') {
  1023. fp = stdout;
  1024. } else {
  1025. fp = fopen(filename, "wb"); /* ensure Unix line endings */
  1026. }
  1027. if (!fp) {
  1028. fprintf(stderr, "Failed opening output file\n");
  1029. goto error;
  1030. }
  1031. fputs(header, fp);
  1032. base64_encode_fp(fp, outblob, outlen, 64);
  1033. fputs(footer, fp);
  1034. fclose(fp);
  1035. ret = 1;
  1036. error:
  1037. if (outblob) {
  1038. memset(outblob, 0, outlen);
  1039. m_free(outblob);
  1040. }
  1041. if (keyblob) {
  1042. buf_burn(keyblob);
  1043. buf_free(keyblob);
  1044. }
  1045. if (extrablob) {
  1046. buf_burn(extrablob);
  1047. buf_free(extrablob);
  1048. }
  1049. return ret;
  1050. }
  1051. #if 0
  1052. /* XXX TODO ssh.com stuff isn't going yet */
  1053. /* ----------------------------------------------------------------------
  1054. * Code to read ssh.com private keys.
  1055. */
  1056. /*
  1057. * The format of the base64 blob is largely ssh2-packet-formatted,
  1058. * except that mpints are a bit different: they're more like the
  1059. * old ssh1 mpint. You have a 32-bit bit count N, followed by
  1060. * (N+7)/8 bytes of data.
  1061. *
  1062. * So. The blob contains:
  1063. *
  1064. * - uint32 0x3f6ff9eb (magic number)
  1065. * - uint32 size (total blob size)
  1066. * - string key-type (see below)
  1067. * - string cipher-type (tells you if key is encrypted)
  1068. * - string encrypted-blob
  1069. *
  1070. * (The first size field includes the size field itself and the
  1071. * magic number before it. All other size fields are ordinary ssh2
  1072. * strings, so the size field indicates how much data is to
  1073. * _follow_.)
  1074. *
  1075. * The encrypted blob, once decrypted, contains a single string
  1076. * which in turn contains the payload. (This allows padding to be
  1077. * added after that string while still making it clear where the
  1078. * real payload ends. Also it probably makes for a reasonable
  1079. * decryption check.)
  1080. *
  1081. * The payload blob, for an RSA key, contains:
  1082. * - mpint e
  1083. * - mpint d
  1084. * - mpint n (yes, the public and private stuff is intermixed)
  1085. * - mpint u (presumably inverse of p mod q)
  1086. * - mpint p (p is the smaller prime)
  1087. * - mpint q (q is the larger)
  1088. *
  1089. * For a DSA key, the payload blob contains:
  1090. * - uint32 0
  1091. * - mpint p
  1092. * - mpint g
  1093. * - mpint q
  1094. * - mpint y
  1095. * - mpint x
  1096. *
  1097. * Alternatively, if the parameters are `predefined', that
  1098. * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
  1099. * containing some predefined parameter specification. *shudder*,
  1100. * but I doubt we'll encounter this in real life.
  1101. *
  1102. * The key type strings are ghastly. The RSA key I looked at had a
  1103. * type string of
  1104. *
  1105. * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
  1106. *
  1107. * and the DSA key wasn't much better:
  1108. *
  1109. * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
  1110. *
  1111. * It isn't clear that these will always be the same. I think it
  1112. * might be wise just to look at the `if-modn{sign{rsa' and
  1113. * `dl-modp{sign{dsa' prefixes.
  1114. *
  1115. * Finally, the encryption. The cipher-type string appears to be
  1116. * either `none' or `3des-cbc'. Looks as if this is SSH2-style
  1117. * 3des-cbc (i.e. outer cbc rather than inner). The key is created
  1118. * from the passphrase by means of yet another hashing faff:
  1119. *
  1120. * - first 16 bytes are MD5(passphrase)
  1121. * - next 16 bytes are MD5(passphrase || first 16 bytes)
  1122. * - if there were more, they'd be MD5(passphrase || first 32),
  1123. * and so on.
  1124. */
  1125. #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
  1126. struct sshcom_key {
  1127. char comment[256]; /* allowing any length is overkill */
  1128. unsigned char *keyblob;
  1129. int keyblob_len, keyblob_size;
  1130. };
  1131. static struct sshcom_key *load_sshcom_key(const char *filename)
  1132. {
  1133. struct sshcom_key *ret;
  1134. FILE *fp;
  1135. char buffer[256];
  1136. int len;
  1137. char *errmsg, *p;
  1138. int headers_done;
  1139. char base64_bit[4];
  1140. int base64_chars = 0;
  1141. ret = snew(struct sshcom_key);
  1142. ret->comment[0] = '\0';
  1143. ret->keyblob = NULL;
  1144. ret->keyblob_len = ret->keyblob_size = 0;
  1145. fp = fopen(filename, "r");
  1146. if (!fp) {
  1147. errmsg = "Unable to open key file";
  1148. goto error;
  1149. }
  1150. if (!fgets(buffer, sizeof(buffer), fp) ||
  1151. 0 != strcmp(buffer, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
  1152. errmsg = "File does not begin with ssh.com key header";
  1153. goto error;
  1154. }
  1155. headers_done = 0;
  1156. while (1) {
  1157. if (!fgets(buffer, sizeof(buffer), fp)) {
  1158. errmsg = "Unexpected end of file";
  1159. goto error;
  1160. }
  1161. if (!strcmp(buffer, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
  1162. break; /* done */
  1163. if ((p = strchr(buffer, ':')) != NULL) {
  1164. if (headers_done) {
  1165. errmsg = "Header found in body of key data";
  1166. goto error;
  1167. }
  1168. *p++ = '\0';
  1169. while (*p && isspace((unsigned char)*p)) p++;
  1170. /*
  1171. * Header lines can end in a trailing backslash for
  1172. * continuation.
  1173. */
  1174. while ((len = strlen(p)) > (int)(sizeof(buffer) - (p-buffer) -1) ||
  1175. p[len-1] != '\n' || p[len-2] == '\\') {
  1176. if (len > (int)((p-buffer) + sizeof(buffer)-2)) {
  1177. errmsg = "Header line too long to deal with";
  1178. goto error;
  1179. }
  1180. if (!fgets(p+len-2, sizeof(buffer)-(p-buffer)-(len-2), fp)) {
  1181. errmsg = "Unexpected end of file";
  1182. goto error;
  1183. }
  1184. }
  1185. p[strcspn(p, "\n")] = '\0';
  1186. if (!strcmp(buffer, "Comment")) {
  1187. /* Strip quotes in comment if present. */
  1188. if (p[0] == '"' && p[strlen(p)-1] == '"') {
  1189. p++;
  1190. p[strlen(p)-1] = '\0';
  1191. }
  1192. strncpy(ret->comment, p, sizeof(ret->comment));
  1193. ret->comment[sizeof(ret->comment)-1] = '\0';
  1194. }
  1195. } else {
  1196. headers_done = 1;
  1197. p = buffer;
  1198. while (isbase64(*p)) {
  1199. base64_bit[base64_chars++] = *p;
  1200. if (base64_chars == 4) {
  1201. unsigned char out[3];
  1202. base64_chars = 0;
  1203. len = base64_decode_atom(base64_bit, out);
  1204. if (len <= 0) {
  1205. errmsg = "Invalid base64 encoding";
  1206. goto error;
  1207. }
  1208. if (ret->keyblob_len + len > ret->keyblob_size) {
  1209. ret->keyblob_size = ret->keyblob_len + len + 256;
  1210. ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
  1211. unsigned char);
  1212. }
  1213. memcpy(ret->keyblob + ret->keyblob_len, out, len);
  1214. ret->keyblob_len += len;
  1215. }
  1216. p++;
  1217. }
  1218. }
  1219. }
  1220. if (ret->keyblob_len == 0 || !ret->keyblob) {
  1221. errmsg = "Key body not present";
  1222. goto error;
  1223. }
  1224. return ret;
  1225. error:
  1226. if (ret) {
  1227. if (ret->keyblob) {
  1228. memset(ret->keyblob, 0, ret->keyblob_size);
  1229. m_free(ret->keyblob);
  1230. }
  1231. memset(ret, 0, sizeof(*ret));
  1232. m_free(ret);
  1233. }
  1234. return NULL;
  1235. }
  1236. int sshcom_encrypted(const char *filename, char **comment)
  1237. {
  1238. struct sshcom_key *key = load_sshcom_key(filename);
  1239. int pos, len, answer;
  1240. *comment = NULL;
  1241. if (!key)
  1242. return 0;
  1243. /*
  1244. * Check magic number.
  1245. */
  1246. if (GET_32BIT(key->keyblob) != 0x3f6ff9eb)
  1247. return 0; /* key is invalid */
  1248. /*
  1249. * Find the cipher-type string.
  1250. */
  1251. answer = 0;
  1252. pos = 8;
  1253. if (key->keyblob_len < pos+4)
  1254. goto done; /* key is far too short */
  1255. len = toint(GET_32BIT(key->keyblob + pos));
  1256. if (len < 0 || len > key->keyblob_len - pos - 4)
  1257. goto done; /* key is far too short */
  1258. pos += 4 + len; /* skip key type */
  1259. len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
  1260. if (len < 0 || len > key->keyblob_len - pos - 4)
  1261. goto done; /* cipher type string is incomplete */
  1262. if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
  1263. answer = 1;
  1264. done:
  1265. *comment = dupstr(key->comment);
  1266. memset(key->keyblob, 0, key->keyblob_size);
  1267. m_free(key->keyblob);
  1268. memset(key, 0, sizeof(*key));
  1269. m_free(key);
  1270. return answer;
  1271. }
  1272. static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
  1273. {
  1274. unsigned bits, bytes;
  1275. unsigned char *d = (unsigned char *) data;
  1276. if (len < 4)
  1277. goto error;
  1278. bits = GET_32BIT(d);
  1279. bytes = (bits + 7) / 8;
  1280. if (len < 4+bytes)
  1281. goto error;
  1282. ret->start = d + 4;
  1283. ret->bytes = bytes;
  1284. return bytes+4;
  1285. error:
  1286. ret->start = NULL;
  1287. ret->bytes = -1;
  1288. return len; /* ensure further calls fail as well */
  1289. }
  1290. static int sshcom_put_mpint(void *target, void *data, int len)
  1291. {
  1292. unsigned char *d = (unsigned char *)target;
  1293. unsigned char *i = (unsigned char *)data;
  1294. int bits = len * 8 - 1;
  1295. while (bits > 0) {
  1296. if (*i & (1 << (bits & 7)))
  1297. break;
  1298. if (!(bits-- & 7))
  1299. i++, len--;
  1300. }
  1301. PUT_32BIT(d, bits+1);
  1302. memcpy(d+4, i, len);
  1303. return len+4;
  1304. }
  1305. sign_key *sshcom_read(const char *filename, char *passphrase)
  1306. {
  1307. struct sshcom_key *key = load_sshcom_key(filename);
  1308. char *errmsg;
  1309. int pos, len;
  1310. const char prefix_rsa[] = "if-modn{sign{rsa";
  1311. const char prefix_dsa[] = "dl-modp{sign{dsa";
  1312. enum { RSA, DSA } type;
  1313. int encrypted;
  1314. char *ciphertext;
  1315. int cipherlen;
  1316. struct ssh2_userkey *ret = NULL, *retkey;
  1317. const struct ssh_signkey *alg;
  1318. unsigned char *blob = NULL;
  1319. int blobsize = 0, publen, privlen;
  1320. if (!key)
  1321. return NULL;
  1322. /*
  1323. * Check magic number.
  1324. */
  1325. if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
  1326. errmsg = "Key does not begin with magic number";
  1327. goto error;
  1328. }
  1329. /*
  1330. * Determine the key type.
  1331. */
  1332. pos = 8;
  1333. if (key->keyblob_len < pos+4 ||
  1334. (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
  1335. errmsg = "Key blob does not contain a key type string";
  1336. goto error;
  1337. }
  1338. if (len > sizeof(prefix_rsa) - 1 &&
  1339. !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
  1340. type = RSA;
  1341. } else if (len > sizeof(prefix_dsa) - 1 &&
  1342. !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
  1343. type = DSA;
  1344. } else {
  1345. errmsg = "Key is of unknown type";
  1346. goto error;
  1347. }
  1348. pos += 4+len;
  1349. /*
  1350. * Determine the cipher type.
  1351. */
  1352. if (key->keyblob_len < pos+4 ||
  1353. (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
  1354. errmsg = "Key blob does not contain a cipher type string";
  1355. goto error;
  1356. }
  1357. if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
  1358. encrypted = 0;
  1359. else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
  1360. encrypted = 1;
  1361. else {
  1362. errmsg = "Key encryption is of unknown type";
  1363. goto error;
  1364. }
  1365. pos += 4+len;
  1366. /*
  1367. * Get hold of the encrypted part of the key.
  1368. */
  1369. if (key->keyblob_len < pos+4 ||
  1370. (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
  1371. errmsg = "Key blob does not contain actual key data";
  1372. goto error;
  1373. }
  1374. ciphertext = (char *)key->keyblob + pos + 4;
  1375. cipherlen = len;
  1376. if (cipherlen == 0) {
  1377. errmsg = "Length of key data is zero";
  1378. goto error;
  1379. }
  1380. /*
  1381. * Decrypt it if necessary.
  1382. */
  1383. if (encrypted) {
  1384. /*
  1385. * Derive encryption key from passphrase and iv/salt:
  1386. *
  1387. * - let block A equal MD5(passphrase)
  1388. * - let block B equal MD5(passphrase || A)
  1389. * - block C would be MD5(passphrase || A || B) and so on
  1390. * - encryption key is the first N bytes of A || B
  1391. */
  1392. struct MD5Context md5c;
  1393. unsigned char keybuf[32], iv[8];
  1394. if (cipherlen % 8 != 0) {
  1395. errmsg = "Encrypted part of key is not a multiple of cipher block"
  1396. " size";
  1397. goto error;
  1398. }
  1399. MD5Init(&md5c);
  1400. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  1401. MD5Final(keybuf, &md5c);
  1402. MD5Init(&md5c);
  1403. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  1404. MD5Update(&md5c, keybuf, 16);
  1405. MD5Final(keybuf+16, &md5c);
  1406. /*
  1407. * Now decrypt the key blob.
  1408. */
  1409. memset(iv, 0, sizeof(iv));
  1410. des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
  1411. cipherlen);
  1412. memset(&md5c, 0, sizeof(md5c));
  1413. memset(keybuf, 0, sizeof(keybuf));
  1414. /*
  1415. * Hereafter we return WRONG_PASSPHRASE for any parsing
  1416. * error. (But only if we've just tried to decrypt it!
  1417. * Returning WRONG_PASSPHRASE for an unencrypted key is
  1418. * automatic doom.)
  1419. */
  1420. if (encrypted)
  1421. ret = SSH2_WRONG_PASSPHRASE;
  1422. }
  1423. /*
  1424. * Strip away the containing string to get to the real meat.
  1425. */
  1426. len = toint(GET_32BIT(ciphertext));
  1427. if (len < 0 || len > cipherlen-4) {
  1428. errmsg = "containing string was ill-formed";
  1429. goto error;
  1430. }
  1431. ciphertext += 4;
  1432. cipherlen = len;
  1433. /*
  1434. * Now we break down into RSA versus DSA. In either case we'll
  1435. * construct public and private blobs in our own format, and
  1436. * end up feeding them to alg->createkey().
  1437. */
  1438. blobsize = cipherlen + 256;
  1439. blob = snewn(blobsize, unsigned char);
  1440. privlen = 0;
  1441. if (type == RSA) {
  1442. struct mpint_pos n, e, d, u, p, q;
  1443. int pos = 0;
  1444. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
  1445. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
  1446. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
  1447. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
  1448. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
  1449. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
  1450. if (!q.start) {
  1451. errmsg = "key data did not contain six integers";
  1452. goto error;
  1453. }
  1454. alg = &ssh_rsa;
  1455. pos = 0;
  1456. pos += put_string(blob+pos, "ssh-rsa", 7);
  1457. pos += put_mp(blob+pos, e.start, e.bytes);
  1458. pos += put_mp(blob+pos, n.start, n.bytes);
  1459. publen = pos;
  1460. pos += put_string(blob+pos, d.start, d.bytes);
  1461. pos += put_mp(blob+pos, q.start, q.bytes);
  1462. pos += put_mp(blob+pos, p.start, p.bytes);
  1463. pos += put_mp(blob+pos, u.start, u.bytes);
  1464. privlen = pos - publen;
  1465. } else if (type == DSA) {
  1466. struct mpint_pos p, q, g, x, y;
  1467. int pos = 4;
  1468. if (GET_32BIT(ciphertext) != 0) {
  1469. errmsg = "predefined DSA parameters not supported";
  1470. goto error;
  1471. }
  1472. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
  1473. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
  1474. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
  1475. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
  1476. pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
  1477. if (!x.start) {
  1478. errmsg = "key data did not contain five integers";
  1479. goto error;
  1480. }
  1481. alg = &ssh_dss;
  1482. pos = 0;
  1483. pos += put_string(blob+pos, "ssh-dss", 7);
  1484. pos += put_mp(blob+pos, p.start, p.bytes);
  1485. pos += put_mp(blob+pos, q.start, q.bytes);
  1486. pos += put_mp(blob+pos, g.start, g.bytes);
  1487. pos += put_mp(blob+pos, y.start, y.bytes);
  1488. publen = pos;
  1489. pos += put_mp(blob+pos, x.start, x.bytes);
  1490. privlen = pos - publen;
  1491. } else
  1492. return NULL;
  1493. dropbear_assert(privlen > 0); /* should have bombed by now if not */
  1494. retkey = snew(struct ssh2_userkey);
  1495. retkey->alg = alg;
  1496. retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
  1497. if (!retkey->data) {
  1498. m_free(retkey);
  1499. errmsg = "unable to create key data structure";
  1500. goto error;
  1501. }
  1502. retkey->comment = dupstr(key->comment);
  1503. errmsg = NULL; /* no error */
  1504. ret = retkey;
  1505. error:
  1506. if (blob) {
  1507. memset(blob, 0, blobsize);
  1508. m_free(blob);
  1509. }
  1510. memset(key->keyblob, 0, key->keyblob_size);
  1511. m_free(key->keyblob);
  1512. memset(key, 0, sizeof(*key));
  1513. m_free(key);
  1514. return ret;
  1515. }
  1516. int sshcom_write(const char *filename, sign_key *key,
  1517. char *passphrase)
  1518. {
  1519. unsigned char *pubblob, *privblob;
  1520. int publen, privlen;
  1521. unsigned char *outblob;
  1522. int outlen;
  1523. struct mpint_pos numbers[6];
  1524. int nnumbers, initial_zero, pos, lenpos, i;
  1525. char *type;
  1526. char *ciphertext;
  1527. int cipherlen;
  1528. int ret = 0;
  1529. FILE *fp;
  1530. /*
  1531. * Fetch the key blobs.
  1532. */
  1533. pubblob = key->alg->public_blob(key->data, &publen);
  1534. privblob = key->alg->private_blob(key->data, &privlen);
  1535. outblob = NULL;
  1536. /*
  1537. * Find the sequence of integers to be encoded into the OpenSSH
  1538. * key blob, and also decide on the header line.
  1539. */
  1540. if (key->alg == &ssh_rsa) {
  1541. int pos;
  1542. struct mpint_pos n, e, d, p, q, iqmp;
  1543. pos = 4 + GET_32BIT(pubblob);
  1544. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
  1545. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
  1546. pos = 0;
  1547. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
  1548. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
  1549. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
  1550. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
  1551. dropbear_assert(e.start && iqmp.start); /* can't go wrong */
  1552. numbers[0] = e;
  1553. numbers[1] = d;
  1554. numbers[2] = n;
  1555. numbers[3] = iqmp;
  1556. numbers[4] = q;
  1557. numbers[5] = p;
  1558. nnumbers = 6;
  1559. initial_zero = 0;
  1560. type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
  1561. } else if (key->alg == &ssh_dss) {
  1562. int pos;
  1563. struct mpint_pos p, q, g, y, x;
  1564. pos = 4 + GET_32BIT(pubblob);
  1565. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
  1566. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
  1567. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
  1568. pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
  1569. pos = 0;
  1570. pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
  1571. dropbear_assert(y.start && x.start); /* can't go wrong */
  1572. numbers[0] = p;
  1573. numbers[1] = g;
  1574. numbers[2] = q;
  1575. numbers[3] = y;
  1576. numbers[4] = x;
  1577. nnumbers = 5;
  1578. initial_zero = 1;
  1579. type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
  1580. } else {
  1581. dropbear_assert(0); /* zoinks! */
  1582. }
  1583. /*
  1584. * Total size of key blob will be somewhere under 512 plus
  1585. * combined length of integers. We'll calculate the more
  1586. * precise size as we construct the blob.
  1587. */
  1588. outlen = 512;
  1589. for (i = 0; i < nnumbers; i++)
  1590. outlen += 4 + numbers[i].bytes;
  1591. outblob = snewn(outlen, unsigned char);
  1592. /*
  1593. * Create the unencrypted key blob.
  1594. */
  1595. pos = 0;
  1596. PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
  1597. pos += 4; /* length field, fill in later */
  1598. pos += put_string(outblob+pos, type, strlen(type));
  1599. {
  1600. char *ciphertype = passphrase ? "3des-cbc" : "none";
  1601. pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
  1602. }
  1603. lenpos = pos; /* remember this position */
  1604. pos += 4; /* encrypted-blob size */
  1605. pos += 4; /* encrypted-payload size */
  1606. if (initial_zero) {
  1607. PUT_32BIT(outblob+pos, 0);
  1608. pos += 4;
  1609. }
  1610. for (i = 0; i < nnumbers; i++)
  1611. pos += sshcom_put_mpint(outblob+pos,
  1612. numbers[i].start, numbers[i].bytes);
  1613. /* Now wrap up the encrypted payload. */
  1614. PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
  1615. /* Pad encrypted blob to a multiple of cipher block size. */
  1616. if (passphrase) {
  1617. int padding = -(pos - (lenpos+4)) & 7;
  1618. while (padding--)
  1619. outblob[pos++] = random_byte();
  1620. }
  1621. ciphertext = (char *)outblob+lenpos+4;
  1622. cipherlen = pos - (lenpos+4);
  1623. dropbear_assert(!passphrase || cipherlen % 8 == 0);
  1624. /* Wrap up the encrypted blob string. */
  1625. PUT_32BIT(outblob+lenpos, cipherlen);
  1626. /* And finally fill in the total length field. */
  1627. PUT_32BIT(outblob+4, pos);
  1628. dropbear_assert(pos < outlen);
  1629. /*
  1630. * Encrypt the key.
  1631. */
  1632. if (passphrase) {
  1633. /*
  1634. * Derive encryption key from passphrase and iv/salt:
  1635. *
  1636. * - let block A equal MD5(passphrase)
  1637. * - let block B equal MD5(passphrase || A)
  1638. * - block C would be MD5(passphrase || A || B) and so on
  1639. * - encryption key is the first N bytes of A || B
  1640. */
  1641. struct MD5Context md5c;
  1642. unsigned char keybuf[32], iv[8];
  1643. MD5Init(&md5c);
  1644. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  1645. MD5Final(keybuf, &md5c);
  1646. MD5Init(&md5c);
  1647. MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
  1648. MD5Update(&md5c, keybuf, 16);
  1649. MD5Final(keybuf+16, &md5c);
  1650. /*
  1651. * Now decrypt the key blob.
  1652. */
  1653. memset(iv, 0, sizeof(iv));
  1654. des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
  1655. cipherlen);
  1656. memset(&md5c, 0, sizeof(md5c));
  1657. memset(keybuf, 0, sizeof(keybuf));
  1658. }
  1659. /*
  1660. * And save it. We'll use Unix line endings just in case it's
  1661. * subsequently transferred in binary mode.
  1662. */
  1663. fp = fopen(filename, "wb"); /* ensure Unix line endings */
  1664. if (!fp)
  1665. goto error;
  1666. fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
  1667. fprintf(fp, "Comment: \"");
  1668. /*
  1669. * Comment header is broken with backslash-newline if it goes
  1670. * over 70 chars. Although it's surrounded by quotes, it
  1671. * _doesn't_ escape backslashes or quotes within the string.
  1672. * Don't ask me, I didn't design it.
  1673. */
  1674. {
  1675. int slen = 60; /* starts at 60 due to "Comment: " */
  1676. char *c = key->comment;
  1677. while ((int)strlen(c) > slen) {
  1678. fprintf(fp, "%.*s\\\n", slen, c);
  1679. c += slen;
  1680. slen = 70; /* allow 70 chars on subsequent lines */
  1681. }
  1682. fprintf(fp, "%s\"\n", c);
  1683. }
  1684. base64_encode_fp(fp, outblob, pos, 70);
  1685. fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
  1686. fclose(fp);
  1687. ret = 1;
  1688. error:
  1689. if (outblob) {
  1690. memset(outblob, 0, outlen);
  1691. m_free(outblob);
  1692. }
  1693. if (privblob) {
  1694. memset(privblob, 0, privlen);
  1695. m_free(privblob);
  1696. }
  1697. if (pubblob) {
  1698. memset(pubblob, 0, publen);
  1699. m_free(pubblob);
  1700. }
  1701. return ret;
  1702. }
  1703. #endif /* ssh.com stuff disabled */
  1704. /* From PuTTY misc.c */
  1705. static int toint(unsigned u)
  1706. {
  1707. /*
  1708. * Convert an unsigned to an int, without running into the
  1709. * undefined behaviour which happens by the strict C standard if
  1710. * the value overflows. You'd hope that sensible compilers would
  1711. * do the sensible thing in response to a cast, but actually I
  1712. * don't trust modern compilers not to do silly things like
  1713. * assuming that _obviously_ you wouldn't have caused an overflow
  1714. * and so they can elide an 'if (i < 0)' test immediately after
  1715. * the cast.
  1716. *
  1717. * Sensible compilers ought of course to optimise this entire
  1718. * function into 'just return the input value'!
  1719. */
  1720. if (u <= (unsigned)INT_MAX)
  1721. return (int)u;
  1722. else if (u >= (unsigned)INT_MIN) /* wrap in cast _to_ unsigned is OK */
  1723. return INT_MIN + (int)(u - (unsigned)INT_MIN);
  1724. else
  1725. return INT_MIN; /* fallback; should never occur on binary machines */
  1726. }