Just a short, simple blog for Bob to share his thoughts.
16 September 2011 • by Bob • FTP, Extensibility
Over the past few years I've created a series of authentication providers for the FTP 7.5 service that ships with Windows Server 2008 R2 and Windows 7, and is available for download for Windows Server 2008. Some of these authentication providers are available on the http://learn.iis.net/page.aspx/590/developing-for-ftp-75/ website, while others have been in my blog posts.
With that in mind, I had a question a little while ago about using an LDAP server to authenticate users for the FTP service, and it seemed like that would make a great subject for another custom FTP authentication provider blog post.
The steps in this blog will lead you through the steps to use managed code to create an FTP authentication provider that uses a server running Active Directory Lightweight Directory Services (AD LDS) that is located on your local network.
Note: I wrote and tested the steps in this blog using both Visual Studio 2010 and Visual Studio 2008; if you use an different version of Visual Studio, some of the version-specific steps may need to be changed.
The following items are required to complete the procedures in this blog:
Note: To test this blog, I used AD LDS on Windows Server 2008; if you use a different LDAP server, you may need to change some of the LDAP syntax in the code samples. To get started using AD LDS, see the following topics:
I tested this blog by using the user objects from both the MS-User.LDF and MS-InetOrgPerson.LDF Lightweight Directory interchange Format (LDIF) files.
To help improve the performance for authentication requests, the FTP service caches the credentials for successful logins for 15 minutes by default. This means that if you change the password in your AD LDS server, this change may not be reflected for the cache duration. To alleviate this, you can disable credential caching for the FTP service. To do so, use the following steps:
cd /d "%SystemRoot%\System32\Inetsrv" Appcmd.exe set config -section:system.ftpServer/caching /credentialsCache.enabled:"False" /commit:apphost Net stop FTPSVC Net start FTPSVC
In this step, you will create a project in Visual Studio 2008 for the demo provider.
net stop ftpsvc
call "%VS100COMNTOOLS%\vsvars32.bat">null
gacutil.exe /if "$(TargetPath)"
net start ftpsvc
net stop ftpsvc
call "%VS90COMNTOOLS%\vsvars32.bat">null
gacutil.exe /if "$(TargetPath)"
net start ftpsvc
In this step, you will implement the authentication and role extensibility interfaces for the demo provider.
using System; using System.Collections.Specialized; using System.Configuration.Provider; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; using Microsoft.Web.FtpServer; public class FtpLdapAuthentication : BaseProvider, IFtpAuthenticationProvider, IFtpRoleProvider { private static string _ldapServer = string.Empty; private static string _ldapPartition = string.Empty; private static string _ldapAdminUsername = string.Empty; private static string _ldapAdminPassword = string.Empty; // Override the default initialization method. protected override void Initialize(StringDictionary config) { // Retrieve the provider settings from configuration. _ldapServer = config["ldapServer"]; _ldapPartition = config["ldapPartition"]; _ldapAdminUsername = config["ldapAdminUsername"]; _ldapAdminPassword = config["ldapAdminPassword"]; // Test for the LDAP server name (Required). if (string.IsNullOrEmpty(_ldapServer) || string.IsNullOrEmpty(_ldapPartition)) { throw new ArgumentException( "Missing LDAP server values in configuration."); } } public bool AuthenticateUser( string sessionId, string siteName, string userName, string userPassword, out string canonicalUserName) { canonicalUserName = userName; // Attempt to look up the user and password. return LookupUser(true, userName, string.Empty, userPassword); } public bool IsUserInRole( string sessionId, string siteName, string userName, string userRole) { // Attempt to look up the user and role. return LookupUser(false, userName, userRole, string.Empty); } private static bool LookupUser( bool isUserLookup, string userName, string userRole, string userPassword) { PrincipalContext _ldapPrincipalContext = null; DirectoryEntry _ldapDirectoryEntry = null; try { // Create the context object using the LDAP connection information. _ldapPrincipalContext = new PrincipalContext( ContextType.ApplicationDirectory, _ldapServer, _ldapPartition, ContextOptions.SimpleBind, _ldapAdminUsername, _ldapAdminPassword); // Test for LDAP credentials. if (string.IsNullOrEmpty(_ldapAdminUsername) || string.IsNullOrEmpty(_ldapAdminPassword)) { // If LDAP credentials do not exist, attempt to create an unauthenticated directory entry object. _ldapDirectoryEntry = new DirectoryEntry("LDAP://" + _ldapServer + "/" + _ldapPartition); } else { // If LDAP credentials exist, attempt to create an authenticated directory entry object. _ldapDirectoryEntry = new DirectoryEntry("LDAP://" + _ldapServer + "/" + _ldapPartition, _ldapAdminUsername, _ldapAdminPassword, AuthenticationTypes.Secure); } // Create a DirectorySearcher object from the cached DirectoryEntry object. DirectorySearcher userSearcher = new DirectorySearcher(_ldapDirectoryEntry); // Specify the the directory searcher to filter by the user name. userSearcher.Filter = String.Format("(&(objectClass=user)(cn={0}))", userName); // Specify the search scope. userSearcher.SearchScope = SearchScope.Subtree; // Specify the directory properties to load. userSearcher.PropertiesToLoad.Add("distinguishedName"); // Specify the search timeout. userSearcher.ServerTimeLimit = new TimeSpan(0, 1, 0); // Retrieve a single search result. SearchResult userResult = userSearcher.FindOne(); // Test if no result was found. if (userResult == null) { // Return false if no matching user was found. return false; } else { if (isUserLookup == true) { try { // Attempt to validate credentials using the username and password. return _ldapPrincipalContext.ValidateCredentials(userName, userPassword, ContextOptions.SimpleBind); } catch (Exception ex) { // Throw an exception if an error occurs. throw new ProviderException(ex.Message); } } else { // Retrieve the distinguishedName for the user account. string distinguishedName = userResult.Properties["distinguishedName"][0].ToString(); // Create a DirectorySearcher object from the cached DirectoryEntry object. DirectorySearcher groupSearcher = new DirectorySearcher(_ldapDirectoryEntry); // Specify the the directory searcher to filter by the group/role name. groupSearcher.Filter = String.Format("(&(objectClass=group)(cn={0}))", userRole); // Specify the search scope. groupSearcher.SearchScope = SearchScope.Subtree; // Specify the directory properties to load. groupSearcher.PropertiesToLoad.Add("member"); // Specify the search timeout. groupSearcher.ServerTimeLimit = new TimeSpan(0, 1, 0); // Retrieve a single search result. SearchResult groupResult = groupSearcher.FindOne(); // Loop through the member collection. for (int i = 0; i < groupResult.Properties["member"].Count; ++i) { string member = groupResult.Properties["member"][i].ToString(); // Test if the current member contains the user's distinguished name. if (member.IndexOf(distinguishedName, StringComparison.OrdinalIgnoreCase) > -1) { // Return true (role lookup succeeded) if the user is found. return true; } } // Return false (role lookup failed) if the user is not found for the role. return false; } } } catch (Exception ex) { // Throw an exception if an error occurs. throw new ProviderException(ex.Message); } } }
Note: If you did not use the optional steps to register the assemblies in the GAC, you will need to manually copy the assemblies to your IIS 7 computer and add the assemblies to the GAC using the Gacutil.exe tool. For more information, see the following topic on the Microsoft MSDN Web site:
In this step, you will add your provider to the list of providers for your FTP service, configure your provider for your LDAP server, and enable your provider to authenticate users for an FTP site.
cd %SystemRoot%\System32\Inetsrv
appcmd.exe set config -section:system.ftpServer/providerDefinitions /+"activation.[name='FtpLdapAuthentication']" /commit:apphost
appcmd.exe set config -section:system.ftpServer/providerDefinitions /+"activation.[name='FtpLdapAuthentication'].[key='ldapServer',value='MYSERVER:389']" /commit:apphost
appcmd.exe set config -section:system.ftpServer/providerDefinitions /+"activation.[name='FtpLdapAuthentication'].[key='ldapPartition',value='CN=MyServer,DC=MyDomain,DC=local']" /commit:apphost
appcmd.exe set config -section:system.ftpServer/providerDefinitions /+"activation.[name='FtpLdapAuthentication'].[key='ldapAdminUsername',encryptedValue='MyAdmin']" /commit:apphost
appcmd.exe set config -section:system.ftpServer/providerDefinitions /+"activation.[name='FtpLdapAuthentication'].[key='ldapAdminPassword',encryptedValue='MyPassword1']" /commit:apphost
In this blog I showed you how to:
When users connect to your FTP site, the FTP service will attempt to authenticate users from your LDAP server by using your custom authentication provider.
The PrincipalContext.ValidateCredentials() method will validate the user name in the userName parameter with the value of the userPrincipalName attribute of the user object in AD LDS. Because of this, the userPrincipalName attribute for a user object is expected to match the name of the user account that an FTP client will use to log in, which will should be the same value as the cn attribute for the user object. Therefore, when you create a user object in AD LDS, you will need to set the corresponding userPrincipalName attribute for the user object. In addition, when you create a user object in AD LDS, the msDS-UserAccountDisabled attribute is set to TRUE by default, so you will need to change the value of that attribute to FALSE before you attempt to log in.
For more information, see my follow-up blog that is titled FTP and LDAP - Part 2: How to Set Up an Active Directory Lightweight Directory Services (AD LDS) Server.
Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/
Tags: FTP, C#, LDAP, Extensibility