Showing posts with label security. Show all posts
Showing posts with label security. Show all posts

Saturday, April 23, 2011

Code to Browse the Security Setup of SharePoint Site Collection

In case if you need to verify the security setup of your SharePoint site collection, you just need to run the following code as shown below:

using System;
using System.Linq;
using Microsoft.SharePoint;

namespace BrowseSecurity
{
    class Program
    {
        static void Main(string[] args)
        {
            BrowseSecurity("http://localhost");
            Console.Out.WriteLine(true);
        }

        private static void BrowseSecurity(string url)
        {
            using (SPSite site = new SPSite(url))
            {
                SPWeb web = site.OpenWeb();
                Console.WriteLine("\n\nUsers:");
                foreach (SPUser user in web.Users)
                {
                    Console.WriteLine(user.Name);
                }

                Console.ReadLine();
                Console.WriteLine("\n\n All Users:");
                foreach (SPUser user in web.AllUsers)
                {
                    Console.WriteLine(user.Name);
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Site Users:");
                foreach (SPUser user in web.AllUsers)
                {
                    Console.WriteLine(user.Name);
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Roles:");
                foreach (SPRole role in web.Roles)
                {
                    Console.WriteLine(role.Name);
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Roles Definitions:");
                foreach (SPRoleDefinition roledef in web.RoleDefinitions)
                {
                    Console.WriteLine(roledef.Name);
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Roles Assignments:");
                foreach (SPRoleAssignment roleA in web.RoleAssignments)
                {
                    Console.WriteLine("The following Role definition bindings exist for " +
                    roleA.Member.Name);
                    foreach (SPRoleDefinition roledef in roleA.RoleDefinitionBindings)
                    {
                        Console.WriteLine(roledef.Name);
                    }
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Groups:");
                foreach (SPGroup group in web.Groups)
                {
                    Console.WriteLine(group.Name);
                }
                Console.ReadLine();
            }
        }
    }
}

Tuesday, July 21, 2009

SharePoint Single Sign-On Error: “User DOMAIN\USERID failed to configure the single sign-on server. The error returned was ERROR NUMBER. Verify this account has sufficient permissions and try again”

When configure SharePoint Single Sign-On (SSO), sometimes you’ll get “You do not have the rights to perform this operation.” error message on the “Manage Settings for Single Sign-On” page and subsequently “User DOMAIN\USERID failed to configure the single sign-on server. The error returned was ERROR NUMBER. Verify this account has sufficient permissions and try again.” error message is displayed in the Windows Event Viewer and SharePoint Log.

To fix this issue, you have to make sure “Single Sign-On Administrator Account” account name to start the Microsoft Single Sign-On Service MUST meet all of the following:

  • Must be a domain user account. It cannot be a group account.
    • The user must be a member of Domain Admins and Domain Users

image

  • Must be an Office SharePoint Server farm account
    • Go to Central Administration > Operations, then click on the “Update farm administrator's group” link to add the user to farm administrator group.
  • Must be a member of the local Administrators group on the encryption-key server
    • The encryption-key server is the first server on which you start SSOSrv
  • Must be a member of the Security Administrators role and Database Creators role on the computer running Microsoft SQL Server.
    • Open SQL Management Studio, go to Security > Server Roles folder, add the user to securityadmin and dbcreator server roles

Also most important setting is to MAKE SURE, the same “Single Sign-On Administrator Account” account name is used at both “Manage Server Settings for Single Sign-On” page and “Service Accounts” page as shown below:

image

Thursday, July 16, 2009

Validate User Base Permissions Before Uploading Document to SharePoint Document Library

If you are building a custom Web Part to upload document to SharePoint Document Library, then you need to validate user’s base permission so that unauthorised user can’t perform upload. You can’t validate based on their permission levels since at anytime base permissions of any permission level can be changed by administrator. Plus, in object model there is no specific method to get the permission level or what permission level assigned to a group or a user.

This article describes how to perform document upload to SharePoint and validate user base permissions so that only authorized users are able to perform the upload.

In SharePoint, the out-of-the-box permission level allowed user with "Contribute" permission level or higher (i.e. "Full Control", "Design", "Manage Hierarchy" and "Approve") to upload document to SharePoint. The following code displays the base permissions for each permission level:

SPSite oSite = new SPSite("http://examplesite");
SPWeb oWeb = oSite.OpenWeb();

SPRoleDefinitionBindingCollection usersRoles = oWeb.AllRolesForCurrentUser;
foreach (SPRoleDefinition roleDefinition in usersRoles)
    retVal += roleDefinition.BasePermissions.ToString() + " | ";

System.Diagnostics.Debug.WriteLine(retVal);

Full Control” permission level:

  • FullMask
  • OR SPWeb.UserIsWebAdmin = TRUE

Design” permission level:

  • ViewListItems | AddListItems | EditListItems | DeleteListItems | ApproveItems | OpenItems | ViewVersions | DeleteVersions | CancelCheckout | ManagePersonalViews | ManageLists | ViewFormPages | Open | ViewPages | AddAndCustomizePages | ApplyThemeAndBorder | ApplyStyleSheets | CreateSSCSite | BrowseDirectories | BrowseUserInfo | AddDelPrivateWebParts | UpdatePersonalWebParts | UseClientIntegration | UseRemoteAPIs | CreateAlerts | EditMyUserInfo

Manage Hierarchy” permission level:

  • ViewListItems | AddListItems | EditListItems | DeleteListItems | OpenItems | ViewVersions | DeleteVersions | CancelCheckout | ManagePersonalViews | ManageLists | ViewFormPages | Open | ViewPages | AddAndCustomizePages | ViewUsageData | CreateSSCSite | ManageSubwebs | ManagePermissions | BrowseDirectories | BrowseUserInfo | AddDelPrivateWebParts | UpdatePersonalWebParts | ManageWeb | UseClientIntegration | UseRemoteAPIs | ManageAlerts | CreateAlerts | EditMyUserInfo | EnumeratePermissions
    OR SPWeb.UserIsWebAdmin = TRUE

Approve” permission level:

  • ViewListItems | AddListItems | EditListItems | DeleteListItems | ApproveItems | OpenItems | ViewVersions | DeleteVersions | CancelCheckout | ManagePersonalViews | ViewFormPages | Open | ViewPages | CreateSSCSite | BrowseDirectories | BrowseUserInfo | AddDelPrivateWebParts | UpdatePersonalWebParts | UseClientIntegration | UseRemoteAPIs | CreateAlerts | EditMyUserInfo

Contribute” permission level:

  • ViewListItems | AddListItems | EditListItems | DeleteListItems | OpenItems | ViewVersions | DeleteVersions | ManagePersonalViews | ViewFormPages | Open | ViewPages | CreateSSCSite | BrowseDirectories | BrowseUserInfo | AddDelPrivateWebParts | UpdatePersonalWebParts | UseClientIntegration | UseRemoteAPIs | CreateAlerts | EditMyUserInfo

Read” permission level:

  • ViewListItems | OpenItems | ViewVersions | ViewFormPages | Open | ViewPages | CreateSSCSite | BrowseUserInfo | UseClientIntegration | UseRemoteAPIs | CreateAlerts

and for "Site Collection Administrator" user, base permission as follows:

  • FullMask
  • OR SPWeb.UserIsSiteAdmin= TRUE

To validate whether user access rights to upload document to SharePoint, the following conditions shall be used:

  • SPWeb.UserIsSiteAdmin = TRUE OR
  • SPWeb.UserIsWebAdmin = TRUE OR
  • AddListItems is exist OR
  • EditListItems is exist OR
  • ApproveItems is exist OR

See code below for details:

public static void IsUserBasePermissionValidToUpload(SPWeb oWeb)
{
    try
    {
        if (oWeb.Exists)
        {
            // If user is site collection administrator or admin
            if (oWeb.UserIsWebAdmin || oWeb.UserIsSiteAdmin)
                return;

            // Get roles for current user
            SPRoleDefinitionBindingCollection usersRoles = oWeb.AllRolesForCurrentUser;
            // Validate if user has rights to upload document
            foreach (SPRoleDefinition roleDefinition in usersRoles)
            {
                if (roleDefinition.BasePermissions.ToString().Contains(SPBasePermissions.FullMask.ToString())
                    || roleDefinition.BasePermissions.ToString().Contains(SPBasePermissions.AddListItems.ToString())
                    || roleDefinition.BasePermissions.ToString().Contains(SPBasePermissions.EditListItems.ToString())
                    || roleDefinition.BasePermissions.ToString().Contains(SPBasePermissions.ApproveItems.ToString()))
                    return;
            }

            // If user has invalid rights, then throw exceptions
            throw new Exception("Unauthorised to upload document to SharePoint Document Library. " +
                "You are currently signed in as: " + oWeb.CurrentUser.LoginName);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Saturday, March 28, 2009

Using Elevated Privileges and AllowSafeUpdates Method - Potential Security Risks

Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform. I have such situation in one of our project, suppose that you wanted to provide add, edit or delete capability to all users who use your application, regardless of their permissions on the list. So how this would be achieved?

By using the SPSecurity class, it provides a method RunWithElevatedPrivileges that allows you to run a subset of code in the context of an account with higher privileges than the current user. You need to wrap the RunWithElevatedPrivileges method around your code, as shown below: 

    protected void btnAddListItem_Click(object sender, EventArgs e)
    {
        using (SPSite oSite = SPContext.Current.Site)
        {
            // Run with an account with higher privileges than the current user
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    // Turn off security validation
                    oWeb.AllowUnsafeUpdates = true;
                    // Code to add list item to a list
                    SPList oList = oWeb.Lists["ListName"];
                    SPListItem oListItem = oList.Items.Add();
                    oListItem["PostCode"] = txtPostCode.Text;
                    oListItem.Update();
                    // Turn on security validation
                    oWeb.AllowUnsafeUpdates = false;
                }
            });
        }
    }

Also, in certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.

This is a common mistake when coding using AllowSafeUpdates method, so I think it is worth a mention because not many people knew this.