Use a one-time password solution to securely authenticate your identity

Source: Internet
Author: User
Tags hmac md5 hash xslt sql server express
CodeDownload location: Otpauthentication2008_05.exe (496 KB)
Browse the code online

This article discusses:

  • Password Problems
  • Generate one-time password
  • Build an OTP Solution Based on Web Services
  • Test and deploy OTP
This article uses the following technologies:
IIS 7.0, SQL Server

One-time directory Password
Complete OTP Solution
Test the OTP generator Client
Sample website
Authentication Web Service
Complete Architecture
Sample Code
Precautions for deployment
Try it

The security and management of passwords enable IT administrators of enterprises. A headache. Users often create very simple passwords or write down their passwords to ensure they can remember them. In addition, there is almost no safe and effective Program To reset the password. Since these restrictions exist, how can we reduce such security problems when remote users access your network? Since many users write their passwords, how can they make the company's password solution more reliable? I will introduce how to use standard-based technologies and C # And C to develop one-time password (OTP) concept verification. However, I 'd like to give a general introduction to password substitution technology. There are multiple methods to remove standard passwords for remote users. The certificate authority can be used to issue certificates to users, but this requires a public key infrastructure (PKI), and the setup and maintenance costs are relatively high. It is also difficult to manage certificates of remote users, especially when using hardware tokens (such as smart cards. Such high security often results in high costs. In addition, you can use the one-time password solution SecureID provided by RSA. However, it should be noted that SecureID is not based on standard technology, so it may lead to incompatibility issues and authorization overhead. The third option is to use a standard-based OTP solution. However, what types of one-time password options does it have? Why is OTP better than traditional passwords? Let's take a look.

A one-time password, a traditional static password, is usually changed only when needed: when it expires or when the user forgets the password and needs to be reset. Since passwords are cached on computer hard disks and stored on servers, they are easily cracked. This is especially true for portable computers because they are prone to theft. Many enterprises are equipped with portable computers for employees and enable the network to allow remote access. They will also employ temporary employees and suppliers. In this environment, a simple static password solution may be a negative factor. Unlike static passwords, one-time passwords are changed each time a user logs on. The password can be generated in two ways: time synchronization or counter synchronization. Both methods usually require users to carry a small hardware device that is synchronized with the server (which can usually be attached to a key chain), and usually use some Algorithm To generate a password. OTP with time synchronization has been widely deployed, but Clock Deviation may occur. That is, if the time of the authentication server and User Token is different, the expected OTP value cannot be generated and user authentication fails. When using OTP that is synchronized with time, you must enter the password within a specific period of time. Otherwise, the password is deemed to have expired and another password must be generated. The OTP solution that synchronizes with the counter synchronizes the counter between the client device and the server. Each time you request the OTP value of a device, the counter increases. Just like using OTP with time synchronization, when a user wants to log on, he must enter the currently displayed OTP on the device. OTP for complex situations is a special case where hardware devices are usually used. However, you must provide a known value (such as a personal ID (PIN) to generate OTP. This type of OTP is currently widely used in Europe and is used to add identity verification for credit and debit cards. Currently, the OTP solution is based on a certain encryption process to generate the current password Based on the synchronization parameters (instant or counter value), keys, and possible pins. For example, hash-based OTP uses an encryption hash algorithm to calculate passwords. As you know, encrypted hash is a one-way function that maps messages of any length to a summary of a fixed length. Therefore, hash-based OTP first enters (synchronization parameters, keys, and PIN), then runs them through a unidirectional function, and generates a fixed-length password. So what method should I choose? To understand how it works, I created and tested a solution. Next, I will introduce how to use IIS 7.0 and key Hash Message Authentication To create OTP synchronized with the counter (as described in RFC 2104 and RFC 4426 standards. RFC 2104 is "HMAC: Enter-hash for Information Authentication". The URL is go.microsoft.com/fwlink /? Linkid = 112151; RFC 4226 is "hotp: HMAC-based one-time password algorithm". The URL is go.microsoft.com/fwlink /? Linkid = 112153 ). Because it is a test deployment, I will use a simple client application to create OTP. As mentioned above, you may want to use it in combination with tamper-resistant hardware devices. I will give a general introduction to the basic knowledge required to use this method and provide some entry-level resources.

the complete OTP solution is to build an OTP solution. I need to create a standard-based OTP Authentication Web service, this service is supported by SQL server and integrated into ASP.. net. I will create an OTP generator. By installing it on each client computer, you can run it to generate a new OTP. When receiving a prompt from a Web browser, you need to enter the OTP value and click the "Submit" button for authentication. The OTP plug-in module receives a notification from IIS and then calls the Web service to verify the authentication request. In the SQL Server table, Web Service searches for the user's key and counter value, checks OTP calculation, and returns whether the authentication succeeds or fails. Figure 1 shows the architecture of the sample solution. Remember: in the production environment, you should further strengthen this architecture by configuring trust relationships between clients and servers and limiting invalid login attempts to prevent Dos) attack. Figure 1 one-time password solution component the sample code included in this article is located in the Download Area of the msdn magazine website) contains a Visual Studio 2005 solution, which contains a C ++ DLL (hmacotpdll) used to generate OTP ). Because the DLL is used by otpclient and web services, I put it in the System32 folder. (I use the generated event to automatically copy it to this location .) This example also contains a console application named otpclient that can be used to generate OTP values. Otpclient uses XML files to store encryption codes and counters. Every time you recreate an application, it copies the XML file from the project root directory to the target directory and resets the counter to 0. The IIS module named iis7module provides the OTP authentication service, and this module uses a web service named WebService to check the OTP value. The Web Service contains an SQL Server express database in app_data. Finally, I included a webpage for testing the solution in the testwebsite project.

Test the OTP generator client test the OTP generator client application is an independent tool that allows users to obtain the OTP authentication value. It removes the hardware devices and challenges (such as pin requests) that are typically required in actual deployment ). To calculate OTP, the client component uses the DLL shared with the Identity Authentication Web service. In this example, you will run this tool to create the next OTP, and then manually enter this value in the Web browser table. I will use C # And some C to complete all the work. (I chose to use C to implement underlying OTP encryption .) You know how OTP works at the user level, but how does this solution work at the functional level? This hash-based OTP solution has two input values: Key and count. However, the OTP solution also has metadata related to the Implementation Program, including the length of the key that the user must type and the length of the expected OTP value when performing authentication. My sample program will generate an OTP with a length of six characters and support a maximum of eight characters. For simplicity, this implementation uses some fixed-length buffers that limit the key length to 64 bytes. However, assuming that the key is a high-quality random number from the cryptography perspective, a huge key space is required. Such keys will not be vulnerable to production deployment. (Currently, the random key is usually 256 bits, that is, 32 bytes .) A specific user (or technically with a specific key) will increase the Count value each time an authentication attempt is made. The security of the OTP solution depends on the Count value that is never used again; this is guaranteed by the OTP server. In actual use, the count is a 64-bit unsigned integer. As mentioned above, another deployment method is to synchronize time with the server. HMAC is a key-based encryption hash. In other words, HMAC accepts any message and key, and maps the message to a fixed-length digest value (such as 20 bytes ), this ensures that only those with the same key can generate the same digest value from the same message. The first computing step of the HMAC-OTP is to accept the Count value and encode it as an input message for HMAC computing. In actual use, a message is an 8-byte buffer with the counter value. Figure 2 This step and the next two steps are described. The next calculation step is to use the User Key to calculate the HMAC of the preceding message. Note that I have configured the byte sequence in this implementation to ensure it is compatible with RFC. Figure 2 One-time password Process (Click the image to get a larger view) then, convert the result to OTP value by decimal encoding of the 20-byte HMAC result. There are two practice requirements: first, I need to keep as many HMAC computing bits as possible, which can be the maximum length of OTP results (six digits in this example ), the loss of BITs exposes computing to encryption attacks. Second, I need to create OTP that is compatible with as many input device types as possible. This compatibility requirement is exactly why I use decimal encoding. (This kind of strong identity authentication is even compatible with dial-up phones !)

My goal of the example website is to ensure that the designed site correctly shows whether the user has successfully logged on using OTP. For ease of testing, this OTP solution contains a sample Website. The homepage of the website is default.htm. This logon page shows the authenticated users how the OTP module protects non-Asp. Net pages. It also contains test for displaying the user name that has passed authentication. aspx file and test. how does the ASPX page. web. UI. page. the user property retrieves the test. aspx. CS file. The solution also includes a Web. config file (including references to otpmodule) and a Visual Studio project solution that references the iismodule. dll file. The iis http otp plug-in module is a component of the website. This module interacts with IIS and redirects users to a web form in which the user name and OTP can be entered. When the user submits the user name and OTP, this module checks the input and redirects the user to the corresponding success or failure page. This module also associates the user's authentication status with the user session. To achieve maintainability and support, I want to manage this module, so I use C # to compile this module. The plug-in module is the client of the Authentication Web Service (I will introduce it later. The OTP module implements the ihttpmodule interface. In fact, this module is very simple and only contains three public methods. The first one is INIT, as shown below:

Copy code

 Public void Init (httpapplication application) {application. beginrequest + = new eventhandler (application_beginrequest) ;}

As you can see, this module uses this method to register the applinrequest handler application_beginrequest. The purpose of the OTP beginrequest handler is to ensure that all HTTP requests come from authenticated users. The specific implementation method is to use the following helper functions: a function is used to determine whether the caller has passed identity authentication, and several other functions are used to perform identity authentication on the caller when the caller has not passed identity authentication. It is worth mentioning that the method of intercepting requests during the beginrequest event does not follow the standard authentication mode used by ASP. NET applications. However, if you do not want other modules to see this request (or even those designed to intercept the request before authentication), we recommend that you use this method. The isauthenticated help function determines whether the request specifies a user that has passed authentication. The solution is to use the httpcontext, httpcookie, and security. formsauthenticationticket classes in the system. Web namespace to check whether the application context contains correctly encrypted authentication cookies. If a cookie exists and can be correctly decrypted, the caller is deemed to have passed authentication. Otherwise, there are two possible states: the request is an OTP authentication request to be processed, or the Web client request is invalid (not authenticated), the login form is displayed. The OTP module contains a built-in logon form named loginpage.htm. It consists of the following five HTML elements: an initial blank error message field, a username field, a password field, a submit button, and a hidden input field named hdloginform. If the caller has passed authentication, the module does not need to perform further operations. Continue processing the request. In this demonstration, the default.htm page is loaded. If the caller fails authentication, the isauthenticationpost help function is called. It checks whether the request type is post and whether the request form contains the hdloginform input field. If both conditions are confirmed, this method returns true. If the request is an authentication request, call the tryauthenticate help function. Retrieve the user name and OTP value from the request context and pass it to the verifyotpcode method of the authentication web service. If the verification succeeds, the new encrypted authentication cookie is appended to the response. Then, redirect the response to the default page (default.htm ). To demonstrate this effect, you can save the original page of the user request and redirect the user to this page after authentication is successful. If verifyotpcode fails to be called, the request is redirected back to the logon form (an error message is displayed) and the help function showloginform is called. This help function loads the logon page from the module's resource section, sets the error message string in the page (if applicable), and sets the logon page as a response to the current request. It then marks the request as completed (this step is completed regardless of the nature of the request ).

Authentication Web Service is responsible for implementing the actual OTP authentication by determining whether the provided OTP value indicates that the named user already has a key ,. Because the underlying encryption library is reused (this database implements OTP computing described in the previous chapter on testing the OTP generator client), it is very easy to implement the OTP Authentication Web service. This form of reuse is a call to P/invoke exported from generateotp of hmacotpdll. dll on the local machine. The Web Service provides a web method verifyotpcode (true is returned when the authentication is successful ). This method first loads the SQL Server database row corresponding to the user name specified in the authentication request. If the SQL server cannot find a matched row, this method returns false. If the user name is found in the SQL Server database, this method will pass the following data items to the native generateotp: OTP value specified in the request, User Key (retrieved from SQL Server) and the counter value (also retrieved from SQL Server ). Generateotp will use continuous counter values for repeated attempts until a matched OTP value is returned or 1,000 consecutive counter values have been checked. Although it is unlikely that the last successful authentication attempt will be repeated for one thousand times, it may cause the user to accidentally run the client counter to go offline! By narrowing down the scope, attackers can also make the probability that the OTP value actually guessed is equal to the value in the sequence lower, however, it increases the possibility that the user accidentally runs the client counter beyond the permitted range of the server. In the latter case, the administrator needs to be requested for further authentication. If a matched OTP value is found within the counter range, the new counter value is written back to the database. Unfortunately, this requires authentication that the Web Service has database write permissions, and as described earlier, since the counter value must not be reused, therefore, it is also crucial for OTP security. (To make the one-time password unique, you must ensure that it is only used once .) SQL Server databases with simple architecture can be used to store user names and corresponding OTP keys or seed values. This architecture can also be expanded to include login information (such as the number and time of successful and unsuccessful logons using OTP ). The database consists of username, secretcode, and counter columns. For an explanation of each element, see the "Authentication Web Service" section. The database copy attached to the sample code contains only one row that stores the username "testuser.

the complete architecture 3 shows the architecture when the solution is completed ., Start the client application, generate OTP, navigate to the authentication web application, and paste OTP into the web browser form. When the OTP module detects that the request has not passed authentication, it generates a form. When you click "Submit", the Web browser form sends the request to the server (where it will be intercepted by the OTP module again ). Next, the OTP module calls the OTP web service to verify the user's identity authentication data. Finally, if successful, the web server will call the processing program for the request page (this page can be of any type: HTML, ASP. NET, PHP, etc. Figure 3 detailed OTP solution architecture (click the image to get a large view)

Run the sample code. To run the sample code, you must have Windows Vista with IIS 7.0Or Windows Server2008 (and enable the "Application Server" role for Windows Server 2008), Visual Studio 2005, SQL Server 2005, SQL Server Express, and OTP sample code. For demonstration, we recommend that you use Windows Server 2008 and SQL Server Express (because I use them ). In the following description, assume that the OTP sample code solution file is located in C: \ test \ OTP. sln. To prepare the environment, use the "IIS manager" or edit the Web. config file to install the IIS module. Grant the read and write permissions to c: \ test \ OTP \ WebService \ app_data to the iis_iusrs account or the account configured with the custom application pool ID. Then, add a website for otptest and otpservice. Use the Web. config file to register the IIS module (this step has been completed in the example-see testwebsite \ WEB. config). The following configuration tag is required:

Copy code

<System. webserver> modules> <Add name = "otpmodule" type = "otpmodule"/> </modules> </system. webserver>

The module dll should also be added to the bin folder or Global Assembly Cache (GAC. To register an OTP module with GAC, run the following command:

Copy code

 
Gacutil.exe/I iis7module. dll

To use "IIS manager", open this manager and click the computer name in the console tree. In the middle pane, double-click the module icon and click Add managed module in the Action pane ). Next, select otpmodule from the drop-down list box. If you add a DLL to GAC and use "IIS manager" to add a module, you may need to restart IIS to refresh the module list. To correctly add the number of attempts in SQL Server Express, the network service account must have read and write permissions on the c: \ test \ OTP \ WebService \ app_data database. This object requires the permission to read and execute, list folder content, read and write (suchFigure 4). Figure 4Required permissions on the app_data directoryYou must also set up a website for the test website in IIS. To do this, open the "IIS manager" console, expand a node with your computer name in its console tree, right-click "sites" (website) click Add web site ). Use the following settings for the new website and click "OK" (Figure 5 shows these settings): Figure 5Otptest website settings(Click the image to get a larger view)

    • "Site name" (website name): otptest
    • "Physical path" (physical path): C: \ test \ OTP \ testwebsite
    • Port: 8000
You must also create a website for the web service. Use the following settings for the website: the website name is otpservice, the physical path is c: \ test \ OTP \ WebService, and the port is 8080. Next, open OTP in Visual Studio. SLN solution, expand iis7module in solution Resource Manager, expand "web references" (Web reference), right-click otpservice, and click "properties) make sure that the Web Reference URL is set to http: // localhost: 8080/service. asmx. In the "build" menu, click "build solution" and confirm that no error is generated. Now you should perform a test to ensure that the OTP module is properly registered and loaded. To this end, navigate to http: // localhost: 8000 and confirm that Figure 6 The logon page shown in. To test the implementation, enter the test username testuser. Figure 6 Homepage of the test website To obtain the value of the OTP code text box, open the Command Prompt window as an administrator and navigate to the directory generated by the OTP Client Program (C: \ test \ OTP \ otpclient \ bin \ Debug ). Run otpclient.exe to obtain the next OTP value. Results should be as follows: Figure 7 . Figure 7 Run otpclient.exe to obtain the OTP Value (Click the image to get a large view) type the OTP value in the OTP code text box, and then click "Submit" (submit ). Figure 8 The sample OTP code is displayed on the page. If the authentication succeeds, you will go to the default.htm page. Figure 8 Test page with sample OTP Value Click the text. aspx link on the login page to go To the demo page. The name of the currently authenticated user (if any) is displayed. If the authentication credential is incorrect Figure 9 Page. Figure 9 Authentication failed

Precautions for deployment if you want to deploy this sample solution in the actual environment, there are many considerations. The actual deployment stores user keys/seeds in tamper-resistant devices (such as hardware tokens ). We recommend that you change the solution to locking your account after multiple consecutive failed authentication attempts. You can add multiple SQL Server columns and a feature to the web service. If interoperability is a consideration, we recommend that you perform interoperability tests for the underlying HMAC code. We should also realize that the MD5 hash algorithm is no longer secure. The purpose of this example solution is to use the algorithms provided in the RFC document to run some basic known vector tests ". However, a deployable solution should use one of the SHA-2 algorithms to create a hash. When developing a user-friendly authentication page, do not differentiate invalid user names and passwords. Otherwise, attackers can obtain valid user names. You also need some setup solutions to add and delete users or associate the Authentication database with another repository (such as Active Directory ) Synchronization. If the goal is only ASP. NET, You can implement the module as a standard ASP. net http module. However, such solutions are only secure. aspx files. Note that the ihttpmodule interface is the same when ASP. NETI is run or IIS 7.0 is used. Therefore, if the initial solution is an ASP. NET-specific module, you can change the configuration to support all file types. I used Visual Studio to edit the database (I didn't notice this cool ide feature before ). To edit the database, go to the Solution Explorer Tree View, expand WebService, expand app_data, and select open from the context menu. On the Server Explorer panel that appears, expand "data connections" and expand OTP. MDF, expand "tables", right-click "users", and click "show table data ). Figure 10 Displays table data in Visual Studio IDE. Do not open the database in the IDE during testing; otherwise, the Web service will not be able to open it, and thus cause authentication failure. Figure 10 One-time password solution component

Try a one-time password with a higher priority than the standard password. Because users are very casual in using passwords (such as writing down passwords and becoming victims of phishing scams), you must strengthen the authentication process. By using the IIS 7.0 plug-in module model, you can use hardware tokens and questions to create a standard-based OTP solution and an OTP solution that is more reliable and can be put into production immediately. Try it by following the example here. Since many employers and consumer-oriented interfaces (such as online banking) use OTP, you should familiarize yourself with this technology. For more information, see what Mike volodarsky wrote in January 2008.Msdn magazineArticle"IIS 7.0: Use the integrated ASP. NET pipeline to enhance the application" at msdn.microsoft.com/msdnmag/issues/08/01/phpandiis7. It provides some useful background information.

Dan GriffinHe is a software security consultant in Seattle, WA. He has worked in Microsoft's Windows Security Development Team for seven years. You can contact Dan at www.eclipsecure.com.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.