Search in sources :

Example 1 with Credentials

use of sun.security.krb5.Credentials in project AntennaPod by AntennaPod.

the class ProxyDialog method test.

private void test() {
    if (subscription != null) {
        subscription.unsubscribe();
    }
    if (!checkValidity()) {
        setTestRequired(true);
        return;
    }
    TypedArray res = context.getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary });
    int textColorPrimary = res.getColor(0, 0);
    res.recycle();
    String checking = context.getString(R.string.proxy_checking);
    txtvMessage.setTextColor(textColorPrimary);
    txtvMessage.setText("{fa-circle-o-notch spin} " + checking);
    txtvMessage.setVisibility(View.VISIBLE);
    subscription = Observable.create(new Observable.OnSubscribe<Response>() {

        @Override
        public void call(Subscriber<? super Response> subscriber) {
            String type = (String) spType.getSelectedItem();
            String host = etHost.getText().toString();
            String port = etPort.getText().toString();
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();
            int portValue = 8080;
            if (!TextUtils.isEmpty(port)) {
                portValue = Integer.valueOf(port);
            }
            SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
            Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase());
            Proxy proxy = new Proxy(proxyType, address);
            OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).proxy(proxy);
            builder.interceptors().clear();
            OkHttpClient client = builder.build();
            if (!TextUtils.isEmpty(username)) {
                String credentials = Credentials.basic(username, password);
                client.interceptors().add(chain -> {
                    Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
                    return chain.proceed(request);
                });
            }
            Request request = new Request.Builder().url("http://www.google.com").head().build();
            try {
                Response response = client.newCall(request).execute();
                subscriber.onNext(response);
            } catch (IOException e) {
                subscriber.onError(e);
            }
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(response -> {
        int colorId;
        String icon;
        String result;
        if (response.isSuccessful()) {
            colorId = R.color.download_success_green;
            icon = "{fa-check}";
            result = context.getString(R.string.proxy_test_successful);
        } else {
            colorId = R.color.download_failed_red;
            icon = "{fa-close}";
            result = context.getString(R.string.proxy_test_failed);
        }
        int color = ContextCompat.getColor(context, colorId);
        txtvMessage.setTextColor(color);
        String message = String.format("%s %s: %s", icon, result, response.message());
        txtvMessage.setText(message);
        setTestRequired(!response.isSuccessful());
    }, error -> {
        String icon = "{fa-close}";
        String result = context.getString(R.string.proxy_test_failed);
        int color = ContextCompat.getColor(context, R.color.download_failed_red);
        txtvMessage.setTextColor(color);
        String message = String.format("%s %s: %s", icon, result, error.getMessage());
        txtvMessage.setText(message);
        setTestRequired(true);
    });
}
Also used : Context(android.content.Context) SocketAddress(java.net.SocketAddress) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Dialog(android.app.Dialog) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) Observable(rx.Observable) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) MDButton(com.afollestad.materialdialogs.internal.MDButton) Patterns(android.util.Patterns) Proxy(java.net.Proxy) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Response(okhttp3.Response) AdapterView(android.widget.AdapterView) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Request(okhttp3.Request) Subscriber(rx.Subscriber) R(de.danoeh.antennapod.R) ContextCompat(android.support.v4.content.ContextCompat) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) ProxyConfig(de.danoeh.antennapod.core.service.download.ProxyConfig) Spinner(android.widget.Spinner) TimeUnit(java.util.concurrent.TimeUnit) ArrayAdapter(android.widget.ArrayAdapter) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Subscription(rx.Subscription) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Observable(rx.Observable) Response(okhttp3.Response) Proxy(java.net.Proxy) TypedArray(android.content.res.TypedArray) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 2 with Credentials

use of sun.security.krb5.Credentials in project jdk8u_jdk by JetBrains.

the class Krb5Util method getTicketFromSubjectAndTgs.

/**
     * Retrieve the service ticket for serverPrincipal from caller's Subject
     * or from Subject obtained by logging in, or if not found, via the
     * Ticket Granting Service using the TGT obtained from the Subject.
     *
     * Caller must have permission to:
     *    - access and update Subject's private credentials
     *    - create LoginContext
     *    - read the auth.login.defaultCallbackHandler security property
     *
     * NOTE: This method is used by JSSE Kerberos Cipher Suites
     */
public static KerberosTicket getTicketFromSubjectAndTgs(GSSCaller caller, String clientPrincipal, String serverPrincipal, String tgsPrincipal, AccessControlContext acc) throws LoginException, KrbException, IOException {
    // 1. Try to find service ticket in acc subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket = SubjectComber.find(accSubj, serverPrincipal, clientPrincipal, KerberosTicket.class);
    if (ticket != null) {
        // found it
        return ticket;
    }
    Subject loginSubj = null;
    if (!GSSUtil.useSubjectCredsOnly(caller)) {
        // 2. Try to get ticket from login
        try {
            loginSubj = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
            ticket = SubjectComber.find(loginSubj, serverPrincipal, clientPrincipal, KerberosTicket.class);
            if (ticket != null) {
                // found it
                return ticket;
            }
        } catch (LoginException e) {
        // No login entry to use
        // ignore and continue
        }
    }
    // Service ticket not found in subject or login
    // Try to get TGT to acquire service ticket
    // 3. Try to get TGT from acc subject
    KerberosTicket tgt = SubjectComber.find(accSubj, tgsPrincipal, clientPrincipal, KerberosTicket.class);
    boolean fromAcc;
    if (tgt == null && loginSubj != null) {
        // 4. Try to get TGT from login subject
        tgt = SubjectComber.find(loginSubj, tgsPrincipal, clientPrincipal, KerberosTicket.class);
        fromAcc = false;
    } else {
        fromAcc = true;
    }
    // 5. Try to get service ticket using TGT
    if (tgt != null) {
        Credentials tgtCreds = ticketToCreds(tgt);
        Credentials serviceCreds = Credentials.acquireServiceCreds(serverPrincipal, tgtCreds);
        if (serviceCreds != null) {
            ticket = credsToTicket(serviceCreds);
            // Store service ticket in acc's Subject
            if (fromAcc && accSubj != null && !accSubj.isReadOnly()) {
                accSubj.getPrivateCredentials().add(ticket);
            }
        }
    }
    return ticket;
}
Also used : KerberosTicket(javax.security.auth.kerberos.KerberosTicket) LoginException(javax.security.auth.login.LoginException) Subject(javax.security.auth.Subject) Credentials(sun.security.krb5.Credentials)

Example 3 with Credentials

use of sun.security.krb5.Credentials in project jdk8u_jdk by JetBrains.

the class Realm method parseCapaths.

/**
     * Parses the [capaths] stanza of the configuration file for a
     * list of realms to traverse to obtain credentials from the
     * initiating realm cRealm to the target realm sRealm.
     *
     * For a given client realm C there is a tag C in [capaths] whose
     * subtag S has a value which is a (possibly partial) path from C
     * to S. When the path is partial, it contains only the tail of the
     * full path. Values of other subtags will be used to build the full
     * path. The value "." means a direct path from C to S. If realm S
     * does not appear as a subtag, there is no path defined here.
     *
     * The implementation ignores all values which equals to C or S, or
     * a "." in multiple values, or any duplicated realm names.
     *
     * When a path value has more than two realms, they can be specified
     * with multiple key-value pairs each having a single value, but the
     * order must not change.
     *
     * For example:
     *
     * [capaths]
     *    TIVOLI.COM = {
     *        IBM.COM = IBM_LDAPCENTRAL.COM MOONLITE.ORG
     *        IBM_LDAPCENTRAL.COM = LDAPCENTRAL.NET
     *        LDAPCENTRAL.NET = .
     *    }
     *
     * TIVOLI.COM has a direct path to LDAPCENTRAL.NET, which has a direct
     * path to IBM_LDAPCENTRAL.COM. It also has a partial path to IBM.COM
     * being "IBM_LDAPCENTRAL.COM MOONLITE.ORG". Merging these info together,
     * a full path from TIVOLI.COM to IBM.COM will be
     *
     *   TIVOLI.COM -> LDAPCENTRAL.NET -> IBM_LDAPCENTRAL.COM
     *              -> IBM_LDAPCENTRAL.COM -> MOONLITE.ORG
     *
     * Please note the sRealm IBM.COM does not appear in the path.
     *
     * @param cRealm the initiating realm
     * @param sRealm the target realm, not the same as cRealm
     * @returns array of realms including at least cRealm as the first
     *          element
     * @throws KrbException if the config does not contain a sub-stanza
     *          for cRealm in [capaths] or the sub-stanza does not contain
     *          sRealm as a tag
     */
private static String[] parseCapaths(String cRealm, String sRealm) throws KrbException {
    // This line could throw a KrbException
    Config cfg = Config.getInstance();
    if (!cfg.exists("capaths", cRealm, sRealm)) {
        throw new KrbException("No conf");
    }
    LinkedList<String> path = new LinkedList<>();
    String head = sRealm;
    while (true) {
        String value = cfg.getAll("capaths", cRealm, head);
        if (value == null) {
            break;
        }
        String[] more = value.split("\\s+");
        boolean changed = false;
        for (int i = more.length - 1; i >= 0; i--) {
            if (path.contains(more[i]) || more[i].equals(".") || more[i].equals(cRealm) || more[i].equals(sRealm) || more[i].equals(head)) {
                // Ignore invalid values
                continue;
            }
            changed = true;
            path.addFirst(more[i]);
        }
        if (!changed)
            break;
        head = path.getFirst();
    }
    path.addFirst(cRealm);
    return path.toArray(new String[path.size()]);
}
Also used : KerberosString(sun.security.krb5.internal.util.KerberosString)

Example 4 with Credentials

use of sun.security.krb5.Credentials in project jdk8u_jdk by JetBrains.

the class KrbApReq method authenticate.

private void authenticate(Krb5AcceptCredential cred, InetAddress initiator) throws KrbException, IOException {
    int encPartKeyType = apReqMessg.ticket.encPart.getEType();
    Integer kvno = apReqMessg.ticket.encPart.getKeyVersionNumber();
    EncryptionKey[] keys = cred.getKrb5EncryptionKeys(apReqMessg.ticket.sname);
    EncryptionKey dkey = EncryptionKey.findKey(encPartKeyType, kvno, keys);
    if (dkey == null) {
        throw new KrbException(Krb5.API_INVALID_ARG, "Cannot find key of appropriate type to decrypt AP REP - " + EType.toString(encPartKeyType));
    }
    byte[] bytes = apReqMessg.ticket.encPart.decrypt(dkey, KeyUsage.KU_TICKET);
    byte[] temp = apReqMessg.ticket.encPart.reset(bytes);
    EncTicketPart enc_ticketPart = new EncTicketPart(temp);
    checkPermittedEType(enc_ticketPart.key.getEType());
    byte[] bytes2 = apReqMessg.authenticator.decrypt(enc_ticketPart.key, KeyUsage.KU_AP_REQ_AUTHENTICATOR);
    byte[] temp2 = apReqMessg.authenticator.reset(bytes2);
    authenticator = new Authenticator(temp2);
    ctime = authenticator.ctime;
    cusec = authenticator.cusec;
    authenticator.ctime = authenticator.ctime.withMicroSeconds(authenticator.cusec);
    if (!authenticator.cname.equals(enc_ticketPart.cname)) {
        throw new KrbApErrException(Krb5.KRB_AP_ERR_BADMATCH);
    }
    if (!authenticator.ctime.inClockSkew())
        throw new KrbApErrException(Krb5.KRB_AP_ERR_SKEW);
    byte[] hash;
    try {
        hash = MessageDigest.getInstance("MD5").digest(apReqMessg.authenticator.cipher);
    } catch (NoSuchAlgorithmException ex) {
        throw new AssertionError("Impossible");
    }
    char[] h = new char[hash.length * 2];
    for (int i = 0; i < hash.length; i++) {
        h[2 * i] = hexConst[(hash[i] & 0xff) >> 4];
        h[2 * i + 1] = hexConst[hash[i] & 0xf];
    }
    AuthTimeWithHash time = new AuthTimeWithHash(authenticator.cname.toString(), apReqMessg.ticket.sname.toString(), authenticator.ctime.getSeconds(), authenticator.cusec, new String(h));
    rcache.checkAndStore(KerberosTime.now(), time);
    if (initiator != null) {
        // sender host address
        HostAddress sender = new HostAddress(initiator);
        if (enc_ticketPart.caddr != null && !enc_ticketPart.caddr.inList(sender)) {
            if (DEBUG) {
                System.out.println(">>> KrbApReq: initiator is " + sender.getInetAddress() + ", but caddr is " + Arrays.toString(enc_ticketPart.caddr.getInetAddresses()));
            }
            throw new KrbApErrException(Krb5.KRB_AP_ERR_BADADDR);
        }
    }
    // XXX check for repeated authenticator
    // if found
    //    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
    // else
    //    save authenticator to check for later
    KerberosTime now = KerberosTime.now();
    if ((enc_ticketPart.starttime != null && enc_ticketPart.starttime.greaterThanWRTClockSkew(now)) || enc_ticketPart.flags.get(Krb5.TKT_OPTS_INVALID))
        throw new KrbApErrException(Krb5.KRB_AP_ERR_TKT_NYV);
    // than the allowable clock skew, throws ticket expired exception.
    if (enc_ticketPart.endtime != null && now.greaterThanWRTClockSkew(enc_ticketPart.endtime)) {
        throw new KrbApErrException(Krb5.KRB_AP_ERR_TKT_EXPIRED);
    }
    creds = new Credentials(apReqMessg.ticket, authenticator.cname, apReqMessg.ticket.sname, enc_ticketPart.key, enc_ticketPart.flags, enc_ticketPart.authtime, enc_ticketPart.starttime, enc_ticketPart.endtime, enc_ticketPart.renewTill, enc_ticketPart.caddr, enc_ticketPart.authorizationData);
    if (DEBUG) {
        System.out.println(">>> KrbApReq: authenticate succeed.");
    }
}
Also used : AuthTimeWithHash(sun.security.krb5.internal.rcache.AuthTimeWithHash) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 5 with Credentials

use of sun.security.krb5.Credentials in project jdk8u_jdk by JetBrains.

the class Credentials method acquireTGTFromCache.

/**
     * Returns a TGT for the given client principal from a ticket cache.
     *
     * @param princ the client principal. A value of null means that the
     * default principal name in the credentials cache will be used.
     * @param ticketCache the path to the tickets file. A value
     * of null will be accepted to indicate that the default
     * path should be searched
     * @returns the TGT credentials or null if none were found. If the tgt
     * expired, it is the responsibility of the caller to determine this.
     */
public static Credentials acquireTGTFromCache(PrincipalName princ, String ticketCache) throws KrbException, IOException {
    if (ticketCache == null) {
        // The default ticket cache on Windows and Mac is not a file.
        String os = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("os.name"));
        if (os.toUpperCase(Locale.ENGLISH).startsWith("WINDOWS") || os.toUpperCase(Locale.ENGLISH).contains("OS X")) {
            Credentials creds = acquireDefaultCreds();
            if (creds == null) {
                if (DEBUG) {
                    System.out.println(">>> Found no TGT's in LSA");
                }
                return null;
            }
            if (princ != null) {
                if (creds.getClient().equals(princ)) {
                    if (DEBUG) {
                        System.out.println(">>> Obtained TGT from LSA: " + creds);
                    }
                    return creds;
                } else {
                    if (DEBUG) {
                        System.out.println(">>> LSA contains TGT for " + creds.getClient() + " not " + princ);
                    }
                    return null;
                }
            } else {
                if (DEBUG) {
                    System.out.println(">>> Obtained TGT from LSA: " + creds);
                }
                return creds;
            }
        }
    }
    /*
         * Returns the appropriate cache. If ticketCache is null, it is the
         * default cache otherwise it is the cache filename contained in it.
         */
    CredentialsCache ccache = CredentialsCache.getInstance(princ, ticketCache);
    if (ccache == null) {
        return null;
    }
    sun.security.krb5.internal.ccache.Credentials tgtCred = ccache.getDefaultCreds();
    if (tgtCred == null) {
        return null;
    }
    if (EType.isSupported(tgtCred.getEType())) {
        return tgtCred.setKrbCreds();
    } else {
        if (DEBUG) {
            System.out.println(">>> unsupported key type found the default TGT: " + tgtCred.getEType());
        }
        return null;
    }
}
Also used : CredentialsCache(sun.security.krb5.internal.ccache.CredentialsCache)

Aggregations

sun.security.krb5.internal (sun.security.krb5.internal)2 CredentialsCache (sun.security.krb5.internal.ccache.CredentialsCache)2 Dialog (android.app.Dialog)1 Context (android.content.Context)1 TypedArray (android.content.res.TypedArray)1 ContextCompat (android.support.v4.content.ContextCompat)1 Editable (android.text.Editable)1 TextUtils (android.text.TextUtils)1 TextWatcher (android.text.TextWatcher)1 Patterns (android.util.Patterns)1 View (android.view.View)1 AdapterView (android.widget.AdapterView)1 ArrayAdapter (android.widget.ArrayAdapter)1 EditText (android.widget.EditText)1 Spinner (android.widget.Spinner)1 TextView (android.widget.TextView)1 DialogAction (com.afollestad.materialdialogs.DialogAction)1 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)1 MDButton (com.afollestad.materialdialogs.internal.MDButton)1 R (de.danoeh.antennapod.R)1