OWASP Security in SharePoint

OWASP stands for “Open Web Application Security Project”. This article will list all the possible threats or risks which a SharePoint server can have and their preventive measures.

Most of these threats and their preventive measures are available in the internet but here I have tried to put them together in one place.

Risk 1 – Injection

Threat: Injection flaws, such as SQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing unauthorized data.

Prevention: Use SharePoint safe API such as list and libraries, user profile service and business data connectivity, and this will avoid direct connection to SQL databases and LDAP. For custom components, use CAML Queries that will interact with SQL Database as an interpreter and will not be directly queried to the SQL server.

Risk 2 – Cross-Site Scripting (XSS)

Threat: XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation and escaping. XSS allows attackers to execute scripts in the victim’s browser that can hijack user sessions, deface web sites or redirect the user to other malicious sites.

Prevention: Properly escape all untrusted data based on the HTML context (body, attribute, JavaScript, CSS, or URL) that the data will be placed using HTML Escape before Inserting Untrusted Data into HTML Element Content or HTML encode/decode utility of SharePoint. Along with this, use positive or “whitelist” input validation as it helps in protecting against XSS. Take into consideration the Content Security Policy (CSP) to defend against XSS across the site.

Risk 3 – Broken Authentication and Session Management

Threat: Application functions related to authentication and session management are often not implemented correctly thereby allowing attackers to compromise passwords, keys, session tokens, or exploit other implementation flaws to assume other users’ identities.

Prevention: Use claimed based authentication and default SharePoint Session management to meet the authentication and session management requirements defined in OWASP’s Application Security Verification Standard areas V2 (Authentication) and V3 (Session Management).

Risk 4 – Insecure Direct Object References

Threat: A direct object reference occurs when a reference is exposed to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.

Prevention: For preventing the insecure direct object references, use the SharePoint security permission level as mentioned below:

  • Check access. – Each use of a direct object reference from an untrusted source must include an access control check to ensure the user is authorized for the requested object.

Risk 5 – Cross-Site Request Forgery (CSRF)

Threat: A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests that the vulnerable application thinks are legitimate requests from the victim.

Prevention: For preventing the Cross site Request Forgery; follow the steps mentioned below:

  • SharePoint will implement Form Digest control on each custom page.
  • Send the query (i.e. AllowUnsafeUpdates property will be set to true while updating objects) with every post back or web service request
  • Validate the query before acting on the post back or web service request

Risk 7 – Insecure Cryptographic Storage

Threat: Many web applications do not properly protect sensitive data, such as credit cards, SSNs, and authentication credentials, with appropriate encryption or hashing. Attackers may steal or modify such weakly protected data to conduct identity theft, credit card fraud, or other crimes.

Prevention: To prevent Insecure Cryptographic storage, follow the steps mentioned below:

  • Identify all sensitive data and encrypt it even when it is stored on a hard drive.
  • Ensure that sensitive data cannot be overwritten.
  • Keep secrets such as proprietary algorithms, encryption keys even from the administrator.
  • Identify sensitive data read into memory, overwrite it with random data and use strong encryption to safeguard it.

Risk 8 – Failure to Restrict URL Access

Threat: Many web applications check URL access rights before rendering protected links and buttons. However, applications need to perform similar access control checks each time these pages are accessed, or attackers will be able to forge URLs to access these hidden pages anyway.

Prevention: To prevent Failure to Restrict URL Access, use appropriate permissions or Access Control settings to disallow anonymous reading. Do not allow read permissions of any sensitive data files to anonymous web visitor user. SharePoint will define/configure the list of file types available for remote reading on the server.

Risk 9 – Insufficient Transport Layer Protection

Threat: Applications frequently fail to authenticate, encrypt, and protect the confidentiality and integrity of sensitive network traffic. When they do, they sometimes support weak algorithms, use expired or invalid certificates, or do not use them correctly.

Prevention: Identify all components and the versions that are being used and consider all the dependencies. Monitor the security of these components in public databases, project mailing lists, and security mailing lists, and keep them up to date. Establish security policies governing component use, such as requiring certain software development practices, passing security tests, and acceptable licenses. Consider adding security wrappers around components to disable unused functionality and/ or secure weak or vulnerable aspects of the component.

Risk 10 – Invalidated Redirects and Forwards

Threat: Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

Prevention: Avoid usage of redirects and forwards. If the above is used, then do not involve user parameters in calculating the destination. If the destination parameters cannot be avoided, ensure that the supplied value is valid, and authorized for the user.

SharePoint Branding – Hiding Header/Footer in Dialogs (Modal-Popup)

Recently, I was working in an Office 365 application and wanted to open a modal-pop on the click of an anchor tag from a custom publishing page. The requirement was to show a new item form in the modal pop-up. Although, I worked on this kind of requirement back in SharePoint 2010, but not in Office 365.

SharePoint allows us to hide elements from dialogs, however the CSS class to change such elements has changed from SharePoint 2010 to SharePoint 2013 & Office 365.

So, for example, when we create a custom master page, we usually add custom header and footer to System Master Page. This starts appearing the modal-pop which is not required. So the solution for this problem is:-

  1. In SharePoint 2010, the CSS class name was “s4-notdlg”. This class needs to be added to an HTML element which we want to hide in the modal-pop.
  2. In SharePoint 2013 or Office 365, we use the same method, just a different CSS class “ms-dialogHidden”.

NOTE:-

  1. You can add the ms-dialogHidden class to any HTML element in your Master Pages and Page Layouts.
  2. If you have created separate master pages for Site and System (Option available in site Settings Master Page), then you need to specify this class in System Master Page HTML.

SharePoint Search Index Partition Error

Recently, the client reported that search service application has stopped working in the production server and that they are not getting the search results. When I checked the search service application, under Search Application Topology section, I saw Search Index partition error – a yellow triangle. This definitely meant something is wrong with Index partition in that particular server.

Try the following steps before resetting the search index:-

  1. Clear the SharePoint Server Cache. Follow this article for detailed steps – Clearing the Configuration Cache
  2. Restart the ‘SharePoint Server Search 15’ service (services.msc) listed under Services(Local).
  3. Reset search index (Option available on left in Search Service Application Configuration Page)

The above steps needs to be performed on all the servers in the farm which are running Search service (Not on WFE, as hopefully on WFE Search Service Application is not running).

If Indices are not corrupted and nothing serious has happened to your search, after clearing cache and restarting the service, your Topology should show up just fine with tick marks under all the components. After this, do a full crawl and everything should start working as before.

This worked for me and hope it helps many 🙂

The last option for this issue is – Rebuild or Recreate the whole search service.

YOU DON’T HAVE ADD AND CUSTOMIZE PAGES PERMISSIONS REQUIRED TO PERFORM THIS ACTION

I was working in the SharePoint 2013 OOTB “Task List” and developed a custom visual web-part for the “Newform.aspx” and “EditForm.aspx” , having all the control as present in the OOTB forms. (You must be thinking that why I developed custom forms, however this question is out-of-context for this blog). Since I was the site collection administrator, I never faced any issues while adding new items or editing the existing ones.

However, users who are having the “Full Control” or “Contribute” permissions at the task list level , reported that they are facing the following issue which says that they do not have permissions to add new items. On the first thought,  it seemed to me a permission issue but I found that if I click on new item from my machine, they were able to open the form from their machines and can add new items in the task list ….Strange enough !!

Error message – “You don’t have Add and Customize Pages permissions required to perform this action”

Web part error
Web part error

 

 

 

 

Solution 1:-

1. Add a new permission level which only includes “Add and Customize Pages” permission, and then create a new SharePoint group with this permission level.
2. Add the users into the SharePoint group and these users will get the “Add and Customize Pages” permission from the site level (site permission).

Solution 2:-

If above solution does not work in your system, then give “Full Control” permission to the users at the Site Level.

Hope this blog helps many 🙂

Restore items from the SharePoint 2013 Recycle Bin

Interestingly, An item was deleted from a list (Task List) by a user, and to restore that item, users went to Recycle Bin and also to Site Collection Recycle Bin, but no avail. I was told to investigate the date of deletion and by whom.

So, the question asked to me was – Is there any other way to get the details of the deleted item or where the deleted item can be found?

Answer – Yes you can find out the user. Login to the content database, there you will have a table “dbo.RecycleBin”. Query this table for DeleteUserID and then query the table “dbo.UserInfo” with this deleteUserID to get user details. You will get other details as well from this DeleteUserID table.

dbo.RecycleBin:-

 

 

 

 

dbo.UserInfo:-

 

 

 

 

Point to Note – Recycle Bin does not keep deleted items for ever. The default setting in SharePoint is to keep content in Recycle Bin for 30 days after deletion, this can be changed by the SharePoint farm administrators. When this grace period is over, items are moved to the second stage aka Site Collection Recycle Bin.

Two Stages of Recycle bin:
Yes, SharePoint offers Two stages in recycle bins,

First-stage recycle bin – When users delete Files/List items it goes to First stage recycle bin. Also called “End user Recycle bin”. Content in this recycle bin is counted on Site quota, so when you delete a file, it goes to recycle bin, But you wont get any additional free space, still it occupies site quota. This recycle bin is accessible to the end users, and its Security trimmed (Even a site collection admin can’t see end user’s recycle bins, He/She needs to use “Site collection Recycle bin” to see end user’s recycle bin.)

Second-stage recycle bin – When the content deleted from First-stage recycle bin, its moved to Second stage recycle bin. Here Items not counted on Site quota, But total space occupied by second stage recycle bin is based on Central administration setting “Second stage Recycle bin Percentage in Live site’s Quota”. This Recycle bin acts at site collection level, and can be accessed only to site collection admins.

I hope this will help you out.

How to identify whether a site is based on SharePoint or not

We often come across many sites on Internet or intranet and we always want to know that whether the site is based on SharePoint or not. So, in this article I am going to list all possible ways to identify if a site is based on SharePoint or not.

  • The simplest way is to check the structure of the site i.e. folder structure or different pages. This pattern may show you a SharePoint Publishing site (Pages/Pagename.aspx or default.aspx). You can also search for /SitePages library by typing in the URL.
  • If the site if of high importance OR if the site is very famous, then it will definitely be published as Microsoft case study : http://www.microsoft.com/casestudies
  • As we know, SharePoint on-premise server is hosted on IIS (Internet Information Server), so we can check using HttpResponse or by some other tools that which hosting server is used for a particular site.
  • In Chrome or Firefox browsers, open up console and view JavaScript’s files used on the page. If you see init.js, core.js etc., then it’s definitely a SharePoint site.
  • Right click on any page and see for “view source”. Click on that and search for meta tag. If it’s a SharePoint site, then it will definitely have:-
    <head><meta name=”GENERATOR” content=”Microsoft SharePoint” />
    src=”/_layouts/1033/init.js”
  • If it’s a SharePoint site, then it must be calling web services in it. You can call any of the SharePoint OOTB web services (if it doesn’t open, then you will see the legendary “Error page” or “Something went wrong” page). Just access any of the web service present inside the “_layouts” folder.
    E.g. – <<Site_Url>>/_layouts/lists.asmx

If you will check or test any of the above one or two points, then definitely you can be say that whether site is based on SharePoint or not.

CASE STUDY: –

Interestingly, while browsing the Indian Income Tax Department website (http://incometaxindia.gov.in/pages/default.aspx), I found that this site is based on SharePoint….voila !!

To confirm on this, I tested using the above points and below are my observations: –

1) Clicked on view source on the home page and searched for meta tag: –

it-1-meta-tag

 

 

2) Then I searched for init.js, _layouts based structure and other files related to SharePoint:-

it-2-init-js

 

 

3) Lastly, I checked the internal web service of SharePoint by typing this URL in browser – http://incometaxindia.gov.in/_layouts/lists.asmx , and see below the SharePoint Error page:-

it-3-error-page

 

 

 

Do you still need proof? Well enough, I know its SharePoint site now.

Getting the Reply Count for a SharePoint Discussion (Discussion List)

SharePoint’s Discussion lists are sort of like Document Sets, in that the original post is a Discussion Content Type which inherits from Folder and the replies are the Message Content Type, which inherits from Item. So there aren’t any Documents involved, but Discussions (Discussion list) are once again Folders.

I was working on task to get the replies of a Discussion in a Discussion list.I implemented the following code using SPServices and was able to get the reply count and replies of a particular discussion.
(ItemCount is that mysterious count of replies I was looking for :))

<!DOCTYPE html>

<html lang=”en” xmlns=””>

<head>
<meta charset=”utf-8″ />
<title>Governance & Nomination Committee</title>

$(document).ready(function() {
var siteURL = _spPageContextInfo.webServerRelativeUrl;
//alert(siteURL);
var discussionListName = “Mergers and Acquisition Committee”;
$().SPServices({
webURL: siteURL,
operation: “GetListItems”,
async: false,
listName: “Mergers and Acquisition Committee”,
CAMLViewFields: “”,
completefunc: function(xData, Status) {
$(xData.responseXML).SPFilterNode(“z:row”).each(function() {
var ItemCount = $(xData.responseXML).SPFilterNode(“rs:data”).attr(“ItemCount”);
//alert(“ItemCount:=” + ItemCount);

var subject, createdOn, modifiedOn, createdOnDate, modifiedOnDate, createdOnTime, modifiedOnTime, discussionURL;
if (ItemCount > 0) {
subject = $(this).attr(“ows_Title”);
createdOn = $(this).attr(“ows_Created”);
modifiedOn = $(this).attr(“ows_Modified”);

createdOnDate = convertDateTime(createdOn, “date”);
//createdOnTime = convertDateTime(createdOn, “time”);

modifiedOnDate = convertDateTime(modifiedOn, “date”);
modifiedOnTime = convertDateTime(modifiedOn, “time”);

var fileRef = $(this).attr(“ows_FileRef”);
//alert(“fileRef:=” + fileRef);
var filepath = getFilePath(fileRef);
//alert(filepath);
var RepliesCount = getDiscussionRepliesCount(discussionListName, filepath, siteURL);
//alert(RepliesCount);

discussionURL = $(this).attr(“ows_EncodedAbsUrl”);
//alert(“discussionURL:=” + discussionURL);
//discussionURL = discussionURL.substr(0, discussionURL.lastIndexOf(“/”));
//alert(“discussionURL:=” + discussionURL);
var disitemURL = discussionURL + “/DispForm.aspx?ID=” + $(this).attr(“ows_ID”);
$(‘#ulMergersNAcquisition’).append(“Title : ” + subject + “” + “Created On : ” + createdOnDate + “” + “Last Updated : ” + modifiedOnDate + “, ” + modifiedOnTime + “” + “Replies : ” + RepliesCount + ““);
} else {
$(‘#ulMergersNAcquisition’).append(“There are no items to show.”);
}

});
} //End of complete function
}); //End of SPServices
}); //End of Doc Ready

function getFilePath(fileRef) {
if (!fileRef) return;
var m = /;#(.*)$/.exec(fileRef);
if (m) {
return m[1];
}
}

function getDiscussionRepliesCount(list, filepath, siteURL) {
//alert(‘In getDiscussionReplies :=’ + filepath);
var i = 0;
var finalReplies;
$().SPServices({
webURL: siteURL,
operation: “GetListItems”,
async: false,
listName: list,
CAMLViewFields: “”,
CAMLQueryOptions: “”,
CAMLQuery: “” + filepath + “”,
completefunc: function(xData, Status) {
$(xData.responseXML).SPFilterNode(“z:row”).each(function() {
//alert(xData.responseText);
if (i == 0) {
var replies = $(this).attr(“ows_ItemChildCount”);
finalRepliesCount = replies.split(‘#’)[1];
//alert(finalRepliesCount);
i = 1;
}
});
//return finalRepliesCount;
} //End of complete function
}); //End of SPServices
return finalRepliesCount;
}

function convertDateTime(x, formatter) {
var months = [‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’];
var shortMonths = [‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’, ‘May’, ‘Jun’, ‘Jul’, ‘Aug’, ‘Sep’, ‘Oct’, ‘Nov’, ‘Dec’];

// split up date and time
xDate = x.split(” “)[0];
xTime = x.split(” “)[1];

// split off the hour from the minute/second
xMinSec = xTime.split(“:”)[1];
xHour = xTime.split(“:”)[0];

// set the am or pm suffix
if (xHour > 12) {
ampm = “PM”;
xHour -= 12;
} else if (xHour
</head>

<body>
<ul id=”ulMergersNAcquisition”></ul>
</body>
</html>

Important points to know about Site Columns and Content Types in SharePoint 2013

In one of my recent projects of SharePoint Online (Office 365), I need to create the site architecture starting with creation of Site Columns and Site Content Types. To give you the glimpse of the project, it involved roll-up and roll-down of data from 300 sub-sites under the root site collection. So, I decided to use Content Search web-part which allows to roll-up the data and by modifying the queries, we can roll-down the data too.

What I learnt –

  1. Use OOTB site columns as much as possible, do not create your new site columns if already provided by SharePoint. However, if OOTB columns doesn’t suits your requirement, then you can create new custom column (For E.g. – OOTB “Due Date” columns is of Date type, so if you wish Date and Time type column then you cannot use this OOTB column)
  2.  Always create a separate group for your site columns and content types.This will help you to filter the columns and content types.
  3. Many times, we make columns as Hidden for one list/library and then try to add the same columns in other list/library which we find is not available. So, before adding a site column in any list/library or any content type, make sure that the column is not hidden at top level.
  4. After migration or after creating a site template, your site is not getting created (assuming your site having workflow also), then change your .wsp file to .cab file and check the XML files. Try to delete the duplicate entries of site columns and content types which are created twice.

Check Existence of User in SharePoint Group using JSOM

While working with SharePoint objects it’s required to check whether user is present in which SharePoint group.Hence, the below script comes in handy to check existence of user in SharePoint group using JSOM.

ExecuteOrDelayUntilScriptLoaded(IsUserExists, “sp.js”);
var spfGroup;
var spfUsers;
var context;
var spfGroupCollection;
var spfUser;

function IsUserExists() {
context = SP.ClientContext.get_current();
spfGroupCollection = context.get_web().get_siteGroups();
spfUser = context.get_web().get_currentUser();
spfGroup = spfGroupCollection.getById(101);
or
spfGroup = spfGroupCollection.getByName(“SPF Owners”);
context.load(spfGroup);
context.load(spfUser);
context.executeQueryAsync(Function.createDelegate(this, this.OnGetGroupSuccess), Function.createDelegate(this, OnFailure));

}

function OnGetGroupSuccess() {
spfUsers = spfGroup.get_spfUsers();
context.load(spfUsers);
context.executeQueryAsync(Function.createDelegate(this, this.OnGetuserSuccess), Function.createDelegate(this, OnFailure));
}

function OnGetuserSuccess() {
var userEnumerator = spfUsers.getEnumerator();
while (userEnumerator.moveNext()) {
var spfUser = userEnumerator.get_current();
if (spfUser.get_id() == spfUser.get_id()) {
alert(“User Exists”);
break;
} else {

}
}
}

function OnFailure(sender, args) {
alert(“Failed to execute IsCurrentUserMemberOfGroup method”);
}

Hope this blog helps 🙂

Pages in SharePoint 2013

It’s very important to make decision when planning a Web Content Management (WCM) application that which type of web page is suitable for the given task. We can create a WIKI page, a Web Part Page, or a Publishing Page. In this blog, I would be discussing that which page would be most appropriate in any given situation.

Publishing Pages

  • Designed for creating content pages in a controlled manner with consistent look and feel, these pages are based on page layouts and content types. Typically, page layouts are created by web page designers and publishing content pages can be created based on pre-defined page layouts by authors. This is a common scenario for Web Content Management (WCM) systems.
  • Publishing Pages have pre-defined content areas similar to Web Part zones. This allows page designers to define page layouts and impose full control over how page content can be rendered.
  • Publishing Pages content can be versioned and maintain a history of changes. Publishing Pages optionally allows for introducing page approval and scheduling life cycle.
  • Publishing Pages are stored in Pages library. This library is only available when publishing infrastructure is enabled on the site. There can only be one page libraries per site.

Web Part Pages

  • Content on a Web Part page is constrained to display in individual Web Parts. Web Part pages are structured Web Part content objects including lists, libraries, and other collaborative content including rich media, web pages, search results, and an information aggregation. Users can’t easily add text or images to Web Part pages – it requires Web Parts like the Content Editor Web Part (CWEP) or image Web Parts. This can be a deciding factor in choosing WIKI Part pages over Web Part pages because adding simple graphic images would require Web Parts and knowledge of the Content Editor Web Part (CWEP) implementation and configuration.
  • Web Part pages have pre-defined content areas like Web Part zones where Web Parts can be added and moved as needed.
  • A Web Part pages’ layout and content can be configured for all users or optionally personalized for individual users.
  • Web Part pages can be stored in any document library, though ideally stored in Site Assets, Site Pages, or another Document Library.

WIKI Pages

  • WIKI pages consists of a rich text editing environment providing WYSIWYG In-Browser editing experience using Web Editing technology. Users add free-form text & rich content like tables, links, images, as well as SharePoint lists and Web Parts anywhere on the page without the limitation of Web Part zones. WIKI Pages do not require Web Parts like the content editor or image Web Parts to add texts or images.
  • While you can easily add Web Parts to Web Part pages, this requires experience with the Content Editor Web Part (CEWP) for advanced customization. It’s much easier to place free-form text, images, and links including Web Parts on a WIKI page. This makes WIKI pages more flexible, faster and easier to develop than Web Part pages.
  • WIKI pages are easier to manage than Web Part pages. End users need minimal IT support. This is a major advantage over Web Part pages. Conversely, because it’s so easy to apply different fonts and styles on WIKI pages, Web Part pages allow better governance and control over the presentation, formatting, and general look and feel.
  • A major issue of WIKI pages is the presence of hidden HTML tags encountered while editing the page in a WYSIWYG editor. This can be frustrating for the user who doesn’t have knowledge of HTML and are concerned with how to remove those hidden tags and spaces. Power Users employ tools like SharePoint Designer to manage HTML tags such as hidden paragraph and DIV tags.
  • Another issue with WIKI pages is targeting specific sections to brand WIKI pages. Because WIKI pages uses CSS classes to wrap most of the content tags like DIV, it may be a challenge to target specific sections of a WIKI page for branding. Web Part pages allow wrapping of Web Part zones with DIV tags to target specific areas with CSS.
  • WIKI pages have HTML zones where content can be added directly on the page.
  • WIKI pages can’t be personalized. They are designed to share information in a collaborative way, allowing multiple contributors to add and update content.
  • WIKI pages’ support versioning and maintain a history of changes.
  • WIKI pages are stored in the site pages’ library.
  • WIKI pages are created and edited by Site Members or above security groups (requires Contribute permission).
  • All the content added to WIKI pages are added as HTML mark-up. There is no direct API available to programmatically maintain (add or remove) Web Parts on the WIKI pages.

Generally, WIKI pages are the best option for Intranet content pages. WIKI pages deliver the flexibility to add diverse content easily while allowing a more intuitive experience for non-IT business users.

The final implementation of a well-designed web presence will most likely employ all three of these web page variations.

Publishing Pages – Main Intranet Home Page: Since this page is the main landing page for all users, it usually requires the most structured presentation with a fixed page layout making Publishing Pages the ideal choice.

Web Part Pages – Department or Major business area Home Pages:  Most department level home pages are maintained by department level content owners. In order to standardize the look and feel and the layout of home pages across an intranet, Web Part pages are considered the ideal choice by encouraging department level content owners to add content in a more controlled manner.

WIKI Pages – Intranet Content Pages and Team Site Home Pages: Given the WYSIWYG in-page editing capabilities, WIKI pages are an ideal vehicle for end-users to create and manage content on team sites.