Saturday, 13 January 2018

"Invalid Username or password" when mapping a network drive for a Windows service

Another recent issue I've come across required such a bizarre fix I thought I'd document it here in case it helps anyone else.

We had a Windows service running as Local System account on Windows Server 2016, and a mapped drive using Azure File Service over SMB.  So our server was on a separate Active Directory domain to the storage (the Azure storage is effectively on a domain called AZURE).

When we tried to access files on this share using a named drive letter, we would always get an error back saying Invalid username or password.  So after reading StackOverflow and other sites, we tried several different tactics:

1) Try to map the drive using a Windows Scheduled Task running as SYSTEM user, to run a batch file with a net use command in.

2) Try to map the drive using an administrative command prompt and the SysInternals PsExec tool (psexec -s -i cmd.exe)

3) Try to save the credentials for the network location in Windows Credential Manager

But whatever we tried, either the logged in windows user could see it, but the system user couldn't, or vice versa, but nothing would allow the service to see the drive.  We couldn't use the UNC path without mapping it because you can't embed credentials (username and password) in a UNC path.

After much more reading, it turns out that:

a) Each user has it's own record of mapped drives and credentials (which we knew anyway).
b) In some cases, such as Windows Services, different logon sessions for the same user have different mapped drives.
c) All Windows services running as the same user share the same session.

It was (c) that allowed us to finally find a (slightly Frankenstein-esque) solution.

If you create a new windows service (using C# and TopShelf for example) which shells out (System.Diagnostics.Process.Start) to run the net use command, and install this service to run as the SYSTEM user (TopShelf defaults to this), then it magically works, now your existing service can see your mapped drive!

P.S. If you get into a situation where you can't un-map a drive, you need to log back in as the user who mapped it in order to delete it (net use * /d)

P.P.S. If you're in a situation where you're able to change the user a service runs as (we weren't), then this whole thing might be a lot easier.  I think it's the special SYSTEM login that complicates things.