Monday, February 2, 2015

Lost MS SQL Server admin access? No Problem

Today I by mistake removed my own windows account from my local MS SQL Server installation. That meant I couldn’t use the DB anymore. I didn’t have any other account setup on this DB because it is a local setup. What it meant was that the SQL Server setup was useless, and only way to use it was to uninstall the whole DB Server and install it again.

However I did some search and found following solution to recover access-

Step 1 :

net stop mssqlserver

or you can stop it from services.msc. Now open a command prompt as an administrator and type:

Step 2 :

net start mssqlserver /f /T3608 

This will start MS SQL server in single user mode.

Step 3 :

sqlcmd 


Step 4 : create new windows user
1 create login [<<DOMAIN\USERNAME>>] from windows;
2 EXEC sys.sp_addsrvrolemember @loginame = N'<<DOMAIN\USERNAME>>', @rolename = N'sysadmin';
3 GO;

OR, create sql server login
1 CREATE LOGIN [testAdmin] WITH PASSWORD=N'test@1234', DEFAULT_DATABASE=[master];
2 EXEC sys.sp_addsrvrolemember @loginame = N'testAdmin', @rolename = N'sysadmin';
3 GO

Step 5 : close sqlcmd by CTRL+c


Step 6 : Login to SQL Server via SQL Server Mgmt. Studio

The curious case of SharePoint integrated SSRS Subscription

Some time ago I found that whenever I create an SSRS subscription with multiple cascaded filters in SharePoint integrated mode, the the time it takes to create subscription after selecting all filter values is more than the total time taken if the SSRS report were executed.

In order to understand why this happens, lets understand what happens when you create a subscription.

image

When you click on “Add Subscription”, all present data sets are executed. You might ask why?, well the answer is because present parameter and filter values need to be populated. This seems normal but the curious case that I’m talking about is something else.

The problem is with cascaded filters i.e. filters values depending on other filters values

Default behavior means all the datasets are fired when “add subscription” is clicked. Because child filter must have values that are derived from the values of parent filter in cascade, the dataset queries are fired multiple times, depending on how many cascaded children you have.

In a scenario where the data sets have complex and long queries, the problem can become very evident in terms of the time it takes to create a subscription.

But why does it happen. I asked this question to Microsoft. The response was – because of POSTBACK. Because it is SharePoint integrated mode, all calls are diverted through SharePoint and POSTBACK re-fires them. Another question I asked Microsoft was – why was it designed this way? They don’t have an answer to this. However they were kind enough to look further and fix this problem.

so here is the problem statement as defined by Microsoft and its solution:

Problem Description:

You’ve a report in SharePoint integrated mode which contains parameters. When you do an add subscription, the page takes a lot of time to come up. Also, when you change any of the parameters, the post back takes really long time to reload the page.

Analysis:

1. We took the profiler traces and found that a single query belonging to a data set is executing 4 times. This has been causing the issue.

3. We engaged our product team to have a better understanding of the behavior and how we can mitigate the same.

4. The reason behind the multiple execution of the query is due to the post back within ASP.NET.

5. We reviewed our code and found a scope for improvement, at least that would remove one level of execution.

6. Our Product team has agreed to release the improved code as part of SQL Server 2012 SP 2 CU 5.

Root cause:

1. Due to the post back behavior of ASP.NET, the queries have been executed multiple times.

Resolution:

A fix will be released as part of SQL Server 2012 SP 2 CU 5. The tentative release date is on March 16, 2015.

Tuesday, December 2, 2014

SSRS tweaks for external facing environment

An external facing (for consumption of non-corporate users e.g. customers, vendors etc.…) SSRS requires some extra tweaking in order to make it functional and compliant with organizational policies.

1. SSRS session expiring even before SharePoint session expires (for SharePoint integrated mode)

SSRS has its own session settings. make sure you have set them at par with SharePoint session settings. I’ve discussed about SharePoint settings in my previous blogs.

image

In case you do not want confusion between SSRS and SharePoint session settings, uncheck the “Use Session Cookies”. If there is a difference between session timeout settings between SharePoint and SSRS, you might face problems while creating subscriptions. Every time the session expires, you might get errors that subscription list doesn’t exist if you are on manage subscription page.

2. Disable “Open with Report Builder”

When SSRS reports are executed they show “Open with Report Builder” option under action button. In case of external facing environment you may not like it, because mostly external users are non-windows users while the report builder tool works only with windows authentication; so its of no use anyways. To remove this option from under the action button run following SQL query on SSRS main database.

1 UPDATE dbo.ConfigurationInfo
2
3 SET value = ‘False’
4
5 WHERE name = ‘EnableReportDesignClientDownload’

Sunday, November 23, 2014

SharePoint External Architecture & Implementation - Part 6

Previous Blog - Part 5
Note:- This is a maxi post.
This blog will deals specifically with Microsoft BI scenario in external. As all roads lead to Rome, all problems lead us to single cause in case of externally facing environments – Authentication.
In case end users of an externally facing Microsoft BI environment are vendors and customers, you do not want them to see each other’s data. However you also don’t want to create separate set of reports for each of these different users. The best, optimized and accepted solution is to provide row level security and handle the authorization of user at the data source level. Different databases have different mechanism to handle row level security. I’m going to talk about how to enable row level security for SSAS (SQL Server Analysis Services) in absence of active directory with SharePoint as front end.

I’ve always wondered what was the reason that Microsoft didn’t allow any other authentication except for Windows authentication in SSAS. It would have provided architects some leg room to try it with non-Microsoft products, nevertheless, they left the window open with “CustomData” implementation as query banding (read here). optional parameters can be passed in connection string with binding it with CustomData. Once this CustomData value is retrieved on the SSAS server, it be used to run logic using DAX (Data Analysis Expressions).

Important thing to note here is that only two solution can be used in an external Microsoft BI environment (assuming its non-windows authentication environment) with row level security; namely SSRS (SQL Server Reporting Services) and PPS (Performance Point Service). Other service such as excel services, Power Pivot, Power View etc.… don’t provide a way to delegate end user’s credentials to the data source.

Now lets look at the implementation of row level security for an Microsoft BI solution with SSAS as data source. The problem has to be divided in two parts.
  1. Send end user’s credentials to data source
  2. Return only those rows where end user has access

Send end user’s credentials to data source

a) SSRS - Use following connection string within SSRS report data source. Make sure its an embedded connection string i.e. connection string passed as a text string within SSRS data source because you can use SSRS inbuilt parameter USERID to pass end user’s identity this way. If you chose to use connection string by specifying it in SharePoint UI, this inbuilt variable will not be available. This is how a connection string would look like.
="Data Source=<SSAS Server Name>:<Port>;Initial Catalog=<Database Name>; Character Encoding=UTF-8; Customdata=" & User!UserID

b) PPS – PPS provides direct way to insert CustomData into the connection string. All you have to do is to click the checkbox “Provide the authenticated user as the value of the connection string property "CustomData"” on the PPS data connection properties page.

Untitled

Because SharePoint keeps the login name in an encoded format (read here) the CustomData that is passed to the SSAS would be in encoded format.

Return only those rows where end user has access

On the SSAS cube, create a role and add member those accounts which were supplied in SSRS data source and PPS unattended service account. Make sure you don’t provide these accounts admin access on SSAS else the whole exercise of row level security would fail and all the users will see whole data.

Because CustomData has been passed via connection string, you can use its value and apply the logic on it. The first logic that you need to apply is to decode the encoded string passed by SharePoint. This can be achieved by using DAX in the role created for the cube access.

Untitled1


Right(right(CustomData(),len(CustomData()) - search("|",CustomData())),len(right(CustomData(),len(CustomData()) - search("|",CustomData())))- search("|",right(CustomData(),len(CustomData()) - search("|",CustomData()))))


Above DAX expression will return you the actual user login ID from encoded value passed from SharePoint. You can use the login ID to run logical operation to return only those rows which match certain values.

Monday, November 17, 2014

SharePoint External Architecture & Implementation - Part 5

Previous Post :- Part 4
One of the major problem for a DMZ environment is that it’s a strictly controlled network enclave. In most of the scenarios you can’t access internet. Your organization might provide proxy as an interface to internet, however it could be a cumbersome process especially if it requires registration of each URL to be accessed.
Why am I talking about access to internet? As it turns out that SharePoint uses its own self created certificate for communication between many of its services. Also if you are using external domain certificates, these certificates will  contact CRLs (certificate revocation list) for certificate validation. Most probably these CRLs are on internet.
Whenever these certificates are invoked, that would be every time somebody connects, authenticates or services need them, these certificates would go online for validation. SharePoint would try to connect to internet to contact CRLs. If a CRL is not accessible, SharePoint would continue to try to access them. This would result in a degraded performance for end users. In fact it could be unacceptable performance. Fortunately there is a setting available in windows that could be used to work around this issue.
Open “Local Security Policy” on all SharePoint servers – type secpol.msc in run prompt.
image
Select “Public Key Policies” from left tree menu and open “Certificate Path Validation Settings” from right pane.
image
Select “Network Retrieval” tab. Check “Define these policy settings” checkbox if its not checked.
Removed check from “Automatically update certificates in the Microsoft Root Certificate Program (recommended)”.
Set 1 second for both “Default URL retrieval timeout” and “Default path validation cumulative retrieval timeout”.
Above setting would cause CRL validation event to timeout in 1 second hence saving a lot of time and performance.

Sunday, November 16, 2014

SharePoint External Architecture & Implementation - Part 4

Previous Blog : SharePoint External Architecture & Implementation - Part 3
In previous blogs I talked about architecture and authentication for an external facing SharePoint environment. However in an enterprise setup, access control would be required to ensure that data is delivered only on need to know basis. Primary issue for an external facing environment is, that it may not have an active directory based user and group store to pick those users and groups for permission assignment. White SharePoint works seamlessly with an active directory, in absence of it a customized solution is required to attach a user and group store for assigning permissions. Because SharePoint uses claims for its internal working, any custom authorization process must provide user and group credentials through claims, hence the name custom claim provider.
Fire command get-spclaimprovider on SharePoint server and you will see a few inbuilt claim providers.
a custom claim provider is a .wsp solution for SharePoint, to be created in Visual Studio. SharePoint provides a few methods, which need to be implemented to attach a custom user and group store. It could be any database such as a SQL Server, file, SharePoint list etc…
Besides providing claims to SharePoint for assigning permissions, custom claim provider can also augment incoming user claims. What it means that you can provide or learn more information about a user is accessing the environment.
There are numerous resources available online to explain how to build a custom claims provider. Some useful that I found are given below.
http://www.codeproject.com/Articles/506023/Understanding-SharePoint-Custom-Claims-Provider
http://blog.podrezo.com/sharepoint-custom-claims-provider/
http://www.titus.com/blog/2012/03/building-a-custom-claim-provider-to-manage-security-clearances/
for Microsoft BI environment, here’s a very useful document.
http://social.technet.microsoft.com/wiki/contents/articles/15274.using-claims-authentication-across-the-microsoft-bi-stack.aspx
Note:- Custom Claim Provider creates issue with SSRS subscriptions if you are planning to use it for BI. I worked with Microsoft to find a solution to this, but even they are unable to pin point the reasons of this problem. For BI environment, you can come up with an alternate approach of creating sharepoing groups through a .wsp solution.

Monday, August 11, 2014

SharePoint External Architecture & Implementation - Part 3

 

Previous Blog : SharePoint External Architecture & Implementation - Part 2

Authentication is a very important factor when building an external environment. One of the most important thing to understand is that, an external platform is usually used by non-corporate users; namely customers and suppliers. There are also applications which are used by corporate employees. For all applications that are accessed by corporate employees, the standard mode of authentication is Active directory (Kerberos). If your application is to be used by corporate employees, very good, because there is already a good authentication mechanism in place. All you have to do is build your application and join it with corporate domain. Well, it’s easier said than done, however there are more challenges to be faced when your application also caters to non-corporate users.

Before we talk about external authentication mechanism, let’s take a look at the authentication mechanism used for any external application.

First, what is Authentication?

“Authentication is the process of determining whether someone or something is, in fact, who or what it is declared to be.”

To successfully and accurately determine identity of a user, it necessary to have a reference list, database, password or any such method which can uniquely identity it. Let’s understand different authentication scenarios from two examples.

Example 1:

I book an airline ticket online. On scheduled date, I arrive at the airport for check-in. Security staff asks me for my ticket, and I show a locally printed ticket to them. They are satisfied that it’s a valid ticket with for a travel that would initiate in some time. However, they would still ask me for my identity verification; to ensure that I’m what I claim to be. This identity verification can be done with my driving license or a passport. They would look at the photograph on the identity card and then at me and will let me board the flight only when they think it belongs to me.

Example 2:

I book a ticket for a movie. I arrive at the movie theater to claim my seat. The gate-keeper asks me for my ticket, and I present it to him. I takes a look at the ticket, validates that it’s for the right show and lets me in.

The major difference in above examples is that, in example 1 – even after I claimed that I’ve a valid ticket, I was asked to prove my identity. While in example 2 – my claim is sufficient. Example 1 showcases working of an active directory authentication mechanism. After I pay for my ticket, through password - I’m issued a ticket with a fixed validity period. My operating system uses this ticket to access applications, and applications on their part validate with Active Directory services that the ticket is valid and was indeed issues to me. Example 2 is a typical scenario for a claim based authentication, usually done for external facing application. Because non-corporate users don’t have valid account in corporate directory service, they are issued a ticket through a mutually trusted use store. Example of such user stores are, Microsoft Live, Microsoft Azure, Google+, Facebook, LinkedIn etc...… Once a user is authenticated through the user store, Identity provider issues a time bound token to the user’s browser or client application. This token may have attributes such as login name, email address, country etc...… User presents this token to external application and the application accepts it, NO QUESTIONS ASKED. It doesn’t go back to user store to validate, it simply trusts it.

External facing applications, which are accessed by non-corporate users work on same mechanism as described in example 2. Valid users are issued tokens after they are authenticated. This token is stored on client machines through cookies.

If external users have to be authorized and authenticated, there needs to be a user store/repository through which these users can be validated. Now it completely depends on the organizational preferences. It could be either an external users repository such as Microsoft Azure, Google + or an internal repository such as IBM Tivoli directory service or any other open LDAP director service.

In absence of active directory, SharePoint uses a custom authentication provider, namely a claims Federation agent. Special configurations have to be put in place to configure this Federation agent with SharePoint. This configuration is done with the help of Power Shell. In this post I’ll walk you through the process of configuring a custom Federation agent and how it works.

During the configuration of Federation agent in SharePoint, you will also define the login URL for the SharePoint. When user request hits SharePoint, SharePoint will redirect user to this login URL. This login URL will belong to an authentication mechanism which will take supplied user credentials and validate them against the user store. Once this authentication mechanism validates that the user is a valid one, it will pass this information to the Federation agent. Also this authentication mechanism will pass any required attributes for this user such as username, email address, et cetera. Federation agent on receiving these attributes; will convert them into a claim token and then it sends this claim token to the SharePoint. SharePoint uses claims authentication within the farm to communicate within servers and services.

Let’s understand how to configure an authentication provider for SharePoint.

   1: $root = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("path to root certificate")
   2: New-SPTrustedRootAuthority -Name "Root" -Certificate $root
   3:  
   4: $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("path to certificate provided by federation agent")
   5: New-SPTrustedRootAuthority -Name "<authenticatino provider name>" -Certificate $cert
   6:  
   7: $upnClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/claims/UID" -IncomingClaimTypeDisplayName "UID" -SameAsIncoming
   8: $emailClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/claims/EmailAddress" -IncomingClaimTypeDisplayName "EmailAddress" -SameAsIncoming
   9: $CNClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/claims/CommonName" -IncomingClaimTypeDisplayName "CommonName" -SameAsIncoming
  10: $FirstNameClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/claims/FirstName" -IncomingClaimTypeDisplayName "FirstName" -SameAsIncoming
  11: $LastNameClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/claims/LastName" -IncomingClaimTypeDisplayName "LastName" -SameAsIncoming
  12:  
  13:  
  14: $realm = "urn:sharepoint:<environment_name>"
  15: $signInURL = "<login url, would be given by federation agent>"
  16: $ap = New-SPTrustedIdentityTokenIssuer -Name "<authentication provider name>" -Description "<description>" -realm $realm -ImportTrustCertificate $cert -ClaimsMappings $upnClaimMap,$emailClaimMap,$CNClaimMap,$FirstNameClaimMap,$LastNameClaimMap -SignInUrl $signInURL -IdentifierClaim $upnClaimMap.InputClaimType
  17:  
  18: $sts = Get-SPSecurityTokenServiceConfig
  19: $sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –minutes 1)
  20: $sts.Update()
  21: iisreset

Lets understand each of above code lines.


$root = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("path to root certificate")
New-SPTrustedRootAuthority -Name "Root" -Certificate $root
 
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("path to certificate provided by federation agent")
New-SPTrustedRootAuthority -Name "<authenticatino provider name>" -Certificate $cert


Above commands import certificates in SharePoint’s trust store. Federation agent always sends a signature with token to SharePoint. For SharePoint to trust that token, the signature should match with available signatures in its trust store. First certificate that we are importing above in SharePoint belongs to your domain name (trust chain). Next certificate belongs to the federation agent.


$upnClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/claims/UID" -IncomingClaimTypeDisplayName "UID" -SameAsIncoming
$emailClaimMap = New-SPClaimTypeMapping -IncomingClaimType "
http://schemas.xmlsoap.org/claims/EmailAddress" -IncomingClaimTypeDisplayName "EmailAddress" -SameAsIncoming
$CNClaimMap = New-SPClaimTypeMapping -IncomingClaimType "
http://schemas.xmlsoap.org/claims/CommonName" -IncomingClaimTypeDisplayName "CommonName" -SameAsIncoming
$FirstNameClaimMap = New-SPClaimTypeMapping -IncomingClaimType "
http://schemas.xmlsoap.org/claims/FirstName" -IncomingClaimTypeDisplayName "FirstName" -SameAsIncoming
$LastNameClaimMap = New-SPClaimTypeMapping -IncomingClaimType "
http://schemas.xmlsoap.org/claims/LastName" -IncomingClaimTypeDisplayName "LastName" -SameAsIncoming


Here we are mapping SharePoint claims with incoming claims in the token sent by federation agent. Total number of claims to be used depends on your requirement. Also the ClaimType format (http://schemas.xmlsoap.org/claims/LastName) depends on your choosing.


$realm = "urn:sharepoint:<environment_name>"
$signInURL = "<login url, would be given by federation agent>"
$ap = New-SPTrustedIdentityTokenIssuer -Name "<authentication provider name>" -Description "<description>" -realm $realm -ImportTrustCertificate $cert -ClaimsMappings $upnClaimMap,$emailClaimMap,$CNClaimMap,$FirstNameClaimMap,$LastNameClaimMap -SignInUrl $signInURL -IdentifierClaim $upnClaimMap.InputClaimType


In above lines, first we are identifying SharePoint as client for federation agent and vice versa. The sing-in URL would be provided by the federation agent. All previous commands were a preparation for the configuration of an authentication provider. With New-SPTrustedIdentityTokenIssuer we are finally implementing it. With this command, we specify all certificates that we have imported, all claims mappings, realm and the sign-in URL. If this final command completed without error, you have setup you custom authentication provider.


To check whether authentication provider is setup run – Get-SPTrustedIdentityTokenIssuer


However there is a great chance that you still can not login to your new site collection created with this authentication provider. You might face the problem where the federation agent sends the token, but SharePoint does not accept it or to put it more accurately – SharePoint authentication goes in a loop. This happens because SharePoint default expiration window for tokens is 10 minutes; whereas most of federation agents create a token with expiration window of just 2 minutes. When SharePoint receives the token from federation agent, it checks the expiration window of the token received. Once it realizes that this token will expire before its own expiry window; it rejects the token and again sends a request to federation agent for new token, and this goes on and on. To fix this problem set SharePoint token expiry window to less than expiry window provided by federation agent. This way SharePoint knows that token is valid for its entire expiry duration. To set the SharePoint token expiry window:


$sts = Get-SPSecurityTokenServiceConfig
$sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –minutes 1)
$sts.Update()
iisreset


With this, you will be able to use your new authentication system.