use of net.i2p.util.SecureDirectory in project i2p.i2p by i2p.
the class KeyStoreUtil method createKeysCLI.
/**
* OLD way - keytool
* Create a keypair and store it in the keystore at ks, creating it if necessary.
*
* Warning, may take a long time.
*
* @param ks path to the keystore
* @param ksPW the keystore password
* @param alias the name of the key
* @param cname e.g. randomstuff.console.i2p.net
* @param ou e.g. console
* @param validDays e.g. 3652 (10 years)
* @param keyAlg e.g. DSA , RSA, EC
* @param keySize e.g. 1024
* @param keyPW the key password, must be at least 6 characters
*
* @return success
* @since 0.8.3, consolidated from RouterConsoleRunner and SSLClientListenerRunner in 0.9.9
*/
private static boolean createKeysCLI(File ks, String ksPW, String alias, String cname, String ou, int validDays, String keyAlg, int keySize, String keyPW) {
if (ks.exists()) {
try {
if (getCert(ks, ksPW, alias) != null) {
error("Not overwriting key " + alias + ", already exists in " + ks, null);
return false;
}
} catch (IOException e) {
error("Not overwriting key \"" + alias + "\", already exists in " + ks, e);
return false;
} catch (GeneralSecurityException e) {
error("Not overwriting key \"" + alias + "\", already exists in " + ks, e);
return false;
}
} else {
File dir = ks.getParentFile();
if (dir != null && !dir.exists()) {
File sdir = new SecureDirectory(dir.getAbsolutePath());
if (!sdir.mkdir()) {
error("Can't create directory " + dir, null);
return false;
}
}
}
String keytool = (new File(System.getProperty("java.home"), "bin/keytool")).getAbsolutePath();
List<String> a = new ArrayList<String>(32);
a.add(keytool);
// -genkeypair preferred in newer keytools, but this works with more
a.add("-genkey");
// a.add("-v"); // verbose, gives you a stack trace on exception
a.add("-storetype");
a.add(KeyStore.getDefaultType());
a.add("-keystore");
a.add(ks.getAbsolutePath());
a.add("-storepass");
a.add(ksPW);
a.add("-alias");
a.add(alias);
a.add("-dname");
a.add("CN=" + cname + ",OU=" + ou + ",O=I2P Anonymous Network,L=XX,ST=XX,C=XX");
// 10 years
a.add("-validity");
// 10 years
a.add(Integer.toString(validDays));
a.add("-keyalg");
a.add(keyAlg);
a.add("-sigalg");
a.add(getSigAlg(keySize, keyAlg));
a.add("-keysize");
a.add(Integer.toString(keySize));
a.add("-keypass");
a.add(keyPW);
if (keyAlg.equals("Ed") || keyAlg.equals("EdDSA") || keyAlg.equals("ElGamal")) {
File f = I2PAppContext.getGlobalContext().getBaseDir();
f = new File(f, "lib");
f = new File(f, "i2p.jar");
// providerpath is not in the man page; see keytool -genkey -help
a.add("-providerpath");
a.add(f.getAbsolutePath());
a.add("-providerclass");
a.add("net.i2p.crypto.provider.I2PProvider");
}
String[] args = a.toArray(new String[a.size()]);
// TODO pipe key password to process; requires ShellCommand enhancements
boolean success = (new ShellCommand()).executeSilentAndWaitTimed(args, 240);
if (success) {
success = ks.exists();
if (success) {
try {
success = getPrivateKey(ks, ksPW, alias, keyPW) != null;
if (!success)
error("Key gen failed to get private key", null);
} catch (IOException e) {
error("Key gen failed to get private key", e);
success = false;
} catch (GeneralSecurityException e) {
error("Key gen failed to get private key", e);
success = false;
}
}
if (!success)
error("Key gen failed for unknown reasons", null);
}
if (success) {
SecureFileOutputStream.setPerms(ks);
info("Created self-signed certificate for " + cname + " in keystore: " + ks.getAbsolutePath());
} else {
StringBuilder buf = new StringBuilder(256);
for (int i = 0; i < args.length; i++) {
buf.append('"').append(args[i]).append("\" ");
}
error("Failed to generate keys using command line: " + buf, null);
}
return success;
}
use of net.i2p.util.SecureDirectory in project i2p.i2p by i2p.
the class PersistentMailCache method makeCacheDirs.
/**
* ~/.i2p/susimail/cache/cache-xxxxx/cur/s[b64char]/mail-xxxxx.full.txt.gz
* folder1 is the base.
*/
private File makeCacheDirs(String host, int port, String user, String pass, String folder) throws IOException {
File f = new SecureDirectory(_context.getConfigDir(), DIR_SUSI);
if (!f.exists() && !f.mkdir())
throw new IOException("Cannot create " + f);
f = new SecureDirectory(f, DIR_CACHE);
if (!f.exists() && !f.mkdir())
throw new IOException("Cannot create " + f);
f = new SecureDirectory(f, CACHE_PREFIX + Base64.encode(user + host + port));
if (!f.exists() && !f.mkdir())
throw new IOException("Cannot create " + f);
File base = new SecureDirectory(f, folder);
if (!base.exists() && !base.mkdir())
throw new IOException("Cannot create " + base);
for (int i = 0; i < B64.length(); i++) {
f = new SecureDirectory(base, DIR_PREFIX + B64.charAt(i));
if (!f.exists() && !f.mkdir())
throw new IOException("Cannot create " + f);
}
return base;
}
use of net.i2p.util.SecureDirectory in project i2p.i2p by i2p.
the class SnarkManager method configFile.
/**
* The config file for a torrent
* @param confDir the config directory
* @param ih 20-byte infohash
* @since 0.9.15
*/
private static File configFile(File confDir, byte[] ih) {
String hex = I2PSnarkUtil.toHex(ih);
File subdir = new SecureDirectory(confDir, SUBDIR_PREFIX + B64.charAt((ih[0] >> 2) & 0x3f));
return new File(subdir, hex + CONFIG_FILE_SUFFIX);
}
use of net.i2p.util.SecureDirectory in project i2p.i2p by i2p.
the class SnarkManager method locked_updateConfig.
private void locked_updateConfig(String dataDir, boolean filesPublic, boolean autoStart, boolean smartSort, String refreshDelay, String startDelay, String pageSize, String seedPct, String eepHost, String eepPort, String i2cpHost, String i2cpPort, String i2cpOpts, String upLimit, String upBW, boolean useOpenTrackers, boolean useDHT, String theme, String lang, boolean enableRatings, boolean enableComments, String commentName, boolean collapsePanels) {
boolean changed = false;
boolean interruptMonitor = false;
// }
if (upLimit != null) {
int limit = _util.getMaxUploaders();
try {
limit = Integer.parseInt(upLimit.trim());
} catch (NumberFormatException nfe) {
}
if (limit != _util.getMaxUploaders()) {
if (limit >= Snark.MIN_TOTAL_UPLOADERS) {
_util.setMaxUploaders(limit);
changed = true;
_config.setProperty(PROP_UPLOADERS_TOTAL, Integer.toString(limit));
addMessage(_t("Total uploaders limit changed to {0}", limit));
} else {
addMessage(_t("Minimum total uploaders limit is {0}", Snark.MIN_TOTAL_UPLOADERS));
}
}
}
if (upBW != null) {
int limit = _util.getMaxUpBW();
try {
limit = Integer.parseInt(upBW.trim());
} catch (NumberFormatException nfe) {
}
if (limit != _util.getMaxUpBW()) {
if (limit >= MIN_UP_BW) {
_util.setMaxUpBW(limit);
changed = true;
_config.setProperty(PROP_UPBW_MAX, Integer.toString(limit));
addMessage(_t("Up BW limit changed to {0}KBps", limit));
} else {
addMessage(_t("Minimum up bandwidth limit is {0}KBps", MIN_UP_BW));
}
}
}
if (startDelay != null && _context.isRouterContext()) {
int minutes = _util.getStartupDelay();
try {
minutes = Integer.parseInt(startDelay.trim());
} catch (NumberFormatException nfe) {
}
if (minutes != _util.getStartupDelay()) {
_util.setStartupDelay(minutes);
changed = true;
_config.setProperty(PROP_STARTUP_DELAY, Integer.toString(minutes));
addMessageNoEscape(_t("Startup delay changed to {0}", DataHelper.formatDuration2(minutes * (60L * 1000))));
}
}
if (refreshDelay != null) {
try {
int secs = Integer.parseInt(refreshDelay.trim());
if (secs != getRefreshDelaySeconds()) {
changed = true;
_config.setProperty(PROP_REFRESH_DELAY, Integer.toString(secs));
if (secs >= 0)
addMessageNoEscape(_t("Refresh time changed to {0}", DataHelper.formatDuration2(secs * 1000)));
else
addMessage(_t("Refresh disabled"));
}
} catch (NumberFormatException nfe) {
}
}
if (pageSize != null) {
try {
int size = Integer.parseInt(pageSize.trim());
if (size <= 0)
size = 999999;
else if (size < 5)
size = 5;
if (size != getPageSize()) {
changed = true;
pageSize = Integer.toString(size);
_config.setProperty(PROP_PAGE_SIZE, pageSize);
addMessage(_t("Page size changed to {0}", pageSize));
}
} catch (NumberFormatException nfe) {
}
}
// set this before we check the data dir
if (areFilesPublic() != filesPublic) {
_config.setProperty(PROP_FILES_PUBLIC, Boolean.toString(filesPublic));
_util.setFilesPublic(filesPublic);
if (filesPublic)
addMessage(_t("New files will be publicly readable"));
else
addMessage(_t("New files will not be publicly readable"));
changed = true;
}
if (dataDir != null && !dataDir.equals(getDataDir().getAbsolutePath())) {
dataDir = DataHelper.stripHTML(dataDir.trim());
File dd = areFilesPublic() ? new File(dataDir) : new SecureDirectory(dataDir);
if (!dd.isAbsolute()) {
addMessage(_t("Data directory must be an absolute path") + ": " + dataDir);
} else if (!dd.exists() && !dd.mkdirs()) {
// save this tag for now, may need it again
if (false)
addMessage(_t("Data directory does not exist") + ": " + dataDir);
addMessage(_t("Data directory cannot be created") + ": " + dataDir);
} else if (!dd.isDirectory()) {
addMessage(_t("Not a directory") + ": " + dataDir);
} else if (!dd.canRead()) {
addMessage(_t("Unreadable") + ": " + dataDir);
} else {
if (!dd.canWrite())
addMessage(_t("No write permissions for data directory") + ": " + dataDir);
changed = true;
interruptMonitor = true;
_config.setProperty(PROP_DIR, dataDir);
addMessage(_t("Data directory changed to {0}", dataDir));
}
}
if (lang != null && !_context.isRouterContext() && lang.length() >= 2 && lang.length() <= 6) {
int under = lang.indexOf('_');
String nlang, ncountry;
if (under > 0 && lang.length() > under + 1) {
nlang = lang.substring(0, under);
ncountry = lang.substring(under + 1);
} else {
nlang = lang;
ncountry = "";
}
String olang = _config.getProperty(PROP_LANG);
String ocountry = _config.getProperty(PROP_COUNTRY);
if (!nlang.equals(olang) || !ncountry.equals(ocountry)) {
changed = true;
_config.setProperty(PROP_LANG, nlang);
_config.setProperty(PROP_COUNTRY, ncountry);
Translate.setLanguage(nlang, ncountry);
}
}
// Start of I2CP stuff.
// i2cpHost will generally be null since it is hidden from the form if in router context.
int oldI2CPPort = _util.getI2CPPort();
String oldI2CPHost = _util.getI2CPHost();
int port = oldI2CPPort;
if (i2cpPort != null) {
try {
port = Integer.parseInt(i2cpPort);
} catch (NumberFormatException nfe) {
}
}
Map<String, String> opts = new HashMap<String, String>();
i2cpOpts = DataHelper.stripHTML(i2cpOpts);
StringTokenizer tok = new StringTokenizer(i2cpOpts, " \t\n");
while (tok.hasMoreTokens()) {
String pair = tok.nextToken();
int split = pair.indexOf('=');
if (split > 0)
opts.put(pair.substring(0, split), pair.substring(split + 1));
}
Map<String, String> oldOpts = new HashMap<String, String>();
String oldI2CPOpts = _config.getProperty(PROP_I2CP_OPTS);
if (oldI2CPOpts == null)
oldI2CPOpts = "";
tok = new StringTokenizer(oldI2CPOpts, " \t\n");
while (tok.hasMoreTokens()) {
String pair = tok.nextToken();
int split = pair.indexOf('=');
if (split > 0)
oldOpts.put(pair.substring(0, split), pair.substring(split + 1));
}
boolean reconnect = i2cpHost != null && i2cpHost.trim().length() > 0 && port > 0 && (port != _util.getI2CPPort() || !oldI2CPHost.equals(i2cpHost));
if (reconnect || !oldOpts.equals(opts)) {
boolean snarksActive = false;
if (reconnect) {
for (Snark snark : _snarks.values()) {
if (!snark.isStopped()) {
snarksActive = true;
break;
}
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("i2cp host [" + i2cpHost + "] i2cp port " + port + " opts [" + opts + "] oldOpts [" + oldOpts + "]");
if (snarksActive) {
Properties p = new Properties();
p.putAll(opts);
_util.setI2CPConfig(i2cpHost, port, p);
_util.setMaxUpBW(getInt(PROP_UPBW_MAX, DEFAULT_MAX_UP_BW));
addMessage(_t("I2CP and tunnel changes will take effect after stopping all torrents"));
} else if (!reconnect) {
// The usual case, the other two are if not in router context
_config.setProperty(PROP_I2CP_OPTS, i2cpOpts.trim());
addMessage(_t("I2CP options changed to {0}", i2cpOpts));
_util.setI2CPConfig(oldI2CPHost, oldI2CPPort, opts);
} else {
// Won't happen, I2CP host/port, are hidden in the GUI if in router context
if (_util.connected()) {
_util.disconnect();
addMessage(_t("Disconnecting old I2CP destination"));
}
addMessage(_t("I2CP settings changed to {0}", i2cpHost + ':' + port + ' ' + i2cpOpts));
_util.setI2CPConfig(i2cpHost, port, opts);
_util.setMaxUpBW(getInt(PROP_UPBW_MAX, DEFAULT_MAX_UP_BW));
boolean ok = _util.connect();
if (!ok) {
addMessage(_t("Unable to connect with the new settings, reverting to the old I2CP settings"));
_util.setI2CPConfig(oldI2CPHost, oldI2CPPort, oldOpts);
ok = _util.connect();
if (!ok)
addMessage(_t("Unable to reconnect with the old settings!"));
} else {
addMessage(_t("Reconnected on the new I2CP destination"));
_config.setProperty(PROP_I2CP_HOST, i2cpHost.trim());
_config.setProperty(PROP_I2CP_PORT, "" + port);
_config.setProperty(PROP_I2CP_OPTS, i2cpOpts.trim());
// no PeerAcceptors/I2PServerSockets to deal with, since all snarks are inactive
for (Snark snark : _snarks.values()) {
if (snark.restartAcceptor()) {
addMessage(_t("I2CP listener restarted for \"{0}\"", snark.getBaseName()));
// this is the common ConnectionAcceptor, so we only need to do it once
break;
}
}
}
}
changed = true;
}
if (shouldAutoStart() != autoStart) {
_config.setProperty(PROP_AUTO_START, Boolean.toString(autoStart));
if (autoStart)
addMessage(_t("Enabled autostart"));
else
addMessage(_t("Disabled autostart"));
changed = true;
}
if (isSmartSortEnabled() != smartSort) {
_config.setProperty(PROP_SMART_SORT, Boolean.toString(smartSort));
if (smartSort)
addMessage(_t("Enabled smart sort"));
else
addMessage(_t("Disabled smart sort"));
changed = true;
}
if (_util.shouldUseOpenTrackers() != useOpenTrackers) {
_config.setProperty(PROP_USE_OPENTRACKERS, useOpenTrackers + "");
if (useOpenTrackers)
addMessage(_t("Enabled open trackers - torrent restart required to take effect."));
else
addMessage(_t("Disabled open trackers - torrent restart required to take effect."));
_util.setUseOpenTrackers(useOpenTrackers);
changed = true;
}
if (_util.shouldUseDHT() != useDHT) {
_config.setProperty(PROP_USE_DHT, Boolean.toString(useDHT));
if (useDHT)
addMessage(_t("Enabled DHT."));
else
addMessage(_t("Disabled DHT."));
if (_util.connected())
addMessage(_t("DHT change requires tunnel shutdown and reopen"));
_util.setUseDHT(useDHT);
changed = true;
}
if (_util.ratingsEnabled() != enableRatings) {
_config.setProperty(PROP_RATINGS, Boolean.toString(enableRatings));
if (enableRatings)
addMessage(_t("Enabled Ratings."));
else
addMessage(_t("Disabled Ratings."));
_util.setRatingsEnabled(enableRatings);
changed = true;
}
if (_util.commentsEnabled() != enableComments) {
_config.setProperty(PROP_COMMENTS, Boolean.toString(enableComments));
if (enableComments)
addMessage(_t("Enabled Comments."));
else
addMessage(_t("Disabled Comments."));
_util.setCommentsEnabled(enableComments);
changed = true;
}
if (commentName == null) {
commentName = "";
} else {
commentName = commentName.trim().replaceAll("[\n\r<>#;]", "");
if (commentName.length() > Comment.MAX_NAME_LEN)
commentName = commentName.substring(0, Comment.MAX_NAME_LEN);
}
if (!_util.getCommentsName().equals(commentName)) {
_config.setProperty(PROP_COMMENTS_NAME, commentName);
addMessage(_t("Comments name set to {0}.", '"' + commentName + '"'));
_util.setCommentsName(commentName);
changed = true;
}
if (theme != null) {
if (!theme.equals(_config.getProperty(PROP_THEME))) {
_config.setProperty(PROP_THEME, theme);
addMessage(_t("{0} theme loaded.", theme));
changed = true;
}
}
if (_util.collapsePanels() != collapsePanels) {
_config.setProperty(PROP_COLLAPSE_PANELS, Boolean.toString(collapsePanels));
if (collapsePanels)
addMessage(_t("Collapsible panels enabled."));
else
addMessage(_t("Collapsible panels disabled."));
_util.setCollapsePanels(collapsePanels);
changed = true;
}
if (changed) {
saveConfig();
if (interruptMonitor)
// Data dir changed. this will stop and remove all old torrents, and add the new ones
_monitor.interrupt();
} else {
addMessage(_t("Configuration unchanged."));
}
}
use of net.i2p.util.SecureDirectory in project i2p.i2p by i2p.
the class SnarkManager method getDataDir.
public File getDataDir() {
String dir = _config.getProperty(PROP_DIR, _contextName);
File f;
if (areFilesPublic())
f = new File(dir);
else
f = new SecureDirectory(dir);
if (!f.isAbsolute()) {
if (areFilesPublic())
f = new File(_context.getAppDir(), dir);
else
f = new SecureDirectory(_context.getAppDir(), dir);
}
return f;
}
Aggregations