Search in sources :

Example 26 with Certificate

use of java.security.cert.Certificate in project tinker by Tencent.

the class ShareSecurityCheck method verifyPatchMetaSignature.

public boolean verifyPatchMetaSignature(File path) {
    if (!SharePatchFileUtil.isLegalFile(path)) {
        return false;
    }
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(path);
        final Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            // no code
            if (jarEntry == null) {
                continue;
            }
            final String name = jarEntry.getName();
            if (name.startsWith("META-INF/")) {
                continue;
            }
            //we will check other files's mad5 written in meta files
            if (!name.endsWith(ShareConstants.META_SUFFIX)) {
                continue;
            }
            metaContentMap.put(name, SharePatchFileUtil.loadDigestes(jarFile, jarEntry));
            Certificate[] certs = jarEntry.getCertificates();
            if (certs == null) {
                return false;
            }
            if (!check(path, certs)) {
                return false;
            }
        }
    } catch (Exception e) {
        throw new TinkerRuntimeException(String.format("ShareSecurityCheck file %s, size %d verifyPatchMetaSignature fail", path.getAbsolutePath(), path.length()), e);
    } finally {
        try {
            if (jarFile != null) {
                jarFile.close();
            }
        } catch (IOException e) {
            Log.e(TAG, path.getAbsolutePath(), e);
        }
    }
    return true;
}
Also used : TinkerRuntimeException(com.tencent.tinker.loader.TinkerRuntimeException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) IOException(java.io.IOException) TinkerRuntimeException(com.tencent.tinker.loader.TinkerRuntimeException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 27 with Certificate

use of java.security.cert.Certificate in project Fairphone by Kwamecorp.

the class RSAUtils method readPublicKeyFormCertificate.

public static PublicKey readPublicKeyFormCertificate(Context context, int certificateResourceId) throws IOException, CertificateException {
    InputStream in = context.getResources().openRawResource(certificateResourceId);
    byte[] buff = new byte[4000];
    int bytesRead;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while ((bytesRead = in.read(buff)) != -1) {
        out.write(buff, 0, bytesRead);
        Log.i(TAG, "bytes read: " + bytesRead);
    }
    byte[] publicKeyBytes = out.toByteArray();
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    Certificate cert = cf.generateCertificate(new ByteArrayInputStream(publicKeyBytes));
    PublicKey pubKey = cert.getPublicKey();
    Log.i(TAG, "Public Key Info: ");
    Log.i(TAG, "Algorithm = " + pubKey.getAlgorithm());
    Log.i(TAG, "toString = " + pubKey.toString());
    return pubKey;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PublicKey(java.security.PublicKey) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CertificateFactory(java.security.cert.CertificateFactory) Certificate(java.security.cert.Certificate)

Example 28 with Certificate

use of java.security.cert.Certificate in project Fairphone by Kwamecorp.

the class RSAUtils method readPublicKeyFormCertificate.

public static PublicKey readPublicKeyFormCertificate(Context context, int certificateResourceId) throws IOException, CertificateException {
    InputStream in = context.getResources().openRawResource(certificateResourceId);
    byte[] buff = new byte[4000];
    int bytesRead;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while ((bytesRead = in.read(buff)) != -1) {
        out.write(buff, 0, bytesRead);
        Log.i(TAG, "bytes read: " + bytesRead);
    }
    byte[] publicKeyBytes = out.toByteArray();
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    Certificate cert = cf.generateCertificate(new ByteArrayInputStream(publicKeyBytes));
    PublicKey pubKey = cert.getPublicKey();
    Log.i(TAG, "Public Key Info: ");
    Log.i(TAG, "Algorithm = " + pubKey.getAlgorithm());
    Log.i(TAG, "toString = " + pubKey.toString());
    return pubKey;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PublicKey(java.security.PublicKey) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CertificateFactory(java.security.cert.CertificateFactory) Certificate(java.security.cert.Certificate)

Example 29 with Certificate

use of java.security.cert.Certificate in project MinecraftForge by MinecraftForge.

the class FMLModContainer method constructMod.

@Subscribe
public void constructMod(FMLConstructionEvent event) {
    try {
        BlamingTransformer.addClasses(getModId(), candidate.getClassList());
        ModClassLoader modClassLoader = event.getModClassLoader();
        modClassLoader.addFile(source);
        modClassLoader.clearNegativeCacheFor(candidate.getClassList());
        //Only place I could think to add this...
        MinecraftForge.preloadCrashClasses(event.getASMHarvestedData(), getModId(), candidate.getClassList());
        Class<?> clazz = Class.forName(className, true, modClassLoader);
        Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
        int len = 0;
        if (certificates != null) {
            len = certificates.length;
        }
        Builder<String> certBuilder = ImmutableList.builder();
        for (int i = 0; i < len; i++) {
            certBuilder.add(CertificateHelper.getFingerprint(certificates[i]));
        }
        ImmutableList<String> certList = certBuilder.build();
        sourceFingerprints = ImmutableSet.copyOf(certList);
        String expectedFingerprint = (String) descriptor.get("certificateFingerprint");
        fingerprintNotPresent = true;
        if (expectedFingerprint != null && !expectedFingerprint.isEmpty()) {
            if (!sourceFingerprints.contains(expectedFingerprint)) {
                Level warnLevel = Level.ERROR;
                if (source.isDirectory()) {
                    warnLevel = Level.TRACE;
                }
                FMLLog.log(getModId(), warnLevel, "The mod %s is expecting signature %s for source %s, however there is no signature matching that description", getModId(), expectedFingerprint, source.getName());
            } else {
                certificate = certificates[certList.indexOf(expectedFingerprint)];
                fingerprintNotPresent = false;
            }
        }
        @SuppressWarnings("unchecked") List<Map<String, Object>> props = (List<Map<String, Object>>) descriptor.get("customProperties");
        if (props != null) {
            com.google.common.collect.ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
            for (Map<String, Object> p : props) {
                builder.put((String) p.get("k"), (String) p.get("v"));
            }
            customModProperties = builder.build();
        } else {
            customModProperties = EMPTY_PROPERTIES;
        }
        Boolean hasDisableableFlag = (Boolean) descriptor.get("canBeDeactivated");
        boolean hasReverseDepends = !event.getReverseDependencies().get(getModId()).isEmpty();
        if (hasDisableableFlag != null && hasDisableableFlag) {
            disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.YES;
        } else {
            disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.RESTART;
        }
        Method factoryMethod = gatherAnnotations(clazz);
        modInstance = getLanguageAdapter().getNewInstance(this, clazz, modClassLoader, factoryMethod);
        NetworkRegistry.INSTANCE.register(this, clazz, (String) (descriptor.containsKey("acceptableRemoteVersions") ? descriptor.get("acceptableRemoteVersions") : null), event.getASMHarvestedData());
        if (fingerprintNotPresent) {
            eventBus.post(new FMLFingerprintViolationEvent(source.isDirectory(), source, ImmutableSet.copyOf(this.sourceFingerprints), expectedFingerprint));
        }
        ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(), getLanguageAdapter());
        AutomaticEventSubscriber.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide());
        ConfigManager.load(this.getModId(), Config.Type.INSTANCE);
        processFieldAnnotations(event.getASMHarvestedData());
    } catch (Throwable e) {
        controller.errorOccurred(this, e);
    }
}
Also used : FMLFingerprintViolationEvent(net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent) Method(java.lang.reflect.Method) ImmutableMap(com.google.common.collect.ImmutableMap) Level(org.apache.logging.log4j.Level) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Certificate(java.security.cert.Certificate) Subscribe(com.google.common.eventbus.Subscribe)

Example 30 with Certificate

use of java.security.cert.Certificate in project MinecraftForge by MinecraftForge.

the class FMLSanityChecker method call.

@Override
public Void call() throws Exception {
    CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
    boolean goodFML = false;
    boolean fmlIsJar = false;
    if (codeSource.getLocation().getProtocol().equals("jar")) {
        fmlIsJar = true;
        Certificate[] certificates = codeSource.getCertificates();
        if (certificates != null) {
            for (Certificate cert : certificates) {
                String fingerprint = CertificateHelper.getFingerprint(cert);
                if (fingerprint.equals(FMLFINGERPRINT)) {
                    FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s", fingerprint);
                    goodFML = true;
                } else if (fingerprint.equals(FORGEFINGERPRINT)) {
                    FMLRelaunchLog.info("Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s", fingerprint);
                    goodFML = true;
                } else {
                    FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint);
                }
            }
        }
    } else {
        goodFML = true;
    }
    // Server is not signed, so assume it's good - a deobf env is dev time so it's good too
    boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv;
    int certCount = 0;
    try {
        Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, cl);
        codeSource = cbr.getProtectionDomain().getCodeSource();
    } catch (Exception e) {
        // Probably a development environment, or the server (the server is not signed)
        goodMC = true;
    }
    JarFile mcJarFile = null;
    if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar")) {
        try {
            String mcPath = codeSource.getLocation().getPath().substring(5);
            mcPath = mcPath.substring(0, mcPath.lastIndexOf('!'));
            mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name());
            mcJarFile = new JarFile(mcPath, true);
            mcJarFile.getManifest();
            JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class");
            InputStream mcJarFileInputStream = mcJarFile.getInputStream(cbrEntry);
            try {
                ByteStreams.toByteArray(mcJarFileInputStream);
            } finally {
                IOUtils.closeQuietly(mcJarFileInputStream);
            }
            Certificate[] certificates = cbrEntry.getCertificates();
            certCount = certificates != null ? certificates.length : 0;
            if (certificates != null) {
                for (Certificate cert : certificates) {
                    String fingerprint = CertificateHelper.getFingerprint(cert);
                    if (fingerprint.equals(MCFINGERPRINT)) {
                        FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s", fingerprint);
                        goodMC = true;
                    }
                }
            }
        } catch (Throwable e) {
            FMLRelaunchLog.log(Level.ERROR, e, "A critical error occurred trying to read the minecraft jar file");
        } finally {
            Java6Utils.closeZipQuietly(mcJarFile);
        }
    } else {
        goodMC = true;
    }
    if (!goodMC) {
        FMLRelaunchLog.severe("The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!", codeSource.getLocation().getFile());
        if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates", "false"))) {
            FMLRelaunchLog.severe("For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file");
            FMLRelaunchLog.severe("Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, " + "and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so " + "run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY " + "want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile.");
            FMLCommonHandler.instance().exitJava(1, false);
        } else {
            FMLRelaunchLog.severe("FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!");
            FMLRelaunchLog.severe("Technical information: ClientBrandRetriever was at %s, there were %d certificates for it", codeSource.getLocation(), certCount);
        }
    }
    if (!goodFML) {
        FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing");
    }
    return null;
}
Also used : InputStream(java.io.InputStream) CodeSource(java.security.CodeSource) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Certificate(java.security.cert.Certificate)

Aggregations

Certificate (java.security.cert.Certificate)723 X509Certificate (java.security.cert.X509Certificate)469 CertificateFactory (java.security.cert.CertificateFactory)272 ByteArrayInputStream (java.io.ByteArrayInputStream)237 KeyStore (java.security.KeyStore)133 PrivateKey (java.security.PrivateKey)132 IOException (java.io.IOException)106 CertificateException (java.security.cert.CertificateException)102 KeyFactory (java.security.KeyFactory)89 KeyStoreException (java.security.KeyStoreException)88 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)72 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)69 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)63 ArrayList (java.util.ArrayList)63 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)56 Entry (java.security.KeyStore.Entry)53 PublicKey (java.security.PublicKey)48 InputStream (java.io.InputStream)40 FileInputStream (java.io.FileInputStream)39 Key (java.security.Key)36