Jaas: Flexible Java Security Mechanism

xiaoxiao2021-03-06  74

Java Authentication Authorization Service (JaaS, Java Verification, and Authorization API) provides a flexible and scalable mechanism to ensure clients or server-side Java programs. The early Safety Framework in Java emphasizes the attack by verifying the source of the code and the author, protecting the user to avoid the attack of the downloaded code. JaaS emphasizes that the system is attacked by users by verifying who is running code and his / her permissions. It allows you to integrate some standard security mechanisms, such as Solaris NIS, Windows NT, LDAP (Lightweight Directory Acquisition Protocol), Kerberos, and the like to be integrated into the system in a system. This article first introduces you some of the core parts of JaaS verification, and then show you how to develop login modules through example. Have you needed to log in to a module for an app? If you are a more experienced programmer, I believe that you have done many times, and it is not exactly every time. You may be based on your login module on the Oracle database, or it is possible to use NT user authentication, or use the LDAP directory. If there is a way to support all of these security mechanisms mentioned above without changing the application-level code, you must be a lucky thing for programmers. Now you can use JaaS to implement the above goals. Jaas is a relatively new Java API. In J2SE 1.3, it is an extension package; in J2SE 1.4 becomes a core package. In this article, we will introduce some core concepts of JaaS, then explain how to apply JAAS to the actual program by example. The example of this article is based on our web-based Java application, in this example, we use the relational database to save the user's login information. Due to the use of JaaS, we implemented a robust and flexible login and authentication module. Java Verification and Authorization: Introduction Before JaaS occurs, Java's security model is designed to meet the needs of cross-platform network applications. In the earlier version of Java, Java is usually used as a remote code, such as applet ,. Therefore, the initial security model puts the attention to protect the user on the source by verifying the code. The concepts contained in the early Java security mechanism, such as the SERCURITYMANAGER, Sandbox concept, code signature, and strategy files, mostly to protect users. The emergence of JAAs reflects the evolution of Java. Traditional server / client programs need to implement login and access control, JaaS is validated by the user of the running program to achieve the purpose of the protection system. Although Jaas has the ability to verify and authorize, in this article, we mainly introduce the verification function. JaaS can simplify program development of Java Security packages by adding an abstract layer between the application and the underlying verification and authorization mechanism. The abstraction layer is independent of the platform to enable developers to use a variety of different security mechanisms without modifying application-level code. Similar to other Java Security APIs, Jaas guarantees that the program is independent of the security mechanism through an extensible framework: Service Provider Interface (SPI). The service provider interface consists of a set of abstractions and interfaces. The overall frame map of the JAAs program is given in Figure 1. Application level code mainly processes logincontext. Below LogInText is a set of dynamic configured loginmodules. LoginModule verifies using the correct security mechanism. Figure 1 gives an overview of JaaS. The code of the application layer only needs to be derived with LoginContext.

Under LoginContext is a set of dynamic configured LoginModule objects, these objects use the relevant security infrastructure to verify operations. Figure 1 JaaS Overview JaaS provides some reference implementation code for loginmodule, such as JNDILoginModule. Developers can also implement the LoginModule interface, just like RDBMSLONGINMODULE in our example. At the same time, we will also tell you how to use a simple profile to install the application. In order to meet the plugability, Jaas is stacked. In a single sign-on, a set of security modules can be stacked together and then is called in the order in the stack by other security mechanisms. The implementation of JAAS models JASS models based on some popular security structural patterns and frameworks. For example, stacked properties are very similar to the stacked verification module (PAM, PLUGGABLE Authentication Module) framework under UNIX. From the perspective of the transaction, JAAS is similar to the behavior of the Two-Phase Commit (2PC) protocol. The concept of secure configuration in JaAs (including policy files and permission) comes from J2SE 1.2. Jaas also borrowed many ideas from other mature security frameworks. The JAAS developers of the client and server-side can apply JAAS to the client and server. It is easy to use Jaas in the client. The situation is more complicated when using JAAS in the server side. The JaaS product currently in the application server market is still not very consistent, and there are some subtle differences using Jaas J2EE application servers. For example, JBOSSSX uses its own structure to integrate JaAs into a bigger security framework; while WebLogic 6.x has also used JaaS, the security framework is completely different. Now you can understand why we need to look at Jaas from the perspective of the client and server. We will list the examples in both cases. In order to make the server-side examples of examples easier, we use the RESIN application server. Core JaaS class Before using Jaas, you first need to install JaaS. Jaas has been included in J2SE 1.4, but there is no in J2SE 1.3. If you want to use J2SE 1.3, you can download Jaas from the official site of Sun. When JaAs is installed correctly, you will find Jaas.jar in the LIB directory of the installation directory. You need to add the path into the classpath. (Note: If you have installed the application server, it already includes JaaS, read the help document of the application server to get more detailed information). In Java Security Property file java.security, you can change some system properties related to JAAS. This file is saved in the / lib / security directory. Using JAAS authentication in the application usually involves the following steps: 1. Create an instance of loginContext. 2. In order to obtain and process verification information, transfer a callbackHandler object as a parameter to LogInContext. 3. Verify by calling the logincontext's login () method. 4. Implement some special features by using the Subject object returned using the login () method (assuming login success). Here is a simple example:

LoginContext lc = new LoginContext ( "MyExample"); try {lc.login ();} {. // Authentication failed} catch (LoginException) // Authentication successful, we can now continue.// We can use the returned Subject if We like.subject sub = lc.getsubject (); Subject.doas (Sub, new myprivilegedaction ()); When running this code, the background works below. 1. When initialization, the LoginContext object first finds the MyExample item in the JAAS configuration file, and then the content of this item determines which LoginModule object is loaded (see Figure 2). 2. When logging in, the LogInText object calls the login () method of each LoginModule object. 3. Each login () method verifies the verification operation or gets a CallbackHandle object. 4. The CallbackHandle object interacts with the user with one or more Callback methods to obtain user input. 5. Fill in the verification information to a new Subject object. We will make further explanations on the code. But before this, let's first look at the core JaAs class and interface involved in the code. These classes can be divided into three types: Type Normal Subject, Principal, certificate authentication LoginContext, LoginModule, CallBackHandler, Callback Authorization Policy, AuthPermission, PrivateCredentialPermission exemplified above classes and interfaces are most javax.security.auth package. In J2SE 1.4, there are also some interface implementations in the com.sun.security.Auth package. Ordinary type: Subject, Principal, the Subject class represents a verification entity, which can be a user, administrator, web service, device, or other process. This class contains three-level type of security information: Identities: Public credentials (public credentials): private credentials, such as names, or private keys, such as passwords or private keys The Principal object represents the identity of the Subject object. They implements Java.security.principal and java.io.serializable interfaces. In the Subject class, the most important method is getName (). This method returns an identity name. A plurality of Principal objects are included in the Subject object, so it can have multiple names. Due to the login name, the ID number, and the email address can be used as the user's identity, it can be seen that the situation with multiple identity names is very common in practical applications. The credentials mentioned above are not a specific class or an excuse, which can be any object. The voucher can contain any authentication information required for a particular security system, such as a tag (Ticket), key, or password.

A set of specific private and public credentials are maintained in the Subject object, which can be obtained by getPrivateCredentials () and getPubliccredentials () methods. These methods are usually called in the application layer in the application layer. Verification: LoginContext In the application layer, you can use the LogInText object to verify the Subject object. The LoginContext object also reflects the dynamic pluggage of JaaS because you need to specify a configuration when you create an instance of loginContext. LoginContext usually loads configuration information from a text file, telling the LoginContext object which loginmodule object when logging in. The three methods often used in LoginContext are listed below: login () is logged in. This method activates all LoginModule objects established in the configuration. If successful, it will create a verified Subject object; otherwise throw the loginexception exception. GetSubject () Returns the verified Subject object logout () Logout Subject object, delete the related Principal object and credential verification: loginmodule loginmodule is the interface that calls a specific verification mechanism. J2EE 1.4 contains the following LoginModule's implementation class: JNDILOGINMODULE is used to verify directory service in JNDI KRB5LoginModule to verify NTLoginModule using the Kerberos protocol to verify NTLoginModu to verify the user information in NT. UnixLoginModule uses the current user in Unix in UNIX User information verifies the implementation class of the corresponding Principal interface that is bound to the above module, such as NTDomainPrincipal and UnixPrincipal. These classes are in the com.sun.security.Auth. Five ways in the LoginModule interface: initialize () When you create a LoginModule instance, constructor call login () verifying COMMIT () When the LGONInContext object accepts the result of all LoginModule objects, the method will call the method. This method assumes the Principal object and the voucher to the Subject object. Abort () This method is called when any LoginModule object verification fails. There is no Principal object or credentials associated with the Subject object. Logout () Deletes the Principal object and credentials associated with the Subject object. In the application's code, programmers usually do not directly call the methods listed above, but indirectly call these methods through LigonContext. Verify: CallbackHandler and Callback CallbackHandler and Callback objects allow LoginModule objects to collect the necessary verification information from the system and users, while independent of the interaction process that occurs when the actual collection information. JAAS contains seven Callback implementation class and two classes in javax.sevurity.auth.callback CallbackHandler implementation package: ChoiceCallback, ConfirmationCallback, LogcaleCallback, NameCallback, PasswordCallback, TextInputCallback, TextOutputCallback, DialogCallbackHandler and TextCallBackHandler. The Callback interface will only be used on the client.

I will introduce how to write your own CallbackHandler class. The configuration file I have mentioned that JaaS scalability comes from it to dynamically configure, and configuration information is usually saved in text. These text files have many configuration blocks, and we usually call these configuration blocks as applications. Each application corresponds to one or more specific LoginModule objects. When your code constructs a LogInContext object, you need to pass the name of the application in the configuration file to it. LoginContext will determine which LoginModule objects are activated according to the information in the application, and what rules are activated in order and what rules are used. The structure of the configuration file is as follows: Application {ModuleClass Flag ModuleOptions; ModuleClass Flag ModuleOptions; ...}; Application {ModuleClass Flag ModuleOptions; ...}; ... The following is an application named SAMPLE

Sample {com.sun.security.auth.module.ntloginmodule rquid debug = true;} The above simple application Specifies that the logincontext object should be verified using NTLoginModule. The name of the class is specified in ModuleClass. FLAG Control When you log in when you include multiple LoginModule: Required, Sufficient, Requisite, and Optional. The most commonly used Required, using it means that the corresponding LoginModule object must be called, and must be required to pass all validation. Because the complexity of the Flag itself, this article is not going to study here. ModuleOption allows multiple parameters. For example, you can set the debug parameter to true (debug = true) so the diagnostic output will be sent to System.out. The configuration file can be named any, and can be placed anywhere. The JAAS framework determines the location of the configuration file by using the java.securty.auth.long.config attribute. For example, when your application is Jaastest, the configuration file is JaaS.config in the current directory, you need to enter: java -djava.security.Auth.login.config = jass.config javatest diagram 2 describe the configuration file The relationship between each element

Figure II JaaS configuration file is logged in by command line to verify what can JaaS can do, I have written two examples here. One is a simple program that is called by the command line, and the other is the server-side JSP program. Both the two programs are logged in by the username / password, and then verify it with the relational database. In order to verify via a database, we need: 1. Implement the RDBMSLoginModul class, which can be verified for the input information. 2. Edit a configuration file and tell LogInText how to use RDBMSLoginModule. 3. Implement the consolecallbackHandler class, you can get the user's input through this class. 4. Write application code. In the RDBMSLoginModul class, we must implement five methods in the LGOINMODULE interface. The first is the initialize () method:

public void initialize (Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {this.subject = subject; this.callbackHandler = callbackHandler; this.sharedState = sharedState; this.options = options; url = (String) options.get ( "URL"); driverclass = (string) Options.get ("driver"); debug = "true" .EqualsignoreCase ("debug")));} LoginContext When calling the login () method Call the initialize () method. The first task of RDBMSLoginModule is to save the reference to the input parameters in the class. Feed Principal objects and credentials to the Subject object after the verification is successful. The CallbackHandler object will be used in the login () method. SharedState allows data to share between different LoginModule objects, but we will not use it in this example. Finally, it is a MAP object called Options. Options passes the value of the parameters defined in the configuration file moduleOption domain to the LGOINModule object. The configuration file is as follows: example {rdbmsloginmodule requiredDriver = "org.gjt.mm.mysql.driver" URL = "JDBC: mysql: // localhost / jaasdb? User = root" debug = "true";}; in the configuration file RDBMSLoginModule contains five parameters, where driver, URL, user, and password are required, and Debug is an optional elaboration. Driver, URL, User and Password parameters tell us how to get JDBC connections. Of course, you can also add information on the tables or columns in the database in the ModuleOption domain. The purpose of using these parameters is to be able to operate the database. In the initialize () method of the LoginModule class, we save the value of each parameter. Let's mention a loginContext corresponding to the configuration file tells it which application should be used in the file. This information is passed through the constructor of LGOINCONTEXT. Below is the code initialized the client's code, created a logincontex object in the code and called the login () method.

ConsolecallbackHandler CBH = New consolecallbackHandler (); logincontext lc = new logincontext ("eXample", cbh); lc.login (); When the LGOINCONTEXT.Login () method is called, it calls all Login () () method. In our example, it is a login () method in RDBMSLoginmodule. The login () method in RDBMSLoginModule has the following: 1. Create two Callback objects. These objects get username / passwords from user input. The two Callback classes in Jaas are used in the program: NameCallback and PasswordCallback (these two classes are included in the javax.security.auth.callback package). 2. Callback is activated by passing Callbacks as a parameter to the CallbackHandler's Handle () method. 3. Get the username / password through the Callback object. 4. Verify the acquired username / password in the database in the RDBMSValidate () method. Below is the code of the login () method in RDBMSLoginmodule

public boolean login () throws LoginException {if (callbackHandler == null) throw new LoginException ( "no handler"); NameCallback nameCb = new NameCallback ( "user:"); PasswordCallback passCb = new PasswordCallback ( "password:", true) ; callbacks = new Callback [] {nameCb, passCb}; callbackHandler.handle (callbacks); String username = nameCb.getName (); String password = new String (passCb.getPassword ()); success = rdbmsValidate (username, password) Return (TRUE);} In the Handle () method of the consolecallbackHandler class, you can see how the Callback object interacts with the user: Log in to verify using the JSP and relational database Now we hope that the programs that will be called through the command line. Web application. Since the web application is different from the interaction of the general application, we will not be able to use the standard Callback and CallbackHandler classes provided by JaaS. Because we cannot open a command window in the web program to allow users to enter information. Maybe you will think we can also use HTTP-based authentication so that we can get usernames from the username / password window popped up from the browser. But there are also some problems that require two-way HTTP connections (in the login () method is difficult to achieve two-way connections). So in our example we will use the form to log in, get information entered from the form, and then verify it through the RDBMSLoginModule class. Since we didn't deal directly with LoginModule, but how did we get the username and password in the LoginModule object through LGOInText. We can use other methods to bypass this problem. For example, we can initialize a Subject object before creating a LoginContext object, saving usernames and passwords in the Subject object's credentials. Then we can pass the Subject object to the constructor of the LoginContext. Although this approach has no problem, it adds a lot of code related to the security mechanism in the application layer. And usually fed to the subject to the Subject after verification, not the previous. As we mentioned in front of you can implement a CallbackHandler class, then pass it to the LoginContext object. Here we can use a similar approach to handle your username and password. We implemented a new class passiveCallbackHandler. Below is the code using this class in JSP: