<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SEC01-A. Be careful using doPrivileged - 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>
<body onload="placeFocus()">
<!--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">
<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/SEC01-A.+Be+careful+using+doPrivileged">SEC01-A. Be careful using doPrivileged</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++</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/SEC01-A.+Be+careful+using+doPrivileged" onClick="javascript:saveDraftOnPageChange(this); return false;" accessKey="v"><u>V</u>iew</a></li>
<li><a id="editPageLink" href="/confluence/pages/editpage.action?pageId=18186686" 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=18186686" 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=18186686" 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=18186686"><img src="/confluence/images/icons/add_page_16.gif" height="16" width="16" border="0" align="absmiddle" title="Add Page"> 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>
</span>
<a href="/confluence/pages/editpage.action?pageId=18186686&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=18186686&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=18186686"><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=18186686"><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;">
SEC01-A. Be careful using doPrivileged
</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 = '18186686';
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=18186686">
<input
type="hidden"
name="originalVersion" value="2" /> <input
type="hidden"
name="originalContent" value="The static method {{doPrivileged}} is used to affirm that the invoking method is taking responsibility for exercising its own permissions and that the access permissions of its callers should be ignored. For example, an application may have permissions to operate on a sensitive file, however, a caller of this application may be allowed to operate with only basic user permissions. Invoking {{doPrivileged()}} in the context of this method allows it to exercise its own (possibly elevated) permissions under such circumstances.
h2. Noncompliant Code Example
There are two fallacies in this noncompliant code example. First, the {{doPrivileged}} method is being called from inside the {{openPasswordFile}} method. The {{openPasswordFile}} method is privileged and returns a {{FileInputStream}} reference to its caller. This allows any caller to call {{openPasswordFile()}} directly and obtain a reference to the sensitive file due to the inherent privileges present within the corresponding code. Second, the name of the sensitive password file is user controllable which introduces other risks such as unaccounted misuse of miscellaneous sensitive files.
{code:bgColor=#FFcccc}
class password {
public static void changePassword(String password_file) throws FileNotFoundException {
FileInputStream fin;
fin = openPasswordFile(password_file);
}
public static FileInputStream openPasswordFile(String password_file) throws FileNotFoundException {
//Declare as final and assign before the body of the anonymous inner class
//Array f[] is used to maintain language semantics while using final
final FileInputStream f[]={null};
final String file = password_file;
//Use own privilege to open the sensitive password file
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = new FileInputStream("c:\\" + file); //Perform privileged action
}catch(FileNotFoundException cnf) { System.err.println(cnf.getMessage()); }
return null; //Still mandatory to return from run()
}
});
return f[0]; //Returns a reference to privileged objects (inappropriate)
}
}
{code}
h2. Compliant Solution
The {{openPasswordFile}} method controls access to the sensitive password file and returns its reference. Since it cannot control being invoked by untrusted user methods, it should not assert its privileges within the body. Instead, {{changePassword()}} the caller method, can safely assert its own privilege whenever someone else calls it. This is because {{changePassword()}} does not return a reference to the sensitive file to any caller but processes the file internally. Also, since the name of the password file is hard-coded in the code, caller supplied (tainted) inputs are not used.
{code:bgColor=#ccccff}
class password {
public static void changePassword() {
//Use own privilege to open the sensitive password file
final String password_file = "password";
final FileInputStream f[] = {null};
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = openPasswordFile(password_file); //call the privileged method here
}catch(FileNotFoundException cnf) { System.err.println(cnf.getMessage()); }
return null;
}
});
//Perform other operations such as password verification
}
public static FileInputStream openPasswordFile(String password_file) throws FileNotFoundException {
FileInputStream f = new FileInputStream("c:\\" + password_file);
//Perform read/write operations on password file
return f;
}
}
{code}
h2. Risk Assessment
TODO
|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| SEC01-J | ?? | ?? | ?? | P?? | L?? |
h3. Automated Detection
TODO
h2. References
Inside Java 2 Platform Security, 6.4 AccessController
Sun Secure Coding Guidelines http://java.sun.com/security/seccodeguide.html
Documentation http://java.sun.com/j2se/1.4.2/docs/api/java/security/AccessController.html#doPrivileged(java.security.PrivilegedAction)" /> <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=18186686"><img src="/confluence/images/icons/trash_16.gif" width="16" height="16" border="0px" align="absmiddle" title="Remove"></a> <a href="/confluence/pages/removepage.action?pageId=18186686">Remove Page</a>
</div>
<div style="float:left"/>
<!--title text field-->
<div style="margin-bottom:5px;">
<input type="text"
name="title"
size="55" value="SEC01-A. Be careful using doPrivileged" 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=18186686¤tspace=' + 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"/>
<input
tabindex="104" type="submit" name="cancel" value="Cancel"/> </div>
</div>
<div id="editorDiv" style="width:100%">
<script type="text/javascript">
var contentId = "18186686" ;
// 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 = '18186686';
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('18186686', '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", "18186686");
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=18186686&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=18186686¤tspace=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"
>The static method {{doPrivileged}} is used to affirm that the invoking method is taking responsibility for exercising its own permissions and that the access permissions of its callers should be ignored. For example, an application may have permissions to operate on a sensitive file, however, a caller of this application may be allowed to operate with only basic user permissions. Invoking {{doPrivileged()}} in the context of this method allows it to exercise its own (possibly elevated) permissions under such circumstances.
h2. Noncompliant Code Example
There are two fallacies in this noncompliant code example. First, the {{doPrivileged}} method is being called from inside the {{openPasswordFile}} method. The {{openPasswordFile}} method is privileged and returns a {{FileInputStream}} reference to its caller. This allows any caller to call {{openPasswordFile()}} directly and obtain a reference to the sensitive file due to the inherent privileges present within the corresponding code. Second, the name of the sensitive password file is user controllable which introduces other risks such as unaccounted misuse of miscellaneous sensitive files.
{code:bgColor=#FFcccc}
class password {
public static void changePassword(String password_file) throws FileNotFoundException {
FileInputStream fin;
fin = openPasswordFile(password_file);
}
public static FileInputStream openPasswordFile(String password_file) throws FileNotFoundException {
//Declare as final and assign before the body of the anonymous inner class
//Array f[] is used to maintain language semantics while using final
final FileInputStream f[]={null};
final String file = password_file;
//Use own privilege to open the sensitive password file
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = new FileInputStream("c:\\" + file); //Perform privileged action
}catch(FileNotFoundException cnf) { System.err.println(cnf.getMessage()); }
return null; //Still mandatory to return from run()
}
});
return f[0]; //Returns a reference to privileged objects (inappropriate)
}
}
{code}
h2. Compliant Solution
The {{openPasswordFile}} method controls access to the sensitive password file and returns its reference. Since it cannot control being invoked by untrusted user methods, it should not assert its privileges within the body. Instead, {{changePassword()}} the caller method, can safely assert its own privilege whenever someone else calls it. This is because {{changePassword()}} does not return a reference to the sensitive file to any caller but processes the file internally. Also, since the name of the password file is hard-coded in the code, caller supplied (tainted) inputs are not used.
{code:bgColor=#ccccff}
class password {
public static void changePassword() {
//Use own privilege to open the sensitive password file
final String password_file = "password";
final FileInputStream f[] = {null};
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = openPasswordFile(password_file); //call the privileged method here
}catch(FileNotFoundException cnf) { System.err.println(cnf.getMessage()); }
return null;
}
});
//Perform other operations such as password verification
}
public static FileInputStream openPasswordFile(String password_file) throws FileNotFoundException {
FileInputStream f = new FileInputStream("c:\\" + password_file);
//Perform read/write operations on password file
return f;
}
}
{code}
h2. References
Inside Java 2 Platform Security, 6.4 AccessController
Sun Secure Coding Guidelines http://java.sun.com/security/seccodeguide.html
Documentation http://java.sun.com/j2se/1.4.2/docs/api/java/security/AccessController.html#doPrivileged(java.security.PrivilegedAction)</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 ('18186686' != '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('18186686', "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', '18186686', { 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"/>
<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* » <b class="strong">bold</b><br/>
_italic_ » <em class="emphasis">italic</em><br/>
-strike- » <del class="deleted">strike</del><br/>
+under+ » <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] » Link a page<br/>
[dev:title#anchor] » In space with 'dev'<br/>
[http://host.com] » Remote link<br/>
[phrase@shortcut] » Shortcut<br/>
<b><i>Note:</i></b> [alias|any_of_above_links] » 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 »</a>
</div>
</div>
</div>
</td>
</tr>
</table>
<!-- End inner content table -->
</td>
</tr>
</table>
</div>
|