Search in sources :

Example 61 with GeneralSecurityException

use of java.security.GeneralSecurityException in project platform_frameworks_base by android.

the class AccountManagerService method finishSessionAsUser.

@Override
public void finishSessionAsUser(IAccountManagerResponse response, @NonNull Bundle sessionBundle, boolean expectActivityLaunch, Bundle appInfo, int userId) {
    Bundle.setDefusable(sessionBundle, true);
    int callingUid = Binder.getCallingUid();
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "finishSession: response " + response + ", expectActivityLaunch " + expectActivityLaunch + ", caller's uid " + callingUid + ", caller's user id " + UserHandle.getCallingUserId() + ", pid " + Binder.getCallingPid() + ", for user id " + userId);
    }
    if (response == null) {
        throw new IllegalArgumentException("response is null");
    }
    // Account type is added to it before encryption.
    if (sessionBundle == null || sessionBundle.size() == 0) {
        throw new IllegalArgumentException("sessionBundle is empty");
    }
    // Only allow the system process to finish session for other users
    if (isCrossUser(callingUid, userId)) {
        throw new SecurityException(String.format("User %s trying to finish session for %s without cross user permission", UserHandle.getCallingUserId(), userId));
    }
    // Only allow system to finish session
    if (!isSystemUid(callingUid)) {
        String msg = String.format("uid %s cannot finish session because it's not system uid.", callingUid);
        throw new SecurityException(msg);
    }
    if (!canUserModifyAccounts(userId, callingUid)) {
        sendErrorResponse(response, AccountManager.ERROR_CODE_USER_RESTRICTED, "User is not allowed to add an account!");
        showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
        return;
    }
    final int pid = Binder.getCallingPid();
    final Bundle decryptedBundle;
    final String accountType;
    // First decrypt session bundle to get account type for checking permission.
    try {
        CryptoHelper cryptoHelper = CryptoHelper.getInstance();
        decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
        if (decryptedBundle == null) {
            sendErrorResponse(response, AccountManager.ERROR_CODE_BAD_REQUEST, "failed to decrypt session bundle");
            return;
        }
        accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
        // properly by #StartAccountSession.
        if (TextUtils.isEmpty(accountType)) {
            sendErrorResponse(response, AccountManager.ERROR_CODE_BAD_ARGUMENTS, "accountType is empty");
            return;
        }
        // update credentials flow, we should replace with the new values of the current call.
        if (appInfo != null) {
            decryptedBundle.putAll(appInfo);
        }
        // Add info that may be used by add account or update credentials flow.
        decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
        decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
    } catch (GeneralSecurityException e) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.v(TAG, "Failed to decrypt session bundle!", e);
        }
        sendErrorResponse(response, AccountManager.ERROR_CODE_BAD_REQUEST, "failed to decrypt session bundle");
        return;
    }
    if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
        sendErrorResponse(response, AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE, "User cannot modify accounts of this type (policy).");
        showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE, userId);
        return;
    }
    long identityToken = clearCallingIdentity();
    try {
        UserAccounts accounts = getUserAccounts(userId);
        logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH, TABLE_ACCOUNTS, callingUid);
        new Session(accounts, response, accountType, expectActivityLaunch, true, /* stripAuthTokenFromResult */
        null, /* accountName */
        false, /* authDetailsRequired */
        true) {

            /* updateLastAuthenticationTime */
            @Override
            public void run() throws RemoteException {
                mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
            }

            @Override
            protected String toDebugString(long now) {
                return super.toDebugString(now) + ", finishSession" + ", accountType " + accountType;
            }
        }.bind();
    } finally {
        restoreCallingIdentity(identityToken);
    }
}
Also used : Bundle(android.os.Bundle) GeneralSecurityException(java.security.GeneralSecurityException) GeneralSecurityException(java.security.GeneralSecurityException) RemoteException(android.os.RemoteException)

Example 62 with GeneralSecurityException

use of java.security.GeneralSecurityException in project openhab1-addons by openhab.

the class OpenWebIfCommunicator method executeRequest.

/**
     * Executes the http request and parses the returned stream.
     */
@SuppressWarnings("unchecked")
private <T> T executeRequest(OpenWebIfConfig config, String url, Class<T> clazz) throws IOException {
    HttpURLConnection con = null;
    try {
        logger.trace("Request [{}]: {}", config.getName(), url);
        con = (HttpURLConnection) new URL(url).openConnection();
        con.setConnectTimeout(CONNECTION_TIMEOUT);
        con.setReadTimeout(10000);
        if (config.hasLogin()) {
            String userpass = config.getUser() + ":" + config.getPassword();
            String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
            con.setRequestProperty("Authorization", basicAuth);
        }
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sCon = (HttpsURLConnection) con;
            TrustManager[] trustManager = new TrustManager[] { new SimpleTrustManager() };
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(new KeyManager[0], trustManager, new SecureRandom());
            sCon.setSSLSocketFactory(context.getSocketFactory());
            sCon.setHostnameVerifier(new AllowAllHostnameVerifier());
        }
        StringWriter sw = new StringWriter();
        IOUtils.copy(con.getInputStream(), sw);
        con.disconnect();
        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String response = sw.toString();
            logger.trace("Response: [{}]: {}", config.getName(), response);
            Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
            return (T) um.unmarshal(new StringReader(response));
        } else {
            throw new IOException(con.getResponseMessage());
        }
    } catch (JAXBException ex) {
        throw new IOException(ex.getMessage(), ex);
    } catch (GeneralSecurityException ex) {
        throw new IOException(ex.getMessage(), ex);
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}
Also used : AllowAllHostnameVerifier(org.openhab.action.openwebif.internal.impl.ssl.AllowAllHostnameVerifier) JAXBException(javax.xml.bind.JAXBException) GeneralSecurityException(java.security.GeneralSecurityException) SimpleTrustManager(org.openhab.action.openwebif.internal.impl.ssl.SimpleTrustManager) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) SimpleTrustManager(org.openhab.action.openwebif.internal.impl.ssl.SimpleTrustManager) HttpURLConnection(java.net.HttpURLConnection) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) Unmarshaller(javax.xml.bind.Unmarshaller) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 63 with GeneralSecurityException

use of java.security.GeneralSecurityException in project openhab1-addons by openhab.

the class ZWaveSecureNonceTracker method createNewSecureRandom.

private static SecureRandom createNewSecureRandom() {
    SecureRandom secureRandom = null;
    // http://www.cigital.com/justice-league-blog/2009/08/14/proper-use-of-javas-securerandom/
    try {
        secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
    } catch (GeneralSecurityException e) {
        secureRandom = new SecureRandom();
    }
    // force an internal seeding
    secureRandom.nextBoolean();
    // Add some entropy of our own to the seed
    secureRandom.setSeed(Runtime.getRuntime().freeMemory());
    for (File root : File.listRoots()) {
        secureRandom.setSeed(root.getUsableSpace());
    }
    return secureRandom;
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) SecureRandom(java.security.SecureRandom) File(java.io.File)

Example 64 with GeneralSecurityException

use of java.security.GeneralSecurityException in project openhab1-addons by openhab.

the class ZWaveSecurityCommandClass method setupNetworkKey.

// package visible for junit
void setupNetworkKey(boolean useSchemeZero) {
    logger.info("NODE {}: setupNetworkKey useSchemeZero={}", this.getNode().getNodeId(), useSchemeZero);
    if (useSchemeZero) {
        logger.info("NODE {}: Using Scheme0 Network Key for Key Exchange since we are in inclusion mode.)", this.getNode().getNodeId());
        // Scheme0 network key is a key of all zeros
        networkKey = new SecretKeySpec(new byte[16], AES);
    } else {
        if (!checkRealNetworkKeyLoaded()) {
            // Nothing we can do
            return;
        }
        // Use the real key
        logger.trace("NODE {}: Using Real Network Key.", this.getNode().getNodeId());
        networkKey = realNetworkKey;
    }
    try {
        // Derived the message encryption key from the network key
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, networkKey);
        encryptKey = new SecretKeySpec(cipher.doFinal(DERIVE_ENCRYPT_KEY), AES);
        // Derived the message auth key from the network key
        cipher.init(Cipher.ENCRYPT_MODE, networkKey);
        authKey = new SecretKeySpec(cipher.doFinal(DERIVE_AUTH_KEY), AES);
    } catch (GeneralSecurityException e) {
        logger.error("NODE " + this.getNode().getNodeId() + ": Error building derived keys", e);
        keyException = e;
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher)

Example 65 with GeneralSecurityException

use of java.security.GeneralSecurityException in project j2objc by google.

the class JarUtils method verifySignature.

/**
     * This method handle all the work with  PKCS7, ASN1 encoding, signature verifying,
     * and certification path building.
     * See also PKCS #7: Cryptographic Message Syntax Standard:
     * http://www.ietf.org/rfc/rfc2315.txt
     * @param signature - the input stream of signature file to be verified
     * @param signatureBlock - the input stream of corresponding signature block file
     * @return array of certificates used to verify the signature file
     * @throws IOException - if some errors occurs during reading from the stream
     * @throws GeneralSecurityException - if signature verification process fails
     */
public static Certificate[] verifySignature(InputStream signature, InputStream signatureBlock) throws IOException, GeneralSecurityException {
    BerInputStream bis = new BerInputStream(signatureBlock);
    ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);
    SignedData signedData = info.getSignedData();
    if (signedData == null) {
        throw new IOException("No SignedData found");
    }
    Collection<org.apache.harmony.security.x509.Certificate> encCerts = signedData.getCertificates();
    if (encCerts.isEmpty()) {
        return null;
    }
    X509Certificate[] certs = new X509Certificate[encCerts.size()];
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    int i = 0;
    for (org.apache.harmony.security.x509.Certificate encCert : encCerts) {
        final byte[] encoded = encCert.getEncoded();
        final InputStream is = new ByteArrayInputStream(encoded);
        certs[i++] = new VerbatimX509Certificate((X509Certificate) cf.generateCertificate(is), encoded);
    }
    List<SignerInfo> sigInfos = signedData.getSignerInfos();
    SignerInfo sigInfo;
    if (!sigInfos.isEmpty()) {
        sigInfo = sigInfos.get(0);
    } else {
        return null;
    }
    // Issuer
    X500Principal issuer = sigInfo.getIssuer();
    // Certificate serial number
    BigInteger snum = sigInfo.getSerialNumber();
    // Locate the certificate
    int issuerSertIndex = 0;
    for (i = 0; i < certs.length; i++) {
        if (issuer.equals(certs[i].getIssuerDN()) && snum.equals(certs[i].getSerialNumber())) {
            issuerSertIndex = i;
            break;
        }
    }
    if (i == certs.length) {
        // No issuer certificate found
        return null;
    }
    if (certs[issuerSertIndex].hasUnsupportedCriticalExtension()) {
        throw new SecurityException("Can not recognize a critical extension");
    }
    // Get Signature instance
    final String daOid = sigInfo.getDigestAlgorithm();
    final String daName = sigInfo.getDigestAlgorithmName();
    final String deaOid = sigInfo.getDigestEncryptionAlgorithm();
    final String deaName = sigInfo.getDigestEncryptionAlgorithmName();
    String alg = null;
    Signature sig = null;
    if (daOid != null && deaOid != null) {
        alg = daOid + "with" + deaOid;
        try {
            sig = Signature.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
        }
        // Try to convert to names instead of OID.
        if (sig == null && daName != null && deaName != null) {
            alg = daName + "with" + deaName;
            try {
                sig = Signature.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
            }
        }
    }
    if (sig == null && deaOid != null) {
        alg = deaOid;
        try {
            sig = Signature.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
        }
        if (sig == null) {
            alg = deaName;
            try {
                sig = Signature.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
            }
        }
    }
    // We couldn't find a valid Signature type.
    if (sig == null) {
        return null;
    }
    sig.initVerify(certs[issuerSertIndex]);
    // If the authenticatedAttributes field of SignerInfo contains more than zero attributes,
    // compute the message digest on the ASN.1 DER encoding of the Attributes value.
    // Otherwise, compute the message digest on the data.
    List<AttributeTypeAndValue> atr = sigInfo.getAuthenticatedAttributes();
    byte[] sfBytes = new byte[signature.available()];
    signature.read(sfBytes);
    if (atr == null) {
        sig.update(sfBytes);
    } else {
        sig.update(sigInfo.getEncodedAuthenticatedAttributes());
        // If the authenticatedAttributes field contains the message-digest attribute,
        // verify that it equals the computed digest of the signature file
        byte[] existingDigest = null;
        for (AttributeTypeAndValue a : atr) {
            if (Arrays.equals(a.getType().getOid(), MESSAGE_DIGEST_OID)) {
                if (existingDigest != null) {
                    throw new SecurityException("Too many MessageDigest attributes");
                }
                Collection<?> entries = a.getValue().getValues(ASN1OctetString.getInstance());
                if (entries.size() != 1) {
                    throw new SecurityException("Too many values for MessageDigest attribute");
                }
                existingDigest = (byte[]) entries.iterator().next();
            }
        }
        // must have a message-digest attribute.
        if (existingDigest == null) {
            throw new SecurityException("Missing MessageDigest in Authenticated Attributes");
        }
        MessageDigest md = null;
        if (daOid != null) {
            md = MessageDigest.getInstance(daOid);
        }
        if (md == null && daName != null) {
            md = MessageDigest.getInstance(daName);
        }
        if (md == null) {
            return null;
        }
        byte[] computedDigest = md.digest(sfBytes);
        if (!Arrays.equals(existingDigest, computedDigest)) {
            throw new SecurityException("Incorrect MD");
        }
    }
    if (!sig.verify(sigInfo.getEncryptedDigest())) {
        throw new SecurityException("Incorrect signature");
    }
    return createChain(certs[issuerSertIndex], certs);
}
Also used : ASN1OctetString(org.apache.harmony.security.asn1.ASN1OctetString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateFactory(java.security.cert.CertificateFactory) ContentInfo(org.apache.harmony.security.pkcs7.ContentInfo) BerInputStream(org.apache.harmony.security.asn1.BerInputStream) MessageDigest(java.security.MessageDigest) SignedData(org.apache.harmony.security.pkcs7.SignedData) BerInputStream(org.apache.harmony.security.asn1.BerInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) AttributeTypeAndValue(org.apache.harmony.security.x501.AttributeTypeAndValue) SignerInfo(org.apache.harmony.security.pkcs7.SignerInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

GeneralSecurityException (java.security.GeneralSecurityException)1171 IOException (java.io.IOException)435 Cipher (javax.crypto.Cipher)144 Test (org.junit.Test)136 X509Certificate (java.security.cert.X509Certificate)124 KeyStore (java.security.KeyStore)89 SSLContext (javax.net.ssl.SSLContext)84 SecretKeySpec (javax.crypto.spec.SecretKeySpec)80 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)72 ArrayList (java.util.ArrayList)72 File (java.io.File)61 InputStream (java.io.InputStream)57 Certificate (java.security.cert.Certificate)57 PublicKey (java.security.PublicKey)53 PrivateKey (java.security.PrivateKey)50 FileInputStream (java.io.FileInputStream)49 BigInteger (java.math.BigInteger)49 SecretKey (javax.crypto.SecretKey)48 IvParameterSpec (javax.crypto.spec.IvParameterSpec)43 SecureRandom (java.security.SecureRandom)42