Viser opslag med etiketten Service. Vis alle opslag
Viser opslag med etiketten Service. Vis alle opslag

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.

tirsdag den 12. juni 2012

Dynamics NAV - Multiple Service Tiers – Part 2

So I felt like a super hero figuring out all the stuff explained in Part 1 but after posting it, and testing some more I started getting weird errors, and stuff would stop working. While working on something else ( implementing Claims based authentication in Citrix XenApp ) I had enabled Kerberos Logging and I noticed this error

image

And I got this sweating feeling all over, like when you did something bad. So I quickly went to test it. First I tried opening the client, making sure AllowNtlm was set to false and ServicePrincipalNameRequired to true, and tried connecting to one of the Navision instance I had problems with.
It failed.
I added a SPN for the service account with instance name pointing to the server’s FQDN(not the cname as explained in the article) and restarted the service and tried again.


Bam, success … so I went to Google and searched for the documentation. Try opening http://msdn.microsoft.com/en-us/library/dd301254.aspx and search for SPN. Notice how it says

setspn -A InstanceName/FullyQualifiedDomainNameOfServer:Port Domain\User

How the freaking hell did I miss that ? I’ve seen that pages a billion times. Oh well, nothing wrong in learning something new once in a while.

Using a CName is still a good idea thou. If you want to use Kerberos when talking to the Web Service you still need a HTTP/HOST SPN Service registered and what I wrote in part 1 will still apply.

mandag den 28. maj 2012

Microsoft Dynamics NAV 6.0 is making my head hurt

So, several things have been “bugging” me while working with this.
First of all, if you are running a 3 tier setup (and you probably are) then NAV server will need to monitor changes in the database. It can do this in one of two ways. Pooling or using notifications, though the service broker. If using pooling it will do a series of SQL queries against the database every few seconds to see if they have been any changes, this is even if you only have one NAV Server service running and all chances are bound to happen though that service anyway. The other way is is though the service broker, where each NAV service can “subscribe” to changes in certain parts of the database and get notified by the SQL server when ever changes occurs. This will ofc lower the “stress” on the SQL, especially if you are running several NAV services for one or more databases.

Pooling works out of the box, no problem. But using Service broker seems more appealing to me. Service broker works out of the box if your running the NAV Server as Local System/Network Service. When running as a domain account it needs a bit more “tweaking”, explained when following this guide.
http://msdn.microsoft.com/en-us/library/dd568739.aspx

As always, Kerberos was giving me a hard time and while troubleshooting one of the errors I noticed I was getting a ton of these errors on the SQL server.
(The activated proc '[$ndo$navlistener].[SqlQueryNotificationStoredProcedure-cf5de25d-f6a3-457e-928f-cfd42a83f241]' running on queue 'NAV6_NAVI0101.$ndo$navlistener.SqlQueryNotificationService-cf5de25d-f6a3-457e-928f-cfd42a83f241' output the following:  'Could not obtain information about Windows NT group/user 'int\NAVI01_NAV601_NAVI01', error code 0x534.')

image

If you search Google for this error you wont get a lot of hits, most tell you to do some stuff that, to me, didn’t make a lot of sense. From what I can understand basically this error comes when the SQL server cannot resolve the user. This can happen if the account your running the SQL Server Agent as, doesn't have read access to the account mentioned in the error, or the account doesn’t exists.
I got the error while backing up and restoring various NAV databases and hadn't cleaned up the database between the restore.  If you backed up a database and restored it, and get this error just, stop the Navision server, delete the Queue and associated service, then start the Navision service again.

image

When testing Navision from the Role Based client, its worth mentioning that the Navision Client will save all user configuration in the LOCAL profile and not the roaming directory. ( this is mentioned on page 31 in Microsoft Dynamics NAV - Hosting Guide too. You get around this by placing the config file somewhere else, and pointing to that file by adding settings:{path} … the guide suggest copying the file to %APPDATA%\ClientUserSettings.config but it could be anywhere that makes sense in your environment.

If you get this error from the client, when tested on a “remote” machine, but everything is working when called locally on the Navision Server
(The login failed when connecting to SQL Server [FQDN] )
image

you probably got the delegation on the Navision account wrong (or if running as local system, delegation on the computer account for the Navision server ) The account need access to pass on the user’s credentials to the SQL Server. IF the SQL server is running as local system, it needs delegation permissions to the SQL computer account, else to the account that SQL Server is running as.

image

Either of the 3 options here will work. Trusting user for delegation to any service (Kerberos only) is not considered safe or secure and should never be used (but will work for Navision too)
Trusting for delegation to the SQL account/server for the Service type MSSQLSvc for Kerberos only is the recommended and most secure way. If you want to support NTLM authentication too, you will need to set this to “any authentication protocol” but this is considered less secure.

One way to check if Kerberos is configured correctly would be to set above to “any authentication protocol” and then in ClientUserSettings.config set AllowNtlm=True. If this works, then change ServicePrincipalNameRequired=True and AllowNtlm=False. If you get the below error

The remote server did not satisfy the mutual authentication requirement
image

Something in the Kerberos authentication went wrong. Looking though the Security Event log will be extremely helpful. Don’t just give up and set AllowNtlm to True. That is for losers

And remember. If something is running as Local System or Network Service, it is running as the computer account. If you mess with SPN or delegation on that computer account, you need to restart the server for the changes to take effect. If you are running as a domain account and make chances to that, you need to restart all services running as that account for the chances to take effect.

lørdag den 26. maj 2012

Dynamics NAV - Multiple Service Tiers

updated 28-05: Small issued fixed
updated 12-06: I was dead wrong regarding SPN’s. Read more here

So you want to host several Navision Server Services on a single host.

Easy, first you read http://msdn.microsoft.com/en-us/library/dd301254.aspx
Seriously, I normally think of my self as one who got the whole delegation stuff figured out, but this on had me spinning for a while.

If a ran the service as Local System or Network Service, (and gave the NAV server computer account permission to delegate for MSSQLSvc to the SQL Server) everything worked but as soon as a ran the service as a Domain account (and gave that user account permission to delegate for MSSQLSvc to the SQL Server) everything worked locally on the NAV server, but when called from a client machine you would get an error saying it couldn’t authenticate to the SQL Server.

Oh my, turns out I was running my SQL server as a domain account, but some how, some where (and it can’t have been me, I swear) the MSSQLSvc was registered to the SQL Servers computer account, and/but not to the Domain Account the SQL Server was running as. so after deleting the SPN from the SQL server and adding it to the SQL Account, everything was working perfectly.

Well, almost.

you will probably come across this post http://blogs.msdn.com/b/nav/archive/2009/10/20/creating-a-web-service-manually-the-importance-of-what-name-you-give-it-and-a-few-small-things-to-remember.aspx and this post http://blogs.msdn.com/freddyk/archive/2009/08/05/multiple-service-tiers-sp1.aspx
Awesome reading by the way, but it doesn’t take into account you might not want to run everything as local system, and all the fun that comes with that.

Next problem, do you want to assign a new port for each NAV Service or share them ?
Managing several ports are fun, managing many many more ports must be so much more fun. not
So you fire up the NetTcpPortSharing service and suddenly nothing works for NAV, since the domain account doesn’t have permission to do Port sharing. Several post if you Google this, will tell you to uninstall .NET 4.0 *pffhhh*, nah, just open C:\Windows\Microsoft.NET\Framework64\v4.0.30319\SMSvcHost.exe.config and add

<system.serviceModel.activation>
<net.tcp>
<allowAccounts>
<add securityIdentifier="S-1-5-11" />
</allowAccounts>
</net.tcp>
</system.serviceModel.activation>

Well, maybe not THAT specifically, this will allow any authenticated user to use port sharing, you might want to add each service account by SID. ( And restart the server every time you update it =| )


Next NAV will start complaining it cannot start a listener on net.tcp://+:7046/[something]/Service … This should fix that


netsh http add urlacl "url=http://+:7046/" user="NT AUTHORITY\Authenticated Users"
(replace NT AUTHORITY\Authenticated Users with the real account your running the service as)


Next the Web Service Service will fail with a similar error ( http://+:7047/ ) ..
Ahh well,
netsh http add urlacl "url=http://+:7047/" user="NT AUTHORITY\Authenticated Users"
will shut it up …. (replace NT AUTHORITY\Authenticated Users with the real account your running the service as)


So now everything is working, you can start the services, and can probably also connect using a locally installed client on the NAV server, but once you go to a client computer it will complain it cannot talk with the SQL Server.
Here is a dilemma. You cannot have a SPN registered twice in AD. (ok, you can but it will not work) lets imagine you have 2 NAV services one on
net.tcp://nav01:7046/navservice1/Service running with domain account “navservice1acct”
and one on
net.tcp://nav01:7046/navservice2/Service running with domain account “navservice2acct”


We know we need to register a DynamicsNAV/FQDN and NAVSERV_DynamicsNAV/FQDN for the account’s but if FQDN is the same, we have a duplicate and it wont work.
So create a CNAME for each service


$rec = Get-WmiObject -Namespace root\MicrosoftDNS -ComputerName $dnsserver -Class MicrosoftDNS_CNAMEType -Filter "ContainerName='$fzone' and OwnerName='$cname'"
if(!$rec){
Write
-Host "$cname not registrered in DNS, creating it now"
$text = "$cname IN CNAME $NAVServer"
#$rec = [WmiClass]('\\$dnsserver\root\MicrosoftDNS:MicrosoftDNS_CNAMEType')
$rec = [WmiClass]"\\$($dnsserver)\root\MicrosoftDNS:MicrosoftDNS_ResourceRecord"
$rec.CreateInstanceFromTextRepresentation($dnsserver, $fzone, $text) | Out-Null
}


And register the SPN’s for those. in my tests, the role based client will be using host SPN and not DynamicsNAV, not sure if that is related to me using cnames and/or using domain accounts for AX, but just be safe add all 3.
Turns out it was not even doing that. See part 2. Use this



$username = $NAVAdmin.Username
Start
-Process -FilePath 'C:\Windows\System32\setspn.exe' -ArgumentList ("-A $instancename/" + $NAVServer + ":7046 -U $username") -NoNewWindow -Wait
Start
-Process -FilePath 'C:\Windows\System32\setspn.exe' -ArgumentList ("-A $instancename/" + $cname + ":7046 -U $username") -NoNewWindow -Wait
Start
-Process -FilePath 'C:\Windows\System32\setspn.exe' -ArgumentList ("-A HOST/" + $cname + " -U $username") -NoNewWindow -Wait
Start
-Process -FilePath 'C:\Windows\System32\setspn.exe' -ArgumentList ("-A HTTP/" + $cname + " -U $username") -NoNewWindow -Wait


We want InstanceName\fqdn since that, is what Navision is using. Using CNames is still a good idear to handle the WebService, but for purely Navision, we could just stick with InstanceName\fqnd of nav server


Next you want to the Service account to allow delegation to the SQL server. If you want to use constrained delegation and restrict it to Kerberos, all you have to do is add the SPN you want to delegate too


$ADNAVAdminUser = Get-ADUser $NAVAdmin.Username
$SQLServerDelegate = @( ("MSSQLSvc/"+$NAVDBServer+":1433") )
$ADNAVAdminUser | Set-ADObject -Replace @{"msDS-AllowedToDelegateTo"=$SQLServerDelegate}

If, how ever you also want to support NTLM, you need to allow constrained delegation to any authentication protocol, and you need to add TRUSTED_TO_AUTH_FOR_DELEGATION to userAccountControl on the accounts


$NORMAL_ACCOUNT = 512
$DONT_EXPIRE_PASSWORD = 65536
$TRUSTED_TO_AUTH_FOR_DELEGATION = 16777216
$userAccountControl = ($NORMAL_ACCOUNT + $DONT_EXPIRE_PASSWORD + $TRUSTED_TO_AUTH_FOR_DELEGATION)

$ADNAVAdminUser = Get-ADUser $NAVAdmin.Username
$SQLServerDelegate = @( ("MSSQLSvc/"+$NAVDBServer+":1433") )
$ADNAVAdminUser | Set-ADObject -Replace @{"msDS-AllowedToDelegateTo"=$SQLServerDelegate; "userAccountControl"=$userAccountControl}

And to make it all easier, you might want to script updating a client config file too
Remember, the NAV client doesn’t support roaming profiles, so you need to override the config file anyway with "C:\Program Files (x86)\Microsoft Dynamics NAV\60\RoleTailored Client\Microsoft.Dynamics.Nav.Client.exe" -settings:"X:\NAV6\ClientUserSettings.config"
So why not place it somewhere everyone have access to, and keep it simple.
( I had a few issues getting Kerberos to work against the cname, but after reading http://blogs.msdn.com/b/nav_developer/archive/2009/08/17/troubleshooting-multi-machine-installations-of-nav-2009.aspx I tried adding DelegationInfo to the client config and setting it to DomainUser and that did the trick, after also adding a HOST SPN to the Service account running Navision )
( if you are using my cname trick, you probably also need to set ServicePrincipalNameRequired to False. This will also make the logon faster so might be a good idea no matter what ????. Since we have no way of telling the Navision Service what hostname to listen to and register it self as, it will always register it self with the hostname of the server. And since the client is connecting on, and expecting a reply for, the cname they cant do a full mutual authentication, based on hostname and you will get below error. )
( The remote server did not satisfy the mutual authentication requirement. )
image


[xml]$CustomSettings = Get-Content ($clientconfig)
(
$CustomSettings.configuration.appSettings.add | ?{$_.key -eq 'Server'}).value = $cname
(
$CustomSettings.configuration.appSettings.add | ?{$_.key -eq 'ServerInstance'}).value = $InstanceName
(
$CustomSettings.configuration.appSettings.add | ?{$_.key -eq 'ServerPort'}).value = "7046"
(
$CustomSettings.configuration.appSettings.add | ?{$_.key -eq 'AllowNtlm'}).value = "False"
(
$CustomSettings.configuration.appSettings.add | ?{$_.key -eq 'ServicePrincipalNameRequired'}).value = "False"
(
$CustomSettings.configuration.appSettings.add | ?{$_.key -eq 'ClientCredentialType'}).value = "Windows"
$CustomSettings.save($clientconfig)

fredag den 4. marts 2011

The troubled life of an “deploy applications on servers” windows service

So still talking about my Windows Service to install applications. One of the first things you run into is some installers require they run as a domain user (most even as a domain administrator). Some installers also require to run at Console of the server (installing Citrix comes to mind) . Being a service to install applications you now face a few challenges. First of all, how do the service get deployed and what state is the servers in, when you get them ?
Well in my case its VMware host’s deployed from an template server, so I just installed the service on these. We how ever use these images for many different installations, and not all go into the same domain, so the template is not member of a domain, and when we deploy new machines from the template the OSCustomizationSpec doesn’t instruct the machine to join a domain. Wonderful, means my service have to run as a built in account. I choose Local System. Mostly to address some permissions issue I might blog about later. One of the things that gave me trouble after this, is the fact that, once VMware is done with sysprep the machine, it keeps the auto generated name ( like WIN-QJ61PJL91J1 ) for a few minutes, before the new name takes effect. If your using the computer name to uniquely identify the machine, that will give some headaches.
Once the computer name thing is handled you can now safely add the computer to what ever domain you want spawning a process like this
"netdom join " & My.Computer.Name.ToUpper & " /Domain:" & domainDomain & " /userD:" & domainUsername & " /passwordD:" & domainPassword & " /Reboot:02"

So now comes the big question. Do you now reinstall your self with domain credentials or do you start going down the road I did ? if you don’t need console access the first is defiantly easy. The latter can be challenging, but rewarding in the end. My first approach went something along the line of adding AutoAdminLogon under Winlogon and then adding my services to the “RUN” key. Once the console application had started I would move the RUN key from HKLM to HCKU so the service wouldn’t start spawning on Remote Desktop/Citrix servers. but it doesn’t take long until you get tiered of having all your machine auto logging in. Besides even if you use LsaStorePrivateData to store the password so it isn't directly readable in the registry its still not that secure, so you properly want to get rid of that at some point. ( I will gladly post the code for storing “auto login password” in the LSA store if anyone needs that )

So, I was struggling with all that, and at the same time being more and more annoyed about not being able to do some good trouble shooting for installing applications, so I started going down the road of spawning a process at console. Go on, Google it … you will find tons of post about how to do it, and equally many posts stating you cant do it in Vista, Windows 8 and windows 2008. Well you can … You need to run as “local system” and enable “interact with desktop” .. no, you don’t need that either ….

First, there are many different ways in .NET you can spawn a process ( hello System.Diagnostics.Process.Start ) . There's also lots fun ways to get old really fast, trying to call windows API’s ( CreateProcess, CreateProcessWithLogon, CreateProcessAsUser is bound to make you scream like a little girl ) but I finally fell in love with CreateProcessAsUser. I found some very nice code to handle calling processes and controlling stdOutput, stdError and stdInput ( look at http://www.vbforums.com/showthread.php?p=3821573 ). I modified the code to allow me to either run a process as my self, or pass in a Token for another users process and spawn it as a child of that and STILL get the input/output. Very nice stuff. So what I do now is I just query all explorer processes, gets the owner, check the permissions for the owner and if the owner have the permissions needed I start it at he’s console. That way I can logon remotely via RDP and see what's going on. If no user is logged on (either at console or RDP with the prober permissions ) I add AutoLogin information, restart the machine, then remove the autologin information again once I see an explore with the proper permissions.