Search in sources :

Example 31 with GeneralSecurityException

use of java.security.GeneralSecurityException in project android_frameworks_base by DirtyUnicorns.

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 32 with GeneralSecurityException

use of java.security.GeneralSecurityException in project android_frameworks_base by AOSPA.

the class OSUClient method remediate.

public void remediate(OSUManager osuManager, Network network, KeyManager km, HomeSP homeSP, int flowType) throws IOException, GeneralSecurityException {
    try (HTTPHandler httpHandler = createHandler(network, homeSP, km, flowType)) {
        URL redirectURL = osuManager.prepareUserInput(homeSP.getFriendlyName());
        OMADMAdapter omadmAdapter = osuManager.getOMADMAdapter();
        String regRequest = SOAPBuilder.buildPostDevDataResponse(RequestReason.SubRemediation, null, redirectURL.toString(), omadmAdapter.getMO(OMAConstants.DevInfoURN), omadmAdapter.getMO(OMAConstants.DevDetailURN));
        OSUResponse serverResponse = httpHandler.exchangeSOAP(mURL, regRequest);
        if (serverResponse.getMessageType() != OSUMessageType.PostDevData) {
            throw new IOException("Expected a PostDevDataResponse");
        }
        String sessionID = serverResponse.getSessionID();
        PostDevDataResponse pddResponse = (PostDevDataResponse) serverResponse;
        Log.d(TAG, "Remediation response: " + pddResponse);
        Map<OSUCertType, List<X509Certificate>> certs = null;
        PrivateKey clientKey = null;
        if (pddResponse.getStatus() != OSUStatus.RemediationComplete) {
            if (pddResponse.getExecCommand() == ExecCommand.UploadMO) {
                String ulMessage = SOAPBuilder.buildPostDevDataResponse(RequestReason.MOUpload, null, redirectURL.toString(), omadmAdapter.getMO(OMAConstants.DevInfoURN), omadmAdapter.getMO(OMAConstants.DevDetailURN), osuManager.getMOTree(homeSP));
                Log.d(TAG, "Upload MO: " + ulMessage);
                OSUResponse ulResponse = httpHandler.exchangeSOAP(mURL, ulMessage);
                if (ulResponse.getMessageType() != OSUMessageType.PostDevData) {
                    throw new IOException("Expected a PostDevDataResponse to MOUpload");
                }
                pddResponse = (PostDevDataResponse) ulResponse;
            }
            if (pddResponse.getExecCommand() == ExecCommand.Browser) {
                if (flowType == OSUManager.FLOW_POLICY) {
                    throw new IOException("Browser launch requested in policy flow");
                }
                String webURL = ((BrowserURI) pddResponse.getCommandData()).getURI();
                if (webURL == null) {
                    throw new IOException("No web-url");
                } else if (!webURL.contains(sessionID)) {
                    throw new IOException("Bad or missing session ID in webURL");
                }
                if (!osuManager.startUserInput(new URL(webURL), network)) {
                    throw new IOException("User session failed");
                }
                Log.d(TAG, " -- Sending user input complete:");
                String userComplete = SOAPBuilder.buildPostDevDataResponse(RequestReason.InputComplete, sessionID, null, omadmAdapter.getMO(OMAConstants.DevInfoURN), omadmAdapter.getMO(OMAConstants.DevDetailURN));
                OSUResponse udResponse = httpHandler.exchangeSOAP(mURL, userComplete);
                if (udResponse.getMessageType() != OSUMessageType.PostDevData) {
                    throw new IOException("Bad user input complete response: " + udResponse);
                }
                pddResponse = (PostDevDataResponse) udResponse;
            } else if (pddResponse.getExecCommand() == ExecCommand.GetCert) {
                certs = new HashMap<>();
                try (ESTHandler estHandler = new ESTHandler((GetCertData) pddResponse.getCommandData(), network, osuManager.getOMADMAdapter(), km, mKeyStore, homeSP, flowType)) {
                    estHandler.execute(true);
                    certs.put(OSUCertType.CA, estHandler.getCACerts());
                    certs.put(OSUCertType.Client, estHandler.getClientCerts());
                    clientKey = estHandler.getClientKey();
                }
                if (httpHandler.isHTTPAuthPerformed()) {
                    // 8.4.3.6
                    httpHandler.renegotiate(certs, clientKey);
                }
                Log.d(TAG, " -- Sending remediation cert enrollment complete:");
                // 8.4.3.5 in the spec actually prescribes that an update URI is sent here,
                // but there is no remediation flow that defines user interaction after EST
                // so for now a null is passed.
                String certComplete = SOAPBuilder.buildPostDevDataResponse(RequestReason.CertEnrollmentComplete, sessionID, null, omadmAdapter.getMO(OMAConstants.DevInfoURN), omadmAdapter.getMO(OMAConstants.DevDetailURN));
                OSUResponse ceResponse = httpHandler.exchangeSOAP(mURL, certComplete);
                if (ceResponse.getMessageType() != OSUMessageType.PostDevData) {
                    throw new IOException("Bad cert enrollment complete response: " + ceResponse);
                }
                pddResponse = (PostDevDataResponse) ceResponse;
            } else {
                throw new IOException("Unexpected command: " + pddResponse.getExecCommand());
            }
        }
        if (pddResponse.getStatus() != OSUStatus.RemediationComplete) {
            throw new IOException("Expected a PostDevDataResponse to MOUpload");
        }
        Log.d(TAG, "Remediation response: " + pddResponse);
        List<MOData> mods = new ArrayList<>();
        for (OSUCommand command : pddResponse.getCommands()) {
            if (command.getOSUCommand() == OSUCommandID.UpdateNode) {
                mods.add((MOData) command.getCommandData());
            } else if (command.getOSUCommand() != OSUCommandID.NoMOUpdate) {
                throw new IOException("Unexpected OSU response: " + command);
            }
        }
        // 1. Machine remediation: Remediation complete + replace node
        // 2a. User remediation with upload: ExecCommand.UploadMO
        // 2b. User remediation without upload: ExecCommand.Browser
        // 3. User remediation only: -> sppPostDevData user input complete
        //
        // 4. Update node
        // 5. -> Update response
        // 6. Exchange complete
        OSUError error = null;
        String updateResponse = SOAPBuilder.buildUpdateResponse(sessionID, error);
        Log.d(TAG, " -- Sending updateResponse:");
        OSUResponse exComplete = httpHandler.exchangeSOAP(mURL, updateResponse);
        Log.d(TAG, "exComplete response: " + exComplete);
        if (exComplete.getMessageType() != OSUMessageType.ExchangeComplete) {
            throw new IOException("Expected ExchangeComplete: " + exComplete);
        } else if (exComplete.getStatus() != OSUStatus.ExchangeComplete) {
            throw new IOException("Bad ExchangeComplete status: " + exComplete);
        }
        // the network is lost and the remediation flow fails.
        try {
            osuManager.remediationComplete(homeSP, mods, certs, clientKey);
        } catch (IOException | GeneralSecurityException e) {
            osuManager.provisioningFailed(homeSP.getFriendlyName(), e.getMessage(), homeSP, OSUManager.FLOW_REMEDIATION);
            error = OSUError.CommandFailed;
        }
    }
}
Also used : PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) ESTHandler(com.android.hotspot2.est.ESTHandler) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) OMADMAdapter(com.android.hotspot2.OMADMAdapter) URL(java.net.URL) MOData(com.android.hotspot2.osu.commands.MOData) BrowserURI(com.android.hotspot2.osu.commands.BrowserURI) ArrayList(java.util.ArrayList) List(java.util.List) GetCertData(com.android.hotspot2.osu.commands.GetCertData)

Example 33 with GeneralSecurityException

use of java.security.GeneralSecurityException in project android_frameworks_base by AOSPA.

the class OSUManager method provisioningComplete.

public void provisioningComplete(OSUInfo osuInfo, MOData moData, Map<OSUCertType, List<X509Certificate>> certs, PrivateKey privateKey, Network osuNetwork) {
    synchronized (mWifiNetworkAdapter) {
        mProvisioningThread = null;
    }
    try {
        Log.d("ZXZ", "MOTree.toXML: " + moData.getMOTree().toXml());
        HomeSP homeSP = mWifiNetworkAdapter.addSP(moData.getMOTree());
        Integer spNwk = mWifiNetworkAdapter.addNetwork(homeSP, certs, privateKey, osuNetwork);
        if (spNwk == null) {
            notifyUser(OSUOperationStatus.ProvisioningFailure, "Failed to save network configuration", osuInfo.getName(LOCALE));
            mWifiNetworkAdapter.removeSP(homeSP.getFQDN());
        } else {
            Set<X509Certificate> rootCerts = OSUSocketFactory.getRootCerts(mKeyStore);
            X509Certificate remCert = getCert(certs, OSUCertType.Remediation);
            X509Certificate polCert = getCert(certs, OSUCertType.Policy);
            if (privateKey != null) {
                X509Certificate cltCert = getCert(certs, OSUCertType.Client);
                mKeyStore.setKeyEntry(CERT_CLT_KEY_ALIAS + homeSP, privateKey.getEncoded(), new X509Certificate[] { cltCert });
                mKeyStore.setCertificateEntry(CERT_CLT_CERT_ALIAS, cltCert);
            }
            boolean usingShared = false;
            int newCerts = 0;
            if (remCert != null) {
                if (!rootCerts.contains(remCert)) {
                    if (remCert.equals(polCert)) {
                        mKeyStore.setCertificateEntry(CERT_SHARED_ALIAS + homeSP.getFQDN(), remCert);
                        usingShared = true;
                        newCerts++;
                    } else {
                        mKeyStore.setCertificateEntry(CERT_REM_ALIAS + homeSP.getFQDN(), remCert);
                        newCerts++;
                    }
                }
            }
            if (!usingShared && polCert != null) {
                if (!rootCerts.contains(polCert)) {
                    mKeyStore.setCertificateEntry(CERT_POLICY_ALIAS + homeSP.getFQDN(), remCert);
                    newCerts++;
                }
            }
            if (newCerts > 0) {
                try (FileOutputStream out = new FileOutputStream(KEYSTORE_FILE)) {
                    mKeyStore.store(out, null);
                }
            }
            notifyUser(OSUOperationStatus.ProvisioningSuccess, null, osuInfo.getName(LOCALE));
            Log.d(TAG, "Provisioning complete.");
        }
    } catch (IOException | GeneralSecurityException | SAXException e) {
        Log.e(TAG, "Failed to provision: " + e, e);
        notifyUser(OSUOperationStatus.ProvisioningFailure, e.toString(), osuInfo.getName(LOCALE));
    }
}
Also used : HomeSP(com.android.hotspot2.pps.HomeSP) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FileOutputStream(java.io.FileOutputStream) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) SAXException(org.xml.sax.SAXException)

Example 34 with GeneralSecurityException

use of java.security.GeneralSecurityException in project GNS by MobilityFirst.

the class Email method simpleMail.

/**
   *
   * @param subject
   * @param recipient
   * @param text
   * @param suppressWarning
   * @return true if the mail was sent
   */
public static boolean simpleMail(String subject, String recipient, String text, boolean suppressWarning) {
    try {
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        Properties props = new Properties();
        props.setProperty("mail.smtp.ssl.enable", "true");
        //props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        Session session = Session.getInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(Config.getGlobalString(GNSConfig.GNSC.SUPPORT_EMAIL)));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
        message.setSubject(subject);
        message.setText(text);
        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        try {
            t.connect(SMTP_HOST, Config.getGlobalString(GNSConfig.GNSC.ADMIN_EMAIL), Config.getGlobalString(GNSConfig.GNSC.ADMIN_PASSWORD));
            t.sendMessage(message, message.getAllRecipients());
            getLogger().log(Level.FINE, "Email response: {0}", t.getLastServerResponse());
        } finally {
            t.close();
        }
        getLogger().log(Level.FINE, "Successfully sent email to {0} with message: {1}", new Object[] { recipient, text });
        return true;
    } catch (GeneralSecurityException | MessagingException e) {
        if (!suppressWarning) {
            getLogger().log(Level.WARNING, "Unable to send email: {0}", e);
        }
        return false;
    }
}
Also used : MailSSLSocketFactory(com.sun.mail.util.MailSSLSocketFactory) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) GeneralSecurityException(java.security.GeneralSecurityException) Properties(java.util.Properties) Session(javax.mail.Session) SMTPTransport(com.sun.mail.smtp.SMTPTransport)

Example 35 with GeneralSecurityException

use of java.security.GeneralSecurityException in project intellij-community by JetBrains.

the class EncryptionUtil method encryptKey.

/**
   * Encrypt key (does not use salting, so the encryption result is the same for the same input)
   *
   * @param password the secret key to use
   * @param rawKey   the raw key to encrypt
   * @return the encrypted key
   */
@NotNull
public static byte[] encryptKey(@NotNull byte[] password, byte[] rawKey) {
    try {
        Cipher c = Cipher.getInstance(ENCRYPT_KEY_ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(password, SECRET_KEY_ALGORITHM), CBC_SALT_KEY);
        return c.doFinal(rawKey);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

GeneralSecurityException (java.security.GeneralSecurityException)1197 IOException (java.io.IOException)448 Cipher (javax.crypto.Cipher)148 Test (org.junit.Test)136 X509Certificate (java.security.cert.X509Certificate)130 KeyStore (java.security.KeyStore)98 SSLContext (javax.net.ssl.SSLContext)86 SecretKeySpec (javax.crypto.spec.SecretKeySpec)82 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)77 ArrayList (java.util.ArrayList)75 File (java.io.File)64 InputStream (java.io.InputStream)63 Certificate (java.security.cert.Certificate)61 PublicKey (java.security.PublicKey)56 FileInputStream (java.io.FileInputStream)54 PrivateKey (java.security.PrivateKey)51 BigInteger (java.math.BigInteger)50 SecretKey (javax.crypto.SecretKey)48 IvParameterSpec (javax.crypto.spec.IvParameterSpec)47 KeyPair (java.security.KeyPair)45