Search in sources :

Example 1 with AMPassword

use of com.sun.identity.security.keystore.AMPassword in project OpenAM by OpenRock.

the class SecureLogHelper method initializeVerifier.

/**
     * Initialize the verifier by using the logger generated PKCS12 file
     * and looking for the appropriate content in that and overwriting with
     * the new password
     * @param oldPassword This was set by the administrator and the Auditor
     *                    wants to overwrite this password.
     * @param newPassword The administrator / auditor's new password
     * @throws Exception if it fails to replace the password 
     */
public synchronized void initializeVerifier(String verFileName, AMPassword oldPassword, AMPassword newPassword) throws Exception {
    verifierFileName = verFileName;
    AMPassword oldPass = oldPassword;
    verifierPass = newPassword;
    initializeKeyStoreManager(verifierPass);
    if (oldPassword != null)
        verifierInitialized = isInitialized(verFileName, verifierPass);
    else
        verifierInitialized = true;
    if (!verifierInitialized) {
        currentVerifierKey = readFromSecretStore(verifierFileName, initialKey, oldPass);
        // Password is erased from the object, so we need to keep this
        AMPassword newverpass = verifierPass;
        // Re-write the verifier file with the new password. Also create the
        // currentKey in the secret Storage
        writeToSecretStore(currentVerifierKey, verifierFileName, verifierPass, initialKey);
        verifierInitialized = true;
        writeToSecretStore(currentVerifierKey, verifierFileName, newverpass, currentKey);
    } else {
        currentVerifierKey = readFromSecretStore(verifierFileName, currentKey, verifierPass);
    }
}
Also used : AMPassword(com.sun.identity.security.keystore.AMPassword)

Example 2 with AMPassword

use of com.sun.identity.security.keystore.AMPassword in project OpenAM by OpenRock.

the class SecureLogHelper method reinitializeVerifier.

/**
     * ReInitialize the verifier
     * @param verFileName Filename of the verifier
     * @param password administrator / auditor password
     * @throws Exception if it fails to reinitialize verifier
     */
public synchronized void reinitializeVerifier(String verFileName, AMPassword password) throws Exception {
    initializeKeyStoreManager(password);
    verifierInitialized = isInitialized(verFileName, password);
    if (verifierInitialized) {
        currentVerifierKey = readFromSecretStore(verifierFileName, initialKey, password);
        // Password is erased from the object, so we need to keep this
        AMPassword newverpass = (AMPassword) password.clone();
        writeToSecretStore(currentVerifierKey, verifierFileName, newverpass, currentKey);
    } else {
        throw new Exception(logFileName + " Verifier is not initialized");
    }
}
Also used : AMPassword(com.sun.identity.security.keystore.AMPassword) IOException(java.io.IOException)

Example 3 with AMPassword

use of com.sun.identity.security.keystore.AMPassword in project OpenAM by OpenRock.

the class ISArchiveVerify method verifyArchive.

/**
     *  Verifies the complete archive including the current set and all 
     *  the previous sets for the specified log.
     *  @param logName the name of the log for which the complete Archive is 
     *  to be verified.
     *  @param path Fully quallified path name for log file
     *  @param uname userv name for logger user
     *  @param passwd Password for logger user
     *  @return value of the status of verification.
     *  @throws Exception if it fails to verify the archive.
     */
public boolean verifyArchive(String logName, String path, String uname, String passwd) throws Exception {
    String log = logName;
    LogManager lm = (LogManager) LogManagerUtil.getLogManager();
    lm.readConfiguration();
    verPassword = new AMPassword(passwd.toCharArray());
    SSOToken ssoToken = null;
    SSOTokenManager ssoMngr = null;
    try {
        ssoMngr = SSOTokenManager.getInstance();
        ssoToken = ssoMngr.createSSOToken(new AuthPrincipal(uname), passwd);
    } catch (SSOException ssoe) {
        System.out.println(bundle.getString("archiveVerification") + "SSOException: " + ssoe.getMessage());
        return false;
    } catch (UnsupportedOperationException uoe) {
        System.out.println(bundle.getString("archiveVerification") + "UnsupportedOperationException: " + uoe.getMessage());
        return false;
    }
    // This function will be used to verify all the files in the current and
    // previous sets for the logname and types.
    VerifierList vl = new VerifierList();
    if (!path.endsWith("/")) {
        path += "/";
    }
    TreeMap tm = vl.getKeysAndFiles(new File(path), logName);
    if (tm.size() == 0) {
        System.out.println(bundle.getString("archiveVerification") + bundle.getString("noFilesToVerify") + ", size == 0");
        return true;
    }
    // To get the list of all keyfiles for that particular logname.type
    Object[] keyFiles = (tm.keySet()).toArray();
    String verFile = new String();
    if (keyFiles.length == 1) {
        System.out.println(bundle.getString("archiveVerification") + bundle.getString("noFilesToVerify") + ", keyFiles.length == 1");
    }
    for (int i = 1; i < keyFiles.length; i++) {
        helper = SecureFileHandler.getSecureLogHelperInst();
        // This is the set of files for that particular keystore.
        Vector logFiles = (Vector) tm.get(keyFiles[i]);
        // Iterate through the list and start verification from 
        // the first file.
        String tmpName = ((String) keyFiles[i]).substring(((String) keyFiles[i]).indexOf(".") + 1);
        verFile = tmpName.substring(tmpName.indexOf("."));
        verFile = PREFIX + "ver" + verFile;
        // Initialize the SecureLogHelper object for the current keystores.
        helper.initializeVerifier(path + verFile, verPassword, verPassword);
        helper.reinitializeVerifier(path + verFile, verPassword);
        // Start verifying the Files associated with the current keystore
        curMAC = null;
        prevSignature = null;
        for (int j = 0; j < logFiles.size(); j++) {
            // flag to indicate that last record in the file is being 
            // verified. This record is the same for the first record 
            // of the next file.
            System.out.println(bundle.getString("fileBeingVerified") + (String) logFiles.elementAt(j));
            int lastRecInFile = 0;
            // Read the logRecords in the File.
            String[][] result = new String[1][1];
            try {
                result = LogReader.read((String) logFiles.elementAt(j), ssoToken);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // empty string.
            if (result != null || result.length != 0) {
                Vector header = new Vector(result[0].length);
                // Extracting the field names as header from the first 
                // line of the returned string array.
                header.addAll(Arrays.asList(result[0]));
                int signPos = -1, macPos = -1;
                String signFldName, macFldName;
                signFldName = LogConstants.SIGNATURE_FIELDNAME;
                macFldName = LogConstants.MAC_FIELDNAME;
                for (int l = 0; l < header.size(); l++) {
                    if ((((String) header.get(l))).equalsIgnoreCase(signFldName)) {
                        signPos = l;
                        break;
                    }
                }
                // end of loop l
                for (int l = 0; l < header.size(); l++) {
                    if ((((String) header.get(l))).equalsIgnoreCase(macFldName)) {
                        macPos = l;
                        break;
                    }
                }
                // end of loop l
                if ((signPos == -1) || (macPos == -1)) {
                    return VerifierAction.doVerifierAction(log, verified);
                }
                // or a log record.
                for (int k = 1; k < result.length; k++) {
                    // add 2 for MAC and Signature fields
                    if (result[k].length < (LogConstants.MAX_FIELDS + 2)) {
                        System.err.println(bundle.getString("recordVerificationFailed") + (String) logFiles.elementAt(j) + "\n\t #fields in record #" + (k - 1) + " (" + result[k].length + ") < 14\n");
                        verified = false;
                        break;
                    }
                    if (result[k][signPos].equals("-")) {
                        verified = verifyLogRecord(result[k], macPos);
                        if (!verified) {
                            System.err.println(bundle.getString("recordVerificationFailed") + (String) logFiles.elementAt(j) + " " + bundle.getString("atRecordNumber") + k);
                            break;
                        }
                        System.out.println(bundle.getString("recordVerificationPassed") + (String) logFiles.elementAt(j) + " " + bundle.getString("atRecordNumber") + k);
                    } else {
                        // To check if this is the last signature in the 
                        // file an additional parameter has to be passed 
                        // to the verifySignature since the signature is 
                        // the same as the first signature in the next file.
                        // This is to ensure that prevSignature is not 
                        // updated with the last signature in the file.
                        // Bcos the checking of the last signature in the 
                        // file will be the same for the first signature 
                        // for the next file.
                        lastRecInFile = (result.length - 1) - k;
                        verified = verifySignature(result[k], signPos, lastRecInFile);
                        if (!verified) {
                            System.err.println(bundle.getString("signatureVerificationFailed") + (String) logFiles.elementAt(j) + bundle.getString("atRecordNumber") + k);
                            break;
                        }
                        System.out.println(bundle.getString("signatureVerificationPassed") + (String) logFiles.elementAt(j) + bundle.getString("atRecordNumber") + k);
                    }
                }
            // end of loop k i.e. end of records for this logFile.
            } else {
                System.err.println(bundle.getString("archiveVerification") + bundle.getString("emptyReturn") + (String) logFiles.elementAt(j));
            }
            if (!verified) {
                return verified;
            }
        }
        // end of loop j i.e. end of Files for the current keystore.
        helper.reinitializeVerifier(path + verFile, verPassword);
    }
    // end of loop i
    return verified;
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) SSOToken(com.iplanet.sso.SSOToken) SSOException(com.iplanet.sso.SSOException) VerifierList(com.sun.identity.log.secure.VerifierList) TreeMap(java.util.TreeMap) ConfiguratorException(com.sun.identity.setup.ConfiguratorException) SSOException(com.iplanet.sso.SSOException) AMPassword(com.sun.identity.security.keystore.AMPassword) AuthPrincipal(com.sun.identity.authentication.internal.AuthPrincipal) LogManager(com.sun.identity.log.LogManager) File(java.io.File) Vector(java.util.Vector)

Example 4 with AMPassword

use of com.sun.identity.security.keystore.AMPassword in project OpenAM by OpenRock.

the class SecureLogHelperJSSImpl method readFromSecretStore.

/**
     * Returns matched secret data from from the secret Storage. 
     * At a time there are only 3 things in logger's secure store file 
     *    - initialkey, currentkey and current signature
     * In the verifier secure store file there is just the initial key of the
     * logger and the currentKey
     * @param filename file for secret storage
     * @param dataType The kind of data to be read, whether it is a
     *                 signature or a key
     * @param password password for the file
     * @return secure data that is matched with dataType
     * @throws Exception if it fails to read secret data from secret store
     */
byte[] readFromSecretStore(String filename, String dataType, AMPassword password) throws Exception {
    // open input file for reading
    FileInputStream infile = null;
    infile = new FileInputStream(filename);
    // Decode the P12 file
    PFX.Template pfxt = new PFX.Template();
    PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(infile, 2048));
    // Verify the MAC on the PFX.  This is important to be sure
    // it hasn't been tampered with.
    StringBuffer reason = new StringBuffer();
    MessageDigest md = MessageDigest.getInstance("SHA");
    Password jssPasswd = new Password(new String(md.digest(password.getByteCopy()), "UTF-8").toCharArray());
    md.reset();
    if (!pfx.verifyAuthSafes(jssPasswd, reason)) {
        throw new Exception("AuthSafes failed to verify because: " + reason.toString());
    }
    AuthenticatedSafes authSafes = pfx.getAuthSafes();
    SEQUENCE safeContentsSequence = authSafes.getSequence();
    byte[] cryptoData = null;
    // Loop over contents of the authenticated safes
    for (int i = 0; i < safeContentsSequence.size(); i++) {
        // The safeContents may or may not be encrypted.  We always send
        // the password in.  It will get used if it is needed.  If the
        // decryption of the safeContents fails for some reason (like
        // a bad password), then this method will throw an exception
        SEQUENCE safeContents = authSafes.getSafeContentsAt(jssPasswd, i);
        SafeBag safeBag = null;
        ASN1Value val = null;
        // Go through all the bags in this SafeContents
        for (int j = 0; j < safeContents.size(); j++) {
            safeBag = (SafeBag) safeContents.elementAt(j);
            // look for bag attributes and then choose the key
            SET attribs = safeBag.getBagAttributes();
            if (attribs == null) {
                Debug.error("Bag has no attributes");
            } else {
                for (int b = 0; b < attribs.size(); b++) {
                    Attribute a = (Attribute) attribs.elementAt(b);
                    if (a.getType().equals(SafeBag.FRIENDLY_NAME)) {
                        // the friendly name attribute is a nickname
                        BMPString bs = (BMPString) ((ANY) a.getValues().elementAt(0)).decodeWith(BMPString.getTemplate());
                        if (dataType.equals(bs.toString())) {
                            // look at the contents of the bag
                            val = safeBag.getInterpretedBagContent();
                            break;
                        }
                    }
                }
            }
        }
        if (val instanceof ANY)
            cryptoData = ((ANY) val).getContents();
    }
    // Close the file
    infile.close();
    return cryptoData;
}
Also used : PFX(org.mozilla.jss.pkcs12.PFX) SET(org.mozilla.jss.asn1.SET) Attribute(org.mozilla.jss.pkix.primitive.Attribute) BMPString(org.mozilla.jss.asn1.BMPString) SafeBag(org.mozilla.jss.pkcs12.SafeBag) ANY(org.mozilla.jss.asn1.ANY) FileInputStream(java.io.FileInputStream) AuthenticatedSafes(org.mozilla.jss.pkcs12.AuthenticatedSafes) ASN1Value(org.mozilla.jss.asn1.ASN1Value) BufferedInputStream(java.io.BufferedInputStream) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) MessageDigest(java.security.MessageDigest) BMPString(org.mozilla.jss.asn1.BMPString) AMPassword(com.sun.identity.security.keystore.AMPassword) Password(org.mozilla.jss.util.Password)

Example 5 with AMPassword

use of com.sun.identity.security.keystore.AMPassword in project OpenAM by OpenRock.

the class SecureLogHelperJSSImpl method writeToSecretStore.

/**
     * Writes to the secret Storage. If the data to be written is a key, then
     * writes the older signature also. If it is a signature then writes the
     * older key also
     * @param cryptoMaterial The data to be written to the secret storage
     * @param filename The file for secret storage
     * @param password The password for the file
     * @param dataType The kind of cryptoMaterial, whether it is a signature
     * or a key
     * @throws Exception if it fails to write secret data from secret store
     */
void writeToSecretStore(byte[] cryptoMaterial, String filename, AMPassword password, String dataType) throws Exception {
    byte[] oldDataFromSecretStorage = null;
    String oldDataType = null;
    MessageDigest md = MessageDigest.getInstance("SHA");
    Password jssPasswd = new Password(new String(md.digest(password.getByteCopy()), "UTF-8").toCharArray());
    md.reset();
    // Do this only when the logger's file is being used
    if (filename.equals(logFileName) && loggerInitialized) {
        // current signature in the PKCS12 file
        if (dataType.equals(currentSignature)) {
            oldDataFromSecretStorage = readFromSecretStore(logFileName, currentKey, password);
            oldDataType = currentKey;
        } else if (dataType.equals(currentKey)) {
            // need to read the currentSignature 
            // for the same reason as above
            oldDataFromSecretStorage = readFromSecretStore(logFileName, currentSignature, password);
            oldDataType = currentSignature;
        }
    }
    // Start building the new contents by adding the older content first
    AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();
    if (oldDataFromSecretStorage != null) {
        SEQUENCE oldSafeContents = AddToSecretStore(oldDataFromSecretStorage, oldDataType);
        // Add the old contents to the existing safe
        newAuthSafes.addEncryptedSafeContents(PBEAlgorithm.PBE_SHA1_DES3_CBC, jssPasswd, null, AuthenticatedSafes.DEFAULT_ITERATIONS, oldSafeContents);
    }
    // not being added for the first time
    if ((filename.equals(logFileName)) && !dataType.equals(initialKey) && loggerInitialized) {
        byte[] key = readFromSecretStore(filename, initialKey, password);
        if (key != null) {
            SEQUENCE initialKeySafeContents = AddToSecretStore(key, initialKey);
            newAuthSafes.addEncryptedSafeContents(PBEAlgorithm.PBE_SHA1_DES3_CBC, jssPasswd, null, AuthenticatedSafes.DEFAULT_ITERATIONS, initialKeySafeContents);
        }
    }
    if ((filename.equals(verifierFileName)) && !dataType.equals(initialKey) && verifierInitialized) {
        byte[] key = readFromSecretStore(filename, initialKey, password);
        if (key != null) {
            SEQUENCE initialKeySafeContents = AddToSecretStore(key, initialKey);
            newAuthSafes.addEncryptedSafeContents(PBEAlgorithm.PBE_SHA1_DES3_CBC, jssPasswd, null, AuthenticatedSafes.DEFAULT_ITERATIONS, initialKeySafeContents);
        }
    }
    // Add the new contents
    SEQUENCE encSafeContents = AddToSecretStore(cryptoMaterial, dataType);
    // Add the new contents to the existing safe
    newAuthSafes.addEncryptedSafeContents(PBEAlgorithm.PBE_SHA1_DES3_CBC, jssPasswd, null, AuthenticatedSafes.DEFAULT_ITERATIONS, encSafeContents);
    PFX newpfx = new PFX(newAuthSafes);
    newpfx.computeMacData(jssPasswd, null, 5);
    // write the new PFX out to the logger
    FileOutputStream fos = new FileOutputStream(filename);
    newpfx.encode(fos);
    fos.close();
}
Also used : PFX(org.mozilla.jss.pkcs12.PFX) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) FileOutputStream(java.io.FileOutputStream) BMPString(org.mozilla.jss.asn1.BMPString) MessageDigest(java.security.MessageDigest) AMPassword(com.sun.identity.security.keystore.AMPassword) Password(org.mozilla.jss.util.Password) AuthenticatedSafes(org.mozilla.jss.pkcs12.AuthenticatedSafes)

Aggregations

AMPassword (com.sun.identity.security.keystore.AMPassword)7 IOException (java.io.IOException)2 MessageDigest (java.security.MessageDigest)2 BMPString (org.mozilla.jss.asn1.BMPString)2 SEQUENCE (org.mozilla.jss.asn1.SEQUENCE)2 AuthenticatedSafes (org.mozilla.jss.pkcs12.AuthenticatedSafes)2 PFX (org.mozilla.jss.pkcs12.PFX)2 Password (org.mozilla.jss.util.Password)2 NullLocationException (com.iplanet.log.NullLocationException)1 SSOException (com.iplanet.sso.SSOException)1 SSOToken (com.iplanet.sso.SSOToken)1 SSOTokenManager (com.iplanet.sso.SSOTokenManager)1 AuthPrincipal (com.sun.identity.authentication.internal.AuthPrincipal)1 LogManager (com.sun.identity.log.LogManager)1 Logger (com.sun.identity.log.Logger)1 SecureLogHelper (com.sun.identity.log.secure.SecureLogHelper)1 VerifierList (com.sun.identity.log.secure.VerifierList)1 ConfiguratorException (com.sun.identity.setup.ConfiguratorException)1 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1