Search in sources :

Example 26 with IllegalCmdParamException

use of org.xipki.console.karaf.IllegalCmdParamException in project xipki by xipki.

the class SpeedP11Action method getSlot.

protected P11Slot getSlot() throws XiSecurityException, P11TokenException, IllegalCmdParamException {
    P11CryptService p11Service = p11CryptServiceFactory.getP11CryptService(moduleName);
    if (p11Service == null) {
        throw new IllegalCmdParamException("undefined module " + moduleName);
    }
    P11Module module = p11Service.getModule();
    P11SlotIdentifier slotId = module.getSlotIdForIndex(slotIndex);
    return module.getSlot(slotId);
}
Also used : P11Module(org.xipki.security.pkcs11.P11Module) P11SlotIdentifier(org.xipki.security.pkcs11.P11SlotIdentifier) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) P11CryptService(org.xipki.security.pkcs11.P11CryptService)

Example 27 with IllegalCmdParamException

use of org.xipki.console.karaf.IllegalCmdParamException in project xipki by xipki.

the class CurlCmd method execute0.

@Override
protected Object execute0() throws Exception {
    byte[] dataBytes = null;
    if (postData != null) {
        dataBytes = postData.getBytes(postDataCharSet);
    } else if (postDataFile != null) {
        dataBytes = IoUtil.read(postDataFile);
    }
    if (dataBytes != null) {
        usePost = Boolean.TRUE;
    }
    URL newUrl = new URL(url);
    HttpURLConnection httpConn = IoUtil.openHttpConn(newUrl);
    try {
        httpConn.setRequestMethod(usePost ? "POST" : "GET");
        httpConn.setUseCaches(false);
        if (headers != null) {
            for (String header : headers) {
                int idx = header.indexOf(':');
                if (idx == -1 || idx == header.length() - 1) {
                    throw new IllegalCmdParamException("invalid HTTP header: '" + header + "'");
                }
                String key = header.substring(0, idx);
                String value = header.substring(idx + 1).trim();
                httpConn.setRequestProperty(key, value);
            }
        }
        if (userPassword != null) {
            int idx = userPassword.indexOf(':');
            if (idx == -1 || idx == userPassword.length() - 1) {
                throw new IllegalCmdParamException("invalid user");
            }
            httpConn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(userPassword.getBytes()));
        }
        Map<String, List<String>> properties;
        if (dataBytes == null) {
            properties = httpConn.getRequestProperties();
        } else {
            httpConn.setDoOutput(true);
            httpConn.setRequestProperty("Content-Length", Integer.toString(dataBytes.length));
            properties = httpConn.getRequestProperties();
            OutputStream outputstream = httpConn.getOutputStream();
            outputstream.write(dataBytes);
            outputstream.flush();
        }
        // show the request headers
        if (verbose) {
            println("=====request=====");
            println("  HTTP method: " + httpConn.getRequestMethod());
            for (String key : properties.keySet()) {
                List<String> values = properties.get(key);
                for (String value : values) {
                    println("  " + key + ": " + value);
                }
            }
        }
        // read the response
        int respCode = httpConn.getResponseCode();
        if (verbose) {
            println("=====response=====");
            println("  response code: " + respCode + " " + httpConn.getResponseMessage());
            properties = httpConn.getHeaderFields();
            for (String key : properties.keySet()) {
                if (key == null) {
                    continue;
                }
                List<String> values = properties.get(key);
                for (String value : values) {
                    println("  " + key + ": " + value);
                }
            }
            println("=====response content=====");
        } else {
            if (respCode != HttpURLConnection.HTTP_OK) {
                println("ERROR: bad response: " + httpConn.getResponseCode() + "    " + httpConn.getResponseMessage());
            }
        }
        InputStream inputStream = null;
        InputStream errorStream = null;
        try {
            inputStream = httpConn.getInputStream();
        } catch (IOException ex) {
            errorStream = httpConn.getErrorStream();
        }
        byte[] respContentBytes;
        if (inputStream != null) {
            respContentBytes = IoUtil.read(inputStream);
        } else if (errorStream != null) {
            respContentBytes = IoUtil.read(errorStream);
        } else {
            respContentBytes = null;
        }
        if (respContentBytes == null || respContentBytes.length == 0) {
            println("NO response content");
            return null;
        }
        if (outFile != null) {
            String fn = (errorStream != null) ? "error-" + outFile : outFile;
            saveVerbose("saved response to file", new File(fn), respContentBytes);
        } else {
            String ct = httpConn.getHeaderField("Content-Type");
            String charset = getCharset(ct);
            if (charset == null) {
                charset = "UTF-8";
            }
            if (errorStream != null) {
                println("ERROR: ");
            }
            println(new String(respContentBytes, charset));
        }
    } finally {
        httpConn.disconnect();
    }
    return null;
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) List(java.util.List) File(java.io.File)

Example 28 with IllegalCmdParamException

use of org.xipki.console.karaf.IllegalCmdParamException in project xipki by xipki.

the class ConvertKeystoreCmd method execute0.

@Override
protected Object execute0() throws Exception {
    File realInFile = new File(IoUtil.expandFilepath(inFile));
    File realOutFile = new File(IoUtil.expandFilepath(outFile));
    if (CompareUtil.equalsObject(realInFile, realOutFile)) {
        throw new IllegalCmdParamException("in and out cannot be the same");
    }
    KeyStore inKs = KeyStore.getInstance(inType);
    KeyStore outKs = KeyStore.getInstance(outType);
    outKs.load(null);
    char[] inPassword = readPasswordIfNotSet("password of the source keystore", inPwd);
    FileInputStream inStream = new FileInputStream(realInFile);
    try {
        inKs.load(inStream, inPassword);
    } finally {
        inStream.close();
    }
    char[] outPassword = readPasswordIfNotSet("password of the destination keystore", outPwd);
    Enumeration<String> aliases = inKs.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (inKs.isKeyEntry(alias)) {
            Certificate[] certs = inKs.getCertificateChain(alias);
            Key key = inKs.getKey(alias, inPassword);
            outKs.setKeyEntry(alias, key, outPassword, certs);
        } else {
            Certificate cert = inKs.getCertificate(alias);
            outKs.setCertificateEntry(alias, cert);
        }
    }
    ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
    outKs.store(bout, outPassword);
    saveVerbose("saved destination keystore to file", realOutFile, bout.toByteArray());
    return null;
}
Also used : IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) File(java.io.File) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) Key(java.security.Key) Certificate(java.security.cert.Certificate)

Example 29 with IllegalCmdParamException

use of org.xipki.console.karaf.IllegalCmdParamException in project xipki by xipki.

the class BaseOcspStatusAction method execute0.

@Override
protected final Object execute0() throws Exception {
    if (StringUtil.isBlank(serialNumberList) && isEmpty(certFiles)) {
        throw new IllegalCmdParamException("Neither serialNumbers nor certFiles is set");
    }
    X509Certificate issuerCert = X509Util.parseCert(issuerCertFile);
    Map<BigInteger, byte[]> encodedCerts = null;
    List<BigInteger> sns = new LinkedList<>();
    if (isNotEmpty(certFiles)) {
        encodedCerts = new HashMap<>(certFiles.size());
        String ocspUrl = null;
        X500Name issuerX500Name = null;
        for (String certFile : certFiles) {
            BigInteger sn;
            List<String> ocspUrls;
            if (isAttrCert) {
                if (issuerX500Name == null) {
                    issuerX500Name = X500Name.getInstance(issuerCert.getSubjectX500Principal().getEncoded());
                }
                X509AttributeCertificateHolder cert = new X509AttributeCertificateHolder(IoUtil.read(certFile));
                // no signature validation
                AttributeCertificateIssuer reqIssuer = cert.getIssuer();
                if (reqIssuer != null && issuerX500Name != null) {
                    X500Name reqIssuerName = reqIssuer.getNames()[0];
                    if (!issuerX500Name.equals(reqIssuerName)) {
                        throw new IllegalCmdParamException("certificate " + certFile + " is not issued by the given issuer");
                    }
                }
                ocspUrls = extractOcspUrls(cert);
                sn = cert.getSerialNumber();
            } else {
                X509Certificate cert = X509Util.parseCert(certFile);
                if (!X509Util.issues(issuerCert, cert)) {
                    throw new IllegalCmdParamException("certificate " + certFile + " is not issued by the given issuer");
                }
                ocspUrls = extractOcspUrls(cert);
                sn = cert.getSerialNumber();
            }
            if (isBlank(serverUrl)) {
                if (CollectionUtil.isEmpty(ocspUrls)) {
                    throw new IllegalCmdParamException("could not extract OCSP responder URL");
                } else {
                    String url = ocspUrls.get(0);
                    if (ocspUrl != null && !ocspUrl.equals(url)) {
                        throw new IllegalCmdParamException("given certificates have different" + " OCSP responder URL in certificate");
                    } else {
                        ocspUrl = url;
                    }
                }
            }
            // end if
            sns.add(sn);
            byte[] encodedCert = IoUtil.read(certFile);
            encodedCerts.put(sn, encodedCert);
        }
        if (isBlank(serverUrl)) {
            serverUrl = ocspUrl;
        }
    } else {
        StringTokenizer st = new StringTokenizer(serialNumberList, ", ");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            StringTokenizer st2 = new StringTokenizer(token, "-");
            BigInteger from = toBigInt(st2.nextToken(), hex);
            BigInteger to = st2.hasMoreTokens() ? toBigInt(st2.nextToken(), hex) : null;
            if (to == null) {
                sns.add(from);
            } else {
                BigIntegerRange range = new BigIntegerRange(from, to);
                if (range.getDiff().compareTo(BigInteger.valueOf(10)) > 0) {
                    throw new IllegalCmdParamException("to many serial numbers");
                }
                BigInteger sn = range.getFrom();
                while (range.isInRange(sn)) {
                    sns.add(sn);
                    sn = sn.add(BigInteger.ONE);
                }
            }
        }
    }
    if (isBlank(serverUrl)) {
        throw new IllegalCmdParamException("could not get URL for the OCSP responder");
    }
    X509Certificate respIssuer = null;
    if (respIssuerFile != null) {
        respIssuer = X509Util.parseCert(IoUtil.expandFilepath(respIssuerFile));
    }
    URL serverUrlObj = new URL(serverUrl);
    RequestOptions options = getRequestOptions();
    checkParameters(respIssuer, sns, encodedCerts);
    boolean saveReq = isNotBlank(reqout);
    boolean saveResp = isNotBlank(respout);
    RequestResponseDebug debug = null;
    if (saveReq || saveResp) {
        debug = new RequestResponseDebug(saveReq, saveResp);
    }
    IssuerHash issuerHash = new IssuerHash(HashAlgo.getNonNullInstance(options.getHashAlgorithmId()), Certificate.getInstance(issuerCert.getEncoded()));
    OCSPResp response;
    try {
        response = requestor.ask(issuerCert, sns.toArray(new BigInteger[0]), serverUrlObj, options, debug);
    } finally {
        if (debug != null && debug.size() > 0) {
            RequestResponsePair reqResp = debug.get(0);
            if (saveReq) {
                byte[] bytes = reqResp.getRequest();
                if (bytes != null) {
                    IoUtil.save(reqout, bytes);
                }
            }
            if (saveResp) {
                byte[] bytes = reqResp.getResponse();
                if (bytes != null) {
                    IoUtil.save(respout, bytes);
                }
            }
        }
    // end if
    }
    return processResponse(response, respIssuer, issuerHash, sns, encodedCerts);
}
Also used : RequestResponsePair(org.xipki.common.RequestResponsePair) AttributeCertificateIssuer(org.bouncycastle.cert.AttributeCertificateIssuer) BigIntegerRange(org.xipki.common.util.BigIntegerRange) RequestResponseDebug(org.xipki.common.RequestResponseDebug) RequestOptions(org.xipki.ocsp.client.api.RequestOptions) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) ASN1String(org.bouncycastle.asn1.ASN1String) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) URL(java.net.URL) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) StringTokenizer(java.util.StringTokenizer) IssuerHash(org.xipki.security.IssuerHash) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) BigInteger(java.math.BigInteger)

Example 30 with IllegalCmdParamException

use of org.xipki.console.karaf.IllegalCmdParamException in project xipki by xipki.

the class UserUpdateCmd method execute0.

@Override
protected Object execute0() throws Exception {
    Boolean realActive;
    if (active != null) {
        if (inactive != null) {
            throw new IllegalCmdParamException("maximal one of --active and --inactive can be set");
        }
        realActive = Boolean.TRUE;
    } else if (inactive != null) {
        realActive = Boolean.FALSE;
    } else {
        realActive = null;
    }
    ChangeUserEntry entry = new ChangeUserEntry(new NameId(null, name));
    if (realActive != null) {
        entry.setActive(realActive);
    }
    if ("CONSOLE".equalsIgnoreCase(password)) {
        password = new String(readPassword());
    }
    if (password != null) {
        entry.setPassword(password);
    }
    String msg = "user " + name;
    try {
        caManager.changeUser(entry);
        println("changed " + msg);
        return null;
    } catch (CaMgmtException ex) {
        throw new CmdFailure("could not change " + msg + ", error: " + ex.getMessage(), ex);
    }
}
Also used : CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) NameId(org.xipki.ca.api.NameId) CmdFailure(org.xipki.console.karaf.CmdFailure) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) ChangeUserEntry(org.xipki.ca.server.mgmt.api.ChangeUserEntry)

Aggregations

IllegalCmdParamException (org.xipki.console.karaf.IllegalCmdParamException)42 CmdFailure (org.xipki.console.karaf.CmdFailure)15 File (java.io.File)8 X509Certificate (java.security.cert.X509Certificate)6 CaMgmtException (org.xipki.ca.server.mgmt.api.CaMgmtException)6 P11Slot (org.xipki.security.pkcs11.P11Slot)6 BigInteger (java.math.BigInteger)5 RequestResponseDebug (org.xipki.common.RequestResponseDebug)5 P11ObjectIdentifier (org.xipki.security.pkcs11.P11ObjectIdentifier)5 FileInputStream (java.io.FileInputStream)4 NameId (org.xipki.ca.api.NameId)4 X509CRL (java.security.cert.X509CRL)3 Date (java.util.Date)3 LinkedList (java.util.LinkedList)3 Certificate (org.bouncycastle.asn1.x509.Certificate)3 CertIdOrError (org.xipki.ca.client.api.CertIdOrError)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 InputStream (java.io.InputStream)2 URL (java.net.URL)2 Key (java.security.Key)2