diff --git a/.github/workflows/tps-basic-test.yml b/.github/workflows/tps-basic-test.yml index 12093868f81..9d5335905cb 100644 --- a/.github/workflows/tps-basic-test.yml +++ b/.github/workflows/tps-basic-test.yml @@ -278,7 +278,7 @@ jobs: --pkcs12-password Secret.123 docker exec pki pki -n caadmin tps-user-show tpsadmin - - name: Set up TPS authentication + - name: Set up TPS authentication and misc cfg settings run: | # import sample TPS users docker exec pki ldapadd \ @@ -297,6 +297,10 @@ jobs: auths.instance.ldap1.ldap.basedn \ ou=people,dc=example,dc=com + # configure TPS to allow tpsclient tests to work + docker exec pki pki-server tps-config-set \ + channel.scp01.no.le.byte true + # restart TPS subsystem docker exec pki pki-server tps-redeploy --wait diff --git a/base/common/src/main/java/com/netscape/cmsutil/crypto/CryptoUtil.java b/base/common/src/main/java/com/netscape/cmsutil/crypto/CryptoUtil.java index a0f1a7a4e35..ba27584c4c9 100644 --- a/base/common/src/main/java/com/netscape/cmsutil/crypto/CryptoUtil.java +++ b/base/common/src/main/java/com/netscape/cmsutil/crypto/CryptoUtil.java @@ -2471,6 +2471,51 @@ public static List exportSharedSecret(String nickname, java.security.cer return listWrappedKeys; } + public static List exportSharedSecretWithAES(String nickname, java.security.cert.X509Certificate wrappingCert, + SymmetricKey wrappingKey,boolean useOAEPKeyWrap) throws Exception { + + CryptoManager cm = CryptoManager.getInstance(); + CryptoToken token = cm.getInternalKeyStorageToken(); + String method = "CrytoUtil.exportSharedSecret"; + List listWrappedKeys = new ArrayList(); + + logger.debug(method + " nickname: " + nickname); + + SymmetricKey sharedSecretKey = null; + + try { + sharedSecretKey = getSymKeyByName(token, nickname); + } catch (Exception e) { + logger.debug(method + " can't find shared secret: " + nickname); + throw new IOException("Shared secret " + nickname + " does not exist"); + } + + PublicKey pub = wrappingCert.getPublicKey(); + PK11PubKey pubK = PK11PubKey.fromSPKI(pub.getEncoded()); + + //Wrap the temp AES key with the cert + byte[] wrappedKey = wrapUsingPublicKey(token, pubK, wrappingKey, useOAEPKeyWrap ? KeyWrapAlgorithm.RSA_OAEP: KeyWrapAlgorithm.RSA); + + listWrappedKeys.add(wrappedKey); + //Use the AES key to wrap the shared secret + + KeyWrapAlgorithm wrapAlg = KeyWrapAlgorithm.AES_CBC_PAD; + int ivLen = wrapAlg.getBlockSize(); + byte[] iv = new byte[ivLen]; + + IVParameterSpec ivsp = new IVParameterSpec(iv); + + byte[] wrappedSharedSecret = wrapUsingSymmetricKey(token, wrappingKey, sharedSecretKey, ivsp, wrapAlg); + + listWrappedKeys.add(wrappedSharedSecret); + + if (listWrappedKeys.size() != 2) { + throw new IOException("Can't write out shared secret data to export for nickname: " + nickname); + } + + return listWrappedKeys; + } + public static void importSharedSecret(byte[] wrappedSessionKey,byte[] wrappedSharedSecret,String subsystemCertNickname,String sharedSecretNickname) throws Exception, NotInitializedException, TokenException, NoSuchAlgorithmException, ObjectNotFoundException, InvalidKeyException, InvalidAlgorithmParameterException, IOException { @@ -2689,8 +2734,8 @@ public static SymmetricKey unwrapAESSKeyFromBytes(CryptoToken token, byte[] inpu String method = "CryptoUtil.unwrapAESKeyFromBytes: "; logger.debug(method + "begins: isPerm: " + isPerm); - //for now assume 128 bits aes - if(inputKeyArray.length > 16) { + //support 128 or 256 bits aes + if(inputKeyArray.length > 32) { throw new Exception(method + "invalid input data size."); } diff --git a/base/common/src/main/java/org/dogtagpki/tps/apdu/APDU.java b/base/common/src/main/java/org/dogtagpki/tps/apdu/APDU.java index 1bbaeaeff58..2f368a8f95a 100644 --- a/base/common/src/main/java/org/dogtagpki/tps/apdu/APDU.java +++ b/base/common/src/main/java/org/dogtagpki/tps/apdu/APDU.java @@ -58,7 +58,9 @@ public enum Type { APDU_GET_ISSUERINFO, APDU_GENERATE_KEY_ECC, APDU_GET_LIFECYCLE, - APDU_CLEAR_KEY_SLOTS + APDU_CLEAR_KEY_SLOTS, + APDU_DELETE_KEYS // ** G&D 256 Key Rollover Support ** + } protected byte cla; @@ -154,6 +156,23 @@ public TPSBuffer getEncoding() { return encoding; } + // New method for IDEMIA token processing + public TPSBuffer getEncodingWithLength() { + + TPSBuffer encoding = new TPSBuffer(); + + encoding.add(cla); + encoding.add(ins); + encoding.add(p1); + encoding.add(p2); + + if (trailer != null) { + encoding.add(trailer); + } + + return encoding; + } + public TPSBuffer getDataToMAC() { TPSBuffer mac = new TPSBuffer(); diff --git a/base/common/src/main/java/org/dogtagpki/tps/apdu/DeleteKeysAPDU.java b/base/common/src/main/java/org/dogtagpki/tps/apdu/DeleteKeysAPDU.java new file mode 100644 index 00000000000..b49a30f0e48 --- /dev/null +++ b/base/common/src/main/java/org/dogtagpki/tps/apdu/DeleteKeysAPDU.java @@ -0,0 +1,34 @@ +package org.dogtagpki.tps.apdu; + +/** + * ** G&D 256 Key Rollover Support ** + */ + +import org.dogtagpki.tps.main.TPSBuffer; + +public class DeleteKeysAPDU extends APDU { + + public DeleteKeysAPDU(TPSBuffer keyVersion) { + setCLA((byte) 0x84); + setINS((byte) 0xE4); + setP1((byte) 0x00); + setP2((byte) 0x00); + + TPSBuffer keyData = new TPSBuffer(); + + keyData.add((byte) 0xD2); // tag for deleting key version + keyData.add((byte) keyVersion.size()); // length of key version + keyData.add(keyVersion); // key version + + //CMS.debug("DeleteKeysAPDU: keyData = " + keyData.toHexString()); + + setData(keyData); + + } + + @Override + public APDU.Type getType() { + return APDU.Type.APDU_DELETE_KEYS; + + } +} diff --git a/base/common/src/main/java/org/dogtagpki/tps/apdu/SelectAPDU.java b/base/common/src/main/java/org/dogtagpki/tps/apdu/SelectAPDU.java index ca13cb96858..c8b0710c64e 100644 --- a/base/common/src/main/java/org/dogtagpki/tps/apdu/SelectAPDU.java +++ b/base/common/src/main/java/org/dogtagpki/tps/apdu/SelectAPDU.java @@ -30,6 +30,18 @@ public SelectAPDU(byte p1, byte p2, TPSBuffer theData) setP1(p1); setP2(p2); setData(theData); + // Add trailer byte + TPSBuffer trailer = new TPSBuffer(1); + setTrailer(trailer); + } + + // This constructor is used to make a card mgr request with no data + public SelectAPDU(byte p1, byte p2) + { + setCLA((byte) 0x00); + setINS((byte) 0xa4); + setP1(p1); + setP2(p2); } @Override diff --git a/base/common/src/main/java/org/dogtagpki/tps/msg/EndOpMsg.java b/base/common/src/main/java/org/dogtagpki/tps/msg/EndOpMsg.java index 7b54b400f64..b6076fd87c5 100644 --- a/base/common/src/main/java/org/dogtagpki/tps/msg/EndOpMsg.java +++ b/base/common/src/main/java/org/dogtagpki/tps/msg/EndOpMsg.java @@ -68,7 +68,8 @@ public enum TPSStatus { STATUS_ERROR_REVOKE_CERTIFICATES_FAILED(42), STATUS_ERROR_NOT_TOKEN_OWNER(43), STATUS_RENEWAL_IS_PROCESSED(44), - STATUS_ERROR_CANNOT_ESTABLISH_COMMUNICATION(45); + STATUS_ERROR_CANNOT_ESTABLISH_COMMUNICATION(45), + STATUS_ERROR_SYMKEY_256_UPGRADE(46); // ** G&D 256 Key Rollover Support ** private TPSStatus(int code) { this.code = code; diff --git a/base/common/src/main/java/org/dogtagpki/tps/msg/TokenPDURequestMsg.java b/base/common/src/main/java/org/dogtagpki/tps/msg/TokenPDURequestMsg.java index 42fcf257ce2..ab3af284c74 100644 --- a/base/common/src/main/java/org/dogtagpki/tps/msg/TokenPDURequestMsg.java +++ b/base/common/src/main/java/org/dogtagpki/tps/msg/TokenPDURequestMsg.java @@ -42,6 +42,34 @@ public TokenPDURequestMsg(APDU apdu) { } + // This constructor is used to add a length byte to the apdu + public TokenPDURequestMsg(APDU apdu, boolean addLength) { + + put(MSG_TYPE_NAME, msgTypeToInt(MsgType.MSG_TOKEN_PDU_REQUEST)); + + TPSBuffer encoding = null; + + if (apdu != null) { + + if (addLength) + { + encoding = apdu.getEncodingWithLength(); + } + else + { + encoding = apdu.getEncoding(); + } + + int apduSize = encoding.size(); + + String apdu_value = Util.uriEncodeInHex(encoding.toBytesArray()); + + put(PDU_SIZE_NAME, apduSize); + put(PDU_DATA_NAME, apdu_value); + } + + } + public static void main(String[] args) { SelectAPDU apdu = null; diff --git a/base/kra/src/main/java/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java b/base/kra/src/main/java/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java index 5328ef4e871..95893f7453d 100644 --- a/base/kra/src/main/java/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java +++ b/base/kra/src/main/java/com/netscape/cms/servlet/connector/GenerateKeyPairServlet.java @@ -161,6 +161,11 @@ private void processServerSideKeyGen(HttpServletRequest req, String rKeytype = req.getParameter(IRemoteRequest.KRA_KEYGEN_KeyType); String rKeycurve = req.getParameter(IRemoteRequest.KRA_KEYGEN_EC_KeyCurve); + //Optional AES key wrap alg, default KWP anyway. + String rAesWrapAlg = req.getParameter(IRemoteRequest.KRA_Aes_Wrap_Alg); + logger.debug("GenerateKeyPairServlet: processServerSideKeygen(): rAesWrapAlg: " + rAesWrapAlg); + + //Get trans wrapped aes session key if provided. String raesKeyString = req.getParameter(IRemoteRequest.KRA_Trans_AesKey); @@ -241,6 +246,10 @@ private void processServerSideKeyGen(HttpServletRequest req, thisreq.setExtData(Request.NETKEY_ATTR_KEY_TYPE, rKeytype); thisreq.setExtData(Request.NETKEY_ATTR_KEY_EC_CURVE, rKeycurve); + if((rAesWrapAlg != null) && (rAesWrapAlg.length() >0)) { + thisreq.setExtData(Request.NETKEY_ATTR_SSKEYGEN_AES_KEY_WRAP_ALG,rAesWrapAlg); + } + queue.processRequest(thisreq); Integer result = thisreq.getExtDataInInteger(Request.RESULT); if (result != null) { diff --git a/base/kra/src/main/java/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java b/base/kra/src/main/java/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java index c584881faa7..46bd2d5c4b3 100644 --- a/base/kra/src/main/java/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java +++ b/base/kra/src/main/java/com/netscape/cms/servlet/connector/TokenKeyRecoveryServlet.java @@ -172,6 +172,7 @@ private void processTokenKeyRecovery(HttpServletRequest req, boolean missingParam = false; boolean missingTransAes = false; boolean missingTransDes = false; + boolean missingAesKeyWrapAlg = false; String status = "0"; @@ -182,9 +183,19 @@ private void processTokenKeyRecovery(HttpServletRequest req, String rKeyid = req.getParameter(IRemoteRequest.KRA_RECOVERY_KEYID); String rdesKeyString = req.getParameter(IRemoteRequest.KRA_Trans_DesKey); String rCert = req.getParameter(IRemoteRequest.KRA_RECOVERY_CERT); + + //RedHat : make sure the key wrap alg is being processed correctly + String aesKeyWrapAlg = req.getParameter(IRemoteRequest.KRA_Aes_Wrap_Alg); + String raesKeyString = req.getParameter(IRemoteRequest.KRA_Trans_AesKey); + //RedHat : make sure the key wrap alg is being processed correctly + if ((aesKeyWrapAlg == null) || (aesKeyWrapAlg.equals(""))) { + logger.debug("TokenKeyRecoveryServlet: processTokenKeyRecovery(): missing request parameter: AES-KeyWrap-alg"); + missingAesKeyWrapAlg = true; + } + if ((rCUID == null) || (rCUID.equals(""))) { logger.warn("TokenKeyRecoveryServlet: processTokenKeyRecovery(): missing request parameter: CUID"); missingParam = true; @@ -231,6 +242,12 @@ private void processTokenKeyRecovery(HttpServletRequest req, thisreq.setExtData(Request.NETKEY_ATTR_DRMTRANS_AES_KEY, raesKeyString); } + //RedHat : make sure the key wrap alg is being processed correctly + if(!missingAesKeyWrapAlg) { + logger.debug("TokenKeyRecoveryServlet: processTokenKeyRecovery(): aesKeyWrapAlg: " + aesKeyWrapAlg); + thisreq.setExtData(Request.NETKEY_ATTR_SSKEYGEN_AES_KEY_WRAP_ALG,aesKeyWrapAlg); + } + if ((rCert != null) && (!rCert.equals(""))) { thisreq.setExtData(Request.NETKEY_ATTR_USER_CERT, rCert); logger.debug("TokenKeyRecoveryServlet: processTokenKeyRecovery(): received request parameter: cert"); diff --git a/base/kra/src/main/java/com/netscape/kra/NetkeyKeygenService.java b/base/kra/src/main/java/com/netscape/kra/NetkeyKeygenService.java index 0c6b2b56372..008c7a5deb9 100644 --- a/base/kra/src/main/java/com/netscape/kra/NetkeyKeygenService.java +++ b/base/kra/src/main/java/com/netscape/kra/NetkeyKeygenService.java @@ -16,7 +16,7 @@ // All rights reserved. // --- END COPYRIGHT BLOCK --- package com.netscape.kra; - +import java.util.Arrays; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FilterOutputStream; @@ -27,8 +27,7 @@ import java.security.KeyPair; import java.security.SecureRandom; -import org.dogtagpki.server.kra.KRAEngine; -import org.dogtagpki.server.kra.KRAEngineConfig; +import org.dogtagpki.tps.main.TPSBuffer; import org.mozilla.jss.asn1.ASN1Util; import org.mozilla.jss.crypto.CryptoToken; import org.mozilla.jss.crypto.EncryptionAlgorithm; @@ -37,34 +36,46 @@ import org.mozilla.jss.crypto.KeyWrapAlgorithm; import org.mozilla.jss.crypto.PrivateKey; import org.mozilla.jss.crypto.SymmetricKey; -import org.mozilla.jss.netscape.security.provider.RSAPublicKey; -import org.mozilla.jss.netscape.security.util.Utils; -import org.mozilla.jss.netscape.security.util.WrappingParams; +import org.mozilla.jss.crypto.KeyPairAlgorithm; import org.mozilla.jss.pkcs11.PK11SymKey; import org.mozilla.jss.pkix.crmf.PKIArchiveOptions; import org.mozilla.jss.util.Base64OutputStream; +import org.dogtagpki.server.kra.KRAEngine; +import org.dogtagpki.server.kra.KRAEngineConfig; + import com.netscape.certsrv.base.EBaseException; import com.netscape.certsrv.base.MetaInfo; import com.netscape.certsrv.base.SessionContext; +import com.netscape.cmscore.dbs.KeyRecord; +import com.netscape.cmscore.dbs.KeyRepository; + import com.netscape.certsrv.dbs.keydb.KeyId; import com.netscape.certsrv.logging.ILogger; +import com.netscape.certsrv.logging.LogEvent; import com.netscape.certsrv.logging.event.SecurityDataArchivalProcessedEvent; import com.netscape.certsrv.logging.event.SecurityDataArchivalRequestEvent; import com.netscape.certsrv.logging.event.SecurityDataExportEvent; import com.netscape.certsrv.logging.event.ServerSideKeyGenEvent; import com.netscape.certsrv.logging.event.ServerSideKeyGenProcessedEvent; + +import com.netscape.cmscore.logging.Auditor; +import com.netscape.cmscore.request.Request; + import com.netscape.certsrv.request.IService; import com.netscape.certsrv.request.RequestId; import com.netscape.certsrv.security.IStorageKeyUnit; +import com.netscape.cms.logging.Logger; +import com.netscape.cms.logging.SignedAuditLogger; import com.netscape.cms.servlet.key.KeyRecordParser; import com.netscape.cmscore.dbs.KeyRecord; -import com.netscape.cmscore.dbs.KeyRepository; -import com.netscape.cmscore.logging.Auditor; -import com.netscape.cmscore.request.Request; import com.netscape.cmscore.security.JssSubsystem; import com.netscape.cmsutil.crypto.CryptoUtil; +import org.mozilla.jss.netscape.security.util.Utils; +import org.mozilla.jss.netscape.security.provider.RSAPublicKey; +import org.mozilla.jss.netscape.security.util.WrappingParams; + /** * A class representing keygen/archival request procesor for requests * from netkey RAs. @@ -91,26 +102,10 @@ public class NetkeyKeygenService implements IService { public final static String ATTR_PROOF_OF_ARCHIVAL = "proofOfArchival"; - private KeyRecoveryAuthority mKRA; - private TransportKeyUnit mTransportUnit; + private KeyRecoveryAuthority mKRA = null; + private TransportKeyUnit mTransportUnit = null; private IStorageKeyUnit mStorageUnit = null; - // AC: KDF SPEC CHANGE - Audit logging helper functions. - // Converts a byte array to an ASCII-hex string. - // We implemented this ourselves rather than using this.pp.toHexArray() because - // the team preferred CUID and KDD strings to be without ":" separators every byte. - final char[] bytesToHex_hexArray = "0123456789ABCDEF".toCharArray(); - - private String bytesToHex(byte[] bytes) { - char[] hexChars = new char[bytes.length * 2]; - for (int i = 0; i < bytes.length; i++) { - int thisChar = bytes[i] & 0x000000FF; - hexChars[i * 2] = bytesToHex_hexArray[thisChar >>> 4]; // div 16 - hexChars[i * 2 + 1] = bytesToHex_hexArray[thisChar & 0x0F]; - } - return new String(hexChars); - } - /** * Constructs request processor. *

@@ -131,7 +126,7 @@ public PKIArchiveOptions toPKIArchiveOptions(byte options[]) { archOpts = (PKIArchiveOptions) (new PKIArchiveOptions.Template()).decode(bis); } catch (Exception e) { - logger.warn("NetkeyKeygenService: getPKIArchiveOptions " + e.getMessage(), e); + logger.debug("NetkeyKeygenService: getPKIArchiveOptions " + e.toString()); } return archOpts; } @@ -152,6 +147,22 @@ private static String base64Encode(byte[] bytes) throws IOException { } } + // AC: KDF SPEC CHANGE - Audit logging helper functions. + // Converts a byte array to an ASCII-hex string. + // We implemented this ourselves rather than using this.pp.toHexArray() because + // the team preferred CUID and KDD strings to be without ":" separators every byte. + final char[] bytesToHex_hexArray = "0123456789ABCDEF".toCharArray(); + + private String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int i = 0; i < bytes.length; i++) { + int thisChar = bytes[i] & 0x000000FF; + hexChars[i * 2] = bytesToHex_hexArray[thisChar >>> 4]; // div 16 + hexChars[i * 2 + 1] = bytesToHex_hexArray[thisChar & 0x0F]; + } + return new String(hexChars); + } + /** * Services an archival request from netkey. *

@@ -160,34 +171,41 @@ private static String base64Encode(byte[] bytes) throws IOException { * @return serving successful or not * @exception EBaseException failed to serve */ - @Override public boolean serviceRequest(Request request) throws EBaseException { - - KRAEngine engine = KRAEngine.getInstance(); - JssSubsystem jssSubsystem = engine.getJSSSubsystem(); - + String auditSubjectID = null; byte[] wrapped_des_key; - byte[] wrapped_aes_key = null; + byte[] wrapped_aes_key = null; String method = "NetkeyKeygenService: serviceRequest: "; byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; + int ivLength = EncryptionAlgorithm.AES_128_CBC.getIVLength(); + + logger.debug(method + " cbc iv len: " + ivLength); + + KRAEngine engine = KRAEngine.getInstance(); + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); + Auditor auditor = engine.getAuditor(); + + byte iv_cbc[] = new byte[ivLength]; String iv_s = ""; try { SecureRandom random = jssSubsystem.getRandomNumberGenerator(); random.nextBytes(iv); } catch (Exception e) { - logger.error("NetkeyKeygenService.serviceRequest: " + e.getMessage(), e); + logger.debug("NetkeyKeygenService.serviceRequest: " + e.toString()); throw new EBaseException(e); } IVParameterSpec algParam = null; - IVParameterSpec desAlgParam = new IVParameterSpec(iv); + IVParameterSpec desAlgParam = new IVParameterSpec(iv); + IVParameterSpec aesCBCAlgParam = new IVParameterSpec(iv_cbc); KRAEngineConfig configStore = engine.getConfig(); boolean allowEncDecrypt_archival = configStore.getBoolean("kra.allowEncDecrypt.archival", false); - boolean useOAEPKeyWrap = configStore.getUseOAEPKeyWrap(); + boolean useOAEPKeyWrap = configStore.getBoolean("keyWrap.useOAEP",false); + wrapped_des_key = null; boolean archive = true; byte[] publicKeyData = null; @@ -208,8 +226,7 @@ public boolean serviceRequest(Request request) String rKeytype = request.getExtDataInString(Request.NETKEY_ATTR_KEY_TYPE); RequestId requestId = request.getRequestId(); - Auditor auditor = engine.getAuditor(); - String auditSubjectID = rCUID + ":" + rUserid; + auditSubjectID = rCUID + ":" + rUserid; SessionContext sContext = SessionContext.getContext(); String agentId = ""; @@ -225,15 +242,24 @@ public boolean serviceRequest(Request request) String rWrappedDesKeyString = request.getExtDataInString(Request.NETKEY_ATTR_DRMTRANS_DES_KEY); String rWrappedAesKeyString = request.getExtDataInString(Request.NETKEY_ATTR_DRMTRANS_AES_KEY); + String aesKeyWrapAlg = request.getExtDataInString(Request.NETKEY_ATTR_SSKEYGEN_AES_KEY_WRAP_ALG); + + logger.debug(method + " Request.NETKEY_ATTR_SSKEYGEN_AES_KEY_WRAP_ALG: " + Request.NETKEY_ATTR_SSKEYGEN_AES_KEY_WRAP_ALG); + + if(aesKeyWrapAlg != null) { + logger.debug(method + " aesKeyWrapAlg: " + aesKeyWrapAlg); + } else { + logger.debug(method + " no aesKeyWrapAlg provided."); + } boolean useAesTransWrapped = false; if(rWrappedAesKeyString != null && rWrappedAesKeyString.length() > 0) { useAesTransWrapped = true; - //If we are getting an aes trans wrapped key, make that the priority moving forwoard. + //If we are getting an aes trans wrapped key, make that the priority moving forwoard. wrapped_aes_key = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rWrappedAesKeyString); logger.debug(method + "TMS has sent trans wrapped aes key."); - request.setExtData(Request.NETKEY_ATTR_DRMTRANS_AES_KEY,""); + request.setExtData(Request.NETKEY_ATTR_DRMTRANS_AES_KEY,""); } // the request reocrd field delayLDAPCommit == "true" will cause @@ -253,10 +279,6 @@ public boolean serviceRequest(Request request) } else logger.debug("NetkeyKeygenService: serviceRequest: key type = "+ rKeytype); - if(wrapped_aes_key != null) { - logger.debug(method + " wrapped aes key size " + wrapped_aes_key.length); - } - /* for EC, keysize is ignored, only key curve is used */ String rKeysize = "2048"; int keysize = 2048; @@ -273,19 +295,21 @@ public boolean serviceRequest(Request request) // get the token for generating user keys CryptoToken keygenToken = mKRA.getKeygenToken(); + if (keygenToken == null) { - logger.warn("NetkeyKeygenService: failed getting keygenToken"); + logger.debug("NetkeyKeygenService: failed getting keygenToken"); request.setExtData(Request.RESULT, Integer.valueOf(10)); return false; - } - logger.debug("NetkeyKeygenService: got keygenToken"); + } else + logger.debug("NetkeyKeygenService: got keygenToken"); - if(wrapped_aes_key != null) { - logger.debug(method + " wrapped aes key size " + wrapped_aes_key.length); + if(wrapped_aes_key != null) { + logger.debug(method + " wrapped aes key size " + wrapped_aes_key.length); } + //Create legacy DES and new AES wrapping params, one or the other will be used. if ((wrapped_des_key != null) && - (wrapped_des_key.length > 0) || useAesTransWrapped == true) { + (wrapped_des_key.length > 0) || useAesTransWrapped == true) { KeyWrapAlgorithm wrapAlg = KeyWrapAlgorithm.RSA; @@ -293,19 +317,15 @@ public boolean serviceRequest(Request request) wrapAlg = KeyWrapAlgorithm.RSA_OAEP; } - //Create legacy DES and new AES wrapping params, one or the other will be used. - // - WrappingParams wrapParams = new WrappingParams( SymmetricKey.DES3, KeyGenAlgorithm.DES3, 0, wrapAlg, EncryptionAlgorithm.DES3_CBC_PAD, KeyWrapAlgorithm.DES3_CBC_PAD, EncryptionUnit.IV, EncryptionUnit.IV); - WrappingParams aesWrapParams = new WrappingParams( - SymmetricKey.AES, KeyGenAlgorithm.AES,0, - wrapAlg, EncryptionAlgorithm.AES_128_CBC_PAD, - KeyWrapAlgorithm.AES_KEY_WRAP_PAD,EncryptionUnit.IV, EncryptionUnit.IV); - + WrappingParams aesWrapParams = new WrappingParams( + SymmetricKey.AES, KeyGenAlgorithm.AES,0, + wrapAlg, EncryptionAlgorithm.AES_128_CBC_PAD, + KeyWrapAlgorithm.AES_KEY_WRAP_PAD,EncryptionUnit.IV, EncryptionUnit.IV); /* XXX could be done in HSM*/ KeyPair keypair = null; @@ -319,7 +339,7 @@ public boolean serviceRequest(Request request) null /* usageList*/); if (keypair == null) { - logger.warn("NetkeyKeygenService: failed generating key pair for " + rCUID + ":" + rUserid); + logger.debug("NetkeyKeygenService: failed generating key pair for " + rCUID + ":" + rUserid); request.setExtData(Request.RESULT, Integer.valueOf(4)); auditor.log(new ServerSideKeyGenProcessedEvent( @@ -335,24 +355,26 @@ public boolean serviceRequest(Request request) logger.debug("NetkeyKeygenService: finished generate key pair for " + rCUID + ":" + rUserid); java.security.PrivateKey privKey; + try { publicKeyData = keypair.getPublic().getEncoded(); if (publicKeyData == null) { request.setExtData(Request.RESULT, Integer.valueOf(4)); - logger.warn("NetkeyKeygenService: failed getting publickey encoded"); + logger.debug("NetkeyKeygenService: failed getting publickey encoded"); return false; - } - //logger.debug("NetkeyKeygenService: public key binary length ="+ publicKeyData.length); - if (rKeytype.equals("EC")) { - /* url encode */ - PubKey = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(publicKeyData); - logger.debug("NetkeyKeygenService: EC PubKey special encoded"); } else { - PubKey = base64Encode(publicKeyData); - } + //logger.debug("NetkeyKeygenService: public key binary length ="+ publicKeyData.length); + if (rKeytype.equals("EC")) { + /* url encode */ + PubKey = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(publicKeyData); + logger.debug("NetkeyKeygenService: EC PubKey special encoded"); + } else { + PubKey = base64Encode(publicKeyData); + } - //logger.debug("NetkeyKeygenService: public key length =" + PubKey.length()); - request.setExtData("public_key", PubKey); + //logger.debug("NetkeyKeygenService: public key length =" + PubKey.length()); + request.setExtData("public_key", PubKey); + } auditor.log(new ServerSideKeyGenProcessedEvent( agentId, @@ -363,56 +385,67 @@ public boolean serviceRequest(Request request) //...extract the private key handle (not privatekeydata) privKey = keypair.getPrivate(); - if (privKey == null) { request.setExtData(Request.RESULT, Integer.valueOf(4)); - logger.warn("NetkeyKeygenService: failed getting private key"); + logger.debug("NetkeyKeygenService: failed getting private key"); return false; + } else { + logger.debug("NetkeyKeygenService: got private key"); } - logger.debug("NetkeyKeygenService: got private key"); - - // unwrap the DES or AES key - // If we are given an AES key, use it, otherwise use DES if it's the only one offered. + // unwrap the DES or AES key + // If we are given an AES key, use it, otherwise use DES if it's the only one offered. PK11SymKey sk = null; if(useAesTransWrapped == false) { - try { - sk = (PK11SymKey) mTransportUnit.unwrap_sym(wrapped_des_key, wrapParams); - logger.debug("NetkeyKeygenService: received DES key"); - } catch (Exception e) { - logger.warn("NetkeyKeygenService: no DES key: probably because crypto token no longer supports DES. " + e); - request.setExtData(Request.RESULT, Integer.valueOf(4)); - return false; - } - } else { - //Unwrap the included trans wrapped AES key. - logger.debug(method + "Attempt to unwrap the trans wrapped AES session key."); - try { - sk = (PK11SymKey) mTransportUnit.unwrap_sym(wrapped_aes_key, aesWrapParams); - logger.debug(method + " received AES session key"); - } catch (Exception e) { - logger.warn(method + " no AES session key: or DES kek key. " + e); - request.setExtData(Request.RESULT, Integer.valueOf(4)); - return false; - } + try { + sk = (PK11SymKey) mTransportUnit.unwrap_sym(wrapped_des_key, wrapParams); + logger.debug("NetkeyKeygenService: received DES key"); + } catch (Exception e) { + logger.debug("NetkeyKeygenService: no DES key: probably because crypto token no longer supports DES. " + e); + request.setExtData(Request.RESULT, Integer.valueOf(4)); + return false; + } + } else { + //Unwrap the included trans wrapped AES key. + logger.debug(method + "Attempt to unwrap the trans wrapped AES session key."); + try { + sk = (PK11SymKey) mTransportUnit.unwrap_sym(wrapped_aes_key, aesWrapParams); + logger.debug(method + " received AES session key"); + } catch (Exception e) { + logger.debug(method + " no AES session key: or DES kek key. " + e); + request.setExtData(Request.RESULT, Integer.valueOf(4)); + return false; + } } - // 3 wrapping should be done in HSM - // wrap private key with session key + // wrap private key with session key logger.debug("NetkeyKeygenService: wrapper token=" + keygenToken.getName()); logger.debug("NetkeyKeygenService: key transport key is on slot: " + sk.getOwningToken().getName()); - KeyWrapAlgorithm symWrapAlg = KeyWrapAlgorithm.DES3_CBC_PAD; if(useAesTransWrapped == true) { - //Here we must use AES KWP because it's the only common AES key wrap to be supoprted on hsm, nss, and soon the coolkey applet. - //Should make this configurable at some point. - symWrapAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD_KWP; - algParam = null; + //Here we recomment to use AES KWP because it's the only common AES key wrap to be supoprted on hsm, nss, and soon the coolkey applet. + //But now we are going to make it configurable to AES CBC based on interest in doing so. KWP is the one that is assured to work + //with the applet and nss / hsm envorinments. CBC can be chosen at the admin's discretion. + + if(aesKeyWrapAlg != null && "CBC".equalsIgnoreCase(aesKeyWrapAlg)) { + // We want CBC + logger.debug(method + " TPS has selected CBC for AES key wrap method."); + symWrapAlg = KeyWrapAlgorithm.AES_CBC_PAD; + + algParam = aesCBCAlgParam; + iv_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(iv_cbc); + + } else { + symWrapAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD_KWP; + algParam = null; + iv_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(iv); + } logger.debug(method + " attemptedAesKeyWrap = true "); } else { algParam = desAlgParam; + iv_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(iv); logger.debug(method + " attemptedAesKeyWrap = false "); } @@ -423,9 +456,6 @@ public boolean serviceRequest(Request request) algParam, symWrapAlg); - logger.debug("NetkeyKeygenService: wrap on private key called"); - //logger.debug(method + " wrapped priv key: " + bytesToHex(wrapped)); - /* logger.debug("NetkeyKeygenService: wrap called"); logger.debug(wrapped); @@ -444,7 +474,7 @@ public boolean serviceRequest(Request request) org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(wrapped); if (wrappedPrivKeyString == null) { request.setExtData(Request.RESULT, Integer.valueOf(4)); - logger.warn("NetkeyKeygenService: failed generating wrapped private key"); + logger.debug("NetkeyKeygenService: failed generating wrapped private key"); auditor.log(new SecurityDataExportEvent( agentId, ILogger.FAILURE, @@ -454,22 +484,23 @@ public boolean serviceRequest(Request request) PubKey)); return false; - } - request.setExtData("wrappedUserPrivate", wrappedPrivKeyString); + } else { + request.setExtData("wrappedUserPrivate", wrappedPrivKeyString); - auditor.log(new SecurityDataExportEvent( - agentId, - ILogger.SUCCESS, - auditSubjectID, - null, - null, - PubKey)); + auditor.log(new SecurityDataExportEvent( + agentId, + ILogger.SUCCESS, + auditSubjectID, + null, + null, + PubKey)); + } - iv_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(iv); + //iv_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(iv); request.setExtData("iv_s", iv_s); } catch (Exception e) { - logger.warn("NetkeyKeygenService: " + e.getMessage(), e); + logger.debug(e.toString()); request.setExtData(Request.RESULT, Integer.valueOf(4)); return false; } @@ -485,7 +516,7 @@ public boolean serviceRequest(Request request) // encKey OCTET_STRING, // } // - // logger.info("KRA encrypts internal private"); + // mKRA.log(ILogger.LL_INFO, "KRA encrypts internal private"); auditor.log(SecurityDataArchivalRequestEvent.createSuccessEvent( agentId, @@ -505,7 +536,6 @@ public boolean serviceRequest(Request request) // the IVs are the same. params.setPayloadEncryptionIV(params.getPayloadWrappingIV()); - logger.debug("NetKeyKeygenService: wrap params: " + params); privateKeyData = mStorageUnit.wrap((org.mozilla.jss.crypto.PrivateKey) privKey, params); } catch (Exception e) { @@ -555,8 +585,8 @@ public boolean serviceRequest(Request request) } } } catch (Exception e) { - logger.warn("NetkeyKeygenService: ASN1Util.getECCurveBytesByX509PublicKeyByte(): " + e.getMessage(), e); - logger.warn("NetkeyKeygenService: exception allowed. continue"); + logger.debug("NetkeyKeygenService: ASN1Util.getECCurveBytesByX509PublicKeyByte() throws exception: "+ e.toString()); + logger.debug("NetkeyKeygenService: exception allowed. continue"); } metaInfo.set(KeyRecordParser.OUT_KEY_EC_CURVE, @@ -596,7 +626,7 @@ public boolean serviceRequest(Request request) request.setExtData(Request.RESULT, Integer.valueOf(1)); } catch (Exception e) { - logger.warn("NetkeyKeygenService: " + e.getMessage(), e); + logger.debug(e.toString()); auditor.log(SecurityDataArchivalProcessedEvent.createFailureEvent( agentId, diff --git a/base/kra/src/main/java/com/netscape/kra/TokenKeyRecoveryService.java b/base/kra/src/main/java/com/netscape/kra/TokenKeyRecoveryService.java index 23370a675b7..0c3ffe737c3 100644 --- a/base/kra/src/main/java/com/netscape/kra/TokenKeyRecoveryService.java +++ b/base/kra/src/main/java/com/netscape/kra/TokenKeyRecoveryService.java @@ -27,8 +27,6 @@ import java.security.SecureRandom; import java.util.Hashtable; -import org.dogtagpki.server.kra.KRAEngine; -import org.dogtagpki.server.kra.KRAEngineConfig; import org.mozilla.jss.crypto.CryptoToken; import org.mozilla.jss.crypto.EncryptionAlgorithm; import org.mozilla.jss.crypto.IVParameterSpec; @@ -37,41 +35,49 @@ import org.mozilla.jss.crypto.PrivateKey; import org.mozilla.jss.crypto.PrivateKey.Type; import org.mozilla.jss.crypto.SymmetricKey; -import org.mozilla.jss.netscape.security.util.BigInt; -import org.mozilla.jss.netscape.security.util.Cert; -import org.mozilla.jss.netscape.security.util.DerInputStream; -import org.mozilla.jss.netscape.security.util.DerValue; -import org.mozilla.jss.netscape.security.util.WrappingParams; -import org.mozilla.jss.netscape.security.x509.X509Key; import org.mozilla.jss.pkcs11.PK11SymKey; import org.mozilla.jss.util.Base64OutputStream; +import com.netscape.cmscore.apps.CMS; import com.netscape.certsrv.base.EBaseException; +import org.dogtagpki.server.kra.KRAEngine; +import org.dogtagpki.server.kra.KRAEngineConfig; import com.netscape.certsrv.base.SessionContext; import com.netscape.certsrv.dbs.keydb.KeyId; import com.netscape.certsrv.kra.EKRAException; import com.netscape.certsrv.logging.ILogger; +import com.netscape.certsrv.logging.LogEvent; import com.netscape.certsrv.logging.event.SecurityDataRecoveryEvent; import com.netscape.certsrv.logging.event.SecurityDataRecoveryProcessedEvent; +import com.netscape.cmscore.request.Request; import com.netscape.certsrv.request.IService; import com.netscape.certsrv.request.RequestId; import com.netscape.certsrv.security.IStorageKeyUnit; -import com.netscape.cmscore.apps.CMS; +import com.netscape.cms.logging.Logger; +import com.netscape.cms.logging.SignedAuditLogger; import com.netscape.cmscore.dbs.KeyRecord; import com.netscape.cmscore.dbs.KeyRepository; import com.netscape.cmscore.logging.Auditor; -import com.netscape.cmscore.request.Request; import com.netscape.cmscore.security.JssSubsystem; import com.netscape.cmsutil.crypto.CryptoUtil; +import org.mozilla.jss.netscape.security.util.BigInt; +import org.mozilla.jss.netscape.security.util.Cert; +import org.mozilla.jss.netscape.security.util.DerInputStream; +import org.mozilla.jss.netscape.security.util.DerValue; +import org.mozilla.jss.netscape.security.util.WrappingParams; + +import org.mozilla.jss.netscape.security.x509.X509Key; + /** * A class represents recovery request processor. * * @author Christina Fu (cfu) + * @version $Revision$, $Date$ */ public class TokenKeyRecoveryService implements IService { - public static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TokenKeyRecoveryService.class); + public static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(NetkeyKeygenService.class); public static final String ATTR_NICKNAME = "nickname"; public static final String ATTR_OWNER_NAME = "ownerName"; @@ -89,16 +95,17 @@ public class TokenKeyRecoveryService implements IService { public static final String ATTR_USER_CERT = "cert"; public static final String ATTR_DELIVERY = "delivery"; - private KeyRecoveryAuthority mKRA; - private KeyRepository mStorage; + private KeyRecoveryAuthority mKRA = null; + private KeyRepository mStorage = null; private IStorageKeyUnit mStorageUnit = null; - private TransportKeyUnit mTransportUnit; + private TransportKeyUnit mTransportUnit = null; /** * Constructs request processor. */ public TokenKeyRecoveryService(KeyRecoveryAuthority kra) { mKRA = kra; + KRAEngine engine = KRAEngine.getInstance(); mStorage = engine.getKeyRepository(); mStorageUnit = mKRA.getStorageKeyUnit(); @@ -183,26 +190,25 @@ private static String base64Encode(byte[] bytes) throws IOException { * @return operation success or not * @exception EBaseException failed to serve */ - @Override public synchronized boolean serviceRequest(Request request) throws EBaseException { - + String auditSubjectID = null; String iv_s = ""; String method = "TokenKeyRecoveryService.serviceRequest: "; - logger.debug("KRA services token key recovery request"); - - KRAEngine engine = KRAEngine.getInstance(); - JssSubsystem jssSubsystem = engine.getJSSSubsystem(); - KRAEngineConfig config = null; + KRAEngine engine = KRAEngine.getInstance(); Boolean allowEncDecrypt_recovery = false; boolean useOAEPKeyWrap = false; + CryptoToken token = null; + + Auditor auditor = engine.getAuditor(); + try { config = engine.getConfig(); allowEncDecrypt_recovery = config.getBoolean("kra.allowEncDecrypt.recovery", false); - useOAEPKeyWrap = config.getUseOAEPKeyWrap(); + useOAEPKeyWrap = config.getBoolean("keyWrap.useOAEP",false); } catch (Exception e) { throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString())); } @@ -210,11 +216,18 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio byte[] wrapped_des_key; byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; + + int ivLength = EncryptionAlgorithm.AES_128_CBC.getIVLength(); + logger.debug(method + " cbc iv len: " + ivLength); + + byte iv_cbc[] = new byte[ivLength]; + try { + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); SecureRandom random = jssSubsystem.getRandomNumberGenerator(); random.nextBytes(iv); } catch (Exception e) { - logger.error("TokenKeyRecoveryService.serviceRequest: " + e.getMessage(), e); + logger.debug("TokenKeyRecoveryService.serviceRequest: " + e.toString()); throw new EBaseException(e); } @@ -232,7 +245,7 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio if (params == null) { // possibly we are in recovery mode - logger.warn("getVolatileRequest params null"); + logger.debug("getVolatileRequest params null"); // return true; } @@ -243,7 +256,15 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio String rCUID = request.getExtDataInString(Request.NETKEY_ATTR_CUID); String rUserid = request.getExtDataInString(Request.NETKEY_ATTR_USERID); String rWrappedDesKeyString = request.getExtDataInString(Request.NETKEY_ATTR_DRMTRANS_DES_KEY); + String rWrappedAesKeyString = request.getExtDataInString(Request.NETKEY_ATTR_DRMTRANS_AES_KEY); + String aesKeyWrapAlg = request.getExtDataInString(Request.NETKEY_ATTR_SSKEYGEN_AES_KEY_WRAP_ALG); + + if(aesKeyWrapAlg != null) { + logger.debug(method + " aesKeyWrapAlg: " + aesKeyWrapAlg); + } else { + logger.debug(method + " no aesKeyWrapAlg provided."); + } // the request record field delayLDAPCommit == "true" will cause // updateRequest() to delay actual write to ldap @@ -251,8 +272,6 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio // wrappedDesKey no longer needed. removing. request.setExtData(Request.NETKEY_ATTR_DRMTRANS_DES_KEY, ""); - Auditor auditor = engine.getAuditor(); - boolean useAesTransWrapped = false; byte[] wrapped_aes_key = null; @@ -263,17 +282,19 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio logger.debug(method + "TMS has sent trans wrapped aes key."); } - String auditSubjectID = rCUID + ":" + rUserid; + auditSubjectID = rCUID + ":" + rUserid; //logger.debug("TokenKeyRecoveryService: received DRM-trans-wrapped des key =" + rWrappedDesKeyString); logger.debug("TokenKeyRecoveryService: received DRM-trans-wrapped des key"); wrapped_des_key = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rWrappedDesKeyString); logger.debug("TokenKeyRecoveryService: wrapped_des_key specialDecoded"); + KeyWrapAlgorithm wrapAlg = KeyWrapAlgorithm.RSA; - if(useOAEPKeyWrap == true) { + if(useOAEPKeyWrap == true) { wrapAlg = KeyWrapAlgorithm.RSA_OAEP; } + //Instantiate both DES3 or AES wrapping params. One or the other will be ultimately used. WrappingParams wrapParams = new WrappingParams( SymmetricKey.DES3, KeyGenAlgorithm.DES3, 0, @@ -286,24 +307,25 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio wrapAlg, EncryptionAlgorithm.AES_128_CBC_PAD, KeyWrapAlgorithm.AES_KEY_WRAP_PAD,EncryptionUnit.IV, EncryptionUnit.IV); - //Attempt legacy DES, if DES key not present or AES key present , drop down to AES processing. - - + //Attempt legacy DES, if DES key not present or AES key present , drop down to AES processing. + if ((wrapped_des_key != null) && (wrapped_des_key.length > 0)) { + // unwrap the des key try { + logger.debug("TokenKeyRecoveryService: received DRM-trans-wrapped des key: length: " + wrapped_des_key.length); sk = (PK11SymKey) mTransportUnit.unwrap_sym(wrapped_des_key, wrapParams); logger.debug("TokenKeyRecoveryService: received des key"); } catch (Exception e) { - logger.debug("TokenKeyRecoveryService: no des key"); + logger.debug("TokenKeyRecoveryService: no des key: " + e); if(!useAesTransWrapped) { request.setExtData(Request.RESULT, Integer.valueOf(4)); return false; - } + } } } else { - logger.warn("TokenKeyRecoveryService: not receive des key"); + logger.debug("TokenKeyRecoveryService: not receive des key"); request.setExtData(Request.RESULT, Integer.valueOf(4)); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, @@ -313,12 +335,15 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio "TokenRecoveryService: Did not receive DES key", agentId)); - //Log the missing des key but we will use the aes key if present - if(!useAesTransWrapped) { - return false; - } + //Log the missing des key but we will use the aes key if present + if(!useAesTransWrapped) { + return false; + } + logger.debug("TokenKeyRecoveryService: no des key use aes key for scp03."); + } + //Now if we failed unwrapping the DES key directly to the token //Use the included trans wrapped AES key to do so. //We will fall back to AES wrapped key if present and DES key not present. @@ -334,19 +359,20 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio //Use aes session key to unwrap the DES3 key } catch (Exception e) { - logger.warn(method + " no AES session key: or DES kek key. " + e); + logger.debug(method + " no AES session key: or DES kek key. " + e); request.setExtData(Request.RESULT, Integer.valueOf(4)); return false; } - } + } // retrieve based on Certificate + token = mStorageUnit.getToken(); String cert_s = request.getExtDataInString(ATTR_USER_CERT); String keyid_s = request.getExtDataInString(Request.NETKEY_ATTR_KEYID); KeyId keyId = keyid_s != null ? new KeyId(keyid_s): null; /* have to have at least one */ if ((cert_s == null) && (keyid_s == null)) { - logger.warn("TokenKeyRecoveryService: not receive cert or keyid"); + logger.debug("TokenKeyRecoveryService: not receive cert or keyid"); request.setExtData(Request.RESULT, Integer.valueOf(3)); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, @@ -366,7 +392,7 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio try { x509cert = Cert.mapCert(cert); if (x509cert == null) { - logger.warn("cert mapping failed"); + logger.debug("cert mapping failed"); request.setExtData(Request.RESULT, Integer.valueOf(5)); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, @@ -378,7 +404,7 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio return false; } } catch (IOException e) { - logger.warn("TokenKeyRecoveryService: mapCert failed"); + logger.debug("TokenKeyRecoveryService: mapCert failed"); request.setExtData(Request.RESULT, Integer.valueOf(6)); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, @@ -398,25 +424,27 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio CryptoToken internalToken = CryptoManager.getInstance().getInternalKeyStorageToken(); */ - token = mStorageUnit.getToken(); + //CryptoToken token = mStorageUnit.getToken(); logger.debug("TokenKeyRecoveryService: got token slot:" + token.getName()); - IVParameterSpec algParam = new IVParameterSpec(iv); + IVParameterSpec desAlgParam = new IVParameterSpec(iv); + IVParameterSpec algParam = null; + IVParameterSpec aesCBCAlgParam = new IVParameterSpec(iv_cbc); KeyRecord keyRecord = null; logger.debug("KRA reading key record"); try { if (keyid != null) { logger.debug("TokenKeyRecoveryService: recover by keyid"); - keyRecord = mStorage.readKeyRecord(keyid); + keyRecord = (KeyRecord) mStorage.readKeyRecord(keyid); } else { logger.debug("TokenKeyRecoveryService: recover by cert"); - keyRecord = mStorage.readKeyRecord(cert); + keyRecord = (KeyRecord) mStorage.readKeyRecord(cert); } if (keyRecord != null) logger.debug("read key record"); else { - logger.warn("key record not found"); + logger.debug("key record not found"); request.setExtData(Request.RESULT, Integer.valueOf(8)); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, @@ -428,7 +456,6 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio return false; } } catch (Exception e) { - logger.warn("TokenKeyRecoveryService: " + e.getMessage(), e); request.setExtData(Request.RESULT, Integer.valueOf(9)); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, @@ -471,7 +498,8 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio CMS.getLogMessage("CMSCORE_KRA_PUBLIC_KEY_LEN"), agentId)); - throw new EKRAException(CMS.getUserMessage("CMS_KRA_PUBLIC_KEY_NOT_MATCHED")); + throw new EKRAException( + CMS.getUserMessage("CMS_KRA_PUBLIC_KEY_NOT_MATCHED")); } for (int i = 0; i < pubData.length; i++) { @@ -484,7 +512,8 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio keyId, CMS.getLogMessage("CMSCORE_KRA_PUBLIC_KEY_LEN"), agentId)); - throw new EKRAException(CMS.getUserMessage("CMS_KRA_PUBLIC_KEY_NOT_MATCHED")); + throw new EKRAException( + CMS.getUserMessage("CMS_KRA_PUBLIC_KEY_NOT_MATCHED")); } } } // else, searched by keyid, can't check @@ -498,13 +527,14 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio Type keyType = PrivateKey.RSA; byte wrapped[]; + if (encrypted) { // Unwrap the archived private key byte privateKeyData[] = null; privateKeyData = recoverKey(params, keyRecord); if (privateKeyData == null) { request.setExtData(Request.RESULT, Integer.valueOf(4)); - logger.warn("TokenKeyRecoveryService: failed getting private key"); + logger.debug("TokenKeyRecoveryService: failed getting private key"); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, ILogger.FAILURE, @@ -542,11 +572,14 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio CMS.getLogMessage("CMSCORE_KRA_PUBLIC_NOT_FOUND"), agentId)); + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); jssSubsystem.obscureBytes(privateKeyData); jssSubsystem.obscureBytes(p); - throw new EKRAException(CMS.getUserMessage("CMS_KRA_INVALID_PUBLIC_KEY")); + throw new EKRAException( + CMS.getUserMessage("CMS_KRA_INVALID_PUBLIC_KEY")); + } else { + logger.debug("TokenKeyRecoveryService: private key verified with public key"); } - logger.debug("TokenKeyRecoveryService: private key verified with public key"); //encrypt and put in private key wrapped = CryptoUtil.encryptUsingSymmetricKey( @@ -556,14 +589,14 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio EncryptionAlgorithm.DES3_CBC_PAD, algParam); + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); jssSubsystem.obscureBytes(privateKeyData); jssSubsystem.obscureBytes(p); - } else { //encrypted == false PrivateKey privKey = recoverKey(params, keyRecord, allowEncDecrypt_recovery); if (privKey == null) { request.setExtData(Request.RESULT, Integer.valueOf(4)); - logger.warn("TokenKeyRecoveryService: failed getting private key"); + logger.debug("TokenKeyRecoveryService: failed getting private key"); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, ILogger.FAILURE, @@ -576,15 +609,29 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio logger.debug("TokenKeyRecoveryService: about to wrap..."); - KeyWrapAlgorithm symWrapAlg = KeyWrapAlgorithm.DES3_CBC_PAD; - if(attemptAesKeyWrap == true) { - //Here we must use AES KWP because it's the only common AES key wrap to be supoprted on hsm, nss, and soon the coolkey applet. - //Should make this configurable at some point. - symWrapAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD_KWP; - algParam = null; + KeyWrapAlgorithm symWrapAlg = KeyWrapAlgorithm.DES3_CBC_PAD; + + if(useAesTransWrapped == true) { + //Here we recomment to use AES KWP because it's the only common AES key wrap to be supoprted on hsm, nss, and soon the coolkey applet. + //But now we are going to make it configurable to AES CBC based on interest in doing so. KWP is the one that is assured to work + //with the applet and nss / hsm envorinments. CBC can be chosen at the admin's discretion. + + if(aesKeyWrapAlg != null && "CBC".equalsIgnoreCase(aesKeyWrapAlg)) { + // We want CBC + logger.debug(method + " TPS has selected CBC for AES key wrap method."); + symWrapAlg = KeyWrapAlgorithm.AES_CBC_PAD; + + algParam = aesCBCAlgParam; + iv_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(iv_cbc); + + } else { + symWrapAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD_KWP; + algParam = null; + iv_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(iv); + } logger.debug(method + " attemptedAesKeyWrap = true "); } else { - symWrapAlg = KeyWrapAlgorithm.DES3_CBC_PAD; + algParam = desAlgParam; logger.debug(method + " attemptedAesKeyWrap = false "); } @@ -593,7 +640,7 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio sk, privKey, algParam, - KeyWrapAlgorithm.DES3_CBC_PAD); + symWrapAlg); iv_s = /*base64Encode(iv);*/org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(iv); request.setExtData("iv_s", iv_s); @@ -604,7 +651,7 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio if (wrappedPrivKeyString == null) { request.setExtData(Request.RESULT, Integer.valueOf(4)); - logger.warn("TokenKeyRecoveryService: failed generating wrapped private key"); + logger.debug("TokenKeyRecoveryService: failed generating wrapped private key"); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, ILogger.FAILURE, @@ -613,12 +660,13 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio "TokenKeyRecoveryService: failed generating wrapped private key", agentId)); return false; + } else { + logger.debug("TokenKeyRecoveryService: got private key data wrapped"); + request.setExtData("wrappedUserPrivate", + wrappedPrivKeyString); + request.setExtData(Request.RESULT, Integer.valueOf(1)); + logger.debug("TokenKeyRecoveryService: key for " + rCUID + ":" + rUserid + " recovered"); } - logger.debug("TokenKeyRecoveryService: got private key data wrapped"); - request.setExtData("wrappedUserPrivate", - wrappedPrivKeyString); - request.setExtData(Request.RESULT, Integer.valueOf(1)); - logger.debug("TokenKeyRecoveryService: key for " + rCUID + ":" + rUserid + " recovered"); //convert and put in the public key String PubKey = ""; @@ -640,7 +688,7 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio if (PubKey == null) { request.setExtData(Request.RESULT, Integer.valueOf(4)); - logger.warn("TokenKeyRecoveryService: failed getting publickey encoded"); + logger.debug("TokenKeyRecoveryService: failed getting publickey encoded"); auditor.log(new SecurityDataRecoveryProcessedEvent( auditSubjectID, ILogger.FAILURE, @@ -649,10 +697,11 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio "TokenKeyRecoveryService: failed getting publickey encoded", agentId)); return false; + } else { + //logger.debug("TokenKeyRecoveryService: got publicKeyData b64 = " + + // PubKey); + logger.debug("TokenKeyRecoveryService: got publicKeyData"); } - //logger.debug("TokenKeyRecoveryService: got publicKeyData b64 = " + - // PubKey); - logger.debug("TokenKeyRecoveryService: got publicKeyData"); request.setExtData("public_key", PubKey); auditor.log(new SecurityDataRecoveryProcessedEvent( @@ -665,7 +714,7 @@ public synchronized boolean serviceRequest(Request request) throws EBaseExceptio return true; } catch (Exception e) { - logger.warn("TokenKeyRecoveryService: " + e.getMessage(), e); + logger.debug(e.toString()); request.setExtData(Request.RESULT, Integer.valueOf(4)); } @@ -697,20 +746,20 @@ public boolean verifyKeyPair(byte publicKeyData[], byte privateKeyData[]) { BigInt privateKeyExponent = privateKeyDerIn.getInteger(); if (!publicKeyModulus.equals(privateKeyModulus)) { - logger.warn("verifyKeyPair modulus mismatch publicKeyModulus=" + logger.debug("verifyKeyPair modulus mismatch publicKeyModulus=" + publicKeyModulus + " privateKeyModulus=" + privateKeyModulus); return false; } if (!publicKeyExponent.equals(privateKeyExponent)) { - logger.warn("verifyKeyPair exponent mismatch publicKeyExponent=" + logger.debug("verifyKeyPair exponent mismatch publicKeyExponent=" + publicKeyExponent + " privateKeyExponent=" + privateKeyExponent); return false; } return true; } catch (Exception e) { - logger.warn("verifyKeyPair error " + e.getMessage(), e); + logger.debug("verifyKeyPair error " + e); return false; } } @@ -721,9 +770,9 @@ public boolean verifyKeyPair(byte publicKeyData[], byte privateKeyData[]) { */ public synchronized PrivateKey recoverKey(Hashtable request, KeyRecord keyRecord, boolean allowEncDecrypt_archival) throws EBaseException { - logger.debug("TokenKeyRecoveryService: recoverKey() - with allowEncDecrypt_archival being false"); + logger.debug( "TokenKeyRecoveryService: recoverKey() - with allowEncDecrypt_archival being false"); if (allowEncDecrypt_archival) { - logger.error( "TokenKeyRecoveryService: recoverKey() - allowEncDecrypt_archival needs to be false for this call"); + logger.debug( "TokenKeyRecoveryService: recoverKey() - allowEncDecrypt_archival needs to be false for this call"); throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "recoverKey, allowEncDecrypt_archival needs to be false for this call")); } @@ -732,7 +781,7 @@ public synchronized PrivateKey recoverKey(Hashtable request, Key try { pubkey = X509Key.parsePublicKey (new DerValue(keyRecord.getPublicKeyData())); } catch (Exception e) { - logger.error("TokenKeyRecoverService: after parsePublicKey: " + e.getMessage(), e); + logger.debug("TokenKeyRecoverService: after parsePublicKey:"+e.toString()); throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "public key parsing failure")); } @@ -744,16 +793,16 @@ public synchronized PrivateKey recoverKey(Hashtable request, Key true, keyRecord.getWrappingParams(mStorageUnit.getOldWrappingParams())); } catch (Exception e) { - logger.error("TokenKeyRecoveryService: recovery failure: " + e.getMessage(), e); + logger.debug("TokenKeyRecoveryService: recoverKey() - recovery failure"); throw new EKRAException( CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "private key recovery/unwrapping failure"), e); } - logger.debug("TokenKeyRecoveryService: recoverKey() - recovery completed, returning privKey"); + logger.debug( "TokenKeyRecoveryService: recoverKey() - recovery completed, returning privKey"); return privKey; } catch (Exception e) { - logger.error("TokenKeyRecoverService: failed with allowEncDecrypt_recovery=false: " + e.getMessage(), e); + logger.debug("TokenKeyRecoverService: recoverKey() failed with allowEncDecrypt_recovery=false:"+e.toString()); throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "Exception:"+e.toString())); } } @@ -762,7 +811,7 @@ public synchronized PrivateKey recoverKey(Hashtable request, Key */ public synchronized byte[] recoverKey(Hashtable request, KeyRecord keyRecord) throws EBaseException { - logger.debug("TokenKeyRecoveryService: recoverKey() - with allowEncDecrypt_archival being true"); + logger.debug( "TokenKeyRecoveryService: recoverKey() - with allowEncDecrypt_archival being true"); /* Credential creds[] = (Credential[]) request.get(ATTR_AGENT_CREDENTIALS); @@ -776,7 +825,7 @@ public synchronized byte[] recoverKey(Hashtable request, KeyReco /* mStorageUnit.logout();*/ } catch (Exception e){ logger.error(CMS.getLogMessage("CMSCORE_KRA_PRIVATE_KEY_NOT_FOUND"), e); - throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "no private key"), e); + throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1", "no private key")); } } } diff --git a/base/server/src/main/java/com/netscape/cmscore/apps/CMSEngine.java b/base/server/src/main/java/com/netscape/cmscore/apps/CMSEngine.java index 9e6d438d139..3417ec38a98 100644 --- a/base/server/src/main/java/com/netscape/cmscore/apps/CMSEngine.java +++ b/base/server/src/main/java/com/netscape/cmscore/apps/CMSEngine.java @@ -875,7 +875,6 @@ public void initSecurityDomain() throws Exception { public void init() throws Exception { logger.info("Initializing " + name + " subsystem"); - loadSubsystems(); initSubsystems(); @@ -978,7 +977,6 @@ protected void loadSubsystems() throws Exception { Subsystem subsystem = (Subsystem) Class.forName(className).getDeclaredConstructor().newInstance(); subsystem.setCMSEngine(this); - subsystems.put(id, subsystem); subsystemInfos.put(id, subsystemInfoConfig); } diff --git a/base/server/src/main/java/com/netscape/cmscore/request/Request.java b/base/server/src/main/java/com/netscape/cmscore/request/Request.java index 5bd4fc5dc76..92e52ddf89f 100644 --- a/base/server/src/main/java/com/netscape/cmscore/request/Request.java +++ b/base/server/src/main/java/com/netscape/cmscore/request/Request.java @@ -180,6 +180,8 @@ public class Request { public static final String NETKEY_ATTR_DRMTRANS_DES_KEY = "drm_trans_desKey"; public static final String NETKEY_ATTR_ARCHIVE_FLAG = "archive"; public static final String NETKEY_ATTR_DRMTRANS_AES_KEY = "drm_trans_aesKey"; + public static final String NETKEY_ATTR_SSKEYGEN_AES_KEY_WRAP_ALG = "drm_aes_wrapAlg"; + public static final String NETKEY_ATTR_SERVERSIDE_MUSCLE_FLAG = "serverSideMuscle"; public static final String NETKEY_ATTR_ENC_PRIVKEY_FLAG = "encryptPrivKey"; diff --git a/base/server/src/main/java/org/dogtagpki/server/connector/IRemoteRequest.java b/base/server/src/main/java/org/dogtagpki/server/connector/IRemoteRequest.java index d1bc0d51895..6d36aa566f3 100644 --- a/base/server/src/main/java/org/dogtagpki/server/connector/IRemoteRequest.java +++ b/base/server/src/main/java/org/dogtagpki/server/connector/IRemoteRequest.java @@ -48,6 +48,7 @@ public interface IRemoteRequest { public static final String TOKEN_NEW_KEYINFO = "newKeyInfo"; public static final String TOKEN_DATA = "data"; public static final String WRAPPED_DEK_SESSION_KEY = "wrappedDekKey"; + public static final String TOKEN_OLD_KEYSET = "oldKeySet"; // ** G&D 256 Key Rollover Support ** // TKS response params /* computeSessionKey responses */ @@ -61,6 +62,8 @@ public interface IRemoteRequest { public static final String TKS_RESPONSE_DRM_Trans_DesKey = "drm_trans_desKey"; public static final String TKS_RESPONSE_DRM_Trans_AesKey = "drm_trans_aesKey"; public static final String TKS_RESPONSE_KeyCheck = "keycheck"; + public static final String TKS_RESPONSE_KeyCheck_Des = "keycheck_des"; // Applet and Alg Selection by Token Range Support + public static final String TKS_RESPONSE_HostCryptogram = "hostCryptogram"; /* createKeySetData response */ @@ -108,6 +111,7 @@ public interface IRemoteRequest { public static final String KRA_UserId = "userid"; public static final String KRA_Trans_DesKey = "drm_trans_desKey"; public static final String KRA_Trans_AesKey = "drm_trans_aesKey"; + public static final String KRA_Aes_Wrap_Alg = "drm_aes_wrapAlg"; public static final String KRA_KEYGEN_Archive = "archive"; public static final String KRA_KEYGEN_KeyType = "keytype"; diff --git a/base/tks/shared/conf/CS.cfg b/base/tks/shared/conf/CS.cfg index 31091edf6a0..3f96dfce243 100644 --- a/base/tks/shared/conf/CS.cfg +++ b/base/tks/shared/conf/CS.cfg @@ -151,7 +151,6 @@ selftests._005=## tks.cert.list = selftests._006=## tks.cert..nickname selftests._007=## tks.cert..certusage selftests._008=## -selftests.container.instance.TKSKnownSessionKey=com.netscape.cms.selftests.tks.TKSKnownSessionKey selftests.container.instance.SystemCertsVerification=com.netscape.cms.selftests.common.SystemCertsVerification selftests.container.logger.bufferSize=512 selftests.container.logger.class=com.netscape.cms.logging.RollingLogFile diff --git a/base/tks/src/main/java/org/dogtagpki/server/tks/rest/base/TPSConnectorProcessor.java b/base/tks/src/main/java/org/dogtagpki/server/tks/rest/base/TPSConnectorProcessor.java index 9afc5f54d67..836fd55fb1b 100644 --- a/base/tks/src/main/java/org/dogtagpki/server/tks/rest/base/TPSConnectorProcessor.java +++ b/base/tks/src/main/java/org/dogtagpki/server/tks/rest/base/TPSConnectorProcessor.java @@ -249,7 +249,7 @@ public KeyData getSharedSecret(Principal principal, String id) { return null; } - List listWrappedKeys = CryptoUtil.exportSharedSecret(nickname, certs[certs.length -1], tempKey, getUseOAEPKeyWrap()); + List listWrappedKeys = CryptoUtil.exportSharedSecretWithAES(nickname, certs[certs.length -1], tempKey,getUseOAEPKeyWrap()); byte[] wrappedSessionKey = listWrappedKeys.get(0); byte[] wrappedSharedSecret = listWrappedKeys.get(1); @@ -507,4 +507,4 @@ private boolean getUseOAEPKeyWrap() throws EBaseException { logger.debug("TPSConnectorProcessor.createSharedSecret.getUseOAEPKeyWrap: {}", useOAEPKeyWrap); return useOAEPKeyWrap; } -} \ No newline at end of file +} diff --git a/base/tks/src/main/java/org/dogtagpki/server/tks/rest/v1/TPSConnectorService.java b/base/tks/src/main/java/org/dogtagpki/server/tks/rest/v1/TPSConnectorService.java index 6aa22954e8b..a8c9226c22f 100644 --- a/base/tks/src/main/java/org/dogtagpki/server/tks/rest/v1/TPSConnectorService.java +++ b/base/tks/src/main/java/org/dogtagpki/server/tks/rest/v1/TPSConnectorService.java @@ -44,6 +44,7 @@ public class TPSConnectorService extends PKIService implements TPSConnectorResou TKSEngineConfig cs = engine.getConfig(); public static final int AES_SESS_KEYSIZE = 128; + public static final int AES_SESS_KEYSIZE_256 = 256; public UGSubsystem userGroupManager = engine.getUGSubsystem(); @Override @@ -302,14 +303,14 @@ public Response createSharedSecret(String id) { throw new BadRequestException("Shared secret already exists"); } - CryptoUtil.createSharedSecret(nickname,KeyGenAlgorithm.AES,AES_SESS_KEYSIZE); + CryptoUtil.createSharedSecret(nickname,KeyGenAlgorithm.AES,AES_SESS_KEYSIZE_256); TPSConnectorConfig tpsConfig = cs.getTPSConnectorConfig(id); tpsConfig.setNickname(nickname); cs.commit(true); //Create aes session sym key to wrap the shared secret. - SymmetricKey tempKey = CryptoUtil.createAESSessionKeyOnInternal(AES_SESS_KEYSIZE); + SymmetricKey tempKey = CryptoUtil.createAESSessionKeyOnInternal(AES_SESS_KEYSIZE_256); if (tempKey == null) { return createNoContentResponse(); @@ -317,7 +318,7 @@ public Response createSharedSecret(String id) { logger.debug("TPSConnectorService.createSharedSecret. about to export shared secret : " + nickname + " certs.length " + certs.length); logger.debug("TPSConnectorService.createSharedSecert cert: " + certs[certs.length -1]); - List listWrappedKeys = CryptoUtil.exportSharedSecret(nickname, certs[certs.length -1], tempKey, getUseOAEPKeyWrap()); + List listWrappedKeys = CryptoUtil.exportSharedSecretWithAES(nickname, certs[certs.length -1], tempKey,getUseOAEPKeyWrap()); logger.debug("TPSConnectorService.createSharedSecret. done exporting shared secret : " + nickname); byte[] wrappedSessionKey = listWrappedKeys.get(0); diff --git a/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/NistSP800_108KDF.java b/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/NistSP800_108KDF.java index 9dbcd06d17b..5a9f0d908be 100644 --- a/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/NistSP800_108KDF.java +++ b/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/NistSP800_108KDF.java @@ -201,6 +201,10 @@ public byte[] kdf_AES_CMAC_SCP03(SymmetricKey masterKey, byte[] context, byte kd for (int i = 1; i <= n; i++) { try { + // Need to flush and reset buffer before using it + input.reset(); + input.flush(); + input.write(headerBytes); input.write((byte) i); input.write(context); @@ -416,7 +420,17 @@ public static byte[] computeAES_CMAC(SymmetricKey aesKey, byte[] input) throws E Cipher encryptor = null; try { - encryptor = token.getCipherContext(EncryptionAlgorithm.AES_128_CBC); + // Base size on key length + if (aesKey.getLength() == AES_CMAC_BLOCK_SIZE) + { + logger.debug(method + " encryptor context set to AES_128_CBC"); + encryptor = token.getCipherContext(EncryptionAlgorithm.AES_128_CBC); + } + else + { + logger.debug(method + " encryptor context set to AES_256_CBC"); + encryptor = token.getCipherContext(EncryptionAlgorithm.AES_256_CBC); + } encryptor.initEncrypt(aesKey, new IVParameterSpec(iv)); k0 = encryptor.doFinal(k0); diff --git a/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/SecureChannelProtocol.java b/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/SecureChannelProtocol.java index 5bcdd4e6108..2a1f3215032 100644 --- a/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/SecureChannelProtocol.java +++ b/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/SecureChannelProtocol.java @@ -10,9 +10,10 @@ import java.util.Map; import org.dogtagpki.server.tks.TKSEngine; +import org.dogtagpki.server.tks.TKSEngineConfig; import org.mozilla.jss.CryptoManager; -import org.mozilla.jss.NoSuchTokenException; import org.mozilla.jss.NotInitializedException; +import org.mozilla.jss.NoSuchTokenException; import org.mozilla.jss.crypto.Cipher; import org.mozilla.jss.crypto.CryptoToken; import org.mozilla.jss.crypto.EncryptionAlgorithm; @@ -25,20 +26,21 @@ import org.mozilla.jss.crypto.SymmetricKey.NotExtractableException; import org.mozilla.jss.crypto.SymmetricKeyDeriver; import org.mozilla.jss.crypto.TokenException; -import org.mozilla.jss.pkcs11.PKCS11Constants; import com.netscape.certsrv.base.EBaseException; import com.netscape.cmscore.security.JssSubsystem; import com.netscape.cmsutil.crypto.CryptoUtil; +import org.mozilla.jss.pkcs11.PKCS11Constants; + public class SecureChannelProtocol { public static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SecureChannelProtocol.class); - static String sharedSecretKeyName = null; static String masterKeyPrefix = null; static final int DEF_AES_KEYLENGTH = 16; + static final int DEF_AES_256_KEYLENGTH = 32; static final int KEYLENGTH = 16; static final int PREFIXLENGHT = 128; static final int DES2_LENGTH = 16; @@ -226,9 +228,6 @@ public SymmetricKey computeSessionKey_SCP03(String selectedToken, logger.debug(method + " entering. nickname: " + keyNickName + " selectedToken: " + selectedToken); - TKSEngine engine = TKSEngine.getInstance(); - JssSubsystem jssSubsystem = engine.getJSSSubsystem(); - CryptoManager cm = null; CryptoToken token = null; CryptoToken internalToken = null; @@ -237,17 +236,18 @@ public SymmetricKey computeSessionKey_SCP03(String selectedToken, token = returnTokenByName(selectedToken, cm); internalToken = returnTokenByName("internal", cm); } catch (NotInitializedException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } catch (NoSuchTokenException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } sharedSecretKeyName = SecureChannelProtocol.getSharedSecretKeyName(transportKeyName); + transportKey = getSharedSecretKey(internalToken); - + //concat host and card challenge: byte[] context = null; @@ -277,7 +277,7 @@ public SymmetricKey computeSessionKey_SCP03(String selectedToken, if (keyType.equalsIgnoreCase(SecureChannelProtocol.macType)) { constant = mac_constant; - constant_gpkmc = enc_constant_gpkmc; + constant_gpkmc = mac_constant_gpkmc; } if (keyType.equalsIgnoreCase(SecureChannelProtocol.rmacType)) { @@ -347,22 +347,27 @@ public SymmetricKey computeSessionKey_SCP03(String selectedToken, divKey = nistKdf.diversifyAESKey(devSymKey, xCUID, constant_gpkmc, token); } } else { - throw new EBaseException(method + " Invalid devolper key type. Does not support diversification: "+ devKeyType); + throw new EBaseException(method + " Invalid developer key type. Does not support diversification: "+ devKeyType); } } + //IN scp03, the kek key IS the card key if (constant == 0 /* kek key */) { sessionKey = divKey; } else { // session keys will become AES if (noDerive) { +logger.debug("session key = divKey"); sessionKey = divKey; } else { - byte[] finalKeyBytes = nistKdf.kdf_AES_CMAC_SCP03(divKey, context, constant, 16); + // Use length of divKey for AES CMAC + logger.debug(method + "Call to nistKdf.kdf_AES_CMAC_SCP03 divKey length = " + divKey.getLength()); + byte[] finalKeyBytes = nistKdf.kdf_AES_CMAC_SCP03(divKey, context, constant, divKey.getLength()); sessionKey = unwrapAESSymKeyOnToken(token, finalKeyBytes, false); - jssSubsystem.obscureBytes(finalKeyBytes); + TKSEngine engine = TKSEngine.getInstance(); + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); //The final session key is AES. } @@ -416,16 +421,17 @@ else if (params.isDiversEmv()) { sessionKey = divKey; } else { - byte[] finalKeyBytes = nistKdf.kdf_AES_CMAC_SCP03(divKey, context, constant, 16); + // Use length of divKey for AES CMAC + byte[] finalKeyBytes = nistKdf.kdf_AES_CMAC_SCP03(divKey, context, constant, divKey.getLength()); sessionKey = unwrapAESSymKeyOnToken(token, finalKeyBytes, false); + TKSEngine engine = TKSEngine.getInstance(); + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); jssSubsystem.obscureBytes(finalKeyBytes); } } } - //SecureChannelProtocol.debugByteArray(sessionKey.getEncoded(), keyType + " : session key"); - return sessionKey; } @@ -501,11 +507,11 @@ public SymmetricKey computeSessionKey_SCP01(String keyType, token = returnTokenByName(selectedToken, cm); internalToken = returnTokenByName(CryptoUtil.INTERNAL_TOKEN_NAME, cm); } catch (NotInitializedException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } catch (NoSuchTokenException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } @@ -526,7 +532,7 @@ public SymmetricKey computeSessionKey_SCP01(String keyType, byte[] context = null; - if ((nistSP800_108KdfUseCuidAsKdd == true) && + if (nistSP800_108KdfUseCuidAsKdd == true && NistSP800_108KDF.useThisKDF(nistSP800_108KdfOnKeyVersion, keyInfo[0])) { context = xCUID; } else { @@ -570,7 +576,7 @@ public SymmetricKey computeSessionKey_SCP01(String keyType, try { keys = nistKDF.computeCardKeys(masterKey, context, token); } catch (EBaseException e) { - logger.error(method + "Can't compute card keys! " + e.getMessage(), e); + logger.debug(method + "Can't compute card keys! " + e); throw e; } @@ -638,7 +644,7 @@ private SymmetricKey deriveKey_SCP01(CryptoToken token, SymmetricKey cardKey, by } } catch (TokenException | InvalidKeyException | EBaseException e) { - logger.error(method + "Unable to derive the key with the proper mechanism! " + e.getMessage(), e); + logger.debug(method + "Unable to derive the key with the proper mechanism!"); throw new EBaseException(e); } @@ -661,11 +667,11 @@ public SymmetricKey getSharedSecretKey(CryptoToken token) throws EBaseException internalToken = returnTokenByName(CryptoUtil.INTERNAL_TOKEN_NAME, cm); finalToken = internalToken; } catch (NotInitializedException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } catch (NoSuchTokenException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } } @@ -690,7 +696,7 @@ private String getKeyName(byte[] keyVersion) { return null; } - //SecureChannelProtocol.debugByteArray(keyVersion, "keyVersion array:"); +// SecureChannelProtocol.debugByteArray(keyVersion, "keyVersion array:"); keyName = "#" + String.format("%02X", keyVersion[0]) + "#" + String.format("%02X", keyVersion[1]); logger.debug(method + " returning: " + keyName); @@ -732,6 +738,7 @@ public SymmetricKey returnDeveloperSymKey(CryptoToken token, String keyType, Str String method = "SecureChannelProtocol.returnDeveloperSymKey:"; + logger.debug(method + "keyAlg: " + keyAlg); boolean isAES = false; String finalAlg = null; if(keyAlg == null) { @@ -784,13 +791,14 @@ public SymmetricKey returnDeveloperSymKey(CryptoToken token, String keyType, Str System.arraycopy(inputKeyArray, 0, des3InputKey, 0, DES3_LENGTH); } - //SecureChannelProtocol.debugByteArray(des3InputKey, "Developer key to import: " + keyType + ": "); +// SecureChannelProtocol.debugByteArray(des3InputKey, "Developer key to import: " + keyType + ": "); devKey = unwrapSymKeyOnToken(token, des3InputKey, true); } else { - if(inputLen == DEF_AES_KEYLENGTH) { // support 128 bits for now + // Allow 256 bit length + if (inputLen == DEF_AES_KEYLENGTH || inputLen == DEF_AES_256_KEYLENGTH) { // support 128 and 256 bits devKey = unwrapAESSymKeyOnToken(token, inputKeyArray, true); } } @@ -804,6 +812,7 @@ public SymmetricKey returnDeveloperSymKey(CryptoToken token, String keyType, Str //Takes raw des key 16 bytes, such as developer key and returns an AES key of the same size //Supports 128 bits for now + //07-08-2022, Updated to work with both 128 and 256 bits public SymmetricKey unwrapAESSymKeyOnToken(CryptoToken token, byte[] inputKeyArray, boolean isPerm) throws EBaseException { @@ -820,10 +829,10 @@ public SymmetricKey unwrapAESSymKeyOnToken(CryptoToken token, byte[] inputKeyArr } byte[] finalInputKeyArray = inputKeyArray; - if(inputKeyArray.length > 16) { - finalInputKeyArray = new byte[16]; - System.arraycopy(inputKeyArray, 0, finalInputKeyArray, 0, 16);; + if(inputKeyArray.length > 32) { + finalInputKeyArray = new byte[32]; + System.arraycopy(inputKeyArray, 0, finalInputKeyArray, 0, 32); } KeyGenerator kg; @@ -839,14 +848,23 @@ public SymmetricKey unwrapAESSymKeyOnToken(CryptoToken token, byte[] inputKeyArr kg.setKeyUsages(usages); kg.temporaryKeys(true); - kg.initialize(128); + // Handle 128 and 256 initialization sizes + kg.initialize(finalInputKeyArray.length*EIGHT_BYTES); SymmetricKey tempKey = kg.generate(); - //unwrap the test aes keys onto the token - - Cipher encryptor = token.getCipherContext(EncryptionAlgorithm.AES_128_CBC); + // Use EncryptionAlgorithm based on key size + Cipher encryptor; + if (tempKey.getStrength() == AES_128_BITS) + { + encryptor = token.getCipherContext(EncryptionAlgorithm.AES_128_CBC); + } + else + { + encryptor = token.getCipherContext(EncryptionAlgorithm.AES_256_CBC); + } + + int ivLength = 16; - int ivLength = EncryptionAlgorithm.AES_128_CBC.getIVLength(); byte[] iv = null; if (ivLength > 0) { @@ -854,16 +872,18 @@ public SymmetricKey unwrapAESSymKeyOnToken(CryptoToken token, byte[] inputKeyArr } encryptor.initEncrypt(tempKey, new IVParameterSpec(iv)); + logger.debug(method + " Did encryptor.initEncrypt successfully..."); byte[] wrappedKey = encryptor.doFinal(finalInputKeyArray); KeyWrapper keyWrap = token.getKeyWrapper(KeyWrapAlgorithm.AES_CBC); keyWrap.initUnwrap(tempKey, new IVParameterSpec(iv)); if(isPerm) - finalAESKey = keyWrap.unwrapSymmetricPerm(wrappedKey, SymmetricKey.AES, AES_128_BYTES); + // Use length of key for finalAESKey + finalAESKey = keyWrap.unwrapSymmetricPerm(wrappedKey, SymmetricKey.AES, wrappedKey.length); else - finalAESKey = keyWrap.unwrapSymmetric(wrappedKey, SymmetricKey.AES, AES_128_BYTES); - + // Use length of key for finalAESKey + finalAESKey = keyWrap.unwrapSymmetric(wrappedKey, SymmetricKey.AES, wrappedKey.length); } catch (Exception e) { throw new EBaseException(method + " Can't unwrap key onto token!"); @@ -890,9 +910,6 @@ public SymmetricKey unwrapAESSymKeyOnToken(CryptoToken token, SymmetricKey keyTo throw new EBaseException(method + " Invalid key size!"); } - TKSEngine engine = TKSEngine.getInstance(); - JssSubsystem jssSubsystem = engine.getJSSSubsystem(); - KeyGenerator kg; SymmetricKey finalAESKey; try { @@ -909,7 +926,6 @@ public SymmetricKey unwrapAESSymKeyOnToken(CryptoToken token, SymmetricKey keyTo kg.initialize(128); SymmetricKey tempKey = kg.generate(); - int ivLength = EncryptionAlgorithm.AES_128_CBC.getIVLength(); byte[] iv = null; @@ -933,6 +949,7 @@ public SymmetricKey unwrapAESSymKeyOnToken(CryptoToken token, SymmetricKey keyTo } KeyWrapper keyWrap = token.getKeyWrapper(KeyWrapAlgorithm.AES_CBC); + keyWrap.initWrap(tempKey, new IVParameterSpec(iv)); byte[] wrappedKey = keyWrap.wrap(finalKeyToWrap); @@ -942,11 +959,10 @@ public SymmetricKey unwrapAESSymKeyOnToken(CryptoToken token, SymmetricKey keyTo keyUnWrap.initUnwrap(tempKey, new IVParameterSpec(iv)); finalAESKey = keyUnWrap.unwrapSymmetric(wrappedKey, SymmetricKey.AES, 16); + TKSEngine engine = TKSEngine.getInstance(); + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); jssSubsystem.obscureBytes(wrappedKey); - //byte[] finalKeyBytes = finalAESKey.getKeyData(); - //displayByteArray(finalKeyBytes, false); - } catch (Exception e) { throw new EBaseException(method + " Can't unwrap key onto token!"); } @@ -969,14 +985,25 @@ public SymmetricKey unwrapSymKeyOnToken(CryptoToken token, SymmetricKey unwrappi throw new EBaseException(method + "Invalid input!"); } - if (inputKeyArray == null || (inputKeyArray.length != DES3_LENGTH && inputKeyArray.length != DES2_LENGTH)) { + // Allow AES-256 + if (inputKeyArray == null || (inputKeyArray.length != DES3_LENGTH && inputKeyArray.length != DES2_LENGTH + && inputKeyArray.length != DEF_AES_256_KEYLENGTH)) { throw new EBaseException(method + "No raw array to use to create key!"); } if (unwrappingKey == null) { try { - KeyGenerator kg = token.getKeyGenerator(KeyGenAlgorithm.DES3); - + // Select algorithm based on key size + KeyGenerator kg; + if (inputKeyArray.length == DES3_LENGTH || inputKeyArray.length == DES2_LENGTH) + { + kg = token.getKeyGenerator(KeyGenAlgorithm.DES3); + } + else + { + kg = token.getKeyGenerator(KeyGenAlgorithm.AES); + } + SymmetricKey.Usage usages[] = new SymmetricKey.Usage[4]; usages[0] = SymmetricKey.Usage.WRAP; usages[1] = SymmetricKey.Usage.UNWRAP; @@ -1010,19 +1037,21 @@ public SymmetricKey unwrapSymKeyOnToken(CryptoToken token, SymmetricKey unwrappi } try { - EncryptionAlgorithm encAlg = EncryptionAlgorithm.DES3_ECB; - KeyWrapAlgorithm wrapAlg = KeyWrapAlgorithm.DES3_ECB; - - IVParameterSpec iv = null; - if(encUnwrapKey.getType() == SymmetricKey.Type.AES) { - encAlg = EncryptionAlgorithm.AES_128_CBC_PAD; - wrapAlg = KeyWrapAlgorithm.AES_CBC_PAD; - iv = new IVParameterSpec(new byte[encAlg.getIVLength()]); + //Differentiate between DES3, DES and AES + if (finalKeyType == SymmetricKey.Type.DES3 || finalKeyType == SymmetricKey.Type.DES) + { + encryptor = token.getCipherContext(EncryptionAlgorithm.DES3_ECB); + } + else if (finalKeyType == SymmetricKey.Type.AES && inputKeyArray.length == DEF_AES_KEYLENGTH) + { + encryptor = token.getCipherContext(EncryptionAlgorithm.AES_128_CBC); + } + else + { + encryptor = token.getCipherContext(EncryptionAlgorithm.AES_256_CBC); } - encryptor = token.getCipherContext(encAlg); - - encryptor.initEncrypt(encUnwrapKey,iv); + encryptor.initEncrypt(encUnwrapKey); if (finalKeyArray != null) { if(finalKeyType == SymmetricKey.Type.DES3 || finalKeyType == SymmetricKey.Type.DES) @@ -1036,12 +1065,22 @@ public SymmetricKey unwrapSymKeyOnToken(CryptoToken token, SymmetricKey unwrappi wrappedKey = encryptor.doFinal(inputKeyArray); } - logger.debug(method + " done enrypting data"); + logger.debug(method + " done encrypting data"); // SecureChannelProtocol.debugByteArray(wrappedKey, " encrypted key"); - KeyWrapper keyWrap = token.getKeyWrapper(wrapAlg); - keyWrap.initUnwrap(encUnwrapKey, iv); + //Differentiate between DES3, DES and AES + KeyWrapper keyWrap = null; + if(finalKeyType == SymmetricKey.Type.DES3 || finalKeyType == SymmetricKey.Type.DES) + { + keyWrap = token.getKeyWrapper(KeyWrapAlgorithm.DES3_ECB); + } + else + { + keyWrap = token.getKeyWrapper(KeyWrapAlgorithm.AES_CBC); + } + + keyWrap.initUnwrap(encUnwrapKey, null); if (isPerm == true) { unwrapped = keyWrap.unwrapSymmetricPerm(wrappedKey, @@ -1051,7 +1090,7 @@ public SymmetricKey unwrapSymKeyOnToken(CryptoToken token, SymmetricKey unwrappi } } catch (Exception e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } finally { if (finalKeyArray != null) { @@ -1059,7 +1098,7 @@ public SymmetricKey unwrapSymKeyOnToken(CryptoToken token, SymmetricKey unwrappi } } - //logger.debug(method + "Returning symkey: " + unwrapped); + //logger.debug(method + "Returning symkey: length = " + unwrapped.getLength()); logger.debug(method + "Returning symkey..."); return unwrapped; @@ -1084,13 +1123,13 @@ public SymmetricKey unwrapWrappedSymKeyOnToken(CryptoToken token, SymmetricKey u } if(keyType == SymmetricKey.Type.AES) { - if(inputKeyArray.length != DEF_AES_KEYLENGTH) - throw new EBaseException(method + "Invalid length of raw input array."); + if(inputKeyArray.length != DEF_AES_KEYLENGTH && inputKeyArray.length != DEF_AES_256_KEYLENGTH) + throw new EBaseException(method + "Invalid length of raw AES input array."); } else if(keyType == SymmetricKey.Type.DES || keyType == SymmetricKey.Type.DES3) { if(inputKeyArray.length != DES3_LENGTH && inputKeyArray.length != DES2_LENGTH) - throw new EBaseException(method + "Invalid length of raw input array."); + throw new EBaseException(method + "Invalid length of raw DES input array."); } try { @@ -1098,7 +1137,8 @@ else if(keyType == SymmetricKey.Type.DES || if(unwrappingKey.getType() == SymmetricKey.Type.AES) { - IVParameterSpec iv = new IVParameterSpec(new byte[EncryptionAlgorithm.AES_128_CBC.getIVLength()]); + // Set iv based on key length + IVParameterSpec iv = new IVParameterSpec(new byte[unwrappingKey.getLength()]); keyWrap = token.getKeyWrapper(KeyWrapAlgorithm.AES_CBC); keyWrap.initUnwrap(unwrappingKey, iv); } @@ -1110,6 +1150,7 @@ else if(unwrappingKey.getType() == SymmetricKey.Type.DES || } else throw new EBaseException(method + " Unsupported transport key type."); + if (isPerm) { unwrapped = keyWrap.unwrapSymmetricPerm(inputKeyArray, keyType, SymmetricKey.Usage.UNWRAP, inputKeyArray.length); @@ -1123,14 +1164,17 @@ else if(unwrappingKey.getType() == SymmetricKey.Type.DES || } } catch (Exception e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } - //logger.debug(method + "Returning symkey: " + unwrapped); + //logger.debug(method + "Returning symkey: length = " + unwrapped.getLength()); logger.debug(method + "Returning symkey..."); - return finalUnwrapped == null ? unwrapped : finalUnwrapped; + if (finalUnwrapped != null) + return finalUnwrapped; + else + return unwrapped; } public SymmetricKey unwrapSymKeyOnToken(CryptoToken token, byte[] inputKeyArray, boolean isPerm) @@ -1141,16 +1185,17 @@ public SymmetricKey unwrapSymKeyOnToken(CryptoToken token, byte[] inputKeyArray, SymmetricKey unwrapped = null; if (token == null) { - throw new EBaseException(method + "Invalide crypto token!"); + throw new EBaseException(method + "Invalid crypto token!"); } if (inputKeyArray == null || (inputKeyArray.length != DES3_LENGTH && inputKeyArray.length != DES2_LENGTH)) { throw new EBaseException(method + "No raw array to use to create key!"); } - SymmetricKey transport = getSharedSecretKey(token); - unwrapped = this.unwrapSymKeyOnToken(token, transport, inputKeyArray, isPerm, SymmetricKey.DES3); + //RedHat For DES3 don's use the AES shared secret as wrapping key + unwrapped = this.unwrapSymKeyOnToken(token, null, inputKeyArray, isPerm, SymmetricKey.DES3); + logger.debug(method + "Returning symkey: length = " + unwrapped.getLength()); //logger.debug(method + "Returning symkey: " + unwrapped); return unwrapped; @@ -1267,7 +1312,7 @@ public CryptoManager getCryptoManger() throws EBaseException { try { cm = CryptoManager.getInstance(); } catch (NotInitializedException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } @@ -1309,7 +1354,7 @@ public SymmetricKey generateSymKey(String selectedToken) throws EBaseException { symKeyFinal = this.makeDes3KeyDerivedFromDes2(symKey, selectedToken); } catch (Exception e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } @@ -1317,29 +1362,6 @@ public SymmetricKey generateSymKey(String selectedToken) throws EBaseException { } - public SymmetricKey generateAESSymKey(String selectedToken, int keySize) throws EBaseException { - String method = "SecureChannelProtocol.generateAESSymKey: "; - - logger.debug(method + " entering , token: " + selectedToken + " size: " + keySize); - SymmetricKey symKey = null; - - if (selectedToken == null) { - throw new EBaseException(method + " Invalid input data!"); - } - - try { - CryptoManager cm = this.getCryptoManger(); - CryptoToken token = returnTokenByName(selectedToken, cm); - symKey = CryptoUtil.generateKey(token, KeyGenAlgorithm.AES, keySize, - session_key_usages,true); - } catch (Exception e) { - logger.error(method + " " + e.getMessage(), e); - throw new EBaseException(e); - } - - return symKey; - } - public byte[] ecbEncrypt(SymmetricKey devKey, SymmetricKey symKey, String selectedToken) throws EBaseException { byte[] result = null; String method = "SecureChannelProtocol.ecbEncrypt:"; @@ -1360,18 +1382,12 @@ public byte[] ecbEncrypt(SymmetricKey devKey, SymmetricKey symKey, String select SymmetricKey des2 = this.extractDes2FromDes3(symKey, devKeyToken); //SecureChannelProtocol.debugByteArray(des2.getEncoded(), method + " raw des2 key, to be wrapped."); - SymmetricKey toBeWrapped = null; - if(symKey.getType() == SymmetricKey.Type.AES) { - toBeWrapped = symKey; - } else { - toBeWrapped = this.extractDes2FromDes3(symKey, devKeyToken); - } - result = this.wrapSessionKey(selectedToken, toBeWrapped, devKey); + result = this.wrapSessionKey(selectedToken, des2, devKey); - //SecureChannelProtocol.debugByteArray(result, " Wrapped sym key"); + //SecureChannelProtocol.debugByteArray(result, " Wrapped des2 key"); - return result; + return result; } /* Convenience routine to create a 3DES key from a 2DES key. @@ -1418,7 +1434,7 @@ public SymmetricKey makeDes3KeyDerivedFromDes2(SymmetricKey des3Key, String sele des3 = concat.derive(); } catch (Exception e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } @@ -1451,7 +1467,7 @@ public SymmetricKey extractDes2FromDes3(SymmetricKey baseKey, String selectedTok extracted16 = extract16.derive(); } catch (Exception e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } @@ -1494,8 +1510,9 @@ public byte[] wrapSessionKey(String tokenName, SymmetricKey sessionKey, Symmetri keyWrap.initWrap(wrapper, null); wrappedSessKeyData = keyWrap.wrap(sessionKey); - } catch (Exception e) { - logger.error(method + " " + e.getMessage(), e); + } catch ( + Exception e) { + logger.debug(method + " " + e); throw new EBaseException(e); } @@ -1506,6 +1523,7 @@ public byte[] wrapSessionKey(String tokenName, SymmetricKey sessionKey, Symmetri CryptoToken token = returnTokenByName(tokenName, cm); int ivLength = EncryptionAlgorithm.AES_128_CBC.getIVLength(); + //logger.debug(method + " Set iv length to " + ivLength); byte[] iv = null; if (ivLength > 0) { @@ -1516,14 +1534,12 @@ public byte[] wrapSessionKey(String tokenName, SymmetricKey sessionKey, Symmetri keyWrap.initWrap(wrapper, new IVParameterSpec(iv)); wrappedSessKeyData = keyWrap.wrap(sessionKey); - } catch (Exception e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } } - //SecureChannelProtocol.debugByteArray(wrappedSessKeyData, "wrappedSessKeyData"); logger.debug(method + " returning session key"); @@ -1544,23 +1560,24 @@ public byte[] computeAES_CBCEncryption(SymmetricKey symKey, String selectedToken } if (iv == null) { - finalIv = new byte[16]; - + // Set iv based on key length + finalIv = new byte[DEF_AES_KEYLENGTH]; } else { finalIv = iv; } + //logger.debug(method + ": iv length = " + finalIv.length); + try { CryptoManager cm = this.getCryptoManger(); CryptoToken token = returnTokenByName(selectedToken, cm); Cipher encryptor = token.getCipherContext(EncryptionAlgorithm.AES_128_CBC); encryptor.initEncrypt(symKey, new IVParameterSpec(finalIv)); output = encryptor.doFinal(input); - - //SecureChannelProtocol.debugByteArray(output, "Encrypted data:"); + //SecureChannelProtocol.debugByteArray(output, "AES CBC Encrypted data:"); } catch (Exception e) { - logger.error(method + e.getMessage(), e); + logger.debug(method + e); throw new EBaseException(method + e); } @@ -1589,15 +1606,14 @@ public byte[] computeDes3EcbEncryption(SymmetricKey desKey, String selectedToken output = encryptor.doFinal(input); //logger.debug(method + "done doFinal " + output); logger.debug(method + "done doFinal"); - - // SecureChannelProtocol.debugByteArray(output, "Encrypted data:"); + //SecureChannelProtocol.debugByteArray(output, "Encrypted data:"); } catch (Exception e) { - logger.error(method + e.getMessage(), e); + logger.debug(method + e); throw new EBaseException(method + e); } logger.debug("returning encrypted output."); - // SecureChannelProtocol.debugByteArray(output, "Encrypted data before leaving:"); + //SecureChannelProtocol.debugByteArray(output, "Encrypted data before leaving:"); return output; } @@ -1614,14 +1630,21 @@ public byte[] computeKeyCheck_SCP03(SymmetricKey symKey, String selectedToken) t byte[] key_check_message = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; //zero iv vector byte[] key_check_iv = new byte[16]; - byte[] output = null; byte[] finalOutput = new byte[3]; + // RedHat :Do the same behavior as computeKeyCheck, use the token where the aes key resides. + String keysToken = null; try { - output = computeAES_CBCEncryption(symKey, selectedToken, key_check_message, key_check_iv); + keysToken = symKey.getOwningToken().getName(); + } catch (TokenException e1) { + throw new EBaseException(e1 + " Can't get owning token for key/"); + } + + try { + output = computeAES_CBCEncryption(symKey, keysToken, key_check_message, key_check_iv); } catch (EBaseException e) { - logger.error(method + e.getMessage(), e); + logger.debug(method + e); throw e; } @@ -1637,7 +1660,7 @@ public byte[] computeKeyCheck_SCP03(SymmetricKey symKey, String selectedToken) t //AES, uses AES_CMAC alg to do the work. public byte[] computeCryptogram_SCP03(SymmetricKey symKey, String selectedToken, byte[] context, byte cryptoType) throws EBaseException { - String method = "SecureChannelProtocol.computeCryptogram_"; + String method = "SecureChannelProtocol.computeCryptogram_SCP03"; logger.debug(method + " entering .."); @@ -1648,6 +1671,7 @@ public byte[] computeCryptogram_SCP03(SymmetricKey symKey, String selectedToken, NistSP800_108KDF nistKdf = new NistSP800_108KDF(this); byte[] crypto = nistKdf.kdf_AES_CMAC_SCP03(symKey, context, cryptoType, 8); + //SecureChannelProtocol.debugByteArray(crypto, " calculated cryptogram"); byte[] finalCrypto = new byte[8]; @@ -1681,7 +1705,7 @@ public byte[] computeKeyCheck(SymmetricKey desKey, String selectedToken) throws try { output = computeDes3EcbEncryption(desKey, keysToken, input); } catch (EBaseException e) { - logger.error(method + e.getMessage(), e); + logger.debug(method + e); throw e; } @@ -1803,14 +1827,15 @@ public byte[] diversifyKey(String tokenName, byte[] CUIDValue, byte[] KDD, byte[] kekKeyArray, byte[] encKeyArray, byte[] macKeyArray, - String useSoftToken, String keySet, byte protocol, GPParams params) throws EBaseException { + String useSoftToken, String keySet, byte protocol, GPParams params, + GPParams oldParams) throws EBaseException { // ** G&D 256 Key Rollover Support ** add oldParams parameter String method = "SecureChannelProtocol.diversifyKey:"; logger.debug(method + " Entering ... newTokenName: " + newTokenName + " protocol: " + protocol); logger.debug(method + " oldMasterKeyName: " + oldMasterKeyName); logger.debug(method + " newMasterKeyName: " + newMasterKeyName); - + //SecureChannelProtocol.debugByteArray(encKeyArray, " Developer enc key array: "); //SecureChannelProtocol.debugByteArray(macKeyArray, " Developer mac key array: "); //SecureChannelProtocol.debugByteArray(kekKeyArray, " Developer kek key array: "); @@ -1858,11 +1883,11 @@ public byte[] diversifyKey(String tokenName, newToken = returnTokenByName(newTokenName, cm); } } catch (NotInitializedException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } catch (NoSuchTokenException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } @@ -1873,15 +1898,15 @@ public byte[] diversifyKey(String tokenName, oldMasterKey = getSymKeyByName(token, fullOldMasterKeyName); } catch (EBaseException e) { masterKey = null; - logger.warn(method + " Master key is null, possibly ok in moving from keyset 2 to 1: " + e.getMessage()); + logger.debug(method + " Master key is null, possibly ok in moving from keyset 2 to 1"); if (oldMasterKey == null) { throw new EBaseException(method + " Can't retrieve old master key!"); } } -// SecureChannelProtocol.debugByteArray(oldKeyInfo, " oldKeyInfo: "); -// SecureChannelProtocol.debugByteArray(newKeyInfo, " newKeyInfo: "); + //SecureChannelProtocol.debugByteArray(oldKeyInfo, " oldKeyInfo: "); + //SecureChannelProtocol.debugByteArray(newKeyInfo, " newKeyInfo: "); byte oldKeyVersion = oldKeyInfo[0]; byte newKeyVersion = newKeyInfo[0]; @@ -1931,7 +1956,7 @@ public byte[] diversifyKey(String tokenName, try { keys = nistKDF.computeCardKeys(oldMasterKey, context, token); } catch (EBaseException e) { - logger.error(method + "Can't compute card keys! " + e.getMessage(), e); + logger.debug(method + "Can't compute card keys! " + e); throw e; } @@ -1950,11 +1975,12 @@ public byte[] diversifyKey(String tokenName, } } else { // Protocol 3 - + // ** G&D 256 Key Rollover Support ** + // use the oldParams to compute the old_kek_sym_key old_kek_sym_key = this.computeSessionKey_SCP03(tokenName, oldMasterKeyName, - oldKeyInfo, SecureChannelProtocol.kekType, kekKeyArray, keySet, - CUIDValue, KDD, null, null, transportKeyName, params); - + oldKeyInfo, SecureChannelProtocol.kekType, kekKeyArray, keySet, + CUIDValue, KDD, null, null, transportKeyName, oldParams); + logger.debug(method + " Moving back to the developer key set case, protocol 3"); } } @@ -1994,7 +2020,7 @@ public byte[] diversifyKey(String tokenName, try { keys = nistKDF.computeCardKeys(masterKey, context, newToken); } catch (EBaseException e) { - logger.error(method + "Can't compute card keys! For new key version. " + e.getMessage(), e); + logger.debug(method + "Can't compute card keys! For new key version. " + e); throw e; } @@ -2027,10 +2053,11 @@ public byte[] diversifyKey(String tokenName, // Generate an old kek key to do the encrypting of the new static keys + // ** G&D 256 Key Rollover Support ** + // use the oldParams to compute the old_kek_sym_key old_kek_sym_key = this.computeSessionKey_SCP03(tokenName, oldMasterKeyName, oldKeyInfo, SecureChannelProtocol.kekType, kekKeyArray, - keySet, CUIDValue, KDD, null, null, transportKeyName, params); - + keySet, CUIDValue, KDD, null, null, transportKeyName, oldParams); } if (encKey == null || macKey == null || kekKey == null) { @@ -2040,16 +2067,16 @@ public byte[] diversifyKey(String tokenName, } - boolean showKeysForDebug = false; + boolean showKeysForDebug = checkAllowDebugKeyRollover(); if (showKeysForDebug == true) { - try { - SecureChannelProtocol.debugByteArray(encKey.getKeyData(), "DiversifyKey: new encKey: "); - SecureChannelProtocol.debugByteArray(macKey.getKeyData(), "DiversifyKey: new macKey:"); - SecureChannelProtocol.debugByteArray(kekKey.getKeyData(), "DiversifyKey: new kekKey"); - } catch (NotExtractableException e) { - logger.warn(method + " Can not display debugging info for key"); - } + byte[] enc = debugAESKeyToBytes(token,encKey); + byte[] mac = debugAESKeyToBytes(token,macKey); + byte[] kek = debugAESKeyToBytes(token,kekKey); + + SecureChannelProtocol.debugByteArray(enc, "DiversifyKey: new encKey: "); + SecureChannelProtocol.debugByteArray(mac, "DiversifyKey: new macKey:"); + SecureChannelProtocol.debugByteArray(kek, "DiversifyKey: new kekKey"); } if (old_kek_sym_key != null) { @@ -2113,11 +2140,11 @@ private byte[] createKeySetDataWithSymKeys(byte newKeyVersion, byte[] old_kek_ke cm = CryptoManager.getInstance(); token = returnTokenByName(tokenName, cm); } catch (NotInitializedException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } catch (NoSuchTokenException e) { - logger.error(method + " " + e.getMessage(), e); + logger.debug(method + " " + e); throw new EBaseException(e); } @@ -2132,7 +2159,7 @@ private byte[] createKeySetDataWithSymKeys(byte newKeyVersion, byte[] old_kek_ke byte[] keycheck_enc_key = null; byte[] keycheck_mac_key = null; byte[] keycheck_kek_key = null; - + if (protocol == PROTOCOL_ONE) { if (old_kek_sym_key == null) { logger.debug(method + " Using old kek key array."); @@ -2194,10 +2221,20 @@ private byte[] createKeySetDataWithSymKeys(byte newKeyVersion, byte[] old_kek_ke byte[] b1 = null; byte[] b2 = null; - if (protocol == PROTOCOL_THREE) { + if (protocol == PROTOCOL_THREE) + { //Will be different if the key is bigger than AES 128 // Support 128 for now - b1 = new byte[] { alg, 0x11, (byte) encrypted_enc_key.length }; + // Added support for AES 256 keys + //logger.debug(method + " encrypted_enc_key length = " + encrypted_enc_key.length); + if (encrypted_enc_key.length == DEF_AES_256_KEYLENGTH) + { + b1 = new byte[] { alg, 0x21, (byte) encrypted_enc_key.length }; + } + else + { + b1 = new byte[] { alg, 0x11, (byte) encrypted_enc_key.length }; + } } else { b1 = new byte[] { alg, 0x10 }; } @@ -2343,9 +2380,97 @@ public byte[] encryptData(String selectedToken, String keyNickName, byte[] data, byte[] output = computeDes3EcbEncryption(kekKey, selectedToken, data); - // debugByteArray(output, " encryptData: Output: "); + //debugByteArray(output, " encryptData: Output: "); return output; } + public SymmetricKey generateAESSymKey(String selectedToken, int keySize) throws EBaseException { + String method = "SecureChannelProtocol.generateAESSymKey: "; + + logger.debug(method + " entering , token: " + selectedToken + " size: " + keySize); + SymmetricKey symKey = null; + + if (selectedToken == null) { + throw new EBaseException(method + " Invalid input data!"); + } + + try { + CryptoManager cm = this.getCryptoManger(); + CryptoToken token = returnTokenByName(selectedToken, cm); + symKey = CryptoUtil.generateKey(token, KeyGenAlgorithm.AES, keySize, + session_key_usages,true); + } catch (Exception e) { + logger.debug(method + " " + e); + throw new EBaseException(e); + } + + return symKey; + } + private static byte[] debugAESKeyToBytes(CryptoToken token,SymmetricKey aesKey) { + KeyGenerator kg; + SymmetricKey sessionKey; + byte[] result = null; + + if(token == null || aesKey == null) { + return result; + } + + try { + kg = token.getKeyGenerator(KeyGenAlgorithm.AES); + + SymmetricKey.Usage usages[] = new SymmetricKey.Usage[4]; + usages[0] = SymmetricKey.Usage.WRAP; + usages[1] = SymmetricKey.Usage.UNWRAP; + usages[2] = SymmetricKey.Usage.ENCRYPT; + usages[3] = SymmetricKey.Usage.DECRYPT; + + kg.setKeyUsages(usages); + kg.temporaryKeys(true); + // Handle 128 and 256 initialization sizes + kg.initialize(256); + SymmetricKey tempKey = kg.generate(); + + // Now wrap and unwrap with AES CBC PAD + + KeyWrapper keyWrap = token.getKeyWrapper(KeyWrapAlgorithm.AES_CBC_PAD); + int ivLen = KeyWrapAlgorithm.AES_CBC_PAD.getBlockSize(); + byte[] iv = new byte[ivLen]; + + IVParameterSpec ivsp = new IVParameterSpec(iv); + keyWrap.initWrap(tempKey, ivsp); + byte [] wrapped = keyWrap.wrap(aesKey); + + Cipher decryptor = token.getCipherContext(EncryptionAlgorithm.AES_256_CBC_PAD); + decryptor.initDecrypt(tempKey,ivsp); + result = decryptor.doFinal(wrapped); + + } catch (Exception e) { + return result; + } + + return result; + } + + private boolean checkAllowDebugKeyRollover() { + boolean allow = false; + + String method = "SecureChannelProtocol.checkAllowDebugKeyRollover: "; + + TKSEngine engine = TKSEngine.getInstance(); + TKSEngineConfig cs = engine.getConfig(); + String allowDebugKeyRollover = "tks.debugKeyRollover"; + + //logger.debug(method + " trying config: " + allowDebugKeyRollover); + + try { + allow = cs.getBoolean("tks.useNewSharedSecretNames", false); + } catch (EBaseException e) { + allow = false; + } + + //logger.debug(method + "returning allow: " + allow); + return allow; + } + } diff --git a/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/TokenServlet.java b/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/TokenServlet.java index 4f5f7a50180..7535f5d3cd7 100644 --- a/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/TokenServlet.java +++ b/base/tks/src/main/java/org/dogtagpki/server/tks/servlet/TokenServlet.java @@ -22,38 +22,42 @@ import java.io.OutputStream; import java.security.PublicKey; import java.security.SecureRandom; +import javax.crypto.spec.PSource; import java.security.spec.MGF1ParameterSpec; + import java.util.ArrayList; -import java.util.Collection; import java.util.StringTokenizer; -import javax.crypto.spec.OAEPParameterSpec; -import javax.crypto.spec.PSource; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.dogtagpki.server.authentication.AuthToken; -import org.dogtagpki.server.authorization.AuthzToken; import org.dogtagpki.server.connector.IRemoteRequest; -import org.dogtagpki.server.tks.TKSEngine; -import org.dogtagpki.server.tks.TKSEngineConfig; -import org.dogtagpki.server.tks.TPSConnectorConfig; -import org.mozilla.jss.CryptoManager; import org.mozilla.jss.NotInitializedException; +import org.mozilla.jss.CryptoManager; import org.mozilla.jss.crypto.CryptoToken; import org.mozilla.jss.crypto.KeyWrapAlgorithm; import org.mozilla.jss.crypto.KeyWrapper; import org.mozilla.jss.crypto.SymmetricKey; +import org.mozilla.jss.crypto.TokenException; import org.mozilla.jss.crypto.X509Certificate; -import org.mozilla.jss.netscape.security.util.PrettyPrintFormat; import org.mozilla.jss.pkcs11.PK11SymKey; import org.mozilla.jss.crypto.IVParameterSpec; import org.mozilla.jss.crypto.EncryptionAlgorithm; import org.mozilla.jss.symkey.SessionKey; +import org.dogtagpki.server.tks.TKSEngine; +import org.dogtagpki.server.tks.TKSEngineConfig; +import org.dogtagpki.server.authentication.AuthToken; +import org.dogtagpki.server.authorization.AuthzToken; import com.netscape.certsrv.base.EBaseException; +import com.netscape.cmscore.base.ConfigStore; +import com.netscape.cmscore.logging.Auditor; +import org.mozilla.jss.netscape.security.util.PrettyPrintFormat; + +import javax.crypto.spec.OAEPParameterSpec; + import com.netscape.certsrv.base.SessionContext; import com.netscape.certsrv.logging.AuditEvent; import com.netscape.certsrv.logging.ILogger; @@ -61,24 +65,29 @@ import com.netscape.certsrv.logging.event.ComputeSessionKeyRequestProcessedEvent; import com.netscape.certsrv.logging.event.DiversifyKeyRequestProcessedEvent; import com.netscape.certsrv.logging.event.EncryptDataRequestProcessedEvent; +import com.netscape.cms.logging.Logger; import com.netscape.cms.servlet.base.CMSServlet; import com.netscape.cms.servlet.common.CMSRequest; import com.netscape.cmscore.apps.CMS; -import com.netscape.cmscore.base.ConfigStore; -import com.netscape.cmscore.logging.Auditor; + +//import com.netscape.cms.servlet.tks.NistSP800_108KDF; +//import com.netscape.cms.servlet.tks.SecureChannelProtocol; import com.netscape.cmscore.security.JssSubsystem; import com.netscape.cmsutil.crypto.CryptoUtil; +//import com.netscape.symkey.SessionKey; /** * A class representings an administration servlet for Token Key * Service Authority. This servlet is responsible to serve * tks administrative operation such as configuration * parameter updates. + * + * @version $Revision$, $Date$ */ public class TokenServlet extends CMSServlet { - public static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TokenServlet.class); - + Logger transactionLogger = Logger.getLogger(ILogger.EV_AUDIT, ILogger.S_TKS); + public static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SecureChannelProtocol.class); private static final long serialVersionUID = 8687436109695172791L; protected static final String PROP_ENABLED = "enabled"; protected static final String TRANSPORT_KEY_NAME = "sharedSecret"; @@ -112,7 +121,6 @@ public static String trim(String a) { return newa.toString(); } - @Override public void init(ServletConfig config) throws ServletException { super.init(config); } @@ -122,7 +130,6 @@ public void init(ServletConfig config) throws ServletException { * * @return name of this servlet */ - @Override public String getServletInfo() { return INFO; } @@ -205,7 +212,8 @@ private void setDefaultSlotAndKeyName(HttpServletRequest req) { /*SessionKey.SetDefaultPrefix(masterKeyPrefix);*/ } catch (Exception e) { - logger.warn("Exception in TokenServlet::setDefaultSlotAndKeyName: " + e.getMessage(), e); + e.printStackTrace(); + logger.debug("Exception in TokenServlet::setDefaultSlotAndKeyName"); } } @@ -215,10 +223,10 @@ private void setDefaultSlotAndKeyName(HttpServletRequest req) { // CAREFUL: Result returned may be negative due to java's lack of unsigned types. // Negative values need to be treated as higher key numbers than positive key numbers. private static byte read_setting_nistSP800_108KdfOnKeyVersion(String keySet) throws Exception { - TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); String nistSP800_108KdfOnKeyVersion_map = "tks." + keySet + ".nistSP800-108KdfOnKeyVersion"; // KDF phase1: default to 00 + TKSEngine engine = TKSEngine.getInstance(); + TKSEngineConfig config = engine.getConfig(); String nistSP800_108KdfOnKeyVersion_value = config.getString(nistSP800_108KdfOnKeyVersion_map, "00" /*null*/); short nistSP800_108KdfOnKeyVersion_short = 0; @@ -251,11 +259,12 @@ private static byte read_setting_nistSP800_108KdfOnKeyVersion(String keySet) thr // If "true" we use the CUID parameter within the NIST SP800-108 KDF. // If "false" we use the KDD parameter within the NIST SP800-108 KDF. private static boolean read_setting_nistSP800_108KdfUseCuidAsKdd(String keySet) throws Exception { - TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); String setting_map = "tks." + keySet + ".nistSP800-108KdfUseCuidAsKdd"; // KDF phase1: default to "false" - String setting_str = config.getString(setting_map, "false" /*null*/); + TKSEngine engine = TKSEngine.getInstance(); + TKSEngineConfig config = engine.getConfig(); + String setting_str = + config.getString(setting_map, "false" /*null*/); boolean setting_boolean = false; // if value does not exist in file if (setting_str == null) { @@ -307,7 +316,11 @@ private String log_string_from_keyInfo(byte[] xkeyInfo) { // if specialDecoded is blank, returns "null" // if specialDecoded != null, returns private String log_string_from_specialDecoded_byte_array(byte[] specialDecoded) { - return specialDecoded == null ? "null" : bytesToHex(specialDecoded); + if (specialDecoded == null) { + return "null"; + } else { + return bytesToHex(specialDecoded); + } } /* Compute Session Key for SCP02 @@ -331,8 +344,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe boolean nistSP800_108KdfUseCuidAsKdd = false; TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); - Auditor auditor = engine.getAuditor(); + TKSEngineConfig sconfig = engine.getConfig(); boolean isCryptoValidate = false; byte[] keyInfo, xCUID = null, session_key = null; @@ -385,6 +397,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe (String) sContext.get(SessionContext.USER_ID); } + auditMessage = CMS.getLogMessage( AuditEvent.COMPUTE_SESSION_KEY_REQUEST, rCUID, @@ -392,10 +405,10 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe ILogger.SUCCESS, agentId); - auditor.log(auditMessage); + audit(auditMessage); if (!missingParam) { - xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); + xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); if (xCUID == null || xCUID.length != 10) { badParams += " CUID length,"; @@ -409,14 +422,14 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe missingParam = true; } - xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); + xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); if (xKDD == null || xKDD.length != 10) { badParams += " KDD length,"; logger.debug("TokenServlet.processComputeSessionKeySCP02: Invalid KDD length"); missingParam = true; } - keyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); + keyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); if (keyInfo == null || keyInfo.length != 2) { badParams += " KeyInfo length,"; logger.debug("TokenServlet.processComputeSessionKeySCP02: Invalid key info length."); @@ -444,11 +457,13 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe // conform to the set-an-error-flag mentality } catch (Exception e) { missingSettingException = e; - logger.warn("TokenServlet: Exception reading Nist SP800-108 KDF config values: " + e.getMessage(), e); + logger.debug("TokenServlet: ComputeSessionKeySCP02(): Exception reading Nist SP800-108 KDF config values: " + + e.toString()); } } + TKSEngineConfig config = engine.getConfig(); String keyInfoMap = "tks." + keySet + ".mk_mappings." + rKeyInfo; //#xx#xx String mappingValue = config.getString(keyInfoMap, null); if (mappingValue == null) { @@ -467,14 +482,16 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe try { mappingValue = config.getString(keyInfoMap, null); } catch (EBaseException e1) { - logger.warn("TokenServlet: " + e1.getMessage(), e1); + + e1.printStackTrace(); } if (mappingValue == null) { try { selectedToken = config.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); } catch (EBaseException e) { - logger.warn("TokenServlet: " + e.getMessage(), e); + + e.printStackTrace(); } keyNickName = rKeyInfo; } else { @@ -490,7 +507,8 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe try { useSoftToken_s = config.getString("tks.useSoftToken", "true"); } catch (EBaseException e1) { - logger.warn("TokenServlet: " + e1.getMessage(), e1); + // TODO Auto-generated catch block + e1.printStackTrace(); } if (!useSoftToken_s.equalsIgnoreCase("true")) useSoftToken_s = "false"; @@ -505,15 +523,18 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe transportKeyName = null; try { - transportKeyName = getSharedSecretName(config); + transportKeyName = getSharedSecretName(sconfig); } catch (EBaseException e1) { - logger.warn("TokenServlet: Can't find transport key name: " + e1.getMessage(), e1); + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.debug("TokenServlet.processComputeSessionKeySCP02: Can't find transport key name!"); + } logger.debug("TokenServlet: processComputeSessionKeySCP02(): tksSharedSymKeyName: " + transportKeyName); try { - isCryptoValidate = config.getBoolean("cardcryptogram.validate.enable", true); + isCryptoValidate = sconfig.getBoolean("cardcryptogram.validate.enable", true); } catch (EBaseException eee) { } @@ -528,11 +549,11 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe if (selectedToken != null && keyNickName != null && transportKeyName != null && missingSettingException == null) { try { - macKeyArray = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + macKeyArray = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".mac_key")); - sequenceCounter = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rSequenceCounter); - derivationConstant = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rDerivationConstant); + sequenceCounter = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rSequenceCounter); + derivationConstant = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rDerivationConstant); //Use old style for the moment. //ToDo: We need to use the nistXP800 params we have collected and send them down to symkey @@ -547,7 +568,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe transportKeyName); if (session_key == null) { - logger.warn("TokenServlet.computeSessionKeySCP02:Tried ComputeSessionKey, got NULL "); + logger.debug("TokenServlet.computeSessionKeySCP02:Tried ComputeSessionKey, got NULL "); throw new EBaseException("Can't compute session key for SCP02!"); } @@ -583,7 +604,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe if (desKey != null) logger.debug("TokenServlet.computeSessionKeySCP02: key encryption key generated for " + rCUID); else { - logger.error("TokenServlet.computeSessionKeySCP02: key encryption key generation failed for " + logger.debug("TokenServlet.computeSessionKeySCP02: key encryption key generation failed for " + rCUID); throw new EBaseException( "TokenServlet.computeSessionKeySCP02: can't generate key encryption key"); @@ -642,13 +663,14 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(keycheck); //use DRM transport cert to wrap desKey - String drmTransNickname = config.getString("tks.drm_transport_cert_nickname", ""); + String drmTransNickname = sconfig.getString("tks.drm_transport_cert_nickname", ""); if ((drmTransNickname == null) || (drmTransNickname == "")) { - logger.error("TokenServlet.computeSessionKeySCP02:did not find DRM transport certificate nickname"); + logger.debug("TokenServlet.computeSessionKeySCP02:did not find DRM transport certificate nickname"); throw new EBaseException("can't find DRM transport certificate nickname"); + } else { + logger.debug("TokenServlet.computeSessionKeySCP02:drmtransport_cert_nickname=" + drmTransNickname); } - logger.debug("TokenServlet.computeSessionKeySCP02:drmtransport_cert_nickname=" + drmTransNickname); X509Certificate drmTransCert = null; drmTransCert = CryptoManager.getInstance().findCertByNickname(drmTransNickname); @@ -663,7 +685,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe keyWrapper = token.getKeyWrapper(KeyWrapAlgorithm.AES_ECB); keyWrapper.initWrap(pubKey, null); } else { - boolean useOAEP = config.getUseOAEPKeyWrap(); + boolean useOAEP = sconfig.getBoolean("keyWrap.useOAEP",false); KeyWrapAlgorithm wrapAlg = KeyWrapAlgorithm.RSA; if(useOAEP == true) { wrapAlg = KeyWrapAlgorithm.RSA_OAEP; @@ -673,7 +695,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe OAEPParameterSpec params = null; if(useOAEP) { params = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT); - } + } keyWrapper.initWrap(pubKey, params); } @@ -685,7 +707,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe } } catch (Exception e) { - logger.warn("TokenServlet.computeSessionKeySCP02 Computing Session Key: " + e.getMessage(), e); + logger.debug("TokenServlet.computeSessionKeySCP02 Computing Session Key: " + e.toString()); errorFound = true; } @@ -799,7 +821,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe ooss.flush(); mRenderResult = false; } catch (IOException e) { - logger.warn("TokenServlet: " + e.getMessage(), e); + logger.debug("TokenServlet: " + e.toString()); } if (status.equals("0")) { @@ -818,8 +840,8 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe "0x" + Integer.toHexString(nistSP800_108KdfOnKeyVersion & 0x000000FF), // NistSP800_108KdfOnKeyVersion Boolean.toString(nistSP800_108KdfUseCuidAsKdd) // NistSP800_108KdfUseCuidAsKdd ); - - auditor.log(event); + Auditor auditor = engine.getAuditor(); + auditor.log(event);; } else { @@ -838,7 +860,7 @@ private void processComputeSessionKeySCP02(HttpServletRequest req, HttpServletRe Boolean.toString(nistSP800_108KdfUseCuidAsKdd), // NistSP800_108KdfUseCuidAsKdd errorMsg // Error ); - + Auditor auditor = engine.getAuditor(); auditor.log(event); } } @@ -879,13 +901,12 @@ private void processComputeSessionKey(HttpServletRequest req, byte[] aes_wrapped_desKey = null; byte[] drm_trans_wrapped_aesKey = null; SymmetricKey desKey = null; - SymmetricKey aesKey = null; + SymmetricKey aesKey = null; // PK11SymKey kek_session_key; SymmetricKey kek_key; TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); - Auditor auditor = engine.getAuditor(); + TKSEngineConfig sconfig = engine.getConfig(); boolean isCryptoValidate = true; boolean missingParam = false; @@ -914,14 +935,14 @@ private void processComputeSessionKey(HttpServletRequest req, ILogger.SUCCESS, agentId); - auditor.log(auditMessage); + audit(auditMessage); String kek_wrapped_desKeyString = null; - String kek_wrapped_aesKeyString = null; + String kek_wrapped_aesKeyString = null; String keycheck_s = null; logger.debug("processComputeSessionKey:"); - String useSoftToken_s = config.getString("tks.useSoftToken", "true"); + String useSoftToken_s = sconfig.getString("tks.useSoftToken", "true"); if (!useSoftToken_s.equalsIgnoreCase("true")) useSoftToken_s = "false"; @@ -934,11 +955,11 @@ private void processComputeSessionKey(HttpServletRequest req, } try { - isCryptoValidate = config.getBoolean("cardcryptogram.validate.enable", true); + isCryptoValidate = sconfig.getBoolean("cardcryptogram.validate.enable", true); } catch (EBaseException eee) { } - transportKeyName = getSharedSecretName(config); + transportKeyName = getSharedSecretName(sconfig); String rcard_challenge = req.getParameter(IRemoteRequest.TOKEN_CARD_CHALLENGE); String rhost_challenge = req.getParameter(IRemoteRequest.TOKEN_HOST_CHALLENGE); @@ -986,7 +1007,7 @@ private void processComputeSessionKey(HttpServletRequest req, if (!missingParam) { - xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); + xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); if (xCUID == null || xCUID.length != 10) { badParams += " CUID length,"; logger.debug("TokenServlet: Invalid CUID length"); @@ -994,28 +1015,28 @@ private void processComputeSessionKey(HttpServletRequest req, } // AC: KDF SPEC CHANGE - read new KDD parameter from TPS - xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); + xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); if (xKDD == null || xKDD.length != 10) { badParams += " KDD length,"; logger.debug("TokenServlet: Invalid KDD length"); missingParam = true; } - xkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); + xkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); if (xkeyInfo == null || xkeyInfo.length != 2) { badParams += " KeyInfo length,"; logger.debug("TokenServlet: Invalid key info length."); missingParam = true; } xcard_challenge = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_challenge); + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_challenge); if (xcard_challenge == null || xcard_challenge.length != 8) { badParams += " card_challenge length,"; logger.debug("TokenServlet: Invalid card challenge length."); missingParam = true; } - xhost_challenge = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rhost_challenge); + xhost_challenge = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rhost_challenge); if (xhost_challenge == null || xhost_challenge.length != 8) { badParams += " host_challenge length,"; logger.debug("TokenServlet: Invalid host challenge length"); @@ -1026,10 +1047,10 @@ private void processComputeSessionKey(HttpServletRequest req, if (!missingParam) { card_challenge = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_challenge); + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_challenge); - host_challenge = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rhost_challenge); - keyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); + host_challenge = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rhost_challenge); + keyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); // AC: KDF SPEC CHANGE - read new config file values (needed for symkey) //ToDo: Will use these values after completing next ticket @@ -1054,14 +1075,15 @@ private void processComputeSessionKey(HttpServletRequest req, // conform to the set-an-error-flag mentality } catch (Exception e) { missingSetting_exception = e; - logger.warn("TokenServlet: Exception reading Nist SP800-108 KDF config values: " + e.getMessage(), e); + logger.debug("TokenServlet: ComputeSessionKey(): Exception reading Nist SP800-108 KDF config values: " + + e.toString()); } String keyInfoMap = "tks." + keySet + ".mk_mappings." + rKeyInfo; //#xx#xx - String mappingValue = config.getString(keyInfoMap, null); + String mappingValue = sconfig.getString(keyInfoMap, null); if (mappingValue == null) { selectedToken = - config.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); + sconfig.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); keyNickName = rKeyInfo; } else { StringTokenizer st = new StringTokenizer(mappingValue, ":"); @@ -1078,7 +1100,7 @@ private void processComputeSessionKey(HttpServletRequest req, try { byte macKeyArray[] = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".mac_key")); logger.debug("TokenServlet about to try ComputeSessionKey selectedToken=" + selectedToken + " keyNickName=" + keyNickName); @@ -1093,13 +1115,13 @@ private void processComputeSessionKey(HttpServletRequest req, session_key = protocol.wrapSessionKey(selectedToken, macKey, null); if (session_key == null) { - logger.error("TokenServlet:Tried ComputeSessionKey, got NULL "); + logger.debug("TokenServlet:Tried ComputeSessionKey, got NULL "); throw new Exception("Can't compute session key!"); } byte encKeyArray[] = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".auth_key")); SymmetricKey encKey = protocol.computeSessionKey_SCP01(SecureChannelProtocol.encType, selectedToken, @@ -1110,7 +1132,7 @@ private void processComputeSessionKey(HttpServletRequest req, enc_session_key = protocol.wrapSessionKey(selectedToken, encKey, null); if (enc_session_key == null) { - logger.error("TokenServlet:Tried ComputeEncSessionKey, got NULL "); + logger.debug("TokenServlet:Tried ComputeEncSessionKey, got NULL "); throw new Exception("Can't compute enc session key!"); } @@ -1127,7 +1149,7 @@ private void processComputeSessionKey(HttpServletRequest req, logger.debug("TokenServlet: calling ComputeKekKey"); byte kekKeyArray[] = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key")); kek_key = protocol.computeKEKKey_SCP01(selectedToken, @@ -1139,7 +1161,7 @@ private void processComputeSessionKey(HttpServletRequest req, logger.debug("TokenServlet: called ComputeKekKey"); if (kek_key == null) { - logger.error("TokenServlet:Tried ComputeKekKey, got NULL "); + logger.debug("TokenServlet:Tried ComputeKekKey, got NULL "); throw new Exception("Can't compute kek key!"); } @@ -1168,6 +1190,7 @@ private void processComputeSessionKey(HttpServletRequest req, desKey = protocol.generateSymKey(CryptoUtil.INTERNAL_TOKEN_NAME); //128 for now until we implement the full > 128 aes funcionality. aesKey = protocol.generateAESSymKey(CryptoUtil.INTERNAL_TOKEN_NAME,128); + //cfu audit here? sym key gen done } else { logger.debug("TokenServlet: key encryption key generated on " + selectedToken); @@ -1182,7 +1205,7 @@ private void processComputeSessionKey(HttpServletRequest req, trim(pp.toHexString(xKDD))); } else { // AC: KDF SPEC CHANGE - Output using CUID and KDD - logger.error("TokenServlet: key encryption key generation failed for CUID=" + + logger.debug("TokenServlet: key encryption key generation failed for CUID=" + trim(pp.toHexString(xCUID)) + ", KDD=" + trim(pp.toHexString(xKDD))); @@ -1196,7 +1219,7 @@ private void processComputeSessionKey(HttpServletRequest req, ", KDD=" + trim(pp.toHexString(xKDD)) */ ); } else { - logger.error("TokenServlet: aes key encryption key generation failed for CUID=" + + logger.debug("TokenServlet: aes key encryption key generation failed for CUID=" + trim(pp.toHexString(xCUID)) /* + ", KDD=" + trim(pp.toHexString(xKDD)) */ ); @@ -1210,8 +1233,15 @@ private void processComputeSessionKey(HttpServletRequest req, * This is done so that the applet can digest it */ + /* Now that ecbEncrypt() can handle AES keys, + * in case it's an AES key, it simply + * wraps the AES key with KEK and returns + * the encrypted byte array + */ + byte[] encDesKey = protocol.ecbEncrypt(kek_key, desKey, selectedToken); - byte[] encAesKey = protocol.ecbEncrypt(kek_key,aesKey,selectedToken); + byte[] encAesKey = protocol.ecbEncrypt(kek_key,aesKey,selectedToken); + /* logger.debug("computeSessionKey:encrypted desKey size = "+encDesKey.length); @@ -1220,27 +1250,28 @@ private void processComputeSessionKey(HttpServletRequest req, kek_wrapped_desKeyString = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(encDesKey); - kek_wrapped_aesKeyString = - org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(encAesKey); + + kek_wrapped_aesKeyString = + org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(encAesKey); // get keycheck byte[] keycheck = protocol.computeKeyCheck(desKey, selectedToken); - /* - logger.debug("computeSessionKey:keycheck size = "+keycheck.length); - logger.debug(keycheck); - */ + //logger.debug("computeSessionKey:keycheck size = "+keycheck.length); + //logger.debug(keycheck); + keycheck_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(keycheck); //use DRM transport cert to wrap desKey - String drmTransNickname = config.getString("tks.drm_transport_cert_nickname", ""); + String drmTransNickname = sconfig.getString("tks.drm_transport_cert_nickname", ""); if ((drmTransNickname == null) || (drmTransNickname == "")) { - logger.error("TokenServlet:did not find DRM transport certificate nickname"); + logger.debug("TokenServlet:did not find DRM transport certificate nickname"); throw new Exception("can't find DRM transport certificate nickname"); + } else { + logger.debug("TokenServlet:drmtransport_cert_nickname=" + drmTransNickname); } - logger.debug("TokenServlet:drmtransport_cert_nickname=" + drmTransNickname); X509Certificate drmTransCert = null; drmTransCert = CryptoManager.getInstance().findCertByNickname(drmTransNickname); @@ -1260,9 +1291,8 @@ private void processComputeSessionKey(HttpServletRequest req, keyWrapper = token.getKeyWrapper(KeyWrapAlgorithm.AES_ECB); keyWrapper.initWrap(pubKey, null); } else { - - boolean useOAEP = config.getUseOAEPKeyWrap(); - KeyWrapAlgorithm wrapAlg = KeyWrapAlgorithm.RSA; + boolean useOAEP = sconfig.getBoolean("keyWrap.useOAEP",false); + KeyWrapAlgorithm wrapAlg = KeyWrapAlgorithm.RSA; if(useOAEP == true) { wrapAlg = KeyWrapAlgorithm.RSA_OAEP; } @@ -1276,7 +1306,8 @@ private void processComputeSessionKey(HttpServletRequest req, } logger.debug("desKey token " + desKey.getOwningToken().getName() + " token: " + token.getName()); drm_trans_wrapped_desKey = keyWrapper.wrap(desKey); - logger.debug("computeSessionKey:desKey wrapped with drm transportation key. size: " + drm_trans_wrapped_desKey.length); + logger.debug("computeSessionKey:desKey wrapped with drm transportation key."); + drm_trans_wrapped_aesKey = keyWrapper.wrap(aesKey); logger.debug("computeSessionKey:aesKey wrapped with drm transportation key. size " + drm_trans_wrapped_aesKey.length); @@ -1290,7 +1321,7 @@ private void processComputeSessionKey(HttpServletRequest req, } // if (serversideKeygen == true) byte authKeyArray[] = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".auth_key")); host_cryptogram = protocol.computeCryptogram_SCP01(selectedToken, keyNickName, card_challenge, @@ -1299,7 +1330,7 @@ private void processComputeSessionKey(HttpServletRequest req, authKeyArray, useSoftToken_s, keySet, transportKeyName); if (host_cryptogram == null) { - logger.error("TokenServlet:Tried ComputeCryptogram, got NULL "); + logger.debug("TokenServlet:Tried ComputeCryptogram, got NULL "); throw new Exception("Can't compute host cryptogram!"); } @@ -1309,18 +1340,18 @@ private void processComputeSessionKey(HttpServletRequest req, xCUID, xKDD, SecureChannelProtocol.CARD_CRYPTOGRAM, authKeyArray, useSoftToken_s, keySet, transportKeyName); if (card_crypto == null) { - logger.error("TokenServlet:Tried ComputeCryptogram, got NULL "); + logger.debug("TokenServlet:Tried ComputeCryptogram, got NULL "); throw new Exception("Can't compute card cryptogram!"); } if (isCryptoValidate) { if (rcard_cryptogram == null) { - logger.error("TokenServlet: ComputeCryptogram(): missing card cryptogram"); + logger.debug("TokenServlet: ComputeCryptogram(): missing card cryptogram"); throw new Exception("Missing card cryptogram"); } input_card_crypto = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_cryptogram); + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_cryptogram); //SecureChannelProtocol.debugByteArray(input_card_crypto, "input_card_crypto"); //SecureChannelProtocol.debugByteArray(card_crypto, "card_crypto"); @@ -1339,12 +1370,13 @@ private void processComputeSessionKey(HttpServletRequest req, } // AC: KDF SPEC CHANGE - print both KDD and CUID - logger.info("processComputeSessionKey for CUID=" + + transactionLogger.log( + ILogger.LL_INFO, "processComputeSessionKey for CUID=" + trim(pp.toHexString(xCUID)) + ", KDD=" + trim(pp.toHexString(xKDD))); } catch (Exception e) { - logger.warn("TokenServlet Computing Session Key: " + e.getMessage(), e); + logger.debug("TokenServlet Computing Session Key: " + e.toString()); if (isCryptoValidate) sameCardCrypto = false; } @@ -1385,7 +1417,7 @@ private void processComputeSessionKey(HttpServletRequest req, status = "1"; } - if (drm_trans_wrapped_aesKey != null && drm_trans_wrapped_aesKey.length > 0) { + if (drm_trans_wrapped_aesKey != null && drm_trans_wrapped_aesKey.length > 0) { drm_trans_wrapped_aesKeyString = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(drm_trans_wrapped_aesKey); //logger.debug("drm_trans_wrapped_aesKeyString: " + drm_trans_wrapped_aesKeyString); @@ -1399,8 +1431,9 @@ private void processComputeSessionKey(HttpServletRequest req, org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(aes_wrapped_desKey); } else { - status = "1"; + status = "1"; } + } if (host_cryptogram != null && host_cryptogram.length > 0) { @@ -1516,7 +1549,7 @@ private void processComputeSessionKey(HttpServletRequest req, ooss.flush(); mRenderResult = false; } catch (IOException e) { - logger.warn("TokenServlet: " + e.getMessage(), e); + logger.debug("TokenServlet: " + e.toString()); } if (status.equals("0")) { @@ -1538,6 +1571,7 @@ private void processComputeSessionKey(HttpServletRequest req, Boolean.toString(nistSP800_108KdfUseCuidAsKdd) // NistSP800_108KdfUseCuidAsKdd ); + Auditor auditor = engine.getAuditor(); auditor.log(event); } else { @@ -1559,7 +1593,7 @@ private void processComputeSessionKey(HttpServletRequest req, Boolean.toString(nistSP800_108KdfUseCuidAsKdd), // NistSP800_108KdfUseCuidAsKdd errorMsg // Error ); - + Auditor auditor = engine.getAuditor(); auditor.log(event); } } @@ -1573,16 +1607,15 @@ private void processComputeSessionKey(HttpServletRequest req, // key based on some parameter in the request in future. // // On legacy systems, this method just returns what was previously returned. - private String getSharedSecretName(TKSEngineConfig cs) throws EBaseException { + private String getSharedSecretName(ConfigStore cs) throws EBaseException { boolean useNewNames = cs.getBoolean("tks.useNewSharedSecretNames", false); if (useNewNames) { - Collection tpsList = cs.getTPSConnectorIDs(); + String tpsList = cs.getString("tps.list", ""); String firstSharedSecretName = null; if (!tpsList.isEmpty()) { - for (String tpsID : tpsList) { - TPSConnectorConfig tpsConfig = cs.getTPSConnectorConfig(tpsID); - String sharedSecretName = tpsConfig.getNickname(); + for (String tpsID : tpsList.split(",")) { + String sharedSecretName = cs.getString("tps." + tpsID + ".nickname", ""); // This one will be a fall back in case we can't get a specific one if (firstSharedSecretName == null) { @@ -1591,7 +1624,7 @@ private String getSharedSecretName(TKSEngineConfig cs) throws EBaseException { if (!sharedSecretName.isEmpty()) { if (mCurrentUID != null) { - String csUid = tpsConfig.getUserID(); + String csUid = cs.getString("tps." + tpsID + ".userid", ""); if (mCurrentUID.equalsIgnoreCase(csUid)) { logger.debug("TokenServlet.getSharedSecretName: found a match of the user id! " + csUid); @@ -1606,7 +1639,7 @@ private String getSharedSecretName(TKSEngineConfig cs) throws EBaseException { return firstSharedSecretName; } } - logger.error("getSharedSecretName: no shared secret has been configured"); + logger.debug("getSharedSecretName: no shared secret has been configured"); throw new EBaseException("No shared secret has been configured"); } @@ -1641,8 +1674,7 @@ private void processDiversifyKey(HttpServletRequest req, byte[] xWrappedDekKey = null; TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); - Auditor auditor = engine.getAuditor(); + TKSEngineConfig sconfig = engine.getConfig(); String rnewKeyInfo = req.getParameter(IRemoteRequest.TOKEN_NEW_KEYINFO); String newMasterKeyName = req.getParameter(IRemoteRequest.TOKEN_NEW_KEYINFO); @@ -1670,6 +1702,11 @@ private void processDiversifyKey(HttpServletRequest req, keySet = "defKeySet"; } logger.debug("keySet selected: " + keySet); + + // ** G&D 256 Key Rollover Support ** + String oldKeySet = req.getParameter(IRemoteRequest.TOKEN_OLD_KEYSET); + logger.debug("oldKeySet: " + oldKeySet); + SessionContext sContext = SessionContext.getContext(); @@ -1689,7 +1726,7 @@ private void processDiversifyKey(HttpServletRequest req, oldMasterKeyName, newMasterKeyName); - auditor.log(auditMessage); + audit(auditMessage); if ((rCUID == null) || (rCUID.equals(""))) { badParams += " CUID,"; @@ -1722,13 +1759,13 @@ private void processDiversifyKey(HttpServletRequest req, xnewkeyInfo = null; // avoid errors about non-initialization if (!missingParam) { - xkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(oldMasterKeyName); + xkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(oldMasterKeyName); if (xkeyInfo == null || (xkeyInfo.length != 2 && xkeyInfo.length != 3)) { badParams += " KeyInfo length,"; logger.debug("TokenServlet: Invalid key info length"); missingParam = true; } - xnewkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(newMasterKeyName); + xnewkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(newMasterKeyName); if (xnewkeyInfo == null || (xnewkeyInfo.length != 2 && xnewkeyInfo.length != 3)) { badParams += " NewKeyInfo length,"; logger.debug("TokenServlet: Invalid new key info length"); @@ -1752,18 +1789,18 @@ private void processDiversifyKey(HttpServletRequest req, } else { logger.debug("process DiversifyKey: wrappedDekKey value: " + rWrappedDekKey); - xWrappedDekKey = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rWrappedDekKey); + xWrappedDekKey = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rWrappedDekKey); } } } - String useSoftToken_s = config.getString("tks.useSoftToken", "true"); + String useSoftToken_s = sconfig.getString("tks.useSoftToken", "true"); if (!useSoftToken_s.equalsIgnoreCase("true")) useSoftToken_s = "false"; KeySetData = null; if (!missingParam) { - xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); + xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); if (xCUID == null || xCUID.length != 10) { badParams += " CUID length,"; logger.debug("TokenServlet: Invalid CUID length"); @@ -1771,7 +1808,7 @@ private void processDiversifyKey(HttpServletRequest req, } // AC: KDF SPEC CHANGE - read new KDD parameter from TPS - xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); + xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); if (xKDD == null || xKDD.length != 10) { badParams += " KDD length,"; logger.debug("TokenServlet: Invalid KDD length"); @@ -1779,7 +1816,7 @@ private void processDiversifyKey(HttpServletRequest req, } } if (!missingParam) { - // CUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); // AC: KDF SPEC CHANGE: Removed duplicative variable/processing. + // CUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); // AC: KDF SPEC CHANGE: Removed duplicative variable/processing. // AC: KDF SPEC CHANGE - read new config file values (needed for symkey) @@ -1809,7 +1846,8 @@ private void processDiversifyKey(HttpServletRequest req, // conform to the set-an-error-flag mentality } catch (Exception e) { missingSetting_exception = e; - logger.warn("TokenServlet: Exception reading Nist SP800-108 KDF config values: " + e.getMessage(), e); + logger.debug("TokenServlet: processDiversifyKey(): Exception reading Nist SP800-108 KDF config values: " + + e.toString()); } if (mKeyNickName != null) @@ -1822,11 +1860,16 @@ private void processDiversifyKey(HttpServletRequest req, // Get the first 6 characters, since scp03 gives us extra characters. tokKeyInfo = tokKeyInfo.substring(0,6); String oldKeyInfoMap = "tks." + keySet + ".mk_mappings." + tokKeyInfo; //#xx#xx + + // ** G&D 256 Key Rollover Support ** + if (oldKeySet != null) + oldKeyInfoMap = "tks." + oldKeySet + ".mk_mappings." + tokKeyInfo; //#xx#xx + logger.debug(method + " oldKeyInfoMap: " + oldKeyInfoMap); - String oldMappingValue = config.getString(oldKeyInfoMap, null); + String oldMappingValue = sconfig.getString(oldKeyInfoMap, null); String oldSelectedToken = null; if (oldMappingValue == null) { - oldSelectedToken = config.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); + oldSelectedToken = sconfig.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); oldKeyNickName = req.getParameter(IRemoteRequest.TOKEN_KEYINFO); } else { StringTokenizer st = new StringTokenizer(oldMappingValue, ":"); @@ -1835,12 +1878,12 @@ private void processDiversifyKey(HttpServletRequest req, } - String newKeyInfoMap = "tks.mk_mappings." + rnewKeyInfo.substring(0,6); //#xx#xx + String newKeyInfoMap = "tks." + keySet + ".mk_mappings." + rnewKeyInfo.substring(0,6); //#xx#xx logger.debug(method + " newKeyInfoMap: " + newKeyInfoMap); - String newMappingValue = config.getString(newKeyInfoMap, null); + String newMappingValue = sconfig.getString(newKeyInfoMap, null); String newSelectedToken = null; if (newMappingValue == null) { - newSelectedToken = config.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); + newSelectedToken = sconfig.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); newKeyNickName = rnewKeyInfo; } else { StringTokenizer st = new StringTokenizer(newMappingValue, ":"); @@ -1853,16 +1896,23 @@ private void processDiversifyKey(HttpServletRequest req, " oldKeyNickName=" + oldKeyNickName + " newKeyNickName=" + newKeyNickName); - byte kekKeyArray[] = getDeveKeyArray("kek_key", config, keySet); - byte macKeyArray[] = getDeveKeyArray("auth_key", config, keySet); - byte encKeyArray[] = getDeveKeyArray("mac_key", config, keySet); + byte kekKeyArray[] = getDeveKeyArray("kek_key", sconfig, keySet); + byte macKeyArray[] = getDeveKeyArray("auth_key", sconfig, keySet); + byte encKeyArray[] = getDeveKeyArray("mac_key", sconfig, keySet); - // org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key")); + // org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key")); //GPParams for scp03 right now, reads some scp03 specific values from the config of a given keyset // passed down to the SecureChannelProtocol functions that deal with SCP03 GPParams gp3Params = readGPSettings(keySet); + + // ** G&D 256 Key Rollover Support ** + // need to use setting associated with the oldKeySet if provided + GPParams oldGp3Params = gp3Params; + if (oldKeySet != null) { + oldGp3Params = readGPSettings(oldKeySet); + } SecureChannelProtocol secProtocol = new SecureChannelProtocol(protocol); // AC: KDF SPEC CHANGE - check for error reading settings @@ -1877,7 +1927,8 @@ private void processDiversifyKey(HttpServletRequest req, nistSP800_108KdfUseCuidAsKdd, // AC: KDF SPEC CHANGE - pass in configuration file value xCUID, // AC: KDF SPEC CHANGE - removed duplicative 'CUID' variable and replaced with 'xCUID' xKDD, // AC: KDF SPEC CHANGE - pass in KDD so symkey can make decision about which value (KDD,CUID) to use - kekKeyArray,encKeyArray,macKeyArray, useSoftToken_s, keySet, (byte) protocol,gp3Params); + kekKeyArray,encKeyArray,macKeyArray, useSoftToken_s, keySet, (byte) protocol,gp3Params, + oldGp3Params); // ** G&D 256 Key Rollover Support ** add oldGp3Params parameter to the method call } else if (protocol == 2) { KeySetData = SessionKey.DiversifyKey(oldSelectedToken, newSelectedToken, oldKeyNickName, @@ -1889,10 +1940,12 @@ private void processDiversifyKey(HttpServletRequest req, logger.debug("TokenServlet.processDiversifyKey: New keyset data obtained"); if (KeySetData == null || KeySetData.length <= 1) { - logger.info("process DiversifyKey: Missing MasterKey in Slot"); + transactionLogger.log(ILogger.LL_INFO, "process DiversifyKey: Missing MasterKey in Slot"); } - logger.info("process DiversifyKey for CUID=" + + transactionLogger.log( + ILogger.LL_INFO, + "process DiversifyKey for CUID=" + trim(pp.toHexString(xCUID)) + // AC: KDF SPEC CHANGE: Log both CUID and KDD ", KDD=" + trim(pp.toHexString(xKDD)) @@ -1911,7 +1964,6 @@ private void processDiversifyKey(HttpServletRequest req, if (KeySetData != null && KeySetData.length > 1) { value = IRemoteRequest.RESPONSE_STATUS + "=0&" + IRemoteRequest.TKS_RESPONSE_KeySetData + "=" + org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(KeySetData); - //logger.debug("TokenServlet:process DiversifyKey.encode " + value); logger.debug("TokenServlet:process DiversifyKey.encode returning KeySetData"); // AC: KDF SPEC CHANGE - check for settings file issue (flag) } else if (missingSetting_exception != null) { @@ -1940,7 +1992,7 @@ private void processDiversifyKey(HttpServletRequest req, ooss.flush(); mRenderResult = false; } catch (Exception e) { - logger.warn("TokenServlet:process DiversifyKey: " + e.getMessage(), e); + logger.debug("TokenServlet:process DiversifyKey: " + e.toString()); } if (status.equals("0")) { @@ -1965,6 +2017,7 @@ private void processDiversifyKey(HttpServletRequest req, Boolean.toString(nistSP800_108KdfUseCuidAsKdd) // NistSP800_108KdfUseCuidAsKdd ); + Auditor auditor = engine.getAuditor(); auditor.log(event); } else { @@ -1989,6 +2042,7 @@ private void processDiversifyKey(HttpServletRequest req, errorMsg // Error ); + Auditor auditor = engine.getAuditor(); auditor.log(event); } } @@ -2010,12 +2064,9 @@ private void processEncryptData(HttpServletRequest req, String errorMsg = ""; String badParams = ""; - TKSEngine engine = TKSEngine.getInstance(); - JssSubsystem jssSubsystem = engine.getJSSSubsystem(); - Auditor auditor = engine.getAuditor(); + TKSEngineConfig sconfig = engine.getConfig(); - TKSEngineConfig config = engine.getConfig(); encryptedData = null; String rdata = req.getParameter(IRemoteRequest.TOKEN_DATA); String rKeyInfo = req.getParameter(IRemoteRequest.TOKEN_KEYINFO); @@ -2046,7 +2097,7 @@ private void processEncryptData(HttpServletRequest req, logger.debug("keySet selected: " + keySet); - String s_isRandom = config.getString("tks.EncryptData.isRandom", "true"); + String s_isRandom = sconfig.getString("tks.EncryptData.isRandom", "true"); if (s_isRandom.equalsIgnoreCase("false")) { logger.debug("TokenServlet: processEncryptData(): Random number not to be generated"); isRandom = false; @@ -2063,7 +2114,7 @@ private void processEncryptData(HttpServletRequest req, ILogger.SUCCESS, agentId, s_isRandom); - auditor.log(auditMessage); + audit(auditMessage); GPParams gp3Params = readGPSettings(keySet); @@ -2074,11 +2125,12 @@ private void processEncryptData(HttpServletRequest req, logger.debug("TokenServlet: processEncryptData(): contain data in request, however, random generation on TKS is required. Generating..."); } try { + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); SecureRandom random = jssSubsystem.getRandomNumberGenerator(); data = new byte[16]; random.nextBytes(data); } catch (Exception e) { - logger.warn("TokenServlet: processEncryptData():" + e.getMessage(), e); + logger.debug("TokenServlet: processEncryptData():" + e.toString()); badParams += " Random Number,"; missingParam = true; } @@ -2113,7 +2165,7 @@ private void processEncryptData(HttpServletRequest req, xkeyInfo = null; // avoid errors about non-initialization if (!missingParam) { - xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); + xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); if (xCUID == null || xCUID.length != 10) { badParams += " CUID length,"; logger.debug("TokenServlet: Invalid CUID length"); @@ -2121,14 +2173,14 @@ private void processEncryptData(HttpServletRequest req, } // AC: KDF SPEC CHANGE - read new KDD parameter from TPS - xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); + xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); if (xKDD == null || xKDD.length != 10) { badParams += " KDD length,"; logger.debug("TokenServlet: Invalid KDD length"); missingParam = true; } - xkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); + xkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); if (xkeyInfo == null || (xkeyInfo.length != 2 && xkeyInfo.length != 3)) { badParams += " KeyInfo length,"; logger.debug("TokenServlet: Invalid key info length"); @@ -2136,7 +2188,7 @@ private void processEncryptData(HttpServletRequest req, } } - String useSoftToken_s = config.getString("tks.useSoftToken", "true"); + String useSoftToken_s = sconfig.getString("tks.useSoftToken", "true"); if (!useSoftToken_s.equalsIgnoreCase("true")) useSoftToken_s = "false"; @@ -2166,17 +2218,18 @@ private void processEncryptData(HttpServletRequest req, // conform to the set-an-error-flag mentality } catch (Exception e) { missingSetting_exception = e; - logger.warn("TokenServlet: Exception reading Nist SP800-108 KDF config values: " + e.getMessage(), e); + logger.debug("TokenServlet: processEncryptData(): Exception reading Nist SP800-108 KDF config values: " + + e.toString()); } if (!isRandom) - data = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rdata); - keyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); + data = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rdata); + keyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); String keyInfoMap = "tks." + keySet + ".mk_mappings." + rKeyInfo.substring(0,6); - String mappingValue = config.getString(keyInfoMap, null); + String mappingValue = sconfig.getString(keyInfoMap, null); if (mappingValue == null) { - selectedToken = config.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); + selectedToken = sconfig.getString("tks.defaultSlot", CryptoUtil.INTERNAL_TOKEN_NAME); keyNickName = rKeyInfo; } else { StringTokenizer st = new StringTokenizer(mappingValue, ":"); @@ -2207,7 +2260,7 @@ private void processEncryptData(HttpServletRequest req, } byte kekKeyArray[] = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + keySet + ".kek_key")); + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key")); // AC: KDF SPEC CHANGE - check for error reading settings if (missingSetting_exception == null) { @@ -2236,7 +2289,8 @@ private void processEncryptData(HttpServletRequest req, // AC: KDF SPEC CHANGE - Log both CUID and KDD - logger.info("process EncryptData for CUID=" + + transactionLogger.log( + ILogger.LL_INFO, "process EncryptData for CUID=" + trim(pp.toHexString(xCUID)) + ", KDD=" + trim(pp.toHexString(xKDD))); @@ -2285,7 +2339,7 @@ private void processEncryptData(HttpServletRequest req, ooss.flush(); mRenderResult = false; } catch (Exception e) { - logger.warn("TokenServlet: " + e.getMessage(), e); + logger.debug("TokenServlet: " + e.toString()); } if (status.equals("0")) { @@ -2306,6 +2360,7 @@ private void processEncryptData(HttpServletRequest req, Boolean.toString(nistSP800_108KdfUseCuidAsKdd) // NistSP800_108KdfUseCuidAsKdd ); + Auditor auditor = engine.getAuditor(); auditor.log(event); } else { @@ -2326,7 +2381,8 @@ private void processEncryptData(HttpServletRequest req, Boolean.toString(nistSP800_108KdfUseCuidAsKdd), // NistSP800_108KdfUseCuidAsKdd errorMsg // Error ); - + + Auditor auditor = engine.getAuditor(); auditor.log(event); } } @@ -2360,10 +2416,6 @@ private void processComputeRandomData(HttpServletRequest req, SessionContext sContext = SessionContext.getContext(); - TKSEngine engine = TKSEngine.getInstance(); - JssSubsystem jssSubsystem = engine.getJSSSubsystem(); - Auditor auditor = engine.getAuditor(); - String agentId = ""; if (sContext != null) { agentId = @@ -2381,7 +2433,7 @@ private void processComputeRandomData(HttpServletRequest req, try { dataSize = Integer.parseInt(sDataSize.trim()); } catch (NumberFormatException nfe) { - logger.warn("TokenServlet::processComputeRandomData invalid data size input: " + nfe.getMessage(), nfe); + logger.debug("TokenServlet::processComputeRandomData invalid data size input!"); badParams += " Random Data size, "; missingParam = true; status = "1"; @@ -2396,15 +2448,17 @@ private void processComputeRandomData(HttpServletRequest req, ILogger.SUCCESS, agentId); - auditor.log(auditMessage); + audit(auditMessage); if (!missingParam) { try { + TKSEngine engine = TKSEngine.getInstance(); + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); SecureRandom random = jssSubsystem.getRandomNumberGenerator(); randomData = new byte[dataSize]; random.nextBytes(randomData); } catch (Exception e) { - logger.warn("TokenServlet::processComputeRandomData:" + e.getMessage(), e); + logger.debug("TokenServlet::processComputeRandomData:" + e.toString()); errorMsg = "Can't generate random data!"; status = "2"; } @@ -2446,9 +2500,12 @@ private void processComputeRandomData(HttpServletRequest req, ooss.flush(); mRenderResult = false; } catch (Exception e) { - logger.warn("TokenServlet::processComputeRandomData " + e.getMessage(), e); + logger.debug("TokenServlet::processComputeRandomData " + e.toString()); } + TKSEngine engine = TKSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); + if (status.equals("0")) { ComputeRandomDataRequestProcessedEvent event = ComputeRandomDataRequestProcessedEvent.success( status, @@ -2466,7 +2523,6 @@ private void processComputeRandomData(HttpServletRequest req, } } - @Override public void process(CMSRequest cmsReq) throws EBaseException { HttpServletRequest req = cmsReq.getHttpReq(); HttpServletResponse resp = cmsReq.getHttpResp(); @@ -2495,7 +2551,7 @@ public void process(CMSRequest cmsReq) throws EBaseException { ooss.flush(); mRenderResult = false; } catch (Exception e) { - logger.warn("TokenServlet: " + e.getMessage(), e); + logger.debug("TokenServlet: " + e.toString()); } // cmsReq.setStatus(CMSRequest.UNAUTHORIZED); @@ -2541,6 +2597,7 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR String errorMsg = ""; String badParams = ""; String transportKeyName = ""; + String rCUID = req.getParameter(IRemoteRequest.TOKEN_CUID); String rKDD = req.getParameter("KDD"); @@ -2561,8 +2618,7 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR boolean serversideKeygen = false; TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); - Auditor auditor = engine.getAuditor(); + TKSEngineConfig sconfig = engine.getConfig(); boolean isCryptoValidate = true; boolean missingParam = false; @@ -2590,15 +2646,15 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR ILogger.SUCCESS, agentId); - auditor.log(auditMessage); + audit(auditMessage); String kek_wrapped_desKeyString = null; - String kek_wrapped_aesKeyString = null; + String kek_wrapped_aesKeyString = null; String keycheck_s = null; - String keycheck_aes_s = null; + String keycheck_aes_s = null; - String useSoftToken_s = config.getString("tks.useSoftToken", "true"); + String useSoftToken_s = sconfig.getString("tks.useSoftToken", "true"); if (!useSoftToken_s.equalsIgnoreCase("true")) useSoftToken_s = "false"; @@ -2613,13 +2669,13 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR logger.debug(method + " serversideKeygen: " + serversideKeygen); try { - isCryptoValidate = config.getBoolean("cardcryptogram.validate.enable", true); + isCryptoValidate = sconfig.getBoolean("cardcryptogram.validate.enable", true); } catch (EBaseException eee) { } logger.debug(method + " Do crypto validation: " + isCryptoValidate); - transportKeyName = getSharedSecretName(config); + transportKeyName = getSharedSecretName(sconfig); String rcard_challenge = req.getParameter(IRemoteRequest.TOKEN_CARD_CHALLENGE); String rhost_challenge = req.getParameter(IRemoteRequest.TOKEN_HOST_CHALLENGE); @@ -2673,28 +2729,28 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR xhost_challenge = null; if (!missingParam) { - xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); + xCUID = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rCUID); if (xCUID == null || xCUID.length != 10) { badParams += " CUID length,"; logger.debug("TokenServlet: Invalid CUID length"); missingParam = true; } - xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); + xKDD = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKDD); if (xKDD == null || xKDD.length != 10) { badParams += " KDD length,"; logger.debug("TokenServlet: Invalid KDD length"); missingParam = true; } - xkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); + xkeyInfo = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rKeyInfo); if (xkeyInfo == null || xkeyInfo.length != 3) { badParams += " KeyInfo length,"; logger.debug("TokenServlet: Invalid key info length."); missingParam = true; } xcard_challenge = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_challenge); + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_challenge); if (xcard_challenge == null || xcard_challenge.length != 8) { badParams += " card_challenge length,"; logger.debug("TokenServlet: Invalid card challenge length."); @@ -2718,11 +2774,12 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR host_challenge = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rhost_challenge); String keyInfoMap = "tks." + keySet + ".mk_mappings." + rKeyInfo.substring(0,6); //#xx#xx - String mappingValue = config.getString(keyInfoMap, null); + String mappingValue = sconfig.getString(keyInfoMap, null); if (mappingValue == null) { - selectedToken = config.getString("tks.defaultSlot", "internal"); + selectedToken = + sconfig.getString("tks.defaultSlot", "internal"); keyNickName = rKeyInfo; } else { StringTokenizer st = new StringTokenizer(mappingValue, ":"); @@ -2744,11 +2801,16 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR try { byte macKeyArray[] = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".mac_key")); logger.debug("TokenServlet about to try ComputeSessionKey selectedToken=" + selectedToken + " keyNickName=" + keyNickName); + SecureChannelProtocol.debugByteArray(macKeyArray, method + " macKeyArray: " + macKeyArray.length); + SecureChannelProtocol.debugByteArray(xKDD, method + " xKDD: " + xKDD.length); + SecureChannelProtocol.debugByteArray(xhost_challenge, method + " xhost_challenge: " + xhost_challenge.length); + SecureChannelProtocol.debugByteArray(xcard_challenge, method + " xcard_challenge: " + xcard_challenge.length); + SecureChannelProtocol protocol = new SecureChannelProtocol(SecureChannelProtocol.PROTOCOL_THREE); macSessionKey = protocol.computeSessionKey_SCP03(selectedToken, keyNickName,xkeyInfo, @@ -2758,13 +2820,13 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR mac_session_key = protocol.wrapSessionKey(selectedToken, macSessionKey, null); if (mac_session_key == null) { - logger.error(method + " Can't get mac session key bytes"); + logger.debug(method + " Can't get mac session key bytes"); throw new Exception(method + " Can't get mac session key bytes"); } byte encKeyArray[] = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".auth_key")); encSessionKey = protocol.computeSessionKey_SCP03(selectedToken, keyNickName,xkeyInfo, @@ -2774,13 +2836,13 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR enc_session_key = protocol.wrapSessionKey(selectedToken, encSessionKey, null); if (enc_session_key == null) { - logger.error("TokenServlet:Tried ComputeEncSessionKey, got NULL "); + logger.debug("TokenServlet:Tried ComputeEncSessionKey, got NULL "); throw new Exception("Can't compute enc session key!"); } byte kekKeyArray[] = - org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(config.getString("tks." + org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." + keySet + ".kek_key")); kekSessionKey = protocol.computeSessionKey_SCP03(selectedToken, keyNickName, xkeyInfo, @@ -2790,7 +2852,6 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR kek_session_key = protocol.wrapSessionKey(selectedToken, kekSessionKey, null); - //Offload some of the tedious params gathering to another method //ToDo, create a method that reads all this stuff at once for all major methods if (serversideKeygen) { @@ -2798,12 +2859,14 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR serverSideValues = calculateServerSideKeygenValues(useSoftToken_s, selectedToken, kekSessionKey, protocol); } catch (EBaseException e) { - logger.warn(method + " Can't calcualte server side keygen required values: " + e.getMessage(), e); + + logger.debug(method + " Can't calculate server side keygen required values..."); + } } try { - isCryptoValidate = config.getBoolean("cardcryptogram.validate.enable", true); + isCryptoValidate = sconfig.getBoolean("cardcryptogram.validate.enable", true); } catch (EBaseException eee) { } @@ -2816,19 +2879,20 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR } host_cryptogram = protocol.computeCryptogram_SCP03(macSessionKey, selectedToken, contextStream.toByteArray(),NistSP800_108KDF.HOST_CRYPTO_KDF_CONSTANT); + //logger.debug("TokenServlet: NistSP800_108KDF.HOST_CRYPTO_KDF_CONSTANT = " + NistSP800_108KDF.HOST_CRYPTO_KDF_CONSTANT); //SecureChannelProtocol.debugByteArray(host_cryptogram, method + " calculated host crypto: " + host_cryptogram.length); - if( isCryptoValidate) { if (rcard_cryptogram == null) { - logger.error(method + " missing card cryptogram"); + logger.debug(method + " missing card cryptogram"); throw new Exception(method + "Missing card cryptogram"); } input_card_crypto = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(rcard_cryptogram); + card_crypto = protocol.computeCryptogram_SCP03(macSessionKey, selectedToken, contextStream.toByteArray(),NistSP800_108KDF.CARD_CRYPTO_KDF_CONSTANT); - //SecureChannelProtocol.debugByteArray(card_crypto, method + " calculated card crypto: "); - //SecureChannelProtocol.debugByteArray(input_card_crypto, method + " original card crypto: "); + SecureChannelProtocol.debugByteArray(card_crypto, method + " calculated card crypto: "); + SecureChannelProtocol.debugByteArray(input_card_crypto, method + " original card crypto: "); if(!cryptoGramsAreEqual(input_card_crypto, card_crypto)) { throw new Exception(method + "Card cryptogram mismatch!"); @@ -2836,7 +2900,7 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR } } catch (Exception e) { - logger.warn("TokenServlet Computing Session Key: " + e.getMessage(), e); + logger.debug("TokenServlet Computing Session Key: " + e.toString()); if (isCryptoValidate) sameCardCrypto = false; } @@ -2883,7 +2947,7 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR // 3 : trans wrapped des key // 4 : trans wrapped aes key // 5 : kek wrapped aes key - + //Values above returned by routine to calculate server side keygen values. if (serversideKeygen == true) { logger.debug(method + " serversideValues.size: " + serverSideValues.size()); @@ -2896,6 +2960,7 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR //Get the value produced even for SC03 . drm_trans_wrapped_desKeyString = serverSideValues.get(3); + kek_wrapped_desKeyString = serverSideValues.get(0); keycheck_s = serverSideValues.get(1); keycheck_aes_s = serverSideValues.get(2); @@ -2908,7 +2973,7 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR if(serverSideValues.size() >= 6) { logger.debug(method + " size >= 6"); kek_wrapped_aesKeyString = serverSideValues.get(5); - //logger.debug(method + "kek_wrapped_aesKeyString: " + kek_wrapped_aesKeyString); + //logger.debug(method + "kek_wrapped_aesKeyString: " + kek_wrapped_aesKeyString); } } else { @@ -2994,6 +3059,8 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR sb.append(kek_wrapped_aesKeyString); sb.append("&" + IRemoteRequest.TKS_RESPONSE_KeyCheck + "="); sb.append(keycheck_aes_s); + sb.append("&" + IRemoteRequest.TKS_RESPONSE_KeyCheck_Des + "="); // Applet and Alg Selection by Token Range Support + sb.append(keycheck_s); // Applet and Alg Selection by Token Range Support sb.append("&" + IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey + "="); sb.append(drm_trans_wrapped_desKeyString); sb.append("&" + IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey + "="); @@ -3010,6 +3077,7 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR sb.append("&" + IRemoteRequest.TKS_RESPONSE_EncSessionKey + "="); sb.append(encSessionKeyString); sb.append("&" + IRemoteRequest.TKS_RESPONSE_KekSessionKey + "="); + sb.append(kekSessionKeyString); value = sb.toString(); } @@ -3024,9 +3092,11 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR ooss.flush(); mRenderResult = false; } catch (IOException e) { - logger.warn("TokenServlet: " + e.getMessage(), e); + logger.debug("TokenServlet: " + e.toString()); } + Auditor auditor = engine.getAuditor(); + if (status.equals("0")) { ComputeSessionKeyRequestProcessedEvent event = ComputeSessionKeyRequestProcessedEvent.success( log_string_from_specialDecoded_byte_array(xCUID), // CUID_decoded @@ -3073,7 +3143,6 @@ private void processComputeSessionKeysSCP03(HttpServletRequest req, HttpServletR * @param req HTTP request * @param resp HTTP response */ - @Override public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.service(req, resp); @@ -3082,11 +3151,12 @@ public void service(HttpServletRequest req, HttpServletResponse resp) private PK11SymKey getSharedSecretKey() throws EBaseException, NotInitializedException { TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); + TKSEngineConfig configStore = engine.getConfig(); + String sharedSecretName = null; try { - sharedSecretName = getSharedSecretName(config); + sharedSecretName = getSharedSecretName(configStore); } catch (EBaseException e) { throw new EBaseException("TokenServlet.getSharedSecetKey: Internal error finding config value: " @@ -3103,7 +3173,7 @@ private PK11SymKey getSharedSecretKey() throws EBaseException, NotInitializedExc logger.debug("TokenServlet.getSharedSecretTransportKey: symmKeys List: " + symmKeys); } catch (Exception e) { // TODO Auto-generated catch block - logger.warn("TokenServlet: " + e.getMessage(), e); + logger.debug(e.toString()); } for (String keyName : symmKeys.split(",")) { @@ -3136,14 +3206,16 @@ private PK11SymKey getSharedSecretKey() throws EBaseException, NotInitializedExc // 3 : trans wrapped des key // 4 : trans wrapped aes key // 5 : kek wrapped aes key + private ArrayList calculateServerSideKeygenValues(String useSoftToken, String selectedToken, SymmetricKey kekSessionKey, SecureChannelProtocol protocol) throws EBaseException { SymmetricKey desKey = null; SymmetricKey aesKey = null; String method = "TokenServlet.calculateSErverSideKeygenValues: "; - ArrayList values = new ArrayList<>(); - int protocolLevel = protocol.getProtocol(); + ArrayList values = new ArrayList(); + int protocolLevel = protocol.getProtocol(); + /** * 0. generate des key @@ -3172,9 +3244,12 @@ private ArrayList calculateServerSideKeygenValues(String useSoftToken, S if (useSoftToken.equals("true")) { logger.debug(method + " key encryption key generated on internal"); desKey = protocol.generateSymKey("internal"); - if(protocolLevel == 3) { + //128 for now until we implement the full > 128 aes funcionality. + if(protocolLevel == 3) { + //still do the des key as a backup later aesKey = protocol.generateAESSymKey("internal",128); } + //cfu audit here? sym key gen done } else { logger.debug("TokenServlet: key encryption key generated on " + selectedToken); @@ -3183,14 +3258,13 @@ private ArrayList calculateServerSideKeygenValues(String useSoftToken, S aesKey = protocol.generateAESSymKey(selectedToken,128); } } - - if (desKey == null && protocolLevel == 1) { + if (desKey == null && protocolLevel == 1) { throw new EBaseException(method + "can't generate DES key encryption key"); - } + } - if (aesKey == null && protocolLevel == 3) { + if (aesKey == null && protocolLevel == 3) { throw new EBaseException(method + "can't generate AES key encryption key"); - } + } /* * ECBencrypt actually takes the 24 byte DES2 key @@ -3198,23 +3272,25 @@ private ArrayList calculateServerSideKeygenValues(String useSoftToken, S * This is done so that the applet can digest it */ - - /* Now that ecbEncrypt() can handle AES keys, + /* Now that ecbEncrypt() can handle AES keys, * in case it's an AES key, it simply * wraps the AES key with KEK and returns * the encrypted byte array */ - byte[] encDesKey = protocol.ecbEncrypt(kekSessionKey, desKey, selectedToken); - byte[] encAesKey = protocol.ecbEncrypt(kekSessionKey, aesKey, selectedToken); + // protocol.wrapSessionKey(tokenName, sessionKey, wrappingKey) + + byte[] encDesKey = protocol.ecbEncrypt(kekSessionKey, desKey, selectedToken); + byte[] encAesKey = protocol.ecbEncrypt(kekSessionKey,aesKey,selectedToken); String kek_wrapped_desKeyString = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(encDesKey); - //logger.debug(method + "kek_wrapped_desKeyString: " + kek_wrapped_desKeyString); + String kek_wrapped_aesKeyString = + org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(encAesKey); + +// logger.debug(method + "kek_wrapped_desKeyString: " + kek_wrapped_desKeyString); - String kek_wrapped_aesKeyString = - org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(encAesKey); values.add(kek_wrapped_desKeyString); // get keycheck @@ -3222,10 +3298,8 @@ private ArrayList calculateServerSideKeygenValues(String useSoftToken, S byte[] keycheck = null; byte[] keycheck_aes = null; - //Calculate both keycheck and keycheck_aes and later use which one is needed. keycheck = protocol.computeKeyCheck(desKey, selectedToken); - - if(aesKey != null) { + if(aesKey != null) { logger.debug(method + "About to compute keycheck scp03"); keycheck_aes = protocol.computeKeyCheck_SCP03(aesKey, selectedToken); } @@ -3233,23 +3307,32 @@ private ArrayList calculateServerSideKeygenValues(String useSoftToken, S String keycheck_s = ""; String keycheck_aes_s = ""; - if(keycheck != null) { - keycheck_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(keycheck); + if(keycheck != null) { + keycheck_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(keycheck); + } + + if(keycheck_aes != null) { + keycheck_aes_s = org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(keycheck_aes); } + + // logger.debug(method + "keycheck_s " + keycheck_s); + values.add(keycheck_s); - values.add(keycheck_aes_s); + values.add(keycheck_aes_s); - //use DRM transport cert to wrap session key TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); - String drmTransNickname = config.getString("tks.drm_transport_cert_nickname", ""); + TKSEngineConfig sconfig = engine.getConfig(); + + //use DRM transport cert to wrap desKey + String drmTransNickname = sconfig.getString("tks.drm_transport_cert_nickname", ""); if ((drmTransNickname == null) || (drmTransNickname == "")) { - logger.error(method + " did not find DRM transport certificate nickname"); + logger.debug(method + " did not find DRM transport certificate nickname"); throw new EBaseException(method + "can't find DRM transport certificate nickname"); + } else { + logger.debug(method + " drmtransport_cert_nickname=" + drmTransNickname); } - logger.debug(method + " drmtransport_cert_nickname=" + drmTransNickname); X509Certificate drmTransCert = null; try { @@ -3272,15 +3355,14 @@ private ArrayList calculateServerSideKeygenValues(String useSoftToken, S keyWrapper = token.getKeyWrapper(KeyWrapAlgorithm.AES_ECB); keyWrapper.initWrap(pubKey, null); } else { - - boolean useOAEP = config.getUseOAEPKeyWrap(); + boolean useOAEP = sconfig.getBoolean("keyWrap.useOAEP",false); KeyWrapAlgorithm wrapAlg = KeyWrapAlgorithm.RSA; if(useOAEP == true) { wrapAlg = KeyWrapAlgorithm.RSA_OAEP; } keyWrapper = token.getKeyWrapper(wrapAlg); - OAEPParameterSpec params = null; + OAEPParameterSpec params = null; if(useOAEP == true) { params = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT); } @@ -3297,12 +3379,11 @@ private ArrayList calculateServerSideKeygenValues(String useSoftToken, S byte[] drm_trans_wrapped_aesKey = keyWrapper.wrap(aesKey); String drmWrappedAesStr = - org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(drm_trans_wrapped_aesKey); + org.mozilla.jss.netscape.security.util.Utils.SpecialEncode(drm_trans_wrapped_aesKey); //logger.debug(method + " drmWrappedAesStr: " + drmWrappedAesStr); values.add(drmWrappedAesStr); values.add(kek_wrapped_aesKeyString); - } catch (Exception e) { throw new EBaseException(e); } @@ -3340,10 +3421,11 @@ static GPParams readGPSettings(String keySet) { String gp3Settings = "tks." + keySet + ".prot3"; TKSEngine engine = TKSEngine.getInstance(); - TKSEngineConfig config = engine.getConfig(); + TKSEngineConfig sconfig = engine.getConfig(); + String divers = "emv"; try { - divers = config.getString(gp3Settings + ".divers", "emv"); + divers = sconfig.getString(gp3Settings + ".divers", "emv"); } catch (EBaseException e) { } @@ -3354,7 +3436,7 @@ static GPParams readGPSettings(String keySet) { String diversVer1Keys = "emv"; try { - diversVer1Keys = config.getString(gp3Settings + ".diversVer1Keys","emv"); + diversVer1Keys = sconfig.getString(gp3Settings + ".diversVer1Keys","emv"); } catch (EBaseException e) { } @@ -3363,7 +3445,7 @@ static GPParams readGPSettings(String keySet) { String keyType = null; try { - keyType = config.getString(gp3Settings + ".devKeyType","DES3"); + keyType = sconfig.getString(gp3Settings + ".devKeyType","DES3"); } catch (EBaseException e) { } @@ -3372,7 +3454,7 @@ static GPParams readGPSettings(String keySet) { params.setDevKeyType(keyType); try { - keyType = config.getString(gp3Settings + ".masterKeyType","DES3"); + keyType = sconfig.getString(gp3Settings + ".masterKeyType","DES3"); } catch (EBaseException e) { } @@ -3384,7 +3466,7 @@ static GPParams readGPSettings(String keySet) { return params; } - private byte[] getDeveKeyArray(String keyType, ConfigStore sconfig, String keySet) throws EBaseException { + private byte[] getDeveKeyArray(String keyType,ConfigStore sconfig,String keySet) throws EBaseException { byte devKeyArray[] = null; try { devKeyArray = org.mozilla.jss.netscape.security.util.Utils.SpecialDecode(sconfig.getString("tks." @@ -3396,5 +3478,9 @@ private byte[] getDeveKeyArray(String keyType, ConfigStore sconfig, String keySe return devKeyArray; } - + private void audit(String msg) { + TKSEngine engine = TKSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); + auditor.log(msg); + } } diff --git a/base/tps/shared/applets/1.5.65cbf5a6.ijc b/base/tps/shared/applets/1.5.65cbf5a6.ijc new file mode 100644 index 00000000000..ac27c4646fc Binary files /dev/null and b/base/tps/shared/applets/1.5.65cbf5a6.ijc differ diff --git a/base/tps/shared/conf/CS.cfg b/base/tps/shared/conf/CS.cfg index 876d88c076a..7fdf7e10277 100644 --- a/base/tps/shared/conf/CS.cfg +++ b/base/tps/shared/conf/CS.cfg @@ -8,15 +8,26 @@ archive.configuration_file=true applet._000=######################################### applet._001=# applet information applet._002=# SAF Key: -applet._003=# applet.aid.cardmgr_instance=A0000001510000 -applet._004=# Stock RSA,KeyRecover applet : 1.4.58768072.ijc +applet._003=# applet.aid.cardmgr_instance=A0000001510000,A000000003000000,A0000001510000 +applet._004=# Stock RSA,KeyRecover applet : 1.4.58768072.ijc applet._005=# RSA/KeyRecovery/GP211/SCP02, SCP03 applet : 1.5.558cdcff.ijc -applet._006=# SCP03 AES server side keygen keywrap applet : 1.5.64260792.ijc -applet._007=# Use GP211 applet only with SCP02 card -applet._008=# For protocol > 1 do this ex: proto 3 : op.format.userKey.update.applet.requiredVersion.prot.3=1.5.558cdcff, 1.5.64260792.ijc for AES keywrap -applet._009=# Use existing config for standard proto1 cards ex: op.format.userKey.update.applet.requiredVersion=1.4.58768072 -applet._010=######################################### -applet.aid.cardmgr_instance=A0000000030000 +applet._006=# SCP03 AES server side keygen keywrap applet :1.5.65cbf5a6.ijc +applet._007=# Use GP211 applet only with SCP03 card +applet._008=# Set the applet for scp03 tokens as follows: +applet._009=# Examples: +applet._010=#Format: +applet._011=#op.format.userKey.update.applet.requiredVersion.prot.3=1.5.65cbf5a6.ijc +applet._012=# Enrollment: +applet._013=#op.enroll.userKey.update.applet.requiredVersion.prot.3=1.5.65cbf5a6.ijc +applet._014=# Pin Reset: +applet._015=#op.pinReset.userKey.update.applet.requiredVersion.prot.3=1.5.65cbf5a6.ijc +applet._016=# +applet._017=# The applet above is the latest and supports CBC and KWP key wrapping. +applet._018=# Use existing config for standard protoco1 cards Example: applet._019=#op.format.userKey.update.applet.requiredVersion=1.4.58768072 +applet._019=# Add ,A000000003000000,A0000001510000 to all instances of *.cardmgr_instance parameters in the CS.cfg file as shown below. Update all format, enroll and pin reset values for every token type in the file. This is to support some newer cards such as the Cosmo Idemia, allowing the code to select the proper AID at run time. +applet._020=# New enroll param for scp03 / AES applet only priv key unrap onto token algorithm: op.enroll.userKey.keyGen.aesKeyWrapAlg=CBC, KWP or DES. +applet._021=######################################### +applet.aid.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 applet.aid.netkey_file=627601FF0000 applet.aid.netkey_instance=627601FF000000 applet.aid.netkey_old_file=A000000001 @@ -280,7 +291,7 @@ op.enroll.delegateIEtoken.maximumGPKeyVersion=FF op.enroll.delegateIEtoken.rollbackKeyVersionOnPutKeyFailure=false op.enroll.delegateIEtoken.validateCardKeyInfoAgainstTokenDB=true op.enroll.delegateIEtoken.auth.id=ldap1 -op.enroll.delegateIEtoken.cardmgr_instance=A0000000030000 +op.enroll.delegateIEtoken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.enroll.delegateIEtoken.issuerinfo.enable=true op.enroll.delegateIEtoken.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.enroll.delegateIEtoken.keyGen.authentication.SANpattern=$auth.exec-edipi$.$auth.exec-pcc$@EXAMPLE.com @@ -436,7 +447,7 @@ op.format.delegateIEtoken.rollbackKeyVersionOnPutKeyFailure=false op.format.delegateIEtoken.validateCardKeyInfoAgainstTokenDB=true op.format.delegateIEtoken.auth.id=ldap1 op.format.delegateIEtoken.ca.conn=ca1 -op.format.delegateIEtoken.cardmgr_instance=A0000000030000 +op.format.delegateIEtoken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.delegateIEtoken.issuerinfo.enable=true op.format.delegateIEtoken.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.format.delegateIEtoken.loginRequest.enable=true @@ -463,7 +474,7 @@ op.enroll.delegateISEtoken.maximumGPKeyVersion=FF op.enroll.delegateISEtoken.rollbackKeyVersionOnPutKeyFailure=false op.enroll.delegateISEtoken.validateCardKeyInfoAgainstTokenDB=true op.enroll.delegateISEtoken.auth.id=ldap1 -op.enroll.delegateISEtoken.cardmgr_instance=A0000000030000 +op.enroll.delegateISEtoken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.enroll.delegateISEtoken.issuerinfo.enable=true op.enroll.delegateISEtoken.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.enroll.delegateISEtoken.keyGen.authentication.SANpattern=$auth.exec-edipi$.$auth.exec-pcc$@EXAMPLE.com @@ -734,7 +745,7 @@ op.format.delegateISEtoken.rollbackKeyVersionOnPutKeyFailure=false op.format.delegateISEtoken.validateCardKeyInfoAgainstTokenDB=true op.format.delegateISEtoken.auth.id=ldap1 op.format.delegateISEtoken.ca.conn=ca1 -op.format.delegateISEtoken.cardmgr_instance=A0000000030000 +op.format.delegateISEtoken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.delegateISEtoken.issuerinfo.enable=true op.format.delegateISEtoken.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.format.delegateISEtoken.loginRequest.enable=true @@ -758,7 +769,7 @@ op.enroll.externalRegAddToToken.maximumGPKeyVersion=FF op.enroll.externalRegAddToToken.rollbackKeyVersionOnPutKeyFailure=false op.enroll.externalRegAddToToken.validateCardKeyInfoAgainstTokenDB=true op.enroll.externalRegAddToToken.auth.id=ldap1 -op.enroll.externalRegAddToToken.cardmgr_instance=A0000000030000 +op.enroll.externalRegAddToToken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.enroll.externalRegAddToToken.issuerinfo.enable=true op.enroll.externalRegAddToToken.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.enroll.externalRegAddToToken.keyGen.encryption.ca.conn=ca1 @@ -830,7 +841,7 @@ op.format.externalRegAddToToken.rollbackKeyVersionOnPutKeyFailure=false op.format.externalRegAddToToken.validateCardKeyInfoAgainstTokenDB=true op.format.externalRegAddToToken.auth.id=ldap1 op.format.externalRegAddToToken.ca.conn=ca1 -op.format.externalRegAddToToken.cardmgr_instance=A0000000030000 +op.format.externalRegAddToToken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.externalRegAddToToken.issuerinfo.enable=true op.format.externalRegAddToToken.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.format.externalRegAddToToken.loginRequest.enable=true @@ -846,7 +857,7 @@ op.format.externalRegAddToToken.update.symmetricKeys.requiredVersion=1 op.format.externalRegISEtoken.auth.enable=true op.format.externalRegISEtoken.auth.id=ldap1 op.format.externalRegISEtoken.ca.conn=ca1 -op.format.externalRegISEtoken.cardmgr_instance=A0000000030000 +op.format.externalRegISEtoken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.externalRegISEtoken.cuidMustMatchKDD=false op.format.externalRegISEtoken.enableBoundedGPKeyVersion=true op.format.externalRegISEtoken.issuerinfo.enable=true @@ -872,7 +883,7 @@ op.enroll.externalRegISEtoken._003=# controlled by registration user record op.enroll.externalRegISEtoken._004=######################################### op.enroll.externalRegISEtoken.auth.enable=true op.enroll.externalRegISEtoken.auth.id=ldap1 -op.enroll.externalRegISEtoken.cardmgr_instance=A0000000030000 +op.enroll.externalRegISEtoken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.enroll.externalRegISEtoken.cuidMustMatchKDD=false op.enroll.externalRegISEtoken.enableBoundedGPKeyVersion=true op.enroll.externalRegISEtoken.issuerinfo.enable=true @@ -1154,7 +1165,7 @@ op.enroll.soKey.rollbackKeyVersionOnPutKeyFailure=false op.enroll.soKey.validateCardKeyInfoAgainstTokenDB=true op.enroll.soKey.auth.enable=true op.enroll.soKey.auth.id=ldap1 -op.enroll.soKey.cardmgr_instance=A0000000030000 +op.enroll.soKey.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.enroll.soKey.issuerinfo.enable=true op.enroll.soKey.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.enroll.soKey.keyGen.encryption.ca.conn=ca1 @@ -1307,7 +1318,7 @@ op.enroll.soKeyTemporary.rollbackKeyVersionOnPutKeyFailure=false op.enroll.soKeyTemporary.validateCardKeyInfoAgainstTokenDB=true op.enroll.soKeyTemporary.auth.enable=true op.enroll.soKeyTemporary.auth.id=ldap1 -op.enroll.soKeyTemporary.cardmgr_instance=A0000000030000 +op.enroll.soKeyTemporary.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.enroll.soKeyTemporary.keyGen.auth.ca.conn=ca1 op.enroll.soKeyTemporary.keyGen.auth.ca.profileId=caTempTokenDeviceKeyEnrollment op.enroll.soKeyTemporary.keyGen.auth.certAttrId=c0 @@ -1478,7 +1489,7 @@ op.enroll.userKey.rollbackKeyVersionOnPutKeyFailure=false op.enroll.userKey.validateCardKeyInfoAgainstTokenDB=true op.enroll.userKey.auth.enable=true op.enroll.userKey.auth.id=ldap1 -op.enroll.userKey.cardmgr_instance=A0000000030000 +op.enroll.userKey.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.enroll.userKey.issuerinfo.enable=true op.enroll.userKey.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.enroll.userKey.keyGen.encryption.ca.conn=ca1 @@ -1644,7 +1655,7 @@ op.enroll.userKey.renewal.signing.gracePeriod.before=30 op.enroll.userKey.renewal.signing.gracePeriod.enable=false op.enroll.userKeyTemporary.auth.enable=true op.enroll.userKeyTemporary.auth.id=ldap1 -op.enroll.userKeyTemporary.cardmgr_instance=A0000000030000 +op.enroll.userKeyTemporary.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.enroll.userKeyTemporary.keyGen.auth.ca.conn=ca1 op.enroll.userKeyTemporary.keyGen.auth.ca.profileId=caTempTokenDeviceKeyEnrollment op.enroll.userKeyTemporary.keyGen.auth.certAttrId=c0 @@ -1823,7 +1834,7 @@ op.format.cleanToken.validateCardKeyInfoAgainstTokenDB=true op.format.cleanToken.auth.enable=false op.format.cleanToken.auth.id=ldap1 op.format.cleanToken.ca.conn=ca1 -op.format.cleanToken.cardmgr_instance=A0000000030000 +op.format.cleanToken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.cleanToken.issuerinfo.enable=true op.format.cleanToken.issuerinfo.value= op.format.cleanToken.loginRequest.enable=true @@ -1845,7 +1856,7 @@ op.format.soCleanSOToken.validateCardKeyInfoAgainstTokenDB=true op.format.soCleanSOToken.auth.enable=false op.format.soCleanSOToken.auth.id=ldap1 op.format.soCleanSOToken.ca.conn=ca1 -op.format.soCleanSOToken.cardmgr_instance=A0000000030000 +op.format.soCleanSOToken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.soCleanSOToken.issuerinfo.enable=true op.format.soCleanSOToken.issuerinfo.value= op.format.soCleanSOToken.loginRequest.enable=false @@ -1867,7 +1878,7 @@ op.format.soCleanUserToken.validateCardKeyInfoAgainstTokenDB=true op.format.soCleanUserToken.auth.enable=false op.format.soCleanUserToken.auth.id=ldap1 op.format.soCleanUserToken.ca.conn=ca1 -op.format.soCleanUserToken.cardmgr_instance=A0000000030000 +op.format.soCleanUserToken.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.soCleanUserToken.issuerinfo.enable=true op.format.soCleanUserToken.issuerinfo.value= op.format.soCleanUserToken.loginRequest.enable=false @@ -1889,7 +1900,7 @@ op.format.soKey.validateCardKeyInfoAgainstTokenDB=true op.format.soKey.auth.enable=true op.format.soKey.auth.id=ldap1 op.format.soKey.ca.conn=ca1 -op.format.soKey.cardmgr_instance=A0000000030000 +op.format.soKey.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.soKey.issuerinfo.enable=true op.format.soKey.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.format.soKey.loginRequest.enable=true @@ -1911,7 +1922,7 @@ op.format.soUserKey.validateCardKeyInfoAgainstTokenDB=true op.format.soUserKey.auth.enable=false op.format.soUserKey.auth.id=ldap1 op.format.soUserKey.ca.conn=ca1 -op.format.soUserKey.cardmgr_instance=A0000000030000 +op.format.soUserKey.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.soUserKey.issuerinfo.enable=true op.format.soUserKey.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.format.soUserKey.loginRequest.enable=false @@ -1933,7 +1944,7 @@ op.format.tokenKey.validateCardKeyInfoAgainstTokenDB=true op.format.tokenKey.auth.enable=true op.format.tokenKey.auth.id=ldap1 op.format.tokenKey.ca.conn=ca1 -op.format.tokenKey.cardmgr_instance=A0000000030000 +op.format.tokenKey.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.tokenKey.issuerinfo.enable=true op.format.tokenKey.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.format.tokenKey.loginRequest.enable=true @@ -1955,7 +1966,7 @@ op.format.userKey.validateCardKeyInfoAgainstTokenDB=true op.format.userKey.auth.enable=true op.format.userKey.auth.id=ldap1 op.format.userKey.ca.conn=ca1 -op.format.userKey.cardmgr_instance=A0000000030000 +op.format.userKey.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.format.userKey.issuerinfo.enable=true op.format.userKey.issuerinfo.value=http://[pki_hostname]:[pki_http_port]/tps/phoneHome op.format.userKey.loginRequest.enable=true @@ -1977,7 +1988,7 @@ op.pinReset.userKey.rollbackKeyVersionOnPutKeyFailure=false op.pinReset.userKey.validateCardKeyInfoAgainstTokenDB=true op.pinReset.userKey.auth.enable=true op.pinReset.userKey.auth.id=ldap1 -op.pinReset.userKey.cardmgr_instance=A0000000030000 +op.pinReset.userKey.cardmgr_instance=A0000000030000,A000000003000000,A0000001510000 op.pinReset.userKey.loginRequest.enable=true op.pinReset.userKey.pinReset.pin.maxLen=10 op.pinReset.userKey.pinReset.pin.minLen=4 diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/TPSEngine.java b/base/tps/src/main/java/org/dogtagpki/server/tps/TPSEngine.java index 085362b07ca..c2cd517184a 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/TPSEngine.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/TPSEngine.java @@ -12,7 +12,7 @@ // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // -// (C) 2018 Red Hat, Inc. +// (C) 2013 Red Hat, Inc. // All rights reserved. // --- END COPYRIGHT BLOCK --- @@ -36,10 +36,11 @@ import org.dogtagpki.tps.main.Util; import org.dogtagpki.tps.msg.EndOpMsg.TPSStatus; -import com.netscape.certsrv.base.EBaseException; import com.netscape.cmscore.apps.CMSEngine; import com.netscape.cmscore.base.ConfigStorage; +import com.netscape.certsrv.base.EBaseException; + public class TPSEngine extends CMSEngine { public static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TPSEngine.class); @@ -97,6 +98,8 @@ public enum ENROLL_MODES { public static final String CFG_ERROR_PREFIX = "logging.error"; public static final String CFG_DEBUG_PREFIX = "logging.debug"; public static final String CFG_SELFTEST_PREFIX = "selftests.container.logger"; + public static final String CFG_TOKENDB = "tokendb"; + public static final String CFG_TOKENDB_ALLOWED_TRANSITIONS = "tokendb.allowedTransitions"; public static final String CFG_OPERATIONS_ALLOWED_TRANSITIONS = "tps.operations.allowedTransitions"; public static final String CFG_TOKENSERVICE_UNFORMATTED_CLEAR_USERID = "tokenservice.status.unformatted.clearUserID"; public static final String CFG_TOKENSERVICE_UNFORMATTED_CLEAR_TYPE = "tokenservice.status.unformatted.clearType"; @@ -108,7 +111,6 @@ public enum ENROLL_MODES { public static final String CFG_RECV_BUF_SIZE = "tps.recvBufSize"; public static final String CFG_CONNECTION_PREFIX = "tps.connection"; public static final String CFG_CONNECTION_MAX_MESSAGE_SIZE = "maxMessageSize"; - public static final String CFG_AUTHS_ENABLE = "auth.enable"; public static final String CFG_PROFILE_MAPPING_ORDER = "mapping.order"; public static final String CFG_ALLOW_UNKNOWN_TOKEN = "allowUnknownToken"; @@ -207,16 +209,13 @@ public enum ENROLL_MODES { public static final String ENROLL_MODE_RECOVERY = RECOVERY_OP; public static final String ERNOLL_MODE_RENEWAL = RENEWAL_OP; public static final String CFG_ALLOW_MULTI_TOKENS_USER = "allowMultiActiveTokensUser"; + public static final String CFG_AES_KEY_WRAP_ALG = "aesKeyWrapAlg"; public TPSEngine() { super("TPS"); instance = this; } - public static TPSEngine getInstance() { - return instance; - } - @Override public TPSEngineConfig createConfig(ConfigStorage storage) throws Exception { return new TPSEngineConfig(storage); @@ -227,6 +226,17 @@ public TPSEngineConfig getConfig() { return (TPSEngineConfig) mConfig; } + public static TPSEngine getInstance() { + return instance; + } + + public int initialize(String cfg_path) { + + int rc = -1; + + return rc; + } + public TKSComputeSessionKeyResponse computeSessionKeySCP02( TPSBuffer kdd, TPSBuffer cuid, @@ -258,9 +268,9 @@ public TKSComputeSessionKeyResponse computeSessionKeySCP02( int status = resp.getStatus(); if (status != 0) { - logger.error("TPSEngine.computeSessionKeySCP02: Non zero status result: " + status); + logger.debug("TPSEngine.computeSessionKeySCP02: Non zero status result: " + status); throw new TPSException("TPSEngine.computeSessionKeySCP02: invalid returned status: " + status, - TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -300,7 +310,7 @@ public TKSComputeSessionKeyResponse computeSessionKeysSCP03(TPSBuffer kdd, TPSBu int status = resp.getStatus(); if (status != 0) { - logger.error("TPSEngine.computeSessionKeysSCP03: Non zero status result: " + status); + logger.debug("TPSEngine.computeSessionKeysSCP03: Non zero status result: " + status); throw new TPSException("TPSEngine.computeSessionKeysSCP03: invalid returned status: " + status, TPSStatus.STATUS_ERROR_SECURE_CHANNEL); @@ -342,7 +352,7 @@ public TKSComputeSessionKeyResponse computeSessionKey(TPSBuffer kdd, TPSBuffer c int status = resp.getStatus(); if (status != 0) { - logger.error("TPSEngine.computeSessionKey: Non zero status result: " + status); + logger.debug("TPSEngine.computeSessionKey: Non zero status result: " + status); throw new TPSException("TPSEngine.computeSessionKey: invalid returned status: " + status, TPSStatus.STATUS_ERROR_SECURE_CHANNEL); @@ -380,7 +390,7 @@ public CARetrieveCertResponse recoverCertificate(TPSCertRecord cert, String seri // test ends - remove up to here } catch (EBaseException e) { - logger.error(method + ":" + e.getMessage(), e); + logger.debug(method + ":" + e); throw new TPSException(method + ": Exception thrown: " + e, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -425,7 +435,7 @@ public CARenewCertResponse renewCertificate(TPSCertRecord cert, String serialS, logger.debug(method + ": retrieved cert: " + retrievedCertB64); } catch (EBaseException e) { - logger.error(method + ":" + e.getMessage(), e); + logger.debug(method + ":" + e); throw new TPSException(method + ": Exception thrown: " + e, TPSStatus.STATUS_ERROR_RENEWAL_FAILED); } @@ -438,7 +448,9 @@ public CARenewCertResponse renewCertificate(TPSCertRecord cert, String serialS, } - public TPSBuffer createKeySetData(TPSBuffer newMasterVersion, TPSBuffer oldVersion, int protocol, TPSBuffer cuid, TPSBuffer kdd, TPSBuffer wrappedDekSessionKey, String connId, String inKeyset) + // ** G&D 256 Key Rollover Support ** + // Add oldKeySet parameter + public TPSBuffer createKeySetData(TPSBuffer newMasterVersion, TPSBuffer oldVersion, int protocol, TPSBuffer cuid, TPSBuffer kdd, TPSBuffer wrappedDekSessionKey, String connId, String inKeyset, String oldKeySet) throws TPSException { String method = "TPSEngine.createKeySetData:"; @@ -449,13 +461,17 @@ public TPSBuffer createKeySetData(TPSBuffer newMasterVersion, TPSBuffer oldVersi TPSStatus.STATUS_ERROR_UPGRADE_APPLET); } + logger.debug(method + " cuid: " + cuid.toHexStringPlain() + " newMasterVersion: " + newMasterVersion.toHexString() + + " oldVersion: " + oldVersion.toHexString() + " protocol: " + protocol + " inKeyset: " + inKeyset + + " oldKeySet: " + oldKeySet); + TKSRemoteRequestHandler tks = null; TKSCreateKeySetDataResponse resp = null; try { tks = new TKSRemoteRequestHandler(connId, inKeyset); - resp = tks.createKeySetData(newMasterVersion, oldVersion, cuid, kdd, protocol,wrappedDekSessionKey); + resp = tks.createKeySetData(newMasterVersion, oldVersion, cuid, kdd, protocol,wrappedDekSessionKey, oldKeySet); // ** G&D 256 Key Rollover Support ** pass oldKeySet to TKS } catch (EBaseException e) { throw new TPSException(method + " failure to get key set data from TKS", @@ -473,7 +489,7 @@ public TPSBuffer createKeySetData(TPSBuffer newMasterVersion, TPSBuffer oldVersi TPSBuffer keySetData = resp.getKeySetData(); if (keySetData == null) { - logger.error(method + " No valid key set data returned."); + logger.debug(method + " No valid key set data returned."); throw new TPSException(method + " No valid key set data returned.", TPSStatus.STATUS_ERROR_UPGRADE_APPLET); @@ -534,17 +550,17 @@ public static RA_Algs intToRAAlgs(int alg) { public KRARecoverKeyResponse recoverKey(String cuid, String userid, TPSBuffer drmWrappedDesKey, TPSBuffer drmWrappedAesKey, - String b64cert, String drmConnId) throws TPSException { + String b64cert, String drmConnId,String aesKeyWrapAlg) throws TPSException { return this.recoverKey(cuid, userid, drmWrappedDesKey, drmWrappedAesKey, - b64cert, drmConnId, BigInteger.valueOf(0)); + b64cert, drmConnId, BigInteger.valueOf(0),aesKeyWrapAlg); } public KRARecoverKeyResponse recoverKey(String cuid, String userid, TPSBuffer drmWrappedDesKey,TPSBuffer drmWrappedAesKey, - String b64cert, String drmConnId,BigInteger keyid) throws TPSException { + String b64cert, String drmConnId,BigInteger keyid,String aesKeyWrapAlg) throws TPSException { String method = "TPSEngine.recoverKey"; logger.debug("TPSEngine.recoverKey"); if (cuid == null) @@ -560,7 +576,6 @@ else if (b64cert == null) else if (drmConnId == null) logger.debug(method + ": drmConnId null"); - //Either we will provide a wrapped Des key (scp01) or a wrapped Aes key (scp03) if (cuid == null || userid == null || drmConnId == null) { throw new TPSException("TPSEngine.recoverKey: invalid input data!", TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } @@ -580,8 +595,8 @@ else if (drmConnId == null) encodedAes = Util.specialURLEncode(drmWrappedAesKey); resp = kra.recoverKey(cuid, userid, encodedDes, - encodedAes, - (b64cert != null) ? Util.uriEncode(b64cert) : b64cert,keyid); + encodedAes, + (b64cert != null) ? Util.uriEncode(b64cert) : b64cert,keyid,aesKeyWrapAlg); } catch (EBaseException e) { throw new TPSException("TPSEngine.recoverKey: Problem creating or using KRARemoteRequestHandler! " + e.toString(), TPSStatus.STATUS_ERROR_RECOVERY_FAILED); @@ -621,7 +636,7 @@ else if (drmConnId == null) public KRAServerSideKeyGenResponse serverSideKeyGen(int keySize, String cuid, String userid, String drmConnId, TPSBuffer wrappedDesKey, TPSBuffer drmWrappedAesKey, boolean archive, - boolean isECC) throws TPSException { + boolean isECC,String aesKeyWrapAlg) throws TPSException { /* logger.debug("TPSEngine.serverSideKeyGen entering... keySize: " + keySize + " cuid: " + cuid + " userid: " @@ -629,9 +644,7 @@ public KRAServerSideKeyGenResponse serverSideKeyGen(int keySize, String cuid, St + " isECC: " + isECC); */ - if (cuid == null || userid == null || drmConnId == null || - (wrappedDesKey == null && drmWrappedAesKey == null)) { - + if (cuid == null || userid == null || drmConnId == null || ( wrappedDesKey == null && drmWrappedAesKey == null)) { throw new TPSException("TPSEngine.serverSideKeyGen: Invalid input data!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -643,9 +656,9 @@ public KRAServerSideKeyGenResponse serverSideKeyGen(int keySize, String cuid, St kra = new KRARemoteRequestHandler(drmConnId); resp = kra.serverSideKeyGen(isECC, keySize, cuid, userid, - (wrappedDesKey != null) ? Util.specialURLEncode(wrappedDesKey) : "", + (wrappedDesKey != null) ? Util.specialURLEncode(wrappedDesKey) : "", (drmWrappedAesKey != null) ? Util.specialURLEncode(drmWrappedAesKey) : "", - archive); + archive,aesKeyWrapAlg); } catch (EBaseException e) { throw new TPSException("TPSEngine.serverSideKeyGen: Problem creating or using KRARemoteRequestHandler! " diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/TPSSession.java b/base/tps/src/main/java/org/dogtagpki/server/tps/TPSSession.java index 4e8282aa520..76349b1265f 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/TPSSession.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/TPSSession.java @@ -29,6 +29,8 @@ import org.dogtagpki.tps.msg.BeginOpMsg; import org.dogtagpki.tps.msg.EndOpMsg; import org.dogtagpki.tps.msg.TPSMessage; +import org.dogtagpki.tps.main.TPSBuffer; + public class TPSSession { @@ -39,6 +41,9 @@ public class TPSSession { private TokenRecord tokenRecord; private ExternalRegAttrs extRegAttrs; + // Store card mgr in session so we only have to query it once per session + private TPSBuffer selectedCardMgr; + public TPSSession(TPSConnection conn, String ip) { @@ -181,4 +186,12 @@ public void setExternalRegAttrs(ExternalRegAttrs erAttrs) { public ExternalRegAttrs getExternalRegAttrs() { return extRegAttrs; } + + public TPSBuffer getSelectedCardMgr() { + return selectedCardMgr; + } + + public void setSelectedCardMgr(TPSBuffer cardMgrBuffer) { + this.selectedCardMgr = cardMgrBuffer; + } } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/channel/SecureChannel.java b/base/tps/src/main/java/org/dogtagpki/server/tps/channel/SecureChannel.java index ce5300c90b0..7f101ec68a0 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/channel/SecureChannel.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/channel/SecureChannel.java @@ -29,6 +29,7 @@ import org.dogtagpki.tps.apdu.CreatePinAPDU; import org.dogtagpki.tps.apdu.DeleteFileAPDU; import org.dogtagpki.tps.apdu.DeleteFileGP211APDU; +import org.dogtagpki.tps.apdu.DeleteKeysAPDU; import org.dogtagpki.tps.apdu.ExternalAuthenticateAPDU; import org.dogtagpki.tps.apdu.ExternalAuthenticateAPDU.SecurityLevel; import org.dogtagpki.tps.apdu.ExternalAuthenticateAPDUGP211; @@ -57,6 +58,8 @@ import com.netscape.certsrv.base.EBaseException; +import java.util.Arrays; + public class SecureChannel { public static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SecureChannel.class); @@ -74,8 +77,6 @@ public class SecureChannel { private PK11SymKey cmacSessionKey; //Used for security level we do not yet suport. - - private PK11SymKey rmacSessionKey; private PK11SymKey dekSessionKey; @@ -85,9 +86,11 @@ public class SecureChannel { private TPSBuffer dekSessionKeyWrapped; private TPSBuffer drmDesKey; + private TPSBuffer drmAesKey; private TPSBuffer aesDesKey; + //SCP01 kek key private TPSBuffer kekDesKey; private TPSBuffer kekAesKey; @@ -330,8 +333,7 @@ public void appendKeyCapabilities(TPSBuffer buffer, String keyTypePrefix, String TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); final String keyCapabilities = "keyCapabilities"; @@ -455,12 +457,12 @@ public void externalAuthenticate() throws TPSException, IOException { if (false == cardCryptogram.equals(calculatedCardCryptogram)) { - logger.error("SecureChannel.eternalAuthenticate. Failed to match calculated to returned card cryptogram!. cardCryptogram: " + logger.debug("SecureChannel.externalAuthenticate. Failed to match calculated to returned card cryptogram!. cardCryptogram: " + cardCryptogram.toHexString() - + " calculatedCardCrytpogram: " + + " calculatedCardCryptogram: " + calculatedCardCryptogram.toHexString()); throw new TPSException( - "SecureChannel.eternalAuthenticate. Failed to match calculated to returned card cryptogram!.", + "SecureChannel.externalAuthenticate. Failed to match calculated to returned card cryptogram!.", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -531,12 +533,10 @@ private void computeAPDU(APDU apdu) throws TPSException { if (secLevel == SecurityLevel.SECURE_MSG_MAC_ENC) { try { - //logger.debug("SecureChannel.computeAPDU: Before encryption data value: " + apdu.getData().toHexString()); apdu.secureMessage(encSessionKey, (byte) 1); - //logger.debug("SecureChannel.computeAPDU: After encryption data value: " + apdu.getData().toHexString()); } catch (EBaseException e) { throw new TPSException("SecureChannel.computeAPDU: Can't encrypt outgoing data! " + e, - TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } logger.debug("SecureChannel.computeAPDU: Successfully encrypted apdu data."); @@ -554,17 +554,12 @@ private void computeAPDU_SCP03(APDU apdu) throws TPSException { if (secLevelGP211 == ExternalAuthenticateAPDUGP211.SecurityLevel.CDEC_CMAC) { try { - //logger.debug("SecureChannel.computeAPDU_SCP03: Before encryption data value: " - // + apdu.getData().toHexString()); this.incrementBuffer(encryptionCounter); TPSBuffer currentEncryptionCounter = new TPSBuffer(encryptionCounter); apdu.secureMessageSCP03(encSessionKey,currentEncryptionCounter); - - //logger.debug("SecureChannel.computeAPDU_SCP03: After encryption data value: " - // + apdu.getData().toHexString()); } catch (EBaseException e) { throw new TPSException("SecureChannel.computeAPDU_SCP03: Can't encrypt outgoing data! " + e, - TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } logger.debug("SecureChannel.computeAPDU_SCP03: Successfully encrypted apdu data."); @@ -591,8 +586,8 @@ public void incrementBuffer(TPSBuffer buffer) { cur++; buffer.setAt(i, cur); break; - } - buffer.setAt(i,(byte) 0x00); + } else + buffer.setAt(i,(byte) 0x00); } System.out.println("enc buffer: " + buffer.toHexString()); @@ -610,14 +605,10 @@ private void computeAPDU_SCP02(APDU apdu) throws TPSException { if (secLevelGP211 == ExternalAuthenticateAPDUGP211.SecurityLevel.CDEC_CMAC) { try { - //logger.debug("SecureChannel.computeAPDU_SCP02: Before encryption data value: " - // + apdu.getData().toHexString()); apdu.secureMessageSCP02(encSessionKey); - //logger.debug("SecureChannel.computeAPDU_SCP02: After encryption data value: " - // + apdu.getData().toHexString()); } catch (EBaseException e) { throw new TPSException("SecureChannel.computeAPDU_SCP02: Can't encrypt outgoing data! " + e, - TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } logger.debug("SecureChannel.computeAPDU_SCP02: Successfully encrypted apdu data."); @@ -636,35 +627,25 @@ private void computeAPDUMacSCP03(APDU apdu) throws TPSException { data = apdu.getDataToMAC(); - //logger.debug("SecureChannel.computeAPDUMacSCP03: data To MAC: " + data.toHexString() + " incoming icv: " - // + icv.toHexString()); - try { - - logger.debug("SecureChannel.computeAPDUMacSCP03: No ecnrypton of ICV."); - TPSBuffer dataToMac = new TPSBuffer(icv); /// Prepend the chaining value to the data to be maced. dataToMac.add(data); - //logger.debug("SecureChannel.computeAPDUMacSCP03: final data To MAC: " + dataToMac.toHexString() + " incoming icv: " - // + icv.toHexString()); - newMac = SecureChannelProtocol.computeAES_CMAC(macSessionKey, dataToMac); } catch (EBaseException e) { - logger.error("SecureChannel.computeAPDUMacSCP03: Can't compute mac: " + e.getMessage(), e); + logger.debug("SecureChannel.computeAPDUMacSCP03: Can't compute mac. " + e); throw new TPSException("SecureChannel.compuatAPDUMacSCP03: Can't compute mac.", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } - logger.debug("SecureChannel.computeAPDUMacSCP03: computed MAC: " /* + newMac.toHexString() */); + //logger.debug("SecureChannel.computeAPDUMacSCP03: computed MAC: " /* + newMac.toHexString() */); apdu.setMAC(newMac.substr(0,8)); - + icv.set(newMac); - } private void computeAPDUMacSCP02(APDU apdu) throws TPSException { @@ -701,7 +682,7 @@ private void computeAPDUMacSCP02(APDU apdu) throws TPSException { } } catch (EBaseException e) { - logger.error("SecureChannel.computeAPDUMacSCP02: Can't compute mac: " + e.getMessage(), e); + logger.debug("SecureChannel.computeAPDUMacSCP02: Can't compute mac. " + e); throw new TPSException("SecureChannel.compuatAPDUMacSCP02: Can't compute mac.", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -732,7 +713,7 @@ private void computeAPDUMac(APDU apdu) throws TPSException { try { newMac = Util.computeMAC(sessionKey, data, icv); } catch (EBaseException e) { - logger.error("SecureChannel.compuatAPDUMac: Can't compute mac: " + e.getMessage(), e); + logger.debug("SecureChannel.compuatAPDUMac: Can't compute mac. " + e); throw new TPSException("SecureChannel.compuatAPDUMac: Can't compute mac.", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -748,8 +729,7 @@ private void computeAPDUMac(APDU apdu) throws TPSException { public void deleteFileX(TPSBuffer aid) throws TPSException, IOException { logger.debug("SecureChannel.deleteFileX: entering..."); if (aid == null) { - throw new TPSException("SecureChannel.deleteFileX: no input aid!", - TPSStatus.STATUS_ERROR_UPGRADE_APPLET); + throw new TPSException("SecureChannel.deleteFileX: no input aid!", TPSStatus.STATUS_ERROR_UPGRADE_APPLET); } if (isGP211()) { @@ -780,14 +760,25 @@ public void installLoad(TPSBuffer packageAID, TPSBuffer sdAID, int fileLength) t + sdAID.toHexString() + " fileLength: " + fileLength); if (packageAID == null || sdAID == null || fileLength <= 0) { - throw new TPSException("SecureChannel.insallLoad bad input parameters!", + throw new TPSException("SecureChannel.installLoad bad input parameters!", TPSStatus.STATUS_ERROR_UPGRADE_APPLET); } TPSBuffer emptySDAID = new TPSBuffer(); if (isGP211()) { + logger.debug("SecureChannel.installLoad: isGP211 is true"); TPSBuffer cardMgrGP211AIDBuff = new TPSBuffer(TPSEngine.CFG_DEF_CARDMGR_211_INSTANCE_AID); + + TPSBuffer aidSubStrBuffer = new TPSBuffer(cardMgrGP211AIDBuff.substr(0,sdAID.size())); + byte[] defaultAIDtoChk = aidSubStrBuffer.toBytesArray(); + + // Use default AID unless another AID was already selected + if (!Arrays.equals(sdAID.toBytesArray(),defaultAIDtoChk)) + { + cardMgrGP211AIDBuff = new TPSBuffer(sdAID); + } + installLoadGP211(packageAID, cardMgrGP211AIDBuff, fileLength); return; } @@ -813,7 +804,7 @@ public void installLoadGP211(TPSBuffer packageAID, TPSBuffer sdAID, int fileLeng logger.debug("SecureChannel.installLoadGP211: entering ..."); if (packageAID == null || sdAID == null || fileLength <= 0) { - throw new TPSException("SecureChannel.insallLoadGP211 bad input parameters!", + throw new TPSException("SecureChannel.installLoadGP211 bad input parameters!", TPSStatus.STATUS_ERROR_UPGRADE_APPLET); } @@ -989,7 +980,7 @@ public void installApplet(TPSBuffer netkeyPAIDBuff, TPSBuffer netkeyAIDBuff, byt } if (!response.checkResult()) { - throw new TPSException("SecureChannel.installApplett. Failed installApplet operation.", + throw new TPSException("SecureChannel.installApplet. Failed installApplet operation.", TPSStatus.STATUS_ERROR_UPGRADE_APPLET); } @@ -1066,7 +1057,7 @@ public void clearAppletKeySlotData(TPSBuffer data) { logger.debug(method + " entering ..."); if(data == null) { - logger.warn(method + " Invalid input data returning..."); + logger.debug(method + " Invalid input data returning..."); return; } @@ -1076,7 +1067,7 @@ public void clearAppletKeySlotData(TPSBuffer data) { computeAPDU(clearKey); response = processor.handleAPDURequest(clearKey); } catch (TPSException | IOException e) { - logger.warn(method + " bad apdu return: " + e.getMessage(), e); + logger.debug(method + " bad apdu return!"); return; } @@ -1121,7 +1112,7 @@ public void writeObject(TPSBuffer objectID, TPSBuffer objectData) throws TPSExce APDUResponse response = processor.handleAPDURequest(write); if (!response.checkResult()) { - logger.error("SecureChannel.writeObject: bad apdu return!"); + logger.debug("SecureChannel.writeObject: bad apdu return!"); //Throw this return code because this happens during enrollment and we don't have // a more specific error code. throw new TPSException("SecureChannel.writeObject. Failed in middle of writeObject.", @@ -1142,6 +1133,7 @@ public void writeObject(TPSBuffer objectID, TPSBuffer objectData) throws TPSExce public TPSBuffer readObject(TPSBuffer objectID, int offset, int len) throws TPSException, IOException { logger.debug("SecureChannel.readObject: entering ..."); + logger.debug("offset: " + offset + " len: " + len + " objectID: " + objectID.toHexString()); if (objectID == null || len == 0) { throw new TPSException("SecureChannel.readObject: invalid input data.", @@ -1168,13 +1160,19 @@ public TPSBuffer readObject(TPSBuffer objectID, int offset, int len) throws TPSE while (sum < len) { read = new ReadObjectAPDU(objectID.toBytesArray(), cur_offset, cur_read); + //RedHat Add a 0x00 Le byte, appease tpsclient if configured + if(!skipTrailerLeByteScp01()) { + read.setTrailer(new TPSBuffer((byte) 0x00)); + } + + //logger.debug("read encoding: " + read.getEncoding().toHexString()); computeAPDU(read); APDUResponse response = processor.handleAPDURequest(read); if (!response.checkResult()) { - logger.error("SecureChannel.readObject: bad apdu return!"); - throw new TPSException("SecureChannel.installApplett. Failed in middle of readObject.", + logger.debug("SecureChannel.readObject: bad apdu return!"); + throw new TPSException("SecureChannel.installApplet. Failed in middle of readObject.", TPSStatus.STATUS_ERROR_CANNOT_PERFORM_OPERATION); } @@ -1247,15 +1245,15 @@ public TPSBuffer createPKCS11PriKeyAttrsBuffer(String id, String label, TPSBuffe TPSBuffer result = new TPSBuffer(); - //logger.debug("SecureChannel.createPKCS11PriKeyAttrsBuffer: entering..."); + logger.debug("SecureChannel.createPKCS11PriKeyAttrsBuffer: entering..."); if (id == null || label == null || keyid == null || modulus == null || keyTypePrefix == null) { throw new TPSException("SecureChannel.craetePKCS11PriKeyAttrsBuffer: invalid input data.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - //logger.debug("SecureChannel.createPKCS11PriKeyAttrsBuffer: id: " + id + " label: " + label + " keyid: " - // + keyid.toHexString()); +// logger.debug("SecureChannel.createPKCS11PriKeyAttrsBuffer: id: " + id + " label: " + label + " keyid: " +// + keyid.toHexString()); byte keytype[] = { 0, 0, 0, 0 }; byte p11class[] = { 3, 0, 0, 0 }; @@ -1364,15 +1362,15 @@ public void finalizeObjectBuffer(TPSBuffer buffer, String id) { public TPSBuffer createPKCS11CertAttrsBuffer(TokenKeyType keyType, String id, String label, TPSBuffer keyid) throws TPSException { - //logger.debug("SecureChannel.createPKCS11CertAttrsBuffer: entering... id: " + id); + logger.debug("SecureChannel.createPKCS11CertAttrsBuffer: entering... id: " + id); if (keyType == null || id == null || label == null || keyid == null) { throw new TPSException("SecureChannel.createPKCS11CertAttrsBuffer. Bad input data.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - //logger.debug("SecureChannel.createPKCS11CertAttrsBuffer: ... id: " + id + " label: " + label + " keyid: " - // + keyid.toHexString()); +// logger.debug("SecureChannel.createPKCS11CertAttrsBuffer: ... id: " + id + " label: " + label + " keyid: " +// + keyid.toHexString()); byte[] type = { 0x0, 0x0, 0x0, 0x0 }; byte[] p11class = { 0x1, 0x0, 0x0, 0x0 }; @@ -1380,8 +1378,8 @@ public TPSBuffer createPKCS11CertAttrsBuffer(TokenKeyType keyType, String id, St TPSBuffer result = new TPSBuffer(); - //logger.debug("SecureChannel.createPKCS11CertAttrsBuffer: label: " + label + " label bytes: " - // + (new TPSBuffer(label)).toHexString()); +// logger.debug("SecureChannel.createPKCS11CertAttrsBuffer: label: " + label + " label bytes: " +// + (new TPSBuffer(label)).toHexString()); appendPKCS11Attribute(result, PKCS11Constants.CKA_LABEL, new TPSBuffer(label.getBytes())); appendPKCS11Attribute(result, PKCS11Constants.CKA_ID, keyid); @@ -1456,6 +1454,11 @@ public int startEnrollment(int pe1, int pe2, TPSBuffer wrappedChallenge, TPSBuff generate_key_apdu = new GenerateKeyAPDU((byte) pe1, (byte) pe2, (byte) algorithm, keySize, (byte) option, (byte) 0, wrappedChallenge, keyCheck); + // RedHat Add a 0x00 Le byte, appease tpsclient if configured. + if(!skipTrailerLeByteScp01()) { + generate_key_apdu.setTrailer(new TPSBuffer((byte) 0x00)); + } + computeAPDU(generate_key_apdu); response = processor.handleAPDURequest(generate_key_apdu); @@ -1482,7 +1485,10 @@ public int tokenTypeToInt(TokenKeyType type) { if (type == TokenKeyType.KEY_TYPE_ENCRYPTION) return 0; - return type == TokenKeyType.KEY_TYPE_SIGNING ? 1 : 2; + if (type == TokenKeyType.KEY_TYPE_SIGNING) + return 1; + else + return 2; } public void setLifecycleState(byte flag) throws TPSException, IOException { @@ -1496,7 +1502,7 @@ public void setLifecycleState(byte flag) throws TPSException, IOException { APDUResponse response = processor.handleAPDURequest(life); if (!response.checkResult()) { - logger.error(method + "result.checkResult() returns false; Throwing exception!"); + logger.debug(method + "result.checkResult() returns false; Throwing exception!"); throw new TPSException("SecureChannel.setLifecycleState. Failed to set Lifecycle State!.", TPSStatus.STATUS_ERROR_MAC_LIFECYCLE_PDU); } @@ -1509,7 +1515,7 @@ public void createPin(int pinNumber, int maxRetries, String pin) throws TPSExcep logger.debug("SecureChannel.createPin: entering..."); if (pin == null) { - throw new TPSException("SecureChannel.createPin: invalid intput data.", + throw new TPSException("SecureChannel.createPin: invalid input data.", TPSStatus.STATUS_ERROR_MAC_RESET_PIN_PDU); } @@ -1530,8 +1536,8 @@ public void resetPin(int pinNumber, String new_pin) throws TPSException, IOExcep logger.debug("SecureChannel.resetPin"); if (new_pin == null) { - throw new TPSException("SecureChannel.resetPin: invalid intput data.", - TPSStatus.STATUS_ERROR_TOKEN_RESET_PIN_FAILED); + throw new TPSException("SecureChannel.resetPin: invalid input data.", + TPSStatus.STATUS_ERROR_MAC_RESET_PIN_PDU); } TPSBuffer newPinBuf = new TPSBuffer(new_pin.getBytes()); @@ -1544,7 +1550,7 @@ public void resetPin(int pinNumber, String new_pin) throws TPSException, IOExcep if (!response.checkResult()) { throw new TPSException("SecureChannel.resetPin: failed to reset pin.", - TPSStatus.STATUS_ERROR_TOKEN_RESET_PIN_FAILED); + TPSStatus.STATUS_ERROR_MAC_RESET_PIN_PDU); } } @@ -1577,6 +1583,11 @@ public void putKeys(byte curVersion, byte curIndex, TPSBuffer keySetData) throws } computeAPDU(putKey); + int kill = 0; + if (kill == 1) { + throw new TPSException("putKeys end of progress.", TPSStatus.STATUS_ERROR_KEY_CHANGE_OVER); + } + APDUResponse response = processor.handleAPDURequest(putKey); if (!response.checkResult()) { @@ -1749,15 +1760,28 @@ protected TPSBuffer computeHostCryptogramSCP02(PK11SymKey encSessionKey) } public boolean isSCP03() { - return platProtInfo.isSCP03(); + if (platProtInfo.isSCP03()) + return true; + else + return false; } public boolean isSCP02() { - return platProtInfo.isGP211() && platProtInfo.isSCP02(); + if (platProtInfo.isGP211() && platProtInfo.isSCP02()) { + + return true; + } + + return false; } private boolean isGP211() { - return platProtInfo.isGP211(); + + if (platProtInfo.isGP211()) { + return true; + } + + return false; } public TPSBuffer getDekSessionKeyWrapped() { @@ -1784,4 +1808,69 @@ public void setRmacSessionKey(PK11SymKey rmacSessionKey) { this.rmacSessionKey = rmacSessionKey; } + /** + * ** G&D 256 Key Rollover Support ** + * This method constructs the APDU for key deletion and sends the request to the card to + * delete keys with the given version. + * + * @param keyVersion the key version to be deleted + * @throws TPSException + * @throws IOException + * + */ + public void deleteKeys(byte keyVersion) throws TPSException, IOException { + String method = "SecureChannel.deleteKeys: keyVersion: " + keyVersion + ": "; + + logger.debug(method + " entering ..."); + + APDUResponse response; + try { + TPSBuffer data = new TPSBuffer(keyVersion); + DeleteKeysAPDU deleteKeyApdu = new DeleteKeysAPDU(data); + computeAPDU(deleteKeyApdu); + response = processor.handleAPDURequest(deleteKeyApdu); + } catch (TPSException | IOException e) { + logger.debug(method + " bad apdu return!"); + logger.debug(e.toString()); + throw e; + } + + if (!response.checkResult()) { + logger.debug(method + " response with unsuccess result"); + throw new TPSException(method + " failed to delete key set!", + TPSStatus.STATUS_ERROR_KEY_CHANGE_OVER); + } + + logger.debug(method + " Successful delete key data operation completed."); + } + + // RedHat + //Check config param if we want to not add le bytes for certain scp01 apdu's. + //default is false. If method returns false the le byte will be added as before. + public boolean skipTrailerLeByteScp01() { + + TPSEngineConfig configStore = this.getConfigStore(); + + String method = "SecureChannel.skipTrailerLeByteScp01: "; + boolean skip = false; + try { + String configName = "channel.scp01.no.le.byte"; + + if(platProtInfo.isSCP01()) { + skip = configStore.getBoolean(configName,false); + } + } catch (Exception e) { + skip = false; + } + + logger.debug(method + skip); + return skip; + } + + private TPSEngineConfig getConfigStore() { + TPSEngine engine = TPSEngine.getInstance(); + TPSEngineConfig configStore = engine.getConfig(); + return configStore; + } + } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/channel/SecureChannelProtocol.java b/base/tps/src/main/java/org/dogtagpki/server/tps/channel/SecureChannelProtocol.java index 510f879841d..8748b9639d1 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/channel/SecureChannelProtocol.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/channel/SecureChannelProtocol.java @@ -45,6 +45,7 @@ public class SecureChannelProtocol { static String masterKeyPrefix = null; static final int DEF_AES_KEYLENGTH = 16; + static final int DEF_AES_256_KEYLENGTH = 32; static final int KEYLENGTH = 16; static final int PREFIXLENGHT = 128; static final int DES2_LENGTH = 16; @@ -514,8 +515,8 @@ public SymmetricKey unwrapWrappedSymKeyOnToken(CryptoToken token, SymmetricKey u } if(keyType == SymmetricKey.Type.AES) { - if(inputKeyArray.length != DEF_AES_KEYLENGTH) - throw new EBaseException(method + "Invalid length of raw input array."); + if(inputKeyArray.length != DEF_AES_KEYLENGTH && inputKeyArray.length != DEF_AES_256_KEYLENGTH) + throw new EBaseException(method + "Invalid length of raw AES input array."); } else if(keyType == SymmetricKey.Type.DES || keyType == SymmetricKey.Type.DES3) { diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/cms/KRARemoteRequestHandler.java b/base/tps/src/main/java/org/dogtagpki/server/tps/cms/KRARemoteRequestHandler.java index 637ed169269..7da31b9a44f 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/cms/KRARemoteRequestHandler.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/cms/KRARemoteRequestHandler.java @@ -68,26 +68,30 @@ public KRAServerSideKeyGenResponse serverSideKeyGen( String userid, String sDesKey, String sAesKey, - boolean archive) + boolean archive, + String aesKeyWrapAlg) throws EBaseException { - logger.info("KRARemoteRequestHandler: Generating key pair on KRA"); - + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): begins."); if (cuid == null || userid == null || sDesKey == null) { - logger.error("KRARemoteRequestHandler: Missing input parameter"); - throw new EBaseException("Missing input parameter"); + throw new EBaseException("KRARemoteRequestHandler: serverSideKeyGen(): input parameter null."); + } + + String aesWrapAlg = aesKeyWrapAlg; + + //Just check for unsupported values that are not CBC or KWP and give default. + if(aesWrapAlg == null || aesWrapAlg.length() != 3) { + aesWrapAlg = "KWP"; } TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); - HttpConnector conn = (HttpConnector) subsystem.getConnectionManager().getConnector(connid); - + HttpConnector conn = + (HttpConnector) subsystem.getConnectionManager().getConnector(connid); + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): sending request to KRA"); HttpResponse resp; String request; - if (isECC) { - logger.info("KRARemoteRequestHandler: Generating EC key pair"); - String eckeycurve; if (keysize == 521) { eckeycurve = "nistp521"; @@ -96,13 +100,12 @@ public KRAServerSideKeyGenResponse serverSideKeyGen( } else if (keysize == 256) { eckeycurve = "nistp256"; } else { - logger.warn("KRARemoteRequestHandler: Unrecognized EC key size: " + keysize); + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): unrecognized ECC keysize" + keysize + + ", setting to nistp256"); keysize = 256; eckeycurve = "nistp256"; } - logger.info("KRARemoteRequestHandler: - key curve: " + eckeycurve); - request = IRemoteRequest.KRA_KEYGEN_Archive + "=" + archive + "&" + IRemoteRequest.TOKEN_CUID + "=" + @@ -116,16 +119,17 @@ public KRAServerSideKeyGenResponse serverSideKeyGen( "&" + IRemoteRequest.KRA_Trans_DesKey + "=" + sDesKey + "&" + IRemoteRequest.KRA_Trans_AesKey + "=" + - sAesKey; + sAesKey + + "&" + IRemoteRequest.KRA_Aes_Wrap_Alg + "=" + + aesWrapAlg; - //logger.debug("KRARemoteRequestHandler: - request: " + request); - - resp = conn.send("GenerateKeyPair", request); + //logger.debug("KRARemoteRequestHandler: outgoing request for ECC: " + request); + resp = + conn.send("GenerateKeyPair", + request); } else { // RSA - logger.info("KRARemoteRequestHandler: Generating RSA key pair"); - request = IRemoteRequest.KRA_KEYGEN_Archive + "=" + archive + "&" + IRemoteRequest.TOKEN_CUID + "=" + @@ -139,87 +143,97 @@ public KRAServerSideKeyGenResponse serverSideKeyGen( "&" + IRemoteRequest.KRA_Trans_DesKey + "=" + sDesKey + "&" + IRemoteRequest.KRA_Trans_AesKey + "=" + - sAesKey; + sAesKey + + "&" + IRemoteRequest.KRA_Aes_Wrap_Alg + "=" + + aesWrapAlg; - //logger.debug("KRARemoteRequestHandler: - request: " + request); - resp = conn.send("GenerateKeyPair", request); + //logger.debug("KRARemoteRequestHandler: outgoing request for RSA: " + request); + + resp = + conn.send("GenerateKeyPair", + request); } //For some reason the send method can return null and not throw an exception. // Check here; if (resp == null) { - logger.error("KRARemoteRequestHandler: Missing response object"); - throw new EBaseException("Missing response object"); + throw new EBaseException( + "KRARemoteRequestHandler: serverSideKeyGen(): No response object returned from connection."); } String content = resp.getContent(); - if (content == null || content.equals("")) { - logger.error("KRARemoteRequestHandler: Missing response content"); - throw new EBaseException("Missing response content"); - } + if (content != null && !content.equals("")) { + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): got content"); + Hashtable response = + parseResponse(content); - logger.info("KRARemoteRequestHandler: Parsing response"); - Hashtable response = parseResponse(content); - - /** - * When a value is not found in response, keep going so we know - * what else is missing - * Note: response values "missing" might not be bad for some cases - */ - Integer ist = Integer.valueOf(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); - String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); - logger.info("KRARemoteRequestHandler: - status: " + value); - - if (value == null) { - logger.error("KRARemoteRequestHandler: Missing status"); - throw new EBaseException("Missing status"); - } - - ist = Integer.parseInt(value); - if (ist != 0) { - value = (String) response.get(IRemoteRequest.RESPONSE_ERROR_STRING); + /** + * When a value is not found in response, keep going so we know + * what else is missing + * Note: response values "missing" might not be bad for some cases + */ + Integer ist = new Integer(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); + String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); if (value == null) { - logger.warn("KRARemoteRequestHandler: Missing error message"); - } else { - logger.error("KRARemoteRequestHandler: " + value); - response.put(IRemoteRequest.RESPONSE_ERROR_STRING, value); + throw new EBaseException("KRARemoteRequestHandler: serverSideKeyGen(): Invalide status returned!"); } - } - response.put(IRemoteRequest.RESPONSE_STATUS, ist); - - value = (String) response.get(IRemoteRequest.KRA_RESPONSE_PublicKey); - if (value == null) { - logger.warn("KRARemoteRequestHandler: Missing public key"); - } else { - logger.info("KRARemoteRequestHandler: Found public key"); - response.put(IRemoteRequest.KRA_RESPONSE_PublicKey, value); - } + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): got status = " + value); + ist = Integer.parseInt(value); + if (ist != 0) { + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): status not 0, getting error string... "); + value = (String) response.get(IRemoteRequest.RESPONSE_ERROR_STRING); + if (value == null) { + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): response missing name-value pair for: " + + IRemoteRequest.RESPONSE_ERROR_STRING); + } else { + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): got IRemoteRequest.RESPONSE_ERROR_STRING = " + + value); + response.put(IRemoteRequest.RESPONSE_ERROR_STRING, value); + } + } + response.put(IRemoteRequest.RESPONSE_STATUS, ist); - value = (String) response.get(IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey); + value = (String) response.get(IRemoteRequest.KRA_RESPONSE_PublicKey); + if (value == null) { + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): response missing name-value pair for: " + + IRemoteRequest.KRA_RESPONSE_PublicKey); + } else { + //logger.debug("KRARemoteRequestHandler:serverSideKeyGen(): got IRemoteRequest.KRA_RESPONSE_PublicKey= " + // + value); + logger.debug("KRARemoteRequestHandler:serverSideKeyGen(): got IRemoteRequest.KRA_RESPONSE_PublicKey"); + response.put(IRemoteRequest.KRA_RESPONSE_PublicKey, value); + } - if (value == null) { - logger.warn("KRARemoteRequestHandler: Missing wrapped private key"); - } else { - logger.info("KRARemoteRequestHandler: Found wrapped private key"); - response.put(IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey, value); - } + value = (String) response.get(IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey); + if (value == null) { + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): response missing name-value pair for: " + + IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey); + } else { + logger.debug("KRARemoteRequestHandler:serverSideKeyGen(): got IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey"); + response.put(IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey, value); + } - value = (String) response.get(IRemoteRequest.KRA_RESPONSE_IV_Param); + value = (String) response.get(IRemoteRequest.KRA_RESPONSE_IV_Param); + if (value == null) { + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): response missing name-value pair for: " + + IRemoteRequest.KRA_RESPONSE_IV_Param); + } else { + logger.debug("KRARemoteRequestHandler:serverSideKeyGen(): got IRemoteRequest.KRA_RESPONSE_IV_Param"); + response.put(IRemoteRequest.KRA_RESPONSE_IV_Param, value); + } - if (value == null) { - logger.warn("KRARemoteRequestHandler: Missing IV param"); + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): ends."); + return new KRAServerSideKeyGenResponse(connid, response); } else { - logger.info("KRARemoteRequestHandler: Found IV param"); - response.put(IRemoteRequest.KRA_RESPONSE_IV_Param, value); + logger.debug("KRARemoteRequestHandler: serverSideKeyGen(): no response content."); + throw new EBaseException("KRARemoteRequestHandler: serverSideKeyGen(): no response content."); } - return new KRAServerSideKeyGenResponse(connid, response); - } /** @@ -238,9 +252,10 @@ public KRARecoverKeyResponse recoverKey( String userid, String sDesKey, String sAesKey, - String b64cert) + String b64cert, + String aesKeyWrapAlg) throws EBaseException { - return recoverKey(cuid, userid, sDesKey,sAesKey, b64cert, BigInteger.valueOf(0)); + return recoverKey(cuid, userid, sDesKey,sAesKey, b64cert, BigInteger.valueOf(0),aesKeyWrapAlg); } public KRARecoverKeyResponse recoverKey( @@ -249,7 +264,8 @@ public KRARecoverKeyResponse recoverKey( String sDesKey, String sAesKey, String b64cert, - BigInteger keyid) + BigInteger keyid, + String aesKeyWrapAlg) throws EBaseException { logger.debug("KRARemoteRequestHandler: recoverKey(): begins."); @@ -260,21 +276,29 @@ public KRARecoverKeyResponse recoverKey( throw new EBaseException("KRARemoteRequestHandler: recoverKey(): input parameter null."); } + String aesWrapAlg = aesKeyWrapAlg; + + //Just check for unsupported values that are not CBC or KWP and give default. + if(aesWrapAlg == null || aesWrapAlg.length() != 3) { + aesWrapAlg = "KWP"; + } + TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + logger.debug("KRARemoteRequestHandler: getting conn id: " + connid); HttpConnector conn = (HttpConnector) subsystem.getConnectionManager().getConnector(connid); if (conn == null) { - logger.error("KRARemoteRequestHandler: recoverKey(): conn null"); + logger.debug("KRARemoteRequestHandler: recoverKey(): conn null"); throw new EBaseException("KRARemoteRequestHandler: recoverKey(): conn null"); } logger.debug("KRARemoteRequestHandler: recoverKey(): sending request to KRA"); String sendMsg = null; try { - String desPart = " "; - String aesPart = " "; + String desPart = ""; + String aesPart = ""; if(sDesKey != null) { desPart = "&" + IRemoteRequest.KRA_Trans_DesKey + "=" + sDesKey; @@ -282,6 +306,7 @@ public KRARecoverKeyResponse recoverKey( if(sAesKey != null) { aesPart = "&" + IRemoteRequest.KRA_Trans_AesKey + "=" + sAesKey; } + if (b64cert != null) { // recover by cert // logger.debug("KRARemoteRequestHandler: recoverKey(): uriEncoded cert= " + b64cert); sendMsg = IRemoteRequest.TOKEN_CUID + "=" + @@ -289,7 +314,10 @@ public KRARecoverKeyResponse recoverKey( "&" + IRemoteRequest.KRA_UserId + "=" + userid + "&" + IRemoteRequest.KRA_RECOVERY_CERT + "=" + - b64cert + desPart + aesPart; + b64cert + desPart + aesPart + + "&" + IRemoteRequest.KRA_Aes_Wrap_Alg + "=" + + aesWrapAlg; + } else if (keyid != BigInteger.valueOf(0)) { // recover by keyid ... keyid != BigInteger.valueOf(0) logger.debug("KRARemoteRequestHandler: recoverKey(): keyid = " + keyid); @@ -298,8 +326,13 @@ public KRARecoverKeyResponse recoverKey( "&" + IRemoteRequest.KRA_UserId + "=" + userid + "&" + IRemoteRequest.KRA_RECOVERY_KEYID + "=" + - keyid.toString() + desPart + aesPart; + keyid.toString() + desPart + aesPart + + "&" + IRemoteRequest.KRA_Aes_Wrap_Alg + "=" + + aesWrapAlg; + + } + //logger.debug("KRARemoteRequestHandler: recoverKey(): outgoing: " + sendMsg); } catch (Exception e) { logger.debug("KRARemoteRequestHandler: recoverKey(): uriEncode failed: " + e); throw new EBaseException("KRARemoteRequestHandler: recoverKey(): uriEncode failed: " + e); @@ -316,67 +349,68 @@ public KRARecoverKeyResponse recoverKey( String content = resp.getContent(); - if (content == null || content.equals("")) { - logger.error("KRARemoteRequestHandler: recoverKey(): no response content."); - throw new EBaseException("KRARemoteRequestHandler: recoverKey(): no response content."); - } - logger.debug("KRARemoteRequestHandler: recoverKey(): got content"); - Hashtable response = - parseResponse(content); - - /** - * When a value is not found in response, keep going so we know - * what else is missing - * Note: response values "missing" might not be bad for some cases - */ - Integer ist = Integer.valueOf(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); - String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); - - logger.debug("KRARemoteRequestHandler: recoverKey(): got status = " + value); - ist = Integer.parseInt(value); - if (ist != 0) { - logger.debug("KRARemoteRequestHandler: recoverKey(): status not 0, getting error string... "); - value = (String) response.get(IRemoteRequest.RESPONSE_ERROR_STRING); + if (content != null && !content.equals("")) { + logger.debug("KRARemoteRequestHandler: recoverKey(): got content"); + Hashtable response = + parseResponse(content); + + /** + * When a value is not found in response, keep going so we know + * what else is missing + * Note: response values "missing" might not be bad for some cases + */ + Integer ist = new Integer(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); + String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); + + logger.debug("KRARemoteRequestHandler: recoverKey(): got status = " + value); + ist = Integer.parseInt(value); + if (ist != 0) { + logger.debug("KRARemoteRequestHandler: recoverKey(): status not 0, getting error string... "); + value = (String) response.get(IRemoteRequest.RESPONSE_ERROR_STRING); + if (value == null) { + logger.debug("KRARemoteRequestHandler: recoverKey(): response missing name-value pair for: " + + IRemoteRequest.RESPONSE_ERROR_STRING); + } else { + logger.debug("KRARemoteRequestHandler: recoverKey(): got IRemoteRequest.RESPONSE_ERROR_STRING = " + + value); + response.put(IRemoteRequest.RESPONSE_ERROR_STRING, value); + } + } + response.put(IRemoteRequest.RESPONSE_STATUS, ist); + + value = (String) response.get(IRemoteRequest.KRA_RESPONSE_PublicKey); if (value == null) { logger.debug("KRARemoteRequestHandler: recoverKey(): response missing name-value pair for: " + - IRemoteRequest.RESPONSE_ERROR_STRING); + IRemoteRequest.KRA_RESPONSE_PublicKey); } else { - logger.debug("KRARemoteRequestHandler: recoverKey(): got IRemoteRequest.RESPONSE_ERROR_STRING = " - + value); - response.put(IRemoteRequest.RESPONSE_ERROR_STRING, value); + //logger.debug("KRARemoteRequestHandler:recoverKey(): got IRemoteRequest.KRA_RESPONSE_PublicKey= " + value); + logger.debug("KRARemoteRequestHandler:recoverKey(): got IRemoteRequest.KRA_RESPONSE_PublicKey"); + response.put(IRemoteRequest.KRA_RESPONSE_PublicKey, value); } - } - response.put(IRemoteRequest.RESPONSE_STATUS, ist); - value = (String) response.get(IRemoteRequest.KRA_RESPONSE_PublicKey); - if (value == null) { - logger.debug("KRARemoteRequestHandler: recoverKey(): response missing name-value pair for: " + - IRemoteRequest.KRA_RESPONSE_PublicKey); - } else { - //logger.debug("KRARemoteRequestHandler:recoverKey(): got IRemoteRequest.KRA_RESPONSE_PublicKey= " + value); - logger.debug("KRARemoteRequestHandler:recoverKey(): got IRemoteRequest.KRA_RESPONSE_PublicKey"); - response.put(IRemoteRequest.KRA_RESPONSE_PublicKey, value); - } + value = (String) response.get(IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey); + if (value == null) { + logger.debug("KRARemoteRequestHandler: recoverKey(): response missing name-value pair for: " + + IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey); + } else { + logger.debug("KRARemoteRequestHandler:recoverKey(): got IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey"); + response.put(IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey, value); + } - value = (String) response.get(IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey); - if (value == null) { - logger.debug("KRARemoteRequestHandler: recoverKey(): response missing name-value pair for: " + - IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey); - } else { - logger.debug("KRARemoteRequestHandler:recoverKey(): got IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey"); - response.put(IRemoteRequest.KRA_RESPONSE_Wrapped_PrivKey, value); - } + value = (String) response.get(IRemoteRequest.KRA_RESPONSE_IV_Param); + if (value == null) { + logger.debug("KRARemoteRequestHandler: recoverKey(): response missing name-value pair for: " + + IRemoteRequest.KRA_RESPONSE_IV_Param); + } else { + logger.debug("KRARemoteRequestHandler:recoverKey(): got IRemoteRequest.KRA_RESPONSE_IV_Param"); + response.put(IRemoteRequest.KRA_RESPONSE_IV_Param, value); + } - value = (String) response.get(IRemoteRequest.KRA_RESPONSE_IV_Param); - if (value == null) { - logger.debug("KRARemoteRequestHandler: recoverKey(): response missing name-value pair for: " + - IRemoteRequest.KRA_RESPONSE_IV_Param); + logger.debug("KRARemoteRequestHandler: recoverKey(): ends."); + return new KRARecoverKeyResponse(connid, response); } else { - logger.debug("KRARemoteRequestHandler:recoverKey(): got IRemoteRequest.KRA_RESPONSE_IV_Param"); - response.put(IRemoteRequest.KRA_RESPONSE_IV_Param, value); + logger.debug("KRARemoteRequestHandler: recoverKey(): no response content."); + throw new EBaseException("KRARemoteRequestHandler: recoverKey(): no response content."); } - - logger.debug("KRARemoteRequestHandler: recoverKey(): ends."); - return new KRARecoverKeyResponse(connid, response); } } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/cms/TKSComputeSessionKeyResponse.java b/base/tps/src/main/java/org/dogtagpki/server/tps/cms/TKSComputeSessionKeyResponse.java index c30e3f04d61..d92879fdc9b 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/cms/TKSComputeSessionKeyResponse.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/cms/TKSComputeSessionKeyResponse.java @@ -59,6 +59,11 @@ public TPSBuffer getKeyCheck() { return (TPSBuffer) nameValTable.get(IRemoteRequest.TKS_RESPONSE_KeyCheck); } + // Applet and Alg Selection by Token Range Support + public TPSBuffer getKeyCheckDes() { + return (TPSBuffer) nameValTable.get(IRemoteRequest.TKS_RESPONSE_KeyCheck_Des); + } + public TPSBuffer getHostCryptogram() { return (TPSBuffer) nameValTable.get(IRemoteRequest.TKS_RESPONSE_HostCryptogram); } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/cms/TKSRemoteRequestHandler.java b/base/tps/src/main/java/org/dogtagpki/server/tps/cms/TKSRemoteRequestHandler.java index 8e300f3299e..f20d8add2cc 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/cms/TKSRemoteRequestHandler.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/cms/TKSRemoteRequestHandler.java @@ -24,14 +24,13 @@ import org.dogtagpki.server.tps.TPSConfig; import org.dogtagpki.server.tps.TPSEngine; import org.dogtagpki.server.tps.TPSEngineConfig; + import org.dogtagpki.server.tps.TPSSubsystem; import org.dogtagpki.server.tps.channel.SecureChannel; import org.dogtagpki.tps.main.TPSBuffer; import org.dogtagpki.tps.main.Util; import com.netscape.certsrv.base.EBaseException; -import com.netscape.certsrv.connector.ConnectorConfig; -import com.netscape.certsrv.connector.ConnectorsConfig; import com.netscape.cmscore.connector.HttpConnector; import com.netscape.cmsutil.http.HttpResponse; @@ -115,11 +114,7 @@ public TKSComputeSessionKeyResponse computeSessionKey( throw new EBaseException("TKSRemoteRequestHandler: computeSessionKey(): input parameter null."); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig conf = engine.getConfig(); - TPSConfig tpsConfig = conf.getTPSConfig(); - ConnectorsConfig connectorsConfig = tpsConfig.getConnectorsConfig(); - ConnectorConfig connectorConfig = connectorsConfig.getConnectorConfig(connid); + TPSEngineConfig conf = this.getConfigStore(); boolean serverKeygen = false; @@ -130,7 +125,7 @@ public TKSComputeSessionKeyResponse computeSessionKey( tokenType + ".keyGen." + keygenString + ".serverKeygen.enable", false); - logger.debug(method + "config serverkegGen enabled for " + keygenString + " : " + enabled); + logger.debug(method + " serverkegGen enabled for " + keygenString + " : " + enabled); if (enabled) { serverKeygen = true; break; @@ -139,9 +134,11 @@ public TKSComputeSessionKeyResponse computeSessionKey( logger.debug(method + " final serverkegGen enabled? " + serverKeygen); if (keySet == null) - keySet = connectorConfig.getString("keySet", "defKeySet"); + keySet = conf.getString("tps.connector." + connid + ".keySet", "defKeySet"); - TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem subsystem = + (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); HttpConnector conn = (HttpConnector) subsystem.getConnectionManager().getConnector(connid); @@ -165,104 +162,104 @@ public TKSComputeSessionKeyResponse computeSessionKey( String content = resp.getContent(); - if (content == null || content.equals("")) { - logger.error("TKSRemoteRequestHandler: computeSessionKey(): no response content."); - throw new EBaseException("TKSRemoteRequestHandler: computeSessionKey(): no response content."); - } - Hashtable response = - parseResponse(content); - - /* - * When a value is not found in response, keep going so we know - * what else is missing - * Note: serverKeygen and !serverKeygen returns different set of - * response values so "missing" might not be bad - */ - Integer ist = Integer.valueOf(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); - String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): status not found."); - //logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got content = " + content); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got status = " + value); - ist = Integer.parseInt(value); - } - response.put(IRemoteRequest.RESPONSE_STATUS, ist); - - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_SessionKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_SessionKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_SessionKey"); - response.put(IRemoteRequest.TKS_RESPONSE_SessionKey, Util.specialDecode(value)); - } + if (content != null && !content.equals("")) { + Hashtable response = + parseResponse(content); + + /* + * When a value is not found in response, keep going so we know + * what else is missing + * Note: serverKeygen and !serverKeygen returns different set of + * response values so "missing" might not be bad + */ + Integer ist = new Integer(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); + String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): status not found."); + //logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got content = " + content); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got status = " + value); + ist = Integer.parseInt(value); + } + response.put(IRemoteRequest.RESPONSE_STATUS, ist); + + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_SessionKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_SessionKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_SessionKey"); + response.put(IRemoteRequest.TKS_RESPONSE_SessionKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_EncSessionKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_EncSessionKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_EncSessionKey"); - response.put(IRemoteRequest.TKS_RESPONSE_EncSessionKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_EncSessionKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_EncSessionKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_EncSessionKey"); + response.put(IRemoteRequest.TKS_RESPONSE_EncSessionKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey"); - response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey"); + response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey "); - response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey "); + response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_DesKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KEK_DesKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_KEK_DesKey"); - response.put(IRemoteRequest.TKS_RESPONSE_KEK_DesKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_DesKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KEK_DesKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_KEK_DesKey"); + response.put(IRemoteRequest.TKS_RESPONSE_KEK_DesKey, Util.specialDecode(value)); + } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_AesKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KEK_AesKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_KEK_AesKey"); + response.put(IRemoteRequest.TKS_RESPONSE_KEK_AesKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_AesKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KEK_AesKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_KEK_AesKey"); - response.put(IRemoteRequest.TKS_RESPONSE_KEK_AesKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeyCheck); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KeyCheck); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_KeyCheck"); + response.put(IRemoteRequest.TKS_RESPONSE_KeyCheck, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeyCheck); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KeyCheck); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_KeyCheck"); - response.put(IRemoteRequest.TKS_RESPONSE_KeyCheck, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_HostCryptogram); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_HostCryptogram); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_HostCryptogram"); + response.put(IRemoteRequest.TKS_RESPONSE_HostCryptogram, Util.specialDecode(value)); + } + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): ends."); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_HostCryptogram); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_HostCryptogram); + return new TKSComputeSessionKeyResponse(response); } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_HostCryptogram"); - response.put(IRemoteRequest.TKS_RESPONSE_HostCryptogram, Util.specialDecode(value)); + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): no response content."); + throw new EBaseException("TKSRemoteRequestHandler: computeSessionKey(): no response content."); } - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): ends."); - - return new TKSComputeSessionKeyResponse(response); } public TKSComputeSessionKeyResponse computeSessionKeysSCP03( @@ -285,11 +282,7 @@ public TKSComputeSessionKeyResponse computeSessionKeysSCP03( throw new EBaseException(method + " invalid input!"); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig conf = engine.getConfig(); - TPSConfig tpsConfig = conf.getTPSConfig(); - ConnectorsConfig connectorsConfig = tpsConfig.getConnectorsConfig(); - ConnectorConfig connectorConfig = connectorsConfig.getConnectorConfig(connid); + TPSEngineConfig conf = this.getConfigStore(); boolean serverKeygen = false; @@ -309,9 +302,11 @@ public TKSComputeSessionKeyResponse computeSessionKeysSCP03( logger.debug(method + " final serverkegGen enabled? " + serverKeygen); if (keySet == null) - keySet = connectorConfig.getString("keySet", "defKeySet"); + keySet = conf.getString("tps.connector." + connid + ".keySet", "defKeySet"); - TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem subsystem = + (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); HttpConnector conn = (HttpConnector) subsystem.getConnectionManager().getConnector(connid); @@ -326,6 +321,9 @@ public TKSComputeSessionKeyResponse computeSessionKeysSCP03( + Util.specialURLEncode(card_cryptogram.toBytesArray()) + "&" + IRemoteRequest.TOKEN_KEYSET + "=" + keySet; + //logger.debug(method + " request to TKS: " + requestString); + logger.debug(method + " sending request to TKS..."); + HttpResponse resp = conn.send("computeSessionKey", requestString @@ -333,117 +331,134 @@ public TKSComputeSessionKeyResponse computeSessionKeysSCP03( String content = resp.getContent(); - if (content == null || content.equals("")) { - logger.error("TKSRemoteRequestHandler: computeSessionKeySCP02(): no response content."); - throw new EBaseException("TKSRemoteRequestHandler: computeSessionKeySCP02(): no response content."); - } - Hashtable response = - parseResponse(content); + if (content != null && !content.equals("")) { + Hashtable response = + parseResponse(content); + + /* + * When a value is not found in response, keep going so we know + * what else is missing + * Note: serverKeygen and !serverKeygen returns different set of + * response values so "missing" might not be bad + */ + Integer ist = new Integer(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); + String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); + if (value == null) { + logger.debug(method + " status not found."); + //logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got content = " + content); + } else { + logger.debug(method + " got status = " + value); + ist = Integer.parseInt(value); + } + response.put(IRemoteRequest.RESPONSE_STATUS, ist); + + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_EncSessionKey); + if (value == null) { + logger.debug(method + " response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_EncSessionKey); + } else { + logger.debug(method+ "got IRemoteRequest.TKS_RESPONSE_EncSessionKey"); + response.put(IRemoteRequest.TKS_RESPONSE_EncSessionKey, Util.specialDecode(value)); + } - /* - * When a value is not found in response, keep going so we know - * what else is missing - * Note: serverKeygen and !serverKeygen returns different set of - * response values so "missing" might not be bad - */ - Integer ist = Integer.valueOf(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); - String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); - if (value == null) { - logger.debug(method + " status not found."); - //logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got content = " + content); - } else { - logger.debug(method + " got status = " + value); - ist = Integer.parseInt(value); - } - response.put(IRemoteRequest.RESPONSE_STATUS, ist); + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); + if (value == null) { + logger.debug(method + " response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); + } else { + logger.debug(method + "got IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey"); + response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_EncSessionKey); - if (value == null) { - logger.debug(method + " response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_EncSessionKey); - } else { - logger.debug(method+ "got IRemoteRequest.TKS_RESPONSE_EncSessionKey"); - response.put(IRemoteRequest.TKS_RESPONSE_EncSessionKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey "); + response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); - if (value == null) { - logger.debug(method + " response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); - } else { - logger.debug(method + "got IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey"); - response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_MacSessionKey); + if (value == null) { + logger.debug(method + "response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_MacSessionKey); + } else { + logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_MacSessionKey"); + response.put(IRemoteRequest.TKS_RESPONSE_MacSessionKey, Util.specialDecode(value)); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKey(): got IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey "); - response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_AesKey, Util.specialDecode(value)); - } + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_MacSessionKey); - if (value == null) { - logger.debug(method + "response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_MacSessionKey); - } else { - logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_MacSessionKey"); - response.put(IRemoteRequest.TKS_RESPONSE_MacSessionKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KekSessionKey); + if (value == null) { + logger.debug(method + "response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KekSessionKey); + } else { + logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KekSessionKey"); + response.put(IRemoteRequest.TKS_RESPONSE_KekSessionKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_AesKey); - if (value == null) { - logger.debug(method + "response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KEK_AesKey); - } else { - logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KEK_AesKey"); - response.put(IRemoteRequest.TKS_RESPONSE_KEK_AesKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_DesKey); + if (value == null) { + logger.debug(method + "response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KEK_DesKey); + } else { + logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KEK_DesKey"); + response.put(IRemoteRequest.TKS_RESPONSE_KEK_DesKey, Util.specialDecode(value)); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KekSessionKey); - if (value == null) { - logger.debug(method + "response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KekSessionKey); - } else { - logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KekSessionKey"); - response.put(IRemoteRequest.TKS_RESPONSE_KekSessionKey, Util.specialDecode(value)); - } + } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_AesKey); + if (value == null) { + logger.debug(method + "response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KEK_AesKey); + } else { + logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KEK_AesKey"); + response.put(IRemoteRequest.TKS_RESPONSE_KEK_AesKey, Util.specialDecode(value)); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_DesKey); - if (value == null) { - logger.debug(method + "response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KEK_DesKey); - } else { - logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KEK_DesKey"); - response.put(IRemoteRequest.TKS_RESPONSE_KEK_DesKey, Util.specialDecode(value)); + } - } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeyCheck); + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeyCheck); - if (value == null) { - logger.debug(method + "response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KeyCheck); + if (value == null) { + logger.debug(method + "response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KeyCheck); - } else { - logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KeyCheck"); - response.put(IRemoteRequest.TKS_RESPONSE_KeyCheck, Util.specialDecode(value)); - } + } else { + logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KeyCheck"); + response.put(IRemoteRequest.TKS_RESPONSE_KeyCheck, Util.specialDecode(value)); + } + + // Applet and Alg Selection by Token Range Support - begin + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeyCheck_Des); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_HostCryptogram); - if ( value == null ) { - logger.debug(method + " response missing name-value pair for: " + IRemoteRequest.TKS_RESPONSE_HostCryptogram); - } else { - logger.debug(method + " got " + IRemoteRequest.TKS_RESPONSE_HostCryptogram); - response.put(IRemoteRequest.TKS_RESPONSE_HostCryptogram, Util.specialDecode(value)); - } + if (value == null) { + logger.debug(method + "response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KeyCheck_Des); + + } else { + logger.debug(method + " got IRemoteRequest.TKS_RESPONSE_KeyCheck_Des"); + response.put(IRemoteRequest.TKS_RESPONSE_KeyCheck_Des, Util.specialDecode(value)); + } + // Applet and Alg Selection by Token Range Support - end + + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_HostCryptogram); + if ( value == null ) { + logger.debug(method + " response missing name-value pair for: " + IRemoteRequest.TKS_RESPONSE_HostCryptogram); + } else { + logger.debug(method + " got " + IRemoteRequest.TKS_RESPONSE_HostCryptogram); + response.put(IRemoteRequest.TKS_RESPONSE_HostCryptogram, Util.specialDecode(value)); + } - logger.debug(method + " ends."); + logger.debug(method + " ends."); - return new TKSComputeSessionKeyResponse(response); + return new TKSComputeSessionKeyResponse(response); + + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): no response content."); + throw new EBaseException("TKSRemoteRequestHandler: computeSessionKeySCP02(): no response content."); + } } @@ -481,7 +496,8 @@ public TKSComputeSessionKeyResponse computeSessionKeySCP02( String tokenType) throws EBaseException { - String method = "TKSRemoteRequestHandler: computeSessionKeySCP02(): "; + String method = "TKSRemoteRequestHandler: computeSessionKeysSCP02(): "; + logger.debug(method + " begins."); if (cuid == null || kdd == null || keyInfo == null || sequenceCounter == null @@ -489,11 +505,7 @@ public TKSComputeSessionKeyResponse computeSessionKeySCP02( throw new EBaseException("TKSRemoteRequestHandler: computeSessionKeySCP02(): input parameter null."); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig conf = engine.getConfig(); - TPSConfig tpsConfig = conf.getTPSConfig(); - ConnectorsConfig connectorsConfig = tpsConfig.getConnectorsConfig(); - ConnectorConfig connectorConfig = connectorsConfig.getConnectorConfig(connid); + TPSEngineConfig conf = this.getConfigStore(); boolean serverKeygen = false; @@ -510,11 +522,14 @@ public TKSComputeSessionKeyResponse computeSessionKeySCP02( break; } } + logger.debug(method + " final serverkegGen enabled? " + serverKeygen); if (keySet == null) - keySet = connectorConfig.getString("keySet", "defKeySet"); + keySet = conf.getString("tps.connector." + connid + ".keySet", "defKeySet"); - TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem subsystem = + (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); HttpConnector conn = (HttpConnector) subsystem.getConnectionManager().getConnector(connid); @@ -534,72 +549,74 @@ public TKSComputeSessionKeyResponse computeSessionKeySCP02( String content = resp.getContent(); - if (content == null || content.equals("")) { - logger.error("TKSRemoteRequestHandler: computeSessionKeySCP02(): no response content."); - throw new EBaseException("TKSRemoteRequestHandler: computeSessionKeySCP02(): no response content."); - } - Hashtable response = - parseResponse(content); + if (content != null && !content.equals("")) { + Hashtable response = + parseResponse(content); + + /* + * When a value is not found in response, keep going so we know + * what else is missing + * Note: serverKeygen and !serverKeygen returns different set of + * response values so "missing" might not be bad + */ + Integer ist = new Integer(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); + String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): status not found."); + //logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got content = " + content); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got status = " + value); + ist = Integer.parseInt(value); + } + response.put(IRemoteRequest.RESPONSE_STATUS, ist); + + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_SessionKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_SessionKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got IRemoteRequest.TKS_RESPONSE_SessionKey"); + response.put(IRemoteRequest.TKS_RESPONSE_SessionKey, Util.specialDecode(value)); + } - /* - * When a value is not found in response, keep going so we know - * what else is missing - * Note: serverKeygen and !serverKeygen returns different set of - * response values so "missing" might not be bad - */ - Integer ist = Integer.valueOf(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); - String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): status not found."); - //logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got content = " + content); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got status = " + value); - ist = Integer.parseInt(value); - } - response.put(IRemoteRequest.RESPONSE_STATUS, ist); + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey"); + response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey, Util.specialDecode(value)); + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_SessionKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_SessionKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got IRemoteRequest.TKS_RESPONSE_SessionKey"); - response.put(IRemoteRequest.TKS_RESPONSE_SessionKey, Util.specialDecode(value)); - } + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_DesKey); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KEK_DesKey); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got IRemoteRequest.TKS_RESPONSE_KEK_DesKey"); + response.put(IRemoteRequest.TKS_RESPONSE_KEK_DesKey, Util.specialDecode(value)); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey"); - response.put(IRemoteRequest.TKS_RESPONSE_DRM_Trans_DesKey, Util.specialDecode(value)); - } + } - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KEK_DesKey); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KEK_DesKey); - } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got IRemoteRequest.TKS_RESPONSE_KEK_DesKey"); - response.put(IRemoteRequest.TKS_RESPONSE_KEK_DesKey, Util.specialDecode(value)); + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeyCheck); - } + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KeyCheck); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeyCheck); + } else { + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got IRemoteRequest.TKS_RESPONSE_KeyCheck"); + response.put(IRemoteRequest.TKS_RESPONSE_KeyCheck, Util.specialDecode(value)); + } + + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): ends."); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KeyCheck); + return new TKSComputeSessionKeyResponse(response); } else { - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): got IRemoteRequest.TKS_RESPONSE_KeyCheck"); - response.put(IRemoteRequest.TKS_RESPONSE_KeyCheck, Util.specialDecode(value)); + logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): no response content."); + throw new EBaseException("TKSRemoteRequestHandler: computeSessionKeySCP02(): no response content."); } - - logger.debug("TKSRemoteRequestHandler: computeSessionKeySCP02(): ends."); - - return new TKSComputeSessionKeyResponse(response); } /* @@ -624,23 +641,20 @@ public TKSComputeSessionKeyResponse computeSessionKeySCP02( public TKSCreateKeySetDataResponse createKeySetData ( TPSBuffer NewMasterVer, TPSBuffer version, - TPSBuffer cuid, TPSBuffer kdd, int protocol, TPSBuffer wrappedDekSessionKey) + TPSBuffer cuid, TPSBuffer kdd, int protocol, TPSBuffer wrappedDekSessionKey, String oldKeySet) // ** G&D 256 Key Rollover Support ** add oldKeySet parameter throws EBaseException { logger.debug("TKSRemoteRequestHandler: createKeySetData(): begins."); if (cuid == null || NewMasterVer == null || version == null) { throw new EBaseException("TKSRemoteRequestHandler: createKeySetData(): input parameter null."); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig conf = engine.getConfig(); - TPSConfig tpsConfig = conf.getTPSConfig(); - ConnectorsConfig connectorsConfig = tpsConfig.getConnectorsConfig(); - ConnectorConfig connectorConfig = connectorsConfig.getConnectorConfig(connid); - + TPSEngineConfig conf = this.getConfigStore(); if (keySet == null) - keySet = connectorConfig.getString("keySet", "defKeySet"); + keySet = conf.getString("tps.connector." + connid + ".keySet", "defKeySet"); - TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem subsystem = + (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); HttpConnector conn = (HttpConnector) subsystem.getConnectionManager().getConnector(connid); logger.debug("TKSRemoteRequestHandler: createKeySetData(): sending request to tks."); @@ -655,50 +669,58 @@ public TKSCreateKeySetDataResponse createKeySetData ( if (wrappedDekSessionKey != null) { // We have secure channel protocol 02 trying to upgrade the key set. command += "&" + IRemoteRequest.WRAPPED_DEK_SESSION_KEY + "=" + Util.specialURLEncode(wrappedDekSessionKey); } - + + // ** G&D 256 Key Rollover Support ** + // include oldKeySet name in the request TKS if provided + if (oldKeySet != null) { + command += "&" + IRemoteRequest.TOKEN_OLD_KEYSET + "=" + oldKeySet; + } + logger.debug("TKSRemoteRequestHandler: createKeySetData(): request to TKS: " + command); + HttpResponse resp = conn.send("createKeySetData", command); String content = resp.getContent(); - if (content == null || content.equals("")) { - logger.error("TKSRemoteRequestHandler: createKeySetData(): no response content."); - throw new EBaseException("TKSRemoteRequestHandler: createKeySetData(): no response content."); - } - Hashtable response = - parseResponse(content); - if (response == null) { - logger.warn("TKSRemoteRequestHandler: createKeySetData(): parseResponse returned null."); - return null; - } + if (content != null && !content.equals("")) { + Hashtable response = + parseResponse(content); + if (response == null) { + logger.debug("TKSRemoteRequestHandler: createKeySetData(): parseResponse returned null."); + return null; + } - /* - * When a value is not found in response, keep going so we know - * what else is missing - */ - Integer ist = Integer.valueOf(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); - String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: createKeySetData(): status not found."); - //logger.debug("TKSRemoteRequestHandler: createKeySetData(): got content = " + content); - } else { - logger.debug("TKSRemoteRequestHandler: createKeySetData(): got status = " + value); - ist = Integer.parseInt(value); - } - response.put(IRemoteRequest.RESPONSE_STATUS, ist); + /* + * When a value is not found in response, keep going so we know + * what else is missing + */ + Integer ist = new Integer(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); + String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: createKeySetData(): status not found."); + //logger.debug("TKSRemoteRequestHandler: createKeySetData(): got content = " + content); + } else { + logger.debug("TKSRemoteRequestHandler: createKeySetData(): got status = " + value); + ist = Integer.parseInt(value); + } + response.put(IRemoteRequest.RESPONSE_STATUS, ist); + + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeySetData); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: createKeySetData(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_KeySetData); + } else { + logger.debug("TKSRemoteRequestHandler: createKeySetData(): got IRemoteRequest.TKS_RESPONSE_KeySetData"); + response.put(IRemoteRequest.TKS_RESPONSE_KeySetData, Util.specialDecode(value)); + } + logger.debug("TKSRemoteRequestHandler: createKeySetData(): ends."); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_KeySetData); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: createKeySetData(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_KeySetData); + return new TKSCreateKeySetDataResponse(response); } else { - logger.debug("TKSRemoteRequestHandler: createKeySetData(): got IRemoteRequest.TKS_RESPONSE_KeySetData"); - response.put(IRemoteRequest.TKS_RESPONSE_KeySetData, Util.specialDecode(value)); + logger.debug("TKSRemoteRequestHandler: createKeySetData(): no response content."); + throw new EBaseException("TKSRemoteRequestHandler: createKeySetData(): no response content."); } - logger.debug("TKSRemoteRequestHandler: createKeySetData(): ends."); - - return new TKSCreateKeySetDataResponse(response); } /* @@ -723,14 +745,13 @@ public TKSComputeRandomDataResponse computeRandomData(int dataSize) * check for absurd dataSize values */ if (dataSize <= 0 || dataSize > 1024) { - logger.error("TKSRemoteRequestHandler: computeRandomData(): invalid dataSize requested:" + dataSize); + logger.debug("TKSRemoteRequestHandler: computeRandomData(): invalid dataSize requested:" + dataSize); throw new EBaseException("TKSRemoteRequestHandler: computeRandomData(): invalid dataSize requested"); } - logger.debug("TKSRemoteRequestHandler: computeRandomData(): sending request to tks."); - TPSEngine engine = TPSEngine.getInstance(); - TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSSubsystem subsystem = + (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); HttpConnector conn = (HttpConnector) subsystem.getConnectionManager().getConnector(connid); HttpResponse resp = @@ -739,41 +760,42 @@ public TKSComputeRandomDataResponse computeRandomData(int dataSize) String content = resp.getContent(); - if (content == null || content.equals("")) { - logger.error("TKSRemoteRequestHandler: computeRandomData(): no response content."); - throw new EBaseException("TKSRemoteRequestHandler: computeRandomData(): no response content."); - } - Hashtable response = - parseResponse(content); - - /* - * When a value is not found in response, keep going so we know - * what else is missing - */ - Integer ist = Integer.valueOf(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); - String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeRandomData(): status not found."); - //logger.debug("TKSRemoteRequestHandler: computeRandomData(): got content = " + content); - } else { - logger.debug("TKSRemoteRequestHandler: computeRandomData(): got status = " + value); - ist = Integer.parseInt(value); - } - response.put(IRemoteRequest.RESPONSE_STATUS, ist); + if (content != null && !content.equals("")) { + Hashtable response = + parseResponse(content); + + /* + * When a value is not found in response, keep going so we know + * what else is missing + */ + Integer ist = new Integer(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); + String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeRandomData(): status not found."); + //logger.debug("TKSRemoteRequestHandler: computeRandomData(): got content = " + content); + } else { + logger.debug("TKSRemoteRequestHandler: computeRandomData(): got status = " + value); + ist = Integer.parseInt(value); + } + response.put(IRemoteRequest.RESPONSE_STATUS, ist); + + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_RandomData); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: computeRandomData(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_RandomData); + } else { + //logger.debug("TKSRemoteRequestHandler: computeRandomData(): got IRemoteRequest.TKS_RESPONSE_RandomData" + // + value); + logger.debug("TKSRemoteRequestHandler: computeRandomData(): got IRemoteRequest.TKS_RESPONSE_RandomData"); + response.put(IRemoteRequest.TKS_RESPONSE_RandomData, Util.uriDecodeFromHex(value)); + } + logger.debug("TKSRemoteRequestHandler: computeRandomData(): ends."); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_RandomData); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: computeRandomData(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_RandomData); + return new TKSComputeRandomDataResponse(response); } else { - //logger.debug("TKSRemoteRequestHandler: computeRandomData(): got IRemoteRequest.TKS_RESPONSE_RandomData" - // + value); - logger.debug("TKSRemoteRequestHandler: computeRandomData(): got IRemoteRequest.TKS_RESPONSE_RandomData"); - response.put(IRemoteRequest.TKS_RESPONSE_RandomData, Util.uriDecodeFromHex(value)); + logger.debug("TKSRemoteRequestHandler: computeRandomData(): no response content."); + throw new EBaseException("TKSRemoteRequestHandler: computeRandomData(): no response content."); } - logger.debug("TKSRemoteRequestHandler: computeRandomData(): ends."); - - return new TKSComputeRandomDataResponse(response); } /* @@ -805,16 +827,14 @@ public TKSEncryptDataResponse encryptData( throw new EBaseException("TKSRemoteRequestHandler: encryptData(): input parameter null."); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig conf = engine.getConfig(); - TPSConfig tpsConfig = conf.getTPSConfig(); - ConnectorsConfig connectorsConfig = tpsConfig.getConnectorsConfig(); - ConnectorConfig connectorConfig = connectorsConfig.getConnectorConfig(connid); + TPSEngineConfig conf = this.getConfigStore(); if (keySet == null) - keySet = connectorConfig.getString("keySet", "defKeySet"); + keySet = conf.getString("tps.connector." + connid + ".keySet", "defKeySet"); - TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem subsystem = + (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); HttpConnector conn = (HttpConnector) subsystem.getConnectionManager().getConnector(connid); logger.debug("TKSRemoteRequestHandler: encryptData(): sending request to tks."); @@ -830,38 +850,46 @@ public TKSEncryptDataResponse encryptData( String content = resp.getContent(); - if (content == null || content.equals("")) { - logger.error("TKSRemoteRequestHandler: encryptData(): no response content."); - throw new EBaseException("TKSRemoteRequestHandler: encryptData(): no response content."); - } - Hashtable response = - parseResponse(content); - - /* - * When a value is not found in response, keep going so we know - * what else is missing - */ - Integer ist = Integer.valueOf(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); - String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: encryptData(): status not found."); - //logger.debug("TKSRemoteRequestHandler: encryptData(): got content = " + content); - } else { - logger.debug("TKSRemoteRequestHandler: encryptData(): got status = " + value); - ist = Integer.parseInt(value); - } - response.put(IRemoteRequest.RESPONSE_STATUS, ist); + if (content != null && !content.equals("")) { + Hashtable response = + parseResponse(content); + + /* + * When a value is not found in response, keep going so we know + * what else is missing + */ + Integer ist = new Integer(IRemoteRequest.RESPONSE_STATUS_NOT_FOUND); + String value = (String) response.get(IRemoteRequest.RESPONSE_STATUS); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: encryptData(): status not found."); + //logger.debug("TKSRemoteRequestHandler: encryptData(): got content = " + content); + } else { + logger.debug("TKSRemoteRequestHandler: encryptData(): got status = " + value); + ist = Integer.parseInt(value); + } + response.put(IRemoteRequest.RESPONSE_STATUS, ist); + + value = (String) response.get(IRemoteRequest.TKS_RESPONSE_EncryptedData); + if (value == null) { + logger.debug("TKSRemoteRequestHandler: encryptData(): response missing name-value pair for: " + + IRemoteRequest.TKS_RESPONSE_EncryptedData); + } else { + logger.debug("TKSRemoteRequestHandler: encryptData(): got IRemoteRequest.TKS_RESPONSE_EncryptedData"); + response.put(IRemoteRequest.TKS_RESPONSE_EncryptedData, Util.specialDecode(value)); + } + logger.debug("TKSRemoteRequestHandler: encryptData(): ends."); - value = (String) response.get(IRemoteRequest.TKS_RESPONSE_EncryptedData); - if (value == null) { - logger.debug("TKSRemoteRequestHandler: encryptData(): response missing name-value pair for: " + - IRemoteRequest.TKS_RESPONSE_EncryptedData); + return new TKSEncryptDataResponse(response); } else { - logger.debug("TKSRemoteRequestHandler: encryptData(): got IRemoteRequest.TKS_RESPONSE_EncryptedData"); - response.put(IRemoteRequest.TKS_RESPONSE_EncryptedData, Util.specialDecode(value)); + logger.debug("TKSRemoteRequestHandler: encryptData(): no response content."); + throw new EBaseException("TKSRemoteRequestHandler: encryptData(): no response content."); } - logger.debug("TKSRemoteRequestHandler: encryptData(): ends."); + } - return new TKSEncryptDataResponse(response); + private TPSEngineConfig getConfigStore() { + TPSEngine engine = TPSEngine.getInstance(); + TPSEngineConfig configStore = engine.getConfig(); + return configStore; } + } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/mapping/BaseMappingResolver.java b/base/tps/src/main/java/org/dogtagpki/server/tps/mapping/BaseMappingResolver.java index 50140126d09..2e9f44c83a5 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/mapping/BaseMappingResolver.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/mapping/BaseMappingResolver.java @@ -1,16 +1,18 @@ package org.dogtagpki.server.tps.mapping; - import org.dogtagpki.server.tps.TPSEngine; import org.dogtagpki.server.tps.TPSEngineConfig; import org.dogtagpki.tps.main.TPSException; +import org.dogtagpki.tps.main.TPSException; + + /** * This class implements the base TPS mapping filter Resolver instance * * @author cfu */ public abstract class BaseMappingResolver { - protected TPSEngineConfig configStore; + protected TPSEngineConfig configStore = null; protected String instanceName = ""; protected String prefix = ""; @@ -21,8 +23,10 @@ public void init(String instName) { instanceName = instName; prefix = MappingResolverManager.MAPPING_RESOLVER_CFG + "." + instanceName; + TPSEngine engine = TPSEngine.getInstance(); configStore = engine.getConfig(); + } public String getName() { @@ -38,5 +42,8 @@ public abstract String getResolvedMapping(FilterMappingParams pPram) public abstract String getResolvedMapping(FilterMappingParams mappingParams, String nameToMap) throws TPSException; - + + // ** G&D 256 Key Rollover Support ** + public abstract String getResolvedMapping(FilterMappingParams mappingParams, String nameToMap, Integer symKeySize) + throws TPSException; } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/mapping/FilterMappingResolver.java b/base/tps/src/main/java/org/dogtagpki/server/tps/mapping/FilterMappingResolver.java index 21045e1d896..8d86f5f0141 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/mapping/FilterMappingResolver.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/mapping/FilterMappingResolver.java @@ -20,7 +20,6 @@ public class FilterMappingResolver extends BaseMappingResolver { public FilterMappingResolver() { } - @Override public String getResolvedMapping(FilterMappingParams mappingParams) throws TPSException { //map tokenType by default @@ -28,9 +27,17 @@ public String getResolvedMapping(FilterMappingParams mappingParams) } // from TPS: RA_Processor::ProcessMappingFilter - @Override public String getResolvedMapping(FilterMappingParams mappingParams, String nameToMap) throws TPSException { + // ** G&D 256 Key Rollover Support ** + // call the overloaded method, passing null for symKeySize + return getResolvedMapping(mappingParams, nameToMap, null); + } + + // ** G&D 256 Key Rollover Support ** + // Overload the method with the symKeySize parameter + public String getResolvedMapping(FilterMappingParams mappingParams, String nameToMap, Integer symKeySize) + throws TPSException { String method = "FilterMappingResolver.getResolvedMapping for "+ nameToMap + ": "; String tokenType = null; String keySet = null; @@ -50,24 +57,34 @@ public String getResolvedMapping(FilterMappingParams mappingParams, String nameT logger.debug(method + " starts"); major_version = mappingParams.getInt(FilterMappingParams.FILTER_PARAM_MAJOR_VERSION); - logger.debug(method + " param major_version: " + major_version); + logger.debug(method + " param major_version =" + major_version); minor_version = mappingParams.getInt(FilterMappingParams.FILTER_PARAM_MINOR_VERSION); - logger.debug(method + " param minor_version: " + minor_version); + logger.debug(method + " param minor_version =" + minor_version); cuid = mappingParams.getString(FilterMappingParams.FILTER_PARAM_CUID); - logger.debug(method + " param cuid: " + cuid); + logger.debug(method + " param cuid =" + cuid); // msn = (String) mappingParams.get(FilterMappingParams.FILTER_PARAM_MSN); // they don't necessarily have extension - extTokenType = mappingParams.getString(FilterMappingParams.FILTER_PARAM_EXT_TOKEN_TYPE, null); - logger.debug(method + " param tokenType extension: " + extTokenType); + try { + extTokenType = mappingParams.getString(FilterMappingParams.FILTER_PARAM_EXT_TOKEN_TYPE); + } catch (TPSException e) { + logger.debug(method + " OK to not have tokenType extension. Continue."); + } + try { + extTokenATR = mappingParams.getString(FilterMappingParams.FILTER_PARAM_EXT_TOKEN_ATR); + } catch (TPSException e) { + logger.debug(method + " OK to not have tokenATR extension. Continue."); + } + try { + extKeySet = mappingParams.getString(FilterMappingParams.FILTER_PARAM_EXT_KEY_SET); + } catch (TPSException e) { + logger.debug(method + " OK to not have keySet extension. Continue."); + } - extTokenATR = mappingParams.getString(FilterMappingParams.FILTER_PARAM_EXT_TOKEN_ATR, null); - logger.debug(method + " param tokenATR extension: " + extTokenATR); - extKeySet = mappingParams.getString(FilterMappingParams.FILTER_PARAM_EXT_KEY_SET, null); - logger.debug(method + " param keySet extension: " + extKeySet); + logger.debug(method + " mapping params retrieved."); String configName = prefix + "." + TPSEngine.CFG_PROFILE_MAPPING_ORDER; @@ -76,14 +93,14 @@ public String getResolvedMapping(FilterMappingParams mappingParams, String nameT configName); mappingOrder = configStore.getString(configName); } catch (EPropertyNotFound e) { - logger.error(method + " exception:" + e.getMessage(), e); + logger.debug(method + " exception:" + e); throw new TPSException( method + " configuration incorrect! Mising mapping order:" + configName, TPSStatus.STATUS_ERROR_MAPPING_RESOLVER_FAILED); } catch (EBaseException e1) { //The whole feature won't work if this is wrong. - logger.error(method + " exception:" + e1.getMessage(), e1); + logger.debug(method + " exception:" + e1); throw new TPSException( method + " Internal error obtaining config value:" + configName, TPSStatus.STATUS_ERROR_MAPPING_RESOLVER_FAILED); @@ -304,7 +321,34 @@ public String getResolvedMapping(FilterMappingParams mappingParams, String nameT continue; } } - + + // ** G&D 256 Key Rollover Support ** + // G&D SPC03 tokens have same token range but different AES key sizes (128 and 256) + // If symKeySize is passed in, and if ...filter.symKeySize is configured, check + // whether the two values match. + // Skip symKeySize comparison if the parameter is not passed in + if (symKeySize != null) { + mappingConfigName = prefix + ".mapping." + mappingId + ".filter.symKeySize"; + logger.debug(method + " mappingConfigName: " + mappingConfigName); + String configSymKeySize = null; + try { + configSymKeySize = configStore.getString(mappingConfigName, null); + } catch (EBaseException e) { + throw new TPSException( + method + " Internal error obtaining config value. Config: " + + mappingConfigName, + TPSStatus.STATUS_ERROR_MAPPING_RESOLVER_FAILED); + } + + // skip symKeySize comparison if not configured + if (configSymKeySize != null && configSymKeySize.length() > 0) { + logger.debug(method + " cuid: " + cuid + ": comparing symKeySize: configured: " + configSymKeySize + " expected: " + symKeySize); + if (Integer.parseInt(configSymKeySize) != symKeySize.intValue()) { + continue; + } + } + } + //if we make it this far, we have a mapped name selectedMappedName = targetMappedName; logger.debug(method + " Selected mapped name: " + selectedMappedName); @@ -312,7 +356,7 @@ public String getResolvedMapping(FilterMappingParams mappingParams, String nameT } if (selectedMappedName == null) { - logger.error(method + " ends, found: " + selectedMappedName); + logger.debug(method + " ends, found: " + selectedMappedName); throw new TPSException(method + " Can't map to target name!", TPSStatus.STATUS_ERROR_MAPPING_RESOLVER_FAILED); } @@ -320,5 +364,4 @@ public String getResolvedMapping(FilterMappingParams mappingParams, String nameT return selectedMappedName; } - } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/processor/CertEnrollInfo.java b/base/tps/src/main/java/org/dogtagpki/server/tps/processor/CertEnrollInfo.java index c862fbb7a99..6c69b66fb0d 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/processor/CertEnrollInfo.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/processor/CertEnrollInfo.java @@ -36,6 +36,8 @@ public class CertEnrollInfo { private String publisherId; private String keyType; private String keyTypePrefix; + private String aesKeyWrapAlg; + private CARetrieveCertResponse recoveredCertData; private KRARecoverKeyResponse recoveredKeyData; @@ -199,6 +201,15 @@ public int getPublicKeyNumber() { return publicKeyNumber; } + public void setAesKeyWrapAlg(String alg) { + aesKeyWrapAlg = alg; + } + + public String getAesKeyWrapAlg() { + return aesKeyWrapAlg; + } + + public void setKeyType(String keyType) { this.keyType = keyType; } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/processor/TPSEnrollProcessor.java b/base/tps/src/main/java/org/dogtagpki/server/tps/processor/TPSEnrollProcessor.java index 03c45d1b52a..c92b3c2e1f3 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/processor/TPSEnrollProcessor.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/processor/TPSEnrollProcessor.java @@ -15,13 +15,9 @@ import java.util.Map; import java.util.zip.DataFormatException; -import org.dogtagpki.server.tps.TPSEngine; -import org.dogtagpki.server.tps.TPSEngine.ENROLL_MODES; -import org.dogtagpki.server.tps.TPSEngineConfig; import org.dogtagpki.server.tps.TPSSession; import org.dogtagpki.server.tps.TPSSubsystem; import org.dogtagpki.server.tps.TPSTokenPolicy; -import org.dogtagpki.server.tps.TokenDBConfig; import org.dogtagpki.server.tps.authentication.TPSAuthenticator; import org.dogtagpki.server.tps.channel.SecureChannel; import org.dogtagpki.server.tps.channel.SecureChannel.TokenKeyType; @@ -36,6 +32,8 @@ import org.dogtagpki.server.tps.dbs.TPSCertRecord; import org.dogtagpki.server.tps.dbs.TokenCertStatus; import org.dogtagpki.server.tps.dbs.TokenRecord; +import org.dogtagpki.server.tps.TPSEngine; +import org.dogtagpki.server.tps.TPSEngine.ENROLL_MODES; import org.dogtagpki.server.tps.main.AttributeSpec; import org.dogtagpki.server.tps.main.ExternalRegAttrs; import org.dogtagpki.server.tps.main.ExternalRegCertToRecover; @@ -47,27 +45,39 @@ import org.dogtagpki.tps.main.TPSException; import org.dogtagpki.tps.main.Util; import org.dogtagpki.tps.msg.BeginOpMsg; +import org.dogtagpki.tps.msg.EndOpMsg; import org.dogtagpki.tps.msg.EndOpMsg.TPSStatus; import org.mozilla.jss.asn1.InvalidBERException; import org.mozilla.jss.crypto.InvalidKeyFormatException; -import org.mozilla.jss.netscape.security.provider.RSAPublicKey; -import org.mozilla.jss.netscape.security.util.BigInt; -import org.mozilla.jss.netscape.security.util.Utils; -import org.mozilla.jss.netscape.security.x509.RevocationReason; -import org.mozilla.jss.netscape.security.x509.X509CertImpl; import org.mozilla.jss.pkcs11.PK11PubKey; import org.mozilla.jss.pkcs11.PK11RSAPublicKey; -import org.mozilla.jss.pkcs11.PKCS11Constants; import org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo; import com.netscape.certsrv.base.EBaseException; import com.netscape.certsrv.base.EPropertyNotFound; +import org.dogtagpki.server.tps.TPSEngineConfig; import com.netscape.certsrv.logging.AuditEvent; import com.netscape.certsrv.tps.token.TokenStatus; import com.netscape.cmscore.apps.CMS; -import com.netscape.cmscore.logging.Auditor; + import com.netscape.cmscore.security.JssSubsystem; +import org.mozilla.jss.netscape.security.util.Utils; + +import org.mozilla.jss.netscape.security.provider.RSAPublicKey; + + +import org.mozilla.jss.netscape.security.util.BigInt; +import org.mozilla.jss.netscape.security.util.Utils; +import org.mozilla.jss.netscape.security.x509.RevocationReason; +import org.mozilla.jss.netscape.security.x509.X509CertImpl; + +import org.mozilla.jss.pkcs11.PK11PubKey; +import org.mozilla.jss.pkcs11.PK11RSAPublicKey; +import org.mozilla.jss.pkcs11.PKCS11Constants; + + + public class TPSEnrollProcessor extends TPSProcessor { public static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TPSEnrollProcessor.class); @@ -80,7 +90,7 @@ public TPSEnrollProcessor(TPSSession session) { public void process(BeginOpMsg beginMsg) throws TPSException, IOException { if (beginMsg == null) { - throw new TPSException("TPSEnrollrocessor.process: invalid input data, not beginMsg provided.", + throw new TPSException("TPSEnrollrocessor.process: invalid input data, no beginMsg provided.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } setBeginMessage(beginMsg); @@ -96,13 +106,11 @@ private void enroll() throws TPSException, IOException { logger.debug(method + " entering..."); String logMsg = null; String auditInfo = null; - TPSEngine engine = TPSEngine.getInstance(); - JssSubsystem jssSubsystem = engine.getJSSSubsystem(); - TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); - TPSTokenPolicy tokenPolicy = null; - TPSEngineConfig configStore = engine.getConfig(); + + TPSTokenPolicy tokenPolicy = null; + TPSEngineConfig configStore = this.getConfigStore(); String configName; AppletInfo appletInfo = null; @@ -126,15 +134,13 @@ private void enroll() throws TPSException, IOException { throw e; } - appletInfo.setAid(getCardManagerAID()); - logger.debug(method + " token cuid: " + appletInfo.getCUIDhexStringPlain()); boolean isTokenPresent = false; tokenRecord = isTokenRecordPresent(appletInfo); if (tokenRecord != null) { - logger.debug("{} found token... policy: {}", method, tokenRecord.getPolicy()); + logger.debug(method + " found token... policy: " + tokenRecord.getPolicy()); isTokenPresent = true; } else { logger.debug(method + " token does not exist in tokendb... create one in memory"); @@ -164,7 +170,7 @@ private void enroll() throws TPSException, IOException { try { authId = configStore.getString(configName); } catch (EBaseException e) { - logger.error(method + " Internal Error obtaining mandatory config values: " + e.getMessage(), e); + logger.debug(method + " Internal Error obtaining mandatory config values. Error: " + e); logMsg = "TPS error getting config values from config store." + e.toString(); tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, "failure"); @@ -184,7 +190,7 @@ private void enroll() throws TPSException, IOException { auditAuthFailure(userid, currentTokenOperation, appletInfo, (userAuth != null) ? userAuth.getID() : null); - logger.error(method + ": authentication exception thrown: " + e.getMessage(), e); + logger.debug(method + ": authentication exception thrown: " + e); logMsg = "ExternalReg authentication failed, status = STATUS_ERROR_LOGIN"; tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, @@ -208,9 +214,7 @@ private void enroll() throws TPSException, IOException { // otherwise stop the operation. logger.debug(method + " checking if record registrationtype matches currentTokenOperation."); if(erAttrs.getRegistrationType() != null && erAttrs.getRegistrationType().length() > 0) { - if(erAttrs.getRegistrationType().equalsIgnoreCase(currentTokenOperation)) { - logger.debug(method + ": --> registrationtype matches currentTokenOperation"); - } else { + if(!erAttrs.getRegistrationType().equalsIgnoreCase(currentTokenOperation)) { logger.debug( method + " Error: registrationType " + erAttrs.getRegistrationType() + @@ -220,11 +224,14 @@ private void enroll() throws TPSException, IOException { tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, "failure"); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_LOGIN); + } else { + logger.debug(method + ": --> registrationtype matches currentTokenOperation"); } } else { logger.debug(method + ": --> registrationtype attribute disabled or not found, continuing."); } + /* * If cuid is provided on the user registration record, then * we have to compare that with the current token cuid; @@ -236,16 +243,16 @@ private void enroll() throws TPSException, IOException { logger.debug(method + " checking if token cuid matches record cuid"); logger.debug(method + " erAttrs.getTokenCUID()=" + erAttrs.getTokenCUID()); logger.debug(method + " tokenRecord.getId()=" + tokenRecord.getId()); - if (tokenRecord.getId().equalsIgnoreCase(erAttrs.getTokenCUID())) { - logMsg = "isExternalReg: token CUID matches record"; - logger.debug(method + logMsg); - } else { + if (!tokenRecord.getId().equalsIgnoreCase(erAttrs.getTokenCUID())) { logMsg = "isExternalReg: token CUID not matching record:" + tokenRecord.getId() + " : " + erAttrs.getTokenCUID(); - logger.error(method + logMsg); + logger.debug(method + logMsg); tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, "failure"); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_NOT_TOKEN_OWNER); + } else { + logMsg = "isExternalReg: token CUID matches record"; + logger.debug(method + logMsg); } } else { logger.debug(method + " no need to check if token cuid matches record"); @@ -266,12 +273,38 @@ private void enroll() throws TPSException, IOException { FilterMappingParams mappingParams = createFilterMappingParams(resolverInstName, appletInfo.getCUIDhexStringPlain(), appletInfo.getMSNString(), appletInfo.getMajorVersion(), appletInfo.getMinorVersion()); + TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + BaseMappingResolver resolverInst = subsystem.getMappingResolverManager() .getResolverInstance(resolverInstName); - String keySet = resolverInst.getResolvedMapping(mappingParams, "keySet"); + + // ** G&D 256 Key Rollover Support ** + // Get the key size on card and pass it in to getResolvedMapping + Integer symKeySize = getCardSymKeyLength(appletInfo.getCUIDhexStringPlain()); + logger.debug(method + " symKeySize on card: " + symKeySize); + + String keySet = resolverInst.getResolvedMapping(mappingParams, "keySet", symKeySize); setSelectedKeySet(keySet); logger.debug(method + " resolved keySet: " + keySet); + + // ** Applet and Alg Selection by Token Range Support begin ** + try { + String keyWrapAlg = resolverInst.getResolvedMapping(mappingParams, "keyWrapAlg", symKeySize); + setSelectedKeyWrapAlg(keyWrapAlg); + logger.debug(method + " resolved keyWrapAlg: " + keyWrapAlg); + } catch (TPSException e) { + logger.debug(method + " OK not to have keyWrapAlg target in token range mapping"); + } + + try { + String appletVer = resolverInst.getResolvedMapping(mappingParams, "appletVer", symKeySize); + setSelectedAppletVer(appletVer); + logger.debug(method + " resolved appletVer: " + appletVer); + } catch (TPSException e) { + logger.debug(method + " OK not to have appletVer target in token range mapping"); + } + // ** Applet and Alg Selection by Token Range Support end ** } } catch (TPSException e) { logMsg = e.toString(); @@ -281,7 +314,6 @@ private void enroll() throws TPSException, IOException { throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_MISCONFIGURATION); } } else { - logger.debug(method + " isExternalReg: OFF"); /* * Note: op.enroll.mappingResolver=none indicates no resolver * plugin used (tokenType resolved perhaps via authentication) @@ -309,9 +341,17 @@ private void enroll() throws TPSException, IOException { } } + //RedHat do this to check the fact that DES has been configured for the non external Reg legacy key wrapping. + if(!isExternalReg) { + //RedHat method name change + String aesKeyWrapAlg = establishSymKeyWrapAlgSSKeyGen(); + //We don't care about the answer here, we just want to set the fact that des is configured. + logger.debug(method + " non external reg: aesKeyWrapAlg: " + aesKeyWrapAlg); + } + checkProfileStateOK(); - boolean doForceFormat = false; + boolean do_force_format = false; if (isTokenPresent) { logger.debug(method + " token exists in tokendb"); @@ -320,11 +360,8 @@ private void enroll() throws TPSException, IOException { checkInvalidTokenStatus(tokenRecord, ActivityDatabase.OP_ENROLLMENT); - if (tps.isOperationTransitionAllowed(tokenRecord, newState)) { - logger.debug(method + " token transition allowed " + - tokenRecord.getTokenStatus() + " to " + newState); - } else { - logger.error(method + " token transition disallowed " + + if (!tps.isOperationTransitionAllowed(tokenRecord, newState)) { + logger.debug(method + " token transition disallowed " + tokenRecord.getTokenStatus() + " to " + newState); logMsg = "Operation for CUID " + cuid + @@ -335,31 +372,37 @@ private void enroll() throws TPSException, IOException { throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_DISABLED_TOKEN); + } else { + logger.debug("TPSPEnrollrocessor.enroll: token transition allowed " + + tokenRecord.getTokenStatus() + + " to " + newState); } - tokenPolicy = new TPSTokenPolicy(tps, cuid); - doForceFormat = tokenPolicy.isForceTokenFormat(); - if (doForceFormat) + tokenPolicy = new TPSTokenPolicy(tps,cuid); + do_force_format = tokenPolicy.isForceTokenFormat(); + if (do_force_format) logger.debug(method + " Will force format first due to policy."); - if (isExternalReg || tokenPolicy.isAllowdTokenReenroll() || tokenPolicy.isAllowdTokenRenew()) { - logMsg = "isExternalReg: skip token policy (reenroll, renewal) check"; - logger.debug(method + logMsg); - } else { - logger.error(method + " token renewal or reEnroll disallowed"); + if (!isExternalReg && + !tokenPolicy.isAllowdTokenReenroll() && + !tokenPolicy.isAllowdTokenRenew()) { + logger.debug(method + " token renewal or reEnroll disallowed "); logMsg = "Operation renewal or reEnroll for CUID " + cuid + - " Disabled"; + " Disabled"; tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, - "failure"); + "failure"); throw new TPSException(logMsg, - TPSStatus.STATUS_ERROR_DISABLED_TOKEN); - } + TPSStatus.STATUS_ERROR_DISABLED_TOKEN); + } else { + logMsg = "isExternalReg: skip token policy (reenroll, renewal) check"; + logger.debug(method + logMsg); + } } else { logger.debug(method + " token does not exist"); checkAllowUnknownToken(TPSEngine.ENROLL_OP); logger.debug(method + "force a format"); - doForceFormat = true; + do_force_format = true; } // isExternalReg : user already authenticated earlier @@ -384,7 +427,7 @@ private void enroll() throws TPSException, IOException { } - if (doForceFormat) { + if (do_force_format) { //We will skip the auth step inside of format format(true); } else { @@ -405,7 +448,7 @@ private void enroll() throws TPSException, IOException { String tksConnId = getTKSConnectorID(); TPSBuffer plaintextChallenge = computeRandomData(16, tksConnId); - //logger.debug(method + " plaintextChallenge: " + plaintextChallenge.toHexString()); +// logger.debug(method + " plaintextChallenge: " + plaintextChallenge.toHexString()); //These will be used shortly TPSBuffer wrappedChallenge = encryptData(appletInfo, channel.getKeyInfoData(), plaintextChallenge, tksConnId, @@ -456,7 +499,7 @@ else if (status == TPSStatus.STATUS_RECOVERY_IS_PROCESSED) { renewed = true; tps.tdb.tdbActivity(ActivityDatabase.OP_RENEWAL, tokenRecord, session.getIpAddress(), logMsg, "success"); } else { - logger.error(method + logMsg); + logger.debug(method + logMsg); tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, "failure"); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); @@ -467,7 +510,18 @@ else if (status == TPSStatus.STATUS_RECOVERY_IS_PROCESSED) { logger.debug(method + logMsg); } if (status == TPSStatus.STATUS_NO_ERROR) { - if (generateCertificates(certsInfo, channel, appletInfo)) { + if (!generateCertificates(certsInfo, channel, appletInfo)) { + logger.debug(method + "generateCertificates returned false means cert enrollment unsuccessful"); + // in case isExternalReg, leave the token alone, do not format + if (!isExternalReg) { + logger.debug(method + + "generateCertificates returned false means some certs failed enrollment; clean up (format) the token"); + format(true /*skipAuth*/); + } + tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, + "failure"); + throw new TPSException("generateCertificates failed", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); + } else { logger.debug(method + "generateCertificates returned true means cert enrollment successful"); /* * isExternalReg - @@ -491,7 +545,7 @@ else if (status == TPSStatus.STATUS_RECOVERY_IS_PROCESSED) { logMsg, "success"); } else { logMsg = method + " externalRegRecover returned: recoverStatus=" + recoverStatus; - logger.error(logMsg); + logger.debug(logMsg); tps.tdb.tdbActivity(ActivityDatabase.OP_RECOVERY, tokenRecord, session.getIpAddress(), logMsg, "failure"); @@ -499,8 +553,8 @@ else if (status == TPSStatus.STATUS_RECOVERY_IS_PROCESSED) { throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } } catch (EBaseException e) { - logMsg = method + " externalRegRecover: " + e.getMessage(); - logger.error(logMsg, e); + logMsg = method + " externalRegRecover: " + e; + logger.debug(logMsg); tps.tdb.tdbActivity(ActivityDatabase.OP_RECOVERY, tokenRecord, session.getIpAddress(), logMsg, "failure"); @@ -512,17 +566,6 @@ else if (status == TPSStatus.STATUS_RECOVERY_IS_PROCESSED) { //tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, //"success"); } - } else { - logger.error(method + "generateCertificates returned false means cert enrollment unsuccessful"); - // in case isExternalReg, leave the token alone, do not format - if (!isExternalReg) { - logger.warn(method - + "generateCertificates returned false means some certs failed enrollment; clean up (format) the token"); - format(true /*skipAuth*/); - } - tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), logMsg, - "failure"); - throw new TPSException("generateCertificates failed", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } } // at this point, enrollment, renewal, or recovery have been processed accordingly; @@ -550,6 +593,7 @@ else if (status == TPSStatus.STATUS_RECOVERY_IS_PROCESSED) { if (lastObjVer != 0) { while (lastObjVer == 0xff) { + JssSubsystem jssSubsystem = engine.getJSSSubsystem(); SecureRandom randomGenerator = jssSubsystem.getRandomNumberGenerator(); lastObjVer = randomGenerator.nextInt(1000); } @@ -612,16 +656,15 @@ else if (status == TPSStatus.STATUS_RECOVERY_IS_PROCESSED) { // spare the retained certs tps.tdb.tdbRemoveCertificatesByCUID(tokenRecord.getId(), erCertsToRecover); } catch (Exception e) { - logMsg = "Attempt to clean up record with tdbRemoveCertificatesByCUID failed; token probably clean; continue anyway: " - + e.getMessage(); - logger.warn(method + logMsg, e); + logMsg = "Attempt to clean up record with tdbRemoveCertificatesByCUID failed; token probably clean; continue anyway:" + + e; + logger.debug(method + logMsg); } // transform EnrolledCertsInfo to TPSCertRecords ArrayList certRecords = certsInfo.toTPSCertRecords(tokenRecord.getId(), tokenRecord.getUserID()); logger.debug(method + " adding certs to token with tdbAddCertificatesForCUID..."); - try { tps.tdb.tdbAddCertificatesForCUID(tokenRecord.getId(), certRecords); logger.debug(method + " tokendb updated with certs to the cuid so that it reflects what's on the token"); @@ -672,8 +715,7 @@ private TPSStatus cleanObjectListBeforeExternalRecovery(EnrolledCertsInfo certsI TPSStatus status = TPSStatus.STATUS_NO_ERROR; final String method = "TPSEnrollProcessor.cleanObjectListBeforeExternalRecovery :"; final int MAX_CERTS = 30; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); /* * Arrays that hold simple indexes of certsToDelete and certsToSave. @@ -688,30 +730,32 @@ private TPSStatus cleanObjectListBeforeExternalRecovery(EnrolledCertsInfo certsI logger.debug(method + ": begins"); if (certsInfo == null) { - logger.warn(method + "certsInfo cannot be null"); + logger.debug(method + "certsInfo cannot be null"); return TPSStatus.STATUS_ERROR_MISCONFIGURATION; } PKCS11Obj pkcs11obj = certsInfo.getPKCS11Obj(); if (pkcs11obj == null) { - logger.warn(method + "no pkcs11obj to work with"); + logger.debug(method + "no pkcs11obj to work with"); return TPSStatus.STATUS_ERROR_MISCONFIGURATION; } ExternalRegAttrs erAttrs = session.getExternalRegAttrs(); if (session == null || erAttrs == null || erAttrs.getCertsToRecover() == null) { - logger.warn(method + "no externalReg attrs to work with"); + logger.debug(method + "no externalReg attrs to work with"); return TPSStatus.STATUS_ERROR_MISCONFIGURATION; } int count = erAttrs.getCertsToRecoverCount(); logger.debug(method + "number of certs to recover=" + count); if (count == 0) { - logger.warn(method + " nothing to process. Returning status: " + status); + logger.debug(method + " nothing to process. Returning status: " + + status); return status; } String tokenType = erAttrs.getTokenType(); if (tokenType == null) { - logger.warn(method + " erAttrs tokenType null. Returning status: " + status); + logger.debug(method + " erAttrs tokenType null. Returning status: " + + status); return TPSStatus.STATUS_ERROR_MISCONFIGURATION; } @@ -745,10 +789,10 @@ private TPSStatus cleanObjectListBeforeExternalRecovery(EnrolledCertsInfo certsI logger.debug(method + " getting config : " + configName); keyTypeValue = configStore.getString(configName); } catch (EPropertyNotFound e) { - logger.warn(method + e.getMessage(), e); + e.printStackTrace(); return TPSStatus.STATUS_ERROR_MISCONFIGURATION; } catch (EBaseException e) { - logger.warn(method + e.getMessage(), e); + e.printStackTrace(); return TPSStatus.STATUS_ERROR_MISCONFIGURATION; } logger.debug(method + " config keyTypeValue: " + keyTypeValue); @@ -762,10 +806,10 @@ private TPSStatus cleanObjectListBeforeExternalRecovery(EnrolledCertsInfo certsI logger.debug(method + " getting config : " + configName); certId = configStore.getString(configName); } catch (EPropertyNotFound e) { - logger.warn(method + e.getMessage(), e); + e.printStackTrace(); return TPSStatus.STATUS_ERROR_MISCONFIGURATION; } catch (EBaseException e) { - logger.warn(method + e.getMessage(), e); + e.printStackTrace(); return TPSStatus.STATUS_ERROR_MISCONFIGURATION; } if (certId != null && certId.length() > 1) { @@ -806,7 +850,8 @@ private TPSStatus cleanObjectListBeforeExternalRecovery(EnrolledCertsInfo certsI try { xCert = new X509CertImpl(certBuff.toBytesArray()); } catch (CertificateException e) { - logger.error(method + e.getMessage(), e); + logger.debug(method + e); + e.printStackTrace(); return TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU; } ExternalRegCertToRecover certToRecover = @@ -869,7 +914,8 @@ private TPSStatus cleanObjectListBeforeExternalRecovery(EnrolledCertsInfo certsI num_objs = pkcs11obj.getObjectSpecCount(); logger.debug(method + "after removeCertFromObjectList(); final obj count: " + num_objs); - logger.debug(method + " ends. Returning status: " + status); + logger.debug(method + " ends. Returning status: " + + status); return status; } @@ -921,22 +967,19 @@ void removeCertFromObjectList(int cIndex, PKCS11Obj pkcs11obj) { private void writeFinalPKCS11ObjectToToken(PKCS11Obj pkcs11objx, AppletInfo ainfo, SecureChannel channel) throws TPSException, IOException { - - final String method = "TPSEnrollProcessor.writeFinalPKCS11ObjectToToken"; if (pkcs11objx == null || ainfo == null || channel == null) { throw new TPSException("TPSErollProcessor.writeFinalPKCS11ObjectToToken: invalid input data!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - logger.debug(method + ": entering..."); + logger.debug("TPSEnrollProcessor.writeFinalPKCS11ObjectToToken: entering..."); - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String compressConfig = "op." + currentTokenOperation + "." + selectedTokenType + "." + "pkcs11obj.compress.enable"; - logger.debug(method + ": config to check: " + compressConfig); + logger.debug("TPSEnrollProcessor.writeFinalPKCS11ObjectToToken: config to check: " + compressConfig); boolean doCompress = false; @@ -944,10 +987,10 @@ private void writeFinalPKCS11ObjectToToken(PKCS11Obj pkcs11objx, AppletInfo ainf doCompress = configStore.getBoolean(compressConfig, true); } catch (EBaseException e) { throw new TPSException( - method + ": internal error obtaining config value " + e); + "TPSEnrollProcessor.writeFinalPKCS11ObjectToToken: internal error obtaining config value " + e); } - logger.debug(method + ": doCompress: " + doCompress); + logger.debug("TPSEnrollProcessor.writeFinalPKCS11ObjectToToken: doCompress: " + doCompress); TPSBuffer tokenData = null; @@ -961,7 +1004,7 @@ private void writeFinalPKCS11ObjectToToken(PKCS11Obj pkcs11objx, AppletInfo ainf if (tokenData.size() > ainfo.getTotalMem()) { throw new TPSException( - method + ": NOt enough memory to write certificates!", + "TPSEnrollProcessor.writeFinalPKCS11ObjectToToken: NOt enough memory to write certificates!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -974,14 +1017,13 @@ private void writeFinalPKCS11ObjectToToken(PKCS11Obj pkcs11objx, AppletInfo ainf channel.writeObject(zobjidBuf, tokenData); - logger.debug(method + ": leaving successfully ..."); + logger.debug("TPSEnrollProcessor.writeFinalPKCS11ObjectToToken: leaving successfully ..."); } private PKCS11Obj getCurrentObjectsOnToken(SecureChannel channel) throws TPSException, IOException, DataFormatException { - final String method = "TPSEnrollProcessor.getCurrentObjectsOnToken"; byte seq = 0; TPSBuffer objects = null; @@ -995,7 +1037,7 @@ private PKCS11Obj getCurrentObjectsOnToken(SecureChannel channel) throws TPSExce lastObjectVersion = randomGenerator.nextInt(1000); - logger.debug(method + ": Random lastObjectVersion: " + lastObjectVersion); + logger.debug("PKCS11Obj.getCurrentObjectsOnToken: Random lastObjectVersion: " + lastObjectVersion); PKCS11Obj pkcs11objx = new PKCS11Obj(); pkcs11objx.setOldFormatVersion(lastFormatVersion); @@ -1006,8 +1048,8 @@ private PKCS11Obj getCurrentObjectsOnToken(SecureChannel channel) throws TPSExce objects = listObjects(seq); if (objects != null) { - //logger.debug(method + ": objects: " + objects.toHexString()); - logger.debug(method + ": objects exist "); + //logger.debug("PKCS11Obj.getCurrentObjectsOnToken: objects: " + objects.toHexString()); + logger.debug("PKCS11Obj.getCurrentObjectsOnToken: objects exist "); } if (objects == null) { @@ -1025,16 +1067,11 @@ private PKCS11Obj getCurrentObjectsOnToken(SecureChannel channel) throws TPSExce TPSBuffer obj = channel.readObject(objectID, 0, (int) objectLenVal); - if (obj != null) { - //logger.debug(method + ": obj: " + obj.toHexString()); - logger.debug(method + ": obj exists"); - } - if ((char) objectID.at(0) == (byte) 'z' && objectID.at(1) == (byte) '0') { lastFormatVersion = obj.getIntFrom2Bytes(0); lastObjectVersion = obj.getIntFrom2Bytes(2); - logger.debug(method + ": Versions read from token: lastFormatVersion : " + logger.debug("PKCS11Obj.getCurrentObjectsOnToken: Versions read from token: lastFormatVersion : " + lastFormatVersion + " lastObjectVersion: " + lastObjectVersion); @@ -1049,9 +1086,9 @@ private PKCS11Obj getCurrentObjectsOnToken(SecureChannel channel) throws TPSExce pkcs11objx.addObjectSpec(objSpec); } - //logger.debug(method + ": just read object from token: " + //logger.debug("TPSEnrollProcessor.getCurrentObjectsOnToken. just read object from token: " // + obj.toHexString()); - logger.debug(method + ": just read object from token"); + logger.debug("TPSEnrollProcessor.getCurrentObjectsOnToken. just read object from token"); } } while (seq != 0); @@ -1070,7 +1107,7 @@ private ExternalRegCertToRecover isInCertsToRecoverList(X509CertImpl xCert) { final String method = "TPSEnrollProcessor.isInCertsToRecoverList :"; ExternalRegCertToRecover foundObj = null; if (xCert == null) { - logger.warn(method + "xCert is null. return false"); + logger.debug(method + "xCert is null. return false"); return null; } ExternalRegAttrs erAttrs = session.getExternalRegAttrs(); @@ -1079,7 +1116,7 @@ private ExternalRegCertToRecover isInCertsToRecoverList(X509CertImpl xCert) { int count = erAttrs.getCertsToRecoverCount(); if (count <= 0) { - logger.warn(method + "ends. recover list empty. returning: null"); + logger.debug(method + "ends. recover list empty. returning: null"); return null; } @@ -1113,10 +1150,12 @@ private TPSStatus generateCertsAfterRenewalRecoveryPolicy(EnrolledCertsInfo cert String logMsg; final String method = "TPSEnrollProcessor.generateCertsAfterRenewalRecoveryPolicy"; logger.debug(method + ": begins"); - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String configName; + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSTokenPolicy tokenPolicy = null; ArrayList tokenRecords = null; @@ -1125,8 +1164,8 @@ private TPSStatus generateCertsAfterRenewalRecoveryPolicy(EnrolledCertsInfo cert } catch (Exception e) { //TODO: when do you get here? // no existing record, means no "renewal" or "recovery" actions needed - logMsg = "no token associated with user: " + userid + ": " + e.getMessage(); - logger.error(method + logMsg, e); + logMsg = "no token associated with user: " + userid; + logger.debug(method + logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_INACTIVE_TOKEN_NOT_FOUND); } logger.debug(method + " found " + tokenRecords.size() + " tokens for user:" + userid); @@ -1151,14 +1190,15 @@ private TPSStatus generateCertsAfterRenewalRecoveryPolicy(EnrolledCertsInfo cert logger.debug(method + ": need to do enrollment"); // need to do enrollment outside break; - } - logger.debug(method + ": There are multiple token entries for user " - + userid); + } else { + logger.debug(method + ": There are multiple token entries for user " + + userid); - //We already know the current token is not active - if (checkUserAlreadyHasActiveToken(userid) == false) { - isRecover = true; - continue; // TODO: or break? + //We already know the current token is not active + if (checkUserAlreadyHasActiveToken(userid) == false) { + isRecover = true; + continue; // TODO: or break? + } } } else if (tokenRecord.getTokenStatus() == TokenStatus.ACTIVE) { @@ -1166,20 +1206,21 @@ private TPSStatus generateCertsAfterRenewalRecoveryPolicy(EnrolledCertsInfo cert tokenPolicy = new TPSTokenPolicy(tps,aInfo.getCUIDhexStringPlain()); if (tokenPolicy.isAllowdTokenRenew()) { return processRenewal(certsInfo, channel, aInfo, tokenRecord); + } else { + logMsg = "token is already active; can't renew because renewal is not allowed; will re-enroll if allowed"; + logger.debug(method + ":" + logMsg); } - logMsg = "token is already active; can't renew because renewal is not allowed; will re-enroll if allowed"; - logger.debug(method + ":" + logMsg); break; } else if (tokenRecord.getTokenStatus() == TokenStatus.TERMINATED) { logMsg = "terminated token cuid=" + aInfo.getCUIDhexStringPlain() + " cannot be reused"; - logger.error(method + ":" + logMsg); + logger.debug(method + ":" + logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_TOKEN_TERMINATED); } else if (tokenRecord.getTokenStatus() == TokenStatus.PERM_LOST) { logMsg = "This token cannot be reused because it has been reported lost"; - logger.error(method + ": " + logMsg); + logger.debug(method + ": " + logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_UNUSABLE_TOKEN_KEYCOMPROMISE); } else if (tokenRecord.getTokenStatus() == TokenStatus.SUSPENDED) { @@ -1190,12 +1231,13 @@ private TPSStatus generateCertsAfterRenewalRecoveryPolicy(EnrolledCertsInfo cert } else if (tokenRecord.getTokenStatus() == TokenStatus.DAMAGED) { logMsg = "This destroyed lost case should not be executed because the token is so damaged. It should not get here"; - logger.error(method + ": " + logMsg); + logger.debug(method + ": " + + logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_DISABLED_TOKEN); } else { logMsg = "No such token status for this cuid=" + aInfo.getCUIDhexStringPlain(); - logger.error(method + ":" + logMsg); + logger.debug(method + ":" + logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_NO_SUCH_TOKEN_STATE); } @@ -1238,19 +1280,19 @@ private TPSStatus generateCertsAfterRenewalRecoveryPolicy(EnrolledCertsInfo cert // ToDo: This section has not been tested to work.. Make sure this works. - configStore = engine.getConfig(); + configStore = this.getConfigStore(); configName = TPSEngine.OP_ENROLL_PREFIX + "." + getSelectedTokenType() + ".temporaryToken.tokenType"; try { String tmpTokenType = configStore.getString(configName); setSelectedTokenType(tmpTokenType); } catch (EPropertyNotFound e) { - logMsg = " configuration " + configName + " not found: " + e.getMessage(); - logger.error(method + ":" + logMsg, e); + logMsg = " configuration " + configName + " not found"; + logger.debug(method + ":" + logMsg); throw new TPSException(method + ":" + logMsg, TPSStatus.STATUS_ERROR_MISCONFIGURATION); } catch (EBaseException e) { - logMsg = " configuration " + configName + " not found: " + e.getMessage(); - logger.error(method + ":" + logMsg, e); + logMsg = " configuration " + configName + " not found"; + logger.debug(method + ":" + logMsg); throw new TPSException(method + ":" + logMsg, TPSStatus.STATUS_ERROR_MISCONFIGURATION); } return processRecovery(lostToken, certsInfo, channel, aInfo); @@ -1259,7 +1301,7 @@ private TPSStatus generateCertsAfterRenewalRecoveryPolicy(EnrolledCertsInfo cert return processRecovery(lostToken, certsInfo, channel, aInfo); } else { logMsg = "No such lost reason: " + reasonStr + " for this cuid: " + aInfo.getCUIDhexStringPlain(); - logger.error(method + ":" + logMsg); + logger.debug(method + ":" + logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_NO_SUCH_LOST_REASON); } } @@ -1300,7 +1342,7 @@ private TPSStatus externalRegRecover( return status; } if (certsInfo == null) { - logger.warn(method + "method param certsInfo cannot be null"); + logger.debug(method + "method param certsInfo cannot be null"); return status; } logger.debug(method + "currentCertIndex = " + certsInfo.getCurrentCertIndex()); @@ -1314,6 +1356,8 @@ private TPSStatus externalRegRecover( session.getExternalRegAttrs().getCertsToRecoverCount()); ArrayList erCertsToRecover = session.getExternalRegAttrs().getCertsToRecover(); + //RedHat method name change + String aesKeyWrapAlg = establishSymKeyWrapAlgSSKeyGen(); for (ExternalRegCertToRecover erCert : erCertsToRecover) { BigInteger keyid = erCert.getKeyid(); BigInteger serial = erCert.getSerial(); @@ -1322,7 +1366,7 @@ private TPSStatus externalRegRecover( if (serial == null || caConn == null) { //bail out right away; we don't do half-baked recovery - logger.warn(method + "invalid exterenalReg cert"); + logger.debug(method + "invalid exterenalReg cert"); status = TPSStatus.STATUS_ERROR_RECOVERY_FAILED; return status; } @@ -1335,7 +1379,7 @@ private TPSStatus externalRegRecover( CARetrieveCertResponse certResp = caRH.retrieveCertificate(serial); if (certResp == null) { logMsg = "In recovery mode, CARetieveCertResponse object not found!"; - logger.warn(method + logMsg); + logger.debug(method + logMsg); return TPSStatus.STATUS_ERROR_RECOVERY_FAILED; } @@ -1352,7 +1396,7 @@ private TPSStatus externalRegRecover( // + cert_bytes_buf.toHexString()); } else { logMsg = "recovering cert b64 not found"; - logger.warn(method + logMsg); + logger.debug(method + logMsg); return TPSStatus.STATUS_ERROR_RECOVERY_FAILED; } @@ -1361,7 +1405,7 @@ private TPSStatus externalRegRecover( !allowRecoverInvalidCert()) { logMsg = "invalid cert not allowed on token per policy; serial=" + serial.toString() + "; cert status=" + recoveredCertStatus.toString(); - logger.warn(method + logMsg); + logger.debug(method + logMsg); return TPSStatus.STATUS_ERROR_RECOVERY_FAILED; } @@ -1371,7 +1415,7 @@ private TPSStatus externalRegRecover( String b64cert = null; if (getExternalRegRecoverByKeyID() == false) { b64cert = certResp.getCertB64(); - //logger.debug(method +": cert blob to recover key with: " + b64cert); + //logger.debug("TPSEnrollProcessor.processRecovery: cert blob to recover key with: " + b64cert); } /* @@ -1388,13 +1432,14 @@ private TPSStatus externalRegRecover( logMsg = " no keyid; retention; skip key recovery; continue"; logger.debug(method + logMsg); continue; - } - logMsg = " keyid in user record: " + keyid.toString(); - logger.debug(method + logMsg); - if ((getExternalRegRecoverByKeyID() == false) && - keyid.compareTo(BigInteger.valueOf(0)) != 0) { - logMsg = " Recovering by cert; keyid is irrelevant from user record"; + } else { + logMsg = " keyid in user record: " + keyid.toString(); logger.debug(method + logMsg); + if ((getExternalRegRecoverByKeyID() == false) && + keyid.compareTo(BigInteger.valueOf(0)) != 0) { + logMsg = " Recovering by cert; keyid is irrelevant from user record"; + logger.debug(method + logMsg); + } } // recover keys @@ -1405,20 +1450,21 @@ private TPSStatus externalRegRecover( if (channel.getDRMWrappedDesKey() == null) { logMsg = "channel.getDRMWrappedDesKey() null"; - logger.warn(method + logMsg); + logger.debug(method + logMsg); return TPSStatus.STATUS_ERROR_RECOVERY_FAILED; + } else { + logMsg = "channel.getDRMWrappedDesKey() not null"; + logger.debug(method + logMsg); } - logMsg = "channel.getDRMWrappedDesKey() not null"; - logger.debug(method + logMsg); - TPSBuffer drmDesKey = getDRMDesKeyByProtocol(channel); TPSBuffer drmAesKey = getDRMAesKeyByProtocol(channel); - keyResp = TPSEngine.getInstance().recoverKey(cuid, + + keyResp = engine.recoverKey(cuid, userid, - drmDesKey, drmAesKey, + drmDesKey,drmAesKey, getExternalRegRecoverByKeyID() ? null : b64cert, - kraConn, keyid); + kraConn, keyid,aesKeyWrapAlg); if (keyResp == null) { auditInfo = "recovering key not found"; @@ -1426,7 +1472,7 @@ private TPSStatus externalRegRecover( channel.getKeyInfoData().toHexStringPlain(), serial, caConn, kraConn, auditInfo); - logger.warn(method + auditInfo); + logger.debug(method + auditInfo); return TPSStatus.STATUS_ERROR_RECOVERY_FAILED; } auditRecovery(userid, appletInfo, "success", @@ -1439,6 +1485,8 @@ private TPSStatus externalRegRecover( cEnrollInfo.setTokenToBeRecovered(tokenRecord); cEnrollInfo.setRecoveredCertData(certResp); cEnrollInfo.setRecoveredKeyData(keyResp); + cEnrollInfo.setAesKeyWrapAlg(aesKeyWrapAlg); + preRecoveredCerts.add(cEnrollInfo); } @@ -1503,6 +1551,7 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan String logMsg; logger.debug(method + ": begins"); + TPSEngine engine = TPSEngine.getInstance(); boolean noFailedCerts = true; if (certsInfo == null || aInfo == null || channel == null) { @@ -1510,8 +1559,8 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + int keyTypeNum = getNumberCertsToRenew(); /* * Get certs from the tokendb for this token to find out about @@ -1519,7 +1568,7 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan */ Collection allCerts = tps.tdb.tdbGetCertRecordsByCUID(tokenRecord.getId()); - Collection oldEncCertsToRecover = new ArrayList<>(); + Collection oldEncCertsToRecover = new ArrayList(); certsInfo.setNumCertsToEnroll(keyTypeNum); @@ -1545,7 +1594,7 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan certsInfo.setCurrentCertIndex(i); CertEnrollInfo cEnrollInfo = new CertEnrollInfo(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); // find all config String configName = null; @@ -1613,13 +1662,13 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan continue; } catch (TPSException ge) { // error in this will just log and keep going - logger.warn(method + ":" + ge.getMessage() + "; continue to try renewal", ge); + logger.debug(method + ":" + ge + "; continue to try renewal"); } } //Renew and fetch the renewed cert blob. - CARenewCertResponse certResponse = TPSEngine.getInstance().renewCertificate(cert, + CARenewCertResponse certResponse = engine.renewCertificate(cert, cert.getSerialNumber(), selectedTokenType, keyType, getCAConnectorID("renewal", keyType)); cEnrollInfo.setRenewedCertData(certResponse); @@ -1647,7 +1696,7 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan //renewCertificate(cert, certsInfo, channel, aInfo, keyType); status = TPSStatus.STATUS_RENEWAL_IS_PROCESSED; } catch (TPSException e) { - logger.warn(method + "renewCertificate: exception:" + e.getMessage(), e); + logger.debug(method + "renewCertificate: exception:" + e); noFailedCerts = false; break; //need to clean up half-done token later } @@ -1658,18 +1707,21 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan if (!noFailedCerts) { // TODO: handle cleanup logMsg = "There has been failed cert renewal"; - logger.error(method + ":" + logMsg); - throw new TPSException(logMsg + TPSStatus.STATUS_ERROR_RENEWAL_FAILED); + logger.debug(method + ":" + logMsg); + throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_RENEWAL_FAILED); } //Handle recovery of old encryption certs //See if policy calls for this feature - TPSTokenPolicy tokenPolicy = new TPSTokenPolicy(tps, tokenRecord.getId()); + TPSTokenPolicy tokenPolicy = new TPSTokenPolicy(tps,tokenRecord.getId()); boolean recoverOldEncCerts = tokenPolicy.isAllowdRenewSaveOldEncCerts(); logger.debug(method + " Recover Old Encryption Certs for Renewed Certs: " + recoverOldEncCerts); + + //RedHat method name change + String aesKeyWrapAlg = establishSymKeyWrapAlgSSKeyGen(); if (oldEncCertsToRecover.size() > 0 && recoverOldEncCerts == true) { logger.debug("About to attempt to recover old encryption certs just renewed."); @@ -1682,19 +1734,20 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan try { - CARetrieveCertResponse certResponse = TPSEngine.getInstance().recoverCertificate(toBeRecovered, + CARetrieveCertResponse certResponse = engine.recoverCertificate(toBeRecovered, serialToRecover, TPSEngine.CFG_ENCRYPTION, getCAConnectorID()); String b64cert = certResponse.getCertB64(); - logger.debug(method +": cert blob recovered"); + logger.debug("TPSEnrollProcessor.processRecovery: cert blob recovered"); TPSBuffer drmDesKey = getDRMDesKeyByProtocol(channel); TPSBuffer drmAesKey = getDRMAesKeyByProtocol(channel); - KRARecoverKeyResponse keyResponse = TPSEngine.getInstance().recoverKey(toBeRecovered.getId(), + KRARecoverKeyResponse keyResponse = engine.recoverKey(toBeRecovered.getId(), toBeRecovered.getUserID(), - drmDesKey, drmAesKey, - b64cert, getDRMConnectorID(toBeRecovered.getKeyType())); + drmDesKey, + drmAesKey, + b64cert, getDRMConnectorID(toBeRecovered.getKeyType()),aesKeyWrapAlg); //Try to write recovered cert to token @@ -1703,6 +1756,7 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan cEnrollInfo.setTokenToBeRecovered(tokenRecord); cEnrollInfo.setRecoveredCertData(certResponse); cEnrollInfo.setRecoveredKeyData(keyResponse); + cEnrollInfo.setAesKeyWrapAlg(aesKeyWrapAlg); PKCS11Obj pkcs11obj = certsInfo.getPKCS11Obj(); int newCertId = pkcs11obj.getNextFreeCertIdNumber(); @@ -1724,7 +1778,8 @@ private TPSStatus processRenewal(EnrolledCertsInfo certsInfo, SecureChannel chan certsInfo.removeCertificate(certResponse.getCert()); } catch (TPSException e) { - logger.warn(method + "Failure to recoverd old encryption certs during renewal operation: " + e.getMessage(), e); + logger.debug(method + "Failure to recoverd old encryption certs during renewal operation."); + } } } @@ -1746,7 +1801,7 @@ private boolean isCertWithinRenewalGracePeriod(TPSCertRecord cert, String renewG int renewGraceAfter = 0; if (cert == null || renewGraceBeforeS == null || renewGraceAfterS == null) { - logger.error(method + ": missing some input"); + logger.debug(method + ": missing some input"); throw new TPSException(method + ": Bad Input data!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -1784,14 +1839,14 @@ private boolean isCertWithinRenewalGracePeriod(TPSCertRecord cert, String renewG */ if (millisDiff >= 0) { if ((renewGraceBefore > 0) && (millisDiff > renewGraceBeforeBI.longValue())) { - logger.warn(method + ": renewal attempted outside of grace period;" + + logger.debug(method + ": renewal attempted outside of grace period;" + renewGraceBefore + " days before and " + renewGraceAfter + " days after original cert expiration date"); return false; } } else { if ((renewGraceAfter > 0) && ((0 - millisDiff) > renewGraceAfterBI.longValue())) { - logger.warn(method + ": renewal attempted outside of grace period;" + + logger.debug(method + ": renewal attempted outside of grace period;" + renewGraceBefore + " days before and " + renewGraceAfter + " days after original cert expiration date"); return false; @@ -1802,8 +1857,7 @@ private boolean isCertWithinRenewalGracePeriod(TPSCertRecord cert, String renewG private boolean getRenewEnabled(String keyType) { String method = "TPSEnrollProcessor.getRenewEnabled"; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); boolean enabled = false; try { @@ -1826,8 +1880,7 @@ private boolean getRenewEnabled(String keyType) { */ private boolean getExternalRegRecoverByKeyID() { String method = "TPSEnrollProcessor.getExternalRegRecoverByKeyID"; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); boolean recoverByKeyID = false; try { @@ -1836,7 +1889,7 @@ private boolean getExternalRegRecoverByKeyID() { } catch (EBaseException e) { // should never get here anyway // but if it does, just take the default "false" - logger.warn(method + " exception, take default: " + e.getMessage(), e); + logger.debug(method + " exception, take default: " + e); } logger.debug(method + ": returning " + recoverByKeyID); return recoverByKeyID; @@ -1844,8 +1897,7 @@ private boolean getExternalRegRecoverByKeyID() { private String getRenewConfigKeyType(int keyTypeIndex) throws TPSException { String method = "TPSEnrollProcessor.getRenewConfigKeyType"; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String keyType = null; try { @@ -1876,8 +1928,7 @@ private String getRenewConfigKeyType(int keyTypeIndex) throws TPSException { private int getNumberCertsToRenew() throws TPSException { String method = "TPSEnrollProcessor.getNumberCertsToRenew"; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int keyTypeNum = 0; try { String configValue = TPSEngine.OP_ENROLL_PREFIX + "." + selectedTokenType + "." @@ -1909,12 +1960,13 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); - TPSEngineConfig configStore = engine.getConfig(); - logger.debug(method + ": entering:"); + TPSEngineConfig configStore = this.getConfigStore(); + + logger.debug("TPSEnrollProcessor.processRecovery: entering:"); if (toBeRecovered == null || certsInfo == null || channel == null || aInfo == null) { - throw new TPSException(method + ": Invalid reason!", + throw new TPSException("TPSEnrollProcessor.processRecovery: Invalid reason!", TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } @@ -1931,7 +1983,8 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c String keyTypeValue = null; String scheme = null; - logger.debug(method + ": About to find if we have any GenerateNewAndRecoverLast schemes."); + logger.debug( + "TPSEnrollProcessor.processRecovery: About to find if we have any GenerateNewAndRecoverLast schemes."); for (int i = 0; i < num; i++) { keyTypeValue = getRecoveryKeyTypeValue(reason, i); scheme = getRecoveryScheme(reason, keyTypeValue); @@ -1941,7 +1994,7 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c //Make sure we are not signing: if (keyTypeValue.equals(TPSEngine.CFG_SIGNING)) { throw new TPSException( - method + ": Can't have GenerateNewAndRecoverLast scheme with a signing key!", + "TPSEnrollProcessor.processRecovery: Can't have GenerateNewAndRecoverLast scheme with a signing key!", TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } totalNumCerts++; @@ -1949,7 +2002,7 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c totalNumCerts++; } - logger.debug(method + ": About to perform actual recoveries: totalNumCerts: " + logger.debug("TPSEnrollProcessor.processRecovery: About to perform actual recoveries: totalNumCerts: " + totalNumCerts); if (!(totalNumCerts > num)) { @@ -1960,6 +2013,8 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c int actualCertIndex = 0; boolean legalScheme = false; + //RedHat method name change. + String aesKeyWrapAlg = establishSymKeyWrapAlgSSKeyGen(); //Go through again and do the recoveries/enrollments certsInfo.setNumCertsToEnroll(totalNumCerts); @@ -1969,7 +2024,7 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c scheme = getRecoveryScheme(reason, keyTypeValue); if (scheme.equals(TPSEngine.RECOVERY_SCHEME_GENERATE_NEW_KEY_AND_RECOVER_LAST)) { - logger.debug(method + ": scheme GenerateNewKeyAndRecoverLast found."); + logger.debug("TPSEnrollProcessor.processRecovery: scheme GenerateNewKeyAndRecoverLast found."); isGenerateAndRecover = true; } else { @@ -1979,20 +2034,23 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c if (scheme.equals(TPSEngine.RECOVERY_GENERATE_NEW_KEY) || isGenerateAndRecover) { legalScheme = true; CertEnrollInfo cEnrollInfo = new CertEnrollInfo(); + cEnrollInfo.setAesKeyWrapAlg(aesKeyWrapAlg); generateCertificate(certsInfo, channel, aInfo, keyTypeValue, TPSEngine.ENROLL_MODES.MODE_ENROLL, actualCertIndex, cEnrollInfo); actualCertIndex = cEnrollInfo.getCertIdIndex(); - logger.debug(method + ": scheme GenerateNewKey found, or isGenerateAndRecove is true: actualCertIndex, after enrollment: " + logger.debug( + "TPSEnrollProcessor.processRecovery: scheme GenerateNewKey found, or isGenerateAndRecove is true: actualCertIndex, after enrollment: " + actualCertIndex); } if (scheme.equals(TPSEngine.RECOVERY_RECOVER_LAST) || isGenerateAndRecover) { legalScheme = true; - logger.debug(method + ": scheme RecoverLast found, or isGenerateAndRecove is true"); + logger.debug( + "TPSEnrollProcessor.processRecovery: scheme RecoverLast found, or isGenerateAndRecove is true"); if (isGenerateAndRecover) { - logger.debug(method + ": isGenerateAndRecover is true."); + logger.debug("TPSEnrollProcessor.processRecovery: isGenerateAndRecover is true."); actualCertIndex++; } @@ -2003,7 +2061,7 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c for (TPSCertRecord rec : certs) { //Just take the end of the list most recent cert of given type. - logger.debug(method +": Looking for keyType record: " + keyTypeValue + logger.debug("TPSEnrollProcessor.processRecovery: Looking for keyType record: " + keyTypeValue + " curSererial: " + rec.getSerialNumber()); if (rec.getKeyType().equals(keyTypeValue)) { @@ -2022,33 +2080,35 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c try { caConnId = configStore.getString(config); } catch (Exception e) { - logMsg = "cannot find config:" + config + ": " + e.getMessage(); - logger.error(method + ":" + logMsg, e); + logMsg = "cannot find config:" + config; + logger.debug(method + ":" + logMsg); throw new TPSException( method + ":" + logMsg, TPSStatus.STATUS_ERROR_MISCONFIGURATION); } - logger.debug(method +": Selecting cert to recover: " + serialToRecover); + logger.debug("TPSEnrollProcessor.processRecovery: Selecting cert to recover: " + serialToRecover); - CARetrieveCertResponse certResponse = TPSEngine.getInstance().recoverCertificate(certToRecover, + CARetrieveCertResponse certResponse = engine.recoverCertificate(certToRecover, serialToRecover, keyTypeValue, caConnId); b64cert = certResponse.getCertB64(); - //logger.debug(method +": recoverd cert blob: " + b64cert); - logger.debug(method +": cert blob recovered"); + //logger.debug("TPSEnrollProcessor.processRecovery: recoverd cert blob: " + b64cert); + logger.debug("TPSEnrollProcessor.processRecovery: cert blob recovered"); - TPSBuffer drmDesKey = getDRMDesKeyByProtocol(channel); - TPSBuffer drmAesKey = getDRMAesKeyByProtocol(channel); - KRARecoverKeyResponse keyResponse = TPSEngine.getInstance().recoverKey(toBeRecovered.getId(), + TPSBuffer drmDesKey = getDRMDesKeyByProtocol(channel); + TPSBuffer drmAesKey = getDRMAesKeyByProtocol(channel); + + KRARecoverKeyResponse keyResponse = engine.recoverKey(toBeRecovered.getId(), toBeRecovered.getUserID(), drmDesKey,drmAesKey, - b64cert, getDRMConnectorID(certToRecover.getKeyType())); + b64cert, getDRMConnectorID(certToRecover.getKeyType()),aesKeyWrapAlg); CertEnrollInfo cEnrollInfo = new CertEnrollInfo(); cEnrollInfo.setTokenToBeRecovered(toBeRecovered); cEnrollInfo.setRecoveredCertData(certResponse); cEnrollInfo.setRecoveredKeyData(keyResponse); + cEnrollInfo.setAesKeyWrapAlg(aesKeyWrapAlg); generateCertificate(certsInfo, channel, aInfo, keyTypeValue, TPSEngine.ENROLL_MODES.MODE_RECOVERY, actualCertIndex, cEnrollInfo); @@ -2070,12 +2130,13 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c auditRevoke(certToRecover.getTokenID(), false /*off-hold*/, -1 /*na*/, String.valueOf(response.getStatus()), serialToRecover, caConnId, null); // successful unrevoke should mark the cert "active" - logger.debug(method + ": unrevoke successful. Setting cert status to active for actualCertIndex:" + logger.debug( + method + ": unrevoke successful. Setting cert status to active for actualCertIndex:" + actualCertIndex); certsInfo.setCertStatus(actualCertIndex, TokenCertStatus.ACTIVE); } catch (EBaseException e) { - logMsg = "failed getting CARemoteRequestHandler: " + e.getMessage(); - logger.error(method + ":" + logMsg, e); + logMsg = "failed getting CARemoteRequestHandler"; + logger.debug(method + ":" + logMsg); auditRevoke(certToRecover.getTokenID(), false/*off-hold*/, -1 /*na*/, "failure", serialToRecover, caConnId, logMsg); throw new TPSException(method + ":" + logMsg, TPSStatus.STATUS_ERROR_RECOVERY_FAILED); @@ -2088,7 +2149,7 @@ private TPSStatus processRecovery(TokenRecord toBeRecovered, EnrolledCertsInfo c } if (!legalScheme) { - throw new TPSException(method +": Invalid recovery configuration!", + throw new TPSException("TPSEnrollProcessor.processRecovery: Invalid recovery configuration!", TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } actualCertIndex++; @@ -2106,21 +2167,21 @@ private boolean generateCertificates(EnrolledCertsInfo certsInfo, SecureChannel boolean noFailedCerts = true; if (certsInfo == null || aInfo == null || channel == null) { - throw new TPSException("TPSEnrollProcess.generateCertificates: Bad Input data!", + throw new TPSException("TPSEnrollProcessor.generateCertificates: Bad Input data!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } int keyTypeNum = getNumberCertsToEnroll(); if (isExternalReg && keyTypeNum == 0) { - logger.warn("TPSEnrollProcess.generateCertificates: isExternalReg with tokenType:" + selectedTokenType + logger.debug("TPSEnrollProcess.generateCertificates: isExternalReg with tokenType:" + selectedTokenType + "; no certs to enroll per configuration"); return noFailedCerts; } certsInfo.setNumCertsToEnroll(keyTypeNum); - logger.debug("TPSEnrollProcess.generateCertificates: Number of certs to enroll: " + keyTypeNum); + logger.debug("TPSEnrollProcessor.generateCertificates: Number of certs to enroll: " + keyTypeNum); for (int i = 0; i < keyTypeNum; i++) { String keyType = getConfiguredKeyType(i); @@ -2128,7 +2189,7 @@ private boolean generateCertificates(EnrolledCertsInfo certsInfo, SecureChannel try { generateCertificate(certsInfo, channel, aInfo, keyType, TPSEngine.ENROLL_MODES.MODE_ENROLL, -1, null); } catch (TPSException e) { - logger.warn("TPSEnrollProcess.generateCertificates: exception:" + e.getMessage(), e); + logger.debug("TPSEnrollProcessor.generateCertificate: exception:" + e); noFailedCerts = false; break; //need to clean up half-done token later } @@ -2144,7 +2205,7 @@ private boolean generateCertificates(EnrolledCertsInfo certsInfo, SecureChannel } */ - logger.debug("TPSEnrollProcess.generateCertificates: ends "); + logger.debug("TPSEnrollProcessor.generateCertificates: ends "); return noFailedCerts; } @@ -2158,8 +2219,7 @@ private String buildTokenLabel(EnrolledCertsInfo certsInfo, AppletInfo ainfo) th logger.debug("TPSEnrollProcessor.buildTokenLabel: entering..."); - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String configName = TPSEngine.OP_ENROLL_PREFIX + "." + getSelectedTokenType() + ".keyGen.tokenName"; String pattern = null; @@ -2175,7 +2235,7 @@ private String buildTokenLabel(EnrolledCertsInfo certsInfo, AppletInfo ainfo) th logger.debug("TPSEnrollProcessor.buildTokenLabel: pattern: " + pattern); - Map nv = new LinkedHashMap<>(); + Map nv = new LinkedHashMap(); nv.put("cuid", ainfo.getCUIDhexString()); nv.put("msn", ainfo.getMSNString()); @@ -2200,19 +2260,17 @@ private void generateCertificate(EnrolledCertsInfo certsInfo, SecureChannel chan String keyType, TPSEngine.ENROLL_MODES mode, int certIdNumOverride, CertEnrollInfo cEnrollInfo) throws TPSException, IOException { - final String method = "TPSEnrollProcessor.generateCertificate"; - logger.debug(method + ": entering ... certIdNumOverride: " + certIdNumOverride + logger.debug("TPSEnrollProcessor.generateCertificate: entering ... certIdNumOverride: " + certIdNumOverride + " mode: " + mode); if (certsInfo == null || aInfo == null || channel == null) { - throw new TPSException(method + ": Bad Input data!", + throw new TPSException("TPSEnrollProcessor.generateCertificate: Bad Input data!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } //get the params needed all at once - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); boolean isRenewal = false; @@ -2231,7 +2289,7 @@ private void generateCertificate(EnrolledCertsInfo certsInfo, SecureChannel chan String keyTypePrefix = TPSEngine.OP_ENROLL_PREFIX + "." + getSelectedTokenType() + "." + operationModifier + "." + keyType; - logger.debug(method + ": keyTypePrefix: " + keyTypePrefix); + logger.debug("TPSEnrollProcessor.generateCertificate: keyTypePrefix: " + keyTypePrefix); String configName = keyTypePrefix + ".ca.profileId"; String profileId = null; @@ -2239,65 +2297,65 @@ private void generateCertificate(EnrolledCertsInfo certsInfo, SecureChannel chan profileId = configStore.getString(configName, "NA"); // if not supplied then does not apply due to recovery } else { profileId = configStore.getString(configName); - logger.debug(method + ": profileId: " + profileId); + logger.debug("TPSEnrollProcessor.generateCertificate: profileId: " + profileId); } configName = keyTypePrefix + ".certId"; String certId = configStore.getString(configName, "C0"); - logger.debug(method + ": certId: " + certId); + logger.debug("TPSEnrollProcessor.generateCertificate: certId: " + certId); configName = keyTypePrefix + ".certAttrId"; String certAttrId = configStore.getString(configName, "c0"); - logger.debug(method + ": certAttrId: " + certAttrId); + logger.debug("TPSEnrollProcessor.generateCertificate: certAttrId: " + certAttrId); configName = keyTypePrefix + ".privateKeyAttrId"; String priKeyAttrId = configStore.getString(configName, "k0"); - logger.debug(method + ": priKeyAttrId: " + priKeyAttrId); + logger.debug("TPSEnrollProcessor.generateCertificate: priKeyAttrId: " + priKeyAttrId); configName = keyTypePrefix + ".publicKeyAttrId"; String publicKeyAttrId = configStore.getString(configName, "k1"); - logger.debug(method + ": publicKeyAttrId: " + publicKeyAttrId); + logger.debug("TPSEnrollProcessor.generateCertificate: publicKeyAttrId: " + publicKeyAttrId); configName = keyTypePrefix + ".keySize"; int keySize = configStore.getInteger(configName, 1024); - logger.debug(method + ": keySize: " + keySize); + logger.debug("TPSEnrollProcessor.generateCertificate: keySize: " + keySize); //Default RSA_CRT=2 configName = keyTypePrefix + ".alg"; int algorithm = configStore.getInteger(configName, 2); - logger.debug(method + ": algorithm: " + algorithm); + logger.debug("TPSEnrollProcessor.generateCertificate: algorithm: " + algorithm); configName = keyTypePrefix + ".publisherId"; String publisherId = configStore.getString(configName, ""); - logger.debug(method + ": publisherId: " + publisherId); + logger.debug("TPSEnrollProcessor.generateCertificate: publisherId: " + publisherId); configName = keyTypePrefix + ".keyUsage"; int keyUsage = configStore.getInteger(configName, 0); - logger.debug(method + ": keyUsage: " + keyUsage); + logger.debug("TPSEnrollProcessor.generateCertificate: keyUsage: " + keyUsage); configName = keyTypePrefix + ".keyUser"; int keyUser = configStore.getInteger(configName, 0); - logger.debug(method + ": keyUser: " + keyUser); + logger.debug("TPSEnrollProcessor.generateCertificate: keyUser: " + keyUser); configName = keyTypePrefix + ".privateKeyNumber"; int priKeyNumber = configStore.getInteger(configName, 0); - logger.debug(method + ": privateKeyNumber: " + priKeyNumber); + logger.debug("TPSEnrollProcessor.generateCertificate: privateKeyNumber: " + priKeyNumber); configName = keyTypePrefix + ".publicKeyNumber"; int pubKeyNumber = configStore.getInteger(configName, 0); - logger.debug(method + ": pubKeyNumber: " + pubKeyNumber); + logger.debug("TPSEnrollProcessor.generateCertificate: pubKeyNumber: " + pubKeyNumber); // get key capabilites to determine if the key type is SIGNING, // ENCRYPTION, or SIGNING_AND_ENCRYPTION configName = keyTypePrefix + ".private.keyCapabilities.sign"; boolean isSigning = configStore.getBoolean(configName, false); - logger.debug(method + ": isSigning: " + isSigning); + logger.debug("TPSEnrollProcessor.generateCertificate: isSigning: " + isSigning); configName = keyTypePrefix + ".public.keyCapabilities.encrypt"; - logger.debug(method + ": encrypt config name: " + configName); + logger.debug("TPSEnrollProcessor.generateCertificate: encrypt config name: " + configName); boolean isEncrypt = configStore.getBoolean(configName, true); - logger.debug(method + ": isEncrypt: " + isEncrypt); + logger.debug("TPSEnrollProcessor.generateCertificate: isEncrypt: " + isEncrypt); TokenKeyType keyTypeEnum; @@ -2308,19 +2366,19 @@ private void generateCertificate(EnrolledCertsInfo certsInfo, SecureChannel chan } else if (isEncrypt) { keyTypeEnum = TokenKeyType.KEY_TYPE_ENCRYPTION; } else { - logger.error(method + ": Illegal toke key type!"); - throw new TPSException(method + ": Illegal toke key type!", + logger.debug("TPSEnrollProcessor.generateCertificate: Illegal toke key type!"); + throw new TPSException("TPSEnrollProcessor.generateCertificate: Illegal toke key type!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - logger.debug(method + ": keyTypeEnum value: " + keyTypeEnum); + logger.debug("TPSEnrollProcessor.generateCertificate: keyTypeEnum value: " + keyTypeEnum); // The certIdNumOverride allows us to place the certs and keys into a different slot. // Thus overriding what is found in the config. // Used in recovery mostly up to this point. if (certIdNumOverride >= 0) { - logger.debug(method + ": called with overridden cert id number: " + logger.debug("TPSEnrollProcessor.generateCertificate: called with overridden cert id number: " + certIdNumOverride); pubKeyNumber = 2 * certIdNumOverride + 1; @@ -2331,7 +2389,7 @@ private void generateCertificate(EnrolledCertsInfo certsInfo, SecureChannel chan priKeyAttrId = "k" + priKeyNumber; publicKeyAttrId = "k" + pubKeyNumber; - logger.debug(method + ": called with overridden cert no: certId: " + certId + logger.debug("TPSEnrollProcessor.generateCertificate: called with overridden cert no: certId: " + certId + " certAttrId: " + certAttrId + " priKeyAttrId: " + priKeyAttrId + " publicKeyAttrId: " + publicKeyAttrId); @@ -2362,7 +2420,7 @@ private void generateCertificate(EnrolledCertsInfo certsInfo, SecureChannel chan int currentCertIndex = certsInfo.getCurrentCertIndex(); int totalNumCerts = certsInfo.getNumCertsToEnroll(); - logger.debug(method + ": Progress values: certsStartProgress: " + logger.debug("TPSEnrollProcessor.generateCertificate: Progress values: certsStartProgress: " + certsStartProgress + " certsEndProgress: " + certsEndProgress + " currentCertIndex: " + currentCertIndex + " totalNumCerts: " + totalNumCerts); @@ -2370,16 +2428,16 @@ private void generateCertificate(EnrolledCertsInfo certsInfo, SecureChannel chan if (totalNumCerts != 0) { progressBlock = (certsEndProgress - certsStartProgress) / totalNumCerts; - logger.debug(method + ": progressBlock: " + progressBlock); + logger.debug("TPSEnrollProcessor.generateCertificate: progressBlock: " + progressBlock); } else {//TODO need to make this more accurate - logger.debug(method + ": totalNumCerts =0, progressBlock left at 0"); + logger.debug("TPSEnrollProcessor.generateCertificate: totalNumCerts =0, progressBlock left at 0"); } int startCertProgValue = certsStartProgress + currentCertIndex * progressBlock; int endCertProgValue = startCertProgValue + progressBlock; - logger.debug(method + ": startCertProgValue: " + startCertProgValue + logger.debug("TPSEnrollProcessor.generateCertificate: startCertProgValue: " + startCertProgValue + " endCertProgValue: " + endCertProgValue); cEnrollInfo.setStartProgressValue(startCertProgValue); @@ -2388,7 +2446,7 @@ private void generateCertificate(EnrolledCertsInfo certsInfo, SecureChannel chan } catch (EBaseException e) { throw new TPSException( - method + ": Internal error finding config value: " + e, + "TPSEnrollProcessor.generateCertificate: Internal error finding config value: " + e, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -2405,18 +2463,17 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE SecureChannel channel, TPSEngine.ENROLL_MODES mode) throws TPSException, IOException { - String method = "TPSEnrollProcessor.enrollOneCertificate"; + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); String auditInfo = null; - logger.debug(method + ": entering ... mode: " + mode); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: entering ... mode: " + mode); if (certsInfo == null || aInfo == null || cEnrollInfo == null || channel == null) { - throw new TPSException(method + ": Bad Input data!", + throw new TPSException("TPSEnrollProcessor.enrollOneCertificate: Bad Input data!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - logger.debug(method + ": currentCertIndex = " + certsInfo.getCurrentCertIndex()); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: currentCertIndex = " + certsInfo.getCurrentCertIndex()); - TPSEngine engine = TPSEngine.getInstance(); - TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); statusUpdate(cEnrollInfo.getStartProgressValue(), "PROGRESS_KEY_GENERATION"); boolean serverSideKeyGen = checkForServerSideKeyGen(cEnrollInfo); boolean objectOverwrite = checkForObjectOverwrite(cEnrollInfo); @@ -2425,10 +2482,10 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE int keyAlg = cEnrollInfo.getAlgorithm(); - boolean isECC = TPSEngine.getInstance().isAlgorithmECC(keyAlg); + boolean isECC = engine.isAlgorithmECC(keyAlg); if (objectOverwrite) { - logger.debug(method +": We are configured to overwrite existing cert objects."); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: We are configured to overwrite existing cert objects."); } else { @@ -2441,7 +2498,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE auditEnrollment(userid, "enrollment", aInfo, "failure", channel.getKeyInfoData().toHexStringPlain(), null, null /*caConnID*/, auditInfo); throw new TPSException( - method +": " + auditInfo, + "TPSEnrollProcessor.enrollOneCertificate: " + auditInfo, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -2457,10 +2514,14 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE boolean isRecovery = false; boolean isRenewal = false; + //Method name change + String aesKeyWrapAlg = establishSymKeyWrapAlgSSKeyGen(); + cEnrollInfo.setAesKeyWrapAlg(aesKeyWrapAlg); + if (mode == ENROLL_MODES.MODE_RECOVERY) { isRecovery = true; - logger.debug(method +": detecting recovery mode!"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: detecting recovery mode!"); if (isRecovery && !serverSideKeyGen) { auditInfo = "Attempting illegal recovery when archival is not enabled"; auditRecovery(userid, aInfo, "failure", @@ -2468,14 +2529,14 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE null, null, null, auditInfo); throw new TPSException( - method +": " + auditInfo, + "TPSEnrollProcessor.enrollOneCertificate: " + auditInfo, TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } } if (mode == ENROLL_MODES.MODE_RENEWAL) { isRenewal = true; - logger.debug(method +": detecting renewal mode!"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: detecting renewal mode!"); } if (serverSideKeyGen || isRecovery) { @@ -2484,7 +2545,8 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE // In recovery the cert and key are recovered. // In server side key gen, cert is enrolled and key is generated and recovered. - logger.debug(method +": either generate private key on the server, or preform recovery or perform renewal."); + logger.debug( + "TPSEnrollProcessor.enrollOneCertificate: either generate private key on the server, or preform recovery or perform renewal."); boolean archive = checkForServerKeyArchival(cEnrollInfo); String kraConnId = getDRMConnectorID(cEnrollInfo.getKeyType()); @@ -2494,20 +2556,20 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE TPSBuffer drmDesKey = getDRMDesKeyByProtocol(channel); TPSBuffer drmAesKey = getDRMAesKeyByProtocol(channel); - ssKeyGenResponse = TPSEngine.getInstance() + ssKeyGenResponse = engine .serverSideKeyGen(cEnrollInfo.getKeySize(), - aInfo.getCUIDhexStringPlain(), userid, kraConnId, drmDesKey, drmAesKey, - archive, isECC); + aInfo.getCUIDhexStringPlain(), userid, kraConnId, drmDesKey,drmAesKey, + archive, isECC, aesKeyWrapAlg); publicKeyStr = ssKeyGenResponse.getPublicKey(); - //logger.debug(method +": public key string from server: " + publicKeyStr); - logger.debug(method +": got public key string from server "); + //logger.debug("TPSEnrollProcessor.enrollOneCertificate: public key string from server: " + publicKeyStr); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: got public key string from server "); public_key_blob = new TPSBuffer(Utils.base64decode(publicKeyStr)); } else { //Here we have a recovery, get the key data from the CertInfo object - logger.debug(method +": Attempt to get key data in recovery mode!"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: Attempt to get key data in recovery mode!"); keyResp = cEnrollInfo.getRecoveredKeyData(); publicKeyStr = keyResp.getPublicKey(); @@ -2522,12 +2584,12 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE // reset to accurate keysize RSAPublicKey rsaKey = new RSAPublicKey(parsedPubKey_ba); cEnrollInfo.setKeySize(rsaKey.getKeySize()); - logger.debug(method +": recovery reset keysize to:" + logger.debug("TPSEnrollProcessor.enrollOneCertificate: recovery reset keysize to:" + rsaKey.getKeySize()); } } catch (InvalidKeyFormatException e) { - auditInfo = method +", can't create public key object from server side key generated public key blob! " - + e.getMessage(); + auditInfo = "TPSEnrollProcessor.enrollOneCertificate, can't create public key object from server side key generated public key blob! " + + e.toString(); if (!isRecovery) { //servrSideKeygen auditEnrollment(userid, "enrollment", aInfo, "failure", channel.getKeyInfoData().toHexStringPlain(), @@ -2538,24 +2600,25 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE null /*serial*/, null /*caConn*/, kraConnId, auditInfo); } - logger.error(auditInfo, e); + logger.debug(auditInfo); throw new TPSException(auditInfo, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } catch (InvalidKeyException e) { - String msg = method +", can't create public key object from server side key generated public key blob! " - + e.getMessage(); - logger.error(msg, e); + String msg = "TPSEnrollProcessor.enrollOneCertificate, can't create public key object from server side key generated public key blob! " + + e.toString(); + logger.debug(msg); throw new TPSException(msg, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } } else if (isRenewal) { - logger.debug(method + ": We are in renewal mode, no work to do with the keys, in renewal the keys remain on the token."); + logger.debug( + "TPSEnrollProcessor: We are in renewal mode, no work to do with the keys, in renewal the keys remain on the token."); } else { //Handle token side keyGen - logger.debug(method +": about to generate the private key on the token."); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: about to generate the private key on the token."); int algorithm = 0x80; @@ -2584,7 +2647,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE } // enrollment/recovery begins - logger.debug(method +": enrollment begins"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: enrollment begins"); X509CertImpl x509Cert = null; TokenCertStatus certStatus = TokenCertStatus.ACTIVE; // track cert status byte[] cert_bytes = null; @@ -2595,7 +2658,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE CARemoteRequestHandler caRH = new CARemoteRequestHandler(caConnID); TPSBuffer encodedParsedPubKey = new TPSBuffer(parsedPubKey_ba); - logger.debug(method +": userid =" + userid + ", cuid=" + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: userid =" + userid + ", cuid=" + aInfo.getCUIDhexString()); CAEnrollCertResponse caEnrollResp; @@ -2603,11 +2666,11 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE session.getExternalRegAttrs().getIsDelegation()) { int sanNum = 0; String urlSanExt = null; - logger.debug(method +": isDelegation true"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: isDelegation true"); /* * build up name/value pairs for pattern mapping */ - LinkedHashMap nv = new LinkedHashMap<>(); + LinkedHashMap nv = new LinkedHashMap(); nv.put("cuid", aInfo.getCUIDhexStringPlain()); nv.put("msn", aInfo.getMSNString()); @@ -2615,18 +2678,18 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE nv.put("auth.cn", userid); nv.put("profileId", getSelectedTokenType()); - logger.debug(method +": fill in nv with authToken name/value pairs"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: fill in nv with authToken name/value pairs"); Enumeration n = authToken.getElements(); while (n.hasMoreElements()) { String name = n.nextElement(); - logger.debug(method +":name =" + name); + logger.debug("TPSEnrollProcessor.enrollOneCertificate::name =" + name); if (ldapStringAttrs != null && ldapStringAttrs.contains(name)) { String[] vals = authToken.getInStringArray(name); if (vals != null) { - logger.debug(method +":val =" + vals[0]); + logger.debug("TPSEnrollProcessor.enrollOneCertificate::val =" + vals[0]); nv.put("auth." + name, vals[0]); } else { - logger.debug(method +":name not found in authToken:" + logger.debug("TPSEnrollProcessor.enrollOneCertificate::name not found in authToken:" + name); } } @@ -2641,7 +2704,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE * becomes: * CN=Jane.Doe.0123456789,E=jdoe@redhat.com,O=TMS Org */ - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String configName; configName = TPSEngine.OP_ENROLL_PREFIX + "." + getSelectedTokenType() + ".keyGen." + @@ -2650,7 +2713,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE String dnpattern = configStore.getString(configName); subjectdn = mapPattern(nv, dnpattern); } catch (EBaseException e) { - logger.warn(method +": isDelegation dnpattern not set: " + e.getMessage(), e); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: isDelegation dnpattern not set"); } /* @@ -2675,7 +2738,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE * 3. append * url_san_ext will look like san1&san2&san3...& */ - logger.debug(method +": isDelegation: sanToken:" + sanToken); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: isDelegation: sanToken:" + sanToken); String sanExt = mapPattern(nv, sanToken); String urlSanExt1 = Util.uriEncode(sanExt); if (urlSanExt == null) { // first one @@ -2686,21 +2749,23 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE "&req_san_pattern_" + sanNum + "=" + urlSanExt1; } - logger.debug(method +": isDelegation: urlSanExt1:" + urlSanExt1); + logger.debug( + "TPSEnrollProcessor.enrollOneCertificate: isDelegation: urlSanExt1:" + urlSanExt1); sanNum++; } } catch (EBaseException e) { - logger.warn(method +": isDelegation sanPattern not set: " + e.getMessage(), e); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: isDelegation sanPattern not set"); } - logger.debug(method +": isDelegation: Before calling enrolCertificate"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: isDelegation: Before calling enrolCertificate"); caEnrollResp = caRH.enrollCertificate(encodedParsedPubKey, userid, subjectdn, sanNum, urlSanExt, aInfo.getCUIDHexStringHyphens(), getSelectedTokenType(), cEnrollInfo.getKeyType()); } else { - logger.debug(method +": not isDelegation: Before calling enrolCertificate"); + logger.debug( + "TPSEnrollProcessor.enrollOneCertificate: not isDelegation: Before calling enrolCertificate"); caEnrollResp = caRH.enrollCertificate(encodedParsedPubKey, userid, aInfo.getCUIDHexStringHyphens(), getSelectedTokenType(), cEnrollInfo.getKeyType()); @@ -2708,30 +2773,30 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE String retCertB64 = caEnrollResp.getCertB64(); if (retCertB64 != null) - //logger.debug(method +": new cert b64 =" + retCertB64); - logger.debug(method +": new cert b64 retrieved from caEnrollResp"); + //logger.debug("TPSEnrollProcessor.enrollOneCertificate:: new cert b64 =" + retCertB64); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: new cert b64 retrieved from caEnrollResp"); else { auditInfo = "new cert b64 not found"; - logger.error(method +": " + auditInfo); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: " + auditInfo); auditEnrollment(userid, "enrollment", aInfo, "failure", channel.getKeyInfoData().toHexStringPlain(), BigInteger.ZERO, caConnID, auditInfo); - throw new TPSException(method +": " + auditInfo, + throw new TPSException("TPSEnrollProcessor.enrollOneCertificate: " + auditInfo, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } cert_bytes = Utils.base64decode(retCertB64); //TPSBuffer cert_bytes_buf = new TPSBuffer(cert_bytes); - //logger.debug(method +": retCertB64: " + cert_bytes_buf.toHexString()); - logger.debug(method +": retCertB64 base64decode done"); + //logger.debug("TPSEnrollProcessor.enrollOneCertificate: retCertB64: " + cert_bytes_buf.toHexString()); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: retCertB64 base64decode done"); x509Cert = caEnrollResp.getCert(); if (x509Cert != null) { - logger.debug(method + ": new cert retrieved"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: new cert retrieved"); } else { - logger.error(method + ": new cert not found"); - throw new TPSException(method + ": new cert not found", + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: new cert not found"); + throw new TPSException("TPSEnrollProcessor.enrollOneCertificate: new cert not found", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -2742,7 +2807,8 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE //Import the cert data from the CertEnrollObject or from Renewal object - logger.debug(method + ": Attempt to import cert data in recovery mode or renew mode!"); + logger.debug( + "TPSEnrollProcessor.enrollOneCertificate: Attempt to import cert data in recovery mode or renew mode!"); if (isRecovery) { @@ -2750,33 +2816,34 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE if (certResp == null) { throw new TPSException( - method + ": In recovery mode, CARetieveCertResponse object not found!", + "TPSEnrollProcessor.enrollOneCertificate: In recovery mode, CARetieveCertResponse object not found!", TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } String retCertB64 = certResp.getCertB64(); if (retCertB64 != null) { - //logger.debug(method +": recovering: new cert b64 =" + retCertB64); - logger.debug(method +": recovering: new cert b64 not null"); + //logger.debug("TPSEnrollProcessor.enrollOneCertificate:: recovering: new cert b64 =" + retCertB64); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: recovering: new cert b64 not null"); } else { - logger.error(method +": recovering new cert b64 not found"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: recovering new cert b64 not found"); throw new TPSException( - method +": recovering: new cert b64 not found", + "TPSEnrollProcessor.enrollOneCertificate: recovering: new cert b64 not found", TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } - //logger.debug(method +": recovering: retCertB64: " + retCertB64); - logger.debug(method +": recovering: retCertB64 retrieved from certResp"); + //logger.debug("TPSEnrollProcessor.enrollOneCertificate: recovering: retCertB64: " + retCertB64); + logger.debug( + "TPSEnrollProcessor.enrollOneCertificate: recovering: retCertB64 retrieved from certResp"); cert_bytes = Utils.base64decode(retCertB64); - logger.debug(method +": recovering: retCertB64 base64decode done"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: recovering: retCertB64 base64decode done"); //TPSBuffer cert_bytes_buf = new TPSBuffer(cert_bytes); - //logger.debug(method +": recovering: retCertB64: " + //logger.debug("TPSEnrollProcessor.enrollOneCertificate: recovering: retCertB64: " // + cert_bytes_buf.toHexString()); x509Cert = certResp.getCert(); if (x509Cert != null) { - logger.debug(method +": recovering new cert retrieved"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: recovering new cert retrieved"); // recovered cert might have different status certStatus = getRetrievedCertStatus(certResp); @@ -2785,11 +2852,11 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE certResp.getConnID(), null); } else { auditInfo = "recovering new cert not found"; - logger.error(method +": " + auditInfo); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: " + auditInfo); auditEnrollment(userid, "retrieval", aInfo, "failure", channel.getKeyInfoData().toHexStringPlain(), null /*unavailable*/, certResp.getConnID(), auditInfo); - throw new TPSException(method +": " + auditInfo, + throw new TPSException("TPSEnrollProcessor.enrollOneCertificate: " + auditInfo, TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } @@ -2805,44 +2872,44 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE auditEnrollment(userid, "renewal", aInfo, "failure", channel.getKeyInfoData().toHexStringPlain(), null, caConnID, auditInfo); throw new TPSException( - method +": " + auditInfo, + "TPSEnrollProcessor.enrollOneCertificate: " + auditInfo, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } String retCertB64 = certResp.getRenewedCertB64(); if (retCertB64 != null) - //logger.debug(method +": renewing: new cert b64 =" + retCertB64); - logger.debug(method +": renewing: new cert b64 retrieved"); + //logger.debug("TPSEnrollProcessor.enrollOneCertificate:: renewing: new cert b64 =" + retCertB64); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: renewing: new cert b64 retrieved"); else { auditInfo = "renewing new cert b64 not found"; - logger.error(method +": " + auditInfo); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: " + auditInfo); auditEnrollment(userid, "renewal", aInfo, "failure", channel.getKeyInfoData().toHexStringPlain(), null, certResp.getConnID(), auditInfo); throw new TPSException( - method +": renewing: new cert b64 not found", + "TPSEnrollProcessor.enrollOneCertificate: remewomg: new cert b64 not found", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } cert_bytes = Utils.base64decode(retCertB64); - logger.debug(method +": renewing: retCertB64 base64decode done"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: renewing: retCertB64 base64decode done"); //TPSBuffer cert_bytes_buf = new TPSBuffer(cert_bytes); - //logger.debug(method +": renewing: retCertB64: " + //logger.debug("TPSEnrollProcessor.enrollOneCertificate: renewing: retCertB64: " // + cert_bytes_buf.toHexString()); x509Cert = certResp.getRenewedCert(); if (x509Cert != null) { - logger.debug(method +": renewing new cert retrieved"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: renewing new cert retrieved"); auditEnrollment(userid, "renewal", aInfo, "success", channel.getKeyInfoData().toHexStringPlain(), x509Cert.getSerialNumber(), certResp.getConnID(), null); } else { auditInfo = "renewing new cert not found"; - logger.error(method +": " + auditInfo); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: " + auditInfo); auditEnrollment(userid, "renewal", aInfo, "failure", channel.getKeyInfoData().toHexStringPlain(), null, certResp.getConnID(), auditInfo); - throw new TPSException(method +": " + auditInfo, + throw new TPSException("TPSEnrollProcessor.enrollOneCertificate: " + auditInfo, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -2855,21 +2922,21 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE //Add origin, special handling for recovery case. if (isRecovery == true) { - logger.debug(method +": about to find origiinal cert record"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: about to find origiinal cert record"); TPSCertRecord origCertRec = tps.getTokendb().tdbGetOrigCertRecord(x509Cert); if (origCertRec != null) { - logger.debug(method +": token origin found"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: token origin found"); certsInfo.addTokenType(origCertRec.getType()); certsInfo.addOrigin(origCertRec.getOrigin()); certsInfo.addKType(origCertRec.getKeyType()); } else { - logger.debug(method +": cert origin not found"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: cert origin not found"); TokenRecord recordToRecover = cEnrollInfo.getTokenToBeRecovered(); //We need to have this token record otherwise bomb out. if (recordToRecover == null) { throw new TPSException( - method +": TokenRecord of token to be recovered not found.", + "TPSEnrollProcessor.enrollOneCertificate: TokenRecord of token to be recovered not found.", TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } @@ -2900,15 +2967,15 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE publicKeyInfo = new SubjectPublicKeyInfo(parsedPubKey); } } catch (InvalidBERException e) { - logger.error(method +": cant get publicKeyInfo object: " + e.getMessage(), e); - throw new TPSException(method +": can't get publcKeyInfo object.", + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: cant get publicKeyInfo object."); + throw new TPSException("TPSEnrollProcessor.enrollOneCertificate: can't get publcKeyInfo object.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } //Create label ToDo: Do this the correct way later label = buildCertificateLabel(cEnrollInfo, aInfo); - logger.debug(method +": cert label: " + label); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: cert label: " + label); keyid = new TPSBuffer(makeKeyIDFromPublicKeyInfo(publicKeyInfo.getEncoded())); @@ -2940,7 +3007,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE // l2 = (certId.charAt(1) & 0xff) << 16; // objid = l1 + l2; - logger.debug(method +": cert objid long: " + objid); + logger.debug("TPSEnrollProcess.enrollOneCertificate: cert objid long: " + objid); ObjectSpec certObjSpec = ObjectSpec.parseFromTokenData(objid, new TPSBuffer(cert_bytes)); pkcs11Obj.addObjectSpec(certObjSpec); @@ -2956,7 +3023,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE objid = ObjectSpec.createObjectID(certAttrId); - logger.debug(method +": cert attr objid long: " + objid); + logger.debug("TPSEnrollProcess.enrollOneCertificate: cert attr objid long: " + objid); ObjectSpec certAttrObjSpec = ObjectSpec.parseFromTokenData(objid, certAttrsBuffer); pkcs11Obj.addObjectSpec(certAttrObjSpec); @@ -2966,7 +3033,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE objid = ObjectSpec.createObjectID(priKeyAttrId); - logger.debug(method + ": pri key objid long: " + objid); + logger.debug("TPSEnrollProcess.enrollOneCertificate: pri key objid long: " + objid); TPSBuffer privKeyAttrsBuffer = channel.createPKCS11PriKeyAttrsBuffer(priKeyAttrId, label, keyid, modulus, cEnrollInfo.getKeyTypePrefix()); @@ -2980,7 +3047,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE objid = ObjectSpec.createObjectID(pubKeyAttrId); - logger.debug(method + ": pub key objid long: " + objid); + logger.debug("TPSEnrollProcess.enrollOneCertificate: pub key objid long: " + objid); TPSBuffer pubKeyAttrsBuffer = channel.createPKCS11PublicKeyAttrsBuffer(pubKeyAttrId, label, keyid, modulus, exponent, cEnrollInfo.getKeyTypePrefix()); @@ -2989,14 +3056,14 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE } } catch (EBaseException e) { - logger.error(method +":" + e.getMessage(), e); - throw new TPSException(method +": Exception thrown: " + e, + logger.debug("TPSEnrollProcessor.enrollOneCertificate::" + e); + throw new TPSException("TPSEnrollProcessor.enrollOneCertificate: Exception thrown: " + e, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } if (serverSideKeyGen || isRecovery) { //Handle injection of private key onto token - logger.debug(method +": About to inject private key"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate: About to inject private key"); if (!isRecovery) { @@ -3009,7 +3076,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE } - logger.debug(method +": enrollment ends"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate:: enrollment ends"); if(x509Cert != null && x509Cert.getSerialNumber() != null) { tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, session.getTokenRecord(), session.getIpAddress(), @@ -3017,7 +3084,7 @@ private void enrollOneCertificate(EnrolledCertsInfo certsInfo, CertEnrollInfo cE } statusUpdate(cEnrollInfo.getEndProgressValue(), "PROGRESS_ENROLL_CERT"); - logger.debug(method +": ends"); + logger.debug("TPSEnrollProcessor.enrollOneCertificate ends"); } @@ -3044,7 +3111,7 @@ TokenCertStatus getRetrievedCertStatus(CARetrieveCertResponse certResponse) if (certResponse.isCertRevoked()) { String revReason = certResponse.getRevocationReason(); logger.debug(method + ": cert revoked; reason=" + revReason); - if (RevocationReason.valueOf(Integer.parseInt(revReason)) == RevocationReason.CERTIFICATE_HOLD) + if (RevocationReason.fromInt(Integer.parseInt(revReason)) == RevocationReason.CERTIFICATE_HOLD) ret = TokenCertStatus.ONHOLD; else ret = TokenCertStatus.REVOKED; @@ -3083,10 +3150,9 @@ private void importPrivateKeyPKCS8(String wrappedPrivKeyStr, String ivParams, Ce SecureChannel channel, boolean isECC) throws TPSException, IOException { - String method = "TPSEnrollProcessor.importPrivateKeyPKCS8"; - logger.debug(method + " entering.."); + logger.debug("TPSEnrollProcessor.importprivateKeyPKCS8 entering.."); if (wrappedPrivKeyStr == null || ivParams == null || cEnrollInfo == null || channel == null) { - throw new TPSException(method + ": invalid input data!", + throw new TPSException("TPSEnrollProcessor.importPrivateKeyPKCS8: invalid input data!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -3111,7 +3177,7 @@ private void importPrivateKeyPKCS8(String wrappedPrivKeyStr, String ivParams, Ce TPSBuffer privKeyBuff = new TPSBuffer(Util.uriDecodeFromHex(wrappedPrivKeyStr)); privKeyBlob.add(privKeyBuff); - //logger.debug(method + " privKeyBlob: " + privKeyBlob.toHexString()); + //logger.debug("TPSEnrollProcessor.importprivateKeyPKCS8 privKeyBlob: " + privKeyBlob.toHexString()); byte[] perms = { 0x40, 0x00, @@ -3132,47 +3198,57 @@ private void importPrivateKeyPKCS8(String wrappedPrivKeyStr, String ivParams, Ce keyCheck = new TPSBuffer(); } - //logger.debug(method + ": keyCheck: " + keyCheck.toHexString()); - logger.debug(method + ": got keyCheck"); + //logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8 : keyCheck: " + keyCheck.toHexString()); + logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8 : got keyCheck"); //String ivParams = ssKeyGenResponse.getIVParam(); - //logger.debug(method + ": ivParams: " + ivParams); + //logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8: ivParams: " + ivParams); TPSBuffer ivParamsBuff = new TPSBuffer(Util.uriDecodeFromHex(ivParams)); if (ivParamsBuff.size() == 0) { - throw new TPSException(method + ": invalid iv vector!", + throw new TPSException("TPSEnrollProcessor.importPrivateKeyPKCS8: invalid iv vector!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - TPSBuffer kekWrappedAESKey = channel.getKekAesKey(); TPSBuffer kekWrappedDesKey = channel.getKekDesKey(); TPSBuffer kekWrappedKey = null; - - if(kekWrappedAESKey != null) { - logger.debug(method + " kekWrappedAesKey provided."); + if(kekWrappedAESKey != null) { + logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8 : kekWrappedAesKey provided."); } - if (kekWrappedDesKey != null) { - //logger.debug(method + ": keyWrappedDesKey: " + kekWrappedDesKey.toHexString()); - logger.debug(method + ": got keyWrappedDesKey"); +// logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8: keyWrappedDesKey: " + kekWrappedDesKey.toHexString()); + logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8: got keyWrappedDesKey"); } else - logger.debug(method + ": null kekWrappedDesKey!"); + logger.debug("TPSEnrollProcessor.importPrivateKeyPKC8: null kekWrappedDesKey!"); byte alg = (byte) 0x80; if (kekWrappedDesKey != null && kekWrappedDesKey.size() > 0) { + logger.debug("TPSEnrollProcessor.importPrivateKeyPKC8: setting alg to 0x81 for DES wrapping!"); kekWrappedKey = kekWrappedDesKey; alg = (byte) 0x81; } - //Give preference to AES kek wrapped key for SCP03, otherwise go with DES for SCP01 - if(kekWrappedAESKey != null && kekWrappedAESKey.size() > 0 && channel.isSCP03()) { - alg = (byte) 0x88; + //RedHat modify to allow for the non external reg key wrap alg to be set to DES for legacy tokens. + //Give preference to AES kek wrapped key for SCP03, otherwise go with DES for SCP01 or even SCP03 if so configured. + //This allows the feature of legacy DES wrapping for SCP03 legacy tokens when not using externalReg. + if(kekWrappedAESKey != null && kekWrappedAESKey.size() > 0 && channel.isSCP03() && !isDesConfigured())// ** Applet and Alg Selection by Token Range Support: check if DES is configured) + { + String aesKeyWrapAlg = cEnrollInfo.getAesKeyWrapAlg(); + + if(aesKeyWrapAlg != null && "CBC".equalsIgnoreCase(aesKeyWrapAlg)) { //CBC + logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8: unwrap the priv key with AES CBC "); + alg = (byte) 0x89; + } else { // KWP + logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8: unwrap the priv key with AES KWP "); + alg = (byte) 0x88; + } + kekWrappedKey = kekWrappedAESKey; } - logger.debug(method + ": kek wrapped key outgoing: size: " + kekWrappedKey.size()); + logger.debug("TPSEnrollProcessor.importPrivateKeyPKCS8 : kek wrapped key outgoing: size: " + kekWrappedKey.size()); TPSBuffer data = new TPSBuffer(); data.add(objIdBuff); @@ -3185,24 +3261,23 @@ private void importPrivateKeyPKCS8(String wrappedPrivKeyStr, String ivParams, Ce } data.add((byte) ivParamsBuff.size()); data.add(ivParamsBuff); - //logger.debug(method + ": key data outgoing: " + data.toHexString()); + //logger.debug("TPSEnrollProcessor.importprivateKeyPKCS8: key data outgoing: " + data.toHexString()); int pe1 = (cEnrollInfo.getKeyUser() << 4) + cEnrollInfo.getPrivateKeyNumber(); int pe2 = (cEnrollInfo.getKeyUsage() << 4) + cEnrollInfo.getPublicKeyNumber(); channel.importKeyEnc(pe1, pe2, data); - logger.debug(method + " successful, leaving..."); + logger.debug("TPSEnrollProcessor.importprivateKeyPKCS8 successful, leaving..."); } private String buildCertificateLabel(CertEnrollInfo cEnrollInfo, AppletInfo ainfo) throws TPSException { - String method = "TPSEnrollProcessor.buildCertificateLabel"; - logger.debug(method + " begins"); + logger.debug("TPSEnrollProcessor.buildCertificateLabel"); if (cEnrollInfo == null) { - throw new TPSException(method + ": Invalid input params!", + throw new TPSException("TPSErollProcessor.buildCertificateLabel: Invalid input params!", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } @@ -3211,13 +3286,12 @@ private String buildCertificateLabel(CertEnrollInfo cEnrollInfo, AppletInfo ainf String defaultLabel = cEnrollInfo.getKeyType() + " key for $userid$"; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String configValue = "op." + currentTokenOperation + "." + selectedTokenType + ".keyGen." + cEnrollInfo.getKeyType() + ".label"; - logger.debug(method + ": label config: " + configValue); + logger.debug("TPSEnrollProcessor.buildCertificateLabel: label config: " + configValue); try { pattern = configStore.getString( @@ -3225,11 +3299,11 @@ private String buildCertificateLabel(CertEnrollInfo cEnrollInfo, AppletInfo ainf } catch (EBaseException e) { throw new TPSException( - method + ": Internal error finding config value: " + e, + "TPSEnrollProcessor.buildCertificateLabel: Internal error finding config value: " + e, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - Map nv = new LinkedHashMap<>(); + Map nv = new LinkedHashMap(); nv.put("cuid", ainfo.getCUIDhexString()); nv.put("msn", ainfo.getMSNString()); @@ -3239,7 +3313,7 @@ private String buildCertificateLabel(CertEnrollInfo cEnrollInfo, AppletInfo ainf label = mapPattern((LinkedHashMap) nv, pattern); - logger.debug(method + ": returning: " + label); + logger.debug("TPSEnrollProcessor.buildCertificateLabel: returning: " + label); return label; } @@ -3320,18 +3394,17 @@ private RSAPublicKey parsePublicKeyBlob( /* TPSBuffer challenge,*/ boolean isECC) throws TPSException { - String method = "TPSEnrollProcessor.parsePublicKeyBlob"; RSAPublicKey parsedPubKey = null; if (public_key_blob == null /*|| challenge == null*/) { throw new TPSException( - method + ": Bad input data! Missing public_key_blob or challenge", + "TPSEnrollProcessor.parsePublicKeyBlob: Bad input data! Missing public_key_blob or challenge", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - //logger.debug(method + ": public key blob from token to parse: " + //logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: public key blob from token to parse: " // + public_key_blob.toHexString()); - logger.debug(method + ": parsing public key blob from token"); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: parsing public key blob from token"); /* * decode blob into structures @@ -3350,19 +3423,19 @@ private RSAPublicKey parsePublicKeyBlob( int pkeyb_len = (len0 << 8) | (len1 & 0xFF); */ int pkeyb_len = public_key_blob.getIntFrom2Bytes(pkeyb_len_offset); - logger.debug(method + ": pkeyb_len = " + + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: pkeyb_len = " + pkeyb_len + ", isECC: " + isECC); // public key blob TPSBuffer pkeyb = public_key_blob.substr(pkeyb_len_offset + 2, pkeyb_len); if (pkeyb == null) { - logger.error(method + ": pkeyb null"); - throw new TPSException(method + ": Bad input data! pkeyb null", + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: pkeyb null "); + throw new TPSException("TPSEnrollProcessor.parsePublicKeyBlob: Bad input data! pkeyb null", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - //logger.debug(method + ": pkeyb = " + //logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: pkeyb = " // + pkeyb.toHexString()); - logger.debug(method + ": public key pkeyb extracted from blob"); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: public key pkeyb extracted from blob"); // 2nd, proof blob length int proofb_len_offset = pkeyb_len_offset + 2 + pkeyb_len; /* @@ -3374,13 +3447,13 @@ private RSAPublicKey parsePublicKeyBlob( // proof blob TPSBuffer proofb = public_key_blob.substr(proofb_len_offset + 2, proofb_len); if (proofb == null) { - logger.error(method + ": proofb null"); - throw new TPSException(method + ": Bad input data! proofb null", + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: proofb null "); + throw new TPSException("TPSEnrollProcessor.parsePublicKeyBlob: Bad input data! proofb null", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - //logger.debug(method + ": proofb = " + //logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: proofb = " // + proofb.toHexString()); - logger.debug(method + ": proof proofb extracted from blob"); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: proof proofb extracted from blob"); // convert pkeyb to pkey // 1 byte encoding, 1 byte key type, 2 bytes key length, then the key @@ -3392,45 +3465,45 @@ private RSAPublicKey parsePublicKeyBlob( if (!isECC) { // int mod_len = len0 << 8 | len1 & 0xFF; int mod_len = pkeyb.getIntFrom2Bytes(pkey_offset); - logger.debug(method + ": mod_len= " + mod_len); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: mod_len= " + mod_len); /* len0 = pkeyb.at(pkey_offset + 2 + mod_len); len1 = pkeyb.at(pkey_offset + 2 + mod_len + 1); int exp_len = len0 << 8 | len1 & 0xFF; */ int exp_len = pkeyb.getIntFrom2Bytes(pkey_offset + 2 + mod_len); - logger.debug(method + ": exp_len= " + exp_len); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: exp_len= " + exp_len); TPSBuffer modb = pkeyb.substr(pkey_offset + 2, mod_len); if (modb == null) { - logger.error(method + ": modb null"); - throw new TPSException(method + ": Bad input data! modb null", + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: modb null "); + throw new TPSException("TPSEnrollProcessor.parsePublicKeyBlob: Bad input data! modb null", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - //logger.debug(method + ": modb= " + //logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: modb= " // + modb.toHexString()); - logger.debug(method + ": modulus modb extracted from blob"); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: modulus modb extracted from blob"); TPSBuffer expb = pkeyb.substr(pkey_offset + 2 + mod_len + 2, exp_len); if (expb == null) { - logger.error(method + ": expb null"); - throw new TPSException(method + ": Bad input data! expb null", + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: expb null "); + throw new TPSException("TPSEnrollProcessor.parsePublicKeyBlob: Bad input data! expb null", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - //logger.debug(method + ": expb= " + //logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: expb= " // + expb.toHexString()); - logger.debug(method + ":processing exponent expb extracted from blob"); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob:processing exponent expb extracted from blob"); BigInt modb_bi = new BigInt(modb.toBytesArray()); BigInt expb_bi = new BigInt(expb.toBytesArray()); try { RSAPublicKey rsa_pub_key = new RSAPublicKey(modb_bi, expb_bi); - logger.debug(method + ": public key blob converted to RSAPublicKey"); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: public key blob converted to RSAPublicKey"); if (rsa_pub_key != null) { parsedPubKey = rsa_pub_key; } } catch (InvalidKeyException e) { - logger.error(method + ":InvalidKeyException thrown: " + e.getMessage(), e); - throw new TPSException(method + ": Exception thrown: " + e, + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob:InvalidKeyException thrown"); + throw new TPSException("TPSEnrollProcessor.parsePublicKeyBlob: Exception thrown: " + e, TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } } else { @@ -3441,32 +3514,73 @@ private RSAPublicKey parsePublicKeyBlob( // sanity-check parsedPubKey before return if (parsedPubKey == null) { - logger.error(method + ": parsedPubKey null"); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: parsedPubKey null"); throw new TPSException( - method + ": parsedPubKey null.", + "TPSEnrollProcessor.parsePublicKeyBlob: parsedPubKey null.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); + } else { + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: parsedPubKey not null"); } - logger.debug(method + ": parsedPubKey not null"); byte[] parsedPubKey_ba = parsedPubKey.getEncoded(); if (parsedPubKey_ba == null) { - logger.error(method + ": parsedPubKey_ba null"); + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: parsedPubKey_ba null"); throw new TPSException( - method + ": parsedPubKey encoding failure.", + "TPSEnrollProcessor.parsePublicKeyBlob: parsedPubKey encoding failure.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); + } else { + logger.debug("TPSEnrollProcessor.parsePublicKeyBlob: parsedPubKey getEncoded not null"); } - logger.debug(method + ": parsedPubKey getEncoded not null"); return parsedPubKey; } + //Redhat change name of method since it's multi purpose. + public String establishSymKeyWrapAlgSSKeyGen() { + + String aesKeyWrapAlg = "KWP"; + + String method = "TPSEnrollProcessor::establishSymKeyWrapAlgSSKeyGen: "; + // Applet and Alg Selection by Token Range Support - check keyWrapAlg target configuration in token range first + String selectedAlg = getSelectedKeyWrapAlg(); + if (selectedAlg == null) { // Applet and Alg Selection by Token Range Support - use aesKeyWrapAlg configured by tokenType + TPSEngineConfig configStore = this.getConfigStore(); + + // op.enroll.userKey.keyGen.aesKeyWrapAlg + try { + String configValue = TPSEngine.OP_ENROLL_PREFIX + "." + selectedTokenType + "." + TPSEngine.CFG_KEYGEN + + "." + TPSEngine.CFG_AES_KEY_WRAP_ALG; + + logger.debug(method + " configValue . " + configValue); + aesKeyWrapAlg = configStore.getString( + configValue, "KWP"); + logger.debug(method + " value " + aesKeyWrapAlg); + // Red Hat call into the new method to set DES to allow it to work for the non external reg case. + if(aesKeyWrapAlg.equalsIgnoreCase("DES")) { + logger.debug(method + " DES configured per original token based value."); + setSelectedKeyWrapAlg(aesKeyWrapAlg); + } + + } catch (EBaseException e) { + //return default + return aesKeyWrapAlg; + } + } else { + aesKeyWrapAlg = selectedAlg; + logger.debug(method + " using keyWrapAlg configured by token range or token type: " + aesKeyWrapAlg); + } + + logger.debug(method + " returning: " + aesKeyWrapAlg); + return aesKeyWrapAlg; + + } + private boolean checkForServerSideKeyGen(CertEnrollInfo cInfo) throws TPSException { if (cInfo == null) { throw new TPSException("TPSEnrollProcessor.checkForServerSideKeyGen: invalid cert info.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); boolean serverSideKeygen = false; try { @@ -3493,8 +3607,7 @@ private boolean checkForServerKeyArchival(CertEnrollInfo cInfo) throws TPSExcept throw new TPSException("TPSEnrollProcessor.checkForServerKeyArchival: invalid cert info.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); boolean serverKeyArchival = false; try { @@ -3521,8 +3634,7 @@ private boolean checkForObjectOverwrite(CertEnrollInfo cInfo) throws TPSExceptio throw new TPSException("TPSEnrollProcessor.checkForObjectOverwrite: invalid cert info.", TPSStatus.STATUS_ERROR_MAC_ENROLL_PDU); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); boolean objectOverwrite = false; try { @@ -3547,8 +3659,7 @@ private boolean checkForObjectOverwrite(CertEnrollInfo cInfo) throws TPSExceptio private String getConfiguredKeyType(int keyTypeIndex) throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String keyType = null; try { @@ -3581,8 +3692,7 @@ private String getDRMConnectorID(String keyType) throws TPSException { if(keyType == null || keyType.isEmpty()) keyType = TPSEngine.CFG_ENCRYPTION; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String id = null; String config = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_KEYGEN @@ -3605,8 +3715,7 @@ private String getDRMConnectorID(String keyType) throws TPSException { protected int getNumberCertsToEnroll() throws TPSException { String method = "TPSEnrollProcessor.getNumberCertsToEnroll:"; String logMsg; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int keyTypeNum = 0; try { String configValue = TPSEngine.OP_ENROLL_PREFIX + "." + selectedTokenType + "." @@ -3619,6 +3728,7 @@ protected int getNumberCertsToEnroll() throws TPSException { logMsg = "Internal error finding config value: " + e; throw new TPSException(method + logMsg, TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } if (!isExternalReg) { @@ -3634,8 +3744,7 @@ protected int getNumberCertsToEnroll() throws TPSException { } protected int getEnrollmentAlg() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int enrollmentAlg; try { String configValue = TPSEngine.OP_ENROLL_PREFIX + "." + selectedTokenType + "." @@ -3665,13 +3774,13 @@ protected String getRecoveryKeyTypeValue(String reason, int index) throws TPSExc TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String keyTypeValue; try { String configValue = TPSEngine.OP_ENROLL_PREFIX + "." + selectedTokenType + "." + TPSEngine.CFG_KEYGEN + "." + TPSEngine.RECOVERY_OP + "." + reason + "." + TPSEngine.CFG_KEYTYPE_VALUE + "." + index; + ; logger.debug("TPSProcess.getRecoveryKeyTypeValue: configValue: " + configValue); @@ -3702,13 +3811,13 @@ protected String getRecoveryScheme(String reason, String keyTypeValue) throws TP TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String scheme = null; try { String configValue = TPSEngine.OP_ENROLL_PREFIX + "." + selectedTokenType + "." + TPSEngine.CFG_KEYGEN + "." + keyTypeValue + "." + TPSEngine.RECOVERY_OP + "." + reason + "." + TPSEngine.CFG_SCHEME; + ; logger.debug("TPSProcess.getRecoveryScheme: configValue: " + configValue); @@ -3738,8 +3847,7 @@ protected int getNumberCertsForRecovery(String reason) throws TPSException { TPSStatus.STATUS_ERROR_RECOVERY_FAILED); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int keyTypeNum = 0; try { String configValue = TPSEngine.OP_ENROLL_PREFIX + "." + selectedTokenType + "." + TPSEngine.CFG_KEYGEN @@ -3802,7 +3910,7 @@ private TPSBuffer makeKeyIDFromPublicKeyInfo(byte[] publicKeyInfo) throws TPSExc keyID = new TPSBuffer(mozillaDigestOut); - //logger.debug("TPSEnrollProcessor.makeKeyIDFromPublicKeyInfo: " + keyID.toHexString()); +// logger.debug("TPSEnrollProcessor.makeKeyIDFromPublicKeyInfo: " + keyID.toHexString()); return keyID; } @@ -3829,9 +3937,6 @@ private void auditEnrollment(String subjectID, String op, String caConnId, String info) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - // when serial is 0, means no serial, as in case of failure String serialNum = ""; if (serial != null && serial.compareTo(BigInteger.ZERO) > 0) @@ -3860,7 +3965,7 @@ private void auditEnrollment(String subjectID, String op, serialNum, caConnId, info); - auditor.log(auditMessage); + audit(auditMessage); } private void auditRecovery(String subjectID, AppletInfo aInfo, @@ -3871,9 +3976,6 @@ private void auditRecovery(String subjectID, AppletInfo aInfo, String kraConnId, String info) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - String serialNum = ""; if (serial.compareTo(BigInteger.ZERO) > 0) serialNum = serial.toString(); @@ -3890,7 +3992,7 @@ private void auditRecovery(String subjectID, AppletInfo aInfo, caConnId, kraConnId, info); - auditor.log(auditMessage); + audit(auditMessage); } private boolean checkUserAlreadyHasActiveToken(String userid) { @@ -3900,6 +4002,7 @@ private boolean checkUserAlreadyHasActiveToken(String userid) { TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + try { tps.tdb.tdbHasActiveToken(userid); result = true; @@ -3919,6 +4022,7 @@ private boolean checkUserAlreadyHasOtherActiveToken(String userid, String cuid) TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + try { tps.tdb.tdbHasOtherActiveToken(userid, cuid); result = true; @@ -3936,9 +4040,7 @@ private boolean checkAllowMultiActiveTokensUser(boolean isExternalReg) { boolean allow = true; String method = "TPSEnrollProcessor.checkAllowMultiActiveTokensUser: "; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); - TokenDBConfig tdbConfig = configStore.getTokenDBConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String scheme = null; @@ -3948,11 +4050,13 @@ private boolean checkAllowMultiActiveTokensUser(boolean isExternalReg) { scheme = TPSEngine.CFG_NON_EXTERNAL_REG; } - String allowMultiConfig = scheme + "." + TPSEngine.CFG_ALLOW_MULTI_TOKENS_USER; - logger.debug(method + " trying config: tokendb." + allowMultiConfig); + String allowMultiConfig = TPSEngine.CFG_TOKENDB + "." + scheme + "." + + TPSEngine.CFG_ALLOW_MULTI_TOKENS_USER; + + logger.debug(method + " trying config: " + allowMultiConfig); try { - allow = tdbConfig.getBoolean(allowMultiConfig, false); + allow = configStore.getBoolean(allowMultiConfig, false); } catch (EBaseException e) { allow = false; } @@ -3962,36 +4066,49 @@ private boolean checkAllowMultiActiveTokensUser(boolean isExternalReg) { return allow; } - public static void main(String[] args) { - } + // RH update for AES Key Wrap Alg private TPSBuffer getDRMDesKeyByProtocol(SecureChannel channel) { String method = "TPSEnrollProcessor.getDRMDesKeyByProtocol: "; int prot = getProtocol(); TPSBuffer drmDesKey = null; + + logger.debug(method + " protocol: " + prot); - logger.debug(method + " protocol: " + prot); - - if(prot == 1) + if(prot == 1 || isDesConfigured()) { // ** Applet and Alg Selection by Token Range Support: case of SafeNet SCP03 still using DES drmDesKey = channel.getDRMWrappedDesKey(); + } return drmDesKey; } + // RH update for AES Key Wrap Alg private TPSBuffer getDRMAesKeyByProtocol(SecureChannel channel) { - String method = "TPSEnrollProcessor.getDRMAesKeyByProtocol: "; + String method = "TPSEnrollProcessor.getDRMAesKeyByProtocol: "; int prot = getProtocol(); TPSBuffer drmAesKey = null; logger.debug(method + " protocol: " + prot); - if(prot == 3) + if(prot == 3 && !isDesConfigured()) { // ** Applet and Alg Selection by Token Range Support: case of SafeNet SCP03 still using DES drmAesKey = channel.getDRMWrappedAesKey(); + } return drmAesKey; } + private TPSEngineConfig getConfigStore() { + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSEngineConfig configStore = engine.getConfig(); + + return configStore; + } + + public static void main(String[] args) { + } + } diff --git a/base/tps/src/main/java/org/dogtagpki/server/tps/processor/TPSProcessor.java b/base/tps/src/main/java/org/dogtagpki/server/tps/processor/TPSProcessor.java index 5d681980c7d..151c4cf5707 100644 --- a/base/tps/src/main/java/org/dogtagpki/server/tps/processor/TPSProcessor.java +++ b/base/tps/src/main/java/org/dogtagpki/server/tps/processor/TPSProcessor.java @@ -34,20 +34,12 @@ import java.util.Map; import java.util.Set; -import org.dogtagpki.server.authentication.AuthManager; -import org.dogtagpki.server.authentication.AuthManagersConfig; -import org.dogtagpki.server.authentication.AuthToken; -import org.dogtagpki.server.authentication.AuthenticationConfig; -import org.dogtagpki.server.tps.TPSEngine; -import org.dogtagpki.server.tps.TPSEngineConfig; import org.dogtagpki.server.tps.TPSSession; import org.dogtagpki.server.tps.TPSSubsystem; -import org.dogtagpki.server.tps.TokenDBConfig; import org.dogtagpki.server.tps.authentication.AuthUIParameter; import org.dogtagpki.server.tps.authentication.TPSAuthenticator; import org.dogtagpki.server.tps.channel.PlatformAndSecChannelProtoInfo; import org.dogtagpki.server.tps.channel.SecureChannel; -import org.dogtagpki.server.tps.channel.SecureChannelProtocol; import org.dogtagpki.server.tps.cms.CARemoteRequestHandler; import org.dogtagpki.server.tps.cms.CARevokeCertResponse; import org.dogtagpki.server.tps.cms.TKSComputeRandomDataResponse; @@ -91,24 +83,31 @@ import org.mozilla.jss.NotInitializedException; import org.mozilla.jss.crypto.CryptoToken; import org.mozilla.jss.crypto.SymmetricKey; -import org.mozilla.jss.netscape.security.x509.RevocationReason; import org.mozilla.jss.pkcs11.PK11SymKey; -import org.mozilla.jss.symkey.SessionKey; - +import com.netscape.cmscore.apps.CMS; import com.netscape.certsrv.authentication.AuthCredentials; +import org.dogtagpki.server.authentication.AuthManager; + +import org.dogtagpki.server.authentication.AuthToken; import com.netscape.certsrv.base.EBaseException; import com.netscape.certsrv.base.EPropertyNotFound; import com.netscape.certsrv.common.Constants; -import com.netscape.certsrv.dbs.DBRecordNotFoundException; import com.netscape.certsrv.logging.AuditEvent; +import com.netscape.certsrv.logging.LogEvent; import com.netscape.certsrv.logging.event.TokenAppletUpgradeEvent; import com.netscape.certsrv.logging.event.TokenAuthEvent; import com.netscape.certsrv.logging.event.TokenFormatEvent; import com.netscape.certsrv.logging.event.TokenKeyChangeoverEvent; import com.netscape.certsrv.tps.token.TokenStatus; -import com.netscape.cmscore.apps.CMS; -import com.netscape.cmscore.logging.Auditor; +import com.netscape.cms.logging.Logger; +import com.netscape.cms.logging.SignedAuditLogger; +import org.dogtagpki.server.tps.channel.SecureChannelProtocol; import com.netscape.cmsutil.crypto.CryptoUtil; +import org.mozilla.jss.symkey.SessionKey; +import org.mozilla.jss.netscape.security.x509.RevocationReason; +import com.netscape.cmscore.logging.Auditor; +import org.dogtagpki.server.tps.TPSEngine; +import org.dogtagpki.server.tps.TPSEngineConfig; public class TPSProcessor { @@ -142,6 +141,8 @@ public class TPSProcessor { //protected TokenRecord tokenRecord; protected String selectedTokenType; protected String selectedKeySet; + protected String selectedKeyWrapAlg; // ** Applet and Alg Selection by Token Range Support ** + protected String selectedAppletVer; // ** Applet and Alg Selection by Token Range Support ** AuthToken authToken; List ldapStringAttrs; @@ -151,7 +152,7 @@ public class TPSProcessor { protected BeginOpMsg beginMsg; private PlatformAndSecChannelProtoInfo platProtInfo; - ProfileDatabase profileDatabase; + ProfileDatabase profileDatabase = new ProfileDatabase(); public TPSProcessor(TPSSession session) { setSession(session); @@ -161,6 +162,7 @@ public TPSProcessor(TPSSession session) { profileDatabase = new ProfileDatabase(); profileDatabase.setEngineConfig(engineConfig); + } protected void setCurrentTokenOperation(String op) { @@ -183,6 +185,16 @@ protected TokenRecord getTokenRecord() { return session.getTokenRecord(); } + protected TPSBuffer getSelectedCardMgr() { + TPSSession session = getSession(); + return session.getSelectedCardMgr(); + } + + protected void setSelectedCardMgr(TPSBuffer cardMgr) { + TPSSession session = getSession(); + session.setSelectedCardMgr(cardMgr); + } + protected void setBeginMessage(BeginOpMsg msg) { beginMsg = msg; } @@ -196,7 +208,8 @@ protected void setSelectedTokenType(String theTokenType) { if (theTokenType == null) { throw new NullPointerException("TPSProcessor.setSelectedTokenType: Attempt to set invalid null token type!"); } - logger.debug("TPSProcessor.setSelectedTokenType: tokenType=" + theTokenType); + logger.debug("TPS_Processor.setSelectedTokenType: tokenType=" + + theTokenType); selectedTokenType = theTokenType; TokenRecord tokenRecord = getTokenRecord(); @@ -216,7 +229,8 @@ protected void setSelectedKeySet(String theKeySet) { if (theKeySet == null) { throw new NullPointerException("TPSProcessor.setSelectedKeySet: Attempt to set invalid null key set!"); } - logger.debug("TPSProcessor.setSelectedKeySet: keySet=" + theKeySet); + logger.debug("TPS_Processor.setSelectedKeySet: keySet=" + + theKeySet); selectedKeySet = theKeySet; } @@ -241,7 +255,7 @@ protected TPSBuffer extractTokenMSN(TPSBuffer cplc_data) throws TPSException { protected TPSBuffer extractTokenCUID(TPSBuffer cplc_data) throws TPSException { //Just make sure no one is inputing bogus cplc_data if (cplc_data == null || cplc_data.size() < CPLC_DATA_SIZE) { - logger.error("TPSProcessor.extractTokenCUID: cplc_data: invalid length."); + logger.debug("TPS_Processor.extractTokenCUID: cplc_data: invalid length."); throw new TPSException("TPSProcessor.extractTokenCUID: Can't extract cuid from cplc data!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -284,7 +298,7 @@ protected TPSBuffer extractTokenCUID(TPSBuffer cplc_data) throws TPSException { protected APDUResponse selectApplet(byte p1, byte p2, TPSBuffer aid) throws IOException, TPSException { - logger.debug("In TPSProcessor.selectApplet"); + logger.debug("In TPS_Processor.SelectApplet."); if (aid == null || aid.size() == 0) { throw new TPSException("TPSProcessor.selectApplet: Invalid aid value!", @@ -300,9 +314,23 @@ protected APDUResponse selectApplet(byte p1, byte p2, TPSBuffer aid) throws IOEx } + protected APDUResponse selectDefaultApplet(byte p1, byte p2, TPSBuffer len) throws IOException, TPSException { + + logger.debug("In TPS_Processor.SelectDefaultApplet."); + + SelectAPDU select_apdu = new SelectAPDU(p1, p2); + + //return the Response because the caller can + //decide what to do, not every failure is fatal. + //For instance the coolkey applet may not yet exist. + //return handleAPDURequest(select_apdu); + return handleAPDURequestWithLength(select_apdu, len); + + } + protected TPSBuffer getStatus() throws IOException, TPSException { - logger.debug("In TPSProcessor.getStatus"); + logger.debug("In TPS_Processor.GetStatus."); GetStatusAPDU get_status_apdu = new GetStatusAPDU(); @@ -316,11 +344,44 @@ public APDUResponse handleAPDURequest(APDU apdu) throws IOException, TPSExceptio } TokenPDURequestMsg request_msg = new TokenPDURequestMsg(apdu); + logger.debug("TPS_Processor.HandleAPDURequest: request_msg=" + request_msg.toString()); + + try { + session.write(request_msg); + } catch (IOException e) { + logger.debug("TPS_Processor.HandleAPDURequest failed WriteMsg: " + e.toString()); + throw e; + + } + + TokenPDUResponseMsg response_msg = null; + + try { + response_msg = (TokenPDUResponseMsg) session.read(); + } catch (IOException e) { + logger.debug("TPS_Processor.HandleAPDURequest failed ReadMsg: " + e.toString()); + throw e; + + } + + return response_msg.getResponseAPDU(); + } + + public APDUResponse handleAPDURequestWithLength(APDU apdu, TPSBuffer trailer) throws IOException, TPSException { + + if (apdu == null) { + throw new TPSException("TPSProcessor.handleAPDURequestWithLength: invalid incoming apdu!"); + } + + apdu.setTrailer(trailer); + + TokenPDURequestMsg request_msg = new TokenPDURequestMsg(apdu,true); + logger.debug("TPSProcessor.handleAPDURequestWithLength: request_msg=" + request_msg.toString()); try { session.write(request_msg); } catch (IOException e) { - logger.error("TPSProcessor.handleAPDURequest failed WriteMsg: " + e.getMessage(), e); + logger.debug("TPSProcessor.handleAPDURequestWithLength: failed WriteMsg: " + e.toString()); throw e; } @@ -330,7 +391,7 @@ public APDUResponse handleAPDURequest(APDU apdu) throws IOException, TPSExceptio try { response_msg = (TokenPDUResponseMsg) session.read(); } catch (IOException e) { - logger.error("TPSProcessor.handleAPDURequest failed ReadMsg: " + e.getMessage(), e); + logger.debug("TPSProcessor.handleAPDURequestWithLength: failed ReadMsg: " + e.toString()); throw e; } @@ -339,14 +400,25 @@ public APDUResponse handleAPDURequest(APDU apdu) throws IOException, TPSExceptio } protected TPSBuffer getCplcData() throws IOException, TPSException { - logger.debug("In TPSProcessor.getCplcData"); + logger.debug("In TPS_Processor. getCplcData"); GetDataAPDU get_data_apdu = new GetDataAPDU(); APDUResponse respApdu = handleAPDURequest(get_data_apdu); if (!respApdu.checkResult()) { - throw new TPSException("TPSProcessor.getCplcData: Can't get data!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + // If card needs length of data, resend request with length + if (respApdu.getSW1() == (byte) 0x6C) + { + TPSBuffer trailer = new TPSBuffer(respApdu.getSW2()); + // Request cplc data again from the token with correct length + logger.debug("TPSProcessor.getCplcData: Request for cplc data failed, retrying with correct length..."); + respApdu = handleAPDURequestWithLength(get_data_apdu, trailer); + } + + if (!respApdu.checkResult()) { + throw new TPSException("TPSProcessor.getCplcData: Can't get data!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + } } TPSBuffer cplcData = respApdu.getData(); @@ -358,7 +430,7 @@ protected TPSBuffer getCplcData() throws IOException, TPSException { } public TPSBuffer getData(byte[] identifier) throws TPSException, IOException { - logger.debug("In TPSProcessor.getData: identifier: " + identifier); + logger.debug("In TPSProcessor.getData: identifier: " + identifier.toString()); if (identifier == null || identifier.length != 2) { throw new TPSException("TPSProcessor.getData: Can't get data, invalid input data!", @@ -368,8 +440,21 @@ public TPSBuffer getData(byte[] identifier) throws TPSException, IOException { APDUResponse respApdu = handleAPDURequest(get_data_apdu); - if (!respApdu.checkResult()) { - throw new TPSException("TPSProcessor.getData: Can't get data!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + if (!respApdu.checkResult()) + { + // If card needs length of data, resend request with length + if (respApdu.getSW1() == (byte) 0x6C) + { + TPSBuffer trailer = new TPSBuffer(respApdu.getSW2()); + // Get data again from the token with correct length + logger.debug("TPSProcessor.getData: Request for card data failed, retrying with correct length..."); + respApdu = handleAPDURequestWithLength(get_data_apdu,trailer); + } + + if (!respApdu.checkResult()) + { + throw new TPSException("TPSProcessor.getData: Can't get data!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + } } return respApdu.getData(); @@ -388,16 +473,16 @@ protected TPSBuffer getAppletVersion() throws IOException, TPSException { APDUResponse respApdu = handleAPDURequest(get_version_apdu); if (!respApdu.checkResult()) { - logger.warn("TPSProcessor.getAppletVersion: No applet version found on card!"); + logger.debug("TPSProcessor.getAppletVersion: No applet version found on card!"); return null; } TPSBuffer apdu_data = respApdu.getData(); if (apdu_data.size() != 6) { - logger.error("TPSProcessor.getAppletVersion: incorrect return data size!"); + logger.debug("TPSProcessor.getAppletVersion: incorrect return data size!"); throw new TPSException("TPSProcessor.getAppletVersion: invalid applet version string returned!", - TPSStatus.STATUS_ERROR_CANNOT_PERFORM_OPERATION); + TPSStatus.STATUS_ERROR_CANNOT_PERFORM_OPERATION); } TPSBuffer build_id = apdu_data.substr(0, 4); @@ -413,7 +498,7 @@ protected byte getLifecycleState() { byte resultState = (byte) 0xf0; String method = "TPSProcessor.getLifecycleState:"; - logger.debug(method + " getLifecycleState: "); + logger.debug(".getLifecycleState: "); GetLifecycleAPDU getLifecycle = new GetLifecycleAPDU(); @@ -440,7 +525,7 @@ protected byte getLifecycleState() { } } catch (TPSException | IOException e) { - logger.warn(method + " problem getting state: " + e.getMessage(), e); + logger.debug(method + " problem getting state: " + e); } return resultState; @@ -503,6 +588,7 @@ protected TPSBuffer initializeUpdate(byte keyVersion, byte keyIndex, TPSBuffer r String method = "TPSProcessor.initializeUpdate:"; logger.debug(method + " Entering..."); + InitializeUpdateAPDU initUpdate = new InitializeUpdateAPDU(keyVersion, keyIndex, randomData); int done = 0; @@ -512,7 +598,7 @@ protected TPSBuffer initializeUpdate(byte keyVersion, byte keyIndex, TPSBuffer r APDUResponse resp = handleAPDURequest(initUpdate); if (!resp.checkResult()) { - logger.error("TPSProcessor.initializeUpdate: Failed intializeUpdate!"); + logger.debug("TPSProcessor.initializeUpdate: Failed intializeUpdate!"); throw new TPSException("TPSBuffer.initializeUpdate: Failed initializeUpdate!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); @@ -555,7 +641,8 @@ protected SecureChannel setupSecureChannel(byte keyVersion, byte keyIndex, //Assume generating host challenge on TKS, we no longer support not involving the TKS. - logger.debug("TPSProcessor.setupSecureChannel: keyVersion: " + keyVersion + " keyIndex: " + keyIndex); + logger.debug("TPSProcessor.setupSecureChannel: keyVersion: " + keyVersion + " keyIndex: " + keyIndex + ); if(appletInfo == null) { throw new TPSException("TPSProcessor.setupSecureChannel: invalid input data.", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); @@ -575,12 +662,12 @@ protected SecureChannel setupSecureChannel(byte keyVersion, byte keyIndex, TPSBuffer initUpdateResp = initializeUpdate(keyVersion, keyIndex, randomData); - //logger.debug("TPSProcessor.setupSecureChanne: initUpdateResponse: " + initUpdateResp.toHexString()); + logger.debug("TPSProcessor.setupSecureChannel: initUpdateResponse: " + initUpdateResp.toHexString()); TPSBuffer key_diversification_data = initUpdateResp.substr(0, DIVERSIFICATION_DATA_SIZE); appletInfo.setKDD(key_diversification_data); - //logger.debug("TPSProcessor.setupSecureChannel: diversification data: " + key_diversification_data.toHexString()); + logger.debug("TPSProcessor.setupSecureChannel: diversification data: " + key_diversification_data.toHexString()); TPSBuffer key_info_data = null; @@ -612,14 +699,15 @@ protected SecureChannel setupSecureChannel(byte keyVersion, byte keyIndex, .substr(CARD_CHALLENGE_OFFSET_GP211_SC02, CARD_CHALLENGE_SIZE_GP211_SC02); card_cryptogram = initUpdateResp.substr(CARD_CRYPTOGRAM_OFFSET, CARD_CRYPTOGRAM_SIZE); //new TPSBuffer(canned_card_challenge); - /* + /* logger.debug("TPSProcessor.setupSecureChannel 02: card cryptogram: " + card_cryptogram.toHexString()); logger.debug("TPSProcessor.setupSecureChannel 02: card challenge: " + card_challenge.toHexString()); logger.debug("TPSProcessor.setupSecureChannel 02: host challenge: " + randomData.toHexString()); */ + logger.debug("TPSProcessor.setupSecureChannel 02: card cryptogram: extracted"); logger.debug("TPSProcessor.setupSecureChannel 02: card challenge: extracted"); - + } //Set the second byte of the keyInfo data to 0x1, this only gives us the secure protocol version 0x2 here. @@ -632,9 +720,9 @@ protected SecureChannel setupSecureChannel(byte keyVersion, byte keyIndex, card_challenge = initUpdateResp.substr(CARD_CHALLENGE_OFFSET_GP211_SC03,CARD_CHALLENGE_SIZE); card_cryptogram = initUpdateResp.substr(CARD_CRYPTOGRAM_OFFSET_GP211_SC03, CARD_CRYPTOGRAM_SIZE); - // logger.debug("TPSProcessor.setupSecureChannel 03: card cryptogram: " + card_cryptogram.toHexString()); - // logger.debug("TPSProcessor.setupSecureChannel 03: card challenge: " + card_challenge.toHexString()); - // logger.debug("TPSProcessor.setupSecureChannel 03: host challenge: " + randomData.toHexString()); + logger.debug("TPSProcessor.setupSecureChannel 03: card cryptogram: " + card_cryptogram.toHexString()); + logger.debug("TPSProcessor.setupSecureChannel 03: card challenge: " + card_challenge.toHexString()); + logger.debug("TPSProcessor.setupSecureChannel 03: host challenge: " + randomData.toHexString()); } else { card_challenge = initUpdateResp.substr(CARD_CHALLENGE_OFFSET, CARD_CHALLENGE_SIZE); @@ -715,18 +803,18 @@ protected SecureChannel generateSecureChannel(String connId, TPSBuffer keyDivers boolean doesVersionMatchTokenDB = checkCardGPKeyVersionMatchesTokenDB(appletInfo.getCUIDhexStringPlain(), appletInfo.getKDDhexStringPlain(), keyInfoData.toHexStringPlain()); - if (!cuidOK) { + if(cuidOK == false) { throw new TPSException("TPSProcessor.generateSecureChannel: cuid vs kdd matching policy not met!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } - if (!isVersionInRange) { + if(isVersionInRange == false) { throw new TPSException("TPSProcessor.generateSecureChannel: key version is not within acceptable range!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } - if (!doesVersionMatchTokenDB) { + if(doesVersionMatchTokenDB == false) { throw new TPSException("TPSProcessor.generateSecureChannel: key version from token does not match that of the token db!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -754,9 +842,10 @@ protected SecureChannel generateSecureChannel(String connId, TPSBuffer keyDivers token = protocol.returnTokenByName(tokenName, cm); sharedSecret = SecureChannelProtocol.getSymKeyByName(token, sharedSecretName); + // sharedSecret = getSharedSecretTransportKey(connId); } catch (Exception e) { - logger.error("TPSProcessor: " + e.getMessage(), e); + logger.debug(e.toString()); throw new TPSException("TPSProcessor.generateSecureChannel: Can't get shared secret key!: " + e, TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -781,10 +870,10 @@ protected SecureChannel generateSecureChannel(String connId, TPSBuffer keyDivers /* sessionKey = SessionKey.UnwrapSessionKeyWithSharedSecret(tokenName, (PK11SymKey) sharedSecret, sessionKeyWrapped.toBytesArray()); */ - sessionKey = (PK11SymKey) protocol.unwrapWrappedSymKeyOnToken(token, sharedSecret, sessionKeyWrapped.toBytesArray(), false,SymmetricKey.DES3); + sessionKey = (PK11SymKey) protocol.unwrapWrappedSymKeyOnToken(token, sharedSecret, sessionKeyWrapped.toBytesArray(), false,SymmetricKey.DES3); if (sessionKey == null) { - logger.error("TPSProcessor.generateSecureChannel: Can't extract session key!"); + logger.debug("TPSProcessor.generateSecureChannel: Can't extract session key!"); throw new TPSException("TPSProcessor.generateSecureChannel: Can't extract session key!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -797,7 +886,7 @@ protected SecureChannel generateSecureChannel(String connId, TPSBuffer keyDivers encSessionKey = (PK11SymKey) protocol.unwrapWrappedSymKeyOnToken(token, sharedSecret,encSessionKeyWrapped.toBytesArray(),false,SymmetricKey.DES3); if (encSessionKey == null) { - logger.error("TPSProcessor.generateSecureChannel: Can't extract enc session key!"); + logger.debug("TPSProcessor.generateSecureChannel: Can't extract enc session key!"); throw new TPSException("TPSProcessor.generateSecureChannel: Can't extract enc session key!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -806,16 +895,15 @@ protected SecureChannel generateSecureChannel(String connId, TPSBuffer keyDivers TPSBuffer drmDesKey = null; TPSBuffer kekDesKey = null; - TPSBuffer kekAesKey = null; + TPSBuffer kekAesKey = null; TPSBuffer keyCheck = null; TPSBuffer drmAesKey = null; drmDesKey = resp.getDRM_Trans_DesKey(); keyCheck = resp.getKeyCheck(); kekDesKey = resp.getKekWrappedDesKey(); - kekAesKey = resp.getKekWrappedAesKey(); - + drmAesKey = resp.getDRM_Trans_AesKey(); //logger.debug("drmAesKey " + drmAesKey); @@ -832,13 +920,14 @@ protected SecureChannel generateSecureChannel(String connId, TPSBuffer keyDivers channel = new SecureChannel(this, sessionKey, encSessionKey, drmDesKey, kekDesKey, keyCheck, keyDiversificationData, cardChallenge, cardCryptogram, hostChallenge, hostCryptogram, keyInfoData, platProtInfo); - //logger.debug(" drm wrapped aes key: " + drmAesKey.toHexString()); - + + //logger.debug(" drm wrapped aes key: " + drmAesKey.toHexString()); channel.setDrmWrappedAesKey(drmAesKey); - channel.setKekAesKey(kekAesKey); + channel.setKekAesKey(kekAesKey); } catch (Exception e) { - logger.error("TPSProcessor: " + e.getMessage(), e); + logger.debug(e.toString()); + e.printStackTrace(); throw new TPSException("TPSProcessor.generateSecureChannel: Problem extracting session keys! " + e, TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -863,7 +952,7 @@ sequenceCounter, new TPSBuffer(SecureChannel.ENCDerivationConstant), encSessionKeyWrappedSCP02.toBytesArray()); if (encSessionKeySCP02 == null) { - logger.error("TPSProcessor.generateSecureChannel: Can't extract the SCP02 enc session key!"); + logger.debug("TPSProcessor.generateSecureChannel: Can't extract the SCP02 enc session key!"); throw new TPSException("TPSProcessor.generateSecureChannel: Can't the emc SCP02 session keys!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -878,7 +967,7 @@ sequenceCounter, new TPSBuffer(SecureChannel.C_MACDerivationConstant), connId, cmacSessionKeyWrappedSCP02.toBytesArray()); if (cmacSessionKeySCP02 == null) { - logger.error("TPSProcessor.generateSecureChannel: Can't extract the SCP02 cmac session key!"); + logger.debug("TPSProcessor.generateSecureChannel: Can't extract the SCP02 cmac session key!"); throw new TPSException("TPSProcessor.generateSecureChannel: Can't the s,ac SCP02 session keys!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -893,7 +982,7 @@ sequenceCounter, new TPSBuffer(SecureChannel.R_MACDerivationConstant), rmacSessionKeyWrappedSCP02.toBytesArray()); if (rmacSessionKeySCP02 == null) { - logger.error("TPSProcessor.generateSecureChannel: Can't extract the SCP02 cmac session key!"); + logger.debug("TPSProcessor.generateSecureChannel: Can't extract the SCP02 cmac session key!"); throw new TPSException("TPSProcessor.generateSecureChannel: Can't the cmac SCP02 session keys!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -910,7 +999,7 @@ sequenceCounter, new TPSBuffer(SecureChannel.DEKDerivationConstant), dekSessionKeyWrappedSCP02.toBytesArray()); if (dekSessionKeySCP02 == null) { - logger.error("TPSProcessor.generateSecureChannel: Can't extract the SCP02 dek session key!"); + logger.debug("TPSProcessor.generateSecureChannel: Can't extract the SCP02 dek session key!"); throw new TPSException("TPSProcessor.generateSecureChannel: Can't the dek SCP02 session keys!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } @@ -924,7 +1013,7 @@ sequenceCounter, new TPSBuffer(SecureChannel.DEKDerivationConstant), keyCheck = respDek02.getKeyCheck(); if (drmDesKey == null || kekDesKey == null) { - logger.error("TPSProcessor.generateSecureChannel: Can't get drmDesKey or kekDesKey from TKS when processing the DEK session key!"); + logger.debug("TPSProcessor.generateSecureChannel: Can't get drmDesKey or kekDesKey from TKS when processing the DEK session key!"); throw new TPSException( "TPSProcessor.generateSecureChannel: Can't get drmDesKey or kekDesKey from TKS when processing the DEK session key!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); @@ -950,34 +1039,38 @@ sequenceCounter, new TPSBuffer(SecureChannel.DEKDerivationConstant), TPSBuffer macSessionKeyBuff = resp.getMacSessionKey(); TPSBuffer hostCryptogramBuff = resp.getHostCryptogram(); TPSBuffer keyCheckBuff = resp.getKeyCheck(); + // Applet and Alg Selection by Token Range Support + if (isDesConfigured()) { + logger.debug(method + " Getting keyCheckDes."); + keyCheckBuff = resp.getKeyCheckDes(); + } TPSBuffer drmDesKeyBuff = resp.getDRM_Trans_DesKey(); TPSBuffer kekDesKeyBuff = resp.getKekWrappedDesKey(); - TPSBuffer kekAesKeyBuff = resp.getKekWrappedAesKey(); + TPSBuffer kekAesKeyBuff = resp.getKekWrappedAesKey(); TPSBuffer drmAesKeyBuff = resp.getDRM_Trans_AesKey(); - /* - if (encSessionKeyBuff != null) - logger.debug(method + " encSessionKeyBuff: " + encSessionKeyBuff.toHexString()); + //if (encSessionKeyBuff != null) + // logger.debug(method + " encSessionKeyBuff: " + encSessionKeyBuff.toHexString()); - if (kekSessionKeyBuff != null) - logger.debug(method + " kekSessionKeyBuff: " + kekSessionKeyBuff.toHexString()); + //if (kekSessionKeyBuff != null) + // logger.debug(method + " kekSessionKeyBuff: " + kekSessionKeyBuff.toHexString()); - if (macSessionKeyBuff != null) - logger.debug(method + " macSessionKeyBuff: " + macSessionKeyBuff.toHexString()); + //if (macSessionKeyBuff != null) + // logger.debug(method + " macSessionKeyBuff: " + macSessionKeyBuff.toHexString()); - if (hostCryptogramBuff != null) - logger.debug(method + " hostCryptogramBuff: " + hostCryptogramBuff.toHexString()); + //if (hostCryptogramBuff != null) + /// logger.debug(method + " hostCryptogramBuff: " + hostCryptogramBuff.toHexString()); if (keyCheckBuff != null) logger.debug(method + " keyCheckBuff: " + keyCheckBuff.toHexString()); - if (drmDesKeyBuff != null) - logger.debug(method + " drmDessKeyBuff: " + drmDesKeyBuff.toHexString()); + //if (drmDesKeyBuff != null) + // logger.debug(method + " drmDessKeyBuff: " + drmDesKeyBuff.toHexString()); + + //if (kekDesKeyBuff != null) + // logger.debug(method + " kekDesKeyBuff: " + kekDesKeyBuff.toHexString()); - if (kekDesKeyBuff != null) - logger.debug(method + " kekDesKeyBuff: " + kekDesKeyBuff.toHexString()); - */ if (encSessionKeyBuff != null) encSessionKeySCP03 = (PK11SymKey) protocol.unwrapWrappedSymKeyOnToken(token, sharedSecret, @@ -991,9 +1084,9 @@ sequenceCounter, new TPSBuffer(SecureChannel.DEKDerivationConstant), kekSessionKeySCP03 = (PK11SymKey) protocol.unwrapWrappedSymKeyOnToken(token, sharedSecret, kekSessionKeyBuff.toBytesArray(), false, SymmetricKey.AES); - // logger.debug(" encSessionKeySCP03 " + encSessionKeySCP03); - // logger.debug(" macSessionKeySCP03 " + macSessionKeySCP03); - // logger.debug(" kekSessionKeySCP03 " + kekSessionKeySCP03); + //logger.debug(" encSessionKeySCP03 " + encSessionKeySCP03.getEncoded()); + //logger.debug(" macSessionKeySCP03 " + macSessionKeySCP03.getEncoded()); + //logger.debug(" kekSessionKeySCP03 " + kekSessionKeySCP03.getEncoded()); channel = new SecureChannel(this, encSessionKeySCP03, macSessionKeySCP03, kekSessionKeySCP03, drmDesKeyBuff, kekDesKeyBuff, @@ -1001,10 +1094,8 @@ sequenceCounter, new TPSBuffer(SecureChannel.DEKDerivationConstant), cardCryptogram, hostChallenge, hostCryptogramBuff, keyInfoData, platProtInfo); - if(channel != null) { - channel.setDrmWrappedAesKey(drmAesKeyBuff); - channel.setKekAesKey(kekAesKeyBuff); - } + channel.setDrmWrappedAesKey(drmAesKeyBuff); + channel.setKekAesKey(kekAesKeyBuff); } if (channel == null) { @@ -1074,10 +1165,17 @@ protected int checkAndUpgradeApplet(AppletInfo appletInfo) throws TPSException, if (upgraded == 0) { logger.debug("TPSProcessor.checkAndUpgradeApplet: applet already at correct version or upgrade disabled."); - // We didn't need to upgrade the applet but create new channel for now. - selectCardManager(); - setupSecureChannel(appletInfo); + TPSBuffer selectedCardMgr = getSelectedCardMgr(); + if (selectedCardMgr == null || selectedCardMgr.size() == 0) + { + selectDefaultCardManager(); + } + + appletInfo.setAid(getSelectedCardMgr()); + logger.debug("TPSProcessor.checkAndUpgradeApplet: Selected Card Mgr from session: " + appletInfo.getAid()); + + setupSecureChannel(appletInfo); } return upgraded; @@ -1088,12 +1186,10 @@ protected void upgradeApplet(AppletInfo appletInfo, String operation, String new TPSException { TPSBuffer netkeyAIDBuff = null; - TPSBuffer cardMgrAIDBuff = null; TPSBuffer netkeyPAIDBuff = null; netkeyAIDBuff = getNetkeyAID(); netkeyPAIDBuff = getNetkeyPAID(); - cardMgrAIDBuff = getCardManagerAID(); int channelBlockSize = getChannelBlockSize(); int channelInstanceSize = getChannelInstanceSize(); @@ -1113,19 +1209,22 @@ protected void upgradeApplet(AppletInfo appletInfo, String operation, String new String appletFilePath = directory + "/" + new_version + "." + appletFileExt; - logger.debug("TPSProcessor.upgradeApplet: targe applet file name: " + appletFilePath); + logger.debug("TPSProcessor.upgradeApplet: target applet file name: " + appletFilePath); appletData = getAppletFileData(appletFilePath); - APDUResponse select = selectApplet((byte) 0x04, (byte) 0x00, cardMgrAIDBuff); - if (!select.checkResult()) { - String logMsg = "Can't selelect the card manager!"; - auditAppletUpgrade(appletInfo, "failure", null /*unavailable*/, new_version, logMsg); - throw new TPSException("TPSProcessor.upgradeApplet:" + logMsg, - TPSStatus.STATUS_ERROR_UPGRADE_APPLET); + // Get card mgr from session or select default + TPSBuffer selectedCardMgr = getSelectedCardMgr(); + + if (selectedCardMgr == null || selectedCardMgr.size() == 0) + { + selectDefaultCardManager(); } + appletInfo.setAid(getSelectedCardMgr()); + logger.debug("TPSProcessor.upgradeApplet: After session.getSelectedCardMgr(), appletInfo.getAid() = " + appletInfo.getAid().toHexStringPlain()); + SecureChannel channel = setupSecureChannel((byte) defKeyVersion, (byte) defKeyIndex, connId, appletInfo); channel.externalAuthenticate(); @@ -1135,7 +1234,7 @@ protected void upgradeApplet(AppletInfo appletInfo, String operation, String new // Next step will be to load the applet file to token. - channel.installLoad(netkeyPAIDBuff, cardMgrAIDBuff, appletData.length); + channel.installLoad(netkeyPAIDBuff, appletInfo.getAid(), appletData.length); TPSBuffer appletDataBuff = new TPSBuffer(appletData); @@ -1145,7 +1244,7 @@ protected void upgradeApplet(AppletInfo appletInfo, String operation, String new //Now select our new applet - select = selectApplet((byte) 0x04, (byte) 0x00, netkeyAIDBuff); + APDUResponse select = selectApplet((byte) 0x04, (byte) 0x00, netkeyAIDBuff); if (!select.checkResult()) { String logMsg = "Cannot select newly created applet!"; @@ -1187,10 +1286,10 @@ protected byte[] getAppletFileData(String appletFilePath) throws IOException, TP contents = Files.readAllBytes(path); } catch (IOException e) { - logger.error("TPSProcessor.getAppletFileData: IOException " + e.getMessage(), e); + logger.debug("TPSProcessor.getAppletFileData: IOException " + e); throw e; } catch (Exception e) { - logger.error("PSProcessor.getAppletFileData: Exception: " + e.getMessage(), e); + logger.debug("PSProcessor.getAppletFileData: Exception: " + e); throw new TPSException("TPSProcessor.getAppletFileData: Exception: " + e, TPSStatus.STATUS_ERROR_UPGRADE_APPLET); } @@ -1214,19 +1313,21 @@ public TPSAuthenticator getAuthentication(String prefix, String tokenType) if (prefix.isEmpty() || tokenType.isEmpty()) { logMsg = "TPSProcessor.getAuthentication: missing parameters: prefix or tokenType"; - logger.error(logMsg); + logger.debug(logMsg); throw new EBaseException(logMsg); } TPSEngine engine = TPSEngine.getInstance(); TPSEngineConfig configStore = engine.getConfig(); + String configName = prefix + "." + tokenType + ".auth.id"; String authId; - logger.debug("TPSProcessor.getAuthentication: getting config: " + configName); + logger.debug("TPSProcessor.getAuthentication: getting config: " + + configName); authId = configStore.getString(configName); if (authId == null) { logMsg = "TPSProcessor.getAuthentication: config param not found:" + configName; - logger.error(logMsg); + logger.debug(logMsg); throw new EBaseException(logMsg); } return getAuthentication(authId); @@ -1239,35 +1340,32 @@ public TPSAuthenticator getAuthentication(String authId) if (authId.isEmpty()) { logMsg = "TPSProcessor.getAuthentication: missing parameters: authId"; - logger.error(logMsg); + logger.debug(logMsg); throw new EBaseException(logMsg); } - TPSEngine engine = TPSEngine.getInstance(); TPSEngineConfig configStore = engine.getConfig(); - AuthenticationConfig authConfig = configStore.getAuthenticationConfig(); - AuthManagersConfig instancesConfig = authConfig.getAuthManagersConfig(); + TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); TPSAuthenticator authInst = subsystem.getAuthenticationManager().getAuthInstance(authId); - - String authCredNameConf = authId + ".authCredName"; - logger.debug("TPSProcessor.getAuthentication: getting config: auths.instance." + authCredNameConf); - String authCredName = instancesConfig.getString(authCredNameConf); - + String authCredNameConf = "auths.instance." + authId + ".authCredName"; + logger.debug("TPSProcessor.getAuthentication: getting config: " + + authCredNameConf); + String authCredName = configStore.getString(authCredNameConf); if (authCredName == null) { - logMsg = "TPSProcessor.getAuthentication: config param not found: auths.instance." + authCredNameConf; - logger.error(logMsg); + logMsg = "TPSProcessor.getAuthentication: config param not found:" + authCredNameConf; + logger.debug(logMsg); throw new EBaseException(logMsg); } authInst.setAuthCredName(authCredName); // set ldapStringAttrs for later processing - String authLdapStringAttrs = authId + ".ldapStringAttributes"; - logger.debug("TPSProcessor.getAuthentication: getting config: auths.instance." + authLdapStringAttrs); - String authLdapStringAttributes = instancesConfig.getString(authLdapStringAttrs, ""); - + String authLdapStringAttrs = "auths.instance." + authId + ".ldapStringAttributes"; + logger.debug("TPSProcessor.getAuthentication: getting config: " + + authLdapStringAttrs); + String authLdapStringAttributes = configStore.getString(authLdapStringAttrs, ""); if (authLdapStringAttributes != null && !authLdapStringAttributes.equals("")) { logMsg = "TPSProcessor.getAuthentication: got ldapStringAttributes... setting up"; logger.debug(logMsg); @@ -1309,7 +1407,7 @@ else if (op.equals(TPSEngine.ENROLL_OP)) * * @param op "enrollment", "format", or "pinReset" //TODO: for tokendb activity log * @param userAuth the authenticator - * @param userCred IAuthCredentials obtained from a successful requestUserId call + * @param userCred AuthCredentials obtained from a successful requestUserId call * @return AuthToken information relating to the performed authentication * -- plugin-specific */ @@ -1322,7 +1420,7 @@ public AuthToken authenticateUser( String logMsg = null; if (op.isEmpty() || userAuth == null || userCred == null) { logMsg = "TPSProcessor.authenticateUser: missing parameter(s): op, userAuth, or userCred"; - logger.error(logMsg); + logger.debug(logMsg); throw new EBaseException(logMsg); } logger.debug("TPSProcessor.authenticateUser: op: " + op); @@ -1331,26 +1429,27 @@ public AuthToken authenticateUser( try { // Authenticate user authToken = auth.authenticate(userCred); - if (authToken == null) { - logger.error("TPSProcessor.authenticateUser: authentication failure with authToken null"); + if (authToken != null) { + logger.debug("TPSProcessor.authenticateUser: authentication success"); + Enumeration n = authToken.getElements(); + while (n.hasMoreElements()) { + String name = n.nextElement(); + logger.debug("TPSProcessor.authenticateUser: got authToken val name:" + name); + /* debugging authToken content vals + String[] vals = authToken.getInStringArray(name); + if (vals != null) { + logger.debug("TPSProcessor.authenticateUser: got authToken val :" + vals[0]); + } + */ + } + return authToken; + } else { + logger.debug("TPSProcessor.authenticateUser: authentication failure with authToken null"); throw new TPSException("TPS error user authentication failed.", TPSStatus.STATUS_ERROR_LOGIN); } - logger.debug("TPSProcessor.authenticateUser: authentication success"); - Enumeration n = authToken.getElements(); - while (n.hasMoreElements()) { - String name = n.nextElement(); - logger.debug("TPSProcessor.authenticateUser: got authToken val name:" + name); - /* debugging authToken content vals - String[] vals = authToken.getInStringArray(name); - if (vals != null) { - logger.debug("TPSProcessor.authenticateUser: got authToken val :" + vals[0]); - } - */ - } - return authToken; } catch (EBaseException e) { - logger.error("TPSProcessor.authenticateUser: authentication failure: " + e, e); + logger.debug("TPSProcessor.authenticateUser: authentication failure:" + e); throw new TPSException("TPS error user authentication failed.", TPSStatus.STATUS_ERROR_LOGIN); } @@ -1363,14 +1462,14 @@ public AuthToken authenticateUser( * @param op "enrollment", "format", or "pinReset" //TODO: for tokendb activity log * @param cuid token CUID //TODO: for tokendb activity log * @param extensions message extensions - * @return IAuthCredentials containing user credential needed for authentication + * @return AuthCredentials containing user credential needed for authentication */ AuthCredentials requestUserId(String op, String cuid, TPSAuthenticator auth, Map extensions) throws IOException, TPSException, EBaseException { logger.debug("TPSProcessor.requestUserId"); if (op.isEmpty() || cuid.isEmpty() || auth == null) { - logger.error("TPSProcessor.requestUserId: missing parameter(s): op, cuid, or auth"); + logger.debug("TPSProcessor.requestUserId: missing parameter(s): op, cuid, or auth"); throw new EBaseException("TPSProcessor.requestUserId: missing parameter(s): op, cuid, or auth"); } @@ -1392,7 +1491,7 @@ AuthCredentials requestUserId(String op, String cuid, TPSAuthenticator auth, Map description = auth.getUiTitle("en"); // parameters HashMap authParamSet = auth.getUiParamSet(); - Set params = new HashSet<>(); + Set params = new HashSet(); for (Map.Entry entry : authParamSet.entrySet()) { params.add(auth.getUiParam(entry.getKey()).toString(locale)); logger.debug("TPSProcessor.requestUserId: for extendedLoginRequest, added param: " + @@ -1423,23 +1522,23 @@ AuthCredentials requestUserId(String op, String cuid, TPSAuthenticator auth, Map * * @param response the message response to be mapped * @param auth the authentication for mapping consultation - * @return IAuthCredentials auth credential for auth manager + * @return AuthCredentials auth credential for auth manager */ public AuthCredentials mapCredFromMsgResponse(TPSMessage response, TPSAuthenticator auth, boolean extendedLogin) throws EBaseException { logger.debug("TPSProcessor.mapCredFromMsgResponse"); if (response == null || auth == null) { - logger.error("TPSProcessor.mapCredFromMsgResponse: missing parameter(s): response or auth"); + logger.debug("TPSProcessor.mapCredFromMsgResponse: missing parameter(s): response or auth"); throw new EBaseException("TPSProcessor.mapCredFromMsgResponse: missing parameter(s): response or auth"); } AuthCredentials login = new com.netscape.certsrv.authentication.AuthCredentials(); - AuthManager authManager = auth.getAuthManager(); - String[] requiredCreds = authManager.getRequiredCreds(); + String[] requiredCreds = auth.getAuthManager().getRequiredCreds(); for (String cred : requiredCreds) { String name = auth.getCredMap(cred, extendedLogin); - logger.debug("TPSProcessor.mapCredFromMsgResponse: cred=" + cred + " &name=" + name); + logger.debug("TPSProcessor.mapCredFromMsgResponse: cred=" + cred + " &name=" + + name); login.set(cred, response.get(name)); } @@ -1459,7 +1558,7 @@ public AuthCredentials requestExtendedLogin(int invalidPW, int blocked, logger.debug("TPSProcessor.requestExtendedLogin"); if (parameters == null || title.isEmpty() || description.isEmpty() || auth == null) { - logger.error("TPSProcessor.requestExtendedLogin: missing parameter(s): parameters, title, description, or auth"); + logger.debug("TPSProcessor.requestExtendedLogin: missing parameter(s): parameters, title, description, or auth"); throw new EBaseException( "TPSProcessor.requestExtendedLogin: missing parameter(s): parameters, title, description, or auth"); } @@ -1469,7 +1568,7 @@ public AuthCredentials requestExtendedLogin(int invalidPW, int blocked, try { session.write(loginReq); } catch (IOException e) { - logger.error("TPSProcessor.requestExtendedLogin failed WriteMsg: " + e.getMessage(), e); + logger.debug("TPSProcessor.requestExtendedLogin failed WriteMsg: " + e.toString()); throw e; } logger.debug("TPSProcessor.requestExtendedLogin: extendedLoginRequest sent"); @@ -1478,7 +1577,7 @@ public AuthCredentials requestExtendedLogin(int invalidPW, int blocked, try { loginResp = (ExtendedLoginResponseMsg) session.read(); } catch (IOException e) { - logger.error("TPSProcessor.requestExtendedLogin failed ReadMsg: " + e.getMessage(), e); + logger.debug("TPSProcessor.requestExtendedLogin failed ReadMsg: " + e.toString()); throw e; } @@ -1496,7 +1595,7 @@ public AuthCredentials requestLogin(int invalidPW, int blocked, logger.debug("TPSProcessor.requestLogin"); if (auth == null) { - logger.error("TPSProcessor.requestLogin: missing parameter(s): parameters, title, description, or auth"); + logger.debug("TPSProcessor.requestLogin: missing parameter(s): parameters, title, description, or auth"); throw new EBaseException( "TPSProcessor.requestLogin: missing parameter(s): parameters, title, description, or auth"); } @@ -1505,7 +1604,7 @@ public AuthCredentials requestLogin(int invalidPW, int blocked, try { session.write(loginReq); } catch (IOException e) { - logger.error("TPSProcessor.requestLogin failed WriteMsg: " + e.getMessage(), e); + logger.debug("TPSProcessor.requestLogin failed WriteMsg: " + e.toString()); throw e; } logger.debug("TPSProcessor.requestLogin: loginRequest sent"); @@ -1514,7 +1613,7 @@ public AuthCredentials requestLogin(int invalidPW, int blocked, try { loginResp = (LoginResponseMsg) session.read(); } catch (IOException e) { - logger.error("TPSProcessor.requestLogin failed ReadMsg: " + e.getMessage(), e); + logger.debug("TPSProcessor.requestLogin failed ReadMsg: " + e.toString()); throw e; } @@ -1533,7 +1632,7 @@ protected void fillTokenRecord(TokenRecord tokenRecord, AppletInfo appletInfo) String method = "TPSProcessor.fillTokenRecord"; logger.debug(method + ": begins"); if (tokenRecord == null || appletInfo == null) { - logger.error(method + ": params tokenRecord and appletInfo cannot be null"); + logger.debug(method + ": params tokenRecord and appletInfo cannot be null"); throw new TPSException( method + ": missing parameter(s): parameter appletInfo"); } @@ -1544,7 +1643,7 @@ protected void fillTokenRecord(TokenRecord tokenRecord, AppletInfo appletInfo) try { build_id = getAppletVersion(); } catch (IOException e) { - logger.warn(method + ": failed getting applet version:" + e.getMessage(), e); + logger.debug(method + ": failed getting applet version:" + e + " ... continue"); } if (build_id != null) { tokenRecord.setAppletID(Integer.toHexString(app_major_version) + "." @@ -1559,20 +1658,20 @@ protected void fillTokenRecord(TokenRecord tokenRecord, AppletInfo appletInfo) protected void fillTokenRecordDefaultPolicy(TokenRecord tokenRecord) throws TPSException { String method = "TPSProcessor.fillTokenRecordDefaultPolicy: "; - + try { TPSEngine engine = TPSEngine.getInstance(); TPSEngineConfig configStore = engine.getConfig(); - TokenDBConfig tdbConfig = configStore.getTokenDBConfig(); - String defaultPolicy = tdbConfig.getString("defaultPolicy"); + String config = "tokendb.defaultPolicy"; + String defaultPolicy = configStore.getString(config); - logger.debug("{} default token policy: {}", method, defaultPolicy); + logger.debug(method + " default token policy: " + defaultPolicy); tokenRecord.setPolicy(defaultPolicy); } catch (Exception e) { - logger.debug("{}Problem with adding the default policy to the token.", method); - throw new TPSException(e.toString(), TPSStatus.STATUS_ERROR_MISCONFIGURATION); + logger.debug(method + "Problem with adding the default policy to the token."); + throw new TPSException(e.toString(),TPSStatus.STATUS_ERROR_MISCONFIGURATION); } } @@ -1592,12 +1691,8 @@ protected TokenRecord isTokenRecordPresent(AppletInfo appletInfo) throws TPSExce tokenRecord = tps.tdb.tdbGetTokenEntry(appletInfo.getCUIDhexStringPlain()); // now the in memory tokenRecord is replaced by the actual token data logger.debug("TPSProcessor.isTokenRecordPresent: found token..."); - - } catch (DBRecordNotFoundException e) { - logger.debug("TPSProcessor.isTokenRecordPresent: Token " + appletInfo.getCUIDhexStringPlain() + " not found, creating token in memory"); - } catch (Exception e) { - logger.warn("TPSProcessor.isTokenRecordPresent: Unable to find token " + appletInfo.getCUIDhexStringPlain() + ": " + e.getMessage(), e); + logger.debug("TPSProcessor.isTokenRecordPresent: token does not exist in tokendb... create one in memory"); } return tokenRecord; @@ -1613,8 +1708,8 @@ protected String getCAConnectorID() throws TPSException { */ protected String getCAConnectorID(String enrollType, String keyType) throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + + TPSEngineConfig configStore = this.getConfigStore(); String id = null; String config = null; String method = "TPSProcessor.getCAConnectorID:"; @@ -1654,8 +1749,7 @@ protected boolean revokeCertsAtFormat() { String logMsg; logger.debug(method + ": begins"); - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String configName = TPSEngine.OP_FORMAT_PREFIX + "." + selectedTokenType + ".revokeCert"; boolean revokeCert = false; try { @@ -1663,8 +1757,8 @@ protected boolean revokeCertsAtFormat() { revokeCert = configStore.getBoolean(configName, false); } catch (EBaseException e) { logMsg = method + ": config not found: " + configName + - "; default to false: " + e.getMessage(); - logger.warn(logMsg, e); + "; default to false"; + logger.debug(logMsg); } if (!revokeCert) { logMsg = method + ": revokeCert = false"; @@ -1677,19 +1771,18 @@ protected RevocationReason getRevocationReasonAtFormat() { String method = "getRevocationReasonAtFormat"; String logMsg; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String configName = TPSEngine.OP_FORMAT_PREFIX + "." + selectedTokenType + ".revokeCert.reason"; logger.debug(method + " finding config: " + configName); RevocationReason revokeReason = RevocationReason.UNSPECIFIED; try { int revokeReasonInt = configStore.getInteger(configName); - revokeReason = RevocationReason.valueOf(revokeReasonInt); + revokeReason = RevocationReason.fromInt(revokeReasonInt); } catch (EBaseException e) { logMsg = method + ": config not found: " + configName + - "; default to unspecified: " + e.getMessage(); - logger.warn(logMsg, e); + "; default to unspecified"; + logger.debug(logMsg); revokeReason = RevocationReason.UNSPECIFIED; } @@ -1709,17 +1802,16 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St if (cuid == null) { logMsg = "cuid null"; - logger.error(method + ":" + logMsg); + logger.debug(method + ":" + logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_REVOKE_CERTIFICATES_FAILED); } logger.debug(method + ": begins for cuid:" + cuid); - TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); boolean isTokenPresent = tps.tdb.isTokenPresent(cuid); if (!isTokenPresent) { logMsg = method + ": token not found: " + cuid; - logger.error(logMsg); + logger.debug(logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_REVOKE_CERTIFICATES_FAILED); } @@ -1727,8 +1819,8 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St try { caRH = new CARemoteRequestHandler(caConnId); } catch (EBaseException e) { - logMsg = method + ": getting CARemoteRequestHandler failure: " + e.getMessage(); - logger.error(logMsg, e); + logMsg = method + ": getting CARemoteRequestHandler failure"; + logger.debug(logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_REVOKE_CERTIFICATES_FAILED); } //find all certs belonging to the token @@ -1744,8 +1836,8 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St try { tps.certDatabase.removeRecord(cert.getId()); } catch (Exception e) { - logMsg = method + ": removeRecord failed: " + e.getMessage(); - logger.error(logMsg, e); + logMsg = method + ": removeRecord failed"; + logger.debug(logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_REVOKE_CERTIFICATES_FAILED); } continue; @@ -1767,8 +1859,8 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St try { tps.certDatabase.removeRecord(cert.getId()); } catch (Exception e) { - logMsg = method + ": removeRecord failed: " + e.getMessage(); - logger.error(logMsg, e); + logMsg = method + ": removeRecord failed"; + logger.debug(logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_REVOKE_CERTIFICATES_FAILED); } continue; @@ -1789,8 +1881,8 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St try { tps.certDatabase.removeRecord(cert.getId()); } catch (Exception e) { - logMsg = method + ": removeRecord failed: " + e.getMessage(); - logger.error(logMsg, e); + logMsg = method + ": removeRecord failed"; + logger.debug(logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_REVOKE_CERTIFICATES_FAILED); } continue; @@ -1810,8 +1902,8 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St auditRevoke(cuid, true, revokeReason.getCode(), String.valueOf(response.getStatus()), serialStr, caConnId, null); } catch (EBaseException e) { - logMsg = method + ": revokeCertificate from CA failed: " + e.getMessage(); - logger.error(logMsg, e); + logMsg = method + ": revokeCertificate from CA failed:" + e; + logger.debug(logMsg); auditRevoke(cuid, true, revokeReason.getCode(), "failure", serialStr, caConnId, null); if (revokeReason == RevocationReason.CERTIFICATE_HOLD) { @@ -1827,7 +1919,7 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St } } else { logMsg = "mulformed hex serial number :" + hexSerial; - logger.error(method + ": " + logMsg); + logger.debug(method + ": " + logMsg); tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, session.getTokenRecord(), session.getIpAddress(), logMsg, "failure"); @@ -1843,8 +1935,8 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St try { tps.certDatabase.removeRecord(cert.getId()); } catch (Exception e) { - logMsg = "removeRecord failed: " + e.getMessage(); - logger.error(method + ": " + logMsg, e); + logMsg = "removeRecord failed:" + e; + logger.debug(method + ": " + logMsg); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_UPDATE_TOKENDB_FAILED); } continue; @@ -1863,8 +1955,7 @@ protected void revokeCertificates(String cuid, RevocationReason revokeReason, St public boolean allowRecoverInvalidCert() throws TPSException { String method = "TPSProcessor.allowRecoverInvalidCert:"; boolean ret = true; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String configName = "externalReg.allowRecoverInvalidCert.enable"; try { ret = configStore.getBoolean(configName, true); @@ -1902,8 +1993,7 @@ ExternalRegAttrs processExternalRegAttrs(/*AuthToken authToken,*/String authId) String tVal; String[] vals; ExternalRegAttrs erAttrs = new ExternalRegAttrs(authId); - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String attributesToProcessStr = configStore.getString( "auths.instance." + authId + @@ -1916,21 +2006,21 @@ ExternalRegAttrs processExternalRegAttrs(/*AuthToken authToken,*/String authId) return erAttrs; if(listCaseInsensitiveContains(erAttrs.ldapAttrNameTokenType, attributesToProcess)) { - logger.debug(method + ": getting from authToken: " + erAttrs.ldapAttrNameTokenType); + logger.debug(method + ": getting from authToken:" + + erAttrs.ldapAttrNameTokenType); vals = authToken.getInStringArray(erAttrs.ldapAttrNameTokenType); if (vals == null) { // get the default externalReg tokenType configName = "externalReg.default.tokenType"; tVal = configStore.getString(configName, "externalRegAddToToken"); - logger.debug(method + ": set default tokenType: " + tVal); + logger.debug(method + ": set default tokenType:" + tVal); erAttrs.setTokenType(tVal); } else { - logger.debug(method + ": retrieved tokenType: " + vals[0]); + logger.debug(method + ": retrieved tokenType:" + vals[0]); erAttrs.setTokenType(vals[0]); } } - if(listCaseInsensitiveContains(erAttrs.ldapAttrNameTokenCUID, attributesToProcess)) { logger.debug(method + ": getting from authToken:" + erAttrs.ldapAttrNameTokenCUID); @@ -1955,6 +2045,7 @@ ExternalRegAttrs processExternalRegAttrs(/*AuthToken authToken,*/String authId) logger.debug(method + ": registrationType attribute not found."); erAttrs.setRegistrationType(null); } + } if(listCaseInsensitiveContains(erAttrs.ldapAttrNameCertsToRecover, attributesToProcess)) { @@ -1967,7 +2058,7 @@ ExternalRegAttrs processExternalRegAttrs(/*AuthToken authToken,*/String authId) vals = authToken.getInStringArray(erAttrs.ldapAttrNameCertsToRecover); if (vals != null) { // A temporary list to hold retainable certs. - ArrayList retainableCerts = new ArrayList<>(); + ArrayList retainableCerts = new ArrayList(); // if any cert is mis-configured, the whole thing will bail for (String val : vals) { @@ -2009,12 +2100,10 @@ else if (i == 2) { } } - /** - * Add the retainable certs after the other certs. Because "un-retainable" - * (e.g. revoked encryption certs or active encryption certs from previous - * registrations) are processed before retainable certs, "un-retainable" certs - * must all come first in the list. - */ + // Add the retainable certs after the other certs. Because "un-retainable" + // (e.g. revoked encryption certs or active encryption certs from previous + // registrations) are processed before retainable certs, "un-retainable" certs + // must all come first in the list. if(!retainableCerts.isEmpty()) erAttrs.getCertsToRecover().addAll(retainableCerts); } else { @@ -2067,8 +2156,8 @@ else if (i == 2) { protected void setExternalRegSelectedTokenType(ExternalRegAttrs erAttrs) throws TPSException { String method = "TPSProcessor.setExternalRegSelectedTokenType: "; + TPSEngineConfig configStore = this.getConfigStore(); TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); logger.debug(method + " begins"); @@ -2080,10 +2169,12 @@ protected void setExternalRegSelectedTokenType(ExternalRegAttrs erAttrs) try { String tokenType = configStore.getString(configName, "externalRegAddToToken"); - logger.debug(method + " setting tokenType to default: " + tokenType); + logger.debug(method + " setting tokenType to default:" + + tokenType); setSelectedTokenType(tokenType); } catch (EBaseException e) { - logger.debug(method + " Internal Error obtaining mandatory config values: " + e.getMessage(), e); + logger.debug(method + " Internal Error obtaining mandatory config values. Error: " + + e); String logMsg = "TPS error getting config values from config store." + e.toString(); tps.tdb.tdbActivity(currentTokenOperation, session.getTokenRecord(), session.getIpAddress(), logMsg, "failure"); @@ -2091,22 +2182,25 @@ protected void setExternalRegSelectedTokenType(ExternalRegAttrs erAttrs) throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_MISCONFIGURATION); } } else { - logger.debug(method + " setting tokenType to tokenType attribute of user entry: " + erAttrs.getTokenType()); + logger.debug(method + " setting tokenType to tokenType attribute of user entry:" + + + erAttrs.getTokenType()); setSelectedTokenType(erAttrs.getTokenType()); } } protected void format(boolean skipAuth) throws TPSException, IOException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String configName = null; String logMsg = null; String appletVersion = null; logger.debug("TPSProcessor.format begins"); + TPSEngine engine = TPSEngine.getInstance(); +logger.debug("engine: " + engine); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); - +logger.debug("tps: " + tps); AppletInfo appletInfo = null; TokenRecord tokenRecord = null; try { @@ -2122,20 +2216,18 @@ protected void format(boolean skipAuth) throws TPSException, IOException { throw e; } - appletInfo.setAid(getCardManagerAID()); - logger.debug("TPSProcessor.format: token cuid: " + appletInfo.getCUIDhexStringPlain()); boolean isTokenPresent = false; tokenRecord = isTokenRecordPresent(appletInfo); - if (tokenRecord == null) { + if (tokenRecord != null) { + logger.debug("TPSProcessor.format: found token..."); + isTokenPresent = true; + } else { logger.debug("TPSProcessor.format: token does not exist in tokendb... create one in memory"); tokenRecord = new TokenRecord(); tokenRecord.setId(appletInfo.getCUIDhexStringPlain()); - } else { - logger.debug("TPSProcessor.format: found token..."); - isTokenPresent = true; } fillTokenRecord(tokenRecord, appletInfo); @@ -2152,7 +2244,8 @@ protected void format(boolean skipAuth) throws TPSException, IOException { byte app_minor_version = appletInfo.getAppMinorVersion(); logger.debug("TPSProcessor.format: major_version " + major_version + " minor_version: " + minor_version - + " app_major_version: " + app_major_version + " app_minor_version: " + app_minor_version); + + " app_major_version: " + app_major_version + " app_minor_version: " + app_minor_version + + " cardMgrAID: " + appletInfo.getAid().toHexStringPlain()); String tokenType = "tokenType"; @@ -2180,7 +2273,7 @@ need to reach out to the Registration DB (authid) try { requireLoginRequest = configStore.getBoolean(configName, false); } catch (EBaseException e) { - logger.error("TPSProcessor.format: Internal Error obtaining mandatory config values: " + e.getMessage(), e); + logger.debug("TPSProcessor.format: Internal Error obtaining mandatory config values. Error: " + e); logMsg = "TPS error getting config values from config store." + e.toString(); tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, "failure"); @@ -2196,7 +2289,7 @@ need to reach out to the Registration DB (authid) "externalRegAddToToken"); setSelectedTokenType(tokenType); } catch (EBaseException e) { - logger.error("TPSProcessor.format: Internal Error obtaining mandatory config values: " + e.getMessage(), e); + logger.debug("TPSProcessor.format: Internal Error obtaining mandatory config values. Error: " + e); logMsg = "TPS error getting config values from config store." + e.toString(); tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, "failure"); @@ -2213,7 +2306,7 @@ need to reach out to the Registration DB (authid) try { authId = configStore.getString(configName); } catch (EBaseException e) { - logger.error("TPSProcessor.format: Internal Error obtaining mandatory config values: " + e.getMessage(), e); + logger.debug("TPSProcessor.format: Internal Error obtaining mandatory config values. Error: " + e); logMsg = "TPS error getting config values from config store." + e.toString(); tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, "failure"); @@ -2232,7 +2325,7 @@ need to reach out to the Registration DB (authid) auditAuthFailure(userid, currentTokenOperation, appletInfo, (userAuth != null) ? userAuth.getID() : null); - logger.error("TPSProcessor.format:: authentication exception thrown: " + e.getMessage(), e); + logger.debug("TPSProcessor.format:: authentication exception thrown: " + e); logMsg = "authentication failed, status = STATUS_ERROR_LOGIN"; tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, @@ -2259,10 +2352,10 @@ need to reach out to the Registration DB (authid) for (ExternalRegCertToRecover erCert : erCertsToRecover) { BigInteger serial = erCert.getSerial(); - logger.debug("In TPSProcessor.format: " + "serial: " + serial); + logger.debug("In TPSProcessor.format: " + "serial: " + serial.toString()); BigInteger keyid = erCert.getKeyid(); if (keyid != null) - logger.debug("In TPSProcessor.format: " + "keyid: " + keyid); + logger.debug("In TPSProcessor.format: " + "keyid: " + keyid.toString()); else logger.debug("In TPSProcessor.format: " + "no keyid"); } @@ -2283,12 +2376,37 @@ need to reach out to the Registration DB (authid) FilterMappingParams mappingParams = createFilterMappingParams(resolverInstName, appletInfo.getCUIDhexStringPlain(), appletInfo.getMSNString(), appletInfo.getMajorVersion(), appletInfo.getMinorVersion()); + TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); BaseMappingResolver resolverInst = subsystem.getMappingResolverManager().getResolverInstance(resolverInstName); - String keySet = resolverInst.getResolvedMapping(mappingParams, "keySet"); + + // ** G&D 256 Key Rollover Support ** + // Get the key size on card and pass it in to getResolvedMapping + Integer symKeySize = getCardSymKeyLength(appletInfo.getCUIDhexStringPlain()); + logger.debug("TPSProcessor.format: symKeySize on card: " + symKeySize); + + String keySet = resolverInst.getResolvedMapping(mappingParams, "keySet", symKeySize); setSelectedKeySet(keySet); logger.debug("In TPSProcessor.format: resolved keySet: " + keySet); + + // ** Applet and Alg Selection by Token Range Support begin ** + try { + String keyWrapAlg = resolverInst.getResolvedMapping(mappingParams, "keyWrapAlg", symKeySize); + setSelectedKeyWrapAlg(keyWrapAlg); + logger.debug("In TPSProcessor.format: resolved keyWrapAlg: " + keyWrapAlg); + } catch (TPSException e) { + logger.debug("TPSProcessor.format: OK not to have keyWrapAlg target in token range mapping"); + } + + try { + String appletVer = resolverInst.getResolvedMapping(mappingParams, "appletVer", symKeySize); + setSelectedAppletVer(appletVer); + logger.debug("In TPSProcessor.format: resolved appletVer: " + appletVer); + } catch (TPSException e) { + logger.debug("TPSProcessor.format: OK not to have appletVer target in token range mapping"); + } + // ** Applet and Alg Selection by Token Range Support end ** } } catch (TPSException e) { logMsg = e.toString(); @@ -2339,7 +2457,7 @@ need to reach out to the Registration DB (authid) String info = " Internal Error obtaining mandatory config values. Error: " + e; auditFormatFailure(userid, appletInfo, info); - logger.error("TPSProcessor.format: " + info, e); + logger.debug("TPSProcessor.format: " + info); logMsg = "TPS error: " + info; tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, "failure"); @@ -2360,7 +2478,7 @@ need to reach out to the Registration DB (authid) auditAuthFailure(userid, currentTokenOperation, appletInfo, (userAuth != null) ? userAuth.getID() : null); - logger.error("TPSProcessor.format:: authentication exception thrown: " + e.getMessage(), e); + logger.debug("TPSProcessor.format:: authentication exception thrown: " + e); logMsg = "authentication failed, status = STATUS_ERROR_LOGIN"; tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, @@ -2382,14 +2500,10 @@ need to reach out to the Registration DB (authid) checkInvalidTokenStatus(tokenRecord, ActivityDatabase.OP_FORMAT); - if (tps.isOperationTransitionAllowed(tokenRecord, newState)) { - logger.debug("TPSProcessor.format: token transition allowed " + - tokenRecord.getTokenStatus() + - " to " + newState); - } else { + if (!tps.isOperationTransitionAllowed(tokenRecord, newState)) { String info = " illegal transition attempted: " + tokenRecord.getTokenStatus() + " to " + newState; - logger.error("TPSProcessor.format: token transition: " + info); + logger.debug("TPSProcessor.format: token transition: " + info); logMsg = "Operation for CUID " + appletInfo.getCUIDhexStringPlain() + " Disabled. " + info; auditFormatFailure(userid, appletInfo, info); @@ -2398,6 +2512,10 @@ need to reach out to the Registration DB (authid) throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_DISABLED_TOKEN); + } else { + logger.debug("TPSProcessor.format: token transition allowed " + + tokenRecord.getTokenStatus() + + " to " + newState); } } else { checkAllowUnknownToken(TPSEngine.FORMAT_OP); @@ -2450,20 +2568,53 @@ need to reach out to the Registration DB (authid) statusUpdate(100, "PROGRESS_DONE"); } + // ** G&D 256 Key Rollover Support ** + // initialize status for key rollover + TPSStatus symKeyUpgradeStatus = TPSStatus.STATUS_NO_ERROR; + // Upgrade Symm Keys if needed - - SecureChannel channel; + + SecureChannel channel = null; try { channel = checkAndUpgradeSymKeys(appletInfo, tokenRecord); } catch (TPSException te) { - auditKeyChangeover(appletInfo, "failure", null /* TODO */, + // ** G&D 256 Key Rollover Support ** + // Check whether the exception is thrown by 256 key rollover + if (te.getStatus() == TPSStatus.STATUS_ERROR_SYMKEY_256_UPGRADE) + { + // will update the token record in the DS before throwing the exception + // because it might be the case that 128 FMK was successfully rolled to 128 OMK + symKeyUpgradeStatus = TPSStatus.STATUS_ERROR_SYMKEY_256_UPGRADE; + } + // Check whether exception is caused by attempting to change 256 OMK to 128 FMK + // RedHat : avoid null ptr. For non external reg case. + else if (getSelectedKeySet() != null && getSelectedKeySet().equals(getKeyDowngradeKeySet()) && getSymmetricKeysRequiredVersion() == getKeyDowngradeVersion()) + { + // proceed with downgrade if configured to do so + logger.debug("TPSProcessor.checkAndUpgradeSymKeys: try downgrade key size."); + try { + channel = downgradeSymKeySize(appletInfo, tokenRecord, getSymmetricKeysRequiredVersion(), getChannelDefKeyIndex(), getTKSConnectorID()); + } catch (TPSException e) { + auditKeyChangeover(appletInfo, "failure", null /* TODO */, + getSymmetricKeysRequiredVersionHexString(), e.toString()); + throw e; + } + } + // throw the exception if none of above + else { + auditKeyChangeover(appletInfo, "failure", null /* TODO */, getSymmetricKeysRequiredVersionHexString(), te.toString()); - throw te; + throw te; + } + } + + // ** G&D 256 Key Rollover Support ** + // check 256 key rollover status before using the channel + if (symKeyUpgradeStatus == TPSStatus.STATUS_NO_ERROR) { + channel.externalAuthenticate(); + + auditFormatSuccess(userid, appletInfo, channel.getKeyInfoData().toHexStringPlain()); } - channel.externalAuthenticate(); - - auditFormatSuccess(userid, appletInfo, channel.getKeyInfoData().toHexStringPlain()); - if (isTokenPresent && revokeCertsAtFormat()) { // Revoke certificates on token, if so configured RevocationReason reason = getRevocationReasonAtFormat(); @@ -2474,15 +2625,15 @@ need to reach out to the Registration DB (authid) } catch (TPSException te) { // failed revocation; capture message and continue String failMsg = "revoke certificates failure"; - logMsg = failMsg + ":" + te.getMessage(); - logger.error("TPSProcessor.format: " + logMsg, te); + logMsg = failMsg + ":" + te.toString(); + logger.debug("TPSProcessor.format: " + logMsg); tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, "failure"); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_REVOKE_CERTIFICATES_FAILED); } catch (Exception ee) { String failMsg = "revoke certificates failure"; - logMsg = failMsg + ":" + ee.getMessage(); - logger.error("TPSProcessor.format: " + logMsg, ee); + logMsg = failMsg + ":" + ee.toString(); + logger.debug("TPSProcessor.format: " + logMsg); tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, "failure"); throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_REVOKE_CERTIFICATES_FAILED); @@ -2494,8 +2645,8 @@ need to reach out to the Registration DB (authid) tps.tdb.tdbRemoveCertificatesByCUID(tokenRecord.getId()); } catch (Exception e) { logMsg = "Attempt to clean up record with tdbRemoveCertificatesByCUID failed; token probably clean; continue anyway:" - + e.getMessage(); - logger.warn("TPSProcessor.format: " + logMsg, e); + + e; + logger.debug("TPSProcessor.format: " + logMsg); } // Set token's userID attribute to null @@ -2504,6 +2655,13 @@ need to reach out to the Registration DB (authid) // Update Token DB tokenRecord.setTokenStatus(TokenStatus.FORMATTED); logMsg = "token format operation"; + + // ** G&D 256 Key Rollover Support ** + // changing the logMsg if exception occurred in 256 key rollover + if (symKeyUpgradeStatus == TPSStatus.STATUS_ERROR_SYMKEY_256_UPGRADE) { + logMsg = "token format operation without symkey 256 upgrade"; + } + try { tps.tdb.tdbUpdateTokenEntry(tokenRecord); tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), logMsg, "success"); @@ -2515,6 +2673,12 @@ need to reach out to the Registration DB (authid) throw new TPSException(logMsg, TPSStatus.STATUS_ERROR_UPDATE_TOKENDB_FAILED); } + // ** G&D 256 Key Rollover Support ** + // if exception was caused by 256 key rollover, throw the exception after token record updated in the DS + if (symKeyUpgradeStatus == TPSStatus.STATUS_ERROR_SYMKEY_256_UPGRADE) { + throw new TPSException("Failed to upgrade symmetric key size to 256"); + } + logger.debug("TPSProcessor.format:: ends"); } @@ -2553,8 +2717,7 @@ protected void writeIssuerInfoToToken(SecureChannel origChannel,AppletInfo apple protected String getResolverInstanceName() throws TPSException { logger.debug("TPSProcessor.getResolverInstanceName: entering for operaiton : " + currentTokenOperation); - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String resolverInstName = null; String opPrefix = null; @@ -2597,12 +2760,11 @@ protected String getResolverInstanceName() throws TPSException { protected String getKeySetResolverInstanceName() throws TPSException { String method = "TPSProcessor.getKeySetResolverInstanceName: "; logger.debug(method + " begins"); - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String resolverInstName = null; if (!isExternalReg) { - logger.warn(method + "externalReg not enabled; keySet mapping currently only supported in externalReg."); + logger.debug(method + "externalReg not enabled; keySet mapping currently only supported in externalReg."); return null; } String config = "externalReg" + @@ -2662,7 +2824,7 @@ protected FilterMappingParams createFilterMappingParams( logger.debug(method + " MappingFilterParams set"); } catch (Exception et) { - logger.error(method + " exception: " + et.getMessage(), et); + logger.debug(method + " exception:" + et); throw new TPSException(method + " failed.", TPSStatus.STATUS_ERROR_MAPPING_RESOLVER_FAILED); } @@ -2671,8 +2833,7 @@ protected FilterMappingParams createFilterMappingParams( } protected String getIssuerInfoValue() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String info = null; String config = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_ISSUER_INFO_VALUE; @@ -2711,7 +2872,7 @@ void checkProfileStateOK() throws TPSException { } if (!profileState.equals(Constants.CFG_ENABLED)) { - logger.error("TPSProcessor.checkProfileStateOK: profile specifically disabled."); + logger.debug("TPSProcessor.checkProfileStateOK: profile specifically disabled."); throw new TPSException("TPSProcessor.checkProfileStateOK: profile disabled!", TPSStatus.STATUS_ERROR_DISABLED_TOKEN); } @@ -2722,8 +2883,7 @@ protected boolean checkIssuerInfoEnabled() throws TPSException { logger.debug("TPSProcessor.checkIssuerEnabled entering..."); - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String issuerEnabledConfig = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_ISSUER_INFO_ENABLE; @@ -2748,23 +2908,21 @@ protected boolean checkIssuerInfoEnabled() throws TPSException { //Obtain value and set class property. protected void checkIsExternalReg() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String External_Reg_Cfg = TPSEngine.CFG_EXTERNAL_REG + "." + "enable"; - logger.debug("TPSProcessor.checkIsExternalReg: getting config:" + External_Reg_Cfg); + logger.debug("TPS_Processor.checkIsExternalReg: getting config:" + External_Reg_Cfg); try { //These defaults are well known, it is safe to use them. - logger.debug("In TPSProcessor.checkIsExternalReg."); + logger.debug("In TPS_Processor.checkIsExternalReg."); this.isExternalReg = configStore.getBoolean(External_Reg_Cfg, false); - logger.debug("In TPSProcessor.checkIsExternalReg. isExternalReg: " + isExternalReg); + logger.debug("In TPS_Processor.checkIsExternalReg. isExternalReg: " + isExternalReg); } catch (EBaseException e1) { - logger.error("TPSProcessor.checkIsExternalReg: Internal Error obtaining mandatory config values: " - + e1.getMessage(), e1); - throw new TPSException("TPS error getting config values from config store.", - TPSStatus.STATUS_ERROR_MISCONFIGURATION); + logger.debug("TPS_Processor.checkIsExternalReg: Internal Error obtaining mandatory config values. Error: " + + e1); + throw new TPSException("TPS error getting config values from config store.", TPSStatus.STATUS_ERROR_MISCONFIGURATION); } } @@ -2772,8 +2930,7 @@ protected void checkIsExternalReg() throws TPSException { boolean checkServerSideKeyGen(String connId) throws TPSException { boolean result; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String profileConfig = "conn." + connId + "." + ".serverKeygen"; logger.debug("TPSProcessor.checkServerSideKeyGen: getting config: " + profileConfig); @@ -2790,8 +2947,7 @@ boolean checkServerSideKeyGen(String connId) throws TPSException { void checkAllowNoAppletToken(String operation) throws TPSException { boolean allow = true; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String noAppletConfig = operation + "." + selectedTokenType + "." + TPSEngine.CFG_ALLOW_NO_APPLET; logger.debug("TPSProcessor.checkAllowNoAppletToken: getting config: " + noAppletConfig); @@ -2813,8 +2969,7 @@ void checkAllowNoAppletToken(String operation) throws TPSException { boolean checkForAppletUpdateEnabled() throws TPSException { boolean enabled = false; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String appletUpdate = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_UPDATE_APPLET_ENABLE; @@ -2823,7 +2978,7 @@ boolean checkForAppletUpdateEnabled() throws TPSException { enabled = configStore.getBoolean(appletUpdate, false); } catch (EBaseException e) { throw new TPSException( - "TPSProcessor.checkForAppleUpdateEnabled: Can't find applet Update Enable. Internal error obtaining value.", + "TPSProcessor.checkForAppletUpdateEnabled: Can't find applet Update Enable. Internal error obtaining value.", TPSStatus.STATUS_ERROR_MISCONFIGURATION); } @@ -2833,38 +2988,40 @@ boolean checkForAppletUpdateEnabled() throws TPSException { protected String checkForAppletUpgrade(String operation) throws TPSException, IOException { String requiredVersion = null; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); acquireChannelPlatformAndProtocolInfo(); - - int prot = getProtocol(); - - logger.debug("TPSProcessor.checkForAppletUpgrad: protocol: " + prot); - - String protString = ""; - - // Let the existing config param handle protocol 1 by default - if(prot > 1) { - protString = ".prot."+ prot; - } - - String appletRequiredConfig = operation + "." + selectedTokenType + "." - + TPSEngine.CFG_APPLET_UPDATE_REQUIRED_VERSION + protString; - logger.debug("TPSProcessor.checkForAppletUpgrade: getting config: " + appletRequiredConfig); - try { - requiredVersion = configStore.getString(appletRequiredConfig, null); - } catch (EBaseException e) { - throw new TPSException( - "TPSProcessor.checkForAppletUpgrade: Can't find applet required Version. Internal error obtaining version.", - TPSStatus.STATUS_ERROR_MISCONFIGURATION); - } - - if (requiredVersion == null) { - throw new TPSException("TPSProcessor.checkForAppletUpgrade: Can't find applet required Version.", - TPSStatus.STATUS_ERROR_MISCONFIGURATION); - } - + + requiredVersion = getSelectedAppletVer(); // ** Applet and Alg Selection by Token Range Support: use appletVer target if it's defined in token range + if (requiredVersion == null) { // otherwise, get the requiredVersion configured by token type + + int prot = getProtocol(); + + logger.debug("TPSProcessor.checkForAppletUpgrad: protocol: " + prot); + + String protString = ""; + + // Let the existing config param handle protocol 1 by default + if(prot > 1) { + protString = ".prot."+ prot; + } + + String appletRequiredConfig = operation + "." + selectedTokenType + "." + + TPSEngine.CFG_APPLET_UPDATE_REQUIRED_VERSION + protString; + logger.debug("TPSProcessor.checkForAppletUpgrade: getting config: " + appletRequiredConfig); + try { + requiredVersion = configStore.getString(appletRequiredConfig, null); + } catch (EBaseException e) { + throw new TPSException( + "TPSProcessor.checkForAppletUpgrade: Can't find applet required Version. Internal error obtaining version.", + TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + + if (requiredVersion == null) { + throw new TPSException("TPSProcessor.checkForAppletUpgrade: Can't find applet required Version.", + TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + } logger.debug("TPSProcessor.checkForAppletUpgrade: returning: " + requiredVersion); return requiredVersion; @@ -2873,8 +3030,7 @@ protected String checkForAppletUpgrade(String operation) throws TPSException, IO protected void checkAllowUnknownToken(String operation) throws TPSException { boolean allow = true; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String unknownConfig = "op." + operation + "." + TPSEngine.CFG_ALLOW_UNKNOWN_TOKEN; logger.debug("TPSProcessor.checkAllowUnknownToken: getting config: " + unknownConfig); @@ -2886,7 +3042,7 @@ protected void checkAllowUnknownToken(String operation) throws TPSException { TPSStatus.STATUS_ERROR_MISCONFIGURATION); } - if (!allow) { + if (allow == false) { throw new TPSException( "TPSProcessor.checkAllowUnknownToken: Unknown tokens not allowed for this operation!", TPSStatus.STATUS_ERROR_UNKNOWN_TOKEN); @@ -2895,8 +3051,7 @@ protected void checkAllowUnknownToken(String operation) throws TPSException { } protected String getTKSConnectorID() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String id = null; String config = "op." + currentTokenOperation + "." + selectedTokenType + ".tks.conn"; @@ -2918,8 +3073,7 @@ protected String getTKSConnectorID() throws TPSException { protected TPSBuffer getNetkeyAID() throws TPSException { String NetKeyAID = null; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); logger.debug("TPSProcessor.getNetkeyAID: getting config: " + TPSEngine.CFG_DEF_NETKEY_INSTANCE_AID); try { @@ -2927,7 +3081,7 @@ protected TPSBuffer getNetkeyAID() throws TPSException { TPSEngine.CFG_DEF_NETKEY_INSTANCE_AID); } catch (EBaseException e1) { - logger.error("TPSProcessor.getNetkeyAID: Internal Error obtaining mandatory config values: " + e1.getMessage(), e1); + logger.debug("TPS_Processor.getNetkeyAID: Internal Error obtaining mandatory config values. Error: " + e1); throw new TPSException("TPS error getting config values from config store.", TPSStatus.STATUS_ERROR_MISCONFIGURATION); } @@ -2939,8 +3093,7 @@ protected TPSBuffer getNetkeyAID() throws TPSException { protected TPSBuffer getNetkeyPAID() throws TPSException { String NetKeyPAID = null; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); logger.debug("TPSProcessor.getNetkeyPAID: getting config: " + TPSEngine.CFG_DEF_NETKEY_FILE_AID); try { @@ -2948,7 +3101,7 @@ protected TPSBuffer getNetkeyPAID() throws TPSException { TPSEngine.CFG_APPLET_NETKEY_FILE_AID, TPSEngine.CFG_DEF_NETKEY_FILE_AID); } catch (EBaseException e1) { - logger.error("TPSProcessor.getNetkeyAID: Internal Error obtaining mandatory config values: " + e1.getMessage(), e1); + logger.debug("TPS_Processor.getNetkeyAID: Internal Error obtaining mandatory config values. Error: " + e1); throw new TPSException("TPS error getting config values from config store.", TPSStatus.STATUS_ERROR_MISCONFIGURATION); } @@ -2960,8 +3113,7 @@ protected TPSBuffer getNetkeyPAID() throws TPSException { protected TPSBuffer getCardManagerAID() throws TPSException { String cardMgrAID = null; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); logger.debug("TPSProcessor.getCardManagerAID: getting config: " + TPSEngine.CFG_APPLET_CARDMGR_INSTANCE_AID); try { @@ -2969,7 +3121,7 @@ protected TPSBuffer getCardManagerAID() throws TPSException { TPSEngine.CFG_DEF_CARDMGR_INSTANCE_AID); } catch (EBaseException e1) { - logger.error("TPSProcessor.getNetkeyAID: Internal Error obtaining mandatory config values: " + e1.getMessage(), e1); + logger.debug("TPS_Processor.getNetkeyAID: Internal Error obtaining mandatory config values. Error: " + e1); throw new TPSException("TPS error getting config values from config store.", TPSStatus.STATUS_ERROR_MISCONFIGURATION); } @@ -2978,9 +3130,35 @@ protected TPSBuffer getCardManagerAID() throws TPSException { return ret; } - protected String getAppletExtension() throws TPSException { + protected List getCardManagerAIDList() throws TPSException { + + String cardMgrAID = null; + List cardMgrAidList = null; TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); + logger.debug("TPSProcessor.getCardManagerAIDList: getting config: " + TPSEngine.CFG_APPLET_CARDMGR_INSTANCE_AID); + try + { + cardMgrAID = configStore.getString(TPSEngine.CFG_APPLET_CARDMGR_INSTANCE_AID, + TPSEngine.CFG_DEF_CARDMGR_INSTANCE_AID); + + if(cardMgrAID.length() > 0) + cardMgrAidList = Arrays.asList(cardMgrAID.split(",")); + + if(cardMgrAidList == null) + cardMgrAidList = Arrays.asList(engine.CFG_DEF_CARDMGR_INSTANCE_AID); + } + catch (EBaseException e1) + { + logger.debug("TPS_Processor.getCardManagerAIDList: Internal Error obtaining mandatory config values. Error: " + e1); + throw new TPSException("TPS error getting config values from config store.", TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + + return cardMgrAidList; + } + + protected String getAppletExtension() throws TPSException { + TPSEngineConfig configStore = this.getConfigStore(); String extension = null; String extensionConfig = TPSEngine.CFG_APPLET_EXTENSION; @@ -2998,8 +3176,7 @@ protected String getAppletExtension() throws TPSException { protected String getAppletDirectory(String operation) throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String directory = null; String directoryConfig = operation + "." + selectedTokenType + "." + TPSEngine.CFG_APPLET_DIRECTORY; @@ -3021,8 +3198,7 @@ protected String getAppletDirectory(String operation) throws TPSException { } protected int getChannelBlockSize() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int blockSize = 0; try { blockSize = configStore.getInteger(TPSEngine.CFG_CHANNEL_BLOCK_SIZE, TPSEngine.CFG_CHANNEL_DEF_BLOCK_SIZE); @@ -3039,8 +3215,7 @@ protected int getChannelBlockSize() throws TPSException { } protected int getChannelInstanceSize() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int instanceSize = 0; try { instanceSize = configStore.getInteger(TPSEngine.CFG_CHANNEL_INSTANCE_SIZE, @@ -3059,8 +3234,7 @@ protected int getChannelInstanceSize() throws TPSException { } protected int getAppletMemorySize() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int memSize = 0; try { memSize = configStore.getInteger(TPSEngine.CFG_CHANNEL_APPLET_MEMORY_SIZE, @@ -3077,8 +3251,7 @@ protected int getAppletMemorySize() throws TPSException { } protected int getChannelDefKeyVersion() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int ver = 0; try { ver = configStore.getInteger(TPSEngine.CFG_CHANNEL_DEFKEY_VERSION, 0x0); @@ -3096,8 +3269,7 @@ protected int getChannelDefKeyVersion() throws TPSException { } protected int getChannelDefKeyIndex() throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); int index = 0; try { index = configStore.getInteger(TPSEngine.CFG_CHANNEL_DEFKEY_INDEX, 0x0); @@ -3116,8 +3288,7 @@ protected int getChannelDefKeyIndex() throws TPSException { protected String getSharedSecretTransportKeyName(String connId) throws TPSException { - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String sharedSecretName = null; try { String configName = "conn." + connId + ".tksSharedSymKeyName"; @@ -3150,12 +3321,13 @@ protected PK11SymKey getSharedSecretTransportKey(String connId) throws TPSExcept symmKeys = SessionKey.ListSymmetricKeys(CryptoUtil.INTERNAL_TOKEN_NAME); logger.debug("TPSProcessor.getSharedSecretTransportKey: symmKeys List: " + symmKeys); } catch (Exception e) { - logger.warn("TPSProcessor.getSharedSecretTransportKey: " + e.getMessage(), e); + // TODO Auto-generated catch block + logger.debug(e.toString()); } for (String keyName : symmKeys.split(",")) { if (sharedSecretName.equals(keyName)) { - logger.debug("TPSProcessor.getSharedSecretTransportKey: shared secret key found!"); + logger.debug("TPSProcessor.getSharedSecret: shared secret key found!"); keyPresent = true; break; } @@ -3231,13 +3403,29 @@ protected AppletInfo getAppletInfo() throws TPSException, IOException { logger.debug("TPSProcessor.getAppletInfo, entering ..."); - selectCardManager(); - - TPSBuffer cplc_data = getCplcData(); - logger.debug("cplc_data: " + cplc_data.toHexString()); - - TPSBuffer token_cuid = extractTokenCUID(cplc_data); - TPSBuffer token_msn = extractTokenMSN(cplc_data); + TPSBuffer cplc_data = null; + TPSBuffer token_cuid = null; + TPSBuffer token_msn = null; + + // Get default card manager + selectDefaultCardManager(); + + // Get the selected card manager + TPSBuffer selectedCardMgr = getSelectedCardMgr(); + logger.debug("TPSProcessor.getAppletInfo: selectedCardMgr = " + selectedCardMgr.toHexStringPlain()); + + cplc_data = getCplcData(); + logger.debug("TPSProcessor.getAppletInfo, cplc_data: " + cplc_data.toHexString()); + + if (cplc_data != null) + { + token_cuid = extractTokenCUID(cplc_data); + token_msn = extractTokenMSN(cplc_data); + } + else + { + throw new TPSException("TPSProcessor.getAppletInfo: Can't get cplc data!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); + } /** * Checks if the netkey has the required applet version. @@ -3252,7 +3440,7 @@ protected AppletInfo getAppletInfo() throws TPSException, IOException { byte app_major_version = 0x0; byte app_minor_version = 0x0; - logger.debug("TPSProcessor.getAppletInfo: status: " + token_status.toHexString()); + logger.debug("TPS_Processor.getAppletInfo: status: " + token_status.toHexString()); if (token_status.size() >= 4) { major_version = token_status.at(0); minor_version = token_status.at(1); @@ -3280,11 +3468,12 @@ protected AppletInfo getAppletInfo() throws TPSException, IOException { result.setMSN(token_msn); result.setTotalMem(total_mem); result.setFreeMem(free_mem); + result.setAid(selectedCardMgr); logger.debug("TPSProcessor.getAppletInfo: cuid: " + result.getCUIDhexString() + " msn: " + result.getMSNString() + " major version: " + result.getMajorVersion() + " minor version: " + result.getMinorVersion() + " App major version: " + result.getAppMajorVersion() + " App minor version: " - + result.getAppMinorVersion()); + + result.getAppMinorVersion() + " cardManagerAID: " + selectedCardMgr.toHexStringPlain()); String currentAppletVersion = formatCurrentAppletVersion(result); if (currentAppletVersion != null) { @@ -3295,25 +3484,110 @@ protected AppletInfo getAppletInfo() throws TPSException, IOException { return result; } - protected void selectCardManager() throws TPSException, IOException { - logger.debug("TPSProcessor.selectCardManager: entering.."); - TPSBuffer aidBuf = getCardManagerAID(); + // Method to get default card manager AID + protected void selectDefaultCardManager() throws TPSException, IOException { + String method = "TPSProcessor.selectDefaultCardManager: "; + logger.debug(method + "entering.."); - APDUResponse select = selectApplet((byte) 0x04, (byte) 0x00, aidBuf); + TPSEngine engine = TPSEngine.getInstance(); + + // Request default AID from the token + TPSBuffer trailer = new TPSBuffer((byte) 0x00); + APDUResponse defaultAID = selectDefaultApplet((byte) 0x04, (byte) 0x00, trailer); + +logger.debug("defaultAID: " + defaultAID); + if (defaultAID == null || !defaultAID.checkResult()) + { + // If card needs length of data, resend request with length + if (defaultAID.getSW1() == (byte) 0x6C) + { + trailer = new TPSBuffer(defaultAID.getSW2()); + // Request default AID again from the token with correct length + logger.debug(method + "Request for card manager failed, retrying with correct length..."); + defaultAID = selectDefaultApplet((byte) 0x04, (byte) 0x00, trailer); + } + else + { + throw new TPSException("TPSProcessor.selectDefaultCardManager: Can't select the card manager applet!", + TPSStatus.STATUS_ERROR_CANNOT_ESTABLISH_COMMUNICATION); + } + } - if (!select.checkResult()) { - throw new TPSException("TPSProcessor.selectCardManager: Can't selelect the card manager applet!", + if (defaultAID != null && defaultAID.checkResult()) + { + TPSBuffer aidData = parseAIDResponse(defaultAID.getData()); + + String defAIDStr = aidData.toHexStringPlain(); + + //RedHat : appease tpsclient tester that only returns 90 00 success, using original default AID. + if(aidData == null || aidData.size() == 0) { + logger.debug(method + "tpsclient tester probably returned only 90 00, assume old default AID."); + defAIDStr = getCardManagerAIDList().get(0); + aidData = new TPSBuffer(defAIDStr); + } + + // Get list of valid AID values from the configuration file + List aidBuf = getCardManagerAIDList(); + + // Check AID matches one in the list + for (String aid:aidBuf) + { + // Found valid AID + if (defAIDStr.equals(aid)) + { + logger.debug(method + "Found cardManagerAID in list of valid values: " + defAIDStr + ", select it to be sure"); + + // Confirm AID is valid by selecting it + APDUResponse confirmedAID = selectApplet((byte) 0x04, (byte) 0x00, aidData); + + if (confirmedAID != null && confirmedAID.checkResult()) + { + logger.debug(method + "Confirmed cardManagerAID: " + defAIDStr); + + // Set this card manager in the session + setSelectedCardMgr(aidData); + break; + } + else + { + logger.debug(method + "Card Manager Selection Failed for cardMgrAID " + defAIDStr + "!"); + } + } + } + //Need to check for null or get a null ptr exception. + TPSBuffer selectedCardMgr = getSelectedCardMgr(); + if (selectedCardMgr == null || selectedCardMgr.size() == 0) + { + throw new TPSException("TPSProcessor.selectDefaultCardManager: Can't select the card manager applet!", TPSStatus.STATUS_ERROR_CANNOT_ESTABLISH_COMMUNICATION); + } + } + else + { + throw new TPSException("TPSProcessor.selectDefaultCardManager: Can't select the card manager applet!", + TPSStatus.STATUS_ERROR_CANNOT_ESTABLISH_COMMUNICATION); } } + protected void selectCardMgr(TPSBuffer aidBuffer) throws TPSException, IOException { + logger.debug("TPSProcessor.selectCardMgr: entering.."); + logger.debug("TPSProcessor.selectCardMgr: cardManagerAID value = " + aidBuffer.toHexStringPlain()); + + APDUResponse select = selectApplet((byte) 0x04, (byte) 0x00, aidBuffer); + + logger.debug("TPSProcessor.selectCardMgr: select result = " + select.checkResult()); + + if (select == null || !select.checkResult()) { + throw new TPSException("TPSProcessor.selectCardMgr: Can't select the card manager applet!", + TPSStatus.STATUS_ERROR_CANNOT_ESTABLISH_COMMUNICATION); + } + } protected boolean checkSymmetricKeysEnabled() throws TPSException { boolean result = true; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String symmConfig = "op" + "." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_SYMM_KEY_UPGRADE_ENABLED; @@ -3331,9 +3605,9 @@ protected boolean checkSymmetricKeysEnabled() throws TPSException { protected int getSymmetricKeysRequiredVersion() throws TPSException { int version = 0; + ; - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String requiredVersionConfig = "op" + "." + currentTokenOperation + "." + selectedTokenType + "." + "update.symmetricKeys.requiredVersion"; @@ -3343,7 +3617,7 @@ protected int getSymmetricKeysRequiredVersion() throws TPSException { version = configStore.getInteger(requiredVersionConfig, 0x0); } catch (EBaseException e) { throw new TPSException("TPSProcessor.getSymmetricKeysRequired: Internal error getting config value.", - TPSStatus.STATUS_ERROR_MISCONFIGURATION); + TPSStatus.STATUS_ERROR_MISCONFIGURATION); } logger.debug("TPSProcessor.getSymmetricKeysRequiredVersion: returning version: " + version); @@ -3380,28 +3654,34 @@ default key version (0). It will return the version */ if(tokenRecord == null || appletInfo == null) { - throw new TPSException("TPSProcessor.checkAndUpgradeSymKeys: invalid input data!"); + throw new TPSException("TPSProcessor.checkAndUpgradeSymKeys: invalid input data!", + TPSStatus.STATUS_ERROR_KEY_CHANGE_OVER); } - TPSEngine eng = TPSEngine.getInstance(); - TPSSubsystem tps = (TPSSubsystem) eng.getSubsystem(TPSSubsystem.ID); + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); SecureChannel channel = null; int defKeyVersion = 0; int defKeyIndex = getChannelDefKeyIndex(); - + if (checkSymmetricKeysEnabled()) { logger.debug("TPSProcessor.checkAndUpgradeSymKeys: Symm key upgrade enabled."); int requiredVersion = getSymmetricKeysRequiredVersion(); - + + // ** G&D 256 Key Rollover Support ** + // set the flag to indicate if card needs to roll over to 256 OMK + // RedHat : avoid null ptr. For non external reg case. + boolean keyRollNeeded = (getSelectedKeySet() != null && getSelectedKeySet().equals(getKeyRolloverKeySet()) && requiredVersion == getKeyRolloverVersion()); + logger.debug(" keyRollNeeded: " + keyRollNeeded); // try to make a secure channel with the 'requiredVersion' keys // If this fails, we know we will have to attempt an upgrade // of the keys boolean failed = false; try { - + channel = setupSecureChannel((byte) requiredVersion, (byte) defKeyIndex, getTKSConnectorID(),appletInfo); @@ -3410,11 +3690,24 @@ default key version (0). It will return the version logger.debug("TPSProcessor.checkAndUpgradeSymKeys: failed to create secure channel with required version, we need to upgrade the keys."); failed = true; } - + //If we failed we need to upgrade the keys - if (failed) { + if (failed == true) { + + // Make sure correct card manager is selected + TPSBuffer selectedCardMgr = getSelectedCardMgr(); + if (selectedCardMgr == null || selectedCardMgr.size() == 0) + { + selectDefaultCardManager(); + } + else + { + selectCardMgr(getSelectedCardMgr()); + } + + appletInfo.setAid(getSelectedCardMgr()); - selectCardManager(); + logger.debug("TPSProcessor.checkAndUpgradeSymKeys: Selected card manager from session: " + appletInfo.getAid().toHexStringPlain()); channel = setupSecureChannel(appletInfo); @@ -3434,7 +3727,6 @@ default key version (0). It will return the version String connId = getTKSConnectorID(); TPSBuffer curKeyInfo = channel.getKeyInfoData(); - TPSEngine engine = TPSEngine.getInstance(); int protocol = 1; if (channel.isSCP02()) { @@ -3460,26 +3752,25 @@ default key version (0). It will return the version boolean isVersionInRange = checkCardGPKeyVersionIsInRange(appletInfo.getCUIDhexStringPlain(), appletInfo.getKDDhexStringPlain(), curKeyInfo.toHexStringPlain()); boolean doesVersionMatchTokenDB = checkCardGPKeyVersionMatchesTokenDB(appletInfo.getCUIDhexStringPlain(), appletInfo.getKDDhexStringPlain(), curKeyInfo.toHexStringPlain()); - if (!cuidOK) { + if(cuidOK == false) { throw new TPSException("TPSProcessor.generateSecureChannel: cuid vs kdd matching policy not met!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } - if (!isVersionInRange) { + if(isVersionInRange == false) { throw new TPSException("TPSProcessor.generateSecureChannel: key version is not within acceptable range!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } - if (!doesVersionMatchTokenDB) { + if(doesVersionMatchTokenDB == false) { throw new TPSException("TPSProcessor.generateSecureChannel: key version from token does not match that of the token db!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } TPSBuffer keySetData = engine.createKeySetData(newVersion, curKeyInfo, protocol, - appletInfo.getCUID(),channel.getKeyDiversificationData(), channel.getDekSessionKeyWrapped(), connId, getSelectedKeySet()); + appletInfo.getCUID(),channel.getKeyDiversificationData(), channel.getDekSessionKeyWrapped(), connId, getSelectedKeySet(), null); - //logger.debug("TPSProcessor.checkAndUpgradeSymKeys: new keySetData from TKS: " + keySetData.toHexString()); logger.debug("TPSProcessor.checkAndUpgradeSymKeys: received new keySetData from TKS"); byte curVersion = curKeyInfo.at(0); @@ -3490,20 +3781,19 @@ default key version (0). It will return the version throw new TPSException("TPSProcessor.checkAndUpgradeSymKeys: end of progress."); try { - channel.putKeys(curVersion, curIndex, keySetData); + channel.putKeys(curVersion, curIndex, keySetData); tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), "Sent new GP Key Set to token", "success"); } catch (TPSException e) { - - logger.warn("TPSProcessor.checkAndUpgradeSymKeys: failed to put key: " + e.getMessage(), e); - logger.warn("TPSProcessor.checkAndUpgradeSymKeys: checking to see if this a SCP02 with 0xFF default key set."); + + logger.debug("TPSProcessor.checkAndUpgradeSymKeys: failed to put key, checking to see if this a SCP02 with 0xFF default key set."); if (protocol == 2 && curVersion == (byte) 0xff) { logger.debug("TPSProcessor.checkAndUpgradeSymKeys: failed to put key, but we have SCP02 and the 0xFF dev key, try again."); byte[] nv_dev = { (byte) 0x1, (byte) 0x1 }; TPSBuffer devKeySetData = engine.createKeySetData(new TPSBuffer(nv_dev), curKeyInfo, protocol, - appletInfo.getCUID(), channel.getKeyDiversificationData(), channel.getDekSessionKeyWrapped(), connId, getSelectedKeySet()); + appletInfo.getCUID(), channel.getKeyDiversificationData(), channel.getDekSessionKeyWrapped(), connId, getSelectedKeySet(), null); logger.debug("TPSProcessor.checkAndUpgradeSymKeys: about to get rid of keyset 0xFF and replace it with keyset 0x1 with developer key set"); channel.putKeys((byte) 0x0, (byte) 0x1, devKeySetData); @@ -3529,17 +3819,35 @@ default key version (0). It will return the version logger.debug("TPSProcessor.checkAndUpgradeSymKeys: curVersionStr: " + curVersionStr + " newVersionStr: " + newVersionStr); - selectCoolKeyApplet(); + + // ** G&D 256 Key Rollover Support ** + // Create the secure channel if no further key rollover is needed + if (!keyRollNeeded) { + selectCoolKeyApplet(); - channel = setupSecureChannel((byte) requiredVersion, (byte) defKeyIndex, + channel = setupSecureChannel((byte) requiredVersion, (byte) defKeyIndex, getTKSConnectorID(), appletInfo); - auditKeyChangeover(appletInfo, "success", curVersionStr, newVersionStr, null); + auditKeyChangeover(appletInfo, "success", curVersionStr, newVersionStr, null); + } - } else { + } else if (!keyRollNeeded) { // ** G&D 256 Key Rollover Support ** message only applicable if no further rollover is needed logger.debug("TPSProcessor.checkAndUpgradeSymeKeys: We are already at the desired key set, returning secure channel."); } // tokenRecord.setKeyInfo(channel.getKeyInfoData().toHexStringPlain()); + + // ** G&D 256 Key Rollover Support ** + // Continue to upgrade keys to 256 bit + if (keyRollNeeded) + { + try { + logger.debug("TPSProcessor.checkAndUpgradeSymKeys: we need to do 256 key rollover for " + getSelectedKeySet()); + channel = upgradeSymKeySize(appletInfo, tokenRecord, requiredVersion, defKeyIndex, getTKSConnectorID()); + } catch (TPSException | IOException e) { + logger.debug("TPSProcessor.checkAndUpgradeSymKeys: Failed to roll symmetric key size to 256"); + throw new TPSException("Failed to upgrade symmetric key size to 256", TPSStatus.STATUS_ERROR_SYMKEY_256_UPGRADE); + } + } } else { //Create a standard secure channel with current key set. @@ -3567,7 +3875,7 @@ protected TPSBuffer listObjects(byte seq) throws TPSException, IOException { APDUResponse respApdu = handleAPDURequest(listObjects); if (!respApdu.checkResult()) { - logger.warn("TPSProcessor.listObjects: Bad response from ListObjects! Token possibly has no objects"); + logger.debug("TPSProcessor.listObjects: Bad response from ListObjects! Token possibly has no objects"); return null; } @@ -3678,9 +3986,14 @@ protected String mapPattern(LinkedHashMap map, String inPattern) pattern = result; } - String returnVal = result.isEmpty() ? inPattern : result; - logger.debug("TPSProcessor.mapPattern: returning: {}", returnVal); - return returnVal; + if (result.equals("")) { + logger.debug("TPSProcessor.mapPattern: returning: " + inPattern); + return (inPattern); + } else { + logger.debug("TPSProcessor.mapPattern: returning: " + result); + return result; + } + } protected String formatCurrentAppletVersion(AppletInfo aInfo) throws TPSException, IOException { @@ -3703,7 +4016,7 @@ protected String formatCurrentAppletVersion(AppletInfo aInfo) throws TPSExceptio TPSBuffer build_id = getAppletVersion(); if (build_id == null) { - logger.warn(method + " getAppletVersion returning null"); + logger.debug(method + " getAppletVersion returning null"); return null; } String build_idStr = build_id.toHexStringPlain(); @@ -3728,8 +4041,7 @@ protected void checkAndHandlePinReset(SecureChannel channel) throws TPSException TPSStatus.STATUS_ERROR_MAC_RESET_PIN_PDU); } - TPSEngine engine = TPSEngine.getInstance(); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String pinResetEnableConfig = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_PIN_RESET_ENABLE; @@ -3765,7 +4077,7 @@ protected void checkAndHandlePinReset(SecureChannel channel) throws TPSException enabled = configStore.getBoolean(pinResetEnableConfig, true); - if (!enabled) { + if (enabled == false) { logger.debug("TPSProcessor.checkAndHandlePinReset: Pin Reset not allowed by configuration, exiting..."); return; @@ -3807,12 +4119,12 @@ protected void checkAndAuthenticateUser(AppletInfo appletInfo, String tokenType) opPrefix = TPSEngine.OP_PIN_RESET_PREFIX; } - TPSEngine engine = TPSEngine.getInstance(); if (!isExternalReg) { // authenticate per profile/tokenType configuration String configName = opPrefix + "." + tokenType + ".auth.enable"; - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); + TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); //TPSSession session = getSession(); boolean isAuthRequired; @@ -3820,8 +4132,8 @@ protected void checkAndAuthenticateUser(AppletInfo appletInfo, String tokenType) logger.debug("TPSProcessor.checkAndAuthenticateUser: getting config: " + configName); isAuthRequired = configStore.getBoolean(configName, true); } catch (EBaseException e) { - logger.error("TPSProcessor.checkAndAuthenticateUser: Internal Error obtaining mandatory config values: " - + e.getMessage(), e); + logger.debug("TPSProcessor.checkAndAuthenticateUser: Internal Error obtaining mandatory config values. Error: " + + e); throw new TPSException("TPS error getting config values from config store.", TPSStatus.STATUS_ERROR_MISCONFIGURATION); } @@ -3846,7 +4158,8 @@ protected void checkAndAuthenticateUser(AppletInfo appletInfo, String tokenType) tps.tdb.tdbActivity(ActivityDatabase.OP_ENROLLMENT, tokenRecord, session.getIpAddress(), msg, "failure"); - throw new TPSException(msg, TPSStatus.STATUS_ERROR_LOGIN, e); + throw new TPSException(msg, + TPSStatus.STATUS_ERROR_LOGIN); } } else { throw new TPSException( @@ -3870,8 +4183,8 @@ public void acquireChannelPlatformAndProtocolInfo() throws TPSException, IOExcep gp211GetSecureChannelProtocolDetails(); } catch (TPSException e) { - logger.warn("TPSProcessor.acquireChannelPlatformProtocolInfo: Error getting gp211 protocol data, assume scp01: " - + e.getMessage()); + logger.debug("TPSProcessor.acquireChannelPlatformProtocolInfo: Error getting gp211 protocol data, assume scp01 " + + e); platProtInfo.setPlatform(SecureChannel.GP201); platProtInfo.setProtocol(SecureChannel.SECURE_PROTO_01); @@ -3896,17 +4209,28 @@ public void gp211GetSecureChannelProtocolDetails() throws TPSException, IOExcept TPSBuffer data = null; TPSBuffer keyData = null; - selectCardManager(); - try { + // If card manager is not selected, select it + TPSBuffer selectedCardMgr = getSelectedCardMgr(); + + if (selectedCardMgr == null || getSelectedCardMgr().size() == 0) + { + selectDefaultCardManager(); + } + // If it was selected already, make sure it is the one used here + else + { + selectCardMgr(getSelectedCardMgr()); + } + try { data = getData(SecureChannel.GP211_GET_DATA_CARD_DATA); + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: data.size() = " + data.size()); keyData = getData(SecureChannel.GP211_GET_DATA_KEY_INFO); } catch (TPSException e) { - logger.error("TPSProcessor.gp211GetSecureChannelProtocolDetails: Card can't understand GP211: " + e.getMessage(), e); + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: Card can't understand GP211! " + e); throw e; - } if (data.size() < 5) { @@ -3914,8 +4238,9 @@ public void gp211GetSecureChannelProtocolDetails() throws TPSException, IOExcept TPSStatus.STATUS_ERROR_SECURE_CHANNEL); } - //logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: returned data: " + data.toHexString()); logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: card data returned"); + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: returned data: " + data.toHexString()); + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: returned key data: " + keyData.toHexString()); // Now process the GP211 data returned by the card. @@ -3924,14 +4249,20 @@ public void gp211GetSecureChannelProtocolDetails() throws TPSException, IOExcept int length = 0; if (data.at(offset) == (byte) 0x66) { + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: data.at(" + offset + ") = 0x66"); offset++; + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: offset = " + offset); totalLength = data.getIntFrom1Byte(offset++); offset++; + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: offset = " + offset); } else { + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: data.at(" + offset + ") = " + data.at(offset)); offset++; + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: offset = " + offset); totalLength = data.getIntFrom1Byte(offset++); + logger.debug("TPSProcessor.gp211GetSecureChannelProtocolDetails: offset = " + offset); } @@ -4021,9 +4352,6 @@ public int getProtocol() { boolean checkCardGPKeyVersionIsInRange(String CUID, String KDD, String keyInfoData) throws TPSException { boolean result = true; - TPSEngine engine = TPSEngine.getInstance(); - TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); - String method = "checkCardGPKeyVersionIsInRange: "; logger.debug(method + " entering: keyInfoData: " + keyInfoData); @@ -4032,7 +4360,9 @@ boolean checkCardGPKeyVersionIsInRange(String CUID, String KDD, String keyInfoDa throw new TPSException(method + " Invalid input data!"); } - TPSEngineConfig configStore = engine.getConfig(); + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + TPSEngineConfig configStore = this.getConfigStore(); String checkBoundedGPKeyVersionConfig = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_ENABLE_BOUNDED_GP_KEY_VERSION; @@ -4050,7 +4380,7 @@ boolean checkCardGPKeyVersionIsInRange(String CUID, String KDD, String keyInfoDa // Check only if asked. - if (result) { + if (result == true) { String minConfig = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_MINIMUM_GP_KEY_VERSION; @@ -4098,7 +4428,7 @@ boolean checkCardGPKeyVersionIsInRange(String CUID, String KDD, String keyInfoDa logger.debug(method + " Version : " + keyInfoVer + " is in range of: " + minVersion + " and: " + maxVersion); result = true; - String logMsg = "Token GP key version is within GP key version range."; + String logMsg = "Token GP key version is within GP key version range."; auditKeySanityCheck( userid, CUID, @@ -4112,6 +4442,7 @@ boolean checkCardGPKeyVersionIsInRange(String CUID, String KDD, String keyInfoDa result = false; logger.debug(method + " Version : " + keyInfoVer + " is NOT in range of: " + minVersion + " and: " + maxVersion); + if(versionMinCompare < 0) { // the token's key version is less than the minimum version String logMsg = "Token key version " + keyInfoVer + " is less than minimum GP key version " + @@ -4179,7 +4510,7 @@ boolean checkCUIDMatchesKDD(String CUID, String KDD) throws TPSException { TPSEngine engine = TPSEngine.getInstance(); TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); - TPSEngineConfig configStore = engine.getConfig(); + TPSEngineConfig configStore = this.getConfigStore(); String checkCUIDMatchesKDDConfig = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_CUID_MUST_MATCH_KDD; @@ -4196,7 +4527,7 @@ boolean checkCUIDMatchesKDD(String CUID, String KDD) throws TPSException { logger.debug(method + " config result: " + result); // Check only if asked to - if (result) { + if (result == true) { if (CUID.compareToIgnoreCase(KDD) == 0) { logger.debug(method + " CUID and KDD values match!"); result = true; @@ -4218,7 +4549,6 @@ boolean checkCUIDMatchesKDD(String CUID, String KDD) throws TPSException { session.getIpAddress(), "CUID: " + CUID + " does not equal KDD: " + KDD, "failure"); - } } else { //Configured to ignore, report success. @@ -4242,7 +4572,7 @@ protected String getKeyInfoFromTokenDB(String cuid) throws TPSException { keyInfo = tokenRecord.getKeyInfo(); - logger.debug("TPProcessor.getKeyInfioFromTokenDB: returning: " + keyInfo); + logger.debug("TPProcessor.getKeyInfoFromTokenDB: returning: " + keyInfo); return keyInfo; @@ -4252,16 +4582,17 @@ boolean checkCardGPKeyVersionMatchesTokenDB(String CUID, String KDD, String keyInfoData) throws TPSException { String method = "checkCardGPKeyVersionMatchesTokenDB: "; - TPSEngine engine = TPSEngine.getInstance(); - TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); if(CUID == null || KDD == null || keyInfoData == null) { throw new TPSException(method + " Invalid input data!"); } boolean result = true; - - TPSEngineConfig configStore = engine.getConfig(); + + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + + TPSEngineConfig configStore = this.getConfigStore(); String checkValidateVersion = "op." + currentTokenOperation + "." + selectedTokenType + "." + TPSEngine.CFG_VALIDATE_CARD_KEY_INFO_AGAINST_DB; @@ -4278,7 +4609,7 @@ boolean checkCardGPKeyVersionMatchesTokenDB(String CUID, String KDD, logger.debug(method + " config result: " + result); - if(result) { + if(result == true) { //Check only if asked to. String keyInfoInDB = getKeyInfoFromTokenDB(CUID); @@ -4329,7 +4660,6 @@ else if(keyInfoData.compareToIgnoreCase(keyInfoInDB) != 0) { session.getIpAddress(), logMsg, "failure"); - } else { logger.debug(method + " Key Info in the DB IS the same as the one from the token!"); result = true; @@ -4344,7 +4674,6 @@ else if(keyInfoData.compareToIgnoreCase(keyInfoInDB) != 0) { null, // newKeyInfo keyInfoInDB, logMsg); - } } else { @@ -4395,13 +4724,15 @@ private String getSymKeyData(PK11SymKey key) { } */ + private TPSEngineConfig getConfigStore() { + TPSEngine engine = TPSEngine.getInstance(); + TPSEngineConfig configStore = engine.getConfig(); + return configStore; + } protected void auditAuthSuccess(String subjectID, String op, AppletInfo aInfo, String authMgrId) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - TokenAuthEvent event = TokenAuthEvent.success( session.getIpAddress(), subjectID, @@ -4412,6 +4743,8 @@ protected void auditAuthSuccess(String subjectID, String op, (aInfo != null) ? aInfo.getFinalAppletVersion() : null, authMgrId); + TPSEngine engine = TPSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); auditor.log(event); } @@ -4419,9 +4752,6 @@ protected void auditAuthFailure(String subjectID, String op, AppletInfo aInfo, String authMgrId) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - TokenAuthEvent event = TokenAuthEvent.failure( session.getIpAddress(), subjectID, @@ -4432,6 +4762,8 @@ protected void auditAuthFailure(String subjectID, String op, (aInfo != null) ? aInfo.getFinalAppletVersion() : null, authMgrId); + TPSEngine engine = TPSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); auditor.log(event); } @@ -4441,10 +4773,6 @@ protected void auditAuthFailure(String subjectID, String op, protected void auditOpRequest(String op, AppletInfo aInfo, String status, String info) { - - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - String auditType = AuditEvent.TOKEN_OP_REQUEST; String auditMessage = CMS.getLogMessage( @@ -4456,16 +4784,13 @@ protected void auditOpRequest(String op, AppletInfo aInfo, op, (aInfo != null) ? aInfo.getFinalAppletVersion() : null, info); - auditor.log(auditMessage); + audit(auditMessage); } protected void auditFormatSuccess(String subjectID, AppletInfo aInfo, String keyVersion) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - TokenFormatEvent event = TokenFormatEvent.success( session.getIpAddress(), subjectID, @@ -4475,6 +4800,8 @@ protected void auditFormatSuccess(String subjectID, (aInfo != null) ? aInfo.getFinalAppletVersion() : null, keyVersion); + TPSEngine engine = TPSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); auditor.log(event); } @@ -4482,9 +4809,6 @@ protected void auditFormatFailure(String subjectID, AppletInfo aInfo, String info) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - TokenFormatEvent event = TokenFormatEvent.failure( session.getIpAddress(), subjectID, @@ -4494,6 +4818,8 @@ protected void auditFormatFailure(String subjectID, (aInfo != null) ? aInfo.getFinalAppletVersion() : null, info); + TPSEngine engine = TPSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); auditor.log(event); } @@ -4503,9 +4829,6 @@ protected void auditAppletUpgrade(AppletInfo aInfo, String newVersion, String info) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - String auditType; switch (status) { @@ -4528,6 +4851,8 @@ protected void auditAppletUpgrade(AppletInfo aInfo, newVersion, info); + TPSEngine engine = TPSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); auditor.log(event); } @@ -4536,9 +4861,6 @@ protected void auditKeyChangeoverRequired(AppletInfo aInfo, String newKeyVersion, String info) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - String auditType = AuditEvent.TOKEN_KEY_CHANGEOVER_REQUIRED; String auditMessage = CMS.getLogMessage( @@ -4553,7 +4875,7 @@ protected void auditKeyChangeoverRequired(AppletInfo aInfo, oldKeyVersion, newKeyVersion, info); - auditor.log(auditMessage); + audit(auditMessage); } protected void auditKeyChangeover(AppletInfo aInfo, @@ -4562,9 +4884,6 @@ protected void auditKeyChangeover(AppletInfo aInfo, String newKeyVersion, String info) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - String auditType; switch (status) { @@ -4588,6 +4907,8 @@ protected void auditKeyChangeover(AppletInfo aInfo, newKeyVersion, info); + TPSEngine engine = TPSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); auditor.log(event); } @@ -4601,9 +4922,6 @@ protected void auditKeySanityCheck( String tokenDBKeyVersion, String info) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - String auditType; switch(status) { case "success": @@ -4625,7 +4943,7 @@ protected void auditKeySanityCheck( tokenDBKeyVersion, info); - auditor.log(auditMessage); + audit(auditMessage); } /* @@ -4639,9 +4957,6 @@ protected void auditRevoke(String cuid, String caConnId, String info) { - TPSEngine engine = TPSEngine.getInstance(); - Auditor auditor = engine.getAuditor(); - String auditType = AuditEvent.TOKEN_CERT_STATUS_CHANGE_REQUEST; /* * requestType is "revoke", "on-hold", or "off-hold" @@ -4667,7 +4982,580 @@ protected void auditRevoke(String cuid, String.valueOf(revokeReason), caConnId, info); - auditor.log(auditMessage); + audit(auditMessage); + } + + protected TPSBuffer parseAIDResponse(TPSBuffer response) + { + TPSBuffer aid = new TPSBuffer(); + + // Response starts with 0x6F + if (response.at(0) == (byte) 0x6F) + { + for(int i = 1; i < response.size(); i++) + { + // Find 0x84, AID follows that + if (response.at(i) == (byte) 0x84) + { + // Next byte is length of AID + int len = response.at(i+1); + + // Grab the AID bytes + aid = response.substr(i+2,len); + break; + } + } + } + else + { + logger.debug("TPSProcessor.parseAIDResponse: select AID response missing mandatory data, cannot parse response!"); + } + return aid; + } + + /** + * Signed Audit Log + * + * This method is called to store messages to the signed audit log. + *

+ * + * @param msg signed audit log message + */ + protected void audit(String msg) { + TPSEngine engine = TPSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); + auditor.log(msg); + } + + protected void audit(LogEvent event) { + TPSEngine engine = TPSEngine.getInstance(); + Auditor auditor = engine.getAuditor(); + auditor.log(event); + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method returns the configured keySet name for the purpose of + * downgrading the 256 OMK to 128 FMK. If such a configuration is not found, + * an empty string will be returned and the downgrade is disallowed. + * + * @return the keySet name + * @throws TPSException + */ + protected String getKeyDowngradeKeySet() throws TPSException { + String method = "TPSProcessor.getKeyDowngradeKeySet: "; + TPSEngineConfig configStore = this.getConfigStore(); + String config = "symKey.downgrade.keySet"; + String keySet; + try { + keySet = configStore.getString(config, ""); + } catch (EBaseException e) { + throw new TPSException(method + "Internal error finding config value:" + config, + TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + logger.debug(method + " returning " + keySet); + return keySet; + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method returns the configured key version to downgrade to for the + * purpose of downgrading the 256 OMK to 128 FMK. If such a configuration + * is not found, key version 3 will be returned as the default FMK version. + * + * @return the key version to downgrade to + * @throws TPSException + */ + protected int getKeyDowngradeVersion() throws TPSException { + String method = "TPSProcessor.getKeyDowngradeVersion: "; + TPSEngineConfig configStore = this.getConfigStore(); + int ver; + String config = "symKey.downgrade.keyVer"; + try { + ver = configStore.getInteger(config, 0x03); + } catch (EBaseException e) { + throw new TPSException(method + "Internal error finding config value:" + config, + TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + logger.debug(method + " returning " + ver); + return ver; + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method returns the configured temporary key slot/version used in the key + * downgrade process for the purpose of downgrading the 256 OMK to 128 FMK. + * If such a configuration is not found, key slot/version 5 will be returned. + * + * @return + * @throws TPSException + */ + protected int getKeyDowngradeTempSlot() throws TPSException { + String method = "TPSProcessor.getKeyDowngradeTempSlot: "; + TPSEngineConfig configStore = this.getConfigStore(); + int slot; + String config = "symKey.downgrade.temp.slot"; + try { + slot = configStore.getInteger(config, 0x5); + } catch (EBaseException e) { + throw new TPSException(method + "Internal error finding config value:" + config, + TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + logger.debug(method + " returning " + slot); + return slot; + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method returns the configured keySet name for the purpose of rolling + * over symmetric key size from 128 to 256. If such a configuration is not + * found, an empty string will be returned and the key upgrade is disallowed. + * + * @return the keySet name + * @throws TPSException + */ + protected String getKeyRolloverKeySet() throws TPSException { + String method = "TPSProcessor.getKeyRolloverKeySet: "; + TPSEngineConfig configStore = this.getConfigStore(); + String config = "symKey.rollover.keySet"; + String keySet; + try { + keySet = configStore.getString(config, ""); + } catch (EBaseException e) { + throw new TPSException(method + "Internal error finding config value:" + config, + TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + logger.debug(method + " returning " + keySet); + return keySet; + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method returns the configured key version to upgrade to for the + * purpose of rolling over symmetric key size from 128 to 256. If such a + * configuration is not found, key version 0x21 will be returned as the + * default OMK version. + * + * @return the key version to roll over to + * @throws TPSException + */ + protected int getKeyRolloverVersion() throws TPSException { + String method = "TPSProcessor.getKeyRolloverVersion: "; + TPSEngineConfig configStore = this.getConfigStore(); + int ver; + String config = "symKey.rollover.keyVer"; + try { + ver = configStore.getInteger(config, 0x21); + } catch (EBaseException e) { + throw new TPSException(method + "Internal error finding config value:" + config, + TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + logger.debug(method + " returning " + ver); + return ver; + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method returns the configured temporary key slot/version used in the key + * upgrade process for the purpose of rolling over symmetric key size from 128 to 256. + * If such a configuration is not found, key slot/version 3 will be returned. + * + * @return + * @throws TPSException + */ + protected int getKeyRolloverTempSlot() throws TPSException { + String method = "TPSProcessor.getKeyRolloverTempSlot: "; + TPSEngineConfig configStore = this.getConfigStore(); + int slot; + String config = "symKey.rollover.temp.slot"; + try { + slot = configStore.getInteger(config, 0x3); + } catch (EBaseException e) { + throw new TPSException(method + "Internal error finding config value:" + config, + TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + logger.debug(method + " returning " + slot); + return slot; + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method gets the key info template on the card and returns it. + * + * @return the TPSBuffer that contains the key info template + * @throws TPSException + * @throws IOException + */ + protected TPSBuffer getKeyInfoTemplate() throws TPSException, IOException { + // If card manager is not selected, select it + if (getSelectedCardMgr().size() == 0) { + selectDefaultCardManager(); + } + // If it was selected already, make sure it is the one used here + else { + selectCardMgr(getSelectedCardMgr()); + } + return getData(SecureChannel.GP211_GET_DATA_KEY_INFO); + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method returns the symmetric key size (e.g. 128 or 256 bits) on the card. + * The key size is calculated by extracting the octet length from the key info + * template on card and multiplying it by 8. + * + * @param cuid the token CUID (for debug logging) + * @return the symmetric key length on the card (e.g. 128 or 256) + * @throws TPSException + * @throws IOException + */ + protected Integer getCardSymKeyLength(String cuid) throws TPSException, IOException { + String method = "TPSProcessor.getCardSymKeyLength: CUID: " + cuid + ": "; + + TPSBuffer keyData; + if (platProtInfo != null) { + keyData = platProtInfo.getKeysetInfoData(); + logger.debug(method + " key info template from platProtInfo: " + keyData.toHexString()); + } + else { + keyData = getKeyInfoTemplate(); + logger.debug(method + " key info template from getData: " + keyData.toHexString()); + } + + Integer symKeyLen = null; + + // example for key info template: + // E0%12%C0%04%01%21%88%20%C0%04%02%21%88%20%C0%04%03%21%88%20%90%00% + // Byte 7 is the key octet length (0x20 in the example above) + int keyLenOffset = 7; + if (keyData.size() > keyLenOffset) { + int keyOctetLen = keyData.getIntFrom1Byte(keyLenOffset); + logger.debug(method + " key octet length: " + keyOctetLen); + symKeyLen = keyOctetLen * 8; + } + return symKeyLen; + } + + /** + * ** G&D 256 Key Rollover Support ** + * This method downgrades the symmetric key size for the purpose of rolling the 256 OMK back to + * 128 FMK. + * + * @param appletInfo + * @param tokenRecord + * @param requiredVersion + * @param defKeyIndex + * @param connId + * @return the SecureChannel set up with the 128 FMK + * @throws TPSException + * @throws IOException + */ + protected SecureChannel downgradeSymKeySize(AppletInfo appletInfo, TokenRecord tokenRecord, int requiredVersion, int defKeyIndex, String connId) throws TPSException, IOException { + String method = "TPSProcessor.downgradeSymKeySize: CUID: " + tokenRecord.getId() + ": "; + SecureChannel channel = null; + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + String oldKeySet = getSelectedKeySet(); + String newKeySet = oldKeySet; + try { + // find keySet name for the 128-bit sym key + String resolverInstName = getKeySetResolverInstanceName(); + if (!resolverInstName.equals("none")) { + FilterMappingParams mappingParams = createFilterMappingParams(resolverInstName, + appletInfo.getCUIDhexStringPlain(), appletInfo.getMSNString(), + appletInfo.getMajorVersion(), appletInfo.getMinorVersion()); + TPSSubsystem subsystem = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + BaseMappingResolver resolverInst = + subsystem.getMappingResolverManager().getResolverInstance(resolverInstName); + + newKeySet = resolverInst.getResolvedMapping(mappingParams, "keySet", 128); + logger.debug(method + " resolved keySet: " + newKeySet); + } else { + throw new TPSException("Invalid keySet resolver instance name: " + resolverInstName, TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + } catch (TPSException e) { + tps.tdb.tdbActivity(ActivityDatabase.OP_FORMAT, tokenRecord, session.getIpAddress(), e.toString(), + "failure"); + throw new TPSException(e.toString(), TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + + // Make sure correct card manager is selected + if (getSelectedCardMgr().size() == 0) { + selectDefaultCardManager(); + } + else { + selectCardMgr(getSelectedCardMgr()); + } + appletInfo.setAid(getSelectedCardMgr()); + + channel = setupSecureChannel(appletInfo); + auditKeyChangeoverRequired(appletInfo, channel.getKeyInfoData().toHexStringPlain(), getSymmetricKeysRequiredVersionHexString(), null); + + // get the temporary slot (key version) where keys will be added to + byte tmpVer = (byte)getKeyDowngradeTempSlot(); + + int protocol = 3; + TPSBuffer curKeyInfo = channel.getKeyInfoData(); + logger.debug(method + " curKeyInfo: " + curKeyInfo.toHexString()); + + byte[] nv = new byte[] { (byte)requiredVersion, curKeyInfo.at(1), curKeyInfo.at(2) }; + TPSBuffer newVersion = new TPSBuffer(nv); + logger.debug(method + " newVersion: " + newVersion.toHexString()); + + // get key data from TKS + TPSBuffer keySetData = engine.createKeySetData(newVersion, curKeyInfo, protocol, + appletInfo.getCUID(),channel.getKeyDiversificationData(), channel.getDekSessionKeyWrapped(), connId, newKeySet, oldKeySet); + logger.debug(method + " new keySetData from TKS: " + keySetData.substr(0, 4).toHexString() + "..."); + + // change the 1st byte of keySetData to the configured temporary key version (slot where keys to be added to) + TPSBuffer modKeySetData = new TPSBuffer(keySetData); + modKeySetData.setAt(0, (byte)tmpVer); + logger.debug(method + " modified keySetData from TKS before add key: " + modKeySetData.substr(0, 4).toHexString() + "..."); + + try { + // step 1: add the new keys (note: 1st param 0x0 is for add, 2nd param is not used in putKeys) + channel.putKeys((byte)0x0, curKeyInfo.at(1), modKeySetData); + logger.debug(method + " successfully added keys to slot " + tmpVer); + } catch (TPSException | IOException e) { + logger.debug(method + " failed to add key to slot " + tmpVer + ": " + e.getMessage()); + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), + "Failed to send new GP Key Set to token", "failure"); + throw e; + } + + try { + // step 2: delete keys at the current version + channel.deleteKeys(curKeyInfo.at(0)); + logger.debug(method + " successfully deleted keys in slot " + curKeyInfo.at(0)); + } catch (TPSException | IOException e) { + logger.debug(method + " failed to delete keys in slot " + curKeyInfo.at(0) + ": " + e.getMessage()); + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), + "Failed to delete GP Key Set from token", "failure"); + throw e; + } + + try { + // step 3: replace the current version/slot with the new key added in step 1 + channel.putKeys(tmpVer, curKeyInfo.at(1), keySetData); + logger.debug(method + " successfully replaced key in slot " + tmpVer + " with key in " + keySetData.at(0)); + } catch (TPSException | IOException e) { + logger.debug(method + " failed to replace keys in slot " + tmpVer + " with key in " + keySetData.at(0) + ": " + e.getMessage()); + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), + "Failed to send new GP Key Set to token", "failure"); + throw e; + } + + // log key changeover event + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), + "Sent new GP Key Set to token", "success"); + + logger.debug(method + " key info template: " + getKeyInfoTemplate().toHexString()); + + logger.debug(method + " changing token db keyInfo to: " + newVersion.toHexStringPlain()); + tokenRecord.setKeyInfo(newVersion.toHexStringPlain()); + + // change the selected keySet name to the new keySet name before calling setupSecureChannel + setSelectedKeySet(newKeySet); + + selectCoolKeyApplet(); + + channel = setupSecureChannel(newVersion.at(0), (byte)defKeyIndex, connId, appletInfo); + + logger.debug(method + " done setupSecureChannel with version " + newVersion.at(0)); + + auditKeyChangeover(appletInfo, "success", curKeyInfo.toHexString(), newVersion.toHexString(), null); + + return channel; + } + + + /** + * ** G&D 256 Key Rollover Support ** + * This method upgrade the symmetric key size for the purpose of rolling the 128 OMK to 256 OMK. + * The steps include adding the 256-bit keys to a temporary slot (e.g. v3), deleting the current + * version 128-bit key, and replacing current version with the 256-bit keys. + * + * @param appletInfo + * @param tokenRecord + * @param requiredVersion + * @param defKeyIndex + * @param connId + * @return the SecureChannel set up with new 256-bit key + * @throws TPSException + * @throws IOException + * + */ + protected SecureChannel upgradeSymKeySize(AppletInfo appletInfo, TokenRecord tokenRecord, int requiredVersion, int defKeyIndex, String connId) throws TPSException, IOException { + String method = "TPSProcessor.upgradeSymKeySize: CUID: " + tokenRecord.getId() + ": "; + SecureChannel channel = null; + TPSEngine engine = TPSEngine.getInstance(); + TPSSubsystem tps = (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + + String oldKeySet = getSelectedKeySet(); + String newKeySet = oldKeySet; + try { + // find keySet name for the 256-bit sym key + String resolverInstName = getKeySetResolverInstanceName(); + if (resolverInstName != null && !resolverInstName.equals("none")) { + FilterMappingParams mappingParams = createFilterMappingParams(resolverInstName, + appletInfo.getCUIDhexStringPlain(), appletInfo.getMSNString(), + appletInfo.getMajorVersion(), appletInfo.getMinorVersion()); + TPSSubsystem subsystem = + (TPSSubsystem) engine.getSubsystem(TPSSubsystem.ID); + BaseMappingResolver resolverInst = + subsystem.getMappingResolverManager().getResolverInstance(resolverInstName); + + newKeySet = resolverInst.getResolvedMapping(mappingParams, "keySet", 256); + logger.debug(method + " resolved keySet: " + newKeySet); + } else { + throw new TPSException("Invalid keySet resolver instance name: " + resolverInstName, TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + } catch (TPSException e) { + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), e.toString(), + "failure"); + throw new TPSException(e.toString(), TPSStatus.STATUS_ERROR_MISCONFIGURATION); + } + + // Make sure correct card manager is selected + if (getSelectedCardMgr().size() == 0) { + selectDefaultCardManager(); + } + else { + selectCardMgr(getSelectedCardMgr()); + } + appletInfo.setAid(getSelectedCardMgr()); + + channel = setupSecureChannel(appletInfo); + auditKeyChangeoverRequired(appletInfo, channel.getKeyInfoData().toHexStringPlain(), getSymmetricKeysRequiredVersionHexString(), null); + + // get the temporary slot (key version) where keys will be added to + byte tmpVer = (byte)getKeyRolloverTempSlot(); + + int protocol = 3; + TPSBuffer curKeyInfo = channel.getKeyInfoData(); + logger.debug(method + " curKeyInfo: " + curKeyInfo.toHexString()); + + byte[] nv = new byte[] { (byte)requiredVersion, curKeyInfo.at(1), curKeyInfo.at(2) }; + TPSBuffer newVersion = new TPSBuffer(nv); + logger.debug(method + " newVersion: " + newVersion.toHexString()); + + // get key data from TKS + TPSBuffer keySetData = engine.createKeySetData(newVersion, curKeyInfo, protocol, + appletInfo.getCUID(),channel.getKeyDiversificationData(), channel.getDekSessionKeyWrapped(), connId, newKeySet, oldKeySet); + logger.debug(method + " new keySetData from TKS: " + keySetData.substr(0, 4).toHexString() + "..."); + + // change the 1st byte of keySetData to the configured temporary key version (slot where keys to be added to) + TPSBuffer modKeySetData = new TPSBuffer(keySetData); + modKeySetData.setAt(0, (byte)tmpVer); + logger.debug(method + " modified keySetData from TKS before add key: " + modKeySetData.substr(0, 4).toHexString() + "..."); + + try { + // step 1: add new 256 OMK to temp slot or 3 (note: 1st param 0x0 is for add, 2nd param is not used in putKeys) + channel.putKeys((byte)0x0, curKeyInfo.at(1), modKeySetData); + logger.debug(method + " successfully added keys to slot " + tmpVer); + } catch (TPSException | IOException e) { + logger.debug(method + " failed to add key to slot " + tmpVer + ": " + e.getMessage()); + + // Attempt to recover from previous upgrade failure: + // Check whether the exception is caused by the previous failure during deleteKeys. + // The previous deleteKeys failure can be determined by the number of keys in + // the key info template. There are 3 keys in each set of keys. If 2 sets of keys (6 keys) + // are in the key info template, then we can proceed with deleteKeys. + boolean errorOutNow = true; + if (platProtInfo != null) { + TPSBuffer keyTemplateOnCard = platProtInfo.getKeysetInfoData(); + logger.debug(method + " key template on card: " + keyTemplateOnCard.toHexString()); + + // The 2nd byte in the key info template tells the total number of bytes of all the keys. + // Each key is made up of 6 bytes in the template. + byte dataLength = keyTemplateOnCard.at(1); + logger.debug(method + " data length: " + String.format("%02X", dataLength)); + + // if 2 sets of keys on card (0x24 = 36; 36/6 = 6 keys), + // try to recover from previous failure by continuing to delete keys + if (dataLength == (byte) 0x24) + { + logger.debug(method + " Found 2 sets of keys on card. Try to delete keys"); + errorOutNow = false; + } + } + // If exception is not caused by previous deleteKeys failure, throw the exception + if (errorOutNow) + { + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), + "Failed to send new GP Key Set to token", "failure"); + throw e; + } + } + + try { + // Step 2: delete the 128 OMK in current slot (S21) + channel.deleteKeys(curKeyInfo.at(0)); + logger.debug(method + " successfully deleted keys in slot " + curKeyInfo.at(0)); + } catch (TPSException | IOException e) { + logger.debug(method + " failed to delete keys in slot " + curKeyInfo.at(0) + ": " + e.getMessage()); + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), + "Failed to delete GP Key Set from token", "failure"); + throw e; + } + + try { + // Step 3: replace key: move the 256 OMK from temp slot (S3) to the current slot (S21) + channel.putKeys(tmpVer, curKeyInfo.at(1), keySetData); + logger.debug(method + " successfully replaced keys in slot " + tmpVer + " with keys in " + keySetData.at(0)); + } catch (TPSException | IOException e) { + logger.debug(method + " failed to replace keys in slot " + tmpVer + " with key in " + keySetData.at(0) + ": " + e.getMessage()); + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), + "Failed to send new GP Key Set to token", "failure"); + throw e; + } + + // log key changeover event + tps.tdb.tdbActivity(ActivityDatabase.OP_KEY_CHANGEOVER, tokenRecord, session.getIpAddress(), + "Sent new GP Key Set to token", "success"); + + logger.debug(method + " key info template: " + getKeyInfoTemplate().toHexString()); + + logger.debug(method + " changing token db keyInfo to: " + newVersion.toHexStringPlain()); + tokenRecord.setKeyInfo(newVersion.toHexStringPlain()); + + // change the selected keySet name to the new 256 keySet name before calling setupSecureChannel + setSelectedKeySet(newKeySet); + + // this is needed for using the secure channel to set the PIN on token + selectCoolKeyApplet(); + + // create the secure channel with S21:256 OMK + channel = setupSecureChannel(newVersion.at(0), (byte)defKeyIndex, connId, appletInfo); + + logger.debug(method + " done setupSecureChannel with version " + newVersion.at(0)); + + auditKeyChangeover(appletInfo, "success", curKeyInfo.toHexString(), newVersion.toHexString(), null); + + return channel; + } + + // ** Applet and Alg Selection by Token Range Support ** + protected void setSelectedKeyWrapAlg(String theKeyWrapAlg) { + selectedKeyWrapAlg = theKeyWrapAlg; + } + + public String getSelectedKeyWrapAlg() { + return selectedKeyWrapAlg; + } + + protected void setSelectedAppletVer(String theAppletVer) { + selectedAppletVer = theAppletVer; + } + + public String getSelectedAppletVer() { + return selectedAppletVer; + } + + public boolean isDesConfigured() { + boolean configured = (selectedKeyWrapAlg != null && selectedKeyWrapAlg.equalsIgnoreCase("DES")); + logger.debug("TPSProcessor.isDesConfigured: returning " + configured); + return configured; } public static void main(String[] args) {