Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

Failure to filter sensitive information when propagating exceptions often results in information leaks that can assist an attacker's efforts to develop further exploits. An attacker may craft input arguments to expose internal structures and mechanisms of the application. Both the exception message text and the type of an exception can leak information. For example, the FileNotFoundException message reveals information about the file system layout, and the exception type reveals the absence of the requested file.

This rule applies to server-side applications as well as to clients. Attackers can glean sensitive information not only from vulnerable web servers but also from victims who use vulnerable web browsers. In 2004, Schönefeld discovered an exploit for the Opera v7.54 web browser in which an attacker could use the sun.security.krb5.Credentials class in an applet as an oracle to "retrieve the name of the currently logged in user and parse his home directory from the information which is provided by the thrown java.security.AccessControlException" [Schönefeld 2004].

All exceptions reveal information that can assist an attacker's efforts to carry out a denial of service (DoS) against the system. Consequently, programs must filter both exception messages and exception types that can propagate across trust boundaries. The following table lists several problematic exceptions.

Exception Name

Description of Information Leak or Threat

java.io.FileNotFoundException

Underlying file system structure, user name enumeration

java.sql.SQLException

Database structure, user name enumeration

java.net.BindException

Enumeration of open ports when untrusted client can choose server port

java.util.ConcurrentModificationException

May provide information about thread-unsafe code

javax.naming.InsufficientResourcesException

Insufficient server resources (may aid DoS)

java.util.MissingResourceException

Resource enumeration

java.util.jar.JarException

Underlying file system structure

java.security.acl.NotOwnerException

Owner enumeration

java.lang.OutOfMemoryError

DoS

java.lang.StackOverflowError

DoS

Printing the stack trace can also result in unintentionally leaking information about the structure and state of the process to an attacker. When a Java program that is run within a console terminates because of an uncaught exception, the exception's message and stack trace are displayed on the console; the stack trace may itself contain sensitive information about the program's internal structure. Consequently, any program that may be run on a console accessible to an untrusted user must never abort due to an uncaught exception.

Noncompliant Code Example (Leaks from Exception Message and Type)

In this noncompliant code example, the program must read a file supplied by the user, but the contents and layout of the file system are sensitive. The program accepts a file name as an input argument but fails to prevent any resulting exceptions from being presented to the user.

Code Block
bgColor#FFcccc
class ExceptionExample {
  public static void main(String[] args) throws FileNotFoundException {
    // Linux stores a user's home directory path in 
    // the environment variable $HOME, Windows in %APPDATA%
    FileInputStream fis =
Wiki Markup
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>SEC00-A. Do not allow exceptions to transmit sensitive information - CERT Secure Coding Standards</title>
                
    <script language="javascript">
        var contextPath = '/confluence';
        var i18n = [];
    </script>

                            <link rel="stylesheet" href="/confluence/s/1116/1/1/_/styles/main-action.css?spaceKey=java" type="text/css" />
                    
            <script type="text/javascript" src="/confluence/s/1116/1/_/decorators/effects.js"></script>
    
            

    <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>

  new FileInputStream(System.getenv("APPDATA") + args[0]);  
  }
}

When a requested file is absent, the FileInputStream constructor throws a FileNotFoundException, allowing an attacker to reconstruct the underlying file system by repeatedly passing fictitious path names to the program.

Noncompliant Code Example (Wrapping and Rethrowing Sensitive Exception)

This noncompliant code example logs the exception and then wraps it in a more general exception before rethrowing it:

Code Block
bgColor#FFcccc
try {
  FileInputStream fis =
      new FileInputStream(System.getenv("APPDATA") +  <body onload="placeFocus()">args[0]);
} catch (FileNotFoundException e) {
  // Log <!--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">
        function hideMessage(messageId)
        {            var message = document.getElementById(messageId)            message.style.display = "none";            setCookie(messageId, true);        }
    </script>

        

<div id="PageContent">
    <table cellspacing="0" cellpadding="0" width="100%">
        <tr class="topBar">
            <td align="left">
                &nbsp;
                <span class="topBarDiv fontSizeSmaller">             
    <script language="JavaScript">
        function showBreadcrumbsEllipsis()
        {            document.getElementById('breadcrumbsEllipsis').style.display = 'none';            document.getElementById('breadcrumbsExpansion').style.display = 'inline';        }
    </script>
                                                    <a href="/confluence/dashboard.action">Dashboard</a>
                                     >                         <a href="/confluence/display/java">java</a>
                                                    <span id="breadcrumbs">
                    >
                    <span id="breadcrumbsEllipsis">
                        <a href="#" onclick="showBreadcrumbsEllipsis();return false;" title="
                    CERT Java Secure Coding Standard    ">...</a>
                    </span>
                    <span id="breadcrumbsExpansion" style="display:none;">
                                <a href="/confluence/display/java/CERT+Java+Secure+Coding+Standard">CERT Java Secure Coding Standard</a>
        </span>
                </span>
                                                             >                         <a href="/confluence/display/java/00.+Security+%28SEC%29">00. Security (SEC)</a>
                                     >                         <a href="/confluence/display/java/SEC00-A.+Do+not+allow+exceptions+to+transmit+sensitive+information">SEC00-A. Do not allow exceptions to transmit sensitive information</a>
                                     >                         Edit Page                
     </span>
            </td>

            <td align="right" valign="middle" style="white-space:nowrap">
                    <form id="quickSearch" method="POST" action="/confluence/dosearchsite.action" name="searchForm">
        <input type="hidden" name="quickSearch" value="true" />
        
        <input type="hidden" name="searchQuery.spaceKey" value="conf_global" />
        <input type="text" accessKey="s" name="searchQuery.queryString" size="25"/>
        <input type="submit" value="Search"/>
    </form>
            </td>
        </tr>
    </table>
    <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 src="/confluence/images/confluence_logo.gif" align="absmiddle" border="0"></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></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>CERT Employment</b> <br/>
<a href="http://www.cert.org/jobs/" rel="nofollow"><b>Opportunities</b></a></p>

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

<p><b>Related Sites</b><br/>
<a href="http://www.us-cert.gov/" rel="nofollow"><img src="https://www.cert.org/images/logo/uscert_4g_sm.jpg" align="absmiddle" border="0" /></a><br/>
<a href="http://www.cylab.cmu.edu/" title="http://www.cylab.cmu.edu/" rel="nofollow"><img src="https://www.cert.org/images/logo/cylab_alt.jpg" align="absmiddle" border="0" /></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/SEC00-A.+Do+not+allow+exceptions+to+transmit+sensitive+information"   onClick="javascript:saveDraftOnPageChange(this); return false;"   accessKey="v"><u>V</u>iew</a></li>
	   		   <li><a  id="editPageLink"  href="/confluence/pages/editpage.action?pageId=18186675"  class="current"   onClick="javascript:saveDraftOnPageChange(this); return false;"   accessKey="e"><u>E</u>dit</a></li>
	   		   <li><a  id="viewAttachmentsLink"  href="/confluence/pages/viewpageattachments.action?pageId=18186675"   onClick="javascript:saveDraftOnPageChange(this); return false;"   accessKey="a"><u>A</u>ttachments (0)</a></li>
	   		   <li><a  id="viewPageInfoLink"  href="/confluence/pages/viewinfo.action?pageId=18186675"   onClick="javascript:saveDraftOnPageChange(this); return false;"   accessKey="i"><u>I</u>nfo</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/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/pages/viewrecentblogposts.action?key=java" >News</a></li>
					<li><a href="/confluence/spaces/usage/report.action?key=java" >Activity</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="Find Content"> Add Content</a></h5>
<div id="addcontent" class="subnav" style="display:none;">
    <ul>
										
									<li><a href="/confluence/pages/createpage.action?spaceKey=java&fromPageId=18186675"><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>
						    			</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">
                            <div style="margin-right: 3px;">
                                                                                                                                    
    <span class="smalltext" id="userNavBar">
                    Welcome <a href="/confluence/display/~jpincar">Justin Pincar</a> |

                            <a href="/confluence/users/viewuserhistory.action" onClick="window.open(this.href,'user_history', 'width=620, height=475, resizable'); return false;" title="View History">History</a> |
            
            <a href="/confluence/users/viewuserprofile.action?username=jpincar">Preferences</a> |

            
            <a href="/confluence/logout.action" id="logout">Log Out</a>&nbsp;
            </span>
                                            <a href="/confluence/pages/editpage.action?pageId=18186675&decorator=printable" rel="nofollow"><img src="/confluence/images/icons/print_16.gif" width="16" height="16" hspace="1" vspace="1" align="absmiddle" border="0" alt="View a printable version of the current page." title="View a printable version of the current page."/></a>

                                                                        
            <a href="/confluence/pages/doexportpage.action?pageId=18186675&type=TYPE_PDF" rel="nofollow">
        <img src="/confluence/images/icons/attachments/pdf.gif" height="16" width="16" border="0" align="absmiddle" title="Export Page as PDF"></a>
                                                                        
                                                            </div>
                        </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=18186675"><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=18186675"><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>
                                <div class="pagetitle" style="padding: 0px; margin-bottom:5px; margin-top: 2px;">
                                                                            SEC00-A. Do not allow exceptions to transmit sensitive information
                                    </div>
                            </div>
                                                        <div id="content">
                                <!-- call the page decorator -->
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              <!--
    Root decorator: all decisions about how a page is to be decorated via the
                    inline decoration begins here.
-->



<!--
    Switch based upon the context. However, for now, just delegate to a decorator
    identified directly by the context.
-->


    
    <!--[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]-->























<style>
    .imageLink{        margin:2px;        vertical-align: bottom;        float:left;    }

        /*Overwritten styles in the main.css*/
        .greybox {            border: 0px;            border-top: 1px solid #ddd;            border-bottom: 1px solid #ddd;            background-color: #F0F0F0;	        padding: 3px;	        margin: 0;        }
</style>











    <div id="editpage">
    <!-- is the user logged in? -->
        
                
    
            <script type="text/javascript" src="/confluence/s/1116/1/_/editpage-javascript"></script>
    
<script type="text/javascript" language="JavaScript">
    var domainName = 'https://www.securecoding.cert.org/confluence';
    var entityId = '18186675';
    var spaceKey = 'java';

    function toggleHierarchy()
    {
        // prepare to toggle the hierarchy checkbox
        var selectbox = document.getElementById('newSpaceKey');
        var checkbox = document.getElementById('hierarchy_checkbox');
        var checkboxText = document.getElementById('hierarchy_text');
        if (selectbox != undefined && selectbox.type == "select-one")
        {
            var selectedSpaceKey = selectbox.options[selectbox.selectedIndex].value;
            var currentSpaceKey = 'java';

            if(currentSpaceKey != selectedSpaceKey){                checkbox.disabled=false;                checkbox.checked=false;                checkboxText.style.color='black';            }
            else{                checkbox.disabled=true;                checkbox.checked = true;                checkboxText.style.color='lightgrey';            }
        }
    }

</script>

<form id="editpageform" name="editpageform" method="post" action="doeditpage.action?pageId=18186675">
    <input
    type="hidden"
          name="originalVersion"            value="2"             />    <input
    type="hidden"
          name="originalContent"            value="Propagating the content of exceptions without performing explicit filtering is often associated with information leakage. An attacker may craft input parameters such that underlying structures and mechanisms may get exposed inadvertently.

h2. Noncompliant Code Example

This example demonstrates code that accepts a file name as an input argument on which operations are to be performed. An attacker can gain insights on the underlying file system structure by repeatedly passing different paths to fictitious files. When a file is not found, the {{FileInputStream}} constructor throws a {{FileNotFoundException}}. Other risks such as revelation of the user's home directory and as a result the user name also manifest themselves.

{code:bgColor=#FFcccc}
import java.io.FileInputStream;
import java.io.FileNotFoundException;

class exception {
  public static void main(String[] args) throws FileNotFoundException {
    FileInputStream dis = new FileInputStream("c:\\" + args[1]);
  }
}
{code}

h2. Compliant Solution

Information leakage can result from both the exception message text and the type of exception. With {{FileNotFoundException}}, the message reveals the file system layout while the type conveys the absence of the file. The same exception must be caught while taking special care to sanitize the message before propagating it to the caller. In cases where the exception type itself can reveal too much, consider throwing a different exception (with a different message) altogether.

{code:bgColor=#ccccff}

import java.io.FileInputStream;
import java.io.FileNotFoundException;

class exception {
  public static void main(String[] args) {
    try {
      FileInputStream dis = new FileInputStream("c:\\" + args[1]);
    }
    catch(FileNotFoundException fnf) { 
      System.out.println("Error: Operation could not be performed"); 
    } //sanitized message
  }
}

{code}



h2. Risk Assessment

TODO
|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| SEC00-J | ?? | ?? | ?? | P?? | L?? |



h3. Automated Detection

TODO

h2. References

Secure coding in Java http://java.sun.com/security/seccodeguide.html"             />    <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"           />

    <div id="editBox">
        <!--headerRow with padding of 10px. needs to be renamed-->

        <div id="headerRow">

            <!--Remove Page Link -->
            <div style="float:right;">
                        <a href="/confluence/pages/removepage.action?pageId=18186675"><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=18186675">Remove Page</a>
                </div>
            <div style="float:left"/>
            <!--title text field-->
            <div style="margin-bottom:5px;">
                                              <input type="text"
                                   name="title"
             size="55"                    value="SEC00-A. Do not allow exceptions to transmit sensitive information"               tabindex="1"             class="pagetitle"       />            </div>

            <!-- Start location section -->
            <div class="inputSection">
                



<script>
<!--

function hideLocationDiv()
{
    $('location_div').style.display = 'none';
            publishFormData($('newSpaceKey'), $('space_info'), $('space_content'));
        publishFormData($('parentPageString'), $('parent_info'), $('parent_content'));

    $('location_edit_link').innerHTML = "EDIT";
    highlight($('location_info'));
}

function showLocationDiv()
{
    $('location_div').style.display = 'block';
    $('location_edit_link').innerHTML = "DONE";
}

function toggleLocation()
{
    if($('location_div').style.display == 'none')
    {       showLocationDiv();    }
    else
    {        hideLocationDiv();    }
    return false;
}

//-->
</script>

<span class="formtitle">Location:</span>
<span id="location_info" onclick="toggleLocation()">
    <span id="space_info" >
        <span id="space_content">java</span>
    </span>
    <span id="parent_info" >
        > <span id="parent_content">00. Security (SEC)</span>
    </span>
    <span class="inline-control-link fontSizeTiny" id="location_edit_link">EDIT</span>
</span>
<div id="location_div" class="toggleFormDiv" style="padding: 8px; display:none">
                      <table>
        <tr>
            <td valign="top">
                <div>
                                    <div>
                        <label onclick="toggleLocation()" class="formtitle">Space</label>
                        <br />
                        <select id="newSpaceKey" name="newSpaceKey" tabindex="3" onChange=" blankParent();">
                                                    <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>
            </td>
            <td valign="top">
                <div>
                    

<div class="formtitle">
    Parent Page
</div>
<input type="text"
                                   name="parentPageString"
             size="30"                    value="00. Security (SEC)"               tabindex="2"                   id="parentPageString"                />            <a href="#" onClick="window.open('/confluence/users/spacepagepicker.action?pageId=18186675&currentspace=' + document.getElementById('newSpaceKey').value + '&formname=editpageform&fieldname=parentPageString&mode=history','link_inserter', 'width=620, height=400, resizable, scrollbars=yes'); return false;" title="Choose Page"  tabindex="diabled"><img src="/confluence/images/icons/document_zoom_in_16.gif" width="16" height="16" border="0"  tabindex="diabled" align="absmiddle"></a>
                    </div>
            </td>
        </tr>
            </table>
</div>

<script>
    </script>
            </div>
            </div>
            <!-- End location section -->
            <div>
            <!-- edit page form -->
            <!-- captcha form elements -->
		<br style="clear: both" />
            </div>
            <!--content editor-->
            <div class="inputSection">
                <div style="float:right;">
                    <div class="submitButtons">
                           <input
         tabindex="102"      accessKey="s"                  type="submit"      name="confirm" value="Save"/>&nbsp;&nbsp;
<input
         tabindex="104"                      type="submit"      name="cancel" value="Cancel"/>                    </div>
                </div>
                <div id="editorDiv" style="width:100%">
                    
<script type="text/javascript">
    var contentId =  "18186675" ;

    // this function is needed to store the caret position for IE browsers
    // you need to insert a call to storeCaret(this); to the onclick, onselect and onkeyup events of
    // the textarea you are editing
    function storeCaret(textAreaObject)
    {
        if (textAreaObject.createTextRange) // test for IE browsers
        {            textAreaObject.caretPos = document.selection.createRange().duplicate();        }
    }

    // this function stores the selected and unselected text for the textarea in hidden fields on the form
    function storeTextareaBits()
    {
        var t = $('markupTextarea');
        var currentForm = getCurrentForm();

        if (t.selectionStart != null)
        {            // for netscape, mozilla, gecko            t.sel = t.value.substr(t.selectionStart, t.selectionEnd - t.selectionStart);            t.sel1 = t.value.substr(0, t.selectionStart);            t.sel2 = t.value.substr(t.selectionEnd);            currentForm.selectedText.value = t.sel;        }
        else if (document.selection && document.selection.createRange)
        {
            // for ie
            var str = document.selection.createRange().text;
            try
            {                currentForm.elements['content'].focus();            }
            catch (e)
            {            // ignore            }
            var sel = document.selection.createRange();
            currentForm.selectedText.value = sel.text;
            return;
        }
    }

    function showRichText(show)
    {
            }

    function showMarkup(show)
    {
        if(show)
        {
            $('markup').style.display = 'block';
            $('markupTab').className = 'current';


            if ($('helptd'))
            {
                try
                {                    $('helptd').style.display = 'table-cell';                }
                catch (e)
                {                    // IE throws exception with invalid display type, so                    // we'll use the incorrect value of 'block'                    $('helptd').style.display = 'block';                }
            }
            if ($('linkinserters'))
            {                $('linkinserters').style.display = 'block';            }
        }
        else
        {
            $('markup').style.display = 'none';
            $('markupTab').className = '';

            if ($('helptd'))
            {                $('helptd').style.display = 'none';            }
            if ($('linkinserters'))
            {                $('linkinserters').style.display = 'none';            }
        }
    }

    function showPreview(show)
    {
        if(show)
        {            $('preview').style.display = 'block';            $('previewTab').className = 'current';        }
        else
        {            $('preview').style.display = 'none';            $('previewTab').className = '';        }
    }

    function setRichTextDefault(value)
    {        AjaxUserProfileEditor.setPreferenceUserEditWysiwyg(value);        $('makeRichTextDefault').style.display = 'none';        $('makeMarkupDefault').style.display = 'none';    }

    function showWaitImage(flag)
    {        $('wysiwygWaitImage').style.visibility = (flag ? 'visible' : 'hidden');    }
    function reply_setTextArea(s)
    {        showWaitImage(false);        setMode('markup');        if (s != null)            $('markupTextarea').value = s;    }
    function reply_setEditorValue(s)
    {        showWaitImage(false);        setMode('richtext');        setEditorValue(s);    }


    function reply_setPreviewArea(s)
    {        showWaitImage(false);        setMode('preview');        $('previewArea').innerHTML = s;    }


    /**
    * Set up the page for rich text or markup editing
    */
    function setMode(mode)
    {
        var inRichText = inRichTextMode();
        var form = getCurrentForm();
        form.mode.value = mode;
        if (mode != 'preview')
        {            form.xhtml.value = (mode == 'richtext');        }

        
        if (mode == 'richtext')
        {            showRichText(true);            showMarkup(false);            showPreview(false);        }

        if (mode == 'markup')
        {            if (inRichText)                showRichText(false);            showMarkup(true);            showPreview(false);        }

        if (mode == 'preview')
        {
                    saveDraft(null);
                    if (inRichText)
            {                // get the editor content in case we come back to wiki-markup                lastKnownGoodContent = getEditorHTML() + "";                showRichText(false);            }
            showMarkup(false);
            showPreview(true);
        }
    }

    // Hide and show the "make default" links, based on what mode the user is currently in, and what the WYSIWYG setting is
    function showDefaultLinks(defaultIsWysiwyg)
    {
        var showRichTextDefault = false;
        var showMarkupDefault = false;
        var form = getCurrentForm();

        // If we are in MARKUP mode, show the text to set markup as default
        if (defaultIsWysiwyg && form.mode.value == 'markup')
        {            showMarkupDefault = true;        }
        // If we are in RICHTEXT mode, show the text to set richtext as default
        else if (!defaultIsWysiwyg && form.mode.value == 'richtext')
        {            showRichTextDefault = true;        }

        $('makeRichTextDefault').style.display = (showRichTextDefault ? 'inline' : 'none');
        $('makeMarkupDefault').style.display = (showMarkupDefault ? 'inline' : 'none');
    }


    // Save the last edit mode in case the user changes to preview and from there to the other edit mode...
    // then we will have to convert the markup to XHTML or vice verca.
    var lastEditMode;

    var lastKnownGoodContent = null;

    function inRichTextMode()
    {        var form = getCurrentForm();        return form.mode.value == 'richtext';    }



    function changeMode(mode)
    {
        var form = getCurrentForm();

                

        if (form.mode.value != mode)
        {
            showWaitImage(true);

            if (mode == 'markup') // going from wysiwyg to markup
            {
                // If the current mode is preview...
                if (form.mode.value == 'preview')
                {
                    // Markup -> Preview -> Markup
                    // We don't need to do any conversion...
                    if(lastEditMode == 'markup')
                    {                        reply_setTextArea(null);                    }
                    // WYSIWYG -> Preview -> Markup
                    // Convert the WYSIWYG html to wiki markup
                    else
                    {                        WysiwygConverter.convertXHtmlToWikiMarkupWithoutPage(lastKnownGoodContent,contentId,reply_setTextArea);                    }
                }
                // WYSIWYG -> Markup, so just convert
                else
                {                    WysiwygConverter.convertXHtmlToWikiMarkupWithoutPage(getEditorHTML() + "",contentId,reply_setTextArea);                }
            }

            else if (mode == 'richtext')// going from markup to wysiwyg
            {
                var textarea = $('markupTextarea');

                // If the current mode is preview...
                if (form.mode.value == 'preview')
                {
                    // WYSIWYG -> Preview -> WYSIWYG
                    // We don't need to reload or convert the contents of the tinyMCE editor
                    if(lastEditMode == 'richtext')
                    {                        reply_setEditorValue(null);                    }
                    // Markup -> Preview -> WYSIWYG
                    // Convert the markup to be used with WYSIWYG
                    else
                    {                        WysiwygConverter.convertWikiMarkupToXHtmlWithoutPage(textarea.value,contentId, reply_setEditorValue);                    }
                }
                // Markup -> WYSIWYG, so just grab the contents of the markup textarea and convert it to be used with WYSIWYG
                else
                {                    WysiwygConverter.convertWikiMarkupToXHtmlWithoutPage(textarea.value,contentId, reply_setEditorValue);                }
            }

            else // viewing the preview
            {
                // WYSIWYG -> Preview
                if (form.mode.value == 'richtext')
                {                    lastEditMode = 'richtext';                    var html = getEditorHTML() + "";                    lastKnownGoodContent = html;                    WysiwygConverter.convertToPreview(html,contentId, 'java', 'richtext', reply_setPreviewArea);                }
                // Markup -> Preview
                else
                {                    lastEditMode = 'markup';                    var textarea = $('markupTextarea');                    WysiwygConverter.convertToPreview(textarea.value, contentId, 'java', 'markup', reply_setPreviewArea);                }
            }
        }
    }

    var contentHasChangedSinceLastAutoSave = false;
    function saveDraft(callback)
    {
        if (!callback)
            callback = function() {};

        var form = getCurrentForm();
        if (hasContentChanged())
        {
            var draftData = new Object();
            draftData.pageId = '18186675';
            if (form.title)
            {                draftData.title = form.title.value;            }
            if (form.newSpaceKey)
            {                draftData.spaceKey = form.newSpaceKey.value;            }
            else
            {                draftData.spaceKey = 'java';            }
            if (form.originalVersion)
            {                draftData.pageVersion = parseInt(form.originalVersion.value);            }
            draftData.type='page';
            draftData.content = getCurrentFormContent(form);
            DraftAjax.saveDraft(draftData, form.xhtml.value == 'true', callback);
            resetContentChanged();
        }
        else
        {            // must call the call back even if we don't save a draft!            callback();        }
    }
    function heartbeat()
    {
        HeartbeatAjax.startActivity('18186675', 'page',
            function (activityResponses)
                {
                    if (activityResponses.length > 0)
                    {
                        $('heartbeatDiv').style.display = 'block';
                        var html = "";
                        var sep = "";
                        for (i = 0; i < activityResponses.length; ++i)
                        {                            var activityResponse = activityResponses[i]                            var usernamelink = '<a href="/confluence/display/~' + activityResponse.userName + '">' + activityResponse.fullName + '</a>';                            var lastEditDateMessage = '';                            if (activityResponse.lastEditDate != null)                                lastEditDateMessage = '<span class="smalltext">(last edit ' + activityResponse.lastEditDate + ')</span>';                            html += sep + usernamelink + ' ' + lastEditDateMessage;                            sep = ", ";                        }
                        $('otherUsersSpan').innerHTML = html;
                    }
                    else
                    {                        $('heartbeatDiv').style.display = 'none';                    }
                }
            );
    }
    function getCurrentForm()
    {        return document.forms['editpageform'];    }
    // Fallback function for Safari to show to submit the form via JavaScript and display the preview page.
    function sendFormWithPreview()
    {        form = getCurrentForm();        // create a hidden field for the update variable        var el = document.createElement("input");        el.type = "hidden";        el.name = "preview";        el.name = "preview";        el.value = "preview";        form.appendChild(el);        form.submit();    }

    // function to send the form to discard/use the draft
    function sendFormDraft(flagName)
    {
        form = getCurrentForm();

        addHiddenElement(form, flagName, "true");
        addHiddenElement(form, "pageId", "18186675");
        if (!form.spaceKey)
        {            addHiddenElement(form, "spaceKey", "java");        }

                    form.action="edit${draft.draftType}.action";
                form.submit();
    }

    function addHiddenElement(form, name, value)
    {        var el = document.createElement("input");        el.type = "hidden";        el.name = name;        el.value = value;        form.appendChild(el);    }

</script>
                <div id='heartbeatDiv' style="display: none;">
    <table style="clear: right" cellpadding='5' width='100%' cellspacing='8px' class='noteMacro' border="0" align='center'>
        <tr><td valign='top' width="1%"><img src="/confluence/images/icons/emoticons/warning.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>
            This page is being edited by <span id='otherUsersSpan'/>.            
        </td></tr>
    </table>
    </div>
    
    <ul class="tabnav" style="border-bottom: 0; width: 400px">
        <li class="tabs">
                        <a id="markupTab"  class="current" href="#" onClick="javascript:changeMode('markup');return false;">Wiki Markup</a>
                        <a id="previewTab"  href="#" onClick="javascript:sendFormWithPreview();return false;">Preview</a>
                </li>
        <li class="nontabs" style="margin: 8px 0pt 0pt 3px"><img id="wysiwygWaitImage" style="visibility:hidden" alt="Wait Image" border=0 src="/confluence/images/icons/wait.gif"></li>

            </ul>
    <!-- clears the floated elements above -->
    <br class="after-tabnav">

        <div style="background-color:#D6D6D6;  border:1px solid #CCC; border-bottom:0; " id='linkinserters'>
                                <a style="text-decoration: none" href="#" onClick="storeTextareaBits(); window.open('/confluence/users/insertimageinpage.action?pageId=18186675&formname=editpageform&fieldname=content&mode=search','link_image_inserter', 'width=700, height=400, resizable, scrollbars=yes'); return false;" title="Insert Image">
            <img src="/confluence/images/icons/confimage.gif" border="0px" title="Insert Image">
        </a>

                        <a style="text-decoration: none" href="#" onClick="storeTextareaBits(); window.open('/confluence/users/insertlink.action?pageId=18186675&currentspace=java&formname=editpageform&fieldname=content' + (document.getElementById('selectedText').value ? '&alias=' + document.getElementById('selectedText').value : ''),'link_inserter', 'width=620, height=480, resizable, scrollbars=yes'); return false;" title="Insert Link">
            <img src="/confluence/images/icons/conflink.gif" border="0px" title="Insert Link">
        </a>
    </div>
    
            <script type="text/javascript">
            var useWysiwyg = false;

            /*---------------------------------------------------------------------------
            Redefine the following two methods without calls to editorHasContentChanged()
            ---------------------------------------------------------------------------*/
            function hasContentChanged()
            {                return contentHasChangedSinceLastAutoSave;            }

            function resetContentChanged()
            {                contentHasChangedSinceLastAutoSave = false;            }
        </script>
    
        
            <script type="text/javascript" src="/confluence/s/1116/1/_/dwr/engine.js"></script>
     <!-- request this the traditional way to fix CONF-5561 -->
        
            <script type="text/javascript" src="/confluence/s/1116/1/_/wysiwyg-javascript"></script>
        <div id="markup" >
    <div>

    <textarea id="markupTextarea" name="content"
                      cols=""
                      rows="30"

                                             tabindex="5"                onclick="storeCaret(this);"
            onselect="storeCaret(this); storeTextareaBits()"
            onkeyup="storeCaret(this);contentChangeHandler();"
            onchange="contentChangeHandler();"
            style="padding:0; margin:0; width:100%; "
            class="monospaceInput"
            >Propagating the content of exceptions without performing explicit filtering is often associated with information leakage. An attacker may craft input parameters such that underlying structures and mechanisms may get exposed inadvertently.

h2. Noncompliant Code Example

This example demonstrates code that accepts a file name as an input argument on which operations are to be performed. An attacker can gain insights on the underlying file system structure by repeatedly passing different paths to fictitious files. When a file is not found, the {{FileInputStream}} constructor throws a {{FileNotFoundException}}. Other risks such as revelation of the user's home directory and as a result the user name also manifest themselves.

{code:bgColor=#FFcccc}
import java.io.FileInputStream;
import java.io.FileNotFoundException;

class exception {
  public static void main(String[] args) throws FileNotFoundException {
    FileInputStream dis = new FileInputStream("c:\\" + args[1]);
  }
}
{code}

h2. Compliant Solution

Information leakage can result from both the exception message text and the type of exception. With {{FileNotFoundException}}, the message reveals the file system layout while the type conveys the absence of the file. The same exception must be caught while taking special care to sanitize the message before propagating it to the caller. In cases where the exception type itself can reveal too much, consider throwing a different exception (with a different message) altogether.

{code:bgColor=#ccccff}

import java.io.FileInputStream;
import java.io.FileNotFoundException;

class exception {
  public static void main(String[] args) {
    try {
      FileInputStream dis = new FileInputStream("c:\\" + args[1]);
    }
    catch(FileNotFoundException fnf) { 
      System.out.println("Error: Operation could not be performed"); 
    } //sanitized message
  }
}

{code}

h2. References

Secure coding in Java http://java.sun.com/security/seccodeguide.html</textarea>
    </div>
    </div>
    <input id="selectedText" name="selectedText" type="hidden">
    <!-- two hidden fields to store textarea parts for mozilla based browsers -->
    <input type="hidden" name="sel1"><!--sel1: text before the selection-->
    <input type="hidden" name="sel2"><!--sel2: text after the selection-->

    <input type="hidden" name="inPreview" value="false"/>
    <input type="hidden" name="mode" value="markup"/>
    <input type="hidden" name="xhtml" value="false"/>

    <div id="preview" style="display:  none ; border:1px solid #CCCCCC; background-color:white;">
                        <div id="previewArea" style="margin:5px;"></div>
    </div>

    <!-- javascript code to initialise draft and heartbeat ajax -->
    <script type="text/javascript">
                DraftAjax.getDraftSaveInterval(
            function (interval) { setInterval("saveDraft()", interval); }
            );
                            if ('18186675' != '0')
            {
                heartbeat();
                HeartbeatAjax.getHeartbeatInterval(
                    function (interval) { setInterval("heartbeat()", interval); }
                );
            }
        
        function contentChangeHandler()
        {            contentHasChangedSinceLastAutoSave = true;        }
    </script>                </div>
            </div>
            <!-- comment field and minor edit checkbox -->
            <div class="inputSection">
                <div style="float:right">
                    <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>

            <!-- Page 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['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-->
            


<script>
function toggleLabels()
{
    toggleVisibility('labels_div');
    toggleVisibility('labels_info');
    if($('labels_div').style.display == 'none')
    {        $('labels_info').innerHTML = $('labelsString').value.toLowerCase();        $('labels_edit_link').innerHTML = "EDIT";        highlight($('labels_info'));    }
    else
    {        SuggestedLabelsForEntity.viewLabels('18186675', "labels/editpage-suggestedlabels.vm", loadSuggestedLabels);        $('labels_edit_link').innerHTML = "DONE";    }
}

    function loadSuggestedLabels(ajaxResponse)
    {
        if (ajaxResponse.success)
        {            $('suggestedLabelsSpan').innerHTML = ajaxResponse.response;        }
    }
</script>

<div id="labels_tab">
    <span class="formtitle">Labels: </span><span onclick="toggleLabels()" class="inline-control-link fontSizeTiny" id="labels_edit_link">EDIT</span>
</div>
<div id="labels_info">
   incomplete
</div>

<div id="labels_div" class="toggleFormDiv" style="padding: 8px; display:none">
    <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"><em>Tip:</em> Looking for a label? Just start typing.</div>
                <div class="auto_complete" id="labelsAutocompleteList"></div>

                <script>new Ajax.Autocompleter('labelsString', 'labelsAutocompleteList', '18186675', { tokens: new Array(',', ' '), dwrFunction: GenerateAutocompleteLabelsListForEntity.autocompleteLabels});</script>
            </td>
            <td valign="top">
                <div id="suggestedLabelsSpan" style="margin-top:5px;">

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

<script>
    </script>
            <div>
                <div class="submitButtons">
                       <input
         tabindex="102"      accessKey="s"                  type="submit"      name="confirm" value="Save"/>&nbsp;&nbsp;
<input
         tabindex="104"                      type="submit"      name="cancel" value="Cancel"/>                </div>
            </div>
        </div>
    </div>
</form>
<script type="text/javascript">
	(function() {
		$A(document.getElementsByClassName("submitButtons")).each(function(div) {
			$A(div.getElementsByTagName("input")).each(function(button) {				Event.observe(button, "click", pageFormSubmit, false);			});
		});
	})();
</script>
    </div>
                            </div>
                        </td>
                                
    
            
    
                                                    <td valign="top" id="helptd" style="display:block; width:200px; border-top:1px solid #CCC;">
                            <div style="padding-left:5px;">
                                <div class="rightpanel">
        <div id="helpheading">
        <img src="/confluence/images/icons/help_16.gif" height=16 width=16 border=0 align=absmiddle title="Help Tips">
        Help Tips
      </div>
      <div id="helpcontent">
                        <p>
    <b>Notation Help:</b>

    (<a href="#" onClick="window.open('/confluence/renderer/notationhelp.action','notation_help','width=780, height=580, resizable, scrollbars')">full guide</a>)

    <br/>
        Text formatting:<br/>
        <span class="smalltext">
            *bold* &raquo; <b class="strong">bold</b><br/>
            _italic_ &raquo; <em class="emphasis">italic</em><br/>
            -strike- &raquo; <del class="deleted">strike</del><br/>
            +under+ &raquo; <u>under</u><br/>
        </span>
    </p>
    <p>
        Headings:<br/>
        <span class="smalltext">
            h1. Large heading!<br />
            h3. Medium heading<br/>
            h5. Small heading...<br/>
        </span>
    </p>
    <p>
        Lists:<br/>
        <span class="smalltext">
            * Bulleted point<br />
            # Numbered point<br/>
        </span>
    </p>
    <p>
        Linking:<br/>
        <span class="smalltext">
            [title#anchor] &raquo; Link a page<br/>
            [dev:title#anchor] &raquo; In space with 'dev'<br/>
            [http://host.com] &raquo; Remote link<br/>
            [phrase@shortcut] &raquo; Shortcut<br/>
            <b><i>Note:</i></b> [alias|any_of_above_links] &raquo; Custom link title
        </span>
    </p>
    <p>
        Tables:<br/>
        <span class="smalltext">
            ||head1||head2||<br/>
            |colA1|colA2|<br/>
            |colB1|colB2|
        </span>
    </p>

    Details and full examples are in the
    <a href="/confluence/renderer/notationhelp.action" onClick="window.open(this.href,'notation_help','width=680, height=440, resizable, scrollbars'); return false;">full notation guide &raquo;</a>
                </div>
  </div>
                            </div>
                        </td>
                                            </tr>
                </table>
                <!-- End inner content table -->
            </td>
        </tr>
    </table>
</div>
  	                                                            <div class="bottomshadow"></div>
<!--   	<div id="poweredby" class="smalltext">
		Powered by <a href="http://www.atlassian.com/software/confluence" class="smalltext">Atlassian Confluence</a> 2.7.3, the <a href="http://www.atlassian.com/software/confluence" class="smalltext">Enterprise Wiki</a>.
		<a href="http://jira.atlassian.com/secure/BrowseProject.jspa?id=10470" class="smalltext">Bug/feature request</a>
		-
		<a href="http://www.atlassian.com/about/connected.jsp?s_kwcid=Confluence-stayintouch" class="smalltext">Atlassian news</a>
		-
		<a href="/confluence/administrators.action">Contact administrators</a>
        <br/>
	</div>
 -->

<!-- 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-2008 Carnegie Mellon University 
</td>
</tr>
</table>


<!--END FOOTER -->
</body>
</html>
the exception
  throw new IOException("Unable to retrieve file", e);
}

Even when the logged exception is not accessible to the user, the original exception is still informative and can be used by an attacker to discover sensitive information about the file system layout.
Note that this example also violates FIO04-J. Release resources when they are no longer needed, as it fails to close the input stream in a finally block. Subsequent code examples also omit this finally block for brevity.

Noncompliant Code Example (Sanitized Exception)

This noncompliant code example logs the exception and throws a custom exception that does not wrap the FileNotFoundException:

Code Block
bgColor#FFcccc
class SecurityIOException extends IOException {/* ... */};

try {
  FileInputStream fis =
      new FileInputStream(System.getenv("APPDATA") + args[0]);
} catch (FileNotFoundException e) {
  // Log the exception
  throw new SecurityIOException();
}

Although this exception is less likely than the previous noncompliant code examples to leak useful information, it still reveals that the specified file cannot be read. More specifically, the program reacts differently to nonexistent file paths than it does to valid ones, and an attacker can still infer sensitive information about the file system from this program's behavior. Failure to restrict user input leaves the system vulnerable to a brute-force attack in which the attacker discovers valid file names by issuing queries that collectively cover the space of possible file names. File names that cause the program to return the sanitized exception indicate nonexistent files, whereas file names that do not return exceptions reveal existing files.

Compliant Solution (Security Policy)

This compliant solution implements the policy that only files that live in c:\homepath may be opened by the user and that the user is not allowed to discover anything about files outside this directory. The solution issues a terse error message when the file cannot be opened or the file does not live in the proper directory. Any information about files outside c:\homepath is concealed.

The compliant solution also uses the File.getCanonicalFile() method to canonicalize the file to simplify subsequent path name comparisons (see FIO16-J. Canonicalize path names before validating them for more information).

Code Block
bgColor#ccccff
class ExceptionExample {
  public static void main(String[] args) {

    File file = null;
    try {
      file = new File(System.getenv("APPDATA") +
             args[0]).getCanonicalFile();
      if (!file.getPath().startsWith("c:\\homepath")) {
        System.out.println("Invalid file");
        return;
      }
    } catch (IOException x) {
      System.out.println("Invalid file");
      return;
    }

    try {
      FileInputStream fis = new FileInputStream(file);
    } catch (FileNotFoundException x) {
      System.out.println("Invalid file");
      return;
    }
  }
}

Compliant Solution (Restricted Input)

This compliant solution operates under the policy that only c:\homepath\file1 and c:\homepath\file2 are permitted to be opened by the user. It also catches Throwable, as permitted by exception ERR08-J-EX2(see ERR08-J. Do not catch NullPointerException or any of its ancestors). It uses the MyExceptionReporter class described in ERR00-J. Do not suppress or ignore checked exceptions, which filters sensitive information from any resulting exceptions.

Code Block
bgColor#ccccff
class ExceptionExample {
  public static void main(String[] args) {
    FileInputStream fis = null;
    try {
      switch(Integer.valueOf(args[0])) {
        case 1: 
          fis = new FileInputStream("c:\\homepath\\file1"); 
          break;
        case 2: 
          fis = new FileInputStream("c:\\homepath\\file2");
          break;
        //...
        default:
          System.out.println("Invalid option"); 
          break;
      }      
    } catch (Throwable t) { 
      MyExceptionReporter.report(t); // Sanitize 
    } 
  }
}

Compliant solutions must ensure that security exceptions such as java.security.AccessControlException and java.lang.SecurityException continue to be logged and sanitized appropriately (see ERR02-J. Prevent exceptions while logging data for additional information). The MyExceptionReporter class from ERR00-J. Do not suppress or ignore checked exceptions demonstrates an acceptable approach for this logging and sanitization.

For scalability, the switch statement should be replaced with some sort of mapping from integers to valid file names or at least an enum type representing valid files.

Risk Assessment

Exceptions may inadvertently reveal sensitive information unless care is taken to limit the information disclosure.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ERR01-J

Medium

Probable

High

P4

L3

Automated Detection

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.ERR01.ACPST
CERT.ERR01.CETS
CERT.ERR01.ACW
Do not call the 'printStackTrace()' method of "Throwable" objects
Catch all exceptions which may be thrown within Servlet methods
Avoid writing to Consoles
SonarQube
Include Page
SonarQube_V
SonarQube_V
S1989Exceptions should not be thrown from servlet methods

Related Vulnerabilities

CVE-2009-2897 describes several cross-site scripting (XSS) vulnerabilities in several versions of SpringSource Hyperic HQ. These vulnerabilities allow remote attackers to inject arbitrary web script or HTML via invalid values for numerical parameters. They are demonstrated by an uncaught java.lang.NumberFormatException exception resulting from entering several invalid numeric parameters to the web interface.

CVE-2015-2080 describes a vulnerability in the Jetty web server, versions 9.2.3 to 9.2.8, where an illegal character passed in an HTML request causes the server to respond with an error message containing the text with the illegal character. But this error message can also contain sensitive information, such as cookies from previous web requests.

Related Guidelines

SEI CERT C++ Coding Standard

VOID ERR12-CPP. Do not allow exceptions to transmit sensitive information

MITRE CWE

CWE-209, Information Exposure through an Error Message
CWE-497, Exposure of System Data to an Unauthorized Control Sphere
CWE-600, Uncaught Exception in Servlet

Bibliography


Image Added Image Added Image Added