Search in sources :

Example 71 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class PKCS12KeyStore method encryptPrivateKey.

/*
     * Encrypt private key using Password-based encryption (PBE)
     * as defined in PKCS#5.
     *
     * NOTE: By default, pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
     *       used to derive the key and IV.
     *
     * @return encrypted private key encoded as EncryptedPrivateKeyInfo
     */
private byte[] encryptPrivateKey(byte[] data, KeyStore.PasswordProtection passwordProtection) throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
    byte[] key = null;
    try {
        String algorithm;
        AlgorithmParameters algParams;
        AlgorithmId algid;
        // Initialize PBE algorithm and parameters
        algorithm = passwordProtection.getProtectionAlgorithm();
        if (algorithm != null) {
            AlgorithmParameterSpec algParamSpec = passwordProtection.getProtectionParameters();
            if (algParamSpec != null) {
                algParams = AlgorithmParameters.getInstance(algorithm);
                algParams.init(algParamSpec);
            } else {
                algParams = getAlgorithmParameters(algorithm);
            }
        } else {
            // Check default key protection algorithm for PKCS12 keystores
            algorithm = AccessController.doPrivileged(new PrivilegedAction<String>() {

                public String run() {
                    String prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[0]);
                    if (prop == null) {
                        prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[1]);
                    }
                    return prop;
                }
            });
            if (algorithm == null || algorithm.isEmpty()) {
                algorithm = "PBEWithSHA1AndDESede";
            }
            algParams = getAlgorithmParameters(algorithm);
        }
        ObjectIdentifier pbeOID = mapPBEAlgorithmToOID(algorithm);
        if (pbeOID == null) {
            throw new IOException("PBE algorithm '" + algorithm + " 'is not supported for key entry protection");
        }
        // Use JCE
        SecretKey skey = getPBEKey(passwordProtection.getPassword());
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
        byte[] encryptedKey = cipher.doFinal(data);
        algid = new AlgorithmId(pbeOID, cipher.getParameters());
        if (debug != null) {
            debug.println("  (Cipher algorithm: " + cipher.getAlgorithm() + ")");
        }
        // wrap encrypted private key in EncryptedPrivateKeyInfo
        // as defined in PKCS#8
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey);
        key = encrInfo.getEncoded();
    } catch (Exception e) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage());
        uke.initCause(e);
        throw uke;
    }
    return key;
}
Also used : KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) DestroyFailedException(javax.security.auth.DestroyFailedException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKey(javax.crypto.SecretKey) UnrecoverableKeyException(java.security.UnrecoverableKeyException) AlgorithmId(sun.security.x509.AlgorithmId) PrivilegedAction(java.security.PrivilegedAction) EncryptedPrivateKeyInfo(sun.security.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) AlgorithmParameters(java.security.AlgorithmParameters) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 72 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class JRELocaleProviderAdapter method isNonENLangSupported.

/*
     * Returns true if the non EN resources jar file exists in jre
     * extension directory. @returns true if the jar file is there. Otherwise,
     * returns false.
     */
private static boolean isNonENLangSupported() {
    if (isNonENSupported == null) {
        synchronized (JRELocaleProviderAdapter.class) {
            if (isNonENSupported == null) {
                final String sep = File.separator;
                String localeDataJar = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("java.home")) + sep + "lib" + sep + "ext" + sep + LOCALE_DATA_JAR_NAME;
                /*
                     * Peek at the installed extension directory to see if
                     * localedata.jar is installed or not.
                     */
                final File f = new File(localeDataJar);
                isNonENSupported = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                    @Override
                    public Boolean run() {
                        return f.exists();
                    }
                });
            }
        }
    }
    return isNonENSupported;
}
Also used : PrivilegedAction(java.security.PrivilegedAction) File(java.io.File)

Example 73 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class FileDialogFilter method init.

private void init(FileDialog target) {
    //new Dialog(target, target.getTitle(), false);
    fileDialog = target;
    this.title = target.getTitle();
    this.mode = target.getMode();
    this.target = target;
    this.filter = target.getFilenameFilter();
    savedFile = target.getFile();
    savedDir = target.getDirectory();
    // Shouldn't save 'user.dir' to 'savedDir'
    // since getDirectory() will be incorrect after handleCancel
    userDir = (String) AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            return System.getProperty("user.dir");
        }
    });
    installStrings();
    gbl = new GridBagLayout();
    gblButtons = new GridBagLayout();
    gbc = new GridBagConstraints();
    fileDialog.setLayout(gbl);
    // create components
    buttons = new Panel();
    buttons.setLayout(gblButtons);
    actionButtonText = (target.getMode() == FileDialog.SAVE) ? saveButtonText : openButtonText;
    openButton = new Button(actionButtonText);
    filterButton = new Button(filterLabelText);
    cancelButton = new Button(cancelButtonText);
    directoryList = new List();
    fileList = new List();
    filterField = new TextField();
    selectionField = new TextField();
    boolean isMultipleMode = AWTAccessor.getFileDialogAccessor().isMultipleMode(target);
    fileList.setMultipleMode(isMultipleMode);
    // the insets used by the components in the fileDialog
    Insets noInset = new Insets(0, 0, 0, 0);
    Insets textFieldInset = new Insets(0, 8, 0, 8);
    Insets leftListInset = new Insets(0, 8, 0, 4);
    Insets rightListInset = new Insets(0, 4, 0, 8);
    Insets separatorInset = new Insets(8, 0, 0, 0);
    Insets labelInset = new Insets(0, 8, 0, 0);
    Insets buttonsInset = new Insets(10, 8, 10, 8);
    // add components to GridBagLayout "gbl"
    Font f = new Font(Font.DIALOG, Font.PLAIN, 12);
    Label label = new Label(pathLabelText);
    label.setFont(f);
    addComponent(label, gbl, gbc, 0, 0, 1, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.NONE, labelInset);
    // Fixed 6260650: FileDialog.getDirectory() does not return null when file dialog is cancelled
    // After showing we should display 'user.dir' as current directory
    // if user didn't set directory programatically
    pathField = new TextField(savedDir != null ? savedDir : userDir);
    pathChoice = new Choice() {

        public Dimension getPreferredSize() {
            return new Dimension(PATH_CHOICE_WIDTH, pathField.getPreferredSize().height);
        }
    };
    pathPanel = new Panel();
    pathPanel.setLayout(new BorderLayout());
    pathPanel.add(pathField, BorderLayout.CENTER);
    pathPanel.add(pathChoice, BorderLayout.EAST);
    //addComponent(pathField, gbl, gbc, 0, 1, 2,
    //             GridBagConstraints.WEST, (Container)fileDialog,
    //             1, 0, GridBagConstraints.HORIZONTAL, textFieldInset);
    //addComponent(pathChoice, gbl, gbc, 1, 1, GridBagConstraints.RELATIVE,
    //            GridBagConstraints.WEST, (Container)fileDialog,
    //           1, 0, GridBagConstraints.HORIZONTAL, textFieldInset);
    addComponent(pathPanel, gbl, gbc, 0, 1, 2, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.HORIZONTAL, textFieldInset);
    label = new Label(filterLabelText);
    label.setFont(f);
    addComponent(label, gbl, gbc, 0, 2, 1, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.NONE, labelInset);
    addComponent(filterField, gbl, gbc, 0, 3, 2, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.HORIZONTAL, textFieldInset);
    label = new Label(foldersLabelText);
    label.setFont(f);
    addComponent(label, gbl, gbc, 0, 4, 1, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.NONE, labelInset);
    label = new Label(filesLabelText);
    label.setFont(f);
    addComponent(label, gbl, gbc, 1, 4, 1, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.NONE, labelInset);
    addComponent(directoryList, gbl, gbc, 0, 5, 1, GridBagConstraints.WEST, (Container) fileDialog, 1, 1, GridBagConstraints.BOTH, leftListInset);
    addComponent(fileList, gbl, gbc, 1, 5, 1, GridBagConstraints.WEST, (Container) fileDialog, 1, 1, GridBagConstraints.BOTH, rightListInset);
    label = new Label(enterFileNameLabelText);
    label.setFont(f);
    addComponent(label, gbl, gbc, 0, 6, 1, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.NONE, labelInset);
    addComponent(selectionField, gbl, gbc, 0, 7, 2, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.HORIZONTAL, textFieldInset);
    addComponent(new Separator(fileDialog.size().width, 2, Separator.HORIZONTAL), gbl, gbc, 0, 8, 15, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.HORIZONTAL, separatorInset);
    // add buttons to GridBagLayout Buttons
    addComponent(openButton, gblButtons, gbc, 0, 0, 1, GridBagConstraints.WEST, (Container) buttons, 1, 0, GridBagConstraints.NONE, noInset);
    addComponent(filterButton, gblButtons, gbc, 1, 0, 1, GridBagConstraints.CENTER, (Container) buttons, 1, 0, GridBagConstraints.NONE, noInset);
    addComponent(cancelButton, gblButtons, gbc, 2, 0, 1, GridBagConstraints.EAST, (Container) buttons, 1, 0, GridBagConstraints.NONE, noInset);
    // add ButtonPanel to the GridBagLayout of this class
    addComponent(buttons, gbl, gbc, 0, 9, 2, GridBagConstraints.WEST, (Container) fileDialog, 1, 0, GridBagConstraints.HORIZONTAL, buttonsInset);
    fileDialog.setSize(400, 400);
    // Update choice's popup width
    XChoicePeer choicePeer = (XChoicePeer) pathChoice.getPeer();
    choicePeer.setDrawSelectedItem(false);
    choicePeer.setAlignUnder(pathField);
    filterField.addActionListener(this);
    selectionField.addActionListener(this);
    directoryList.addActionListener(this);
    directoryList.addItemListener(this);
    fileList.addItemListener(this);
    fileList.addActionListener(this);
    openButton.addActionListener(this);
    filterButton.addActionListener(this);
    cancelButton.addActionListener(this);
    pathChoice.addItemListener(this);
    pathField.addActionListener(this);
    // b6227750 FileDialog is not disposed when clicking the 'close' (X) button on the top right corner, XToolkit
    target.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent e) {
            handleCancel();
        }
    });
    // 6259434 PIT: Choice in FileDialog is not responding to keyboard interactions, XToolkit
    pathChoice.addItemListener(this);
}
Also used : PrivilegedAction(java.security.PrivilegedAction)

Example 74 with PrivilegedAction

use of java.security.PrivilegedAction in project tomee by apache.

the class BasicURLClassPath method getUcpField.

private Field getUcpField() throws Exception {
    if (ucpField == null) {
        ucpField = AccessController.doPrivileged(new PrivilegedAction<Field>() {

            @Override
            public Field run() {
                try {
                    final Field ucp = URLClassLoader.class.getDeclaredField("ucp");
                    ucp.setAccessible(true);
                    return ucp;
                } catch (final Exception e2) {
                    if (!ucpFieldErrorLogged) {
                        System.err.println("Can't get ucp field of URLClassLoader");
                        ucpFieldErrorLogged = true;
                    }
                }
                return null;
            }
        });
    }
    return ucpField;
}
Also used : Field(java.lang.reflect.Field) PrivilegedAction(java.security.PrivilegedAction) IOException(java.io.IOException)

Example 75 with PrivilegedAction

use of java.security.PrivilegedAction in project admin-console-beta by connexta.

the class GraphQLServlet method query.

private void query(String query, String operationName, Map<String, Object> variables, GraphQLSchema schema, HttpServletRequest req, HttpServletResponse resp, GraphQLContext context) throws IOException {
    if (Subject.getSubject(AccessController.getContext()) == null && context.getSubject().isPresent()) {
        Subject.doAs(context.getSubject().get(), new PrivilegedAction<Void>() {

            @Override
            @SneakyThrows
            public Void run() {
                query(query, operationName, variables, schema, req, resp, context);
                return null;
            }
        });
    } else {
        runListeners(operationListeners, l -> runListener(l, it -> it.beforeGraphQLOperation(context, operationName, query, variables)));
        ExecutionResult executionResult = new GraphQL(schema, getQueryExecutionStrategy(), getMutationExecutionStrategy()).execute(query, operationName, context, transformVariables(schema, query, variables));
        List<GraphQLError> errors = executionResult.getErrors();
        Object data = executionResult.getData();
        String response = mapper.writeValueAsString(createResultFromDataAndErrors(data, errors));
        resp.setContentType(APPLICATION_JSON_UTF8);
        resp.setStatus(STATUS_OK);
        resp.getWriter().write(response);
        if (errorsPresent(errors)) {
            runListeners(operationListeners, l -> l.onFailedGraphQLOperation(context, operationName, query, variables, data, errors));
        } else {
            runListeners(operationListeners, l -> l.onSuccessfulGraphQLOperation(context, operationName, query, variables, data));
        }
    }
}
Also used : InvalidSyntaxError(graphql.InvalidSyntaxError) Setter(lombok.Setter) GraphQL(graphql.GraphQL) ExecutionStrategy(graphql.execution.ExecutionStrategy) Getter(lombok.Getter) SneakyThrows(lombok.SneakyThrows) ServletException(javax.servlet.ServletException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ExecutionResult(graphql.ExecutionResult) HttpServletRequest(javax.servlet.http.HttpServletRequest) CharStreams(com.google.common.io.CharStreams) GraphQLError(graphql.GraphQLError) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) GraphQLSchema(graphql.schema.GraphQLSchema) TypeReference(com.fasterxml.jackson.core.type.TypeReference) JsonDeserializer(com.fasterxml.jackson.databind.JsonDeserializer) RuntimeJsonMappingException(com.fasterxml.jackson.databind.RuntimeJsonMappingException) DeserializationContext(com.fasterxml.jackson.databind.DeserializationContext) JsonParser(com.fasterxml.jackson.core.JsonParser) HttpServlet(javax.servlet.http.HttpServlet) Servlet(javax.servlet.Servlet) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) PrivilegedAction(java.security.PrivilegedAction) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) Subject(javax.security.auth.Subject) Consumer(java.util.function.Consumer) ValidationError(graphql.validation.ValidationError) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Part(javax.servlet.http.Part) Optional(java.util.Optional) AccessController(java.security.AccessController) JsonDeserialize(com.fasterxml.jackson.databind.annotation.JsonDeserialize) InputStream(java.io.InputStream) GraphQL(graphql.GraphQL) SneakyThrows(lombok.SneakyThrows) GraphQLError(graphql.GraphQLError) ExecutionResult(graphql.ExecutionResult)

Aggregations

PrivilegedAction (java.security.PrivilegedAction)129 IOException (java.io.IOException)33 AccessControlContext (java.security.AccessControlContext)18 File (java.io.File)13 InputStream (java.io.InputStream)11 Method (java.lang.reflect.Method)11 ExecutorService (java.util.concurrent.ExecutorService)8 Field (java.lang.reflect.Field)7 Subject (javax.security.auth.Subject)7 PrivilegedActionException (java.security.PrivilegedActionException)6 ArrayList (java.util.ArrayList)6 Properties (java.util.Properties)6 UserGroupInformation (org.apache.hadoop.security.UserGroupInformation)6 FileInputStream (java.io.FileInputStream)5 ProtectionDomain (java.security.ProtectionDomain)5 Enumeration (java.util.Enumeration)5 FileNotFoundException (java.io.FileNotFoundException)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)4 MalformedURLException (java.net.MalformedURLException)4