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;
}
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);
}
}
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");
}
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"));
}
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) {
}
}
}
Aggregations