Search in sources :

Example 1 with MyPKCS10CertRequest

use of edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest in project OA4MP by ncsa.

the class ACS2 method doDelegation.

protected void doDelegation(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Throwable {
    info("6.a. Starting to process cert request");
    PARequest paRequest = new PARequest(httpServletRequest, getClient(httpServletRequest));
    String statusString = "client = " + paRequest.getClient().getIdentifier();
    // The next call will pull the access token off of any parameters. The result may be null if there is
    // no access token.
    paRequest.setAccessToken(getAccessToken(httpServletRequest));
    PAResponse paResponse = (PAResponse) getPAI().process(paRequest);
    debug("6.a. " + statusString);
    ServiceTransaction t = verifyAndGet(paResponse);
    Map params = httpServletRequest.getParameterMap();
    if (t.getCertReq() == null) {
        String rawCR = ((String[]) params.get(CONST(ServiceConstantKeys.CERT_REQUEST_KEY)))[0];
        // CIL-409 fix -- fail immediately if the cert request is missing
        if (!params.containsKey(CONST(ServiceConstantKeys.CERT_REQUEST_KEY))) {
            throw new GeneralException("Error: Missing cert request parameter.");
        }
        // CIL-409 fix
        if (isEmpty(rawCR)) {
            throw new GeneralException("Error: Empty cert request.");
        }
        MyPKCS10CertRequest certReq;
        try {
            certReq = CertUtil.fromStringToCertReq(rawCR);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new GeneralException("Error: cert request is bad/not understandable:" + (rawCR == null ? "(null)" : rawCR), throwable);
        }
        t.setCertReq(certReq);
        // The assumption at this point is that this value is in seconds, which is valid for OIDC clients.
        if (params.containsKey(CONST(ServiceConstantKeys.CERT_LIFETIME_KEY))) {
            t.setLifetime(1000 * Long.parseLong(((String[]) params.get(CONST(ServiceConstantKeys.CERT_LIFETIME_KEY)))[0]));
        } else {
            // set the default to 10 days if there is no certlifetime parameter passed in.
            t.setLifetime(1000 * 10 * 24 * 3600);
        }
        getTransactionStore().save(t);
    }
    info("6.a. Processing request for transaction " + t.getIdentifier());
    doRealCertRequest(t, statusString);
    t.setAccessTokenValid(false);
    preprocess(new TransactionState(httpServletRequest, httpServletResponse, paResponse.getParameters(), t));
    debug("6.a. protected asset:" + (t.getProtectedAsset() == null ? "(null)" : "ok") + ", " + statusString);
    HashMap<String, String> username = new HashMap<String, String>();
    username.put("username", t.getUsername());
    if (paResponse.getParameters() != null) {
        username.putAll(paResponse.getParameters());
    }
    paResponse.setAdditionalInformation(username);
    paResponse.setProtectedAsset(t.getProtectedAsset());
    debug("6.a. Added username \"" + t.getUsername() + "\" & cert for request from " + statusString);
    getTransactionStore().save(t);
    info("6.b. Done with cert request " + statusString);
    paResponse.write(httpServletResponse);
    info("6.b. Completed transaction " + t.getIdentifierString() + ", " + statusString);
    postprocess(new TransactionState(httpServletRequest, httpServletResponse, paResponse.getParameters(), t));
}
Also used : TransactionState(edu.uiuc.ncsa.security.delegation.servlet.TransactionState) GeneralException(edu.uiuc.ncsa.security.core.exceptions.GeneralException) ServiceTransaction(edu.uiuc.ncsa.security.delegation.server.ServiceTransaction) HashMap(java.util.HashMap) PAResponse(edu.uiuc.ncsa.security.delegation.server.request.PAResponse) PARequest(edu.uiuc.ncsa.security.delegation.server.request.PARequest) HashMap(java.util.HashMap) Map(java.util.Map) MyPKCS10CertRequest(edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest)

Example 2 with MyPKCS10CertRequest

use of edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest in project OA4MP by ncsa.

the class CRServlet method doCertRequest.

protected void doCertRequest(ServiceTransaction trans, String statusString) throws Throwable {
    if (!hasMPConnection(trans)) {
        throw new ConnectionException("Error: There is no currently active MyProxy connection.");
    }
    MyPKCS10CertRequest localCertRequest = trans.getCertReq();
    KeyPair keyPair = null;
    if (trans.getClient().isProxyLimited()) {
        info("3.b. starting proxy limited for " + trans.getClient().getIdentifier() + ". Generating keypair and cert request.");
        try {
            keyPair = getServiceEnvironment().getKeyPair();
            localCertRequest = CertUtil.createCertRequest(keyPair);
        } catch (GeneralSecurityException e) {
            error("3.b. " + e.getMessage());
        }
    }
    LinkedList<X509Certificate> certs = getX509Certificates(trans, localCertRequest, statusString);
    debug("3.b. Got cert from server, count=" + certs.size());
    LinkedList<X509Certificate> certList = new LinkedList<>();
    // If it is a limited cert, sign it
    if (trans.getClient().isProxyLimited()) {
        info("3.b. Limited proxy for client " + trans.getClient().getIdentifier() + ", creating limited cert and signing it.");
        certList.addAll(certs);
        certList.addFirst(JGlobusUtil.createProxyCertificate(certs.getLast(), keyPair.getPrivate(), trans.getCertReq().getPublicKey(), (int) (trans.getLifetime() / 1000)));
        certs = certList;
    }
    debug("3.b. Preparing to return cert chain of " + certs.size() + " to client.");
    MyX509Certificates myCerts = new MyX509Certificates(certs);
    trans.setProtectedAsset(myCerts);
    String userName = trans.getUsername();
    if (getServiceEnvironment().getAuthorizationServletConfig().isReturnDnAsUsername()) {
        if (myCerts.getX509Certificates().length > 0) {
            X500Principal x500Principal = myCerts.getX509Certificates()[0].getSubjectX500Principal();
            userName = x500Principal.getName();
            if (getServiceEnvironment().getAuthorizationServletConfig().isConvertDNToGlobusID()) {
                userName = JGlobusUtil.toGlobusID(userName);
            }
            debug(statusString + ": USERNAME = " + userName);
        } else {
            userName = "no_certificates_found";
        }
        trans.setUsername(userName);
        info("3.c. Set username returned to client to first certificate's DN: " + userName);
    }
    // Fixes OAUTH-102 username might not be set in some cases, so just reset it here.
    trans.setUsername(userName);
    // Our response is a simple ok, since otherwise exceptions are thrown. No need to set this since that is the default.
    trans.setVerifier(MyProxyDelegationServlet.getServiceEnvironment().getTokenForge().getVerifier());
    getServiceEnvironment().getTransactionStore().save(trans);
    if (hasMPConnection(trans.getIdentifier())) {
        // It can happen (especially in cases of manual testing when there is considerable time between calls)
        // that the connection goes away. This prevents a bogus failure in that case.
        getMPConnection(trans.getIdentifier()).close();
    }
}
Also used : KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) X500Principal(javax.security.auth.x500.X500Principal) MyX509Certificates(edu.uiuc.ncsa.security.delegation.token.MyX509Certificates) ConnectionException(edu.uiuc.ncsa.security.core.exceptions.ConnectionException) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) MyPKCS10CertRequest(edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest)

Example 3 with MyPKCS10CertRequest

use of edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest in project OA4MP by ncsa.

the class OA2MPService method preGetCert.

@Override
public void preGetCert(Asset asset, Map parameters) {
    super.preGetCert(asset, parameters);
    OA2Asset a = (OA2Asset) asset;
    parameters.put(ClientEnvironment.CERT_REQUEST_KEY, PEMFormatUtil.bytesToChunkedString(asset.getCertReq().getEncoded()));
    if (!parameters.containsKey(getEnvironment().getConstants().get(CALLBACK_URI_KEY))) {
        parameters.put(getEnvironment().getConstants().get(CALLBACK_URI_KEY), getEnvironment().getCallback().toString());
    }
    if (0 <= getEnvironment().getCertLifetime()) {
        parameters.put(ClientEnvironment.CERT_LIFETIME_KEY, getEnvironment().getCertLifetime());
    }
    if (asset.getCertificates() != null) {
        // We have some, so restart the sequence to get more.
        MyPKCS10CertRequest certRequest = asset.getCertReq();
        KeyPair keyPair = null;
        if (certRequest == null) {
            // ok... generate a new keypair
            try {
                keyPair = KeyUtil.generateKeyPair();
            } catch (Throwable e) {
                String msg = "Unable to generate a new keypair.";
                getEnvironment().getMyLogger().warn(msg, e);
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }
                throw new GeneralException(msg, e);
            }
            asset.setPrivateKey(keyPair.getPrivate());
        } else {
            // need to public key.
            keyPair = new KeyPair(certRequest.getPublicKey(), asset.getPrivateKey());
        }
        if (asset.getPrivateKey() == null) {
            String msg = "Error: The private key is missing. The internal state of the asset is invalid";
            NFWException x = new NFWException((msg));
            getEnvironment().getMyLogger().warn(msg, x);
            throw x;
        }
        try {
            asset.setCertReq(CertUtil.createCertRequest(keyPair));
        } catch (Throwable t) {
            String msg = "Error: could not create cert request.";
            getEnvironment().getMyLogger().warn(msg, t);
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            }
            throw new GeneralException(msg, t);
        }
    }
}
Also used : NFWException(edu.uiuc.ncsa.security.core.exceptions.NFWException) KeyPair(java.security.KeyPair) GeneralException(edu.uiuc.ncsa.security.core.exceptions.GeneralException) MyPKCS10CertRequest(edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest)

Example 4 with MyPKCS10CertRequest

use of edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest in project OA4MP by ncsa.

the class AssetStoreTest method storeTest.

/**
 * @param store
 * @return
 * @throws Exception
 */
public void storeTest(AssetStore store) throws Exception {
    if (store == null) {
        System.out.println("WARNING: no asset store configured, skipping test.");
        return;
    }
    int count = 10;
    ArrayList<Asset> assets = new ArrayList<>();
    SecureRandom secureRandom = new SecureRandom();
    long l = secureRandom.nextLong();
    String r = Long.toHexString(l);
    KeyPair kp = KeyUtil.generateKeyPair();
    PrivateKey privateKey = kp.getPrivate();
    MyPKCS10CertRequest cr = CertUtil.createCertRequest(kp);
    String rawCR = CertUtil.fromCertReqToString(cr);
    for (int i = 0; i < count; i++) {
        Identifier id = BasicIdentifier.newID("asset:id:/" + r + "/" + i);
        Asset asset = store.create();
        assert asset != null : "Error: The store is not producing valid assets when requested. A null was returned";
        assets.add(asset);
        asset.setIdentifier(id);
        String username = "testUser-" + r;
        URI redirect = URI.create("http://test.foo/test/" + r);
        asset.setPrivateKey(privateKey);
        asset.setUsername(username);
        asset.setRedirect(redirect);
        asset.setCertReq(cr);
        store.save(asset);
    }
    for (Asset asset : assets) {
        Asset asset2 = store.get(asset.getIdentifier());
        assert asset2 != null : "No asset found for identifier \"" + asset.getIdentifier() + "\" on iteration # ";
        assert asset.getIdentifier().equals(asset2.getIdentifier()) : "Identifiers on assets do not match. " + "Expected \"" + asset.getIdentifierString() + "\" but got \"" + asset2.getIdentifierString() + "\"";
        assert asset.getUsername().equals(asset2.getUsername()) : "Username on assets do not match. " + "Expected \"" + asset.getUsername() + "\" but got \"" + asset2.getUsername();
        assert asset.getPrivateKey().equals(asset2.getPrivateKey()) : "Private keys on assets do not match. " + "Expected \"" + asset.getPrivateKey() + "\" but got \"" + asset2.getPrivateKey();
        assert asset.getRedirect().equals(asset2.getRedirect()) : "Redirect on assets do not match. " + "Expected \"" + asset.getRedirect() + "\" but got \"" + asset2.getRedirect();
        // Special note: MySQL will truncate nanoseconds from dates so the best we can do is verify the milliseconds match.
        assert Math.abs(asset.getCreationTime().getTime() - asset2.getCreationTime().getTime()) < 1000 : "Timestamp on assets do not match. " + "Expected \"" + asset.getCreationTime() + "\" but got \"" + asset2.getCreationTime() + "\"";
        // the requests should be identical so we can compare them as strings. This is a data integrity test.
        assert rawCR.equals(CertUtil.fromCertReqToString(asset2.getCertReq())) : "Certification requests on assets do not match. " + "Expected \"" + asset.getCertReq() + "\" but got \"" + asset2.getCertReq();
        // Don't clutter up the store with test cases.
        store.remove(asset.getIdentifier());
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) BasicIdentifier(edu.uiuc.ncsa.security.core.util.BasicIdentifier) Identifier(edu.uiuc.ncsa.security.core.Identifier) ArrayList(java.util.ArrayList) Asset(edu.uiuc.ncsa.myproxy.oa4mp.client.Asset) SecureRandom(java.security.SecureRandom) URI(java.net.URI) MyPKCS10CertRequest(edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest)

Example 5 with MyPKCS10CertRequest

use of edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest in project OA4MP by ncsa.

the class PKCS10_CSR_Test method testBadCSR.

@Test
public void testBadCSR() throws Exception {
    try {
        MyPKCS10CertRequest certReq = CertUtil.fromStringToCertReq(BAD_GLOBUS_CR);
        System.out.println(certReq.getPublicKey());
        assert false : "Was able to process a bad cert request.";
    } catch (InvalidCertRequestException iox) {
        assert true;
    }
    try {
        MyPKCS10CertRequest certReq = CertUtil.fromStringToCertReq(GOOD_GLOBUS_CR);
        assert certReq.getPublicKey() != null;
    } catch (InvalidCertRequestException iox) {
        iox.printStackTrace();
        assert false : "Good cert request failed to parse correctly.";
    }
}
Also used : InvalidCertRequestException(edu.uiuc.ncsa.security.core.exceptions.InvalidCertRequestException) MyPKCS10CertRequest(edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest) Test(org.junit.Test)

Aggregations

MyPKCS10CertRequest (edu.uiuc.ncsa.security.util.pkcs.MyPKCS10CertRequest)13 KeyPair (java.security.KeyPair)7 GeneralException (edu.uiuc.ncsa.security.core.exceptions.GeneralException)5 Test (org.junit.Test)3 Asset (edu.uiuc.ncsa.myproxy.oa4mp.client.Asset)2 Identifier (edu.uiuc.ncsa.security.core.Identifier)2 BasicIdentifier (edu.uiuc.ncsa.security.core.util.BasicIdentifier)2 ServiceTransaction (edu.uiuc.ncsa.security.delegation.server.ServiceTransaction)2 MyX509Certificates (edu.uiuc.ncsa.security.delegation.token.MyX509Certificates)2 URI (java.net.URI)2 PrivateKey (java.security.PrivateKey)2 SecureRandom (java.security.SecureRandom)2 AssetResponse (edu.uiuc.ncsa.myproxy.oa4mp.client.AssetResponse)1 ConnectionException (edu.uiuc.ncsa.security.core.exceptions.ConnectionException)1 InvalidCertRequestException (edu.uiuc.ncsa.security.core.exceptions.InvalidCertRequestException)1 NFWException (edu.uiuc.ncsa.security.core.exceptions.NFWException)1 UnregisteredObjectException (edu.uiuc.ncsa.security.core.exceptions.UnregisteredObjectException)1 AGResponse (edu.uiuc.ncsa.security.delegation.server.request.AGResponse)1 PARequest (edu.uiuc.ncsa.security.delegation.server.request.PARequest)1 PAResponse (edu.uiuc.ncsa.security.delegation.server.request.PAResponse)1