Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

10.9 KB
Raw Blame
package opensuite.proxy;

import opensuite.core.SuiteContext;

import javax.swing.*;
import java.awt.Component;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * The CA certificate actions beneath the proxy listeners: hand the certificate
 * to another tool, adopt one from another installation, or start again with a
 * fresh authority.
 */
final class CertificateActions {

    private CertificateActions() {}

    private static final String TITLE = "CA Certificate";

    /**
     * Export the certificate, its key or both for another tool or installation,
     * or import a certificate and key to use here. What is imported is read and
     * checked first: a file that is not what it should be is refused and the
     * current authority stays.
     */
    static void importExport(Component parent, SuiteContext ctx, ProxyServer server) {
        CertificateAuthority ca = server == null ? null : server.ca();
        if (ca == null) return;
        String[] labels = {
            "Certificate in DER format", "Private key in DER format", "Certificate and private key in PKCS#12 keystore",
            "Certificate and private key in DER format", "Certificate and private key from PKCS#12 keystore"};
        JRadioButton[] pick = new JRadioButton[labels.length];
        ButtonGroup group = new ButtonGroup();
        JPanel page = new JPanel();
        page.setLayout(new BoxLayout(page, BoxLayout.Y_AXIS));
        JLabel intro = new JLabel("<html><body style='width:420px'>You can export your certificate and key for use in other"
                + " tools, or in another installation of Open Suite. You can import a certificate and key to use in this"
                + " installation. You can also export the current certificate by visiting http://opensuite/cert in your"
                + " browser.</body></html>");
        intro.setAlignmentX(Component.LEFT_ALIGNMENT);
        page.add(intro);
        for (int i = 0; i < labels.length; i++) {
            if (i == 0 || i == 3) {
                page.add(Box.createVerticalStrut(12));
                JLabel head = new JLabel(i == 0 ? "Export" : "Import");
                head.setFont(head.getFont().deriveFont(java.awt.Font.BOLD));
                head.setAlignmentX(Component.LEFT_ALIGNMENT);
                page.add(head);
                page.add(Box.createVerticalStrut(4));
            }
            pick[i] = new JRadioButton(labels[i]);
            pick[i].setAlignmentX(Component.LEFT_ALIGNMENT);
            group.add(pick[i]);
            page.add(pick[i]);
        }
        String[] next = {"Next", "Cancel"};
        while (true) {
            int go = JOptionPane.showOptionDialog(parent, page, TITLE, JOptionPane.DEFAULT_OPTION,
                    JOptionPane.PLAIN_MESSAGE, null, next, next[0]);
            if (go != 0) return;
            int chosen = -1;
            for (int i = 0; i < pick.length; i++) if (pick[i].isSelected()) chosen = i;
            if (chosen < 0) continue;
            try {
                switch (chosen) {
                    case 0 -> export(parent, ctx, "opensuite-ca.der", "certificate", ca.caCertificateDer());
                    case 1 -> export(parent, ctx, "opensuite-ca-key.der", "private key", ca.caKeyDer());
                    case 2 -> exportStore(parent, ctx, ca);
                    case 3 -> importFiles(parent, ctx, ca);
                    default -> importStore(parent, ctx, ca);
                }
                return;
            } catch (Back back) {
                // the first page again
            } catch (Exception e) {
                JOptionPane.showMessageDialog(parent, "Failed to " + (chosen < 3 ? "export" : "import") + " certificate: "
                        + e.getMessage(), TITLE, JOptionPane.WARNING_MESSAGE);
            }
        }
    }

    /** The user went back to the first page. */
    private static final class Back extends RuntimeException {
        Back() { super(null, null, false, false); }
    }

    private static void export(Component parent, SuiteContext ctx, String name, String what, byte[] data) throws Exception {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setSelectedFile(new File(name));
        if (fc.showSaveDialog(parent) != JFileChooser.APPROVE_OPTION) throw new Back();
        Path out = fc.getSelectedFile().toPath();
        Files.write(out, data);
        if (!what.equals("certificate")) CertificateAuthority.ownerOnly(out);
        ctx.alert("proxy", "exported the CA " + what + " to " + out);
        JOptionPane.showMessageDialog(parent, "The " + what + " was successfully exported.", TITLE, JOptionPane.INFORMATION_MESSAGE);
    }

    private static void exportStore(Component parent, SuiteContext ctx, CertificateAuthority ca) throws Exception {
        JPasswordField password = new JPasswordField(24);
        String[] next = {"Next", "Back"};
        while (true) {
            int go = JOptionPane.showOptionDialog(parent, opensuite.ui.Ui.form("Password for the keystore:", password), TITLE,
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, next, next[0]);
            if (go != 0) throw new Back();
            if (password.getPassword().length > 0) break;
            JOptionPane.showMessageDialog(parent, "Password is required", TITLE, JOptionPane.WARNING_MESSAGE);
        }
        export(parent, ctx, "opensuite-ca.p12", "certificate and private key", ca.storeBytes(password.getPassword()));
    }

    /** A text field with a button that fills it from a file chooser. */
    private static JPanel fileRow(Component parent, JTextField field) {
        JButton select = opensuite.ui.Ui.button("Select file ...");
        select.addActionListener(e -> {
            JFileChooser fc = new opensuite.ui.FileChooser();
            if (fc.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) field.setText(fc.getSelectedFile().getPath());
        });
        JPanel row = new JPanel(new java.awt.BorderLayout(6, 0));
        row.add(field, java.awt.BorderLayout.CENTER);
        row.add(select, java.awt.BorderLayout.EAST);
        return row;
    }

    private static void importFiles(Component parent, SuiteContext ctx, CertificateAuthority ca) throws Exception {
        JTextField cert = opensuite.ui.Ui.field("", 30), key = opensuite.ui.Ui.field("", 30);
        JPanel page = new JPanel();
        page.setLayout(new BoxLayout(page, BoxLayout.Y_AXIS));
        for (Object[] row : new Object[][] {
                {"Select the file containing the CA certificate to import.", cert},
                {"Select the file containing the private key to import.", key}}) {
            JLabel l = new JLabel((String) row[0]);
            l.setAlignmentX(Component.LEFT_ALIGNMENT);
            JPanel r = fileRow(parent, (JTextField) row[1]);
            r.setAlignmentX(Component.LEFT_ALIGNMENT);
            page.add(l); page.add(Box.createVerticalStrut(4)); page.add(r); page.add(Box.createVerticalStrut(10));
        }
        String[] next = {"Next", "Back"};
        while (true) {
            int go = JOptionPane.showOptionDialog(parent, page, TITLE, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, next, next[0]);
            if (go != 0) throw new Back();
            if (!cert.getText().isBlank() && !key.getText().isBlank()) break;
            JOptionPane.showMessageDialog(parent, "Both files are required", TITLE, JOptionPane.WARNING_MESSAGE);
        }
        adopt(parent, ctx, ca, CertificateAuthority.readFiles(Path.of(cert.getText().trim()), Path.of(key.getText().trim())));
    }

    private static void importStore(Component parent, SuiteContext ctx, CertificateAuthority ca) throws Exception {
        JTextField file = opensuite.ui.Ui.field("", 30);
        JPasswordField password = new JPasswordField(24);
        JPanel page = new JPanel();
        page.setLayout(new BoxLayout(page, BoxLayout.Y_AXIS));
        JLabel l = new JLabel("Select the file containing the keystore to import, and the password for the keystore.");
        l.setAlignmentX(Component.LEFT_ALIGNMENT);
        JPanel r = fileRow(parent, file);
        r.setAlignmentX(Component.LEFT_ALIGNMENT);
        JPanel pw = opensuite.ui.Ui.form("Password:", password);
        pw.setAlignmentX(Component.LEFT_ALIGNMENT);
        page.add(l); page.add(Box.createVerticalStrut(4)); page.add(r); page.add(Box.createVerticalStrut(8)); page.add(pw);
        String[] next = {"Next", "Back"};
        while (true) {
            int go = JOptionPane.showOptionDialog(parent, page, TITLE, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, next, next[0]);
            if (go != 0) throw new Back();
            if (file.getText().isBlank()) { JOptionPane.showMessageDialog(parent, "A file is required", TITLE, JOptionPane.WARNING_MESSAGE); continue; }
            if (password.getPassword().length == 0) { JOptionPane.showMessageDialog(parent, "Password is required", TITLE, JOptionPane.WARNING_MESSAGE); continue; }
            break;
        }
        adopt(parent, ctx, ca, CertificateAuthority.readStore(Path.of(file.getText().trim()), password.getPassword()));
    }

    private static void adopt(Component parent, SuiteContext ctx, CertificateAuthority ca, CertificateAuthority.Pair pair) throws Exception {
        ca.adopt(pair);
        ctx.alert("proxy", "imported a CA certificate: " + pair.cert().getSubjectX500Principal().getName());
        JOptionPane.showMessageDialog(parent, "The CA certificate was successfully imported. The proxy uses it for new"
                + " connections from now on.\nA browser already open may need restarting.", TITLE, JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * Throw the current authority away so a new one is generated. Every client
     * that trusted the old certificate stops trusting this proxy, which is why
     * it is confirmed first.
     */
    static void regenerate(Component parent, SuiteContext ctx, ProxyServer server) {
        int ok = JOptionPane.showConfirmDialog(parent,
                "Generate a new CA certificate?\n\n"
                + "Every browser and tool that trusts the current certificate will stop trusting "
                + "this proxy until the new certificate is installed.",
                "Regenerate CA certificate", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
        if (ok != JOptionPane.OK_OPTION) return;
        try {
            Files.deleteIfExists(server.ca().storePath());
            ctx.alert("proxy", "deleted the CA store; a new authority is generated at the next start");
            JOptionPane.showMessageDialog(parent,
                    "The CA store has been removed. A new certificate is generated when Open Suite "
                    + "next starts and must then be trusted in your browser.",
                    "Regenerate CA certificate", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(parent, "Could not remove the CA store: " + e.getMessage(),
                    "Regenerate CA certificate", JOptionPane.WARNING_MESSAGE);
        }
    }
}