Search in sources :

Example 6 with RouterIdentity

use of net.i2p.data.router.RouterIdentity in project i2p.i2p by i2p.

the class NTCPTransport method bid.

public TransportBid bid(RouterInfo toAddress, long dataSize) {
    if (!isAlive())
        return null;
    if (dataSize > NTCPConnection.MAX_MSG_SIZE) {
        // let SSU deal with it
        _context.statManager().addRateData("ntcp.noBidTooLargeI2NP", dataSize);
        return null;
    }
    Hash peer = toAddress.getIdentity().calculateHash();
    if (_context.banlist().isBanlisted(peer, STYLE)) {
        // we aren't banlisted in general (since we are trying to get a bid), but we have
        // recently banlisted the peer on the NTCP transport, so don't try it
        _context.statManager().addRateData("ntcp.attemptBanlistedPeer", 1);
        return null;
    } else if (isUnreachable(peer)) {
        _context.statManager().addRateData("ntcp.attemptUnreachablePeer", 1);
        return null;
    }
    boolean established = isEstablished(toAddress.getIdentity());
    if (established) {
        // _log.debug("fast bid when trying to send to " + peer + " as its already established");
        return _fastBid;
    }
    RouterAddress addr = getTargetAddress(toAddress);
    if (addr == null) {
        markUnreachable(peer);
        return null;
    }
    // Check for supported sig type
    SigType type = toAddress.getIdentity().getSigType();
    if (type == null || !type.isAvailable()) {
        markUnreachable(peer);
        return null;
    }
    // Can we connect to them if we are not DSA?
    RouterInfo us = _context.router().getRouterInfo();
    if (us != null) {
        RouterIdentity id = us.getIdentity();
        if (id.getSigType() != SigType.DSA_SHA1) {
            String v = toAddress.getVersion();
            if (VersionComparator.comp(v, MIN_SIGTYPE_VERSION) < 0) {
                markUnreachable(peer);
                return null;
            }
        }
    }
    if (!allowConnection()) {
        // _log.warn("no bid when trying to send to " + peer + ", max connection limit reached");
        return _transientFail;
    }
    // _log.debug("slow bid when trying to send to " + peer);
    if (haveCapacity()) {
        if (addr.getCost() > DEFAULT_COST)
            return _slowCostBid;
        else
            return _slowBid;
    } else {
        if (addr.getCost() > DEFAULT_COST)
            return _nearCapacityCostBid;
        else
            return _nearCapacityBid;
    }
}
Also used : RouterInfo(net.i2p.data.router.RouterInfo) RouterIdentity(net.i2p.data.router.RouterIdentity) RouterAddress(net.i2p.data.router.RouterAddress) Hash(net.i2p.data.Hash) SigType(net.i2p.crypto.SigType)

Example 7 with RouterIdentity

use of net.i2p.data.router.RouterIdentity in project i2p.i2p by i2p.

the class NTCPTransport method removeCon.

/**
 * @return usually the con passed in, but possibly a second connection with the same peer...
 */
NTCPConnection removeCon(NTCPConnection con) {
    NTCPConnection removed = null;
    RouterIdentity ident = con.getRemotePeer();
    if (ident != null) {
        synchronized (_conLock) {
            removed = _conByIdent.remove(ident.calculateHash());
        }
    }
    return removed;
}
Also used : RouterIdentity(net.i2p.data.router.RouterIdentity)

Example 8 with RouterIdentity

use of net.i2p.data.router.RouterIdentity in project i2p.i2p by i2p.

the class CreateRouterInfoJob method createRouterInfo.

/**
 *  Writes 6 files: router.info (standard RI format),
 *  router.keys.dat, and 4 individual key files under keyBackup/
 *
 *  router.keys.dat file format: This is the
 *  same "eepPriv.dat" format used by the client code,
 *  as documented in PrivateKeyFile.
 *
 *  Old router.keys file format: Note that this is NOT the
 *  same "eepPriv.dat" format used by the client code.
 *<pre>
 *   - Private key (256 bytes)
 *   - Signing Private key (20 bytes)
 *   - Public key (256 bytes)
 *   - Signing Public key (128 bytes)
 *  Total 660 bytes
 *</pre>
 *
 *  Caller must hold Router.routerInfoFileLock.
 */
RouterInfo createRouterInfo() {
    SigType type = getSigTypeConfig(getContext());
    RouterInfo info = new RouterInfo();
    OutputStream fos1 = null;
    try {
        info.setAddresses(getContext().commSystem().createAddresses());
        // not necessary, in constructor
        // info.setPeers(new HashSet());
        info.setPublished(getCurrentPublishDate(getContext()));
        Object[] keypair = getContext().keyGenerator().generatePKIKeypair();
        PublicKey pubkey = (PublicKey) keypair[0];
        PrivateKey privkey = (PrivateKey) keypair[1];
        SimpleDataStructure[] signingKeypair = getContext().keyGenerator().generateSigningKeys(type);
        SigningPublicKey signingPubKey = (SigningPublicKey) signingKeypair[0];
        SigningPrivateKey signingPrivKey = (SigningPrivateKey) signingKeypair[1];
        RouterIdentity ident = new RouterIdentity();
        Certificate cert = createCertificate(getContext(), signingPubKey);
        ident.setCertificate(cert);
        ident.setPublicKey(pubkey);
        ident.setSigningPublicKey(signingPubKey);
        byte[] padding;
        int padLen = SigningPublicKey.KEYSIZE_BYTES - signingPubKey.length();
        if (padLen > 0) {
            padding = new byte[padLen];
            getContext().random().nextBytes(padding);
            ident.setPadding(padding);
        } else {
            padding = null;
        }
        info.setIdentity(ident);
        Properties stats = getContext().statPublisher().publishStatistics(ident.getHash());
        info.setOptions(stats);
        info.sign(signingPrivKey);
        if (!info.isValid())
            throw new DataFormatException("RouterInfo we just built is invalid: " + info);
        // remove router.keys
        (new File(getContext().getRouterDir(), KEYS_FILENAME)).delete();
        // write router.info
        File ifile = new File(getContext().getRouterDir(), INFO_FILENAME);
        fos1 = new BufferedOutputStream(new SecureFileOutputStream(ifile));
        info.writeBytes(fos1);
        // write router.keys.dat
        File kfile = new File(getContext().getRouterDir(), KEYS2_FILENAME);
        PrivateKeyFile pkf = new PrivateKeyFile(kfile, pubkey, signingPubKey, cert, privkey, signingPrivKey, padding);
        pkf.write();
        // set or overwrite old random keys
        Map<String, String> map = new HashMap<String, String>(2);
        byte[] rk = new byte[32];
        getContext().random().nextBytes(rk);
        map.put(Router.PROP_IB_RANDOM_KEY, Base64.encode(rk));
        getContext().random().nextBytes(rk);
        map.put(Router.PROP_OB_RANDOM_KEY, Base64.encode(rk));
        getContext().router().saveConfig(map, null);
        getContext().keyManager().setKeys(pubkey, privkey, signingPubKey, signingPrivKey);
        if (_log.shouldLog(Log.INFO))
            _log.info("Router info created and stored at " + ifile.getAbsolutePath() + " with private keys stored at " + kfile.getAbsolutePath() + " [" + info + "]");
        getContext().router().eventLog().addEvent(EventLog.REKEYED, ident.calculateHash().toBase64());
    } catch (GeneralSecurityException gse) {
        _log.log(Log.CRIT, "Error building the new router information", gse);
    } catch (DataFormatException dfe) {
        _log.log(Log.CRIT, "Error building the new router information", dfe);
    } catch (IOException ioe) {
        _log.log(Log.CRIT, "Error writing out the new router information", ioe);
    } finally {
        if (fos1 != null)
            try {
                fos1.close();
            } catch (IOException ioe) {
            }
    }
    return info;
}
Also used : PrivateKey(net.i2p.data.PrivateKey) SigningPrivateKey(net.i2p.data.SigningPrivateKey) HashMap(java.util.HashMap) RouterInfo(net.i2p.data.router.RouterInfo) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) Properties(java.util.Properties) SimpleDataStructure(net.i2p.data.SimpleDataStructure) BufferedOutputStream(java.io.BufferedOutputStream) SigningPublicKey(net.i2p.data.SigningPublicKey) SigningPublicKey(net.i2p.data.SigningPublicKey) PublicKey(net.i2p.data.PublicKey) RouterIdentity(net.i2p.data.router.RouterIdentity) GeneralSecurityException(java.security.GeneralSecurityException) PrivateKeyFile(net.i2p.data.PrivateKeyFile) IOException(java.io.IOException) SigType(net.i2p.crypto.SigType) SigningPrivateKey(net.i2p.data.SigningPrivateKey) DataFormatException(net.i2p.data.DataFormatException) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File) Certificate(net.i2p.data.Certificate) KeyCertificate(net.i2p.data.KeyCertificate)

Example 9 with RouterIdentity

use of net.i2p.data.router.RouterIdentity in project i2p.i2p by i2p.

the class UDPTransport method bid.

public TransportBid bid(RouterInfo toAddress, long dataSize) {
    if (dataSize > OutboundMessageState.MAX_MSG_SIZE) {
        // NTCP max is lower, so msg will get dropped
        return null;
    }
    Hash to = toAddress.getIdentity().calculateHash();
    PeerState peer = getPeerState(to);
    if (peer != null) {
        if (_log.shouldLog(Log.DEBUG))
            _log.debug("bidding on a message to an established peer: " + peer);
        if (preferUDP())
            return _cachedBid[FAST_PREFERRED_BID];
        else
            return _cachedBid[FAST_BID];
    } else {
        // If we don't have a port, all is lost
        if (_reachabilityStatus == Status.HOSED) {
            markUnreachable(to);
            return null;
        }
        // Validate his SSU address
        RouterAddress addr = getTargetAddress(toAddress);
        if (addr == null) {
            markUnreachable(to);
            return null;
        }
        // Check for supported sig type
        SigType type = toAddress.getIdentity().getSigType();
        if (type == null || !type.isAvailable()) {
            markUnreachable(to);
            return null;
        }
        // Can we connect to them if we are not DSA?
        RouterInfo us = _context.router().getRouterInfo();
        if (us != null) {
            RouterIdentity id = us.getIdentity();
            if (id.getSigType() != SigType.DSA_SHA1) {
                String v = toAddress.getVersion();
                if (VersionComparator.comp(v, MIN_SIGTYPE_VERSION) < 0) {
                    markUnreachable(to);
                    return null;
                }
            }
        }
        if (!allowConnection())
            return _cachedBid[TRANSIENT_FAIL_BID];
        if (_log.shouldLog(Log.DEBUG))
            _log.debug("bidding on a message to an unestablished peer: " + to);
        // Try to maintain at least 5 peers (30 for v6) so we can determine our IP address and
        // we have a selection to run peer tests with.
        // If we are firewalled, and we don't have enough peers that volunteered to
        // also introduce us, also bid aggressively so we are preferred over NTCP.
        // (Otherwise we only talk UDP to those that are firewalled, and we will
        // never get any introducers)
        int count = _peersByIdent.size();
        if (alwaysPreferUDP()) {
            return _cachedBid[SLOW_PREFERRED_BID];
        } else if (count < _min_peers || (_haveIPv6Address && count < _min_v6_peers) || (introducersRequired() && _introManager.introducerCount() < MIN_INTRODUCER_POOL)) {
            // TODO After some time, decide that UDP is blocked/broken and return TRANSIENT_FAIL_BID?
            if (_context.random().nextInt(4) == 0)
                return _cachedBid[SLOWEST_BID];
            else
                return _cachedBid[SLOW_PREFERRED_BID];
        } else if (preferUDP()) {
            return _cachedBid[SLOW_BID];
        } else if (haveCapacity()) {
            if (addr.getCost() > DEFAULT_COST)
                return _cachedBid[SLOWEST_COST_BID];
            else
                return _cachedBid[SLOWEST_BID];
        } else {
            if (addr.getCost() > DEFAULT_COST)
                return _cachedBid[NEAR_CAPACITY_COST_BID];
            else
                return _cachedBid[NEAR_CAPACITY_BID];
        }
    }
}
Also used : RouterInfo(net.i2p.data.router.RouterInfo) RouterIdentity(net.i2p.data.router.RouterIdentity) RouterAddress(net.i2p.data.router.RouterAddress) Hash(net.i2p.data.Hash) SigType(net.i2p.crypto.SigType)

Example 10 with RouterIdentity

use of net.i2p.data.router.RouterIdentity in project i2p.i2p by i2p.

the class KademliaNetworkDatabaseFacade method processStoreFailure.

/**
 *  If the validate fails, call this
 *  to determine if it was because of unsupported crypto.
 *
 *  If so, this will banlist-forever the router hash or permanently negative cache the dest hash,
 *  and then throw the exception. Otherwise it does nothing.
 *
 *  @throws UnsupportedCryptoException if that's why it failed.
 *  @since 0.9.16
 */
private void processStoreFailure(Hash h, DatabaseEntry entry) throws UnsupportedCryptoException {
    if (entry.getHash().equals(h)) {
        if (entry.getType() == DatabaseEntry.KEY_TYPE_LEASESET) {
            LeaseSet ls = (LeaseSet) entry;
            Destination d = ls.getDestination();
            Certificate c = d.getCertificate();
            if (c.getCertificateType() == Certificate.CERTIFICATE_TYPE_KEY) {
                try {
                    KeyCertificate kc = c.toKeyCertificate();
                    SigType type = kc.getSigType();
                    if (type == null || !type.isAvailable() || type.getBaseAlgorithm() == SigAlgo.RSA) {
                        failPermanently(d);
                        String stype = (type != null) ? type.toString() : Integer.toString(kc.getSigTypeCode());
                        if (_log.shouldLog(Log.WARN))
                            _log.warn("Unsupported sig type " + stype + " for destination " + h);
                        throw new UnsupportedCryptoException("Sig type " + stype);
                    }
                } catch (DataFormatException dfe) {
                }
            }
        } else if (entry.getType() == DatabaseEntry.KEY_TYPE_ROUTERINFO) {
            RouterInfo ri = (RouterInfo) entry;
            RouterIdentity id = ri.getIdentity();
            Certificate c = id.getCertificate();
            if (c.getCertificateType() == Certificate.CERTIFICATE_TYPE_KEY) {
                try {
                    KeyCertificate kc = c.toKeyCertificate();
                    SigType type = kc.getSigType();
                    if (type == null || !type.isAvailable()) {
                        String stype = (type != null) ? type.toString() : Integer.toString(kc.getSigTypeCode());
                        _context.banlist().banlistRouterForever(h, "Unsupported signature type " + stype);
                        if (_log.shouldLog(Log.WARN))
                            _log.warn("Unsupported sig type " + stype + " for router " + h);
                        throw new UnsupportedCryptoException("Sig type " + stype);
                    }
                } catch (DataFormatException dfe) {
                }
            }
        }
    }
    if (_log.shouldLog(Log.WARN))
        _log.warn("Verify fail, cause unknown: " + entry);
}
Also used : LeaseSet(net.i2p.data.LeaseSet) Destination(net.i2p.data.Destination) KeyCertificate(net.i2p.data.KeyCertificate) DataFormatException(net.i2p.data.DataFormatException) RouterInfo(net.i2p.data.router.RouterInfo) RouterIdentity(net.i2p.data.router.RouterIdentity) SigType(net.i2p.crypto.SigType) Certificate(net.i2p.data.Certificate) KeyCertificate(net.i2p.data.KeyCertificate)

Aggregations

RouterIdentity (net.i2p.data.router.RouterIdentity)17 RouterInfo (net.i2p.data.router.RouterInfo)10 IOException (java.io.IOException)6 DataFormatException (net.i2p.data.DataFormatException)5 Hash (net.i2p.data.Hash)5 RouterAddress (net.i2p.data.router.RouterAddress)5 SigType (net.i2p.crypto.SigType)4 OutNetMessage (net.i2p.router.OutNetMessage)4 Certificate (net.i2p.data.Certificate)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InetAddress (java.net.InetAddress)2 ArrayList (java.util.ArrayList)2 KeyCertificate (net.i2p.data.KeyCertificate)2 PrivateKey (net.i2p.data.PrivateKey)2 PublicKey (net.i2p.data.PublicKey)2 SigningPrivateKey (net.i2p.data.SigningPrivateKey)2 SigningPublicKey (net.i2p.data.SigningPublicKey)2 DatabaseStoreMessage (net.i2p.data.i2np.DatabaseStoreMessage)2 BufferedInputStream (java.io.BufferedInputStream)1 BufferedOutputStream (java.io.BufferedOutputStream)1