Search in sources :

Example 1 with Fault

use of com.intel.mtwilson.util.validation.Fault in project OpenAttestation by OpenAttestation.

the class Input method printFault.

/**
     * 
     * @param f
     * @param level of indentation;  use 0 for top-level faults, and increment once for each level of logical nesting
     */
private static void printFault(Fault f, int level) {
    StringBuilder spaces = new StringBuilder(level * 2);
    // each level is indented two spaces from the previous level
    for (int i = 0; i < level; i++) {
        spaces.append("  ");
    }
    String indentation = spaces.toString();
    System.err.println(String.format("%s- %s", indentation, f.toString()));
    //        }
    if (!f.getFaults().isEmpty()) {
        System.err.println(String.format("%s  Related errors:", indentation));
        for (Fault related : f.getFaults()) {
            printFault(related, level + 1);
        }
    }
}
Also used : Fault(com.intel.mtwilson.util.validation.Fault)

Example 2 with Fault

use of com.intel.mtwilson.util.validation.Fault in project OpenAttestation by OpenAttestation.

the class Input method getRequiredInputWithDefaultPrompt.

public static <T> T getRequiredInputWithDefaultPrompt(InputModel<T> model, String caption, String prompt, String defaultValue) throws IOException {
    while (true) {
        if (caption != null && !caption.isEmpty()) {
            System.out.println(caption);
        }
        String input = readLine(prompt + " [" + defaultValue + "] ");
        if (input == null || input.isEmpty()) {
            input = defaultValue;
        }
        model.setInput(input);
        if (model.isValid()) {
            return model.value();
        } else {
            // TODO: print faults
            for (Fault f : model.getFaults()) {
                System.err.println(f.toString());
            }
        }
    // TODO: allow user to break by typing 'exit', 'cancel', 'abort', etc, and we can throw an exception like UserAbortException (must create it) so the main program can have a chance to save what has already been validated and exit, or skip to the next step, or something.
    }
}
Also used : Fault(com.intel.mtwilson.util.validation.Fault)

Example 3 with Fault

use of com.intel.mtwilson.util.validation.Fault in project OpenAttestation by OpenAttestation.

the class Hostname method getFaults.

@Override
public List<Fault> getFaults() {
    if (isValid()) {
        return Collections.EMPTY_LIST;
    } else {
        ArrayList<Fault> faults = new ArrayList<Fault>();
        faults.add(new Fault("Invalid hostname: %s", hostname));
        return faults;
    }
}
Also used : ArrayList(java.util.ArrayList) Fault(com.intel.mtwilson.util.validation.Fault)

Example 4 with Fault

use of com.intel.mtwilson.util.validation.Fault in project OpenAttestation by OpenAttestation.

the class TagCreateCaKey method execute.

@Override
public void execute(String[] args) throws Exception {
    // file name, and either outfile or stdout
    String dn;
    if (args.length > 0) {
        dn = args[0];
    } else {
        dn = "CN=asset-tag-service,OU=mtwilson";
    }
    // create a new key pair
    KeyPair cakey = RsaUtil.generateRsaKeyPair(2048);
    X509Builder builder = X509Builder.factory();
    X509Certificate cacert = builder.selfSigned(dn, cakey).expires(3650, TimeUnit.DAYS).build();
    if (cacert == null) {
        //            log.error("Failed to create certificate"); // no need to print this, if the build failed there are guaranteed to be faults to print...
        List<Fault> faults = builder.getFaults();
        for (Fault fault : faults) {
            log.error(String.format("%s: %s", fault.getClass().getName(), fault.toString()));
        //                log.error(String.format("%s%s", fault.toString(), fault.getCause() == null ? "" : ": "+fault.getCause().getMessage()));
        }
        return;
    }
    String privateKeyPem = RsaUtil.encodePemPrivateKey(cakey.getPrivate());
    String cacertPem = X509Util.encodePemCertificate(cacert);
    String combinedPrivateKeyAndCertPem = privateKeyPem + cacertPem;
    byte[] combinedPrivateKeyAndCertPemBytes = combinedPrivateKeyAndCertPem.getBytes("UTF-8");
    byte[] cacertPemContent = cacertPem.getBytes("UTF-8");
    // for now... there can only be ONE CA private key in the database  (but we support storing multiple certs)
    File cakeyFile = TagJdbi.fileDao().findByName(PRIVATEKEY_FILE);
    if (cakeyFile == null) {
        // create new private key file
        TagJdbi.fileDao().insert(new UUID(), PRIVATEKEY_FILE, "text/plain", combinedPrivateKeyAndCertPemBytes);
    } else {
        // replace existing private key... 
        TagJdbi.fileDao().update(cakeyFile.getId(), PRIVATEKEY_FILE, "text/plain", combinedPrivateKeyAndCertPemBytes);
    }
    // add the ca cert to the list of approved certs
    File cacertsFile = TagJdbi.fileDao().findByName(CACERTS_FILE);
    if (cacertsFile == null) {
        // create new cacerts file
        TagJdbi.fileDao().insert(new UUID(), CACERTS_FILE, "text/plain", cacertPemContent);
    } else {
        // append new cacert to existing file in database
        byte[] content = ByteArray.concat(cacertsFile.getContent(), cacertPemContent);
        TagJdbi.fileDao().update(cacertsFile.getId(), CACERTS_FILE, "text/plain", content);
        // and write to disk also for easy sharing with mtwilson: tag-cacerts.pem
        try (FileOutputStream out = new FileOutputStream(ASConfig.getAssetTagCaCertificateFile())) {
            IOUtils.write(content, out);
        }
    }
}
Also used : KeyPair(java.security.KeyPair) X509Builder(com.intel.mtwilson.crypto.X509Builder) FileOutputStream(java.io.FileOutputStream) Fault(com.intel.mtwilson.util.validation.Fault) UUID(com.intel.mtwilson.util.io.UUID) File(com.intel.mtwilson.datatypes.File) X509Certificate(java.security.cert.X509Certificate)

Example 5 with Fault

use of com.intel.mtwilson.util.validation.Fault in project OpenAttestation by OpenAttestation.

the class TagCertificateAuthority method createTagCertificate.

/**
     * Does not attempt to match the subject to the selection. Do not call
     * directly unless you have already verified that you want to create a
     * certificate for the given subject with the given selection with no
     * further checks.
     *
     * @param subject
     * @param selection element representing a set of host attributes by
     * reference via the selection uuid or selection name or inline via the
     * attribute elements
     * @return
     * @throws Exception
     */
public byte[] createTagCertificate(UUID subject, SelectionType selection) throws IOException, com.intel.mtwilson.ApiException {
    // check if we have a private key to use for signing
    PrivateKey cakey = Global.cakey();
    X509Certificate cakeyCert = Global.cakeyCert();
    if (cakey == null || cakeyCert == null) {
        throw new IllegalStateException("Missing tag certificate authority key");
    }
    X509AttrBuilder builder = X509AttrBuilder.factory().issuerName(cakeyCert).issuerPrivateKey(cakey).dateSerial().subjectUuid(subject).expires(configuration.getTagValiditySeconds(), TimeUnit.SECONDS);
    for (AttributeType attribute : selection.getAttribute()) {
        X509AttrBuilder.Attribute oidAndValue = Util.toAttributeOidValue(attribute);
        builder.attribute(oidAndValue.oid, oidAndValue.value);
    }
    byte[] attributeCertificateBytes = builder.build();
    if (attributeCertificateBytes == null) {
        log.error("Cannot build attribute certificate");
        for (Fault fault : builder.getFaults()) {
            log.error(String.format("%s: %s", fault.getClass().getName(), fault.toString()));
        }
        throw new IllegalArgumentException("Cannot build attribute certificate");
    }
    // if auto-import to mtwilson is enabled, do it here, but if there is an exception we only log it
    try {
        log.debug("Tag certificate auto-import enabled: {}", configuration.isTagProvisionAutoImport());
        if (configuration.isTagProvisionAutoImport()) {
            //String url = My.configuration().getAssetTagMtWilsonBaseUrl();
            String url = ASConfig.getMtWilsonURL().toString();
            if (url != null && !url.isEmpty()) {
                AssetTagCertCreateRequest request = new AssetTagCertCreateRequest();
                request.setCertificate(attributeCertificateBytes);
                log.debug("Importing tag certificate to Mt Wilson");
                Global.mtwilson().importAssetTagCertificate(request);
            }
        }
    } catch (IOException e) {
        log.error("Failed to auto-import tag certificate to Mt Wilson", e);
    } catch (SignatureException e) {
        log.error("Failed to auto-import tag certificate to Mt Wilson", e);
    }
    return attributeCertificateBytes;
}
Also used : PrivateKey(java.security.PrivateKey) Fault(com.intel.mtwilson.util.validation.Fault) IOException(java.io.IOException) SignatureException(java.security.SignatureException) X509Certificate(java.security.cert.X509Certificate) AssetTagCertCreateRequest(com.intel.mtwilson.datatypes.AssetTagCertCreateRequest) X509AttrBuilder(com.intel.mtwilson.tag.common.X509AttrBuilder)

Aggregations

Fault (com.intel.mtwilson.util.validation.Fault)5 X509Certificate (java.security.cert.X509Certificate)2 X509Builder (com.intel.mtwilson.crypto.X509Builder)1 AssetTagCertCreateRequest (com.intel.mtwilson.datatypes.AssetTagCertCreateRequest)1 File (com.intel.mtwilson.datatypes.File)1 X509AttrBuilder (com.intel.mtwilson.tag.common.X509AttrBuilder)1 UUID (com.intel.mtwilson.util.io.UUID)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 KeyPair (java.security.KeyPair)1 PrivateKey (java.security.PrivateKey)1 SignatureException (java.security.SignatureException)1 ArrayList (java.util.ArrayList)1