Search in sources :

Example 6 with SignatureException

use of java.security.SignatureException in project android_frameworks_base by ResurrectionRemix.

the class ApkSignatureSchemeV2Verifier method verifySigner.

private static X509Certificate[] verifySigner(ByteBuffer signerBlock, Map<Integer, byte[]> contentDigests, CertificateFactory certFactory) throws SecurityException, IOException {
    ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
    ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
    byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
    int signatureCount = 0;
    int bestSigAlgorithm = -1;
    byte[] bestSigAlgorithmSignatureBytes = null;
    List<Integer> signaturesSigAlgorithms = new ArrayList<>();
    while (signatures.hasRemaining()) {
        signatureCount++;
        try {
            ByteBuffer signature = getLengthPrefixedSlice(signatures);
            if (signature.remaining() < 8) {
                throw new SecurityException("Signature record too short");
            }
            int sigAlgorithm = signature.getInt();
            signaturesSigAlgorithms.add(sigAlgorithm);
            if (!isSupportedSignatureAlgorithm(sigAlgorithm)) {
                continue;
            }
            if ((bestSigAlgorithm == -1) || (compareSignatureAlgorithm(sigAlgorithm, bestSigAlgorithm) > 0)) {
                bestSigAlgorithm = sigAlgorithm;
                bestSigAlgorithmSignatureBytes = readLengthPrefixedByteArray(signature);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new SecurityException("Failed to parse signature record #" + signatureCount, e);
        }
    }
    if (bestSigAlgorithm == -1) {
        if (signatureCount == 0) {
            throw new SecurityException("No signatures found");
        } else {
            throw new SecurityException("No supported signatures found");
        }
    }
    String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(bestSigAlgorithm);
    Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams = getSignatureAlgorithmJcaSignatureAlgorithm(bestSigAlgorithm);
    String jcaSignatureAlgorithm = signatureAlgorithmParams.first;
    AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second;
    boolean sigVerified;
    try {
        PublicKey publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
        sig.initVerify(publicKey);
        if (jcaSignatureAlgorithmParams != null) {
            sig.setParameter(jcaSignatureAlgorithmParams);
        }
        sig.update(signedData);
        sigVerified = sig.verify(bestSigAlgorithmSignatureBytes);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | InvalidAlgorithmParameterException | SignatureException e) {
        throw new SecurityException("Failed to verify " + jcaSignatureAlgorithm + " signature", e);
    }
    if (!sigVerified) {
        throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify");
    }
    // Signature over signedData has verified.
    byte[] contentDigest = null;
    signedData.clear();
    ByteBuffer digests = getLengthPrefixedSlice(signedData);
    List<Integer> digestsSigAlgorithms = new ArrayList<>();
    int digestCount = 0;
    while (digests.hasRemaining()) {
        digestCount++;
        try {
            ByteBuffer digest = getLengthPrefixedSlice(digests);
            if (digest.remaining() < 8) {
                throw new IOException("Record too short");
            }
            int sigAlgorithm = digest.getInt();
            digestsSigAlgorithms.add(sigAlgorithm);
            if (sigAlgorithm == bestSigAlgorithm) {
                contentDigest = readLengthPrefixedByteArray(digest);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new IOException("Failed to parse digest record #" + digestCount, e);
        }
    }
    if (!signaturesSigAlgorithms.equals(digestsSigAlgorithms)) {
        throw new SecurityException("Signature algorithms don't match between digests and signatures records");
    }
    int digestAlgorithm = getSignatureAlgorithmContentDigestAlgorithm(bestSigAlgorithm);
    byte[] previousSignerDigest = contentDigests.put(digestAlgorithm, contentDigest);
    if ((previousSignerDigest != null) && (!MessageDigest.isEqual(previousSignerDigest, contentDigest))) {
        throw new SecurityException(getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm) + " contents digest does not match the digest specified by a preceding signer");
    }
    ByteBuffer certificates = getLengthPrefixedSlice(signedData);
    List<X509Certificate> certs = new ArrayList<>();
    int certificateCount = 0;
    while (certificates.hasRemaining()) {
        certificateCount++;
        byte[] encodedCert = readLengthPrefixedByteArray(certificates);
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
        } catch (CertificateException e) {
            throw new SecurityException("Failed to decode certificate #" + certificateCount, e);
        }
        certificate = new VerbatimX509Certificate(certificate, encodedCert);
        certs.add(certificate);
    }
    if (certs.isEmpty()) {
        throw new SecurityException("No certificates listed");
    }
    X509Certificate mainCertificate = certs.get(0);
    byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
    if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
        throw new SecurityException("Public key mismatch between certificate and signature record");
    }
    return certs.toArray(new X509Certificate[certs.size()]);
}
Also used : ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) BufferUnderflowException(java.nio.BufferUnderflowException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) DirectByteBuffer(java.nio.DirectByteBuffer) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 7 with SignatureException

use of java.security.SignatureException in project OpenAM by OpenRock.

the class QuerySignatureUtil method isValidSignature.

private static boolean isValidSignature(Signature sig, Set<X509Certificate> certificates, byte[] queryString, byte[] signature) throws SAML2Exception {
    final String classMethod = "QuerySignatureUtil.isValidSignature: ";
    Exception firstException = null;
    for (X509Certificate certificate : certificates) {
        try {
            sig.initVerify(certificate);
            sig.update(queryString);
            if (sig.verify(signature)) {
                return true;
            }
        } catch (InvalidKeyException | SignatureException ex) {
            SAML2Utils.debug.warning(classMethod + "Signature validation failed due to " + ex);
            if (firstException == null) {
                firstException = ex;
            }
        }
    }
    if (firstException != null) {
        throw new SAML2Exception(firstException);
    }
    return false;
}
Also used : SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) SignatureException(java.security.SignatureException) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) X509Certificate(java.security.cert.X509Certificate)

Example 8 with SignatureException

use of java.security.SignatureException in project OpenAM by OpenRock.

the class OpenIdConnectToken method sign.

/**
     * Signs the OpenId Connect token.
     *
     * @return A SignedJwt
     * @throws SignatureException If an error occurs with the signing of the OpenId Connect token.
     */
public SignedJwt sign() throws SignatureException {
    final JwsAlgorithm jwsAlgorithm = JwsAlgorithm.valueOf(algorithm);
    if (jwsAlgorithm == null) {
        logger.error("Unable to find jws algorithm for: " + algorithm);
        throw new SignatureException();
    }
    final SigningHandler signingHandler;
    if (JwsAlgorithmType.RSA.equals(jwsAlgorithm.getAlgorithmType())) {
        signingHandler = new SigningManager().newRsaSigningHandler(keyPair.getPrivate());
    } else {
        signingHandler = new SigningManager().newHmacSigningHandler(clientSecret);
    }
    JwsHeaderBuilder builder = jwtBuilderFactory.jws(signingHandler).headers().alg(jwsAlgorithm);
    JwtClaimsSet claimsSet = jwtBuilderFactory.claims().claims(asMap()).build();
    if (kid != null) {
        builder.kid(kid);
    }
    return builder.done().claims(claimsSet).asJwt();
}
Also used : JwsAlgorithm(org.forgerock.json.jose.jws.JwsAlgorithm) JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) SignatureException(java.security.SignatureException) JwsHeaderBuilder(org.forgerock.json.jose.builders.JwsHeaderBuilder) SigningHandler(org.forgerock.json.jose.jws.handlers.SigningHandler) SigningManager(org.forgerock.json.jose.jws.SigningManager)

Example 9 with SignatureException

use of java.security.SignatureException in project android_frameworks_base by ResurrectionRemix.

the class RecoverySystem method verifyPackage.

/**
     * Verify the cryptographic signature of a system update package
     * before installing it.  Note that the package is also verified
     * separately by the installer once the device is rebooted into
     * the recovery system.  This function will return only if the
     * package was successfully verified; otherwise it will throw an
     * exception.
     *
     * Verification of a package can take significant time, so this
     * function should not be called from a UI thread.  Interrupting
     * the thread while this function is in progress will result in a
     * SecurityException being thrown (and the thread's interrupt flag
     * will be cleared).
     *
     * @param packageFile  the package to be verified
     * @param listener     an object to receive periodic progress
     * updates as verification proceeds.  May be null.
     * @param deviceCertsZipFile  the zip file of certificates whose
     * public keys we will accept.  Verification succeeds if the
     * package is signed by the private key corresponding to any
     * public key in this file.  May be null to use the system default
     * file (currently "/system/etc/security/otacerts.zip").
     *
     * @throws IOException if there were any errors reading the
     * package or certs files.
     * @throws GeneralSecurityException if verification failed
     */
public static void verifyPackage(File packageFile, ProgressListener listener, File deviceCertsZipFile) throws IOException, GeneralSecurityException {
    final long fileLen = packageFile.length();
    final RandomAccessFile raf = new RandomAccessFile(packageFile, "r");
    try {
        final long startTimeMillis = System.currentTimeMillis();
        if (listener != null) {
            listener.onProgress(0);
        }
        raf.seek(fileLen - 6);
        byte[] footer = new byte[6];
        raf.readFully(footer);
        if (footer[2] != (byte) 0xff || footer[3] != (byte) 0xff) {
            throw new SignatureException("no signature in file (no footer)");
        }
        final int commentSize = (footer[4] & 0xff) | ((footer[5] & 0xff) << 8);
        final int signatureStart = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8);
        byte[] eocd = new byte[commentSize + 22];
        raf.seek(fileLen - (commentSize + 22));
        raf.readFully(eocd);
        // end-of-central-directory record.
        if (eocd[0] != (byte) 0x50 || eocd[1] != (byte) 0x4b || eocd[2] != (byte) 0x05 || eocd[3] != (byte) 0x06) {
            throw new SignatureException("no signature in file (bad footer)");
        }
        for (int i = 4; i < eocd.length - 3; ++i) {
            if (eocd[i] == (byte) 0x50 && eocd[i + 1] == (byte) 0x4b && eocd[i + 2] == (byte) 0x05 && eocd[i + 3] == (byte) 0x06) {
                throw new SignatureException("EOCD marker found after start of EOCD");
            }
        }
        // Parse the signature
        PKCS7 block = new PKCS7(new ByteArrayInputStream(eocd, commentSize + 22 - signatureStart, signatureStart));
        // Take the first certificate from the signature (packages
        // should contain only one).
        X509Certificate[] certificates = block.getCertificates();
        if (certificates == null || certificates.length == 0) {
            throw new SignatureException("signature contains no certificates");
        }
        X509Certificate cert = certificates[0];
        PublicKey signatureKey = cert.getPublicKey();
        SignerInfo[] signerInfos = block.getSignerInfos();
        if (signerInfos == null || signerInfos.length == 0) {
            throw new SignatureException("signature contains no signedData");
        }
        SignerInfo signerInfo = signerInfos[0];
        // Check that the public key of the certificate contained
        // in the package equals one of our trusted public keys.
        boolean verified = false;
        HashSet<X509Certificate> trusted = getTrustedCerts(deviceCertsZipFile == null ? DEFAULT_KEYSTORE : deviceCertsZipFile);
        for (X509Certificate c : trusted) {
            if (c.getPublicKey().equals(signatureKey)) {
                verified = true;
                break;
            }
        }
        if (!verified) {
            throw new SignatureException("signature doesn't match any trusted key");
        }
        // The signature cert matches a trusted key.  Now verify that
        // the digest in the cert matches the actual file data.
        raf.seek(0);
        final ProgressListener listenerForInner = listener;
        SignerInfo verifyResult = block.verify(signerInfo, new InputStream() {

            // The signature covers all of the OTA package except the
            // archive comment and its 2-byte length.
            long toRead = fileLen - commentSize - 2;

            long soFar = 0;

            int lastPercent = 0;

            long lastPublishTime = startTimeMillis;

            @Override
            public int read() throws IOException {
                throw new UnsupportedOperationException();
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                if (soFar >= toRead) {
                    return -1;
                }
                if (Thread.currentThread().isInterrupted()) {
                    return -1;
                }
                int size = len;
                if (soFar + size > toRead) {
                    size = (int) (toRead - soFar);
                }
                int read = raf.read(b, off, size);
                soFar += read;
                if (listenerForInner != null) {
                    long now = System.currentTimeMillis();
                    int p = (int) (soFar * 100 / toRead);
                    if (p > lastPercent && now - lastPublishTime > PUBLISH_PROGRESS_INTERVAL_MS) {
                        lastPercent = p;
                        lastPublishTime = now;
                        listenerForInner.onProgress(lastPercent);
                    }
                }
                return read;
            }
        });
        final boolean interrupted = Thread.interrupted();
        if (listener != null) {
            listener.onProgress(100);
        }
        if (interrupted) {
            throw new SignatureException("verification was interrupted");
        }
        if (verifyResult == null) {
            throw new SignatureException("signature digest verification failed");
        }
    } finally {
        raf.close();
    }
}
Also used : PKCS7(sun.security.pkcs.PKCS7) PublicKey(java.security.PublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SignatureException(java.security.SignatureException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) SignerInfo(sun.security.pkcs.SignerInfo) RandomAccessFile(java.io.RandomAccessFile) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 10 with SignatureException

use of java.security.SignatureException in project OpenAM by OpenRock.

the class RestAuthenticationHandler method authenticate.

/**
     * Handles either the creation or retrieval of the Login Process, dependent on if the request is a new
     * authentication request or a continuation of one.
     *
     * @param request The HttpServletRequest.
     * @param response The HttpServletResponse.
     * @param postBody The post body of the request.
     * @param authIndexType The authentication index type.
     * @param indexValue The authentication index value.
     * @param sessionUpgradeSSOTokenId The SSO Token Id of the user's current session, null if not performing a session
     *                                 upgrade.
     * @return The Response of the authentication request.
     */
private JsonValue authenticate(HttpServletRequest request, HttpServletResponse response, JsonValue postBody, String authIndexType, String indexValue, String sessionUpgradeSSOTokenId) throws RestAuthException {
    LoginProcess loginProcess = null;
    try {
        AuthIndexType indexType = getAuthIndexType(authIndexType);
        String authId = null;
        String sessionId = null;
        if (postBody != null) {
            authId = getAuthId(postBody);
            if (authId != null) {
                SignedJwt jwt = authIdHelper.reconstructAuthId(authId);
                sessionId = getSessionId(jwt);
                indexType = getAuthIndexType(jwt);
                indexValue = getAuthIndexValue(jwt);
                String realmDN = getRealmDomainName(jwt);
                AuditRequestContext.putProperty(SESSION_ID, sessionId);
                authIdHelper.verifyAuthId(realmDN, authId);
            }
        }
        LoginConfiguration loginConfiguration = new LoginConfiguration().httpRequest(request).httpResponse(response).indexType(indexType).indexValue(indexValue).sessionId(sessionId).forceAuth(request.getParameter(AuthUtils.FORCE_AUTH)).sessionUpgrade(sessionUpgradeSSOTokenId);
        loginProcess = loginAuthenticator.getLoginProcess(loginConfiguration);
        return processAuthentication(request, response, postBody, authId, loginProcess, loginConfiguration);
    } catch (RestAuthException e) {
        if (loginProcess != null) {
            String failureUrl = urlValidator.getRedirectUrl(loginProcess.getAuthContext().getOrgDN(), loginProcess.getFailureURL(), null);
            e.setFailureUrl(failureUrl);
        }
        throw e;
    } catch (L10NMessageImpl e) {
        throw new RestAuthException(amAuthErrorCodeResponseStatusMapping.getAuthLoginExceptionResponseStatus(e.getErrorCode()), e);
    } catch (JsonException e) {
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, e);
    } catch (SignatureException e) {
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, e);
    } catch (AuthLoginException e) {
        throw new RestAuthException(amAuthErrorCodeResponseStatusMapping.getAuthLoginExceptionResponseStatus(e.getErrorCode()), e);
    } catch (JwsSigningException jse) {
        DEBUG.error("JwsSigningException", jse);
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, "JwsSigningException, " + jse.getMessage());
    }
}
Also used : RestAuthException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthException) JsonException(org.forgerock.json.JsonException) JwsSigningException(org.forgerock.json.jose.exceptions.JwsSigningException) L10NMessageImpl(com.sun.identity.shared.locale.L10NMessageImpl) AuthIndexType(org.forgerock.openam.core.rest.authn.core.AuthIndexType) LoginConfiguration(org.forgerock.openam.core.rest.authn.core.LoginConfiguration) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) SignatureException(java.security.SignatureException) LoginProcess(org.forgerock.openam.core.rest.authn.core.LoginProcess)

Aggregations

SignatureException (java.security.SignatureException)329 InvalidKeyException (java.security.InvalidKeyException)171 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)132 Signature (java.security.Signature)132 IOException (java.io.IOException)75 PublicKey (java.security.PublicKey)53 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)39 X509Certificate (java.security.cert.X509Certificate)33 BigInteger (java.math.BigInteger)32 CertificateException (java.security.cert.CertificateException)31 NoSuchProviderException (java.security.NoSuchProviderException)29 PrivateKey (java.security.PrivateKey)25 ByteArrayInputStream (java.io.ByteArrayInputStream)17 KeyFactory (java.security.KeyFactory)15 ArrayList (java.util.ArrayList)15 MySignature1 (org.apache.harmony.security.tests.support.MySignature1)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)12 GeneralSecurityException (java.security.GeneralSecurityException)12 MessageDigest (java.security.MessageDigest)12