Documente Academic
Documente Profesional
Documente Cultură
Contents
..................................................................................................................................................1 Terms of Use............................................................................................................................2 Release Notes...........................................................................................................................3 SampleCredentialProvider......................................................................................................3 Common Tasks For Extending SampleCredentialProvider....................................................5 SampleCredUICredentialProvider........................................................................................10 SampleAllControlsCredentialProvider.................................................................................11 SampleHardwareEventCredentialProvider..........................................................................13 SampleWrapExistingCredentialProvider..............................................................................14 Summary.................................................................................................................................19 Questions................................................................................................................................19
Terms of Use
This code and information is provided "as is" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose. Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. Copyright (c) 2006 Microsoft Corporation. All rights reserved. Microsoft, Windows Vista, Windows XP, and Visual Studio are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
Introduction
In this document, well take a look at some custom Windows Vista credential provider samples. Specifically, well cover the following topics: Understanding the base SampleCredentialProvider codebase. Common tasks for extending the base SampleCredentialProvider codebase. SampleCredUICredentialProvider, which supports CredUI. SampleAllControlsCredentialProvider, which exposes each possible UI control. 5. SampleHardwareEventCredentialProvider, which supports asynchronous events. 6. SampleWrapExistingCredentialProvider, which wraps the default username/password credential provider in Windows Vista. 1. 2. 3. 4.
Release Notes
We previously released a version of SampleCredentialProvider. This release of the samples has the following changes 4 new samples showing uses of additional features of the credential provider model Updated the base samplecredentialprovider in the following ways o Fixed the issue where the release configuration wouldnt build o Built & tested in on x64fre o Fixed a bug in the implementation of GetBitmapValue that caused the tiles not to show up on some machines. NOTE: Everyone should make sure they pick up this fix. o Added an implementation of SetSerialization
SampleCredentialProvider
Out of the box, SampleCredentialProvider provides a DLL project that exposes the two COM interfaces required to develop a credential provider: ICredentialProvider and ICredentialProviderCredential. ICredentialProvider exposes the functionality to enumerate available credentials, and ICredentialProviderCredential exposes the functionality required for each specific credential during the authentication process.
Project Structure
The SampleCredentialProvider project includes a small set of files, each with their own purpose: File[s] common.h CSampleCredential.h/.cpp CSampleProvider.h/.cpp Purpose Describes the UI and layout of the credentials. Edit this file to change the number and type of UI elements in each credential tile. Defines the behavior of a credential tile. Edit these files to change the way a tile responds to user input. Defines the behavior of the credential provider, which typically manages one or more CSampleCredentials. Edit this file to change the way credentials are enumerated. Fulfills baseline support for COM server and DLL requirements. You shouldnt need to edit these files. Defines the providers GUID. Youll need to edit guid.h to reference your unique GUID. Provides utility methods for working with UNICODE strings and auth packages. You shouldnt need to edit these files. Registers and unregisters the sample credential provider, respectively. Youll need to edit these files to use the GUID from guid.h wherever a GUID appears. Youll also need to edit the Register.reg file to reflect the name of your object (the first two registry keys) and the name of the DLL (the third registry key). Manages provider resources, such as the tile image. Edit these files if you want to add more resources, such as images, to the credential provider. 4
resource.h, resources.rc
tileimage.bmp
The image to display on the credential tile. Edit this file (or add different images) to change the image that appears in the tile.
10. Open samplecredentialprovider.def. Change SAMPLECREDENTIALPROVIDER.DLL to MYCREDENTIALPROVIDER.DLL. Save samplecredentialprovider.def. 11. Open guid.h. Replace the GUID in DEFINE_GUID with a unique one. You can generate a unique GUID from Tools | Create GUID. Be sure to remember it for later. Save guid.h. 12. Open Register.reg in notepad or Visual Studio (do not execute it in Explorer). Replace the GUIDs in each registry key with the one created in the last step. Also change sampleprovider to MyCredentialProvider as well as "SampleCredentialProvider.dll" to "MyCredentialProvider.dll". Save Register.reg. 13. Open Unregister.reg in notepad or Visual Studio (do not execute it in Explorer). Replace the GUID in the registry key with the one used in the Register.reg. Save Unregister.reg. 14. Select Build | Build Solution. If there are any build errors, review the steps above. 15. Copy the freshly built MyCredentialProvider.dll to the System32 directory of the test machine. 16. Copy Register.reg to the test machine and run it from Explorer to register the credential provider. 17. From the Start Menu, select the option to switch users. 18. The login screen should now have an extra Administrator and Guest account. If all you see is one large tile, click Switch User to see the list of tiles.
19. You should be able to log in using the newly created Administrator account tile. The Guest account may or may not be enabled due to the security settings of your system. 20. If you want to remove the sample, copy Unregister.reg to the test machine and run it to unregister the credential provider.
Rebooting
When rebooting the test machine, it is highly recommended that you unregister the credential provider you are working on (unless you are specifically testing its behavior during the reboot itself). Credential providers that are registered during boot are locked by the operating system and cannot be overwritten. If you leave a credential provider registered during a reboot, you will not be able to overwrite it with a new version until you unregister it and reboot once again. As a result, its a good practice to unregister before each reboot to save effort. Once the system has booted, you can register and unregister credential providers without them being locked by Windows (unless they are actively in use). There are a few other possibilities to simplify updating binaries: You may choose to set up a dual boot system with a safe OS (like Windows XP) on one partition and your Windows Vista installation on another partition. Then when you need to update your credential provider dll, you can boot into the safe OS, replace the dll (since it wont be locked in the safe OS) and then reboot into your Windows Vista installation to test your changes. A quicker use at your own risk tactic is to run kill.exe logonUI.exe from an elevated command prompt, copy the updated binary over, then log out (which will create a new session with a new logonUI.exe)
Register.reg file from Explorer to register the DLL as a credential provider once again.
3. Update the project to link against CredUI.lib. You may need to update your Additional Include Directories and Additional Library Directories to point to the Windows Vista SDK from the projects property pages dialog. 4. Add your credential provider project to the solution. 5. Build the credential provider and make sure the latest version is deployed to the System32 directory and is registered as a credential provider. 6. Set breakpoints, etc, and then run the console app in debug mode. Your breakpoints should get hit as appropriate after CredUIPromptForWindowsCredentials is called from the console app.
Debugging LogonUI
In short: hook up kd between your test machine and your debugging machine and then pipe ntsd over kd for logonUI. Theres a fair amount of info on how to do this on the web (although not specifically for logonUI). But heres some basic pointers. 1. Install the debugger package
(http://www.microsoft.com/whdc/devtools/debugging/default.mspx)
2. Get kd set up between the two computers (for more info look on the web or MSDN)
a. Hook up your debug cable b. On the debugee machine, run something like the following (change command line arguments as necessary) i. Bcdedit debug on ii. Bcdedit dbgsettings serial debugport:1 baudrate:115200 c. Reboot debuggee d. On debugger machine, run something like i. Kd.exe r k com:port=com1,baud=115200 3. Copy symbols that you will need locally to the box since NTSD wont have access to the network 4. Create a key named logonui.exe under HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options 5. In the logonui.exe key, create a string value named Debugger a. Populate that value with the path to ntsd.exe on your machine, for example C:\debuggers\ntsd.exe -d -gG -y <path to local symbols> (space between y and path required) b. d pipes the NTSD output to KD c. g ignores the initial startup breakpoint in the process (if you want the process to break instantly when first executed to set BPs, do not set the small g) d. G ignores the termination breakpoint, so the process will exit quietly
e. y sets the local symbol path on the debugee for NTSD 6. Breaking in when a .DLL loads (not required, but good to know if needed) a. Follow all of the steps above for the executable that loads the .dll, but do not set the small g flag, then when the process starts, NTSD will break in b. Type sxeld <dll name> c. Then g the debugger and NTSD will break in on load of that dll and you can set breakpoints, etc.
SampleCredUICredentialProvider
Windows Vista introduces CredUIPromptForWindowsCredentials, which can be thought of as the next generation of CredUIPromptForCredentials (although CredUIPromptForCredentials is still maintained for backwards compatibility). Unlike CredUIPromptForCredentials, CredUIPromptForWindowsCredentials relies on the same credential providers used by the login screen. While implementing these credential providers are fundamentally the same, there is one place youll need to make a decision regarding how your credential provider works. The implementation of CSampleProvider::SetUsageScenario contains everything we need to add support for CredUI. This method is called with a specific usage scenario (a CREDENTIAL_PROVIDER_USAGE_SCENARIO), which asks the 10
credential provider if it supports it. By default, SampleCredentialProvider does not support the CPUS_CREDUI usage scenario, which means that an application using CredUIPromptForWindowsCredentials will not be able to access credentials provided through it. However, we have changed this by having requests for the CPUS_CREDUI scenario treated in the same way as CPUS_LOGON.
HRESULT CSampleProvider::SetUsageScenario( CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus, DWORD dwFlags ) { UNREFERENCED_PARAMETER(dwFlags); HRESULT hr; switch (cpus) { case CPUS_LOGON: case CPUS_UNLOCK_WORKSTATION: // If we didnt want CredUI to be supported, we would return // E_NOTIMPL if this request was for CPUS_CREDUI. case CPUS_CREDUI: hr = _EnumerateCredentials(); break; case CPUS_CHANGE_PASSWORD: hr = E_NOTIMPL; break; default: hr = E_INVALIDARG; break; } return hr; }
SampleAllControlsCredentialProvider
The SampleAllControlsCredentialProvider project illustrates the usage of each of the nine UI control available to credential providers. Heres an example of what youll see when you run this sample from LogonUI:
11
Note that the Cancel button is automatically inserted by LogonUI. One of the nice things about this sample is that it differs only slightly from the base sample credential provider discussed earlier. Specifically, the key areas changed are in Common.h and CSampleCredential.h. In Common.h, weve added more controls to the SAMPLE_FIELD_ID enumeration, as well as respective entries for s_rgFieldStatePairs and s_rgCredProvFieldDescriptors. As youll see from the screenshots above, only the tile image and large text are configured to display in both selected and deselected mode, whereas the small text is configured to only appear when the tile is deselected. All other controls appear only in the selected tile. To change this behavior, modify the second member of the s_rgFieldStatePairs (its a CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE). In addition to the new fields in Common.h, its necessary to add in support for each type of control to the CSampleCredential.cpp implementation. By default, the base sample only implements support for the String and Bitmap methods, such as GetStringValue, etc. Since those are the only types of controls used in the sample, it was fine to return E_NOTIMPL from the unused control methods, such as GetCheckboxValue. However, since were using these controls now, weve implemented support for getting and setting their respective values. Control SFI_TILEIMAGE SFI_LARGE_TEXT, Required Methods GetBitmapValue GetStringValue 12
GetStringValue, SetStringValue GetSubmitButtonValue GetCheckboxValue, SetCheckboxValue GetComboBoxValueCount, GetComboBoxValueAt, SetComboBoxSelectedValue GetStringValue, CommandLinkClicked
SampleHardwareEventCredentialProvider
A common scenario for custom credentials involves external events, such as the arrival of a message generated by a fingerprint scanner. The SampleHardwareEventCredential sample illustrates processing asynchronous events such as these. When run, this sample displays a window with a single button. This window is designed to emulate an external element that has two states: connected and disconnected. When disconnected, the credential merely displays a large text asking the user to connect:
By pressing the Press to connect button, the credential provides different controls, allowing the user to log in:
13
Since you cannot change the controls used by a credential from an event, this sample actually implements two credentials: a please connect message credential and an actual log in credential, which is effectively the same as the CSampleCredential from the SampleCredentialProvider project. Depending on the state of the connection emulator window, the provider displays the proper one. The window is created on a separate thread, which provides it with a way to pump messages while the provider thread is managed by an external authority. When the button is pressed, the window thread calls in to the provider, asking it to re-enumerate its credentials by calling the CredentialsChanged method on the ICredentialProviderEvents pointer it received in an earlier Advise call:
void CSampleProvider::OnConnectStatusChanged() { if (this->_pcpe != NULL) { this->_pcpe->CredentialsChanged(this->_upAdviseContext); } }
When the credentials are enumerated, methods like GetCredentialCount and GetFieldDescriptorCount are called again. In turn, the provider checks the state of the connection emulator and provides data for the appropriate credential. In either case, exactly one credential is always displayed. Note that were calling CredentialsChanged from a separate thread, which is okay to do. However, be extra careful when trying to call other methods from the separate thread. While this sample illustrates using a button on a window as an event, you could customize CCommandWindow::ThreadProc to look for any event you need, provided its supported on the secure desktop.
SampleWrapExistingCredentialProvider
In some scenarios, you may find that an existing credential provider fits almost all of your needs, with the exception of an additional field or two you need to retrieve from the user. It would be a shame to have to re-implement the functionality of 14
the existing credential provider, so this sample illustrates the process of wrapping an existing credential provider and extending it with two additional fields. Please note that encapsulation (or "wrapping") should be used sparingly. It is not a one size fits all replacement for the GINA chaining behavior. Unlike GINA chaining, the behavior you add only applies if the user clicks on your credential tile and does not apply if they click on another credential tile. Encapsulation is only done explicitly and should only be done when you know exactly what the behavior of the wrapped credprov is. It should be used when you want to extend the credential information that the wrapped credprov is getting. If you merely want to do something extra with the credentials gathered by another credprov, then a network provider is likely more suited to your needs than a credential provider.
In our scenario, we simply attached an extra small text and combobox to the existing password providers credentials. Well let the existing credential provider decide how many credentials to enumerate, how to enumerate them, and how to authenticate. Well also let it deal with the behavior for the controls it defines. Credential providers are COM objects, so they can be created and managed just like any other COM object. In our scenario, we use the CLSID_PasswordCredentialProvider found in CredentialProvider.h to instantiate the provider, and then we proxy most of the calls through to it, returning the
15
results as though they were our own. However, if we receive calls related to our specific extensions, we handle those ourselves. Since we dont want to limit the functionality of the wrapped credential, its important to avoid assumptions where possible. For example, we dont use a checkbox in our extension, but it is possible that the underlying credential may (if not now, then possibly sometime in the future). As a result, calls to methods we dont do anything for should still be passed along to the wrapped credential. For example:
HRESULT hr = E_NOTIMPL; if (this->_pInnerCredential != NULL) { // If the field is in the wrapped credential, pass it along. if (dwFieldID < this->_dwInnerDescriptorCount) { hr = this->_pInnerCredential->GetCheckboxValue( dwFieldID, pbChecked, ppwzLabel); } } return hr;
In some cases, we do handle calls that our wrapped credential needs as well. Fortunately, we can use the dwFieldID parameter to determine whether the referenced fields are ours or theirs. Since our sample appends controls to the wrapped credential, we can perform a simple check to see if the field is ours or theirs. For example:
HRESULT hr = E_NOTIMPL; if (this->_pInnerCredential != NULL) { // If the field is in the wrapped credential, pass it along. if (dwFieldID < this->_dwInnerDescriptorCount) { hr = this->_pInnerCredential->GetStringValue( dwFieldID, ppwz); } // Otherwise, offset into the array to account for wrapped fields // and handle it ourselves. else { dwFieldID -= this->_dwInnerDescriptorCount; if (dwFieldID < SFI_NUM_FIELDS) { hr = SHStrDupW( this->_rgFieldStrings[SFI_I_WORK_IN_STATIC], ppwz); } else { hr = E_INVALIDARG; } }
16
} return hr;
However, if you decide to insert controls between controls in the wrapped credential, youll need to be extra careful to track which field IDs are yours and which are theirs. For some well-known credential fields, such as the password providers password field, you can determine their location by checking the guidFieldType property of their CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR. For example, password fields CLSID is CPFG_LOGON_PASSWORD. More wellknown CLSIDs are available in shlguid.h.
Default Tiles
A Credential Provider may specify a default tile when queried regarding the number of tiles it intends to return. Although this is straightforward from the perspective of each individual Credential Provider, developers should keep in mind that LogonUI will not necessarily treat their tile as the default in all cases. The Credential Provider most recently used for interactive logon will receive preference when multiple providers return a default tile. In other words, when two or more providers return a default tile, the tile specified by the Credential Provider last used to log on will be displayed in zoomed view. This behavior does not occur in a remote session because the most recently used Credential Provider is not saved. Credential Providers may also specify default tiles for the CredUI usage scenario. The default tile in this scenario will receive focus when CredUI appears to the user. CredUI resolves multiple default tile conflicts using the same logic as LogonUI. There is no way for a Credential Provider to determine if other providers specify a default tile. The default tile provided by the Credential Provider last used to successfully logon does not need to be the same tile used during the previous logon. The Credential Provider is free to specify any of its tiles when it enumerates the default.
17
Developers need to be aware that wrapping can be very dangerous if a Credential Provider filters out the original instance of the wrapped provider. In certain situations this is acceptable, but the consequences of unanticipated filtering should be considered to avoid unexpected (and undesirable) consequences. IT Professionals writing Credential Providers which filter out providers on every box in a domain are most likely safe to filter at their discretion. These administrators own the experience on the desktops in their domain. Due to the nature of the controlled environment, they most likely do not need to worry about conflicting filters unexpectedly breaking their machines. Best practices should be followed when installing new Credential Providers. Deploy in a staged environment prior to rolling your changes out to the entire domain. If you are an ISV or an OEM designing a Credential Provider intended for deployment to desktops you do not control then you will want to proceed with much greater caution. For instance, consider a case where two separate credential providers each wrap and filter the in-box password provider. Imagine at least one of them performs an operation effecting the entire machine before logon. Consider what happens when a user installs both these hypothetical credential providers on the same machine. During logon only one of them will be used. In this scenario the user can reach the desktop without performing an important operation specified by one of the credential providers. In general, you should Only filter out other Credential Providers if you explicitly ask and obtain permission from the administrator in charge of setup Not filter out any of the built-in providers (for instance, the password provider) unless one of the following is true o Not filtering an in-box provider will cause user confusion. Consider the consequences of not filtering the in-box provider if it does not severely impact user experience (and wouldnt cause bad problems if a user logged on using this in-box provider), you probably do not need to filter it out. o If you are an OEM or ISV and you are guaranteed to be the only 3rd Party Credential Provider on the box, then you are essentially in ITPro category above and you should have no problem.
If you are not guaranteed to be the only Credential Provider on the box then you may introduce possible instabilities if you filter any built-in providers. Some Credential Provider authors might be tempted to do this in order to force users to use the installed 3rd party Credential Provider for all logons (for instance, to run a script). It is bad practice to depend on users logging on using a specific Credential Provider. Third Party Credential Provider authors generally should not assume there will not be other Credential Provider installed on the users system.
18
Summary
In this document, we took a look at some Windows Vista credential provider samples, as well as some tips & tricks for the process of developing custom credential providers.
Questions
Please contact credprov@microsoft.com with any questions.
19