diff options
author | PKI Team <PKI Team@c9f7a03b-bd48-0410-a16d-cbbf54688b0b> | 2008-03-18 22:36:57 +0000 |
---|---|---|
committer | PKI Team <PKI Team@c9f7a03b-bd48-0410-a16d-cbbf54688b0b> | 2008-03-18 22:36:57 +0000 |
commit | d0f2e4efbd3eb0f1d7f5a28e7f97c1fb4ec027bb (patch) | |
tree | 7e7473fae8af5ad7e6cda7eabbef787093fc59a7 /pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java | |
parent | 273f8d85df5c31293a908185622b378c8f3cf7e8 (diff) | |
download | pki-d0f2e4efbd3eb0f1d7f5a28e7f97c1fb4ec027bb.tar.gz pki-d0f2e4efbd3eb0f1d7f5a28e7f97c1fb4ec027bb.tar.xz pki-d0f2e4efbd3eb0f1d7f5a28e7f97c1fb4ec027bb.zip |
Initial open source version based upon proprietary Red Hat Certificate System (RHCS) 7.3.
git-svn-id: svn+ssh://svn.fedorahosted.org/svn/pki/trunk@2 c9f7a03b-bd48-0410-a16d-cbbf54688b0b
Diffstat (limited to 'pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java')
-rw-r--r-- | pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java | 556 |
1 files changed, 556 insertions, 0 deletions
diff --git a/pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java b/pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java new file mode 100644 index 000000000..59f3a0a55 --- /dev/null +++ b/pki/base/kra/src/com/netscape/kra/NetkeyKeygenService.java @@ -0,0 +1,556 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.kra; + + +import com.netscape.cmscore.util.Debug; +import java.util.StringTokenizer; +import java.util.Vector; +import java.io.IOException; +import java.io.ByteArrayInputStream; + +import java.math.BigInteger; +import java.security.*; +import java.security.KeyPair; +import java.security.cert.CertificateException; +import netscape.security.util.*; +import netscape.security.util.BigInt; +import netscape.security.pkcs.*; +import netscape.security.x509.*; +import netscape.security.provider.*; +import org.mozilla.jss.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.crypto.PrivateKey; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.crypto.KeyPairGenerator; +import org.mozilla.jss.pkix.crmf.*; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.pkix.primitive.AVA; +import org.mozilla.jss.pkcs11.*; +import com.netscape.certsrv.common.*; +import com.netscape.cmscore.util.*; +import com.netscape.certsrv.logging.*; +import com.netscape.certsrv.security.*; +import com.netscape.cmscore.crmf.*; +import com.netscape.certsrv.kra.*; +import com.netscape.certsrv.base.*; +import com.netscape.cmscore.cert.*; +//import com.netscape.cmscore.ca.*; +import com.netscape.cmscore.dbs.*; +import com.netscape.certsrv.dbs.*; +import com.netscape.certsrv.dbs.repository.*; +import com.netscape.certsrv.profile.*; +import com.netscape.certsrv.dbs.keydb.*; +import com.netscape.certsrv.request.*; +import com.netscape.certsrv.policy.*; +import com.netscape.certsrv.authentication.*; +import com.netscape.certsrv.apps.*; +import com.netscape.certsrv.apps.CMS; + +//for b64 encoding +import org.mozilla.jss.util.Base64OutputStream; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.*; + +/** + * A class representing keygen/archival request procesor for requests + * from netkey RAs. + * the user private key of the encryption cert is wrapped with a + * session symmetric key. The session symmetric key is wrapped with the + * storage key and stored in the internal database for long term + * storage. + * The user private key of the encryption cert is to be wrapped with the + * DES key which came in in the request wrapped with the KRA + * transport cert. The wrapped user private key is then sent back to + * the caller (netkey RA) ...netkey RA should already has kek-wrapped + * des key from the TKS. They are to be sent together back to + * the token. + * + * @author Christina Fu (cfu) + * @version $Revision: 14563 $, $Date: 2007-05-01 10:35:23 -0700 (Tue, 01 May 2007) $ + */ + +public class NetkeyKeygenService implements IService { + public final static String ATTR_KEY_RECORD = "keyRecord"; + public final static String ATTR_PROOF_OF_ARCHIVAL = + "proofOfArchival"; + + // private + private final static String + LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST = + "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_REQUEST_4"; + private final static String + LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_PROCESSED = + "LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_PROCESSED_3"; + // these need to be defined in LogMessages_en.properties later when we do this + private final static String + LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST = + "LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST_3"; + private final static String + LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_PROCESSED = + "LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_PROCESSED_3"; + private IKeyRecoveryAuthority mKRA = null; + private ITransportKeyUnit mTransportUnit = null; + private IStorageKeyUnit mStorageUnit = null; + private ILogger mSignedAuditLogger = CMS.getSignedAuditLogger(); + + /** + * Constructs request processor. + * <P> + * + * @param kra key recovery authority + */ + public NetkeyKeygenService(IKeyRecoveryAuthority kra) { + mKRA = kra; + mTransportUnit = kra.getTransportKeyUnit(); + mStorageUnit = kra.getStorageKeyUnit(); + } + + public PKIArchiveOptions toPKIArchiveOptions(byte options[]) { + ByteArrayInputStream bis = new ByteArrayInputStream(options); + PKIArchiveOptions archOpts = null; + + try { + archOpts = (PKIArchiveOptions) + (new PKIArchiveOptions.Template()).decode(bis); + } catch (Exception e) { + CMS.debug("NetkeyKeygenService: getPKIArchiveOptions " + e.toString()); + } + return archOpts; + } + + public KeyPair generateKeyPair( + KeyPairAlgorithm kpAlg, int keySize, PQGParams pqg) + throws NoSuchAlgorithmException, TokenException, InvalidAlgorithmParameterException, + InvalidParameterException, PQGParamGenException { + + CryptoToken token = mKRA.getKeygenToken(); + + CMS.debug("NetkeyKeygenService: key pair is to be generated on slot: "+token.getName()); + KeyPairGenerator kpGen = token.getKeyPairGenerator(kpAlg); + // make it temporary so can work with HSM + kpGen.temporaryPairs(true); + kpGen.sensitivePairs(true); + kpGen.extractablePairs(true); + + if (kpAlg == KeyPairAlgorithm.DSA) { + if (pqg == null) { + kpGen.initialize(keySize); + } else { + kpGen.initialize(pqg); + } + } else { + kpGen.initialize(keySize); + } + + if (pqg == null) { + KeyPair kp; + synchronized (new Object()) { + kp = kpGen.genKeyPair(); + mKRA.addEntropy(true); + } + return kp; + } else { + // DSA + KeyPair kp = null; + + /* no DSA for now... netkey prototype + do { + // 602548 NSS bug - to overcome it, we use isBadDSAKeyPair + kp = kpGen.genKeyPair(); + } + while (isBadDSAKeyPair(kp)); + */ + return kp; + } + } + + + + public KeyPair generateKeyPair( String alg, + int keySize, PQGParams pqg) throws EBaseException { + + KeyPairAlgorithm kpAlg = null; + + if (alg.equals("RSA")) + kpAlg = KeyPairAlgorithm.RSA; + else + kpAlg = KeyPairAlgorithm.DSA; + + try { + KeyPair kp = generateKeyPair( kpAlg, keySize, pqg); + + return kp; + } catch (InvalidParameterException e) { + throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEYSIZE_PARAMS", + "" + keySize)); + } catch (PQGParamGenException e) { + throw new EBaseException(CMS.getUserMessage("CMS_BASE_PQG_GEN_FAILED")); + } catch (NoSuchAlgorithmException e) { + throw new EBaseException(CMS.getUserMessage("CMS_BASE_ALG_NOT_SUPPORTED", + kpAlg.toString())); + } catch (TokenException e) { + throw new EBaseException(CMS.getUserMessage("CMS_BASE_TOKEN_ERROR_1", e.toString())); + } catch (InvalidAlgorithmParameterException e) { + throw new EBaseException(CMS.getUserMessage("CMS_BASE_ALG_NOT_SUPPORTED", "DSA")); + } + } + + private static String base64Encode(byte[] bytes) throws IOException { + // All this streaming is lame, but Base64OutputStream needs a + // PrintStream + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Base64OutputStream b64 = new Base64OutputStream(new + PrintStream(new + FilterOutputStream(output) + ) + ); + + b64.write(bytes); + b64.flush(); + + // This is internationally safe because Base64 chars are + // contained within 8859_1 + return output.toString("8859_1"); + } + + // this encrypts bytes with a symmetric key + public byte[] encryptIt(byte[] toBeEncrypted, SymmetricKey symKey, CryptoToken token, + IVParameterSpec IV) + { + try { + Cipher cipher = token.getCipherContext( + EncryptionAlgorithm.DES3_CBC_PAD); + + cipher.initEncrypt(symKey, IV); + byte pri[] = cipher.doFinal(toBeEncrypted); + return pri; + } catch (Exception e) { + CMS.debug("NetkeyKeygenService:initEncrypt() threw exception: "+e.toString()); + return null; + } + + } + + + /** + * Services an archival request from netkey. + * <P> + * + * @param request enrollment request + * @return serving successful or not + * @exception EBaseException failed to serve + */ + public boolean serviceRequest(IRequest request) + throws EBaseException { + String auditMessage = null; + String auditSubjectID = null; + String auditRequesterID = "TPSagent"; + String auditArchiveID = ILogger.UNIDENTIFIED; + String auditPublicKey = ILogger.UNIDENTIFIED; + byte[] wrapped_des_key; + + byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1}; + String iv_s =""; +/* + org.mozilla.jss.pkcs11.PK11SecureRandom random = + new org.mozilla.jss.pkcs11.PK11SecureRandom(); + random.nextBytes(iv); +*/ + + IVParameterSpec algParam = new IVParameterSpec(iv); + + wrapped_des_key = null; + boolean archive = true; + PK11SymKey sk= null; + byte[] publicKeyData = null;; + String PubKey = ""; + + String id = request.getRequestId().toString(); + if (id != null) { + auditArchiveID = id.trim(); + } + + String rArchive = request.getExtDataInString(IRequest.NETKEY_ATTR_ARCHIVE_FLAG); + if (rArchive.equals("true")) { + archive = true; + CMS.debug("NetkeyKeygenService: serviceRequest " +"archival requested for serverSideKeyGen"); + } else { + archive = false; + CMS.debug("NetkeyKeygenService: serviceRequest " +"archival not requested for serverSideKeyGen"); + } + + String rCUID = request.getExtDataInString(IRequest.NETKEY_ATTR_CUID); + String rUserid = request.getExtDataInString(IRequest.NETKEY_ATTR_USERID); + String rKeysize = request.getExtDataInString(IRequest.NETKEY_ATTR_KEY_SIZE); + int keysize = Integer.parseInt(rKeysize); + auditSubjectID=rCUID+":"+rUserid; + + SessionContext sContext = SessionContext.getContext(); + String agentId=""; + if (sContext != null) { + agentId = + (String) sContext.get(SessionContext.USER_ID); + } + + auditMessage = CMS.getLogMessage( + LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_REQUEST, + auditSubjectID, + ILogger.SUCCESS, + agentId); + + audit(auditMessage); + + + String rWrappedDesKeyString = request.getExtDataInString(IRequest.NETKEY_ATTR_DRMTRANS_DES_KEY); + // CMS.debug("NetkeyKeygenService: received DRM-trans-wrapped DES key ="+rWrappedDesKeyString); + wrapped_des_key = com.netscape.cmsutil.util.Utils.SpecialDecode(rWrappedDesKeyString); + CMS.debug("NetkeyKeygenService: wrapped_des_key specialDecoded"); + + // get the token for generating user keys + CryptoToken keygenToken = mKRA.getKeygenToken(); + if (keygenToken == null) { + CMS.debug("NetkeyKeygenService: failed getting keygenToken"); + request.setExtData(IRequest.RESULT, Integer.valueOf(10)); + return false; + } else + CMS.debug("NetkeyKeygenService: got keygenToken"); + + if ((wrapped_des_key != null) && + (wrapped_des_key.length > 0)) { + + // unwrap the DES key + sk= (PK11SymKey) mTransportUnit.unwrap_sym(wrapped_des_key); + + /* XXX could be done in HSM*/ + KeyPair keypair = null; + + CMS.debug("NetkeyKeygenService: about to generate key pair"); + + keypair = generateKeyPair("RSA"/*alg*/, + keysize /*Integer.parseInt(len)*/, null /*pqgParams*/); + + if (keypair == null) { + CMS.debug("NetkeyKeygenService: failed generating key pair for "+rCUID+":"+rUserid); + request.setExtData(IRequest.RESULT, Integer.valueOf(4)); + + auditMessage = CMS.getLogMessage( + LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_PROCESSED, + auditSubjectID, + ILogger.FAILURE, + agentId); + + audit(auditMessage); + + return false; + } else { + CMS.debug("NetkeyKeygenService: finished generate key pair for " +rCUID+":"+rUserid); + CMS.debug("NetkeyKeygenService: server-side key generated at keysize "+keysize); + + auditMessage = CMS.getLogMessage( + LOGGING_SIGNED_AUDIT_SERVER_SIDE_KEYGEN_PROCESSED, + auditSubjectID, + ILogger.SUCCESS, + agentId); + + audit(auditMessage); + + } + + //...extract the private key handle (not privatekeydata) + java.security.PrivateKey privKey = + keypair.getPrivate(); + + if (privKey == null) { + request.setExtData(IRequest.RESULT, Integer.valueOf(4)); + CMS.debug("NetkeyKeygenService: failed getting private key"); + return false; + } else { + CMS.debug("NetkeyKeygenService: got private key"); + } + + try { + + if (sk == null) { + CMS.debug("NetkeyKeygenService: no DES key"); + request.setExtData(IRequest.RESULT, Integer.valueOf(4)); + return false; + } else { + CMS.debug("NetkeyKeygenService: received DES key"); + } + + // 3 wrapping should be done in HSM + // wrap private key with DES + KeyWrapper symWrap = + keygenToken.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD); + CMS.debug("NetkeyKeygenService: wrapper token=" + keygenToken.getName()); + CMS.debug("NetkeyKeygenService: got key wrapper"); + + CMS.debug("NetkeyKeygenService: key transport key is on slot: "+sk.getOwningToken().getName()); + symWrap.initWrap((SymmetricKey)sk, algParam); + byte wrapped[] = symWrap.wrap((PrivateKey)privKey); + /* + CMS.debug("NetkeyKeygenService: wrap called"); + CMS.debug(wrapped); + */ + /* This is for using with my decryption tool and ASN1 + decoder to see if the private key is indeed PKCS#8 format + { // cfu debug + String oFilePath = "/tmp/wrappedPrivKey.bin"; + File file = new File(oFilePath); + FileOutputStream ostream = new FileOutputStream(oFilePath); + ostream.write(wrapped); + ostream.close(); + } + */ + String wrappedPrivKeyString = /*base64Encode(wrapped);*/ + com.netscape.cmsutil.util.Utils.SpecialEncode(wrapped); + if (wrappedPrivKeyString == null) { + request.setExtData(IRequest.RESULT, Integer.valueOf(4)); + CMS.debug("NetkeyKeygenService: failed generating wrapped private key"); + return false; + } else { + request.setExtData("wrappedUserPrivate", wrappedPrivKeyString); + } + + publicKeyData = keypair.getPublic().getEncoded(); + if (publicKeyData == null) { + request.setExtData(IRequest.RESULT, Integer.valueOf(4)); + CMS.debug("NetkeyKeygenService: failed getting publickey encoded"); + return false; + } else { + //CMS.debug("NetkeyKeygenService: public key binary length ="+ publicKeyData.length); + PubKey = base64Encode(publicKeyData); + + //CMS.debug("NetkeyKeygenService: public key length =" + PubKey.length()); + request.setExtData("public_key", PubKey); + } + + iv_s = /*base64Encode(iv);*/com.netscape.cmsutil.util.Utils.SpecialEncode(iv); + request.setExtData("iv_s", iv_s); + + + /* + * archival - option flag "archive" controllable by the caller - TPS + */ + if (archive) { + // + // privateKeyData ::= SEQUENCE { + // sessionKey OCTET_STRING, + // encKey OCTET_STRING, + // } + // + // mKRA.log(ILogger.LL_INFO, "KRA encrypts internal private"); + + CMS.debug("KRA encrypts private key to put on internal ldap db"); + byte privateKeyData[] = + mStorageUnit.wrap((org.mozilla.jss.crypto.PrivateKey) privKey); + + if (privateKeyData == null) { + request.setExtData(IRequest.RESULT, Integer.valueOf(4)); + CMS.debug("NetkeyKeygenService: privatekey encryption by storage unit failed"); + return false; + } else + CMS.debug("NetkeyKeygenService: privatekey encryption by storage unit successful"); + + // create key record + KeyRecord rec = new KeyRecord(null, publicKeyData, + privateKeyData, rCUID+":"+rUserid, + keypair.getPublic().getAlgorithm(), + agentId); + + if (rec == null) { + request.setExtData(IRequest.RESULT, Integer.valueOf(11)); + CMS.debug("NetkeyKeygenService: privatekey recording failed"); + return false; + } else + CMS.debug("NetkeyKeygenService: got key record"); + + // we deal with RSA key only + try { + RSAPublicKey rsaPublicKey = new RSAPublicKey(publicKeyData); + + rec.setKeySize(Integer.valueOf(rsaPublicKey.getKeySize())); + } catch (InvalidKeyException e) { + request.setExtData(IRequest.RESULT, Integer.valueOf(11)); + CMS.debug("NetkeyKeygenService: failed:InvalidKeyException"); + return false; + } + //?? + IKeyRepository storage = mKRA.getKeyRepository(); + BigInteger serialNo = storage.getNextSerialNumber(); + + if (serialNo == null) { + request.setExtData(IRequest.RESULT, Integer.valueOf(11)); + CMS.debug("NetkeyKeygenService: serialNo null"); + return false; + } + CMS.debug("NetkeyKeygenService: before addKeyRecord"); + rec.set(KeyRecord.ATTR_ID, serialNo); + request.setExtData(ATTR_KEY_RECORD, serialNo); + storage.addKeyRecord(rec); + CMS.debug("NetkeyKeygenService: key archived for "+rCUID+":"+rUserid); + + auditMessage = CMS.getLogMessage( + LOGGING_SIGNED_AUDIT_PRIVATE_KEY_ARCHIVE_PROCESSED, + auditSubjectID, + ILogger.SUCCESS, + PubKey); + + audit(auditMessage); + + } //if archive + + request.setExtData(IRequest.RESULT, Integer.valueOf(1)); + } catch (Exception e) { + CMS.debug("NetKeyKeygenService: " + e.toString()); + Debug.printStackTrace(e); + request.setExtData(IRequest.RESULT, Integer.valueOf(4)); + + } + } else + request.setExtData(IRequest.RESULT, Integer.valueOf(2)); + + return true; + } //serviceRequest + + /** + * Signed Audit Log + *y + * This method is called to store messages to the signed audit log. + * <P> + * + * @param msg signed audit log message + */ + private void audit(String msg) { + // in this case, do NOT strip preceding/trailing whitespace + // from passed-in String parameters + + if (mSignedAuditLogger == null) { + return; + } + + mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT, + null, + ILogger.S_SIGNED_AUDIT, + ILogger.LL_SECURITY, + msg); + } +} |