This month I've been doing some work in WinPE. For those that don't know what it is it's a stripped down version of Windows for Preinstallation Environment(s). It provides a bootable CD (or RIS image delivered over the network when a bare metal machine is booted, assuming it supports PXE). The environment is rather limited, but can be built to support Windows Shell Scripts, ADO and HTA.
The client requirement was to write an HTA menu program which would write a bunch of database entries which would then be picked up by their existing SMS based installation environment. Setting aside the utter pain of the combination of ADO in HTAs under WinPE (which I'll write about later) it all seemed easy enough; at least until I read the standard SQL server configuration which specified all SQL servers would only allow trusted connections. The application was to prompt the build engineers for their domain login and use this information to create a trusted connection to the SQL server.
However that's not how trusted connections work. A SQL trusted connection needs you to be logged in already (into the AD/domain environment if the SQL server resides in a domain, or into a local account which is mirrored via a matching username and password if you are in a workgroup). As PE doesn't have any login process there are no existing security tokens to use when creating a connection and trusted connections don't allow you to specify a username and password, that's partly the point of using them.
So how do you get around this? You need to perform an action that will create a security token in the OS that will then be passed when the database connection is created. The easiest way to do this is to map a network share to the SQL server, this process creates a token that's good enough to use to authenticate a trusted SQL connection request. There doesn't need to be any files in the share, nor does it need to have write access, so the security implications are minimal, for the live client environment they will create a hidden share (one with a share name suffixed by a $ sign) with only read permissions for engineers. A Windows Shell Host file maps a local drive using the login information gathered on the first screen of the HTA and opens a connection. Why a shell script you ask? As I teased earlier, I'll write about that soon.
One slight caveat however; this only works with Named Pipe connections. You can force these by prefixing the machine name or IP address with the desired protocol in the Data Source section of your connection string; "Data Source=np:ServerName". You should note that the protocol specifier is case sensitive, np for named pipes, tcp for tcp connections and so on.
This technique is not limited to PE and will work in XP, 2003, C#, ASP, ASP.Net and pretty much anywhere where you can create a mapped drive. Enjoy.