Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

According to the Java API Class SecurityManager documentation [API 2014],

The security manager is a class that allows applications to implement a security policy. It allows an application to determine, before performing a possibly unsafe or sensitive operation, what the operation is and whether it is being attempted in a security context that allows the operation to be performed. The application can allow or disallow the operation.

A security manager may be associated with any Java code.

The applet security manager denies applets all but the most essential privileges. It is designed to protect against inadvertent system modification, information leakage, and user impersonation. The use of security managers is not limited to client-side protection. Web servers, such as Tomcat and WebSphere, use this facility to isolate trojan servlets and malicious Java Server Pages (JSP) code as well as to protect sensitive system resources from inadvertent access.

Java applications that run from the command line can set a default or custom security manager using a command-line flag. Alternatively, it is possible to install a security manager programmatically. Installing a security manager programmatically helps create a default sandbox that allows or denies sensitive actions on the basis of the security policy in effect.

From Java 2 SE Platform onward, SecurityManager is a nonabstract class. As a result, there is no explicit requirement to override its methods. To create and use a security manager programmatically, the code must have the runtime permissions createSecurityManager (to instantiate SecurityManager) and setSecurityManager (to install it). These permissions are checked only if a security manager is already installed. This is useful for situations in which a default security manager is in place, such as on a virtual host, and individual hosts must be denied the requisite permissions for overriding the default security manager with a custom one.

The security manager is closely tied to the AccessController class. The former is used as a hub for access control, whereas the latter provides the actual implementation of the access control algorithm. The security manager supports

  • Providing backward compatibility: Legacy code often contains custom implementations of the security manager class because it was originally abstract.
  • Defining custom policies: Subclassing the security manager permits definition of custom security policies (for example, multilevel, coarse, or fine grain).

Regarding the implementation and use of custom security managers as opposed to default ones, the Java security architecture specification [SecuritySpec 2010] states:

We encourage the use of AccessController in application code, while customization of a security manager (via subclassing) should be the last resort and should be done with extreme care. Moreover, a customized security manager, such as one that always checks the time of the day before invoking standard security checks, could and should utilize the algorithm provided by AccessController whenever appropriate.

Many of the Java SE APIs perform security manager checks by default before performing sensitive operations. For example, the constructor of class java.io.FileInputStream throws a SecurityException if the caller does not have the permission to read a file. Because SecurityException is a subclass of RuntimeException, the declarations of some API methods (for example, those of the java.io.FileReader class) may lack a throws clause that lists the SecurityException. Avoid depending on the presence or absence of security manager checks that are not specified in the API method's documentation.

Noncompliant Code Example (Command-Line Installation)

This noncompliant code example fails to install any security manager from the command line. Consequently, the program runs with all permissions enabled; that is, there is no security manager to prevent any nefarious actions the program might perform.

Code Block
bgColor#FFcccc
java LocalJavaApp

Compliant Solution (Default Policy File)

Any Java program can attempt to install a SecurityManager programmatically, although the currently active security manager may forbid this operation. Applications designed to run locally can specify a default security manager by use of a flag on the command line at invocation.

The command-line option is preferred when applications must be prohibited from installing custom security managers programmatically and are required to abide by the default global security policy under all circumstances. This compliant solution installs the default security manager using the appropriate command-line flags. The security policy file grants permissions to the application for its intended actions.

Code Block
bgColor#ccccff
java -Djava.security.manager -Djava.security.policy=policyURL \
     LocalJavaApp

The command-line flag can specify a custom security manager whose policies are enforced globally. Use the -Djava.security.manager flag, as follows:

Code Block
java -Djava.security.manager=my.security.CustomManager ...

If the current security policy enforced by the current security manager forbids replacements (by omitting the RuntimePermission("setSecurityManager")), any attempt to invoke setSecurityManager() will throw a SecurityException.

The default security policy file java.policy—found in the /path/to/java.home/lib/security directory on UNIX-like systems and its equivalent on Microsoft Windows systems—grants a few permissions (reading system properties, binding to unprivileged ports, and so forth). A user-specific policy file may be located in the user's home directory. The union of these policy files specifies the permissions granted to a program. The java.security file can specify which policy files are used. If either of the systemwide java.policy or java.security files is deleted, no permissions are granted to the executing Java program.

Compliant Solution (Custom Policy File)

Use double equals (==) instead of the single equals (=) when overriding the global Java security policy file with a custom policy file:

Code Block
bgColor#ccccff
java -Djava.security.manager \
     -Djava.security.policy==policyURL \
     LocalJavaApp

Compliant Solution (Additional Policy Files)

The appletviewer automatically installs a security manager with the standard policy file. To specify additional policy files, use the -J flag.

Code Block
bgColor#ccccff
appletviewer -J-Djava.security.manager \
Wiki Markup
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>ENV30-J. Create a secure sandbox using a Security Manager - CERT Secure Coding Standards</title>

        

                        
    
            
<meta id="confluence-context-path" name="confluence-context-path" content="/confluence">
<meta id="atlassian-token" name="atlassian-token" content="3UIncFJ_LX">
<meta id="confluence-space-key" name="confluence-space-key" content="java">

<script type="text/javascript">
    // Deprecated global variables. To be removed in a future version of Confluence.
    var contextPath = '/confluence';
    var i18n = [];
</script>

    

<!-- include system resources -->
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:prototype/confluence.web.resources:prototype.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:scriptaculous/confluence.web.resources:scriptaculous.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:jquery/com.atlassian.auiplugin:jquery.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:jquery-base/com.atlassian.auiplugin:jquery-base.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:ajs/com.atlassian.auiplugin:ajs.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:dwr/engine.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:dwr/util.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:page-editor/confluence.web.resources:page-editor.css" media="all"/>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:page-editor/dwr-wysiwyg-converter.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:page-editor/dwr-user-profile-editor.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:page-editor/dwr-draft.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:page-editor/dwr-heartbeat.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:page-editor/confluence.web.resources:page-editor.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:jquery-selection/com.atlassian.auiplugin:jquery-selection.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:dialog/com.atlassian.auiplugin:dialog.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:dialog/com.atlassian.auiplugin:dialog.css" media="all"/>
<!--[if IE]>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:dialog/com.atlassian.auiplugin:dialog.css?ieonly=true" media="all"/>
<![endif]-->
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:raphael/confluence.web.resources:raphael.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.editor.actions:editor-macro-browser/confluence.editor.actions:editor-macro-browser.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.editor.actions:editor-macro-browser/confluence.editor.actions:editor-macro-browser.css" media="all"/>
<!--[if IE]>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.editor.actions:editor-macro-browser/confluence.editor.actions:editor-macro-browser.css?ieonly=true" media="all"/>
<![endif]-->
<script type="text/javascript" src="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:jquery-ui-draggable/com.atlassian.auiplugin:jquery-ui-draggable.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:page-ordering-tree/confluence.web.resources:page-ordering-tree.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:page-ordering-tree/confluence.web.resources:page-ordering-tree.css" media="all"/>
<!--[if IE]>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:page-ordering-tree/confluence.web.resources:page-ordering-tree.css?ieonly=true" media="all"/>
<![endif]-->
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:page-location-editor/confluence.web.resources:page-location-editor.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:page-permissions-editor/confluence.web.resources:page-permissions-editor.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:page-permissions-editor/EntitiesAjaxService.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:labels-editor/AddLabeltoEntity.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:labels-editor/RemoveLabelFromEntity.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:labels-editor/SuggestedLabelsForEntity.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:labels-editor/GenerateAutocompleteLabelsListForEntity.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:labels-editor/confluence.web.resources:labels-editor.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:labels-editor/confluence.web.resources:labels-editor.css" media="all"/>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:master-styles/confluence.web.resources:master-styles.css" media="all"/>
<!--[if IE]>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:master-styles/confluence.web.resources:master-styles.css?ieonly=true" media="all"/>
<![endif]-->
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:breadcrumbs/confluence.web.resources:breadcrumbs.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:print-styles/confluence.web.resources:print-styles.css?media=print" media="print"/>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:safe-ajax/confluence.web.resources:safe-ajax.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.userstatus:userstatus-resources/confluence.userstatus:userstatus-resources.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.userstatus:userstatus-resources/confluence.userstatus:userstatus-resources.css" media="all"/>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:master-scripts/confluence.web.resources:master-scripts.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/resources/confluence.web.resources:master-scripts/PageNotification.js" ></script>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:contentnamesearch/confluence.web.resources:contentnamesearch.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:contentnamesearch/confluence.web.resources:contentnamesearch.css" media="all"/>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:userlink/confluence.web.resources:userlink.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:userlink/confluence.web.resources:userlink.css" media="all"/>
<!--[if IE]>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:userlink/confluence.web.resources:userlink.css?ieonly=true" media="all"/>
<![endif]-->
<script type="text/javascript" src="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:drop-down/com.atlassian.auiplugin:drop-down.js" ></script>
<link type="text/css" rel="stylesheet" href="/confluence/s/1627/6/1.0.2/_/download/batch/com.atlassian.auiplugin:drop-down/com.atlassian.auiplugin:drop-down.css" media="all"/>
<script type="text/javascript" src="/confluence/s/1627/6/1.0/_/download/batch/confluence.web.resources:atlassian-effects/confluence.web.resources:atlassian-effects.js" ></script>

<!-- end system resources -->

    <link rel="stylesheet" href="/confluence/s/1627/6/1/_/styles/combined.css?spaceKey=jg" type="text/css">

    <meta name="robots" content="noindex,nofollow">
    <meta name="robots" content="noarchive">
    <meta name="confluence-request-time" content="1250711135246">

    <link rel="shortcut icon" href="/confluence/favicon.ico">
    <link rel="icon" type="image/png" href="/confluence/s/1627/6/_/images/logo/confluence_16.png">

<link rel="search" type="application/opensearchdescription+xml" href="/confluence/opensearch/osd.action" title="CERT Secure Coding Standards"/>

    

    <script type="text/javascript">

    function toggleMenu(menuId)
    {
        var visible = toggleVisibility(menuId);
        if (visible)
            setCookie("confluence.leftnav." + menuId, true);
        else
            setCookie("confluence.leftnav.", false);
    }

    function isMenuExpanded(menuId)
    {
        return getCookie("confluence.leftnav." + menuId);
    }

    function initMenuItem(menuId)
    {
        if (document.getElementById(menuId))
        {
            if (isMenuExpanded(menuId) == 'true')
            {
                document.getElementById(menuId).style.display = "block";
            }
            else
            {
                document.getElementById(menuId).style.display = "none";
            }
        }
    }
</script>

</head>

            <body onload="placeFocus()" id="com-atlassian-confluence">
    <!--BEGIN HEADER -->

<table border="0" width="100%" cellspacing="0" cellpadding="0" bgcolor="#ffffff"><tr>
<td valign="middle"><img src="https://www.cert.org/images/1pxinv.gif" width="5" height="94"></td><td valign="middle"><a href="https://www.cert.org/"><img 
src="https://www.cert.org/cert/images/cert_logo.gif" alt="CERT" border="0"></a></td><td valign="bottom" align="right" width="100%">

<!--NAVIGATION TABLE-->
<table border="0" cellspacing="0" cellpadding="0" width="600"><a href="https://www.cert.org/work/software_assurance.html"><img src="https://www.cert.org/cert/images/1off.jpg" 
width="132" height="21" 
alt="Software Assurance" border="0"></a><img src="https://www.cert.org/images/1pxinv.gif" width="1" height="21"><a href="https://www.cert.org/work/secure_systems.html"><img 
src="https://www.cert.org/cert/images/2off.jpg" width="109" height="21" alt="Secure Systems" border="0"></a><img src="https://www.cert.org/images/1pxinv.gif" width="1" height="21"><a 
href="https://www.cert.org/work/organizational_security.html"><img 
src="https://www.cert.org/cert/images/3off.jpg" width="140" height="21" alt="Organizational Security" border="0"></a><img src="https://www.cert.org/images/1pxinv.gif" width="1" height="21"><a 
href="https://www.cert.org/work/coordinating_response.html"><img 
src="https://www.cert.org/cert/images/4off.jpg" width="140" height="21" alt="Coordinating Response" border="0"></a><img 
src="https://www.cert.org/images/1pxinv.gif" width="1" height="21"><a href="https://www.cert.org/work/training.html"><img src="https://www.cert.org/cert/images/5off.jpg" width="75" 
height="21" alt="Training" border="0"></a></td></tr></table>

<!--END NAVIGATION TABLE -->

</td></tr></table>

<table border="0" width="100%" cellspacing="0" cellpadding="0" bgcolor="#666666"><tr><td><img src="https://www.cert.org/images/1pxinv.gif" width="1" height="3"></td></tr></table>

<!--END HEADER -->


    <script type="text/javascript">
        AJS.toInit(function ($) {
            $(".message-close-button").each(function () {
                var li = $(this).parent();
                var cookieId = this.alt;
                $(this).click(function () {
                    li.slideUp();
                    setCookie(cookieId, true);
                });
            });

            $("#messageContainer .confluence-messages").each(function () {
                if (!getCookie(this.id)) {
                    $(this).show();
                }
            })
        });
    </script>

        

<div id="header">
        <form id="quick-search" class="quick-search" method="get" action="/confluence/dosearchsite.action">
                <fieldset>
            <legend>Quick Search</legend>
            <input class="quick-search-query" id="quick-search-query" type="text" accessKey="q" autocomplete="off" name="queryString" size="25" />
            <input class="quick-search-submit" id="quick-search-submit" type="submit" value="Search" />
        </fieldset>
        <fieldset class="hidden parameters">
            <input type="hidden" class="quickSearchPlaceholder" id="quickSearchPlaceholder" value="Search" />

            <input type="hidden" id="quickNavEnabled" value="true" />
             <!-- Quick nav disabled. SettingsManager could not be found -->         </fieldset>
    </form>
    
    
    <ol id="breadcrumbs">
                    
        <li class="first" ><span>
                                    <a href="/confluence/dashboard.action">Dashboard</a>
                </span></li>
                    
        <li><span>
                                    <a href="/confluence/display/java">java</a>
                </span></li>
                                        <li id="ellipsis" title="    &#8230;
                    The CERT Sun Microsystems Secure Coding Standard for Java
        &#8230;
"><span><strong>&#8230;</strong></span></li>
                                    
        <li class="hidden-crumb" ><span>
                                    <a href="/confluence/display/java/The+CERT+Sun+Microsystems+Secure+Coding+Standard+for+Java">The CERT Sun Microsystems Secure Coding Standard for Java</a>
                </span></li>
                    
        <li><span>
                                    <a href="/confluence/display/java/00.+Runtime+Environment+%28ENV%29">00. Runtime Environment (ENV)</a>
                </span></li>
                    
        <li><span>
                                    <a href="/confluence/display/java/ENV30-J.+Create+a+secure+sandbox+using+a+Security+Manager">ENV30-J. Create a secure sandbox using a Security Manager</a>
                </span></li>
                    
        <li><span>
                                    Edit Page
                </span></li>
        </ol>

</div>

<div id="PageContent">
    <table cellspacing="0" cellpadding="0" width="100%">
        <tr>
                    <td width="150px" valign="top" class="sidebar" nowrap>
                <div class="leftnav">
                     <div id="logodiv">
                        					        <a href="/confluence/display/java"><img class="logo global" src="/confluence/images/logo/confluence_48_white.png" alt=""></a>					                          </div>
                      <div id="menu">
                        <table class="sectionMacro" border="0" cellpadding="5" cellspacing="0" width="100%"><tbody><tr>
<td class="confluenceTd" valign="top" width="105%">
<div class='panelMacro'><table class='infoMacro'><tr><td><p><b>Standards</b><br/>
<a href="/confluence/display/seccode/CERT+Secure+Coding+Standards" title="CERT Secure Coding Standards">Overview</a><br/>
<a href="/confluence/display/seccode/CERT+C+Secure+Coding+Standard" title="CERT C Secure Coding Standard">C Language</a><br/>
<a href="/confluence/pages/viewpage.action?pageId=637" title="CERT C++ Secure Coding Standard">C+&#43;</a><br/>
<a href="/confluence/display/java/The+CERT+Sun+Microsystems+Secure+Coding+Standard+for+Java" title="The CERT Sun Microsystems Secure Coding Standard for Java">Java</a></p>

<p><b>CERT Websites</b><br/>
<a href="http://www.cert.org/" rel="nofollow">CERT</a><br/>
<a href="http://www.cert.org/secure-coding" rel="nofollow">Secure Coding</a><br/>
<a href="http://www.cert.org/tech_tips/" rel="nofollow">Tech Tips</a></p>

<p><b>Related Websites</b><br/>
<a href="https://buildsecurityin.us-cert.gov/daisy/bsi/home.html" rel="nofollow">Build Security In</a></p>

<p><a href="http://www.informit.com/store/product.aspx?isbn=0321563212" rel="nofollow"><span class="image-wrap" style=""><img src="https://www.cert.org/images/cert-c-book-cover-100.jpg" border="0" width="100" /></span></a></p>

<p><a href="http://www.cert.org/books/secure-coding/" rel="nofollow"><span class="image-wrap" style=""><img src="https://www.cert.org/images/securec.jpg" border="0" width="100" /></span></a></p>

<p><b>Related Sites</b><br/>
<a href="http://www.us-cert.gov/" rel="nofollow"><span class="image-wrap" style=""><img src="https://www.cert.org/images/logo/uscert_4g_sm.jpg" border="0" /></span></a><br/>
<a href="http://www.cylab.cmu.edu/" title="http://www.cylab.cmu.edu/" rel="nofollow"><span class="image-wrap" style=""><img src="https://www.cert.org/images/logo/cylab_alt.jpg" border="0" /></span></a></p></td></tr></table></div></td></tr></tbody></table>
                        
<h5><a href="#" onCLick="toggleMenu('pagenav'); return false;"><img src="/confluence/images/icons/docs_16.gif" width=16 height=16 border=0 align=absmiddle >Page Operations</a></h5>
<div id="pagenav" class="subnav" style="display:none;">
   <ul>
	   		   <li><a  id="viewPageLink"  href="/confluence/display/java/ENV30-J.+Create+a+secure+sandbox+using+a+Security+Manager"   onClick="javascript:saveDraftOnPageChange(this); return false;"   accessKey="v"><u>V</u>iew</a></li>
	   		   <li><a  id="editPageLink"  href="/confluence/pages/editpage.action?pageId=18186729"  class="current"   onClick="javascript:saveDraftOnPageChange(this); return false;"   accessKey="e"><u>E</u>dit</a></li>
	   		   <li><a  id="view-attachments-link"  href="/confluence/pages/viewpageattachments.action?pageId=18186729"   onClick="javascript:saveDraftOnPageChange(this); return false;"   accessKey="a"><u>A</u>ttachments (0)</a></li>
	   		   <li><a  id="view-page-info-link"  href="/confluence/pages/viewinfo.action?pageId=18186729"   onClick="javascript:saveDraftOnPageChange(this); return false;"   accessKey="i"><u>I</u>nfo</a></li>
	   		   <li><a  href="/confluence/pages/worddav/uploadimport.action?pageId=18186729"   onClick="javascript:saveDraftOnPageChange(this); return false;"  >Doc Import</a></li>
	      </ul>
</div>

                        
                        
<h5><a href="#" onCLick="toggleMenu('browsenav'); return false;"><img src="/confluence/images/icons/browse_space.gif" height="16" width="16" border="0" align="absmiddle" title="Find Content">Browse Space</a></h5>
<div id="browsenav" class="subnav" style="display:none;">
	<ul>
					<li><a href="/confluence/pages/listpages.action?key=java" >Pages</a></li>
					<li><a href="/confluence/pages/viewrecentblogposts.action?key=java" >News</a></li>
					<li><a href="/confluence/labels/listlabels-heatmap.action?key=java" >Labels</a></li>
					<li><a href="/confluence/spaces/listattachmentsforspace.action?key=java" >Attachments</a></li>
					<li><a href="/confluence/spaces/viewmailarchive.action?key=java" >Mail</a></li>
					<li><a href="/confluence/spaces/viewspacesummary.action?key=java" >Advanced</a></li>
			</ul>
</div>

<h5><a href="#" onCLick="toggleMenu('addcontent'); return false;"><img src="/confluence/images/icons/add_16.gif" height="16" width="16" border="0" align="absmiddle" title="Add Content">Add Content</a></h5>
<div id="addcontent" class="subnav" style="display:none;">
    <ul>
										
									<li><a href="/confluence/pages/createpage.action?spaceKey=jg&fromPageId=18186729"><img src="/confluence/images/icons/add_page_16.gif" height="16" width="16" border="0" align="absmiddle" title="Add Page">&nbsp;Add Page</a></li>
						    					
									<li><a href="/confluence/pages/createblogpost.action?spaceKey=jg"><img src="/confluence/images/icons/add_blogentry_16.gif" height="16" width="16" border="0" align="absmiddle" title="Add News">&nbsp;Add News</a></li>
						    			</ul>
</div>

                      </div>
                    <script type="text/javascript">
                        initMenuItem("browsenav");
                        initMenuItem("pagenav");
                        initMenuItem("addcontent");
                    </script>
                </div>
            </td>
                    <td valign="top" width="100%">
                <!-- Inner content table -->
                <table width="100%" cellpadding="2" cellspacing="0">
                    <tr>
                        <td colspan="2" valign="middle" align="right" style="background-color:#F0F0F0">
                            
    <ul id="page-view-panel">
        <li>    <a href="/confluence/pages/editpage.action?pageId=18186729&decorator=printable" rel="nofollow" title="View a printable version of the current page." class="print icon">View a printable version of the current page.</a>
</li>
                    <li>    
                            <a href="/confluence/spaces/flyingpdf/pdfpageexport.action?pageId=18186729&atl_token=3UIncFJ_LX" rel="nofollow" title="Export Page as PDF" class="pdf icon">Export Page as PDF</a>
                        </li>
                 <li>    </li>
    </ul>

                                        <ul id="user-control-panel">
                    <li class="first">Welcome <a href="/confluence/display/~agoyal">Ankur Goyal</a></li>

                                                                                    <li><a  id="set-user-status-link" href="/confluence/display/~agoyal" >Update Status&hellip;</a></li>
                                            <li><a  id="view-user-history-link" href="/confluence/users/viewuserhistory.action" >Recently Viewed</a></li>
                                            <li><a  id="user-settings-link" href="/confluence/users/viewmysettings.action" >Settings</a></li>
                                            <li><a  id="logout-link" href="/confluence/logout.action" >Log Out</a></li>
                                                                </ul>
                            </td>
                    </tr>
                    <tr>
                        <td id="mainViewPane">
                            <div>
                                <table class="fullWidthBorderless">
                                    <td><span id="spaceFullNameLink">            <a href="/confluence/display/java">java</a>    </span></td>
                                    <td align="right">
    <a  id="pageFavourite"  href="/confluence/labels/addfavourite.action?entityId=18186729&atl_token=3UIncFJ_LX"><img src="/confluence/images/icons/star_grey.gif" height="16" width="16" border="0" align="absmiddle" title="Add this page to your favourites list" alt="Add this page to your favourites list"></a>
    <a  id="pageWatch"  href="/confluence/pages/addpagenotification.action?pageId=18186729&atl_token=3UIncFJ_LX"><img src="/confluence/images/icons/watch_16.gif" height="16" width="16" border="0" align="absmiddle" title="Watch this page" alt="Watch this page"></a>
</td>
                                </table>
                                <h1>
                                                                                                                                                                                                                        <a href="/confluence/display/java/ENV30-J.+Create+a+secure+sandbox+using+a+Security+Manager">ENV30-J. Create a secure sandbox using a Security Manager</a>
                                                                                                        </h1>
                            </div>
                                                        <div id="content">
                                <!-- call the page decorator -->
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

<!--
    Root decorator: this is a layer of abstraction that Confluence doesn't need. It will be removed eventually.
-->




    
    <!--[if gte IE 5.5000]>
<script language="JavaScript">
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
   {
   for(var i=0; i<document.images.length; i++)
      {
	  var img = document.images[i]
	  var imgName = img.src.toUpperCase()
	  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	     {
		 var imgID = (img.id) ? "id='" + img.id + "' " : ""
		 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
		 var imgStyle = "display:inline-block;" + img.style.cssText
		 if (img.align == "left") imgStyle = "float:left;" + imgStyle
		 if (img.align == "right") imgStyle = "float:right;" + imgStyle
		 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
		 var strNewHTML = "<span " + imgID + imgClass + imgTitle
		 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	     + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
		 img.outerHTML = strNewHTML
		 i = i-1
	     }
      }
   }
window.attachEvent("onload", correctPNG);
</script>
<![endif]-->


































    <div id="editpage">
    <fieldset class="hidden parameters">
    <input type="hidden" id="spaceKey" value="java">
    <input type="hidden" id="pageId" value="18186729">
    <input type="hidden" id="originalParentPage" value="00. Runtime Environment (ENV)">
    <input type="hidden" id="formName" value="editpageform">
    <input type="hidden" id="defaultContentTitle" value="">
    <input type="hidden" id="draftSavedMessage" value="Draft saved at {0}">
    <input type="hidden" id="draftSavingMessage" value="Saving draft&hellip;">
    <input type="hidden" id="draftSavingTimedOutMessage" value="Draft saving timed out">
</fieldset>


<form id="editpageform" name="editpageform" method="post" action="doeditpage.action?pageId=18186729" class="editor">
        <input type="hidden" name="atl_token" value="3UIncFJ_LX">
    <input
    type="hidden"
          name="labelsShowing"            value="false"                     id="labelsShowing"           />    <input
    type="hidden"
          name="restrictionsShowing"            value="false"                     id="restrictionsShowing"           />    <input
    type="hidden"
          name="locationShowing"            value="false"                     id="locationShowing"           />
                <input
    type="hidden"
          name="originalVersion"            value="38"                     id="originalVersion"           />        <input
    type="hidden"
          name="originalContent"            value="According to the Class {{SecurityManager}} documentation \[[API 06|AA. Java References#API 06]\]:

{quote}
The security manager is a class that allows applications to implement a security policy. It allows an application to determine, before performing a possibly unsafe or sensitive operation, what the operation is and whether it is being attempted in a security context that allows the operation to be performed. The application can allow or disallow the operation.
{quote}

As an example, the security manager denies applets all but the most essential privileges. It is designed to protect inadvertent system modification, information leakage and user impersonation. For Java applications that run from the command line, a default or custom security manager can be set using a special flag described a little later. Alternatively, it is possible to install a security manager programatically.

From Java 2 SE Platform onwards, {{SecurityManager}} is a non-abstract class. As a result, there is no explicit requirement of overriding its methods. To create and use a security manager programatically, the code must have the runtime permissions {{createSecurityManager}} (to instantiate {{SecurityManager}}) and {{setSecurityManager}} to install it.  

The security manager is closely related to the {{AccessController}}. The former is used as a hub for access control whereas the latter is the implementer of a particular access control algorithm. Two requirements necessitate the use of the security manager:

* Providing backward compatibility: Legacy code often contains custom implementations of the security manager class because it was originally {{abstract}}. 

* Defining custom policies: It is sometimes desired to subclass the security manager to define multilevel, coarse or fine grained security policies with system wide application.    

The Java Security Architecture Specification \[[SecuritySpec 08|AA. Java References#SecuritySpec 08]\] aptly paints the picture:

{quote}
We encourage the use of {{AccessController}} in application code, while customization of a security manager (via subclassing) should be the last resort and should be done with extreme care. Moreover, a customized security manager, such as one that always checks the time of the day before invoking standard security checks, could and should utilize the algorithm provided by {{AccessController}} whenever appropriate.
{quote}

h2. Noncompliant Code Example

The worst form of non-compliance is not using the the security manager at all. Even when used, there can be cases where the appropriate checks are not installed. In the noncompliant code example that follows, a {{null}} value is passed to the {{setSecurityManager}} method that is responsible for establishing a current instance of {{SecurityManager}}. As a result, no security manager will be installed (assuming that the security manager is not installed from the command line either).

{code:bgColor=#FFcccc}
try {
  System.setSecurityManager(null);
} catch (SecurityException se) { System.out.println("SecurityManager is already set!"); }
{code}

h2. Noncompliant Code Example

In this noncompliant code example, none of the {{check*}} methods have been used even though a custom security manager has been set programatically.

{code:bgColor=#FFcccc}
try {
  System.setSecurityManager(new CustomSecurityManager("password here"));
} catch (SecurityException se) { System.out.println("SecurityManager is already set!"); }
{code}


h2. Compliant Solution

This compliant solution demonstrates how a custom {{SecurityManager}} class called {{CustomSecurityManager}} can be activated by invoking its constructor with a password. Various {{check*}} methods defined within the class can then be invoked to perform access checks. In this case, {{checkRead()}} succeeds if the current protection domain's file permission name tallies with that of the file name argument for the {{read}} action.

{code:bgColor=#ccccff}
try {
  System.setSecurityManager(new CustomSecurityManager("password here"));
  SecurityManager sm = System.getSecurityManager();
  if(sm != null) {  //check if file can be read
    sm.checkRead("/temp/tempFile");
  } 
} catch (SecurityException se) { System.out.println("Not allowed"); }
{code}

h2. Compliant Solution

An alternative is to use the default security manager instead of a custom one, as shown below. To do this, change the active instance to {{java.lang.SecurityManager}} (invoke {{setSecurityManager()}} with the argument {{new SecurityManager()}}). 

{code:bgColor=#ccccff}
try {
  System.setSecurityManager(new SecurityManager());
  SecurityManager sm = System.getSecurityManager();
  if(sm != null) {  //check if file can be read
    sm.checkRead("/temp/tempFile");
  } 
} catch (SecurityException se) { System.out.println("Not allowed"); }
{code}


h2. Compliant Solution

The methods detailed in the preceding compliant solutions were more prevalent in JDK versions 1.x. Two methods, {{checkPermission(Permission perm)}} and {{checkPermission(Permission perm, Object context)}} were added in J2SE 1.2. The motivations for this change were manifold -

* The {{checkPermission}} methods eliminated the need for hardcoding names of the checks in the call.
* They used only one copy of the complicated algorithms and code for examining the Java runtime by using a common {{checkPermission}} method. 
* Newer permissions for resources could be easily added by encapsulating them in a new {{Permission}} class. 

The single argument {{checkPermission}} method uses the context of the currently executing environment to perform the checks. If the context has the permission as defined in the local policy file, the check succeeds, otherwise a {{SecurityException}} is thrown. 

This compliant solution exemplifies the single argument {{checkPermission}} method.

{code:bgColor=#ccccff}
try {
  System.setSecurityManager(new CustomSecurityManager("password here"));
  SecurityManager sm = System.getSecurityManager();
  if(sm != null) {  //check if file can be read
    FilePermission perm = new FilePermission("/temp/tempFile", "read");
    sm.checkPermission(perm);
  } 
} catch (SecurityException se) { System.out.println("Not allowed"); }
{code}

Sometimes the security check code exists in one context (such as a worker thread) while the check has to be conducted on a different context, such as another thread. The two argument {{checkPermission}} is used here, passing in the instance of an {{AccessControlContext}} as the {{context}} argument. Both the single and double argument {{checkPermission}} methods defer to the single argument {{java.security.AccessController.checkPermission(Permission perm)}} method. When invoked directly, this method operates only on the currently execution context and as a result does not supersede the security manager's two argument version. There is also, however, another (cleaner and preferable) way to handle the security check from a different context. 

This is accomplished by taking a _snapshot_ of the currently executing context using the {{java.security.AccessController.getContext()}} method that returns an {{AccessControlContext}} object. The {{AccessControlContext}} class itself defines a {{checkPermission}} method that encapsulates a context instead of taking in the currently executing context. This is shown below.

{code:bgColor=#ccccff}
// Take the snapshot of the required context
AccessControlContext acc = AccessController.getContext(); 
// ...
acc.checkPermission(perm); // Check permissions in another context
{code}

h2. Compliant Solution

Any Java program (bean, servlet or application) can instantiate a {{SecurityManager}}. However, for applications designed to run locally, an explicit flag must be set to enforce the {{SecurityManager}} policy whenever the security manager is not set programatically. Sometimes this is desired when the user operates using a custom security policy and does not want to rely on the vendor supplied security policy. The default security manager at the user end can be installed using the flags as follows: 

{code:bgColor=#ccccff}
java -Djava.security.manager -Djava.security.policy=policyURL LocalJavaApp
{code}

If it is known in advance that the user prefers using a custom security policy, the {{setSecurityManager()}} method in code can be forgone and substituted with just the {{getSecurityManager()}} method as the security manager is installed using the command line flag and need not be set explicitly. A custom security manager can be installed by adding the absolute path to the custom security manager, after an equal-to sign appended immediately after the flag.

The default policy file {{java.policy}} grants a few permissions (reading system properties, binding to unprivileged ports and so forth) and can be found in the {{~/java.home/lib/security}} directory on UNIX-like systems and its equivalent on Microsoft Windows systems. There is also a user specific policy file in the user's home directory. The union of both these policy files defines the permissions given to a program. Refer to the {{java.security}} file to set which policy files should be used. If either of these is deleted, by default no permissions are granted to the implementing code.

If the default policy file needs to be bypassed in lieu of a custom policy file, a double equals ({{==}}) idiom should be used.

{code:bgColor=#ccccff}
java -Djava.security.manager -Djava.security.policy==policyURL LocalJavaApp
{code}

The {{appletviewer}} automatically installs a security manager with the standard policy file. To specify additional policy files, use the {{-J}} flag.


{code:bgColor=#ccccff}
appletviewer -J-Djava.security.manager -Djava.security.policy==policyURL LocalJavaApp
{code}

Notably, the policy file specified in the argument is ignored when the {{policy.allowSystemProperty}} property in the security properties file ({{java.security}}) is set to {{false}}. Its default value is {{true}}. The document "Default Policy Implementation and Policy File Syntax" \[[Policy 02|AA. Java References#Policy 02]\] discusses writing policy files in depth.  



h2. Risk Assessment

Running Java code without a Security Manager being set means that there is no restrictive sandbox and arbitrary code may get executed.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| ENV30-CPP | high | probable | low | {color:red}{*}P18{*}{color} | {color:red}{*}L1{*}{color} |



h3. Automated Detection

TODO



h3. Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+ENV30-J].

h2. References

\[[API 06|AA. Java References#API 06]\] [Class SecurityManager|http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html], Class AccessControlContext, Class AccessController
\[[Policy 02|AA. Java References#Policy 02]\]
\[[Pistoia 04|AA. Java References#Pistoia 04]\] Section 7.4, The Security Manager
\[[Gong 03|AA. Java References#Gong 03]\] Section 6.1, Security Manager
\[[SecuritySpec 08|AA. Java References#SecuritySpec 08]\] 6.2 SecurityManager versus AccessController
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 358|http://cwe.mitre.org/data/definitions/358.html] "Improperly Implemented Security Check for Standard"

----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|SEC05-J. Minimize accessibility of classes and their members]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|01. Platform Security (SEC)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|ENV31-J. Never grant AllPermission to untrusted code]

"                     id="orginalContent"           />        <input
    type="hidden"
          name="conflictingVersion"            value="38"                     id="conflictingVersion"           />    

    <div id="wiki-editor">
        <!-- remove content link -->
                <div class="remove-control">
                                                        <a href="/confluence/pages/removepage.action?pageId=18186729"><img src="/confluence/images/icons/trash_16.gif" width="16" height="16" border="0px" align="absmiddle" title="Remove"></a>&nbsp;<a href="/confluence/pages/removepage.action?pageId=18186729">Remove Page</a>
                                        </div>

        <!-- title text field -->
        <div id="content-title-div" class="inputSection">
                                                  <input type="text" name="title" size="43" value="ENV30-J. Create a secure sandbox using a Security Manager" tabindex="1" id="content-title" class="pagetitle">
        </div>
        
                <!-- captcha form elements -->
        
<div id='heartbeat-div' class="hidden">
    <table cellpadding='5' cellspacing='8px' class='noteMacro' border="0" align='center'>
        <tr><td valign='top' width="1%"><img src="/confluence/s/1627/6/_/images/icons/emoticons/warning.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>
            This page is being edited by <span id='other-users-span'></span>.
        </td></tr>
    </table>
</div>



        <!-- template link -->
        
        <!-- content editor -->
        <div class="inputSection">
            <div class="submit-buttons">
                   <input tabindex="102"  accessKey="s"  type="submit"  name="confirm" value="Save">&nbsp;&nbsp;
<input tabindex="104"  type="submit"  name="cancel" value="Cancel">            </div>
            <div id="draft-status">
            </div>
                                    <div id="editorDiv">
                

    
    
    
    
    
                    
    



        

<fieldset class="hidden parameters">
    <input type="hidden" id="contextPath" value="/confluence">
    <input type="hidden" id="contentId" value="18186729">
    <input type="hidden" id="contentType" value="page">
    <input type="hidden" id="useWysiwyg" value="false">
    <input type="hidden" id="saveDrafts" value="true">
    <input type="hidden" id="draftType" value="page">
    <input type="hidden" id="heartbeat" value="true">
    <input type="hidden" id="newPage" value="">
    <input type="hidden" id="maxThumbWidth" value="200">
    <input type="hidden" id="editorMode" value="markup">
    <input type="hidden" id="paramsHeight" value="480">
    <input type="hidden" id="isDevMode" value="false">
    <input type="hidden" id="parametersName" value="content">
    <input type="hidden" id="parametersId" value="content">
    <input type="hidden" id="actionLocale" value="en_GB">
    <input type="hidden" id="actionMarkup" value="markup">
    <input type="hidden" id="actionRichtext" value="richtext">
    <input type="hidden" id="actionPreview" value="preview">
    <input type="hidden" id="spaceKey" value="java">
    <input type="hidden" id="remoteUser" value="agoyal">
    <input type="hidden" id="editorPluginResourcePrefix" value="/confluence/s/1627/6/3.0.0_01/_">
        <input type="hidden" id="staticResourceUrlPrefix" value="/confluence/s/1627/6/_">
    <input type="hidden" id="blankSearchText" value="Search">
    <input type="hidden" id="loadBrowserErrorMessage" value="There has been an error loading the macro browser. Please try again or see your system administrator.">
    <input type="hidden" id="unknownMacroMessage" value="Could not load unknown macro in the macro browser.">
    <input type="hidden" id="nestingSameMacroNotAllowedMessage" value="Macros with the same name cannot be nested inside each other.">
    <input type="hidden" id="loadingMessage" value="The Macro Browser has not yet been initialised. Please try again in a few seconds.">
    <input type="hidden" id="categoryAllLabel" value="All">
    <input type="hidden" id="nextButtonLabel" value="Next">
    <input type="hidden" id="backButtonLabel" value="Back">
    <input type="hidden" id="previewButtonLabel" value="Preview">
    <input type="hidden" id="cancelButtonLabel" value="Cancel">
    <input type="hidden" id="insertButtonLabel" value="Insert">
    <input type="hidden" id="saveButtonLabel" value="Save">
                <input type="hidden" id="formName" value="editpageform">
    </fieldset>

    
    <ul id="editor-tabs" class="tab-navigation">
        
        <li id="markupTab" class="tab  current">
            <a href="#">Wiki Markup</a>
        </li>

        <li id="previewTab" class="tab ">
            <a href="#">Preview</a>
        </li>

        <li id="wysiwygWaitImage" class="notab loading">Loading...</li>

            </ul>

        <div id="linkinserters" >
                    <a id="editor-insert-link" href="#" title="Insert Link (Ctrl+K)">
            <span class="editor-icon"></span>
        </a>
            <a id="editor-insert-image" href="#" title="Insert Image (Ctrl+M)">
            <span class="editor-icon"></span>
        </a>
            <a id="editor-insert-macro" href="#" title="Macro Browser">
            <span class="editor-icon"></span>
        </a>
        </div>
    
    
    <div id="markup" >
        <textarea id="markupTextarea" name="content"
                      cols="80"
                      rows="30"

                                             tabindex="5"                style=""
            class="monospaceInput"
            >According to the Class {{SecurityManager}} documentation \[[API 06|AA. Java References#API 06]\]:

{quote}
The security manager is a class that allows applications to implement a security policy. It allows an application to determine, before performing a possibly unsafe or sensitive operation, what the operation is and whether it is being attempted in a security context that allows the operation to be performed. The application can allow or disallow the operation.
{quote}

As an example, the security manager denies applets all but the most essential privileges. It is designed to protect inadvertent system modification, information leakage and user impersonation. For Java applications that run from the command line, a default or custom security manager can be set using a special flag described a little later. Alternatively, it is possible to install a security manager programatically.

From Java 2 SE Platform onwards, {{SecurityManager}} is a non-abstract class. As a result, there is no explicit requirement of overriding its methods. To create and use a security manager programatically, the code must have the runtime permissions {{createSecurityManager}} (to instantiate {{SecurityManager}}) and {{setSecurityManager}} to install it.  

The security manager is closely related to the {{AccessController}}. The former is used as a hub for access control whereas the latter is the implementer of a particular access control algorithm. Two requirements necessitate the use of the security manager:

* Providing backward compatibility: Legacy code often contains custom implementations of the security manager class because it was originally {{abstract}}. 

* Defining custom policies: It is sometimes desired to subclass the security manager to define multilevel, coarse or fine grained security policies with system wide application.    

The Java Security Architecture Specification \[[SecuritySpec 08|AA. Java References#SecuritySpec 08]\] aptly paints the picture:

{quote}
We encourage the use of {{AccessController}} in application code, while customization of a security manager (via subclassing) should be the last resort and should be done with extreme care. Moreover, a customized security manager, such as one that always checks the time of the day before invoking standard security checks, could and should utilize the algorithm provided by {{AccessController}} whenever appropriate.
{quote}

h2. Noncompliant Code Example

The worst form of non-compliance is not using the the security manager at all. Even when used, there can be cases where the appropriate checks are not installed. In the noncompliant code example that follows, a {{null}} value is passed to the {{setSecurityManager}} method that is responsible for establishing a current instance of {{SecurityManager}}. As a result, no security manager will be installed (assuming that the security manager is not installed from the command line either).

{code:bgColor=#FFcccc}
try {
  System.setSecurityManager(null);
} catch (SecurityException se) { System.out.println("SecurityManager is already set!"); }
{code}

h2. Noncompliant Code Example

In this noncompliant code example, none of the {{check*}} methods have been used even though a custom security manager has been set programatically.

{code:bgColor=#FFcccc}
try {
  System.setSecurityManager(new CustomSecurityManager("password here"));
} catch (SecurityException se) { System.out.println("SecurityManager is already set!"); }
{code}


h2. Compliant Solution

This compliant solution demonstrates how a custom {{SecurityManager}} class called {{CustomSecurityManager}} can be activated by invoking its constructor with a password. Various {{check*}} methods defined within the class can then be invoked to perform access checks. In this case, {{checkRead()}} succeeds if the current protection domain's file permission name tallies with that of the file name argument for the {{read}} action.

{code:bgColor=#ccccff}
try {
  System.setSecurityManager(new CustomSecurityManager("password here"));
  SecurityManager sm = System.getSecurityManager();
  if(sm != null) {  //check if file can be read
    sm.checkRead("/temp/tempFile");
  } 
} catch (SecurityException se) { System.out.println("Not allowed"); }
{code}

h2. Compliant Solution

An alternative is to use the default security manager instead of a custom one, as shown below. To do this, change the active instance to {{java.lang.SecurityManager}} (invoke {{setSecurityManager()}} with the argument {{new SecurityManager()}}). 

{code:bgColor=#ccccff}
try {
  System.setSecurityManager(new SecurityManager());
  SecurityManager sm = System.getSecurityManager();
  if(sm != null) {  //check if file can be read
    sm.checkRead("/temp/tempFile");
  } 
} catch (SecurityException se) { System.out.println("Not allowed"); }
{code}


h2. Compliant Solution

The methods detailed in the preceding compliant solutions were more prevalent in JDK versions 1.x. Two methods, {{checkPermission(Permission perm)}} and {{checkPermission(Permission perm, Object context)}} were added in J2SE 1.2. The motivations for this change were manifold -

* The {{checkPermission}} methods eliminated the need for hardcoding names of the checks in the call.
* They used only one copy of the complicated algorithms and code for examining the Java runtime by using a common {{checkPermission}} method. 
* Newer permissions for resources could be easily added by encapsulating them in a new {{Permission}} class. 

The single argument {{checkPermission}} method uses the context of the currently executing environment to perform the checks. If the context has the permission as defined in the local policy file, the check succeeds, otherwise a {{SecurityException}} is thrown. 

This compliant solution exemplifies the single argument {{checkPermission}} method.

{code:bgColor=#ccccff}
try {
  System.setSecurityManager(new CustomSecurityManager("password here"));
  SecurityManager sm = System.getSecurityManager();
  if(sm != null) {  //check if file can be read
    FilePermission perm = new FilePermission("/temp/tempFile", "read");
    sm.checkPermission(perm);
  } 
} catch (SecurityException se) { System.out.println("Not allowed"); }
{code}

Sometimes the security check code exists in one context (such as a worker thread) while the check has to be conducted on a different context, such as another thread. The two argument {{checkPermission}} is used here, passing in the instance of an {{AccessControlContext}} as the {{context}} argument. Both the single and double argument {{checkPermission}} methods defer to the single argument {{java.security.AccessController.checkPermission(Permission perm)}} method. When invoked directly, this method operates only on the currently execution context and as a result does not supersede the security manager's two argument version. There is also, however, another (cleaner and preferable) way to handle the security check from a different context. 

This is accomplished by taking a _snapshot_ of the currently executing context using the {{java.security.AccessController.getContext()}} method that returns an {{AccessControlContext}} object. The {{AccessControlContext}} class itself defines a {{checkPermission}} method that encapsulates a context instead of taking in the currently executing context. This is shown below.

{code:bgColor=#ccccff}
// Take the snapshot of the required context
AccessControlContext acc = AccessController.getContext(); 
// ...
acc.checkPermission(perm); // Check permissions in another context
{code}

h2. Compliant Solution

Any Java program (bean, servlet or application) can instantiate a {{SecurityManager}}. However, for applications designed to run locally, an explicit flag must be set to enforce the {{SecurityManager}} policy whenever the security manager is not set programatically. Sometimes this is desired when the user operates using a custom security policy and does not want to rely on the vendor supplied security policy. The default security manager at the user end can be installed using the flags as follows: 

{code:bgColor=#ccccff}
java -Djava.security.manager -Djava.security.policy=policyURL LocalJavaApp
{code}

If it is known in advance that the user prefers using a custom security policy, the {{setSecurityManager()}} method in code can be forgone and substituted with just the {{getSecurityManager()}} method as the security manager is installed using the command line flag and need not be set explicitly. A custom security manager can be installed by adding the absolute path to the custom security manager, after an equal-to sign appended immediately after the flag.

The default policy file {{java.policy}} grants a few permissions (reading system properties, binding to unprivileged ports and so forth) and can be found in the {{~/java.home/lib/security}} directory on UNIX-like systems and its equivalent on Microsoft Windows systems. There is also a user specific policy file in the user's home directory. The union of both these policy files defines the permissions given to a program. Refer to the {{java.security}} file to set which policy files should be used. If either of these is deleted, by default no permissions are granted to the implementing code.

If the default policy file needs to be bypassed in lieu of a custom policy file, a double equals ({{==}}) idiom should be used.

{code:bgColor=#ccccff}
java -Djava.security.manager -Djava.security.policy==policyURL LocalJavaApp
{code}

The {{appletviewer}} automatically installs a security manager with the standard policy file. To specify additional policy files, use the {{-J}} flag.


{code:bgColor=#ccccff}
appletviewer -J-Djava.security.manager -Djava.security.policy==policyURL LocalJavaApp
{code}

Notably, the policy file specified in the argument is ignored when the {{policy.allowSystemProperty}} property in the security properties file ({{java.security}}) is set to {{false}}. Its default value is {{true}}. The document "Default Policy Implementation and Policy File Syntax" \[[Policy 02|AA. Java References#Policy 02]\] discusses writing policy files in depth.  



h2. Risk Assessment

Running Java code without a Security Manager being set means that there is no restrictive sandbox and arbitrary code may get executed.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| ENV30-CPP | high | probable | low | {color:red}{*}P18{*}{color} | {color:red}{*}L1{*}{color} |



h3. Automated Detection

TODO



h3. Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+ENV30-J].

h2. References

\[[API 06|AA. Java References#API 06]\] [Class SecurityManager|http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html], Class AccessControlContext, Class AccessController
\[[Policy 02|AA. Java References#Policy 02]\]
\[[Pistoia 04|AA. Java References#Pistoia 04]\] Section 7.4, The Security Manager
\[[Gong 03|AA. Java References#Gong 03]\] Section 6.1, Security Manager
\[[SecuritySpec 08|AA. Java References#SecuritySpec 08]\] 6.2 SecurityManager versus AccessController
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 358|http://cwe.mitre.org/data/definitions/358.html] "Improperly Implemented Security Check for Standard"

----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|SEC05-J. Minimize accessibility of classes and their members]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|01. Platform Security (SEC)]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|ENV31-J. Never grant AllPermission to untrusted code]

</textarea>
    </div>
    <input id="selectedText" name="selectedText" type="hidden">
        <input type="hidden" name="sel1">    <input type="hidden" name="sel2">    <input type="hidden" name="inPreview" value="false"/>
    <input type="hidden" name="mode" value="markup"/>
    <input type="hidden" name="xhtml" value="false"/>

    <div id="preview" class="hidden">
                        <div id="previewArea"></div>
    </div>
    <div id="macro-browser-templates" class="hidden">
        <ol id="macro-summaries-template" class="macro-list"></ol>
    <ul>
    <li id="macro-summary-template" class="macro-list-item">
        <h3 class="macro-title"></h3>
        <div class="macro-desc"></div>
    </li>
    </ul>
        <div id="macro-insert-template">
        <input class="macro-name" type="hidden"/>
        <div class="macro-preview-container dialog-panel">
            <div class="macro-preview-header">
                <a href="#">Refresh</a>
                <span>Preview</span>
            </div>
            <div class="macro-preview"></div>
        </div>
        <div class="macro-input-fields dialog-panel"></div>
    </div>
    <span id="macro-doco-link-template">
        <a href="#" class="macro-doco-link">Documentation</a>
    </span>
    <div id="macro-freeform-template" class="macro-freeform-div">
        <div class="macro-freeform-desc">This macro does not provide any parameter information. If the available information does not help, you may find its documentation at <a href=http://confluence.atlassian.com/display/CONFEXT>Confluence Extensions</a>.</div>
        <div class="macro-freeform-input">
            {<span class="macro-name-display"></span><input type="text" class="macro-text"/>}
        </div>
        <div class="macro-example hidden">
            <h3 class="underlined">Examples</h3>
        </div>
        <div class="macro-help hidden">
            <h3 class="underlined">Description</h3>
        </div>
    </div>
    <div id="macro-param-template" class="macro-param-div">
        <label></label>
        <input type="text" class="text"/>
    </div>
    <div id="macro-param-checkbox-template" class="macro-param-div boolean-param">
        <label></label>
        <input type="checkbox" value="true"/>
    </div>
    <div id="macro-param-select-template" class="macro-param-div">
        <label></label>
        <select></select>
    </div>
    <div id="macro-param-hidden-text-template" class="macro-param-div">
        <label></label>
        <input type="text" class="text"/>
        <input type="hidden"/>
    </div>
    <div id="macro-param-hidden-template" class="macro-param-div">
        <input type="hidden"/>
    </div>
    <div id="macro-param-desc-template" class="macro-param-desc"></div>
    <div id="macro-body-template" class="macro-body-div">
        <label>Body Text</label>
        <textarea class="monospaceInput textarea" type="text" rows="10"></textarea>
    </div>
</div>            </div>
        </div>

        <!-- comment field and minor edit checkbox -->
        <div class="inputSection">
                            <div class="minor-edit">
                    <input id="minorEdit" type="checkbox" name="minorEdit" value="true"  />
                    <label for="minorEdit">
                        <span class="smalltext"><b>Minor change?</b> (no notifications will be sent)</span>
                    </label>
                </div>
                                                                      <span class="formtitle">Comment:</span>
                <input type="text"
                                   name="versionComment"
             size="40"                     tabindex="6"             class="monospaceInput"                style="width: 50%"       />                    </div>

        <!-- content location editor -->
                    <div class="inputSection">
               	

    
    
    


<fieldset class="hidden parameters">
    <input type="hidden" title="editLabel" value="Edit">
    <input type="hidden" title="doneLabel" value="Done">
    <input type="hidden" title="showLocation" value="false">
    <input type="hidden" title="hasChildren" value="false">
    <input type="hidden" title="availableSpacesSize" value="4">
    <input type="hidden" title="spaceKey" value="java">
    <input type="hidden" title="pageId" value="18186729">
    <input type="hidden" title="actionMode" value="edit">
    <input type="hidden" title="parentPageId" value="33128636">
        <input type="hidden" title="expandedNodes" class="list" value="4179">
        <input type="hidden" title="expandedNodes" class="list" value="33128636">
    </fieldset>

<span class="formtitle">Location:</span>
<span id="location_info">
    <span id="space_info" >
        <span id="space_content">java</span>
    </span>
    <span id="parent_info" >
        > <span id="parent_content">00. Runtime Environment (ENV)</span>
    </span>
    <a href="" class="inline-control-link" id="location_edit_link">Edit</a>
</span>

<a name="locationSection"/>
<div id="location_div" class="toggleFormDiv editor-panel hidden">
                  
          <div class="smalltext" style="float:right">You can move the highlighted page by dragging it to a new position in the tree.</div>
      <div>
          <label id="currentLocation" class="formtitle">Space</label>

                <select id="newSpaceKey" name="newSpaceKey" tabindex="3">
                        <option value="cplusplus" >C++ Secure Coding Practices</option>
                        <option value="java"  selected>java</option>
                        <option value="seccode" >Secure Coding</option>
                        <option value="SD" >Secure Design</option>
                    </select>
            </div>
   
    <div id="resultsDiv"></div>
    <div style="padding: 10px" id="outer-container"><div id="tree-div" style="min-height:150px"></div></div>
    <input id="parentPageString" type="hidden" value="00. Runtime Environment (ENV)" name="parentPageString"/>
	<input id="hierarchy_checkbox" type="hidden" name="moveHierarchy" value="true" />
    <input id="position" type="hidden" value="" name="position"/>
    <input id="targetId" type="hidden" value="" name="targetId"/>
</div>
            </div>
        
        <!-- content permissions -->
                    <div class="inputSection">
                

    
    

<!-- Copy some methods out of prototype 1.5 since we can't rev to it yet due to it causing a memory leak in jwebunit 1.2 and hence our func tests -->
<!-- this block of javascript can be removed when we rev to prototype 1.5 -->
<script type="text/javascript">
    Array.prototype.indexOf = function(object)
    {
        for (var i = 0, length = this.length; i < length; i++)
            if (this[i] == object) return i;
        return -1;
    }

    Array.prototype.without = function()
    {
        var values = $A(arguments);
        return this.select(function(value)
        {
            return !values.include(value);
        });
    }

    String.prototype.strip = function()
    {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    }
</script>

<script type="text/javascript">



var viewPagePermissions = new PagePermissions();

var editPagePermissions = new PagePermissions();

var viewPermissionManager = new PermissionManager(PagePermissionType.VIEW);
var editPermissionManager = new PermissionManager(PagePermissionType.EDIT);
var currentPermissionManager = viewPermissionManager;



i18n['perms.remove'] = 'Remove';
i18n['done.name.caps'] = 'Done';
i18n['edit.name.caps'] = 'Edit';
i18n['page.perms.viewing.restricted'] = 'Viewing restricted to:';
i18n['page.perms.editing.restricted'] = 'Editing restricted to:';
i18n['page.perms.no.view.restrictions'] = 'No viewing restrictions set on this page';
i18n['page.perms.no.edit.restrictions'] = 'No editing restrictions set on this page';
i18n['page.perms.duplicate.names'] = 'Duplicate user or group name(s):';
i18n['page.perms.invalid.entity.names'] = 'Invalid user or group name(s):';

</script>

              </div>
        
        <!-- labels section -->
        <div class="inputSection">
            
    
    
    
    

<fieldset class="hidden parameters">
    <input type="hidden" id="editLabel" value="Edit">
    <input type="hidden" id="doneLabel" value="Done">
    <input type="hidden" id="pageId" value="18186729">
</fieldset>

<div id="labels_tab">
    <span class="formtitle">Labels: </span>
    <a href="" class="inline-control-link" id="labels_edit_link">Edit</a>
</div>
<div id="labels_info">
   incomplete
</div>

<div id="labels_div" class="toggleFormDiv editor-panel hidden" style="padding: 8px;">
    <table width="100%">
        <tr>
            <td width="60%" valign="top">
                <span class="error">
                    <span class="errorMessage" id="errorSpan"></span>
                </span>
                                              <input autocomplete="off" type="text" id="labelsString" name="labelsString" value="incomplete" class="monospaceInput" style="width:100%;" />
                <div class="smalltext">Looking for a label? Just start typing.</div>
                <div class="auto_complete" id="labelsAutocompleteList"></div>
            </td>
            <td valign="top">
                <div id="suggestedLabelsSpan" style="margin-top:5px;">
                </div>
            </td>
        </tr>
    </table>
</div>
        </div>

        
        <div class="submit-buttons bottom">
               <input tabindex="102"  accessKey="s"  type="submit"  name="confirm" value="Save">&nbsp;&nbsp;
<input tabindex="104"  type="submit"  name="cancel" value="Cancel">        </div>
    </div>
</form>
    </div>
                            </div>
                        </td>
                                
    
            
    
                                                    <td valign="top" id="helptd" style="display:block; width:200px; border-top:1px solid #CCC;">
                            <div style="padding-left:5px;">
                                <div id="info-panel" class="rightpanel">
        <h3 id="helpheading">Help Tips</h3>
      <div id="helpcontent">
                        <dl>
    <dt class="first">Text formatting</dt>
    <dd class="text-formatting"><code>*bold*</code> <strong>bold</strong></dd>
    <dd class="text-formatting"><code>_italic_</code> <em>italic</em></dd>
    <dd class="text-formatting"><code>-strike-</code> <del>strike</del></dd>
    <dd class="text-formatting"><code>+under+</code> <u>under</u></dd>

    <dt>Headings
    <dd><code>h1.</code> Large heading</dd>
    <dd><code>h3.</code> Medium heading</dd>
    <dd><code>h5.</code> Small heading</dd>

    <dt>Lists</dt>
    <dd><code>*</code> Bulleted point</dd>
    <dd><code>#</code> Numbered point</dd>

    <dt>Tables</dt>
    <dd><pre>||head1 ||head2||
| colA1 | colA2 |
| colB1 | colB2 |</pre></dd>

    <dt>Links</dt>
    <dd><code>[title#anchor]</code> Link a page</dd>
    <dd><code>[dev:title]</code> In 'dev' space</dd>
    <dd><code>[http://host.com]</code> Remote link</dd>
    <dd><code>[phrase@shortcut]</code> Shortcut</dd>
    <dd><code>[alias|link]</code> Custom link title
</dl>
<a href="/confluence/renderer/notationhelp.action" onClick="window.open('/confluence/renderer/notationhelp.action','notation_help','width=780, height=580, resizable, scrollbars'); return false;">Full notation guide</a>
                </div>
  </div>
                            </div>
                        </td>
                                            </tr>
                </table>
                <!-- End inner content table -->
            </td>
        </tr>
    </table>
</div>
                                                        <!--     <ul id="poweredby">
        <li>Powered by <a href="http://www.atlassian.com/software/confluence" class="smalltext">Atlassian Confluence</a> 3.0.0_01, the <a href="http://www.atlassian.com/software/confluence" class="smalltext">Enterprise Wiki</a>.</li>
        <li><a href="http://jira.atlassian.com/secure/BrowseProject.jspa?id=10470" class="smalltext">Bug/feature request</a> &#8211;</li>
        <li><a href="http://www.atlassian.com/about/connected.jsp?s_kwcid=Confluence-stayintouch" class="smalltext">Atlassian news</a> &#8211;</li>
        <li><a href="/confluence/administrators.action">Contact administrators</a></li>
    </ul>
 -->

<!-- delay the loading of large javascript files to the end so that they don't interfere with the loading of page content -->
<span style="display: none"></span>

<!--BEGIN FOOTER -->


<table border="0" width="100%" cellspacing="0" cellpadding="8" bgcolor="#666666"><tr>
<td width="50%"><img src="https://www.cert.org/cert/images/sei_cmu_logo2.gif" alt="Software Engineering Institute | Carnegie Mellon University" border="0" usemap="#footermap"/>
        <map name="footermap" id="footermap">
                <area shape="rect" coords="2,2,233,19" href="http://www.sei.cmu.edu/"  alt="Software Engineering Institute"/>
                <area shape="rect" coords="241,3,341,19" href="http://www.cmu.edu/" alt="Carnegie Mellon University" />
        </map>
</td>
<td width="50%" align="right">
        <span style="font-size:11px; color:#ffffff; font-family:Verdana">
        <a style="color:#ffffff" href="https://www.cert.org/">Home</a> | 
        <a style="color:#ffffff" href="https://www.cert.org/meet_cert/meetcertcc.html">About</a> | 
        <a  style="color:#ffffff" href="https://www.cert.org/contact_cert/">Contact</a> | 
        <a style="color:#ffffff" href="https://www.cert.org/faq/cert_faq.html">FAQ</a> | 
        <a style="color:#ffffff" href="https://www.cert.org/stats/">Statistics</a> | 
        <a style="color:#ffffff" href="https://www.cert.org/jobs/">Jobs</a> | 
        <a style="color:#ffffff" href="https://www.cert.org/legal_stuff/">Legal</a> | 
        <a style="color:#ffffff" href="https://www.securecoding.cert.org/confluence/display/seccode/Terms+and+Conditions">Legal</a>
        <br/>
        Copyright © 1995-2009 Carnegie Mellon University 
</td>
</tr>
</table>


<!--END FOOTER -->
</body>
</html>
-J-Djava.security.policy==policyURL LocalJavaApp

Note that the policy file specified in the argument is ignored when the policy.allowSystemProperty property in the security properties file (java.security) is set to false; the default value of this property is true. Default Policy Implementation and Policy File Syntax [Policy 2010] discusses in depth the issues of and syntax for writing policy files.

Noncompliant Code Example (Programmatic Installation)

A SecurityManager can also be activated using the static System.setSecurityManager() method. Only one SecurityManager may be active at a time. This method replaces the currently active SecurityManager with the SecurityManager provided in its argument or no SecurityManager if its argument is null.

This noncompliant code example deactivates any current SecurityManager but does not install another SecurityManager in its place. Consequently, subsequent code will run with all permissions enabled; there will be no restrictions on any nefarious action the program might perform.

Code Block
bgColor#FFcccc
try {
  System.setSecurityManager(null);
} catch (SecurityException se) {
  // Cannot set security manager, log to file
}

An active SecurityManager that enforces a sensible security policy will prevent the system from deactivating it, causing this code to throw a SecurityException.

Compliant Solution (Default Security Manager)

This compliant solution instantiates and sets the default security manager:

Code Block
bgColor#ccccff
try {
  System.setSecurityManager(new SecurityManager());
} catch (SecurityException se) {
  // Cannot set security manager, log appropriately
}

Compliant Solution (Custom Security Manager)

This compliant solution demonstrates how to instantiate a custom SecurityManager class called CustomSecurityManager by invoking its constructor with a password; this custom security manager is then installed as the active security manager.

Code Block
bgColor#ccccff
char password[] = /* initialize */
try {
  System.setSecurityManager(
    new CustomSecurityManager("password here")
  );
} catch (SecurityException se) {
  // Cannot set security manager, log appropriately
}

After this code executes, APIs that perform security checks use the custom security manager. As noted earlier, custom security managers should be installed only when the default security manager lacks the required functionality.

Applicability

Java security fundamentally depends on the existence of a security manager. In its absence, sensitive actions can execute without restriction.

Programmatic detection of the presence or absence of a SecurityManager at runtime is straightforward. Static analysis can address the presence or absence of code that would attempt to install a SecurityManager if the code were executed. Checking whether the SecurityManager is installed early enough, whether it specifies the desired properties, or whether it is guaranteed to be installed may be possible in some special cases but is generally undecidable.

Bibliography

[API 2014]Class SecurityManager
Class AccessControlContext
Class AccessController
[Gong 2003]§6.1, "Security Manager"
[Pistoia 2004]§7.4, "The Security Manager"
[Policy 2010]Default Policy Implementation and Policy File Syntax
[SecuritySpec 2010]§6.2, "SecurityManager versus AccessController"

 

...

Image Added Image Added Image Added