All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.wildfly.security.tool.Command Maven / Gradle / Ivy

/*
 * JBoss, Home of Professional Open Source
 * Copyright 2017 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.wildfly.security.tool;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;

import java.io.BufferedReader;
import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Supplier;
import java.util.regex.Pattern;

import javax.crypto.SecretKey;

import org.wildfly.security.credential.SecretKeyCredential;
import org.wildfly.security.credential.store.CredentialStore;
import org.wildfly.security.credential.store.CredentialStoreException;
import org.wildfly.security.credential.store.UnsupportedCredentialTypeException;
import org.wildfly.security.credential.store.impl.PropertiesCredentialStore;
import org.wildfly.security.encryption.SecretKeyUtil;
import org.wildfly.security.keystore.AtomicLoadKeyStore;
import org.wildfly.security.keystore.KeyStoreUtil;
import org.wildfly.security.keystore.WildFlyElytronKeyStoreProvider;
import org.wildfly.security.password.WildFlyElytronPasswordProvider;
import org.wildfly.security.provider.util.ProviderUtil;

/**
 * Base command class
 * @author Peter Skopek
 */
public abstract class Command {

    /**
     * General configuration error exit code.
     */
    public static final int GENERAL_CONFIGURATION_ERROR = 7;

    public static final int GENERAL_CONFIGURATION_WARNING = 1;

    public static final int INPUT_DATA_NOT_CONFIRMED = 3;

    public static Supplier ELYTRON_KS_PASS_PROVIDERS = () -> new Provider[] {
            WildFlyElytronKeyStoreProvider.getInstance(),
            WildFlyElytronPasswordProvider.getInstance()
    };

    private int status = 255;

    private List redirectionValues;

    private boolean enableDebug;

    /**
     * Command used to execute the tool.
     */
    private String toolCommand = "java -jar wildfly-elytron-tool.jar";

    public abstract void execute(String[] args) throws Exception;

    /**
     * Default help line width.
     */
    public static final int WIDTH = 1024;

    /**
     * Display help to the command.
     *
     */
    public void help() {

    }

    public boolean isAlias(String alias) {
        return aliases().contains(alias);
    }

    protected Set aliases() {
        return Collections.emptySet();
    }

    public int getStatus() {
        return status;
    }

    protected void setStatus(int status) {
        this.status = status;
    }

    public static boolean isWindows() {
        String opsys = System.getProperty("os.name").toLowerCase();
        return (opsys.indexOf("win") >= 0);
    }

    /**
     * Prompt for interactive user input with possible confirmation of input data.
     * When data are not confirmed tool exits with {@link #INPUT_DATA_NOT_CONFIRMED} exit code
     *
     * @param echo echo the characters typed
     * @param prompt text to display before the input
     * @param confirm confirm data after the first input
     * @param confirmPrompt confirmation text
     * @return data as user inputs it
     * @throws Exception if a {@link BufferedReader} cannot be created
     */
    protected String prompt(boolean echo, String prompt, boolean confirm, String confirmPrompt) throws Exception {
        Console console = System.console();
        if (echo || console == null) {
            if (console == null && redirectionValues == null) {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
                    redirectionValues = new ArrayList<>();
                    String value;
                    while ((value = in.readLine()) != null) {
                        redirectionValues.add(value);
                    }
                } catch (IOException e) {
                    setStatus(GENERAL_CONFIGURATION_ERROR);
                    throw new Exception(e);
                }
            }
            String first = console != null ? console.readLine(prompt)
                    : (redirectionValues.size() == 0 ? null : redirectionValues.remove(0));
            if (first != null && confirm) {
                String second = console != null ? console.readLine(confirmPrompt)
                        : (redirectionValues.size() == 0 ? null : redirectionValues.remove(0));
                if (first.equals(second)) {
                    return first;
                } else {
                    System.err.println(ElytronToolMessages.msg.inputDataNotConfirmed());
                    System.exit(INPUT_DATA_NOT_CONFIRMED);
                    return null;
                }
            } else {
                return first;
            }
        } else {
            char[] inVisible = console.readPassword(prompt != null ? prompt : "Password:");
            if (inVisible != null && confirm) {
                char[] inVisible2 = console.readPassword(confirmPrompt != null ? confirmPrompt : "Confirm password:");
                if (Arrays.equals(inVisible, inVisible2)) {
                    return new String(inVisible);
                } else {
                    System.err.println(ElytronToolMessages.msg.inputDataNotConfirmed());
                    System.exit(INPUT_DATA_NOT_CONFIRMED);
                    return null;
                }
            }
            if (inVisible != null) {
                return new String(inVisible);
            }
            return null;
        }
    }

    /**
     * Alerts if any of the command line options used are duplicated
     * @param cmdLine the command line options used when invoking the command, after parsing
     */
    public void printDuplicatesWarning(CommandLine cmdLine) {
        List




© 2015 - 2024 Weber Informatics LLC | Privacy Policy