Search in sources :

Example 1 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class TunnelController method createPrivateKey.

/**
 * @return success
 */
private boolean createPrivateKey() {
    I2PClient client = I2PClientFactory.createClient();
    File keyFile = getPrivateKeyFile();
    if (keyFile == null) {
        log("No filename specified for the private key");
        return false;
    }
    if (keyFile.exists()) {
        // log("Not overwriting existing private keys in " + keyFile.getAbsolutePath());
        return true;
    } else {
        File parent = keyFile.getParentFile();
        if ((parent != null) && (!parent.exists()))
            parent.mkdirs();
    }
    FileOutputStream fos = null;
    try {
        fos = new SecureFileOutputStream(keyFile);
        SigType stype = PREFERRED_SIGTYPE;
        String st = _config.getProperty(OPT_SIG_TYPE);
        if (st != null) {
            SigType type = SigType.parseSigType(st);
            if (type != null && type.isAvailable())
                stype = type;
            else
                log("Unsupported sig type " + st + ", reverting to " + stype);
        }
        Destination dest = client.createDestination(fos, stype);
        String destStr = dest.toBase64();
        log("Private key created and saved in " + keyFile.getAbsolutePath());
        log("You should backup this file in a secure place.");
        log("New destination: " + destStr);
        String b32 = dest.toBase32();
        log("Base32: " + b32);
        File backupDir = new SecureFile(I2PAppContext.getGlobalContext().getConfigDir(), KEY_BACKUP_DIR);
        if (backupDir.isDirectory() || backupDir.mkdir()) {
            String name = b32 + '-' + I2PAppContext.getGlobalContext().clock().now() + ".dat";
            File backup = new File(backupDir, name);
            if (FileUtil.copy(keyFile, backup, false, true)) {
                SecureFileOutputStream.setPerms(backup);
                log("Private key backup saved to " + backup.getAbsolutePath());
            }
        }
    } catch (I2PException ie) {
        if (_log.shouldLog(Log.ERROR))
            _log.error("Error creating new destination", ie);
        log("Error creating new destination: " + ie.getMessage());
        return false;
    } catch (IOException ioe) {
        if (_log.shouldLog(Log.ERROR))
            _log.error("Error creating writing the destination to " + keyFile.getAbsolutePath(), ioe);
        log("Error writing the keys to " + keyFile.getAbsolutePath());
        return false;
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (IOException ioe) {
            }
    }
    return true;
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) SecureFile(net.i2p.util.SecureFile) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) FileOutputStream(java.io.FileOutputStream) I2PClient(net.i2p.client.I2PClient) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) SecureFile(net.i2p.util.SecureFile) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File) SigType(net.i2p.crypto.SigType)

Example 2 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class NewsFetcher method gunzip.

/**
 *  Gunzip the file
 *
 *  @since 0.9.17
 */
private static void gunzip(File from, File to) throws IOException {
    ReusableGZIPInputStream in = ReusableGZIPInputStream.acquire();
    OutputStream out = null;
    try {
        in.initialize(new FileInputStream(from));
        out = new SecureFileOutputStream(to);
        DataHelper.copy(in, out);
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
        ReusableGZIPInputStream.release(in);
    }
}
Also used : SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ReusableGZIPInputStream(net.i2p.util.ReusableGZIPInputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 3 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class NewsFetcher method processBlocklistEntries.

/**
 *  Process blocklist entries
 *
 *  @since 0.9.28
 */
private void processBlocklistEntries(BlocklistEntries ble) {
    long oldTime = _context.getProperty(PROP_BLOCKLIST_TIME, 0L);
    if (ble.updated <= oldTime) {
        if (_log.shouldWarn())
            _log.warn("Not processing blocklist " + new Date(ble.updated) + ", already have " + new Date(oldTime));
        return;
    }
    Blocklist bl = _context.blocklist();
    Banlist ban = _context.banlist();
    DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
    fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
    String reason = "Blocklist feed " + new Date(ble.updated);
    int banned = 0;
    for (Iterator<String> iter = ble.entries.iterator(); iter.hasNext(); ) {
        String s = iter.next();
        if (s.length() == 44) {
            byte[] b = Base64.decode(s);
            if (b == null || b.length != Hash.HASH_LENGTH) {
                iter.remove();
                continue;
            }
            Hash h = Hash.create(b);
            if (!ban.isBanlistedForever(h))
                ban.banlistRouterForever(h, reason);
        } else {
            byte[] ip = Addresses.getIP(s);
            if (ip == null) {
                iter.remove();
                continue;
            }
            if (!bl.isBlocklisted(ip))
                bl.add(ip);
        }
        if (++banned >= BlocklistEntries.MAX_ENTRIES) {
            // prevent somebody from destroying the whole network
            break;
        }
    }
    for (String s : ble.removes) {
        if (s.length() == 44) {
            byte[] b = Base64.decode(s);
            if (b == null || b.length != Hash.HASH_LENGTH)
                continue;
            Hash h = Hash.create(b);
            if (ban.isBanlistedForever(h))
                ban.unbanlistRouter(h);
        } else {
            byte[] ip = Addresses.getIP(s);
            if (ip == null)
                continue;
            if (bl.isBlocklisted(ip))
                bl.remove(ip);
        }
    }
    // Save the blocks. We do not save the unblocks.
    File f = new SecureFile(_context.getConfigDir(), BLOCKLIST_DIR);
    f.mkdirs();
    f = new File(f, BLOCKLIST_FILE);
    boolean fail = false;
    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new OutputStreamWriter(new SecureFileOutputStream(f), "UTF-8"));
        out.write("# ");
        out.write(ble.supdated);
        out.newLine();
        banned = 0;
        for (String s : ble.entries) {
            // IPv6
            s = s.replace(':', ';');
            out.write(reason);
            out.write(':');
            out.write(s);
            out.newLine();
            if (++banned >= BlocklistEntries.MAX_ENTRIES)
                break;
        }
    } catch (IOException ioe) {
        _log.error("Error writing blocklist", ioe);
        fail = true;
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
    }
    if (!fail) {
        f.setLastModified(ble.updated);
        String upd = Long.toString(ble.updated);
        _context.router().saveConfig(PROP_BLOCKLIST_TIME, upd);
        _mgr.notifyVersionAvailable(this, _currentURI, BLOCKLIST, "", HTTP, null, upd, "");
    }
    if (_log.shouldWarn())
        _log.warn("Processed " + ble.entries.size() + " blocks and " + ble.removes.size() + " unblocks from news feed");
}
Also used : SecureFile(net.i2p.util.SecureFile) IOException(java.io.IOException) Hash(net.i2p.data.Hash) Date(java.util.Date) RFC822Date(net.i2p.util.RFC822Date) Banlist(net.i2p.router.Banlist) BufferedWriter(java.io.BufferedWriter) Blocklist(net.i2p.router.Blocklist) DateFormat(java.text.DateFormat) OutputStreamWriter(java.io.OutputStreamWriter) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) SU3File(net.i2p.crypto.SU3File) SecureFile(net.i2p.util.SecureFile) File(java.io.File)

Example 4 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class NewsFetcher method persistCRLEntries.

/**
 *  Output any updated CRL entries
 *
 *  @since 0.9.26
 */
private void persistCRLEntries(List<CRLEntry> entries) {
    File dir = new SecureFile(_context.getConfigDir(), "certificates");
    if (!dir.exists() && !dir.mkdir()) {
        _log.error("Failed to create CRL directory " + dir);
        return;
    }
    dir = new SecureFile(dir, "revocations");
    if (!dir.exists() && !dir.mkdir()) {
        _log.error("Failed to create CRL directory " + dir);
        return;
    }
    int i = 0;
    for (CRLEntry e : entries) {
        if (e.id == null || e.data == null) {
            if (_log.shouldWarn())
                _log.warn("Bad CRL entry received");
            continue;
        }
        byte[] bid = DataHelper.getUTF8(e.id);
        byte[] hash = new byte[32];
        _context.sha().calculateHash(bid, 0, bid.length, hash, 0);
        String name = "crl-" + Base64.encode(hash) + ".crl";
        File f = new File(dir, name);
        if (f.exists() && f.lastModified() >= e.updated)
            continue;
        OutputStream out = null;
        try {
            byte[] data = DataHelper.getUTF8(e.data);
            // test for validity
            CertUtil.loadCRL(new ByteArrayInputStream(data));
            out = new SecureFileOutputStream(f);
            out.write(data);
        } catch (GeneralSecurityException gse) {
            _log.error("Bad CRL", gse);
        } catch (IOException ioe) {
            _log.error("Failed to write CRL", ioe);
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException ioe) {
                }
        }
        f.setLastModified(e.updated);
        i++;
    }
    if (i > 0)
        _log.logAlways(Log.WARN, "Stored " + i + " new CRL " + (i > 1 ? "entries" : "entry"));
}
Also used : SecureFile(net.i2p.util.SecureFile) ByteArrayInputStream(java.io.ByteArrayInputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) GeneralSecurityException(java.security.GeneralSecurityException) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) CRLEntry(net.i2p.router.news.CRLEntry) IOException(java.io.IOException) SU3File(net.i2p.crypto.SU3File) SecureFile(net.i2p.util.SecureFile) File(java.io.File)

Example 5 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class NewsFetcher method outputOldNewsXML.

/**
 *  Output in the old format.
 *
 *  @since 0.9.17
 */
private void outputOldNewsXML(NewsMetadata data, List<NewsEntry> entries, String sudVersion, String signingKeyName, File to) throws IOException {
    NewsMetadata.Release latestRelease = data.releases.get(0);
    Writer out = null;
    try {
        out = new BufferedWriter(new OutputStreamWriter(new SecureFileOutputStream(to), "UTF-8"));
        out.write("<!--\n");
        // update metadata in old format
        out.write("<i2p.release ");
        if (latestRelease.i2pVersion != null)
            out.write(" version=\"" + latestRelease.i2pVersion + '"');
        if (latestRelease.minVersion != null)
            out.write(" minVersion=\"" + latestRelease.minVersion + '"');
        if (latestRelease.minJavaVersion != null)
            out.write(" minJavaVersion=\"" + latestRelease.minJavaVersion + '"');
        String su3Torrent = "";
        String su2Torrent = "";
        for (NewsMetadata.Update update : latestRelease.updates) {
            if (update.torrent != null) {
                if ("su3".equals(update.type))
                    su3Torrent = update.torrent;
                else if ("su2".equals(update.type))
                    su2Torrent = update.torrent;
            }
        }
        if (!su2Torrent.isEmpty())
            out.write(" su2Torrent=\"" + su2Torrent + '"');
        if (!su3Torrent.isEmpty())
            out.write(" su3Torrent=\"" + su3Torrent + '"');
        out.write("/>\n");
        // su3 and feed metadata for debugging
        out.write("** News version:\t" + DataHelper.stripHTML(sudVersion) + '\n');
        out.write("** Signed by:\t" + signingKeyName + '\n');
        out.write("** Feed:\t" + DataHelper.stripHTML(data.feedTitle) + '\n');
        out.write("** Feed ID:\t" + DataHelper.stripHTML(data.feedID) + '\n');
        out.write("** Feed Date:\t" + (new Date(data.feedUpdated)) + '\n');
        out.write("-->\n");
        if (entries == null)
            return;
        DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
        // the router sets the JVM time zone to UTC but saves the original here so we can get it
        fmt.setTimeZone(SystemVersion.getSystemTimeZone(_context));
        for (NewsEntry e : entries) {
            if (e.title == null || e.content == null)
                continue;
            Date date = new Date(e.updated);
            out.write("<!-- Entry Date: " + date + " -->\n");
            out.write("<h3>");
            out.write(fmt.format(date));
            out.write(": ");
            out.write(e.title);
            out.write("</h3>\n");
            out.write(e.content);
            out.write("\n\n");
        }
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : NewsMetadata(net.i2p.router.news.NewsMetadata) DateFormat(java.text.DateFormat) OutputStreamWriter(java.io.OutputStreamWriter) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) NewsEntry(net.i2p.router.news.NewsEntry) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter) Date(java.util.Date) RFC822Date(net.i2p.util.RFC822Date) BufferedWriter(java.io.BufferedWriter)

Aggregations

SecureFileOutputStream (net.i2p.util.SecureFileOutputStream)55 IOException (java.io.IOException)50 File (java.io.File)33 OutputStream (java.io.OutputStream)22 OutputStreamWriter (java.io.OutputStreamWriter)21 FileOutputStream (java.io.FileOutputStream)19 BufferedWriter (java.io.BufferedWriter)16 FileInputStream (java.io.FileInputStream)11 SecureFile (net.i2p.util.SecureFile)9 BufferedOutputStream (java.io.BufferedOutputStream)8 PrintWriter (java.io.PrintWriter)7 InputStream (java.io.InputStream)6 GeneralSecurityException (java.security.GeneralSecurityException)6 DataFormatException (net.i2p.data.DataFormatException)6 EncryptedOutputStream (i2p.bote.fileencryption.EncryptedOutputStream)4 KeyStore (java.security.KeyStore)4 X509Certificate (java.security.cert.X509Certificate)4 Properties (java.util.Properties)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Writer (java.io.Writer)3