Search in sources :

Example 1 with SECertificateListener

use of com.biglybt.core.security.SECertificateListener in project BiglyBT by BiglySoftware.

the class SESecurityManagerImpl method installServerCertificates.

private SSLSocketFactory installServerCertificates(final URL https_url, boolean sni_hack, boolean dh_hack) {
    try {
        this_mon.enter();
        String host = https_url.getHost();
        int port = https_url.getPort();
        if (port == -1) {
            port = 443;
        }
        SSLSocket socket = null;
        try {
            // to get the server certs we have to use an "all trusting" trust manager
            TrustManagerFactory tmf = getTrustManagerFactory();
            final List<X509TrustManager> default_tms = new ArrayList<>();
            if (tmf != null) {
                for (TrustManager tm : tmf.getTrustManagers()) {
                    if (tm instanceof X509TrustManager) {
                        default_tms.add((X509TrustManager) tm);
                    }
                }
            }
            final List<Object> trustedChains = new ArrayList<>();
            TrustManager[] trustAllCerts = SESecurityManager.getAllTrustingTrustManager(new X509TrustManager() {

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return (null);
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    try {
                        for (X509TrustManager tm : default_tms) {
                            tm.checkServerTrusted(chain, authType);
                            trustedChains.add(chain);
                            break;
                        }
                    } catch (Throwable e) {
                    }
                }
            });
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, RandomUtils.SECURE_RANDOM);
            SSLSocketFactory factory = sc.getSocketFactory();
            InetSocketAddress targetSockAddress = new InetSocketAddress(InetAddress.getByName(host), port);
            InetAddress bindIP = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress(targetSockAddress.getAddress() instanceof Inet6Address ? NetworkAdmin.IP_PROTOCOL_VERSION_REQUIRE_V6 : NetworkAdmin.IP_PROTOCOL_VERSION_REQUIRE_V4);
            if (sni_hack) {
                Socket base_socket = new Socket();
                if (bindIP != null) {
                    base_socket.bind(new InetSocketAddress(bindIP, 0));
                }
                base_socket.connect(targetSockAddress);
                socket = (SSLSocket) factory.createSocket(base_socket, "", base_socket.getPort(), true);
                socket.setEnabledProtocols(new String[] { "TLSv1" });
                socket.setUseClientMode(true);
            } else {
                if (bindIP != null) {
                    socket = (SSLSocket) factory.createSocket(host, port, bindIP, 0);
                } else {
                    socket = (SSLSocket) factory.createSocket(host, port);
                }
            }
            if (dh_hack) {
                String[] cs = socket.getEnabledCipherSuites();
                List<String> new_cs = new ArrayList<>();
                for (String x : cs) {
                    if (x.contains("_DH_") || x.contains("_DHE_")) {
                    } else {
                        new_cs.add(x);
                    }
                }
                socket.setEnabledCipherSuites(new_cs.toArray(new String[new_cs.size()]));
            }
            socket.startHandshake();
            java.security.cert.Certificate[] serverCerts = socket.getSession().getPeerCertificates();
            java.security.cert.X509Certificate[] x509_certs = new java.security.cert.X509Certificate[serverCerts.length];
            for (int i = 0; i < serverCerts.length; i++) {
                java.security.cert.Certificate cert = serverCerts[i];
                java.security.cert.X509Certificate x509_cert;
                if (cert instanceof java.security.cert.X509Certificate) {
                    x509_cert = (java.security.cert.X509Certificate) cert;
                } else {
                    java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
                    x509_cert = (java.security.cert.X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));
                }
                x509_certs[i] = x509_cert;
            }
            boolean chain_trusted = false;
            if (trustedChains.size() > 0) {
                for (Object ochain : trustedChains) {
                    java.security.cert.X509Certificate[] chain = (java.security.cert.X509Certificate[]) ochain;
                    if (chain.length == x509_certs.length) {
                        boolean match = true;
                        for (int i = 0; i < chain.length; i++) {
                            if (!chain[i].equals(x509_certs[i])) {
                                match = false;
                                break;
                            }
                        }
                        if (match) {
                            chain_trusted = true;
                            break;
                        }
                    }
                }
            }
            SSLSocketFactory result = null;
            for (int i = 0; i < serverCerts.length; i++) {
                java.security.cert.Certificate cert = serverCerts[i];
                java.security.cert.X509Certificate x509_cert = x509_certs[i];
                String resource = https_url.toString();
                int param_pos = resource.indexOf("?");
                if (param_pos != -1) {
                    resource = resource.substring(0, param_pos);
                }
                // recalc - don't use port above as it may have been changed
                String url_s = https_url.getProtocol() + "://" + https_url.getHost() + ":" + https_url.getPort() + "/";
                Object[] handler = (Object[]) certificate_handlers.get(url_s);
                String alias = host.concat(":").concat(String.valueOf(port));
                if (i > 0) {
                    alias += "[" + i + "]";
                }
                KeyStore keystore = getTrustStore();
                byte[] new_encoded = x509_cert.getEncoded();
                int count = 0;
                boolean already_trusted = false;
                while (count < 256) {
                    String test_alias = count == 0 ? alias : (alias + "." + count);
                    Certificate existing = keystore.getCertificate(test_alias);
                    if (existing != null) {
                        if (Arrays.equals(new_encoded, existing.getEncoded())) {
                            alias = test_alias;
                            already_trusted = true;
                            break;
                        }
                    } else {
                        alias = test_alias;
                        break;
                    }
                    count++;
                }
                if (auto_install_certs || chain_trusted || already_trusted || result != null) {
                    result = addCertToTrustStore(alias, cert, true);
                } else {
                    if (handler != null) {
                        if (((SECertificateListener) handler[0]).trustCertificate(resource, x509_cert)) {
                            result = addCertToTrustStore(alias, cert, true);
                        }
                    }
                    for (SECertificateListener listener : certificate_listeners) {
                        if (listener.trustCertificate(resource, x509_cert)) {
                            result = addCertToTrustStore(alias, cert, true);
                        }
                    }
                }
            }
            return (result);
        } catch (Throwable e) {
            String msg = Debug.getNestedExceptionMessage(e);
            if (msg.contains("unrecognized_name")) {
                if (!sni_hack) {
                    return (installServerCertificates(https_url, true, dh_hack));
                }
            }
            if (msg.contains("DH keypair")) {
                if (!dh_hack) {
                    return (installServerCertificates(https_url, sni_hack, true));
                }
            }
            Debug.out(e);
            return (null);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Throwable e) {
                    Debug.printStackTrace(e);
                }
            }
        }
    } finally {
        this_mon.exit();
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) CertificateException(java.security.cert.CertificateException) SECertificateListener(com.biglybt.core.security.SECertificateListener) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 2 with SECertificateListener

use of com.biglybt.core.security.SECertificateListener in project BiglyBT by BiglySoftware.

the class NetworkAdminSpeedTesterBTImpl method start.

/**
 * The downloads have been stopped just need to do the testing.
 * @param tot - Torrent recieved from testing service.
 */
public synchronized void start(TOTorrent tot) {
    if (test_started) {
        Debug.out("Test already started!");
        return;
    }
    test_started = true;
    // OK lets start the test.
    try {
        TorrentUtils.setFlag(tot, TorrentUtils.TORRENT_FLAG_LOW_NOISE, true);
        Torrent torrent = new TorrentImpl(tot);
        String fileName = torrent.getName();
        sendStageUpdateToListeners(MessageText.getString("SpeedTestWizard.stage.message.preparing"));
        // create a blank file of specified size. (using the temporary name.)
        File saveLocation = AETemporaryFileHandler.createTempFile();
        File baseDir = saveLocation.getParentFile();
        File blankFile = new File(baseDir, fileName);
        File blankTorrentFile = new File(baseDir, "speedTestTorrent.torrent");
        torrent.writeToFile(blankTorrentFile);
        URL announce_url = torrent.getAnnounceURL();
        if (announce_url.getProtocol().equalsIgnoreCase("https")) {
            SESecurityManager.setCertificateHandler(announce_url, new SECertificateListener() {

                @Override
                public boolean trustCertificate(String resource, X509Certificate cert) {
                    return (true);
                }
            });
        }
        Download speed_download = plugin.getDownloadManager().addDownloadStopped(torrent, blankTorrentFile, blankFile);
        speed_download.setBooleanAttribute(speedTestAttrib, true);
        DownloadManager core_download = PluginCoreUtils.unwrap(speed_download);
        core_download.setPieceCheckingEnabled(false);
        // make sure we've got a bunch of upload slots
        core_download.getDownloadState().setIntParameter(DownloadManagerState.PARAM_MAX_UPLOADS, 32);
        core_download.getDownloadState().setIntParameter(DownloadManagerState.PARAM_MAX_UPLOADS_WHEN_SEEDING, 32);
        if (use_crypto) {
            core_download.setCryptoLevel(NetworkManager.CRYPTO_OVERRIDE_REQUIRED);
        }
        core_download.addPeerListener(new DownloadManagerPeerListener() {

            @Override
            public void peerManagerWillBeAdded(PEPeerManager peer_manager) {
                DiskManager disk_manager = peer_manager.getDiskManager();
                DiskManagerPiece[] pieces = disk_manager.getPieces();
                int startPiece = setStartPieceBasedOnMode(testMode, pieces.length);
                for (int i = startPiece; i < pieces.length; i++) {
                    pieces[i].setDone(true);
                }
            }

            @Override
            public void peerManagerAdded(PEPeerManager peer_manager) {
            }

            @Override
            public void peerManagerRemoved(PEPeerManager manager) {
            }

            @Override
            public void peerAdded(PEPeer peer) {
            }

            @Override
            public void peerRemoved(PEPeer peer) {
            }
        });
        speed_download.moveTo(1);
        speed_download.setFlag(Download.FLAG_DISABLE_AUTO_FILE_MOVE, true);
        core_download.initialize();
        core_download.setForceStart(true);
        TorrentSpeedTestMonitorThread monitor = new TorrentSpeedTestMonitorThread(speed_download);
        monitor.start();
    // The test has now started!!
    } catch (Throwable e) {
        test_completed = true;
        abort("Could not start test", e);
    }
}
Also used : TOTorrent(com.biglybt.core.torrent.TOTorrent) Torrent(com.biglybt.pif.torrent.Torrent) TorrentImpl(com.biglybt.pifimpl.local.torrent.TorrentImpl) PEPeer(com.biglybt.core.peer.PEPeer) DiskManager(com.biglybt.core.disk.DiskManager) DownloadManager(com.biglybt.core.download.DownloadManager) URL(java.net.URL) X509Certificate(java.security.cert.X509Certificate) DownloadManagerPeerListener(com.biglybt.core.download.DownloadManagerPeerListener) SECertificateListener(com.biglybt.core.security.SECertificateListener) PEPeerManager(com.biglybt.core.peer.PEPeerManager) File(java.io.File) Download(com.biglybt.pif.download.Download)

Example 3 with SECertificateListener

use of com.biglybt.core.security.SECertificateListener in project BiglyBT by BiglySoftware.

the class SESecurityManagerImpl method addCertificateListener.

@Override
public void addCertificateListener(final CertificateListener listener) {
    SECertificateListener sepl = new SECertificateListener() {

        @Override
        public boolean trustCertificate(String resource, X509Certificate cert) {
            return (listener.trustCertificate(resource, cert));
        }
    };
    certificate_listeners.put(listener, sepl);
    SESecurityManager.addCertificateListener(sepl);
}
Also used : SECertificateListener(com.biglybt.core.security.SECertificateListener) X509Certificate(java.security.cert.X509Certificate)

Aggregations

SECertificateListener (com.biglybt.core.security.SECertificateListener)3 X509Certificate (java.security.cert.X509Certificate)3 DiskManager (com.biglybt.core.disk.DiskManager)1 DownloadManager (com.biglybt.core.download.DownloadManager)1 DownloadManagerPeerListener (com.biglybt.core.download.DownloadManagerPeerListener)1 PEPeer (com.biglybt.core.peer.PEPeer)1 PEPeerManager (com.biglybt.core.peer.PEPeerManager)1 TOTorrent (com.biglybt.core.torrent.TOTorrent)1 Download (com.biglybt.pif.download.Download)1 Torrent (com.biglybt.pif.torrent.Torrent)1 TorrentImpl (com.biglybt.pifimpl.local.torrent.TorrentImpl)1 File (java.io.File)1 URL (java.net.URL)1 KeyStore (java.security.KeyStore)1 Certificate (java.security.cert.Certificate)1 CertificateException (java.security.cert.CertificateException)1