In today’s lesson, you will look at• How the J2EE specification supports the common requirements for asecure system • The common terminology used when discussing system security • Symmet
Trang 1In today’s lesson, you will look at
• How the J2EE specification supports the common requirements for asecure system
• The common terminology used when discussing system security
• Symmetric and asymmetric encryption
• Securing a J2EE application using principals and roles
• Using declarative security for EJBs and Web pages
• Using programmatic security in EJBs and Web pages
• Supplying security credentials to an LDAP naming service provider forJNDI
Trang 2Security Overview
Security is an essential aspect of most, if not all, enterprise applications However, ing an application as secure is not as easy as it sounds, because the definition of securecan be interpreted in different ways
defin-To some users, a Web site is secure if they have to provide a username and password toobtain access to the Web pages As you will see, just because a site requires a user tologin does not make it secure
Authentication
Authentication means identifying a client as a valid user of the system Identifying aclient has two components:
• Initially confirming the client’s identity
• Authenticating the client each time it accesses the application
Initial Identification
At its simplest level, initial identification requires a user to simply register with an cation without any additional identification More often, a third party, such as the HumanResources department or manager in a company, identifies a user At its most complexlevel, usually associated with military systems, identification requires background checks
appli-to confirm a user’s identity Identified users are registered with the system and grantedaccess to some or all of the facilities provided by the system (see the “Authorization”later in this chapter)
Trang 3Client Authentication
Registered users of an application must identify themselves each time they use the cation The most common form of authentication is to give each user a unique name (typi-cally an account or login name) and a password associated with that account Users sim-ply have to provide their account names and passwords to gain access to the application
appli-The information identifying a client is usually called the user credentials appli-The most
com-monly encountered forms of user credentials are as follows:
• Account name and password
• Swipe cards
• Smart cards
• Physical identification systems, such as fingerprints and retinal images
• Digital certificatesAuthentication is like the entrance gate to a modern theme park As long as you have aticket, you are allowed into the park—you have been authenticated But authenticationdoes not necessarily allow you to use all of the rides and facilities in the park The means
by which you are allowed access to different parts of the theme park is called
authoriza-tion.
Authorization
Authorization involves controlling access to capabilities of an application according tothe authenticated user’s identity Authorization differentiates between different categories
or types of users and grants, or denies them access to different parts of the system
Using the theme park analogy again, you may only be authorized to use certain rides
Rides may have height, weight, or age restrictions that authorize access to some usersand deny access to others
Confidentiality
Another aspect of security relates not to controlling access to functionality but to ing that data is only seen by authorized users In other words, the data remains confiden-tial Maintaining confidentiality is not just a question of authorizing access to the databut also of ensuring unauthorized access either cannot occur, or if it does, that the dataremains “secure.” In practical terms, confidentiality is often achieved by encrypting thedata so that only authorized users can decrypt and access the data
ensur-Integrity
Ensuring data integrity means preventing deliberate or accidental attempts to modify thedata in an unauthorized manner Applying authorization correctly solves most of the dataintegrity problems concerned with accessing data on a server
Trang 4Data transferred across the network must not be changed or corrupted as it is ferred The user must be sure that the data they receive is the data that was transmitted.Techniques, such as encryption, checksums, and message digests (see the “MessagesDigests and Checksums” section later in today’s lesson), help ensure data integrity acrossnetworks.
trans-Integrity also means that any changes made to a system, are not lost, such as might occurwhen a server crashes Good auditing practices (see the “Auditing” section later in thischapter) help prevent the loss of changes to persistent data
Non-Repudiation
Non-repudiation means being able to prove a user did something, even if the user quently denies it A simple example is a user with online banking facilities A fraudulentuser could transfer money to another bank account and then try to claim this was a spuri-ous transaction and a fault of the banking system With good accounting processes, thebank can prove this was not the case
subse-Auditing
Auditing is familiar to database users and has the same meaning in security—providing arecord of activity Good auditing is an adjunct to supporting non-repudiation and integri-
ty Remember, audit records must themselves be kept secure
Common Security Technology
Modern software architectures make use of several technologies for supporting systemsecurity This section is a quick summary of the key technologies that are used and howthen can help support the different aspects of secure systems
Symmetric Encryption
Data encryption means converting the data so that it can only be decrypted and read byauthorized users Data encryption requires an algorithm that is applied to the data toencrypt it
Symmetric encryption is so called because it uses the same key to both encrypt anddecrypt the data
One of the simplest cryptographic techniques is the Caesar cipher (named because JuliusCaesar was reported to have used it) The Caesar cipher simply replaces each letter of thealphabet by the letter three positions further on, so that A is replaced by D, B by E, and
so on, with the last three letters replaced by the start of the alphabet Figure 15.1 showsthe Caesar cipher
Trang 5The Caesar cipher is a specific example of a simple shift substitution cipher when oneletter replaces another A different cipher is obtained by shifting the alphabet by more orless than three letters, as shown in Figure 15.2
2 5KEY
The number of letters the enciphering alphabet is shifted by is called the cipher key.
Given an encrypted message, anyone with the key can decipher the message Because the
same key is used to encrypt and decrypt the message, this is know as a symmetric
encryption algorithm.
In programming terms, each letter is represented by a number, and the substitution ciphersimply adds the key number to the value of each letter to get the encrypted form Theresultant number must be adjusted to map the last few letters (X, Y, and Z) onto the firstfew (A, B, and C) letters This is a very simple algorithm
In real applications, symmetric algorithms use sophisticated algorithms with numberkeys of 56 or 128 bits (approximately 45 decimal digits) The algorithms used are usual-
ly well known but, due to the size of the keys used, they cannot be easily reversed Inother words, without the key, the original plain text message can only be recovered byapplying each possible key in turn As long as the key is a large one and the encryptionalgorithm is sufficiently robust, the time taken to crack the cipher with a brute-forcemethod attack, such as applying every possible key, can be hundreds of years
Trang 6One of the most widely used symmetric encryption algorithms is called DES (DataEncryption Standard).
Symmetric encryption is used to ensure data confidentiality Symmetric encryptionensures that only the intended recipients who know the decryption key can recover theoriginal data
Asymmetric Encryption
Asymmetric encryption uses different algorithms than symmetric encryption and requiresthe use of two keys One key is used to encrypt the data, and the other is used to decryptthe data The two keys can be very large numbers, with modern systems using numbers
of 1024 bits (approximately 140 decimal digits) Asymmetric encryption is called public key encryption due to the way the two keys are used.
Of the two keys used in asymmetric encryption, one is made public, while the other is
kept private to the owner The keys are known, respectively, as the public key and the private key.
If data is encrypted with the public key, only the owner of the private key can decrypt it.This approach is used to ensure data confidentiality but is restricted to supporting onlyone recipient per message
In contrast, using symmetric key encryption allows one message to be distributed to eral recipients, as long as each recipient knows the key used to encrypt the message Ifthe private key was known by more than one person, it would undermine the other bene-fits of using asymmetric encryption (such as non-repudiation) and avoid the need to dis-tribute the cipher key Distributing the keys used in symmetric encryption is a majorproblem, because the keys have to be distributed in a secure manner An attacker obtain-ing the keys can decrypt the message to recover the original data
sev-Another use of asymmetric encryption is to support non-repudiation If a message isencrypted with the private key, it can only have originated from the key owner Anyonecan decrypt the data using the public key with the knowledge that it can only have origi-nated from the owner of the private key This use of asymmetric encryption is the basis
of digital signatures.
Asymmetric encryption is slow compared to symmetric encryption To improve mance, it may be desirable to use symmetric encryption The problem here is how to dis-tribute the encryption key to the recipient securely
perfor-A common approach is to use symmetric encryption for the data and to pass the encryption key with the data To make this approach secure, the recipient’s public key
is used to encrypt the symmetric key passed with the encrypted data The recipient can use his or her private key to recover the key and then decrypt the actual data
Trang 7http://localhost:8000Ordinary socket communication uses plain (unencrypted) data Any user that can monitornetwork traffic can read any usernames, passwords, credit card details, bank accountinformation, or anything else passed over the network This is obviously an unacceptablesituation from a security point of view.
One solution to securing confidential data over a network is to encrypt the data withinthe application This is an inconsistent solution because some applications will be securewhile others are not
Another solution is to always encrypt all network traffic Because encryption adds anoverhead to the network communication, this will affect overall performance and isunnecessary when data does not need to be encrypted
The workable solution is to seamlessly provide network encryption only for applicationsthat require secure data transmission Using this approach, any application can encryptconfidential data simply by using the encrypted network communications instead of theusual plain text data transfer Each application decides if encryption is needed but doesnot have to implement the encryption algorithms
SSL is a network encryption layer than can be used by any TCP/IP application Theapplication has to connect by using a secure socket rather than a plain socket, but other-wise, the application remains unchanged
Hypertext Transfer Protocol Secure (HTTPS) is the name given to the HTTP protocolwhen it uses a secure socket The default port used by an HTTPS is 443 When a URLspecifies the HTTPS service, the Web browser connects to an HTTP server but uses SSL
to encrypt the data All the popular Web browsers indicate on the status line when SSLcommunication is taking place Typically, an open and closed padlock is used to shownwhether data is encrypted
Online credit card verification services and banking systems use SSL communication
Trang 8Checksums and Digests
Data integrity is usually achieved by providing checksums or digests of the data Thedata in a message is subjected to a numerical algorithm that calculates one or more vali-dation numbers that are transmitted with the data The recipient receives the data andapplies the same algorithms to the data As long as the recipient’s calculations yield thesame numbers as those transmitted with the data, the recipient is reasonably confidentthat the data is unchanged
Checksums use simple algorithms and are primarily intended to detect accidental tion of data Message digests use sophisticated algorithms that are designed to preventdeliberate changes to data The algorithms used in a message digest generate many digitsand are chosen so that it is virtually impossible to change the original data withoutchanging at least one of the digest numbers
corrup-There are several digest algorithms in use, with Message Digest version 5 (MD5) rently one of the most popular The MD5 specification can be found at
cur-http://www.ietf.org/rfc/rfc1321.txt.Many applications that can be downloaded from the Web also have an associated signa-ture file A signature file is used to validate the contents of the associated file (the one itsigns) Signature files usually contain one or more digests (typically MD5) of the filethey are signing After downloading the file, a conscientious user can also download thesignature file and check the integrity of the download file by calculating the digest of thefile and comparing it to the value in the signature file Programs to calculate digests arewidely available on the Internet
Digital Certificates
Digital certificates are specified by the X509 international standard and define a formatfor representing public keys and other information about an entity (it could be a user, aprogram, a company, or anything that has a public key)
The official specification for the X.500 Directory Service is available from theInternational Telecommunications Union (ITU) web site at
http://www.itu.int/rec/recommendation.asp?type=folders&lang=e&parent= TREC-X.509
Digital certificates are often sent with a request for data so that the server can encrypt thedata with the recipient’s public key
Digital certificates must be signed by a Certification Authority (CA) to prove their
validi-ty A signed digital certificate contains a message digest of the certificate encrypted usingthe CA’s private key Any recipient of the certificate can decrypt the digest using the CA’spublic key and verify that the rest of the certificate has not been corrupted or modified
Trang 9Security in J2EE
The J2EE specification takes a pragmatic approach to security by focusing primarily onauthorization within the J2EE environment and integration with security features thatalready exist in the enterprise
You have already seen the J2EE design philosophy of separating roles with the ment lifecycle identifying code developers, application assemblers, deployers, andadministrators The J2EE security supports this role-based model by using two forms ofsecurity:
develop-• Declarative security—Declarative security is defined within the application’s
deployment descriptor (DD) and authorizes access to J2EE components, such asWeb pages, servlets, EJBs, and so on End user tools, such as the J2EE RI deploy- tool, support declarative security
• Programmatic security—Programmatic security is used when declarative security
is not sufficient to meet the needs of an application Security-aware componentsimplement the security requirements by using programming constructs
The J2EE security specification also requires transparent propagation of security tials between components In layman’s terms, this means that once clients have logged in
creden-to a Web page, they do not need creden-to authenticate themselves again for any EJBs accessedfrom the Web page Also, the authenticated identity of the user remains the same for allcomponents (Web pages, servlets, client applications, and EJBs)
J2EE Security Terminology
The J2EE security domain is based around the concept of principals, roles, and role erences
ref-Principals
Principals represent authenticated entities, such as users The authentication mechanism
is not defined within the J2EE specification, allowing existing authentication schemes to
be integrated with a J2EE application
Trang 10The downside of not defining how users are authenticated means that some parts of theJ2EE security features vary between one manufacturer’s implementation and another Asthe J2EE specification has evolved, additional security requirements have been incorpo-rated to remove the variation between implementations Future versions of the J2EEspecification will add additional security-related constraints as the underlying technologymatures and standardizes.
In a simple implementation, a J2EE principal is a user and the principal’s name is theusername However, there is no requirement for a particular implementation to map thereal usernames onto unique principal names In fact, a principal can represent a group ofusers rather than an individual user Principal names are only used in programmatic secu-rity and are inherently non-portable
Wherever possible, J2EE security should be based on roles rather than principals becauseroles are more portable than principal names Using principals to implement securityrequires coordination between the developer and the deployer and can restrict thereusability a particular J2EE component
Roles
Roles are identified by the developer and represent how components in an applicationwill be used Typically, a developer will identify roles, such as user, administrator, man-ager, and so on, and suggest how the functionality in the application will be used by eachidentified role
A deployer will map principals (real users and groups of users) onto the roles defined inthe application The deployer has total control on how the actual security authentication
is mapped onto the J2EE application
An assembler will combine the roles from many different components to create roles thatrepresent common security requirements across different components
Role References
Role references are used to map the names used in programmatic security to the rolesdefined in the deployment descriptor (DD) The developer defines the coded role namesused in the code, and the assembler or deployer maps the coded references onto the rolesdefined in the application
The relationships between principals, role references, and roles are shown in Figure 15.3
Trang 11Working with J2EE RI Security
So far, you have only been aware of J2EE RI security when running client applications
Even though your applications so far have not been security aware, the J2EE RI ment requires your code to be run inside an environment that has a security context
environ-Web applications run within the J2EE RI environ-Web server that does have a security context
However, applications that run from the command line, such as those you developed onDay 4, “Introduction to EJBs,” and Day 5, “Session EJBs,” do not have a security con-text You must add your client classes to the Enterprise Application Resource (EAR) file
as a client application to obtain a security context The runclientprogram is used to runyour client applications with a security context
Before you look at making your J2EE application security aware, you must spend a shorttime looking at the J2EE RI support for a simple authentication system
The J2EE RI provides an authentication domain that can be used during applicationdevelopment The RI security domain supports:
F IGURE 15.3
Mapping J2EE
princi-pals and roles.
Trang 12• Realms—A realm defines users that are authenticated using the same mechanism.
The J2EE RI defines two realms:
• default Consisting of users identified by passwords
• certificate Consisting of users identified by X509 digital certificates,(certificates are only used to authenticate Web browser clients)
• Users—Defines a username within the J2EE security domain In the default realm,
the username is the principal name In the certificate realm, the common name onthe certificate is the username
• Groups—Users in the default realm can be assigned to groups Groups can be
mapped onto role references to simplify security administration
Adding Users and Groups
Users and groups can be added to the J2EE RI server via two tools:
• realmtool A command-line–based interface
• deploytool A GUI interfaceBoth tools provide limited support for adding users, groups, and certificates to the J2EEauthentication domain After changes have been made to the J2EE security realms, theserver must be restarted before those changes take effect
The command line realmtoolsupports the following options:
RealmTool Options -show -list realm-name -add username password group[,group]
-addGroup group -import certificate-file -alias alias -remove realm-name username
-removeGroup groupThe tool lacks the ability to list groups in the default realm, but it has the advantage ofworking without having to have the J2EE server up and running
The GUI interface is more functional and easier to use and is accessed via the “Tools -> Server_Configuration” menu in deploytool Figure 15.4 shows the main user configu-ration screen
Although the GUI interface is easier to use, it requires the J2EE server to be running.The server must be stopped and restarted for the changes to be recognized by your appli-cations
Trang 13Neither utility supports the ability to change a user’s password If a password is ten, the user must be deleted and re-created to define a new password
forgot-The default users provided with the J2EE RI server are shown in Table 15.1
T ABLE 15.1 Pre-Defined J2EE RI Users
guest guest123
Both utilities are intuitive to use For today’s work, you will need to add some sampleusers as defined in Table 15.2
T ABLE 15.2 Agency Case Study Users
juliet juliet Applicant winston winston Customer
F IGURE 15.4
Adding users with
deploytool
Trang 14You will need to add the groups for applicantand customeras well as the users shown
in Table 15.2 After making your changes, don’t forget to stop and restart the J2EE server
You must make these changes to your J2EE server if you want to use the example code provided on the accompanying CD-ROM.
Note
Security and EJBs
EJB security is determined either by the declarative entries added to the DD, the grammatic constraints coded into the EJBs, or a combination of both
pro-Ideally, EJB security should only use the declarative approach, but where declarativesecurity cannot represent the application’s requirements, security must be encoded in theEJB class The programmatic security is less portable and may restrict the way an appli-cation assembler can combine beans from different sources
Defining EJB Security
Defining security for an EJB involves
• Defining one or more roles to control access to different areas of your application
• Restricting access to EJBs and EJB methods according to the clients roles
• Mapping roles onto principals in the authentication domain
• Optionally adding programmatic authorization to Session and Entity beans
If you are using the J2EE RI, the security can be defined using deploytool Other J2EEenvironments may provide GUI tools similar to deploytoolor, if you are unlucky, youmay have to manually edit the DD to include the security requirements
In the rest of this section, you will use deploytoolto add security to the Agency casestudy You will see how extra information is added to the DD to define the securityrequirements
Defining Roles
There are three distinct roles with the simple Agencyapplication:
• Administrators that can modify the skills and location tables
• Customers who advertise jobs
• Applicants who advertise their locations and skills
Trang 15You may even decide that there are only two roles—administrators and clients (for want
of a better term) Clients can register their own skills or advertise jobs for other clients
While this is a perfectly acceptable model, it looses the differentiation between cants and customers
appli-Currently, there are no constraints on who can be a client and who can be a customer
However, in a real world job agency, it may become necessary to restrict who can beapplicants and customers Perhaps customers will be charged for applicants who matchtheir jobs, so they need to be validated before they can use your system
Having decided on your roles, you must add them to the DD Roles are added to JARfiles in your application If several EJBs are defined in the same JAR file, they can sharethe same roles EJBs in separate JAR files must define their own roles If the same rolename is used in different JAR files, it still represents a different role
Grouping related EJBs into a single JAR file is a good design philosophy because itallows related beans to share the same security roles
Now you will add security constraints to the Agency case study If you want to look atthe finished results of following the steps described in the rest of this section, you canlook at the agency.earfile in the exercisesdirectory for Day 15 (“Security”) on theaccompanying CD-ROM
If you want to add security to the Agency case study as you have developed it so far, start
up deploytooland open the agency.earfile in the Day 10 (“Message-Driven Beans”)examplesdirectory The Agencyapplication has three JAR files—one for the Sessionbeans, one for the Entity beans, and one for the Web interface Select the agencySessionbean and display the “Roles” page Use the Addbutton to add the three roles defined inTable 15.3 Figure 15.5 shows the screen after adding these roles
T ABLE 15.3 Agency Case Study Roles
Administrator Administers the skills and locations tables
Applicant Registers details to apply for jobs
Customer Advertises job details
Roles are defined in the <assembly-descriptor>component inside the <ejb-jar>tag inthe DD Listing 15.1 shows the entry created for the three roles you have just defined
Trang 16L ISTING 15.1 Security Role Entries in the DD
Defining the Security Identity
After the roles for a JAR file have been defined, you can restrict access to the methods of
an EJB In deploytool, select the AgencyBeanEJB and then the Security tab You willsee the screen shown in Figure 15.6
F IGURE 15.5
Adding security roles.
Trang 17The Security Identitysection at the top of the screen shows that authorization is trolled by the caller’s identity There are two options for security identity:
con-• Use the caller’s ID
• Use a defined role
In Figure 15.6, Use Caller ID is selected
The <security-identity>tag in the DD defines how access to an EJB is authorized
The tag is part of the <session>bean definition, and the <use-caller-identity>option
is shown in Listing 15.2
L ISTING 15.2 Security Identity Entries in the DD
1: <enterprise-beans>
2: … 3: <session>
Trang 1814: </security-identity>
15: … 16: </session>
17: … 18: </enterprise-beans>
The use of roles for the security identity is discussed in the “Using Roles as the SecurityIdentity” section later in this chapter
The lower part of the deploytoolSecurity page is the Role Referencessection, andthis is discussed in the section “Programmatic EJB Security”
Defining Method Permissions
The Method Permissionssection in the middle of the deploytoolwindow shown inFigure 15.6 lists the methods for the interfaces defined for your bean The radio buttonselects which interface is displayed (the default for the agencybean is the remote inter-face) Each bean method defines a row in a table, and the columns are the roles definedfor the JAR file By using the cells in this table, you can select which methods can becalled by each role
From Figure 15.6, you can see that the default access (the Availability column) to allmethods is All Users which is why, so far, you have been able to access all your applica-tion functionality regardless of any username you supplied when logging in to run theapplication
In the underlying DD, the method permissions are added to the <assembly-descriptor>tag The <method-permissions>tag associates one or more permissions with one ormore methods A permission is the name of a role specified with the <role-name>tag orthe empty tag <unchecked/>to show that access is unchecked (it is callable by allclients) A method is defined by the <method>tag that has three variants:
1 Authorize all methods in an EJB using a tag of the following form:
<method>
<ejb-name>EJBname</ejb-name>
<method-name>*</method-name>
</method>
where the * means all methods
2 Authorize a named method in an EJB using a tag of the following form:
Trang 19differenti-The <method>tag also allows a<method-intf>(method interface) tag for defining theinterface name if it is duplicated in the home and remote interfaces.
As an example, you could set all the methods in the agencybean to be accessible only
by the Administratorrole using the example in Listing 15.3
L ISTING 15.3 Method Permission Entries in the DD
"Tools->Descriptor Viewer”menu, you will see the method permission entries for theagency EJB, as shown in Figure 15.7
Trang 20Applying security is now just a matter of deciding which roles can call which methodsfor every EJB in your application In the agencybean, you can set the access permissions
as shown in Table 15.4
T ABLE 15.4 Agency EJB Authorization
Method Roles
removeLocation Administrator updateLocation Administrator deleteCustomer Administrator , Customer getPrimaryKey none
getAgencyName All
getHandle none
select Administrator addLocation Administrator remove All
Trang 22Authorization is only required for the methods in the remote interface Some of themethods (such as getSkills()) can be accessed by all users, so the home interfacemethods (such as create()) must also be available to all users Consequently, the defaultauthorizations are appropriate for the home interface.
This is a slightly contrived example used to illustrate the purpose of roles within anapplication In a real world job agency, you would probably only want administrators tocreate customers However, you would probably be comfortable with allowing any user
to register themselves as an applicant There would be no need to differentiate betweenapplicant clients and customer clients In the “Programmatic EJB Security” section later
in this chapter, you will see how the Agency case study can use programmatic security toprovide a more realistic authorization mechanism
The remaining three EJBs in the Agencyapplication must also have method permissionsdefined These are much easier to specify
The RegisterEJB must have all the home and remote interface methods accessible tothe Administrationand Applicantroles only
The AdvertiseEJB and AdvertiseJobEJB must have all the home and remote interfacemethods accessible to the Administrationand Customerroles only
After all these method permissions have been defined, the application is now ready forthe deployer to map the principals on to the roles you have just defined If you haven’talready done so, it is worth saving your agency.earfile at this point just in case some-thing goes wrong later
Just before you learn how to do this with the J2EE RI deploytool, you should considerthe security of the Entity beans in the dataJAR file How can the Entity beans beaccessed, and what authorization is required?
The Entity beans are only ever accessed via the Session beans Consequently, by ing authorization to the Session beans, you have also protected the Entity beans Shouldyou redesign the application so that the Entity beans are exposed to client code (maybe
apply-by accessing the beans directly from a Web page), you will need to change the methodpermissions for all of the Entity beans
By designing access to Entity beans via the Session beans, you have simplified thedesign of the security features This is one of the advantages of not exposing Entitybeans to client code
Mapping Principals to Roles
A developer or assembler in the EJB development lifecycle undertakes the process ofdefining the roles and method permissions The process of mapping principals to roles isvery much a deployer function
Trang 23The exact mechanism of mapping principals onto roles is not defined in the EJB cation (at least not yet) There are no tags defined in the DD; instead, each J2EE serverdefines its own mechanism for mapping principals to roles The J2EE RI defines a pro-prietary XML file (sun-j2ee-ri.xml) that is stored in the Enterprise ApplicationResource (EAR) file This file is maintained by using deploytooland deployed with theEJB components
specifi-The deploytoolmaps principals to roles at the application level To map the roles for theAgency case study, you must run deploytooland select the Agencyapplication contain-ing the JAR file in which you defined the roles Select the Security tab and you will see awindow similar to the one shown in Figure 15.9
or groups in the authentication domain
The Agency case study requires the role mappings shown in Table 15.5
T ABLE 15.5 Case study Role Mappings
Administrator j2ee
Trang 24After defining the role mappings for the Agency case study, you can deploy and test yourchanges by using the GUI client code in the Day 15 “examples” directory.
If you run the example GUI clients from Day 15 on the accompanying ROM, you will see an error message and a stack trace prior to being prompt-
CD-ed for a username and password The last few lines of the error are java.lang.NullPointerException
No local string for enterprise.deployment.unabletoloadtld Unable to load TLD WEB-INF/agency.tld
java.lang.Exception: parsing error: null This error can be ignored because it is related to the TLD descriptor used by the custom tag libraries of the Web interface (see Day 14 “JSP Tag
Libraries”) This error appears to be a problem with Sun Microsystem’s J2EE
RI and does not affect the functionality of the Web interface to the Agency case study (you may have seen this exception when working on the exam- ples and exercise for Day 14).
Note
Because the j2eeuser has unrestricted access, you can test all the functionality if youlog in as j2ee(password j2ee) If you log in as an applicant, such as romeoor juliet,you will only be able to use the applicant registration functionality Similarly, customerssuch as winstonand georgewill only be able to access job advertisement functionality Any attempt to access unauthorized functionality results in a J2EE vendor-specificexception
Using Roles as the Security Identity
An alternative to propagating the caller’s security identity is to define a bean as using aspecific role This is achieved using deploytoolby selecting the Run As Specified Roleoption and selecting the appropriate role from the list of roles The developer or assem-bler determines whether to use the caller ID or a specific role for a bean
The <run-as>tag is used to define the role for beans that run with a specified role, asshown in Listing 15.4 The role name is defined in the <role-name>tag and must specifythe name of a role defined in the <assembly-descriptor>of the <ejb-jar>definition
L ISTING 15.4 Run-As Specified Role in the DD
1: <enterprise-beans>
2: … 3: <session>
4: <display-name>AgencyBean</display-name>
5: <ejb-name>AgencyBean</ejb-name>
Trang 2519: … 20: </enterprise-beans>
Defining the bean to run using a specific role meets the developer’s requirements, but thedeployer must also map the role onto a principal in the target security domain for it to beeffective The actual method of defining the principal for the “Run as role” security iden-tity is vendor specific The J2EE RI adds an entry to the sun-j2ee-ri.xmldescriptor file
To set the required principal using deploytool, click the Deployment Settingsbuttonand choose the role from the available list in the pop-up window Figure 15.10 shows thej2eeuser selected as the principal for a bean that defines the run as role as
Trang 26permis-Any client with access to the bean automatically gets the appropriate security permissions;therefore, it is imperative that only authorized clients can use the bean.
The “Run as role”bean is often a helper Session bean used as an adapter (or wrapper)around other J2EE components, such as Entity beans
When using the “ Run as role ” security identity, it is usual to define all bean methods as having <unchecked/> access allowing access to all roles If checked access is applied to the methods, the run as role must be allowed; otherwise, the method can never be called.
Note
Programmatic EJB Security
If simple declarative security constraints cannot express all of the security policy rules,the developer must resort to adding security into the EJB code
The javax.ejb.EJBContextinterface defines two methods for supporting programmaticsecurity:
• java.security.Principal getCallerPrincipal()returns an object defining theprincipal calling the method The Principalclass defines a getName()methodthat returns the name of the principal The getCallerPrincipal()method neverreturns null
• boolean isCallerInRole(String roleName)returns trueif the caller of themethod is in the role passed as a parameter
These two methods allow the developer to use the client security identity to enable ordisable EJB functionality
Of the two methods,isCallerInRole()is considered portable because the developerdefines the role name used in the code, and the deployer (or assembler) maps this rolereference onto a real role This allows the developer to write the code without knowingthe real role names defined for the application
The getCallerPrincipal()method is considered non-portable because the principalname used is dependent on the authentication mechanism used by the target J2EE server
In practice, as long as principal names are not defined as string literals in the Java code,the getCallerPrincipal()method can be used in a portable manner
Using the Agency case study as an example, you will now implement a real-world solution
to authorizing access to your application Instead of identifying administrators, applicants,and customers, you can simply differentiate between administrators and all other clients
Trang 27Some functionality would be restricted to administrators only (creating new skills, for ple), but most functionality would be available to all clients
exam-Client-specific authorization could be implemented so that
• Any client can register as an applicant, but the applicant name must be the same asthe client's principal name
• Any client can register an customer, but the customer name must be the same asthe client's principal name
• Registered applicants or customers can only remove their own details from the system
• Registered applicants or customers can only log in to access their own data in thesystem
• Administrators have unrestricted access to the system
Listing 15.5 shows the ejbCreate()method of the AdvertiseSession bean that hasbeen modified to prevent a client from accessing data that does not match his or her prin-cipal name Administrators are permitted to access data for any client
L ISTING 15.5 The ejbCreate() Method from agency.AdvertiseBean.java
1: public void ejbCreate (String login) throws CreateException { 2: try {
3: if (ctx.isCallerInRole(“admin”) ||
4: ctx.getCallerPrincipal().getName().equals(login)) { 5: customer = customerHome.findByPrimaryKey(login);
6: } 7: else 8: throw new CreateException
➥(“Customer name does not match principal name”);
9: } 10: catch (FinderException ex) { 11: error (“Cannot find applicant: “+login,ex);
12: } 13: }
The revised ejbCreate()method checks if the caller is not in the adminrole and rejectsthe operation if the customer login name does not match the caller’s principal name
The parameter to the isCallerInRole()method is a role reference, and this must bemapped onto a real role by the application deployer Figure 15.11 shows the Advertisebean security page in deploytoolwith the role reference defined
F IGURE 15.11
Trang 2815.11, the coded role of adminis mapped onto the real role of Administrator The rolereferences for a bean are defined in the bean’s entry in the DD with the
<security-role-ref>tag, as shown in Listing 15.6
L ISTING 15.6 Role References in the DD
1: <enterprise-beans>
2: … 3: <session>
12: <role-name>admin</role-name>
13: <role-link>Administrator</role-link>
14: </security-role-ref>
15: … 16: </session>
17: … 18: </enterprise-beans>
Defining a role reference.
In Figure
Trang 29In addition to the change to the AdvertiseEJB, the AgencySession bean must also beupdated to ensure non-administrator clients can only create or delete customers with alogin name equal to the client’s principal name (see Listing 15.7)
L ISTING 15.7 The Create and Delete Customer Methods from agency.AgencyBean.java
1: public void createCustomer(String login, String name, String email)
➥throws DuplicateException, CreateException{
2: try { 3: if (ctx.isCallerInRole(“admin”) ||
4: ctx.getCallerPrincipal().getName().equals(login)) { 5: CustomerLocal customer =
➥customerHome.create(login,name,email);
6: } 7: else 8: throw new IllegalArgumentException(
➥”Cannot create a customer with a different name to the principal name”);
9: } 10: catch (CreateException e) { 11: error(“Error adding Customer “+login,e);
12: } 13: } 14:
15: public void deleteCustomer (String login) throws NotFoundException { 16: try {
17: if (ctx.isCallerInRole(“admin”) ||
18: ctx.getCallerPrincipal().getName().equals(login)) { 19: customerHome.remove(login);
20: } 21: else 22: throw new IllegalArgumentException(
➥”Cannot delete a customer with a different name to the principal name”);
23: } 24: catch (RemoveException e) { 25: error(“Error removing customer “+login,e);
26: } 27: }
The code uses the java.lang.IllegalArgumentExceptionto show the error when thecustomer login name does not match the principal name
The adminto administratorrole ref must also be added for the Agencysession EJB
The ejbCreate()method in agency.AdvertiseJobBeanshould also be updated in asimilar manner to the ejbCreate()method in agency.AdvertiseBean, and the admintoadministratorrole ref created for the AdvertiseJobsession EJB
The revised application can now be deployed and tested
Trang 30So far, the security constraints have been added to the Session beans An alternativeapproach would have been to add the authorization code to the Entity beans.
The advantage of adding security to the Entity beans is that security is enforced at thedata access level, preventing a badly written client from bypassing the security or violat-ing the data integrity Security is also applied uniformly across all clients and obviatesany need for duplicated code to enforce security
The disadvantage of applying the security within the Entity beans is that it confuses therole of the Entity bean An Entity bean represents persistent data but should not enforcebusiness rules (other than those required to ensure data integrity) Adding security con-trols to an Entity bean is adding business rules to the data access layer
The Agency case study implements the business rules in the Session beans and tently uses the beans in the GUI client and the Web client For the Agency case study, theSession bean is the logical place to enforce the security business rules
consis-Security in Web Applications and Components
The Web security features of J2EE use the same model as the EJB security Security isimplemented using declarations in the deployment descriptor and programming in theWeb pages Authorization is enforced using roles and principals in the same manner asEJB security
The key concepts for the Web security model are
• Single login—A client is only required to authenticate itself once to access all Web
pages in the same realm The Web server defines security realms, and the deployerdecides to which realm each Web application belongs Each realm can use a differ-ent authentication mechanism (effectively, a different collection of usernames)
• Spans multiple applications—An authenticated client should be able to use Web
pages from different Web applications without having to login for each application
• Associated with session—The security credentials must be associated with the
servlet session, so that each servlet or JSP can access the credentials when requiredfor programmatic authorization
The J2EE Web security specifies requirements for client authentication as well as rization for Web applications
Trang 31Web Authentication
The J2EE 1.3 specification does not explicitly specify a Web authentication mechanism,but uses the Servlet 2.3 specification that defines four mechanisms for authenticatingusers:
• Basic HTTP
• HTTP Digest
• Forms based
• HTTPS ClientThe Servlet 2.3 specification can be found on the Sun Microsystems’ web site athttp://java.sun.com/products/servlet/download.html
Basic HTTP Authentication
The HTTP protocol defines a simple authentication system where the Web server canrequest the client to supply a username and password The Web client obtains the user-name and password of the user and returns them to the Web server for authentication
The popular Web browsers display a simple login form for the user to provide cation information
authenti-The username and password are returned to the Web server using a simple encodingscheme Basic HTTP authentication is simple and effective, but it does not provide confi-dentiality because the username and password are easily obtained by hackers that canmonitor network traffic In reality, hackers will find it almost impossible to monitor net-work traffic outside of their own organization However, malicious company employeeswith the requisite knowledge and software will be able to monitor internal networks
HTTP Digest Authentication
HTTP Digest authentication works in a similar manner to Basic HTTP authenticationexcept that the username and password are returned in an encrypted form The encryptedusername and password are more secure against illicit monitoring of network traffic
HTTP digest authentication is not required by the Servlet 2.3 specification because it isnot widely supported by Web clients at the present time
Forms-Based Authentication
J2EE Web applications can specify their own forms-based authentication This is similar
to basic HTTP authentication, but a form is supplied by the application when a user has
to be authenticated The application can supply an authentication form with the samelook and feel as the other Web pages in the application, instead of using the simple formprovided by a Web browser
Trang 32HTTPS Client Authentication
This is the most secure form of authentication because it requires the client to identifyitself using a digital certificate Client authentication is usually implemented by usingSSL and is supported by the common Web browsers This is a large subject area, andthere is insufficient space for it to be covered in today’s lesson
Configuring J2EE RI Basic Authentication
To illustrate the basic features of J2EE Web security, you will need to configure the Webinterface to the Agency case study to authenticate users You will use basic HTTP authen-tication because it is the simplest mechanism to configure for your Web application.Start up deploytool, open the agency.earfile in today’s “examples” directory andselect the Web application you developed on Day 13, “JavaServer Pages” and Day 14(called web) Choose the Security tab and select Basic from the list of options in the UserAuthentication Method section on the form Figure 15.12 shows the Basic authenticationmechanism being selected from the list of choices
F IGURE 15.12
Defining Basic HTTP Web authentication.
The Settings button is used to configure additional features for each authenticationmethod The only configurable property for Basic HTTP authentication is the realm inwhich to authenticate the user The J2EE RI only provides one realm, called default, foruse with Basic HTTP authentication Although the J2EE RI defines a second realmcalled certificate, but this is for use with HTTPS (SSL)-based client authentication
Trang 335: <auth-method>BASIC</auth-method>
6: <realm-name></realm-name>
7: </login-config>
8: … 9: <web-app>
Defining the authentication mechanism does not force the client to authenticate itself forpages in the Web application You will need to add declarative security constraints for theWeb pages that have to be protected as discussed in the “Declarative Web Authorization”
section later in this chapter When the user accesses one of the protected pages, the
serv-er will use Basic HTTP authentication to obtain the usserv-ername and password and validatethese credentials against the default security realm
Declarative Web Authorization
Authorized access to Web pages is based on the URL of the Web page By default, allpages are unprotected, but the DD for a Web application can define security constraints
to force a client to authenticate itself before accessing the protected pages
Authorization is based on roles and constraints A Web application defines the rolesrequired to access different functionality within the application One or more constraintscan be defined to authorize access to an individual page or a group of pages based on theroles defined for the application
As with EJB security roles, the deployer must map the role references used in the DDonto principals defined in the target authentication domain
Configuring J2EE RI Declarative Web Security
Web application roles are defined in deploytoolusing the Roles page for the Web cation To contrast with the example of EJB security that identified applicants and cus-tomers as separate roles, the Web application will treat all potential applicants and cus-tomers as clients You will configure two roles for your Web application, as shown inTable 15.6
Trang 34appli-T ABLE 15.6 Agency Case Study Roles
Role Description
Administrator Administers the skills and locations tables
Client A potential applicant or customer
Figure 15.13 shows the configured roles for the Agency case study
con-• A list of roles that are authorized by this constraint
• One or more Web resource collections that define the Web pages protected by thisconstraint
• A list of protected Web pages each defined by a URL pattern and the HTTPrequest names GETand POST
Constraints are applied to the Web application rather than an individual Web component
In deploytool, select the Web application (called web) and the Security tab (this page isshown in Figure 15.14 after you have made the changes discussed in the rest of this sec-tion)
Trang 35Before adding any constraints, you must decide which parts of the Web application must
be protected The main portal page (agency.jsp) should be accessible to all usersbecause this page is used to create new customer or applicant details Existing customersalso use this page to access their data
Functionality for customers, jobs, and applicants should be protected so that only ticated clients can use those pages The administration page (admin.jsp) for maintainingskill and location lists should only be accessible to authenticated clients in the
On Day 13, you chose aliases for your Web pages to simplify the definition of the
securi-ty constraints All of the customer functionalisecuri-ty uses aliases of the form /customer/…;similarly, applicant functionality is /applicant/… This naming scheme can be usedwhen applying authorization to Web pages
The following steps will set up the first of these constraints:
1 In the Security Constraints section, click Add to add a new constraint accept thedefault name of SecurityConstraintbecause changing it has no effect (the name
is not saved in the DD)
2 In the Authorized Roles section, click Edit and add the Client and Administratorroles by using the pop-up screen
3 In the Web Resource Collections section, click Add to add a new resource bundleand rename this to Customers
4 Also in the Web Resource Collections section, click Edit to add the protected URLpatterns You will need to protect the individual page names (in the next step) andthe aliases you defined when deploying the application
5 On the pop-up screen Edit Web Resource Collection page, add the following tomer related JSP pages to the collection:
cus-• advertise.jsp
• createCustomer.jsp
• createJob.jsp
• deleteCustomer.jsp
Trang 367 Click OK to save your changes.
8 Back on the Security page, check the GETand POSTboxes to ensure all HTTPrequests to your selected pages are authorized Your screen will now be similar tothe one shown in Figure 15.14
Trang 37It only takes one determined hacker to find that the URLadvertise.jsp?customer=winstonworks and your security mechanism has been cir-cumvented unless you protect the individual JSP pages as well as the URL pattern cus- tomer/*
Where security is concerned, it is better to err on the side of caution and protect thing rather than leave a small loophole for a hacker to exploit
every-You must now add a second Resource Collection for protecting access to the applicantregistration functionality Create a new Resource Collection (call it Applicants) and pro-tect the URL Pattern /applicant/*and the following JSP pages:
• register.jsp
• createApplicant.jsp
• deleteApplicant.jsp
• updateApplicant.jspThe last constraint you need is to protect the administrative functionality on theadmin.jsppage Because this requires a different set of roles, you will need to
1 Create a new Security Constraint (it will be named SecurityConstraint1)
2 Add the Administrationrole to this constraint
3 Create a new Web Resource Collection and call it Administration
4 Add the URL pattern /admin/*and the following pages to this collection
• none There are no network security requirements
• integral The transfer of the data between server and client must guarantee thatthe data will not be changed
Trang 38• confidential The transfer of the data between server and client must guaranteethat the data cannot be observed.
In practice, choosing an option other than nonewill usually necessitate the use of SSL.The default value of nonewill suffice during your study of J2EE security
After you have defined all of these changes, the DD will have the
<security-constraint>entries, as shown in Listing 15.9
L ISTING 15.9 Web Security Constraints in the DD
Trang 39cus-You must log in with the same name as the customer (winston) you selected from the list
on the agency.jsppage If you chose any other login name, the EJB programmatic rity you added to the advertiseSession bean will throw an exception because the cus-tomer name does not match your principal name
secu-In the next section, you will use programmatic Web security to remove the need for anexisting customer or applicant to select his or her name from a list
Programmatic Web Authorization
Web applications that are security aware use three methods in the HTTP request object toaccess the authenticated client’s security information.:
• boolean HttpServletRequest.isUserInRole(String role) Returns trueifthe client is in the role passed as a parameter
• Principal HttpServletRequest.getUserPrincipal() Returns a ty.Principalobject representing the client’s principal Unlike the
java.securi-EJBContext.getCallerPrincipal()method, this method can return nullif theclient has not been authenticated
L ISTING 15.9 Continued
Trang 40• String HttpServletRequest.getRemoteUser() Returns the principal name ofthe client or nullif the client has not been authenticated.
Adding Programmatic Web Security to the Case Study
The Agency case study does not need any programmatic security additions The nent Session beans (advertiseand register) ensure that authenticated clients can onlyaccess his or her own details However, the user interface can be improved by makinguse of the principal information from the client authentication
compo-The Agency case study main page (agency.jsp) presents the user with a list of tomers to select from and a small form for creating a new customer There is no need forthe user to be given a list of customers if an authentication mechanism is used Theuser’s login name can be used to the appropriate customer data The customer section ofthe simplified form is shown in Listing 15.10
cus-L ISTING 15.10 Customer Options in agency.jsp