Search in sources :

Example 6 with SecureDirectory

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

the class KeyStoreUtil method createKeysAndCRL.

/**
 *  New way - Native Java, does not call out to keytool.
 *  Create a keypair and store it in the keystore at ks, creating it if necessary.
 *
 *  This returns the public key, private key, certificate, and CRL in an array.
 *  All of these are Java classes. Keys may be converted to I2P classes with SigUtil.
 *  The private key and selfsigned cert are stored in the keystore.
 *  The public key may be derived from the private key with KeyGenerator.getSigningPublicKey().
 *  The public key certificate may be stored separately with
 *  CertUtil.saveCert() if desired.
 *  The CRL is not stored by this method, store it with
 *  CertUtil.saveCRL() or CertUtil.exportCRL() if desired.
 *
 *  Throws on all errors.
 *  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. localhost. Must be a hostname or email address. IP addresses will not be correctly encoded.
 *  @param altNames the Subject Alternative Names. May be null. May contain hostnames and/or IP addresses.
 *                  cname, localhost, 127.0.0.1, and ::1 will be automatically added.
 *  @param ou e.g. console
 *  @param validDays e.g. 3652 (10 years)
 *  @param keyPW the key password, must be at least 6 characters
 *  @return all you need:
 *      rv[0] is a Java PublicKey
 *      rv[1] is a Java PrivateKey
 *      rv[2] is a Java X509Certificate
 *      rv[3] is a Java X509CRL
 *  @since 0.9.34 added altNames param
 */
public static Object[] createKeysAndCRL(File ks, String ksPW, String alias, String cname, Set<String> altNames, String ou, int validDays, SigType type, String keyPW) throws GeneralSecurityException, IOException {
    File dir = ks.getParentFile();
    if (dir != null && !dir.exists()) {
        File sdir = new SecureDirectory(dir.getAbsolutePath());
        if (!sdir.mkdirs())
            throw new IOException("Can't create directory " + dir);
    }
    Object[] rv = SelfSignedGenerator.generate(cname, altNames, ou, "I2P", "I2P Anonymous Network", null, null, validDays, type);
    // PublicKey jpub = (PublicKey) rv[0];
    PrivateKey jpriv = (PrivateKey) rv[1];
    X509Certificate cert = (X509Certificate) rv[2];
    // X509CRL crl = (X509CRL) rv[3];
    List<X509Certificate> certs = Collections.singletonList(cert);
    storePrivateKey(ks, ksPW, alias, keyPW, jpriv, certs);
    return rv;
}
Also used : PrivateKey(java.security.PrivateKey) SecureDirectory(net.i2p.util.SecureDirectory) IOException(java.io.IOException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate)

Example 7 with SecureDirectory

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

the class Daemon method run.

public void run(String[] args) {
    _running = true;
    String settingsLocation = "config.txt";
    File homeFile;
    if (args.length > 0) {
        homeFile = new SecureDirectory(args[0]);
        if (!homeFile.isAbsolute())
            homeFile = new SecureDirectory(I2PAppContext.getGlobalContext().getRouterDir(), args[0]);
    } else {
        homeFile = new SecureDirectory(System.getProperty("user.dir"));
    }
    Map<String, String> defaultSettings = new HashMap<String, String>();
    defaultSettings.put("proxy_host", "127.0.0.1");
    defaultSettings.put("proxy_port", "4444");
    defaultSettings.put("master_addressbook", "../userhosts.txt");
    defaultSettings.put("router_addressbook", "../hosts.txt");
    defaultSettings.put("published_addressbook", "../eepsite/docroot/hosts.txt");
    defaultSettings.put("should_publish", "false");
    defaultSettings.put("log", "log.txt");
    defaultSettings.put("subscriptions", "subscriptions.txt");
    defaultSettings.put("etags", "etags");
    defaultSettings.put("last_modified", "last_modified");
    defaultSettings.put("last_fetched", "last_fetched");
    defaultSettings.put("update_delay", "12");
    defaultSettings.put("update_direct", "false");
    defaultSettings.put("naming_service", "hosts.txt");
    if (!homeFile.exists()) {
        boolean created = homeFile.mkdirs();
        if (created)
            System.out.println("INFO:  Addressbook directory " + homeFile.getName() + " created");
        else
            System.out.println("ERROR: Addressbook directory " + homeFile.getName() + " could not be created");
    }
    File settingsFile = new File(homeFile, settingsLocation);
    Map<String, String> settings = ConfigParser.parse(settingsFile, defaultSettings);
    // wait
    try {
        Thread.sleep(5 * 60 * 1000 + I2PAppContext.getGlobalContext().random().nextLong(5 * 60 * 1000));
    // Static method, and redundent Thread.currentThread().sleep(5*60*1000);
    } catch (InterruptedException ie) {
    }
    while (_running) {
        long delay = Long.parseLong(settings.get("update_delay"));
        if (delay < 1) {
            delay = 1;
        }
        update(settings, homeFile.getAbsolutePath());
        try {
            synchronized (this) {
                wait(delay * 60 * 60 * 1000);
            }
        } catch (InterruptedException exp) {
        }
        if (!_running)
            break;
        settings = ConfigParser.parse(settingsFile, defaultSettings);
    }
}
Also used : SecureDirectory(net.i2p.util.SecureDirectory) HashMap(java.util.HashMap) File(java.io.File)

Example 8 with SecureDirectory

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

the class FamilyKeyCrypto method exportCRL.

/**
 * Save the CRL just in case.
 * @param ksdir parent of directory to save in
 * @since 0.9.25
 */
private void exportCRL(File ksdir, X509CRL crl) {
    File sdir = new SecureDirectory(ksdir, CRL_DIR);
    if (sdir.exists() || sdir.mkdirs()) {
        String name = KEYSTORE_PREFIX + _fname.replace("@", "_at_") + '-' + System.currentTimeMillis() + CRL_SUFFIX;
        File out = new File(sdir, name);
        boolean success = CertUtil.saveCRL(crl, out);
        if (success) {
            _log.logAlways(Log.INFO, "Created certificate revocation list (CRL) for netdb family \"" + _fname + "\" in file: " + out.getAbsolutePath() + "\n" + "Back up the keystore and CRL files and keep them secure.\n" + "If your private key is ever compromised, give the CRL to an I2P developer for publication.");
        } else {
            _log.error("Error saving family key CRL");
        }
    } else {
        _log.error("Error saving family key CRL");
    }
}
Also used : SecureDirectory(net.i2p.util.SecureDirectory) File(java.io.File)

Example 9 with SecureDirectory

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

the class WorkingDir method getWorkingDir.

/**
 * Only call this once on router invocation.
 * Caller should store the return value for future reference.
 *
 * This also redirects stdout and stderr to a wrapper.log file if there is no wrapper present,
 * unless system property I2P_DISABLE_OUTPUT_OVERRIDE is set.
 *
 * @param migrateOldConfig whether to copy all data over from an existing install
 */
public static String getWorkingDir(Properties envProps, boolean migrateOldConfig) {
    String dir = null;
    if (envProps != null)
        dir = envProps.getProperty(PROP_WORKING_DIR);
    if (dir == null)
        dir = System.getProperty(PROP_WORKING_DIR);
    boolean isWindows = SystemVersion.isWindows();
    File dirf = null;
    String gentooWarning = null;
    if (dir != null) {
        dirf = new SecureDirectory(dir);
    } else {
        String home = System.getProperty("user.home");
        if (isWindows) {
            String appdata = System.getenv("APPDATA");
            if (appdata != null)
                home = appdata;
            dirf = new SecureDirectory(home, WORKING_DIR_DEFAULT_WINDOWS);
        } else if (SystemVersion.isMac()) {
            String appdata = "/Library/Application Support/";
            File old = new File(home, WORKING_DIR_DEFAULT);
            if (old.exists() && old.isDirectory())
                dirf = new SecureDirectory(home, WORKING_DIR_DEFAULT);
            else {
                home = home + appdata;
                dirf = new SecureDirectory(home, WORKING_DIR_DEFAULT_MAC);
            }
        } else {
            if (SystemVersion.isLinuxService()) {
                if (SystemVersion.isGentoo() && SystemVersion.GENTOO_USER.equals(System.getProperty("user.name"))) {
                    // whoops, we didn't recognize Gentoo as a service until 0.9.29,
                    // so the config dir was /var/lib/i2p/.i2p through 0.9.28
                    // and changed to /var/lib/i2p/i2p-config in 0.9.29.
                    // Look for both to decide which to use.
                    // We prefer .i2p if neither exists.
                    // We prefer the newer if both exist.
                    File d1 = new SecureDirectory(home, WORKING_DIR_DEFAULT);
                    File d2 = new SecureDirectory(home, WORKING_DIR_DEFAULT_DAEMON);
                    boolean e1 = isSetup(d1);
                    boolean e2 = isSetup(d2);
                    if (e1 && e2) {
                        // d1 is probably older. Switch if it isn't.
                        if (d2.lastModified() < d1.lastModified()) {
                            File tmp = d2;
                            d2 = d1;
                            d1 = tmp;
                        // d1 now is the older one
                        }
                        dirf = d2;
                        gentooWarning = "Warning - Found both an old configuration directory " + d1.getAbsolutePath() + " and new configuration directory " + d2.getAbsolutePath() + " created due to a bug in release 0.9.29\n. Using the new configuration" + " directory. To use the old directory instead, stop i2p," + " delete the new directory, and restart.";
                    } else if (e1 && !e2) {
                        dirf = d1;
                    } else if (!e1 && e2) {
                        dirf = d2;
                    } else {
                        dirf = d1;
                    }
                } else {
                    dirf = new SecureDirectory(home, WORKING_DIR_DEFAULT_DAEMON);
                }
            } else {
                dirf = new SecureDirectory(home, WORKING_DIR_DEFAULT);
            }
        }
    }
    // where we are now
    String cwd = null;
    if (envProps != null)
        cwd = envProps.getProperty(PROP_BASE_DIR);
    if (cwd == null) {
        cwd = System.getProperty(PROP_BASE_DIR);
        if (cwd == null)
            cwd = System.getProperty("user.dir");
    }
    // Check for a hosts.txt file, if it exists then I2P is there
    File oldDirf = new File(cwd);
    File test = new File(oldDirf, "hosts.txt");
    if (!test.exists()) {
        setupSystemOut(cwd);
        System.err.println("ERROR - Cannot find I2P installation in " + cwd + " - Will probably be just a router with no apps or console at all!");
        // we are probably doomed...
        return cwd;
    }
    // apparently configured for "portable" ?
    try {
        if (oldDirf.getCanonicalPath().equals(dirf.getCanonicalPath())) {
            setupSystemOut(cwd);
            return cwd;
        }
    } catch (IOException ioe) {
    }
    // where we want to go
    String rv = dirf.getAbsolutePath();
    if (dirf.exists()) {
        if (dirf.isDirectory()) {
            if (isSetup(dirf)) {
                setupSystemOut(rv);
                // see above for why
                if (gentooWarning != null)
                    System.err.println(gentooWarning);
                // all is good, we found the user directory
                return rv;
            }
        } else {
            setupSystemOut(null);
            System.err.println("Wanted to use " + rv + " for a working directory but it is not a directory");
            return cwd;
        }
    }
    // Check for a router.keys file or logs dir, if either exists it's an old install,
    // and only migrate the data files if told to do so
    // (router.keys could be deleted later by a killkeys())
    test = new File(oldDirf, CreateRouterInfoJob.KEYS_FILENAME);
    boolean oldInstall = test.exists();
    if (!oldInstall) {
        test = new File(oldDirf, "logs");
        oldInstall = test.exists();
    }
    // keep everything where it is, in one place...
    if (oldInstall && !migrateOldConfig) {
        setupSystemOut(cwd);
        return cwd;
    }
    // this is a terrible idea
    boolean migrateOldData = false;
    if (!dirf.exists() && !dirf.mkdir()) {
        setupSystemOut(null);
        System.err.println("Wanted to use " + rv + " for a working directory but could not create it");
        return cwd;
    }
    setupSystemOut(dirf.getAbsolutePath());
    // Do the copying
    if (migrateOldData)
        System.err.println("Migrating data files to new user directory " + rv);
    else
        System.err.println("Setting up new user directory " + rv);
    boolean success = migrate(MIGRATE_BASE, oldDirf, dirf);
    // this one must be after MIGRATE_BASE
    File oldEep = new File(oldDirf, "eepsite");
    File newEep = new File(dirf, "eepsite");
    String newPath = newEep.getAbsolutePath() + File.separatorChar;
    success &= migrateJettyXml(oldEep, newEep, "jetty.xml", "./eepsite/", newPath);
    success &= migrateJettyXml(oldEep, newEep, "jetty-ssl.xml", "./eepsite/", newPath);
    success &= migrateJettyXml(oldEep, newEep, "contexts/base-context.xml", "./eepsite/", newPath);
    success &= migrateJettyXml(oldEep, newEep, "contexts/cgi-context.xml", "./eepsite/", newPath);
    success &= migrateClientsConfig(oldDirf, dirf);
    // for later news.xml updates (we don't copy initialNews.xml over anymore)
    success &= (new SecureDirectory(dirf, "docs")).mkdir();
    // prevent correlation of eepsite timestamps with router first-seen time
    touchRecursive(new File(dirf, "eepsite/docroot"), EEPSITE_TIMESTAMP);
    // Report success or failure
    if (success) {
        System.err.println("Successfully copied data files to new user directory " + rv);
        return rv;
    } else {
        System.err.println("FAILED copy of some or all data files to new directory " + rv);
        System.err.println("Check logs for details");
        System.err.println("Continung to use data files in old directory " + cwd);
        return cwd;
    }
}
Also used : SecureDirectory(net.i2p.util.SecureDirectory) IOException(java.io.IOException) File(java.io.File)

Example 10 with SecureDirectory

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

the class WorkingDir method copy.

/**
 * Recursive copy a file or dir to a dir
 *
 * @param src file or directory, need not exist
 * @param targetDir the directory to copy to, will be created if it doesn't exist
 * @return true for success OR if src does not exist
 */
private static boolean copy(File src, File targetDir) {
    if (!src.exists())
        return true;
    if (!targetDir.exists()) {
        if (!targetDir.mkdir()) {
            System.err.println("FAILED copy " + src.getPath());
            return false;
        }
        System.err.println("Created " + targetDir.getPath());
    }
    // SecureDirectory is a File so this works for non-directories too
    File targetFile = new SecureDirectory(targetDir, src.getName());
    if (!src.isDirectory())
        return copyFile(src, targetFile);
    File[] children = src.listFiles();
    if (children == null) {
        System.err.println("FAILED copy " + src.getPath());
        return false;
    }
    // make it here so even empty dirs get copied
    if (!targetFile.exists()) {
        if (!targetFile.mkdir()) {
            System.err.println("FAILED copy " + src.getPath());
            return false;
        }
        System.err.println("Created " + targetFile.getPath());
    }
    boolean rv = true;
    for (int i = 0; i < children.length; i++) {
        rv &= copy(children[i], targetFile);
    }
    return rv;
}
Also used : SecureDirectory(net.i2p.util.SecureDirectory) File(java.io.File)

Aggregations

SecureDirectory (net.i2p.util.SecureDirectory)32 File (java.io.File)31 IOException (java.io.IOException)16 HashMap (java.util.HashMap)5 Properties (java.util.Properties)4 GeneralSecurityException (java.security.GeneralSecurityException)3 ArrayList (java.util.ArrayList)3 OrderedProperties (net.i2p.util.OrderedProperties)3 SecureFile (net.i2p.util.SecureFile)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 PrivateKey (java.security.PrivateKey)2 Map (java.util.Map)2 StringTokenizer (java.util.StringTokenizer)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 SU3File (net.i2p.crypto.SU3File)2 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)2 InputStream (java.io.InputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 Writer (java.io.Writer)1 InetSocketAddress (java.net.InetSocketAddress)1