Viser opslag med etiketten ADFS. Vis alle opslag
Viser opslag med etiketten ADFS. Vis alle opslag

onsdag den 15. januar 2014

Managing CRM 2011 and 2013

I fixed a series of bugs and tested my CRM powershell module against both 2011 and 2013. Enjoy.

PSCRM.zip

Add-CRMRoleMember
Disable-CrmLanguage
Disable-CrmOrganization
Disable-CRMSystemUser
Enable-CrmLanguage
Enable-CrmOrganization
Enable-CRMSystemUser
Get-CrmAvailableLanguage
Get-CrmLanguage
Get-CrmOrganization
Get-CRMRole
Get-CRMSystemUser
Get-CRMSystemUserSettings
Get-CrmUsermappingFile
Import-CrmOrganization
New-CrmConfig
New-CRMCustomerAdminRole
New-CrmOrganization
New-CRMSystemUser
Remove-CrmOrganization
Remove-CRMRole
Remove-CRMRoleMember
Remove-CRMSystemUser
Select-CrmOrganization
Set-CRMSystemUser
Set-CRMSystemUserSettings

mandag den 25. februar 2013

ASP.NET and/or MVC websites and Claims based Authentication

Implementing WIF on a website is pretty straight forward. There are ton’s of guide out there on how to do it …. By doing a bit of magic in web.config you can make any website support claims based authentication. ( even Exchange 2010 and Citrix  )

If you are a developer, implementing WIF on your website is just as easy. You install WIF SDK and run FedUtil.exe who will handle configuring your web.config for you …

But what if you want absolute control over the login process. You often end up, with a mix of stuff in web.config and some in code. So I decided to figure out, what it would take, to support getting a user signed on, without ever touching web.config.

You will need to handle 4 actions. Requesting login, Handle login, Handle sign-out and handling Cleanup. So lets start with requesting login. But before we can do that, we need to have a basic setup of WIF. WIF normally do most of it’s magic though 3-4 modules, that get’s its configuration though web.config, and is saved in a static (shared) variable you can access simply by typing

Dim fam As Microsoft.IdentityModel.Web.WSFederationAuthenticationModule = Microsoft.IdentityModel.Web.FederatedAuthentication.WSFederationAuthenticationModule

But we want to control. To make things simple, we function like this

Public Function GetAuthenticationModule() As WSFederationAuthenticationModule
Dim fam As New WSFederationAuthenticationModule
fam.ServiceConfiguration = New Microsoft.IdentityModel.Configuration.ServiceConfiguration()
' use this, to allow any realm
' fam.ServiceConfiguration.AudienceRestriction.AudienceMode = IdentityModel.Selectors.AudienceUriMode.Never
' Add known Audience's ( Realms )
' This would proberly come from a database or what ever
For Each Realm in my.settings.Realms
Dim AllowedUri = fam.ServiceConfiguration.AudienceRestriction.AllowedAudienceUris.Where(Function(x) x.AbsoluteUri = IDP.TargetRealm).FirstOrDefault()
If AllowedUri Is Nothing Then
fam.ServiceConfiguration.AudienceRestriction.AllowedAudienceUris.Add(New Uri(IDP.TargetRealm))
End If
Next
fam.ServiceConfiguration.IssuerNameRegistry = New CustomTrustedIssuerNameRegistry()

Dim certificate As System.Security.Cryptography.X509Certificates.X509Certificate2 = CustomSecurityTokenServiceConfiguration.Current.EncryptingCertificate
AttachCert(fam.ServiceConfiguration, certificate)
' If you later decide to let WIF set the identity and save a FedAuth cookie, use thise to allow it to work incase you got
' your website hosted in Azure. The reason is Azure's Loadbalencing are using true round robin and doesnt support Sticky sessions.
' So in order to make all websites able to read the cookie, you need to a "common" ground for reading the encrypted token
'Dim sessionTransforms As New List(Of CookieTransform)(New CookieTransform() {New DeflateCookieTransform(), New RsaEncryptionCookieTransform(certificate),
' New RsaSignatureCookieTransform(certificate)})
'Dim sessionHandler As New Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler(sessionTransforms.AsReadOnly())
'fam.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler)
Return fam
End Function

Private Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
Sub AttachCert(configuration As Microsoft.IdentityModel.Configuration.ServiceConfiguration, certificate As System.Security.Cryptography.X509Certificates.X509Certificate2)
configuration.ServiceCertificate = certificate
Dim certificates = New List(Of System.IdentityModel.Tokens.SecurityToken)() From { _
New System.IdentityModel.Tokens.X509SecurityToken(Configuration.ServiceCertificate) _
}
Dim encryptedSecurityTokenHandler = TryCast((From handler In Configuration.SecurityTokenHandlers Where TypeOf handler Is Microsoft.IdentityModel.Tokens.EncryptedSecurityTokenHandler).First(), Microsoft.IdentityModel.Tokens.EncryptedSecurityTokenHandler)
configuration.ServiceTokenResolver = InlineAssignHelper(encryptedSecurityTokenHandler.Configuration.ServiceTokenResolver, System.IdentityModel.Selectors.SecurityTokenResolver.CreateDefaultSecurityTokenResolver(certificates.AsReadOnly(), False))
End Sub

We need to tell WIF the realm(s) we are running under right now, called Audience Uri.
We need to tell WIF what signing certificate's to allow tokens from, called Issuer Name Registry.
CustomTrustedIssuerNameRegistry is a class that will get “fed” the signing certificates when WIF is validating the tokens, and should return a name (any name) if the certificate was allowed. Code for that is further down


Perfect, so now we are ready to create a sign request ( what happens when a user clicks the “login” button or what ever)

Public Function CreateSignInRequestMessage(Issuer As String, Realm As String, Reply As String) As SignInRequestMessage
Dim fam = GetAuthenticationModule()
fam.Issuer = Issuer
fam.Realm = Realm
Dim signInRequest = New SignInRequestMessage(New Uri(fam.Issuer), fam.Realm) With { _
.AuthenticationType = fam.AuthenticationType, _
.Freshness = fam.Freshness, .Reply = Reply
}
Return signInRequest
End Function

So in the code for your “login button” you do something down the line of this


Dim STSLoginPage as string = "https://adfs.wingu.dk/adfs/ls/"
' This webpage, must be in the AllowedAudienceUris
Dim TargetRealm as string = "https://domain.com/MyAwsomeWebapp"
Dim returnURL as string = "https://domain.com/MyAwsomeWebapp/login.aspx"
' or if using MVC
Dim returnURL as string = "https://domain.com/MyAwsomeWebapp/login/signin/"

Dim signInRequest = WIFHelper.CreateSignInRequestMessage(STSLoginPage, TargetRealm, returnURL)
Dim redirURL As String = signInRequest.WriteQueryString()
Response.Redirect(redirURL)

That will kick the user over to the identity provider, and if all goes well, he will then return with a POST to the return URL, where we can now pickup he’s SAML token.
So on the login page (or MVC controller) its now time to read the token, we add a function to our module, than handles that part


Private Function GetSignInResponseMessage() As SignInResponseMessage
Dim ctx = System.Web.HttpContext.Current
Dim req = ctx.Request
Dim message As SignInResponseMessage = WSFederationMessage.CreateFromFormPost(req) 'as SignInResponseMessage
Return message
End Function

Public Function GetWIFPrincipal(ByRef Issuer As String) As Microsoft.IdentityModel.Claims.ClaimsPrincipal 'System.Security.Principal.IPrincipal
Dim fam = GetAuthenticationModule()
Dim message As SignInResponseMessage = GetSignInResponseMessage()
'Dim token As System.IdentityModel.Tokens.SamlSecurityToken = fam.GetSecurityToken(message)
Dim token = fam.GetSecurityToken(message)
If token IsNot Nothing Then
Dim claims As Microsoft.IdentityModel.Claims.ClaimsIdentityCollection = fam.ServiceConfiguration.SecurityTokenHandlers.ValidateToken(token)
Dim principal As System.Security.Principal.IPrincipal = New Microsoft.IdentityModel.Claims.ClaimsPrincipal(claims)
If TypeOf token Is System.IdentityModel.Tokens.SamlSecurityToken Then
Dim t As System.IdentityModel.Tokens.SamlSecurityToken = token
Issuer = t.Assertion.Issuer
ElseIf TypeOf token Is Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken Then
Dim t As Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken = token
Issuer = t.Assertion.Issuer.Value
Else
Throw New Exception("Failed resolving SecurityToken to a known type '" & token.GetType.Name & "'")
End If
Return principal
End If
Return Nothing
End Function

And in the login page/controller you, can now either set the current principal, or parse the claims and sign in the user with formsbased authentication or what ever makes you tick.

Dim Issuer As String = Nothing
Dim Principal As Microsoft.IdentityModel.Claims.ClaimsPrincipal = GetWIFPrincipal(Issuer)
If Principal Is Nothing Then Throw New Exception("Failed parsing sign message to new Principal")
Dim Identity As Microsoft.IdentityModel.Claims.ClaimsIdentity = Principal.Identity
If Identity Is Nothing Then Throw New Exception("Failed parsing sign message to new Principal")
Issuer = Issuer.ToLower

Lastly, to make everything work correctly, we need to make our “login” page support at least 3 of the WS-Federation commands ( I guess that makes “login” page a wrong name then ? ) . So to wrap it all up, you will get something like this

Dim action as string = Request.QueryString(WSFederationConstants.Parameters.Action)
Select Case action
Case WSFederationConstants.Actions.SignIn
' Send user to the identity provider
Dim STSLoginPage As String = "https://adfs.wingu.dk/adfs/ls/"
' This webpage, must be in the AllowedAudienceUris
Dim TargetRealm As String = "https://domain.com/MyAwsomeWebapp"
Dim returnURL As String = "https://domain.com/MyAwsomeWebapp/login.aspx"
' or if using MVC
returnURL = "https://domain.com/MyAwsomeWebapp/login/signin/"
Case WSFederationConstants.Actions.SignOut
Dim requestMessage As SignOutRequestMessage = Nothing
Try
' This will fail, if a "sharepoint" login message
requestMessage = WSFederationMessage.CreateFromUri(Request.Url)
Catch ex As Exception
' ignore
End Try
' Return user to front page
model.RedirectURL = Request.Url.Scheme & "://" & Request.Url.Host & Request.ApplicationPath
If Not requestMessage Is Nothing Then
If Not String.IsNullOrEmpty(requestMessage.Reply) Then
' unless they logged out from another site, then send them back there
model.RedirectURL = requestMessage.Reply
End If
End If
FormsAuthentication.SignOut()
Session.Abandon()

' clear authentication cookie
Dim cookie1 As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, "")
cookie1.Expires = DateTime.Now.AddYears(-1)
Response.Cookies.Add(cookie1)

' clear session cookie
Dim cookie2 As HttpCookie = New HttpCookie("ASP.NET_SessionId", "")
cookie2.Expires = DateTime.Now.AddYears(-1)
Response.Cookies.Add(cookie2)
Case WSFederationConstants.Actions.SignOutCleanup
' Do the same as above, but send an "ok" image back
End Select
And lastly, we need to create class that validates singing certificates. 
Imports Microsoft.IdentityModel.Tokens
Imports System.IdentityModel.Tokens

Public Class CustomTrustedIssuerNameRegistry
Inherits IssuerNameRegistry
'Inherits Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry

Public Sub New()
End Sub
'Public Sub New(customConfiguration As System.Xml.XmlNodeList)
' MyBase.New(customConfiguration)
'End Sub

Public Overrides Function GetWindowsIssuerName() As String
Return MyBase.GetWindowsIssuerName()
End Function

Public Overloads Overrides Function GetIssuerName(securityToken As IdentityModel.Tokens.SecurityToken) As String
Dim x509Token As X509SecurityToken = TryCast(securityToken, X509SecurityToken)
If x509Token IsNot Nothing Then

For Each Thumbprint in My.Settings.AllowedSigningThumbprints
If [String].Equals(x509Token.Certificate.Thumbprint, Thumbprint) Then
Return x509Token.Certificate.SubjectName.Name
End If
Next
End If
Throw New SecurityTokenException("Untrusted issuer.")
End Function

End Class

lørdag den 23. februar 2013

SharePoint/CRM/Exchange and other Claims based websites with Social Sign in

The last week I have been working on a project, regarding combining Claims based authentication and login using Social Providers. In the cloud control panel that I normal work on, I have implemented support for signing in using Office 365, Azure AD, pass-through using Azure ACS, and the mandatory Open ID, Google ID, Windows Live ID, LinkedIn, Facebook, and Twitter. But for reasons I don’t want go into, a need came up, to create a simple STS (Secure Token Service), than would “tie” together one or more identities from social network, and offer those to websites and applications supporting WIF/Claims based authentication.

Why a new STS
If you implemented Social Network, either directly, or indirectly though ACS you probably noticed that if a user sign in using Google ID they will not be the same user, if they later decide to sign in using Facebook. That is relatively easy to “handle” if you wrote the application your self, and Microsoft did a decent job, tying it all up, using the membership provider together with DotNetOpenAuth in MVC 4, but if you don’t want to mess with wrapping up your own customer member ship provider, or if your facilitating WIF in Exchange/CRM/SharePoint/Navision or what ever, wouldn’t it just be awesome if you could just get it all “out of the box” some where. And what if that Service would also allow you to setup your own Identity Providers, so you could implement sign in using Office 365/Azure AD, your own ADFS server, or any other Secure Token Service you might have. You can now

The basic setup
We are still figuring out license models and such, but for now were thinking either a hosted solution, and one where you get the website to run for your self, lets image a hosted setup, and after that you get billed a small amount for each 100k users or something like that. So let’s imaging you want to implement this with Microsoft CRM 2011.

  • First signup for an account, you then get access to a Manage menu. But before you go there, head to CRM and start the “Configure Claims-Based Authentication” wizard
    image
    Type in the URL of the Secure Token Service
    image
    Select a certificate to use, when signing the Claims inside the tokens (this certificate needs to exists on all your CRM servers if you got more than one. It can be a self signed, from your internal CA, or one you bought from a third party
    image
    Go though the rest. Go though the “Configure Internet-Facing Deployment” if you haven't don’t so already, and at the end note the URL to the CRM servers metadata.xml file
  • Go to the STS, click Relays, past in the URL from the “Create new relying part” field, and press Create. By default all Social connectors will be allowed, but if you only want for instance Live ID, select that under Identity Providers, and hit Save.

And that is that. SharePoint how ever doesn’t have these cool metadata.xml files, so configuring that, will take a tiny bit more work, but not to worry, that is why we got PowerShell.

  • Open a PowerShell prompt locally on any of the servers in your farm. And run the following PowerShell Script . ( there is a link on the Relaying Party page too ) Make sure you modify the variables at the top to fit your installation
  • Head to the STS, click management, type a meaningful name into “Create new relying part” field, and press Create
    If you went with the defaults in the script, SharePoint should be sending a reply URL, so we can leave PassiveRequestorURI blank.
    SharePoint (default) doesn’t want the claims to be encrypted so we don’t need to add a certificate.
    Under “Audience Uris” add each of the URN’s that was mapped for each of the websites, show in the end of the script.

And you are all done.

Adding Azure AD, office 365, Azure ACS or an ADFS server
That’s all nice, but what about all your local users, or all your Office 365 users ?
Not a problem, head to the “Providers” page, and type in the URL to the metadata file.

If you are using Office 365 or Azure AD the URL will look something like this
https://accounts.accesscontrol.windows.net/<tenant>.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml

If your using Microsoft ACS, your URL will look something like this
https://<yourname>.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml
(note, someone at Microsoft fucked this up, so it doesn’t sent a Signing Certificate, but it does doing Office 365 … it’s the same certificate thou, so is easy to grab )

If your using ADFS, the URL will look something like
https://adfs.wingu.dk/FederationMetadata/2007-06/federationmetadata.xml

If your using ACS or ADFS, you don’t need to do anything else than going to the ADFS Server/Azure ACS/Azure AD website and add https://STS/FederationMetadata.xml and it will all configure it self. If how ever your using Office 365, you need to add a ServicePrincipal representing the STS. At the top of the Provider screen is a link to a powershell scrip that will set this up. Once the script is run, past in the “spn:<guid>” from the output of the script into the Target Realm field of the new Provider.

Lastly, go back to your Relying Party, and you can now also select your new Office 365 or what ever Provider you added, and let your users sign in using that

SharePoint 2010 and claims based authentication made a little bit easier

updated 05/03-2013: Added support for extracting root cert from signing certificate
So you have ADFS 2.0 installed. Or your reading some guide about how to configure SharePoint to allow login in using Office 365 or Azure AD or any other kind of Secure Token Service. And 99,9% of them will tell you to copy 1 or more certificates, and run a lot of weird PowerShell command, and it all ends up with you being able to setup some awesome new login page here

image

Well, fear not. If your STS support generating a FederationMetadata.xml URL, you can now use this PowerShell Script to quickly setup your SPTrustedIdentityTokenIssuer . The script can also setup Uri mappings and configure the websites, but I do not recommend using that part in other than development/test environments. Make sure to modify the variables at the top.

I’ve updated the script. If your STS was using a self issued certificate, or a certificate from an internal CA, it wouldn’t be trusted by SharePoint, so added a bit of code to traverse the certificate chain, and then add the root certificate to the Trusted store and also add the root to the list of trusted certificates inside SharePoint

# URL for ADFS / ACS / Office 365 / SimpleSTS / Wingu Cloud ControlPanel / what ever

# $metadataurl = 'https://adfs.wingu.dk/FederationMetadata/2007-06/federationmetadata.xml' # ADFS
# $metadataurl = 'https://accounts.accesscontrol.windows.net/skadefro.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml' # Azure AD
# $metadataurl = 'https://skadefro.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml' # Azure ACS - Wont work, apperently the guy who made this, forgot to add the signing certificat .. :-(
# $metadataurl = 'https://simplests.wingu.dk/FederationMetadata.xml' # Simple STS
# $metadataurl = 'http://admin.wingu.dk/sts2/FederationMetadata/2007-06/federationmetadata.xml' # Wingu Cloud Control Panel
$metadataurl = 'https://simplests.wingu.dk/FederationMetadata.xml'


# This should really be NameID, but often people will use emails or UPN. choose what fits your needs
$IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
# What claims do you want mapped. All will be exposed in the ClaimsToken, but what will show up in the people picker ?
$mapClaims = @('UPN', 'Role')

# Default realm. If you only have 1 website, you can add that here, but more correctly would be adding
# Each URI accessible on your farm, mapping it to a URN
# If your using Wingu Cloud Control Panal or SimpleSTS, urn:sps will automaticly be converte to a SharePoint signin URI
# urn:sps:http://spfarm01.cloudapp.net becomes http://spfarm01.cloudapp.net/_trust/
# if not, just use the full uri, like http://spfarm01.cloudapp.net/_trust/
# if you want several sharepoint sites to allow the user access without prompting for login each time,
# use one shared urn (not URI) for all those sites. There are certain restrictions, on how/where you can do that
$defaultrealm = 'urn:sps:https://sharepoint.domain.com'

# Be carefull with this. Not all STS' understand/support's this, and often the above is a simpler solution
# set this to true, will go though the list of sites in the farm and add an "urn:sps:URI" entry for each site
$autoGenerateProviderRealms = $false

# Dont, Dont, DONT ... D-O-N-T, use this
# This will add Windows and ALL identityProviders to all WebApplication's (except Central Admin) for the "default" zone.
$autoAddSTS = $false

$stsname = 'SimpleSTS'
$name = $stsname
$realm = $null
$stsd = $null
$asd = $null

$snapin = Get-PSSnapin | where {$_.name -eq 'Microsoft.SharePoint.PowerShell'}
if($snapin -eq $null){ Add-PSSnapin Microsoft.SharePoint.PowerShell }


function Get-medadata ($metadataurl) {
[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.IdentityModel")
$STSReader = New-Object Microsoft.IdentityModel.Protocols.WSFederation.Metadata.MetadataSerializer
$req = [System.Net.WebRequest]::Create($metadataurl)
$xmlreader = [System.Xml.XmlReader]::Create($req.GetResponse().GetResponseStream())
$metadata = $STSReader.ReadMetadata([System.Xml.XmlReader]$xmlreader)
$metadata
}

function Get-STS ($metadata) {
foreach($RoleDescriptor in $metadata.RoleDescriptors){
if($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.SecurityTokenServiceDescriptor'){
# metadata have a STS
$stsd = $RoleDescriptor
} elseif($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.ApplicationServiceDescriptor'){
# metadata have a Relying Party
$asd = $RoleDescriptor
}
}
$stsd
}
function Get-RelyingParty ($metadata) {
foreach($RoleDescriptor in $metadata.RoleDescriptors){
if($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.SecurityTokenServiceDescriptor'){
# metadata have a STS
$stsd = $RoleDescriptor
} elseif($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.ApplicationServiceDescriptor'){
# metadata have a Relying Party
$asd = $RoleDescriptor
}
}
$asd
}

function Get-GetCertificate ($stsd, $certificatetype) {
if( ($certificatetype -ne 'Signing') -and ($certificatetype -ne 'Encryption')){
Write-Error "CertificateType should be 'Signing' or 'Encryption'"
return
}
$has40 = [Reflection.Assembly]::LoadWithPartialName("System.IdentityModel")

$SigningCertificate = $null
foreach($key in $stsd.Keys){
if($key.Use -eq $certificatetype){
if($has40.GetName().Version.Major -eq 4){
#if .net 4.0 is install we can just do this, when System.IdentityModel v4.0.30319 is loaded
$bytes = $key.Keyinfo.GetX509RawData()
} else {
#but default, sharepoint 2010 only have version v2 loaded so, lets do it, the ugly way
$str = $key.Keyinfo.ToString()
$str = $str.Substring( $str.IndexOf('RawData = ') + 10)
$str = $str.Substring(0, $str.IndexOf(')'))

$bytes = ([system.Text.Encoding]::UTF8).GetBytes($str)
}
$SigningCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]([byte[]]$bytes)
}
}
$SigningCertificate
}

Function Ensure-SPProvider($name, $defaultrealm, $SigningCertificate, $SigninURL, $claims, $IdentifierClaim, $mapClaims){
$certificatename = "$($name) Signing Certificate"
$cert = get-SPTrustedRootAuthority | ?{($_.Certificate.Thumbprint -eq $SigningCertificate.Thumbprint) -or ($_.Name -eq $certificatename)}
if(!$cert){
Write-Host "Adding $($SigningCertificate.Thumbprint) as a Trust Certificate"
$cert = New-SPTrustedRootAuthority -name $certificatename -Certificate $SigningCertificate
} else {
$cert | Set-SPTrustedRootAuthority -Certificate $SigningCertificate
}
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
$chain.Build($SigningCertificate)
$SigningCertificateRoot = $chain.ChainElements[$chain.ChainElements.Count -1].Certificate

# Ensure Root Cert has been added to Trusted Store
$store = get-item cert:\LocalMachine\Root
$store.Open("ReadWrite")
$store.Add($SigningCertificateRoot )
$store.Close()

# And now, add it to SharePoint too
$rootcert = get-SPTrustedRootAuthority | ?{($_.Certificate.Thumbprint -eq $SigningCertificateRoot.Thumbprint)}
if(!$rootcert){
Write-Host "Adding $($SigningCertificateRoot.Thumbprint) as a Trust Certificate"
$rootcert = New-SPTrustedRootAuthority -name $SigningCertificateRoot.Subject -Certificate $SigningCertificateRoot
}

$IDClaim = $null
$claimsmappings = @()
foreach($claim in $claims) {
# http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name is reserved inside SharePoint (??? Why ?... really, WTF !!!!)
# http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid is only used in SharePoint 2013 ( not tested yet )
# its SharePoints internal STS job to handle the requiered fields
# http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod
# http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant

if($claim.ClaimType -eq 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'){
$claimsmappings += New-SPClaimTypeMapping $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -LocalClaimType 'http://simplests.wingu.dk/identity/claims/name'
} elseif($claim.ClaimType -eq 'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod'){
# Skip
} elseif($claim.ClaimType -eq 'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant'){
# Skip
} elseif($claim.ClaimType -eq 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier'){
$claimsmappings += New-SPClaimTypeMapping $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -LocalClaimType 'http://simplests.wingu.dk/identity/claims/nameidentifier'
} else {
$claimsmappings += New-SPClaimTypeMapping -IncomingClaimType $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -SameAsIncoming
}
if($IdentifierClaim -eq $claim.ClaimType){
$IDClaim = $claim.ClaimType
}
}

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $name}
if(!$ap){
$ap = New-SPTrustedIdentityTokenIssuer -Name $name -Description $name -Realm $defaultrealm -ImportTrustCertificate $SigningCertificate -ClaimsMappings $claimsmappings -SignInUrl $SigninURL -IdentifierClaim $IDClaim
}
# Ensure all claim mappins are there
#foreach($claim in $claims) {
# $hasClaim = $ap.ClaimTypes | ?{$_ -eq $claim.ClaimType}
# if(!$hasClaim) {
# Write-Host "adding ClaimType $($claim.DisplayTag) to $name"
# $ap.ClaimTypes.Add($claim.ClaimType)
# }
#}

#$ap.Update()
#Add-SPClaimTypeMapping -Identity $claim -TrustedIdentityTokenIssuer $ap
#$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $name}

# if you only have 1 sharepoint site, and dont want to "bother" setting up
# Reply URL on your STS ( adfs - AD FS 2.0 Management -> Trust Releationships ->
# Relying Party Trusts -> Properties on RP Go to "Endpoints" tab -> WS-Federation Passive Endpoint
# Or SimpleSTS -> Management -> Relying Party -> Manage -> PassiveRequestorURI
# you can just override the $ap.DefaultProviderRealm
# but the correct way would be to list each unique URI with an associated URN in $ap.ProviderRealms
$ap.DefaultProviderRealm = $defaultrealm

$ap.ProviderUri = $SigninURL
#$ap.Name = $name
#$ap.DisplayName = $name


# If WReply is not set, sharepoint will not add return URL when sending user to login page
# if DefaultProviderRealm/$ap.ProviderRealms URN is not listed with a Return URL in the STS
# the STS will not know where to send the user. What's "correct" ? dont know.
# if your paranoid, leacing WReply $false, using URN's all the places, and keeping Passive Federation
# URL's in you STS would proberly be best, but let's ensure we can have both unique URI's, prober return URI's
# and unique'nes by using $ap.ProviderRealms
$ap.UseWReplyParameter = $true

# HomeRealm tells the STS how the user want to to login instead of prompting.
# ADFS will ask and save a cookie, for 3 months, most custom solutions, will prompt each time
# for instance SimpleSTS will allow you to choose each time from a list of all allowed providers
# Sharepoint will NEVER know what those homerealms could be.
# SharePoint's internet STS will normaly "strip" off HomeRealm ( WHR= ) but with the Juni RU this new
# parameter was added to allow adding HomeRealm in custom code (modules or custom login page) without loosing the WHR parameter
# http://blogs.msdn.com/b/chriskeyser/archive/2011/10/02/sharepoint-2010-claims-and-home-realm-discover-passing-whr-on-the-url-to-sharepoint.aspx
try {
$ap.UseWHomeRealmParameter = $true
} catch {
Write-Warning "SharePoint is not update, and wont allow setting UseWHomeRealmParameter, make sure you use uri:sp: as realms/AudienceURIs, or set PassiveRequestorURI to [SharePointURI]/_trust/"
$Error.Clear()
}
$ap.Update()

}
$metadata = Get-medadata $metadataurl
$stsrealm = $metadata.EntityId.Id
$stsd = Get-STS $metadata
#$asd = Get-RelyingParty $metadata
$SigningCertificate = Get-GetCertificate $stsd 'Signing'
#$encryptionCertificate = Get-GetCertificate $asd 'Encryption'
$claims = $stsd.ClaimTypesOffered

foreach($PassiveRequestorEndpoint in $stsd.PassiveRequestorEndpoints){
$SigninURL = $PassiveRequestorEndpoint.Uri.AbsoluteUri
}

Ensure-SPProvider $stsname $defaultrealm $SigningCertificate $SigninURL $claims $IdentifierClaim $mapClaims

if($autoGenerateProviderRealms -eq $true){
# We could use Get-SPWebApplication, and then Get-SPAlternateURL on each site
# we could also filter out only "external" sites, etc ....

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $stsname}
#$ap.ProviderRealms.Clear()
foreach($wa in Get-SPWebApplication){
$pr = $ap.ProviderRealms.keys | where {$_.AbsoluteUri -eq $wa.Url}
if(!$pr){ $pr = $ap.ProviderRealms.Add([uri]($wa.Url), "urn:sps:$($wa.Url)") }
}
$ap.Update()
}
if($autoAddSTS -eq $true){
$windowsap = New-SPAuthenticationProvider
#$aps = Get-SPAuthenticationProvider -Zone "Default" -WebApplication $wa
$aps = @()
$aps += $windowsap
foreach($ap in Get-SPTrustedIdentityTokenIssuer){
$aps += $ap
}
foreach($wa in Get-SPWebApplication){
Set-SPWebApplication -Identity $wa -Zone "Default" -AuthenticationProvider $aps # -Force
}
}

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $stsname}
Write-Host "ensure '$($defaultrealm) and each 'Value' is added to the Relying Party in the STS"
$ap.ProviderRealms

onsdag den 6. februar 2013

Requesting email when using Windows LiveID OAuth2

didn’t take long to figure out, but just in case. If you are using DotNetOpenAuth and are using the ApplicationBlock.WindowsLiveGraph to get the identity of the user, you will not get the email address of the user. You can how ever request it, by sending wl.emails in the Scope:

Dim WindowsLiveIDTokenManager As New SQLTokenManager(WindowsLiveIDConsumerKey, WindowsLiveIDConsumerSecret)
Dim WindowsLiveClient As New DotNetOpenAuth.ApplicationBlock.WindowsLiveClient() With { _
    .ClientIdentifier = WindowsLiveIDConsumerKey, _
    .ClientSecret = WindowsLiveIDConsumerSecret _
}
Dim authUrl = New Uri(Request.Url.Scheme + "://" + Request.Url.Authority + "/sts2/login.aspx")
WindowsLiveClient.RequestUserAuthorization(scope:=New String() {ApplicationBlock.WindowsLiveClient.Scopes.Basic, "wl.emails"}, returnTo:=authUrl)

Next, when validating the access token, don’t use the built in JSON Deserialize function, but use your own

 

If authorization IsNot Nothing Then
    Dim request = System.Net.WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken))
    Using response = request.GetResponse()
        Dim JSON As String = ""
        Using responseStream = response.GetResponseStream()
            Dim reader As New IO.StreamReader(responseStream, Encoding.UTF8)
            JSON = reader.ReadToEnd()
        End Using

        Dim jss As New Script.Serialization.JavaScriptSerializer
        Dim LiveIDUser As LiveIDGraph = jss.Deserialize(JSON, GetType(LiveIDGraph))    End Using
End If

 

And this is how your LiveIDGraph would look like

Imports System.Runtime.Serialization

<DataContract(Namespace:="")>
Public Class LiveIDGraph

    <DataMember> Public id As String
    <DataMember> Public name As String
    <DataMember> Public first_name As String
    <DataMember> Public last_name As String
    <DataMember> Public link As String
    <DataMember> Public gender As String
    <DataMember> Public emails As LiveIDEmails
    <DataMember> Public locale As String
    <DataMember> Public updated_time As DateTime

End Class

<DataContract(Namespace:="")>
Public Class LiveIDEmails
    <DataMember> Public preferred As String
    <DataMember> Public account As String
    <DataMember> Public personal As String
    <DataMember> Public business As String
End Class

mandag den 18. juni 2012

Remote Desktop and Claimsbased authentication

I have had a wet dream for a long time, about implementing WIF/Claimsbased authentication into Windows Credential Provider/Remote Desktop. I don’t really care weather it could be though the RDP Website and/or directly on the Windows Server.

If we want to implement claims based authentication in corporation with remote desktop we need to consider what scenario this makes sense for, and how the logon process should be. Doing passive authentication in a browser, the user gets redirected to an identity provider and validated, has a SAML token issued and posted back to the website. Validation at the Identity Provider could also involve redirecting the user to yet another Identity provider (Microsoft Azure ACS, another ADFS 2.0 server, Google ID, Facebook and such) and the all this without the original website knowing anything about this, all it cares about is getting a SAML token from its trusted Identity Provider.

Doing Active Federation, lets say, from a Windows Application, we (could) ask the user how he wants to be validated and then though Kerberos, Certificates or Username/Password send the users credentials to the Identity Provider on behalf of the user and get’s back a SAML token. If the user want to logon though Windows Live ID in this scenario, we first need to ask the user for he's username/password ( this is where all alarm bells should go off for most security aware users ) and send this to login.live.com and by some kind of magic we get back a SAML token. We then ask out local Identity provider to Authorize us, using the SAML token from Windows Live ID and get back a SAML token and can continue the login process.

First of all, asking a user to type in a username and password for Facebook/windows Live ID/what ever on a “proprietary login page” is not good practice. Next, I doubt Microsoft/Facebook/whatever is allowing validating username and passwords though any kind of API, so the above will not work in any case.

So why is this even interesting, if its wrong ? Imaging the most common setup. Company A and Company B wants to collaborate and allow each other users access to certain resources. Instead of creating an Active Directory trust, Company A and B both install ADFS 2.0 and created a mutual trust between these. Now they can both add users to each others SharePoint 2010 and other Claims aware web applications. But what if they want to grant access to Microsoft CRM 2011, create Exchange mailbox's, allow access to Axapta 2009/2012 or use any other kind of application that rely on a Windows user in the Active Directory, then they need to map the User Principal name to locally created Active Directory users. How you do that, is beyond the scope of this post, but its doable and used many places.

Now image you want to allow users from Company A to access Company B’s Citrix XenApp or Remote Desktop servers. So User1 from Company A also have a User account in Company B, but he doesn’t know the password for that account. To give the whole Single Sing-on experience all he needs to know is the username and password to he’s own AD account in Company A.

You might think that implementing Claimsbased authentication on Remote Desktop WebApp is easy, and to be honest, it is. it just doesn’t work. The reason is, when you login to RDWeb the webpage loads an instance of your locally installed Remote Desktop client, though JavaScript/ActiveX and feeds it, the username and password you logged in with. So after implementing Claimsbased authentication in enabling it to use the c2wts service ( Claims to Windows Token Service ) you WILL get the correct list of application, but when ever you launch any of those, you will be prompted to login with a real windows username and password, and the whole concept falls apart. See this post

If you rely on Citrix XenApp you could implement the solution explained here, but that will not work with Remote Desktop. The solution explained there, will not work for user accessing the solution with PNAgent installed locally either ( PDA, Tablets, Thin Clients or what ever ) so an alternative solution will need to rely on replacing the Credential Provider ( called Gina pre windows vista ).

I came across this blog post and I really really wish I was better a coding C++ so I could create this my self. I can do hello world and maybe write to a text file, but this is just to much for my skillset. Google is not much help here, but you will probably come across www.pgina.org at some point.

This will not be completely what I wanted, but at least it’s a few steps in the right direction. Pgina is a cool, yet in some ways limited implementation of a Gina/Credential Provider that send events back to a Service written in .NET 4.0, you can then develop plugins that gets loaded into this service and react/modify things doing the login process. It come bundled with tons of cute add-ons that can validate users though LDAP/Radius/SQL or even IMAP/POP3 . When I say it is limited, I do that, from the perspective that it could have been nice if they had implemented support for asking for more than just username and password. a 3rd field for a passcode to do RSA Token or SMS 2 factor validation would have been a very nice touch, but for now lets just focus on Claimsbased authentication.

So just to test my theory I installed Pgina on a server and wrote a simple add-on to Pgina, that would take what ever the user types in, validate it against and Identity Provider, find the user based on the UPN claim in the local Active Directory and then log the user on.

image

Doing login, no matter what, it all have to end up with win logon getting a valid username and password. But in a world of claims based authentication we don’t have the password. God knows how Citrix manage to get a user logged on purely based on a Kerberos Ticket, and I would love to see this implemented in Pgina too, but a even better solution would be if someone with more brains than me, could write an Authentication Package as explained by Steve Syfuhs in he's blog post. But for now, we focus on the scenario where a user from Company A logs on to a Server inside Company B and the user have an account in the local AD with same UPN.
What I do here is validate what ever the user types in,
1) by asking for a SAML token from the remote Identity Provider.
2) If I get a token back, I extract the User Principal name and search the local Active Directory for such an user.
3) I then validate that the password the user typed is also the password the local Active Directory account, and if login fails, I reset the password and set the login password to this.

Since the context the login process run as, does not have permission to look up in the local AD and/or reset passwords, we also need to tell the PGina addon what username and password to use when talking to AD

image

Finally, since RDP will try to Negotiate security (the popup for credentials before you are connected) and we want PGina to handle this, you need to open Remote Desktop Session Host Configuration and set it to RDP Security Layer

image

And voila, we just logged on to Remote Desktop using Claims based authentication.

mandag den 11. juni 2012

Citrix XenApp and ADFS 2.0 / Claims based authentication

Updated 12-06: forgot to add LDAP service SPN’s in PowerShell script.
This has been one of my little pet project for a long time. I knew I would get a few issues but I sure didn’t expect it to take more than 6 months to get working, but now things are starting to look bright.

So XenApp supports Claims based authentication, it does this by facilitating Kerberos authentication on the website and by some stuff I still don’t quite understand (several people have been mentioning Protocol Transition ) it ends up spawning a desktop/application on the XenApp server as the user. Several layers are part of this and several things can go wrong, so ill do a quick “how to” based on my initial findings.

Step one – Active Directory Federation Service
Get ADFS 2.0 or some other Secure Token Service Provider up and running. For this setup I will be assuming we use ADFS 2.0.
Next get ADFS 1.1 up and running. Its part of Windows Server 2008 R2
We need to configure ADFS 2.0 to support issuing Tokens to ADFS 1.1 .
We do that by first configuring a few Claims types, open the management console and go to Services –> Claim Description and add a new Claim Description.
Display name: AD FS 1.x UPN
Claim type: http://schemas.xmlsoap.org/claims/UPN
Description: The UPN of the user when interoperating with AD FS 1.1 or ADFS 1.0

image

Next add your ADFS 1.x server as a Relying Party on the ADFS 2.0 server. Go to Trust Relationships –> Relying Party Trusts and add a new Relying Party Trust
Choose to manually setup the Relying party, Choose AD FS 1.0 and 1.1 profile.
type path to your 1.X server ( for instance https://adfs11.domain.com/adfs/ls/ )
While troubleshooting I also added https://adfs11.domain.com/adfs/ but I am not sure its needed

Once done, setup Claim Rules for the new Relying Party. You want to at least send Name ID, UPN, Authentication method and Authentication time stamp.
image

image

image

image

Perfect, now head to your ADFS 1.x server, open Server Manager –> Roles –> ADFS –> Federation Service –> Trust Policy –> My Organization –> Account Store –> Active Directory. Right click it and choose disable. ( while testing it can be helpful to enable this and make sure everything works, while implementing ADFS on the Citrix site )
open Server Manager –> Roles –> ADFS –> Federation Service –> Trust Policy –> Partner Organizations –> Account Partners, and Add a new partner
Federation Service URI: http://adfs.wingu.dk/adfs/services/trust
Federation Service Endpoint URL: https://adfs.wingu.dk/adfs/ls/
(be very aware … Slash / in the end of URL, but not URI … )
Link to Token Signing Certificate on the ADFS 2.0 server
Choose “Federated Web SSO” and not “Federated Web SSO with Forest Trust”
Select “UPN Claim”, and then add all the domains you will be using for UPN’s.

Step two – Setup Citrix Web Interface
Citrix only supports using ADFS on 32 bit OS, so install Windows Server 2008 in 32bit version. Install Secure Gateway and Web Interface 5.4 or what ever version is the newest.
Open Server Manager and add Active Federation Service Role and choose to install “Windows Token-based Agent”
Open Server Manager –> Roles –> Web Server (IIS) –> Internet Information Services, Select [your server] and in the Feature View pane, choose “Federation Service URL” and type in “https://adfs10.domain.com/adfs/fs/federationserverservice.asmx”
Open Services and make sure “AD FS Web Agent Authentication Services” is runningimage
Setup you Secure Gateway like normal, and then configure the Web Interface, Open “Citrix Web Interface Management” –> XenApp Web Sites, Create Site.
Choose “at Microsoft AD FS account partner” and enter return URL
https://xenapp.domain.com/Citrix/XenApp
Note, no / in the end
Once done, setup your site like normal, defining farm and so on.

Step 3, Add XenApp Web Interface as Relying Party on ADFS 1.x server
Open Server Manager –> Roles –> ADFS –> Federation Service –> Trust Policy –> My Organization –> Applications –> Add new application
Choose Windows NT Token-based Application
Give it a name, and add the return URL from XenApp Web Interface
https://xenapp.domain.com/Citrix/XenApp
Note, no / in the end
Choose UPN, and choose to enable the application.

Step 4, setting up Kerberos Delegation
First, make sure IIS is working properly on your XML Service machines. ( see http://support.citrix.com/article/CTX130480 )
This is the part that always goes wrong. Lets step back a little and see what is actually happening here.
A user hits https://xenapp.domain.com/Citrix/XenApp and is not authenticated. XenApp will not be handling authentication but leaves it to the Web Server. Web Server looks for a cookie on the client machine with a SAML token, if the user does not have it, it redirects the user to the Federation Service.
The ADFS 1.x service (who should have Active Directory disabled) forwards the user to its Federation Partner, the ADFS 2.0 server. The user gets authenticated and a SAML token gets issued and posted back to ADFS 1.x. It then issues a new Token and that gets posted back to the Citrix Website. This gets saved in a cookie in the users browser and ifssvc ( AD FS Web Agent Authentication Services ) now created an iPrincipal representing the user based on the UPN and sets the authenticated user to be this Principal. The Citrix Web Application now see the users as authenticated though Kerberos and does it’s “magic”. The Web App needs to talk to the XML service on one of the Citrix Servers, on behalf of the user enumerate a list of applications and desktops. Since the Principal is restricted to only be used locally, we need tell Active Directory that this server can “delegate” Kerberos tickets to other servers. We do that from Active Directory Users and Computers, find the Computer account of the WI server and go to the “Delegation” tab. When giving an (user or computer) account permission to delegate on behalf of another user, we can allow it to any computer (unconstrained delegation) or we can specify we will only allow this to specific services (run by a computer or user account) this is called Constrained Delegation. The Kerberos ticked created by the AD FS Web Agent Authentication Services is only allowed to be delegated onwards by means of Constrained Delegation, so we select that. Several documents on the internet will tell you to choose “Kerberos only” here, but since Citrix uses Kerberos Protocol Transition later in the process we need to select “Any protocol” here

image
Its important that there is an delegation for HTTP to the all XML Services, HOST will not be enough.
If everything worked, when a user logs on to the web interface they should now get a list of applications and desktops, but we are not done yet. When the user, for instance, launch a Desktop the user will now be logged on to the XenApp server with a Restricted Token and we therefor need to allow each Citrix XenApp server permission to Delegate to each service. As part of the Logon process, we at least need permission to delegate to the Active Directory Servers and what ever File Server is hosting the Profiles (if you use Roaming Profiles or Folder Redirection )

So, for every Citrix XenApp Server, you need to Delegate the following.
For every Domain Control, add delegation to Service CIFS and LDAP.
For your file server(s) , add delegation to Service CIFS
(not sure about this one, but just to be safe) For the SQL server or account running the SQL service, hosting your Citrix Store Database, add delegation to Service MSSQLSvc.
Lastly, the Citrix Servers need permission to talk to each other and it self, so add delegation to Service HOST, for every XenApp server, including it self.
Again, several documents say you need to delegate constrained delegation using Kerberos only. I have seen it working, but some times it is just not enough, so setting this to any protocol at least while testing should eliminate a few errors.

image

If you have a lot of servers, it might be worth scripting this. This is a part of the script I have been using while building a Proof of Concept environment. You can modify this to fit what ever yours look like, just do this by hand first, to make sure everything works, then you can modify this to generate something similar.

Import-Module 'activedirectory'

#Locate domain I am running in and choose a prefered domain controller

$ADInfo = Get-ADDomain
$DCprefix = "," + $ADInfo.distinguishedName.ToString()
$RandomDC = Get-ADDomainController
$PreferedDC = $RandomDC.HostName
$domainname = $RandomDC.Domain

Write
-Host -ForegroundColor Green "I am running in domain $domainname and will use $PreferedDC as Prefered Domain Controller"


# List of Citrix XenApp Servers.
#
Its important we get an HTTP entry for each XML Service, to the Web Interface, if its missing add on first, with somethign like
#
SetSPN -a HTTP/xentest01.int.wingu.dk xentest01
$XenAppServers = @('XEN01$', 'XEN02$', 'XEN03$', 'XEN04$', 'XEN05$', 'XEN12$', 'XEN13$', 'XENTEST01$', 'XENTEST02$')


# List of Xitrix XenApp Web Interface Servers
$XenAppWIServers = @('XENGW01$', 'XENGW02$')

# List of File Servers
$FileServers = @('FS01$')

# List of SQL Servers. IF SQL is running as a Domain account, type the name of the Account instead.
$SQLAccounts = @('sqlacct','SQLEXP01$')

# List of Microsoft Application Virtualization Servers ( AppV / SoftGrid )
$AppVServers = @('APPV01$','APPV02$')

# Any other servers or Service Accounts, you might just want to bulk import host for.
#
For now, we just copy everything.
$OtherServers = @('provacct', 'mail$', 'NAVI01$','NAVI01_NAV601_NAVI01', 'NAVI01_NAV602_NAVI01' )


# Computer Account - Any Protocol
$WORKSTATION_TRUST_ACCOUNT = 4096
$TRUSTED_TO_AUTH_FOR_DELEGATION = 16777216
$userAccountControl = $WORKSTATION_TRUST_ACCOUNT + $TRUSTED_TO_AUTH_FOR_DELEGATION


$delegates= @()
Write
-Host "***************************************************************"
Write
-Host "* Create delegates list for Citrix WebInterface servers"
Write
-Host "***************************************************************"
foreach($server in $XenAppServers){
$ADServer = Get-ADObject -Filter {SamAccountName -eq $server} -Properties @('servicePrincipalName') -Server $preferedDC
$servicePrincipalNames = $ADServer | Select -ExpandProperty servicePrincipalName
foreach($servicePrincipalName in $servicePrincipalNames){
if(($servicePrincipalName.ToLower() -like 'host*') -or ($servicePrincipalName.ToLower() -like 'http*')){
$delegates += $servicePrincipalName
}
}

}

foreach($server in $XenAppWIServers){
$ADServer = Get-ADObject -Filter {SamAccountName -eq $server} -Properties @('servicePrincipalName') -Server $preferedDC
$servicePrincipalNames = $ADServer | Select -ExpandProperty servicePrincipalName
foreach($servicePrincipalName in $servicePrincipalNames){
if(($servicePrincipalName.ToLower() -like 'host*') -or ($servicePrincipalName.ToLower() -like 'http*')){
$delegates += $servicePrincipalName
}
}

}

foreach($del in $delegates){ Write-Host $del }

foreach($server in $XenAppWIServers){
Write
-Host "Updating msDS-AllowedToDelegateTo and userAccountControl on $server"
$ADServer = Get-ADObject -Filter {SamAccountName -eq $server} -Properties @('msDS-AllowedToDelegateTo','userAccountControl') -Server $preferedDC
if($ADServer.userAccountControl -ne 16781312){
Write
-Warning "Updating $server to Trust for delegation with any protocol. Please restart it."
$ADServer | Set-ADObject -Replace @{"userAccountControl"=$userAccountControl} -Server $preferedDC
}

$ADServer | Set-ADObject -Clear "msDS-AllowedToDelegateTo" -Server $preferedDC
# For some reason, adding it all in one go, sometimes fails, so adding each entry one by one
foreach($del in $delegates){
$ADServer | Set-ADObject -add @{"msDS-AllowedToDelegateTo"="$del"} -Server $preferedDC
}
}

Write
-Host "***************************************************************"
Write
-Host "* Adding cifs/ldap and SQL to delegates list for Citrix servers"
Write
-Host "***************************************************************"

foreach($server in $SQLAccounts){
$ADServer = Get-ADObject -Filter {SamAccountName -eq $server} -Properties @('servicePrincipalName') -Server $preferedDC
$servicePrincipalNames = $ADServer | Select -ExpandProperty servicePrincipalName
foreach($servicePrincipalName in $servicePrincipalNames){
if( ($servicePrincipalName.ToLower() -like 'mssqlsvc*') -or ($servicePrincipalName.ToLower() -like 'host*') ){
$delegates += $servicePrincipalName
}
}
}

foreach($server in $ADInfo.ReplicaDirectoryServers){
$DC = Get-ADDomainController $server -Server $preferedDC
$SamAccountName = ($DC.Name + '$')
$ADServer = Get-ADObject -Filter {SamAccountName -eq $SamAccountName} -Properties @('servicePrincipalName') -Server $preferedDC
$servicePrincipalNames = $ADServer | Select -ExpandProperty servicePrincipalName
foreach($servicePrincipalName in $servicePrincipalNames){
if(($servicePrincipalName.ToLower() -like 'dfsr-*') -or ($servicePrincipalName.ToLower() -like 'ldap*')) {
$delegates += $servicePrincipalName
}
}

# CIFS services is not listed in servicePrincipalName, so add those manually
$delegates += ("CIFS/" + $DC.Name)
$delegates += ("CIFS/" + $DC.Name + "/" + $ADInfo.NetBIOSName)

$delegates += ("CIFS/" + $server)
$delegates += ("CIFS/" + $server + "/" + $ADInfo.NetBIOSName)
$delegates += ("CIFS/" + $server + "/" + $RandomDC.Domain)

# Not sure if this is needed, but i see Kerberos errors about it, when Kerberos logging is enabled
$delegates += ("ProtectedStorage/" + $DC.Name)
$delegates += ("ProtectedStorage/" + $DC.Name + "/" + $ADInfo.NetBIOSName)

$delegates += ("ProtectedStorage/" + $server)
$delegates += ("ProtectedStorage/" + $server + "/" + $ADInfo.NetBIOSName)
$delegates += ("ProtectedStorage/" + $server + "/" + $RandomDC.Domain)
}



foreach($server in $FileServers){
$ADServer = Get-ADObject -Filter {SamAccountName -eq $server} -Properties @('servicePrincipalName') -Server $preferedDC
$servicePrincipalNames = $ADServer | Select -ExpandProperty servicePrincipalName
foreach($servicePrincipalName in $servicePrincipalNames){
if($servicePrincipalName.ToLower() -like 'dfsr-*') {
$delegates += $servicePrincipalName
}
}
$delegates += ("CIFS/" + $ADServer.Name)
$delegates += ("CIFS/" + $ADServer.Name + "." + $RandomDC.Domain)
}

foreach($server in $AppVServers){
$ADServer = Get-ADObject -Filter {SamAccountName -eq $server} -Properties @('servicePrincipalName') -Server $preferedDC
$servicePrincipalNames = $ADServer | Select -ExpandProperty servicePrincipalName
foreach($servicePrincipalName in $servicePrincipalNames){
if( ($servicePrincipalName.ToLower() -like 'host*') -or ($servicePrincipalName.ToLower() -like 'softgrid*') ){
$delegates += $servicePrincipalName
}
}
}

foreach($server in $OtherServers){
$ADServer = Get-ADObject -Filter {SamAccountName -eq $server} -Properties @('servicePrincipalName') -Server $preferedDC
$servicePrincipalNames = $ADServer | Select -ExpandProperty servicePrincipalName
foreach($servicePrincipalName in $servicePrincipalNames){
#if($servicePrincipalName.ToLower() -like 'host*'){
$delegates += $servicePrincipalName
#}
}

}

foreach($del in $delegates){ Write-Host $del }

foreach($server in $XenAppServers){
Write
-Host "Updating msDS-AllowedToDelegateTo and userAccountControl on $server"
$ADServer = Get-ADObject -Filter {SamAccountName -eq $server} -Properties @('msDS-AllowedToDelegateTo','userAccountControl') -Server $preferedDC
if($ADServer.userAccountControl -ne 16781312){
Write
-Warning "Updating $server to Trust for delegation with any protocol. Please restart it."
$ADServer | Set-ADObject -Replace @{"userAccountControl"=$userAccountControl} -Server $preferedDC
}

$ADServer | Set-ADObject -Clear "msDS-AllowedToDelegateTo" -Server $preferedDC
# For some reason, adding it all in one go, sometimes fails, so adding each entry one by one
foreach($del in $delegates){
$ADServer | Set-ADObject -add @{"msDS-AllowedToDelegateTo"="$del"} -Server $preferedDC
}
}