Example usage for java.lang System getSecurityManager

List of usage examples for java.lang System getSecurityManager

Introduction

In this page you can find the example usage for java.lang System getSecurityManager.

Prototype

public static SecurityManager getSecurityManager() 

Source Link

Document

Gets the system-wide security manager.

Usage

From source file:com.sshtools.sshterm.SshTerminalPanel.java

private void initActions() {
    //  Create the action menu groups
    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("File", "File", 'f', 0));
    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("Edit", "Edit", 'e', 10));
    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("View", "View", 'v', 20));
    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("Proxy", "Proxy", 'p', 80));
    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("Help", "Help", 'h', 90));
    actions = new Vector();

    // MRU//w  w w  .j av  a 2  s .  c o  m
    if (getApplication().getMRUModel() != null) {
        registerAction(mruAction = new MRUActionImpl(getApplication().getMRUModel()));
    }

    //
    connectionPropertiesAction = new ConnectionPropertiesActionImpl();
    registerAction(connectionPropertiesAction);
    newAction = new NewAction();
    registerAction(newAction);

    //  Only allow opening of files if allowed by the security manager
    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "read"));
        }

        openAction = new OpenAction();
        registerAction(openAction);
        playAction = new PlayAction();
        registerAction(playAction);
    } catch (AccessControlException ace) {
        log.warn("File reading actions are not available");
    }

    //  Only allow saving of files if allowed by the security manager
    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write"));
        }

        saveAction = new SaveAction();
        registerAction(saveAction);
        saveAsAction = new SaveAsAction();
        registerAction(saveAsAction);
        recordAction = new RecordAction();
        registerAction(recordAction);
        stopAction = new StopAction();
        registerAction(stopAction);
    } catch (AccessControlException ace) {
        log.warn("File write actions are not available");
    }

    //  Only allow editing of connection file if read / write is allowed
    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write"));
        }

        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "read"));
        }

        editAction = new EditActionImpl();
        registerAction(editAction);
    } catch (AccessControlException ace) {
        log.warn("Read / write actions are not available");
    }

    //  Checking if printing is allowed
    if (pageFormat != null) {
        try {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new RuntimePermission("queuePrintJob"));
            }

            printAction = new PrintActionImpl();
            registerAction(printAction);
            printPreviewAction = new PrintPreviewActionImpl();
            registerAction(printPreviewAction);
        } catch (AccessControlException ace) {
            log.warn("Print actions are not available");
        }
    }

    //  Always allow refreshing of terminal
    refreshAction = new RefreshActionImpl();
    registerAction(refreshAction);

    //  Always allow closing of connect
    closeAction = new CloseAction();
    registerAction(closeAction);

    //  Copy / Paste
    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new AWTPermission("accessClipboard"));
        }

        copyAction = new CopyActionImpl();
        registerAction(copyAction);
        pasteAction = new PasteActionImpl();
        registerAction(pasteAction);
    } catch (AccessControlException ace) {
    }

    //  Theres no point in having the keygen action if we can't write to local file
    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write"));
        }

        keygenAction = new KeygenAction();
        registerAction(keygenAction);
    } catch (AccessControlException ace) {
        log.warn("Keygen actions is not available");
    }

    //  Clear action
    clearAction = new ClearActionImpl();
    registerAction(clearAction);

    // GSI options
    proxyInfoAction = new ProxyInfoAction();
    registerAction(proxyInfoAction);
    proxyDestroyAction = new ProxyDestroyAction();
    registerAction(proxyDestroyAction);

    // Secure Tunneling
    /*try {
      SessionProvider provider = SessionProviderFactory.getInstance().getProvider("tunneling");
      if(provider!=null) {
        tunnelingAction = (StandardAction)new SessionProviderAction(
    provider);
        registerAction(tunnelingAction);
      }
         }
         catch (Throwable t) {
      log.info(
          "Secure Tunneling not available on CLASSPATH");
         }
         //  ShiFT action
         try {
      SessionProvider provider = SessionProviderFactory.getInstance().getProvider("shift");
      if(provider!=null) {
        shiftAction = (StandardAction)new SessionProviderAction(
    provider);
        registerAction(shiftAction);
      }
         }
         catch (Throwable t) {
      log.info(
          "ShiFT not available on CLASSPATH");
         }*/

    java.util.List providers = SessionProviderFactory.getInstance().getSessionProviders();
    SessionProvider provider;
    SessionProviderAction action;
    for (Iterator it = providers.iterator(); it.hasNext();) {
        provider = (SessionProvider) it.next();
        action = new SessionProviderAction(provider);
        sessionActions.put(action.getActionCommand(), action);
        registerAction(action);
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean/*  w ww  .ja  v  a2  s.c  om*/
 * @param mbd the bean definition for the bean
 * @return a BeanWrapper for the new instance
 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController
                    .doPrivileged((PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd,
                            beanName, parent), getAccessControlContext());
        } else {
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed",
                ex);
    }
}

From source file:Tcpbw100.java

public boolean test_sfw(Protocol ctl) throws IOException {
    Message msg = new Message();
    if ((tests & TEST_SFW) == TEST_SFW) {
        showStatus(messages.getString("sfwTest"));
        results.append(messages.getString("checkingFirewalls") + "  ");
        statistics.append(messages.getString("checkingFirewalls") + "  ");
        emailText = messages.getString("checkingFirewalls") + "  ";
        pub_status = "checkingFirewalls";

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }/*from www.  j  a  v a 2 s.  c  o m*/
        if (msg.type != TEST_PREPARE) {
            errmsg = messages.getString("sfwWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }

        String message = new String(msg.body);

        int srvPort, testTime;
        try {
            int k = message.indexOf(" ");
            srvPort = Integer.parseInt(message.substring(0, k));
            testTime = Integer.parseInt(message.substring(k + 1));
        } catch (Exception e) {
            errmsg = messages.getString("sfwWrongMessage") + "\n";
            return true;
        }

        System.out.println("SFW: port=" + srvPort);
        System.out.println("SFW: testTime=" + testTime);

        ServerSocket srvSocket;
        try {
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                System.out.println("Asking security manager for listen permissions...");
                security.checkListen(0);
            }
            srvSocket = new ServerSocket(0);
        } catch (Exception e) {
            e.printStackTrace();
            errmsg = messages.getString("sfwSocketFail") + "\n";
            return true;
        }

        System.out.println("SFW: oport=" + srvSocket.getLocalPort());
        ctl.send_msg(TEST_MSG, Integer.toString(srvSocket.getLocalPort()).getBytes());

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_START) {
            errmsg = messages.getString("sfwWrongMessage");
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }

        OsfwWorker osfwTest = new OsfwWorker(srvSocket, testTime);
        new Thread(osfwTest).start();

        Socket sfwSocket = new Socket();
        try {
            sfwSocket.connect(new InetSocketAddress(host, srvPort), testTime * 1000);

            Protocol sfwCtl = new Protocol(sfwSocket);
            sfwCtl.send_msg(TEST_MSG, new String("Simple firewall test").getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_MSG) {
            errmsg = messages.getString("sfwWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        c2sResult = Integer.parseInt(new String(msg.body));

        osfwTest.finalize();

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_FINALIZE) {
            errmsg = messages.getString("sfwWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        results.append(messages.getString("done") + "\n");
        statistics.append(messages.getString("done") + "\n");
        emailText += messages.getString("done") + "\n%0A";
    }
    return false;
}

From source file:org.rythmengine.RythmEngine.java

/**
 * Create a {@link Sandbox} instance to render the template
 *
 * @return an new sandbox instance/*from w  w  w . ja  va 2  s . c o  m*/
 */
public synchronized Sandbox sandbox() {
    if (null != _secureExecutor) {
        return new Sandbox(this, _secureExecutor);
    }
    int poolSize = (Integer) conf().get(RythmConfigurationKey.SANDBOX_POOL_SIZE);
    SecurityManager csm = conf().get(RythmConfigurationKey.SANDBOX_SECURITY_MANAGER_IMPL);
    int timeout = (Integer) conf().get(RythmConfigurationKey.SANDBOX_TIMEOUT);
    SandboxThreadFactory fact = conf().get(RythmConfigurationKey.SANBOX_THREAD_FACTORY_IMPL);

    SecurityManager ssm = System.getSecurityManager();
    RythmSecurityManager rsm;
    String code;
    if (null == ssm || !(ssm instanceof RythmSecurityManager)) {
        code = conf().get(RythmConfigurationKey.SANDBOX_SECURE_CODE);
        rsm = new RythmSecurityManager(csm, code, this);
    } else {
        rsm = ((RythmSecurityManager) ssm);
        code = rsm.getCode();
    }
    secureCode = code;
    _secureExecutor = new SandboxExecutingService(poolSize, fact, timeout, this, code);
    Sandbox sandbox = new Sandbox(this, _secureExecutor);
    if (ssm != rsm)
        System.setSecurityManager(rsm);
    return sandbox;
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Apply the given property values, resolving any runtime references
 * to other beans in this bean factory. Must use deep copy, so we
 * don't permanently modify this property.
 * @param beanName the bean name passed for better exception information
 * @param mbd the merged bean definition
 * @param bw the BeanWrapper wrapping the target object
 * @param pvs the new property values/* www .  j a  v a2s  .co  m*/
 */
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs.isEmpty()) {
        return;
    }

    if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
        ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
    }

    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;

    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        if (mpvs.isConverted()) {
            // Shortcut: use the pre-converted values as-is.
            try {
                bw.setPropertyValues(mpvs);
                return;
            } catch (BeansException ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Error setting property values", ex);
            }
        }
        original = mpvs.getPropertyValueList();
    } else {
        original = Arrays.asList(pvs.getPropertyValues());
    }

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

    // Create a deep copy, resolving any references for values.
    List<PropertyValue> deepCopy = new ArrayList<>(original.size());
    boolean resolveNecessary = false;
    for (PropertyValue pv : original) {
        if (pv.isConverted()) {
            deepCopy.add(pv);
        } else {
            String propertyName = pv.getName();
            Object originalValue = pv.getValue();
            Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
            Object convertedValue = resolvedValue;
            boolean convertible = bw.isWritableProperty(propertyName)
                    && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
            if (convertible) {
                convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
            }
            // Possibly store converted value in merged bean definition,
            // in order to avoid re-conversion for every created bean instance.
            if (resolvedValue == originalValue) {
                if (convertible) {
                    pv.setConvertedValue(convertedValue);
                }
                deepCopy.add(pv);
            } else if (convertible && originalValue instanceof TypedStringValue
                    && !((TypedStringValue) originalValue).isDynamic()
                    && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                pv.setConvertedValue(convertedValue);
                deepCopy.add(pv);
            } else {
                resolveNecessary = true;
                deepCopy.add(new PropertyValue(pv, convertedValue));
            }
        }
    }
    if (mpvs != null && !resolveNecessary) {
        mpvs.setConverted();
    }

    // Set our (possibly massaged) deep copy.
    try {
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    } catch (BeansException ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values",
                ex);
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Initialize the given bean instance, applying factory callbacks
 * as well as init methods and bean post processors.
 * <p>Called from {@link #createBean} for traditionally defined beans,
 * and from {@link #initializeBean} for existing bean instances.
 * @param beanName the bean name in the factory (for debugging purposes)
 * @param bean the new bean instance we may need to initialize
 * @param mbd the bean definition that the bean was created with
 * (can also be {@code null}, if given an existing bean instance)
 * @return the initialized bean instance (potentially wrapped)
 * @see BeanNameAware//from   w  ww.  j  a  v a  2 s . c  om
 * @see BeanClassLoaderAware
 * @see BeanFactoryAware
 * @see #applyBeanPostProcessorsBeforeInitialization
 * @see #invokeInitMethods
 * @see #applyBeanPostProcessorsAfterInitialization
 */
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    } else {
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        invokeInitMethods(beanName, wrappedBean, mbd);
    } catch (Throwable ex) {
        throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null), beanName,
                "Invocation of init method failed", ex);
    }
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Give a bean a chance to react now all its properties are set,
 * and a chance to know about its owning bean factory (this object).
 * This means checking whether the bean implements InitializingBean or defines
 * a custom init method, and invoking the necessary callback(s) if it does.
 * @param beanName the bean name in the factory (for debugging purposes)
 * @param bean the new bean instance we may need to initialize
 * @param mbd the merged bean definition that the bean was created with
 * (can also be {@code null}, if given an existing bean instance)
 * @throws Throwable if thrown by init methods or by the invocation process
 * @see #invokeCustomInitMethod/*ww w.j  av  a 2 s  .c  o  m*/
 */
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
        throws Throwable {

    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isTraceEnabled()) {
            logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((InitializingBean) bean).afterPropertiesSet();
                    return null;
                }, getAccessControlContext());
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        } else {
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }

    if (mbd != null && bean.getClass() != NullBean.class) {
        String initMethodName = mbd.getInitMethodName();
        if (StringUtils.hasLength(initMethodName)
                && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName))
                && !mbd.isExternallyManagedInitMethod(initMethodName)) {
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Invoke the specified custom init method on the given bean.
 * Called by invokeInitMethods.//from w  w w  . ja v a  2  s. c o  m
 * <p>Can be overridden in subclasses for custom resolution of init
 * methods with arguments.
 * @see #invokeInitMethods
 */
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {

    String initMethodName = mbd.getInitMethodName();
    Assert.state(initMethodName != null, "No init method set");
    final Method initMethod = (mbd.isNonPublicAccessAllowed()
            ? BeanUtils.findMethod(bean.getClass(), initMethodName)
            : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

    if (initMethod == null) {
        if (mbd.isEnforceInitMethod()) {
            throw new BeanDefinitionValidationException("Couldn't find an init method named '" + initMethodName
                    + "' on bean with name '" + beanName + "'");
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("No default init method named '" + initMethodName + "' found on bean with name '"
                        + beanName + "'");
            }
            // Ignore non-existent default lifecycle methods.
            return;
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
    }

    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            ReflectionUtils.makeAccessible(initMethod);
            return null;
        });
        try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> initMethod.invoke(bean),
                    getAccessControlContext());
        } catch (PrivilegedActionException pae) {
            InvocationTargetException ex = (InvocationTargetException) pae.getException();
            throw ex.getTargetException();
        }
    } else {
        try {
            ReflectionUtils.makeAccessible(initMethod);
            initMethod.invoke(bean);
        } catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

From source file:org.apache.click.util.ClickUtils.java

/**
 * Returns true if Click resources (JavaScript, CSS, images etc) packaged
 * in jars can be deployed to the root directory of the webapp, false
 * otherwise.//from   ww  w  . java 2s .c o m
 * <p/>
 * This method will return false in restricted environments where write
 * access to the underlying file system is disallowed. Examples where
 * write access is not allowed include the WebLogic JEE server (this can be
 * changed though) and Google App Engine.
 *
 * @param servletContext the application servlet context
 * @return true if writes are allowed, false otherwise
 */
public static boolean isResourcesDeployable(ServletContext servletContext) {
    try {
        boolean canWrite = (servletContext.getRealPath("/") != null);
        if (!canWrite) {
            return false;
        }

        // Since Google App Engine returns a value for getRealPath, check
        // SecurityManager if writes are allowed
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite("/click");
        }
        return true;
    } catch (Throwable e) {
        return false;
    }
}