Web Security  IntroductionOur lesson on web programming would not be complete without a discussion on how tosecure our app...
Generating the certificate private keyIt is easier to perform our next set of operations in the same directory that the se...
keytool -import -v -trustcacerts-alias keyAlias-file certificateFileName-keystore cacerts.jks-keypass keypassword         ...
Figure 2
The above screen shows the results of clicking on the New button with sample valuesalready filled in. The values that may ...
Lets look at the top 10, and see how we can safeguard our applications from them.   Unvalidated InputAll web applications ...
users or functions. IDs can be guessed however, and if a hacker can make use of        them to mimic an authorized user, t...
Cross site scripting happens when someone makes use of another web application tosend malicious scripts to another user. T...
select * from someTable where someField=jedi AND true; DROP DATABASE;The first statement would always be accepted due to t...
Also, it is better to make use of external encryption algorithms instead of making one foryour own. Make sure that the alg...
•   Accessible administrative or debugging functions.•   Overly informative error messages.•   Misconfigured SSL certifica...
Upcoming SlideShare
Loading in...5

MELJUN CORTES Jedi course notes web programming-lesson11-web security


Published on

MELJUN CORTES Jedi course notes web programming-lesson11-web security

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

MELJUN CORTES Jedi course notes web programming-lesson11-web security

  1. 1. Web Security IntroductionOur lesson on web programming would not be complete without a discussion on how tosecure our applications. Nifty features, great usability, and maintainability mean little ifour application were to fail due to a lack of trusting web clients.In this lesson, we will learn how to secure communications between the server and clientusing Session Socket Layer. We will also look at the top 10 secuity flaws in any webapplication and learn measures to avoid them. SSLSSL has become the de facto standard within the community to secure communicationsbetween clients and servers. It stands for Secure Socket Layer; it is a protocol layer thatinterposes itself between the standard TCP/IP layer and higher, application-levelprotocols such as HTTP. It allows the server to authenticate itself to the client andthereafter encrypts the communication channel.A full-fledged discussion on the mechanics of SSL operation is outside of the scope ofthis material. For our purposes, it is enough to know that usage of this technologyguarantees a secure channel between the server and the client. Confidentiality is furtherpreserved due to the tamper-detection measure automatically included as part of theSSL. Enabling SSL in our applicationTo enjoy the benefits of SSL with our application, we need in configuring the serverenvironment it runs in to accept SSL connections. Different servlet containers havedifferent ways of doing this. Here, we will learn how to configure the Sun ApplicationServer 8.1. . CertificatesOne of the first things that we need to configure our server for SSL-basedcommunications is a valid security certificate. Think of a certificate as something like apassport – it identifies the holder to others and contains other important information.Certificates are usually issued by Certification Authorities (CAs). A CA is like a passportoffice – it validates the certificate owners identity and signs the certificate so that itcannot be forged or tampered with.There are several well-known Certification Authorities, most popular of which is Verisign.It is the administrators decision as to which CA will provide the server with a certificate.In the absence of a certificate from a trusted CA, a temporary one can be created usingtools included within the Java 1.4 SDK. Take note however that discerning clients willmost likely not continue with transactions that require high confidentiality once theydetect that the certificate we use is one that we have created for ourselves.
  2. 2. Generating the certificate private keyIt is easier to perform our next set of operations in the same directory that the serveruses to store its certificates. This can be found at %APP_SERVER_HOME%/domains/domain1/config.Go to the specified directory using the command line. From there, perform the followingcommand:keytool -genkey -alias keyAlias-keyalg RSA -keypass keypassword-storepass storepassword-keystore keystore.jks • keyAlias – the alias or ID that this certificate will be referred to. • keypassword – the password for the private key to be used for encryption. • storepassword – the password for the keystore.It may be a bit confusing to see a need for two passwords in the creation of a newcertificate. However, lets keep in mind that all key entries reside in what is called akeystore. A keystore can hold one or more keys. keypassword then refers to thepassword of the private key our certificate will use, while storepassword refers to thepassword of the keystore that will contain it. The directory we are operating on alreadyhas a keystore file with an existing password though, so we will need to set storepass toits value: changeit.This password can be changed later on, using keytool:keytool -keystore keystore.jks -storepass newPasswordCreating the certificateAfter we have generated the key that will be used by our certificate, we can now createthe certificate file itself:keytool -export -alias keyAlias-storepass storepassword-file certificateFileName-keystore keystore.jksThe previous line tells the keytool utility to generate the certificate file using the privatekey referred to by keyAlias which is contained in the keystore.Managing the certificateFor the application server to recognize the certificate we have just created, we need toadd it up to the list of trusted certificates. The server contains a file named cacerts.jkswhich contains such certificates. We can add ours into this file by using the keytool:
  3. 3. keytool -import -v -trustcacerts-alias keyAlias-file certificateFileName-keystore cacerts.jks-keypass keypassword . Creating a secure HTTP listenerAfter we have successfully created a certificate and registered it for use in theapplication server, we can now create an HTTP listener that can make use of thecertificate. Having such a listener sets aside a port on our server machine which can beused for secure communications.To do this, first login to the administration console. On the right, expand the tab namedConfiguration, then expand HTTP Service: Figure 1Next, click on the link named HTTP Listeners, and on the pane to the right, click on theNew button.
  4. 4. Figure 2
  5. 5. The above screen shows the results of clicking on the New button with sample valuesalready filled in. The values that may change are the name of the listener and the portwhich will be used according to the administrators preferences.Perform a server restart. Our new configuration can be tried out by accessing thefollowing address:https://serverAddress:listenerPort/index.htmlTo utilize secure communications between the client and the server, redirect the user tothe secure listener port when accessing your application. The Top 10 Security Flaws in Web ApplicationsThe Open Web Application Security Project (OWASP) is an open source project funded bya non-profit entity that aims to find the causes of unsecure software and find measuresagainst them. It has released a list of the top 10 security flaws of web applicationsaccording to their findings, and recommends that any web application be made secureagainst them as a minimum standard of security.
  6. 6. Lets look at the top 10, and see how we can safeguard our applications from them. Unvalidated InputAll web applications retrieve data from the HTTP request made by the user and make useof that data to perform its operations. Hackers can manipulate any part of the request(the query string, cookie information, headers) to try to bypass a sites securitymechanism or normal control flow.There are different kinds of attack that relates to this problem. They are discussed inmore detail later: • Cross site scripting • Buffer overflows • Injection flawsThere are some things to take note of when handling our applications validation. First, itis not enough for any web application to rely only on client-side scripting. This kind ofscripts usually stops form submission when it detects that the input is invalid. However,it does nothing to prevent hackers from generating their own HTTP requests independentof any form. Using only client-side validation still leaves web application wide-open toattacks.Second, some applications use a "negative" approach in validation: they try to detect ifthere are any harmful elements in the request parameters. The problem with this kind ofapproach is that it can only protect against a limited set of possible attacks. Only theattacks recognized by the validation code are prevented. There is an increasing numberof methods hackers can use to bypass security through unvalidated input; it is possiblethat a new method not recognized by the application can bypass this kind of validationand wreak havoc. It is always better to make use of a positive approach: define a formator pattern for allowable values and ensure that the received input conforms to it. Broken Access ControlThere are a lot of applications that categorize its users into different roles and providedifferent levels of interaction or different kinds of content for each of those categories.As a simple example, most applications define a user role and an admin role: only theadmin role is "authorized" to access pages or perform actions that are integral to theadministration of the site.The problem is that some applications do not effectively enforce this authorization. As anexample, some programs only make use of a checkpoint within the usual screen flowwhich only selected users can pass: to proceed further, the user must prove himself tobe authorized with the use of a user name and password. However, they do not enforcechecks once past this checkpoint: once a user skips the "login" page, they are free toperform operations.Other problems related to access control include: • Insecure Ids – some sites make use of some sort of id or key to refer to its
  7. 7. users or functions. IDs can be guessed however, and if a hacker can make use of them to mimic an authorized user, then the site is wide open to attack. • File permissions – most web and application servers rely on an external file to provide themselves with a list of authorized users and which resources they can and/or cannot access. If this file is readily accessible to the outside, then hackers can freely modify it to include themselves in the list of allowed users.What are the steps that we can do to fix this problem? For the earlier example, we candevelop filters or similar components that can be applied to sensitive resources. Thesecan ensure that only authorized users can gain access. To protect ourselves frominsecure Ids, we should develop the application such that it does not rely on the secrecyof any Ids to provide it with access control. To address the problem of the permissionfile, these files must be placed in locations inaccessible to web browsers and furthermarked in the operating system level as being available only to specific roles. Broken Authentication and Session ManagementAuthentication and session management refers to all aspects of handling userauthentication and the management of active sessions. There are several areas thoughthat can be overlooked in this area that expose vulnerabilities to the system: • Password strength – our application must maintain a minimum level of password strength, which can be checked by looking at the length of the password and its complexity. Take for example an application that lets its newly registered users create their own passwords: it must not allow passwords of 3 to 4 characters-length or simple words or phrases that can be guessed by hackers. • Password use – our application must enforce a maximum number of attempts that a user can use to login to the system within a given time period. This protects our application from brute force attacks where hackers repeatedly attempt to login into the system. Also, failed log-in attempts should be logged to provide administrators an indication and warning of possible attacks. • Password storage – passwords must never be stored as is within our application. Whether they be stored in an external database, a flat file, etc, they must be recorded in an encrypted format. This makes sure that such sensitive information does not spread in the case of a successful breach within the application.Another related issue: passwords must never be hardcoded in any source code. • Session ID Protection – servers typically use session Ids to identify a user as participating in a session. However, if this session ID could be retrieved by someone in the same network, that person can then pass himself off as the client.One of the best ways in preventing session Ids from being retrieved by someone in thesame network is to place communications between the server and client in an SSL-protected channel. Cross Site Scripting
  8. 8. Cross site scripting happens when someone makes use of another web application tosend malicious scripts to another user. This can be done by embedding active content(such as JavaScript, ActiveX objects, Flash) into a request which generates HTML outputthat can be seen by another user. Once other users access these content, their browsersdo not know that they are not to be trusted.One of the best ways in preventing cross site scripting attacks is to rigorously validate alldata coming in from user requests (headers, cookies, user parameters, etc.). A negativeapproach should not be used: trying to filter out all forms of embedded active content isnot a a hundred percent effective. Buffer OverflowsAttackers can use buffer overflows to corrupt the execution stack of a web application.They are able to do this by sending in carefully crafted requests that make the serverperform arbitrary code.Buffer overflow problems are usually difficult to detect and are difficult to exploit byhackers. However, attackers still have managed to identify this kind of vulnerability in anumber of products. Thanks to the design of the Java environment though, applicationsrunning within a J2EE server is immune to these kinds of attack.To ensure our safety though, it is always best to constantly monitor the availability ofpatches and bug reports for the server products that we use. Injection flawsOne popular type of vulnerability are injection flaws, where hackers can send in or"inject" calls to the operating system or to external resources such as databases.One common injection flaw is SQL injection. Take into account the following URL:http://someServer/someApp/someAction?searchString=jediThe above is a possible URL generated by an application from a form which searches itsdatabase for a key named jedi. Implementations which do not validate their input wouldmost likely just have the following SQL code:select * from someTable where someField=valuewhere value is the value of the searchString parameter directly retrieved from the HTTPrequest.What if, for example, some hacker directly input the following URL:http://someServer/someApp/someAction?searchString=jedi%20AND%20true;%20DROP%20DATABASE;The SQL query that would then be generated would be something like:
  9. 9. select * from someTable where someField=jedi AND true; DROP DATABASE;The first statement would always be accepted due to the AND true clause in the wherestatement. The second statement would then execute, doing a lot of damage in ourapplication.This is basically an attack made possible through unvalidated input. Aside fromrigorously validating the information from the users request, there are two otherprecautions that we can take: • Instead of using simple SELECT, INSERT, UPDATE, and DELETE statements, create functions that perform their functional equivalent. Functions have the benefit of treating their parameters as data, instead of executable content. They also require their parameters to be in the specific type declared. These provide a significant amount of protection against SQL injection, though validation still must be performed. • Provide the application only the minimum amount of privileges that it needs to perform its functionality. For example, if the application is primarily an application to view data, do not give it INSERT, UPDATE, or DELETE privileges. Do not let the web application access the database using its admin account. This can minimize the damage that hackers can do. Insecure StorageWeb applications usually need to store sensitive information such as passwords, creditcard information, and others. Due to their sensitive nature, these items are usually (orshould be) encrypted to prevent casual access. However, such encryptionimplementations are sometimes weak and still vulnerable to persistent attempts.Here are some areas where mistakes are commonly made: • Failure to encrypt critical data. • Insecure storage of keys, certificates, and passwords. • Improper storage of secrets in memory. • Poor source of randomness. • Poor choice of algorithm. • Attempting to invent a new encryption algorithm.Consider the following scenario: there exists an application which, in its modelling of theusers state and attributes, included the password as part of its User object. However,the application stores this User object into session after the user has logged in as amechanism for further authorization. The problem with this scenario is that the passwordcan now be easily retrieved by someone who manages to hack into or share the userssession.One good policy to avoid improper storage of sensitive information is to not store themin the first place: do not model the password as an attribute of the class representingthe user if the said class needs to be stored anywhere in the application. Instead ofencrypting a users credit card number, simply ask them for it each time that they needit.
  10. 10. Also, it is better to make use of external encryption algorithms instead of making one foryour own. Make sure that the algorithm that you will use has been subject to publicscrutiny and has proven itself to be reliable. Denial of ServiceDenial of service refers to a malicious attack made by hackers that makes use ofmultiple concurrent requests to the server. Due to the sheer number of such requests,the server becomes swamped and is then unable to service other users.DoS attacks do more than just consume bandwidth leading to the server. They can alsoconsume important limited resources such as internal memory, database connection,CPU cycles, threads, and/or application specific resources.It is generally very difficult to completely protect our application from this kind of attack,as there is no 100% fool-proof solution. A good rule of thumb though is to limit thenumber of resources allotted to a user to the bare minimum required. It can also be agood idea to establish load quotas which dictate just how much load a user can put inyour system.An example of this limiting of resources is a common feature in most bulletin boardimplementations. They limit a user to performing search operations only once every 20seconds. This makes sure that the user cannot consume a large portion of the databaseconnections available.Another possible solution is to design your web application such that unauthorized usershave little to no access to content that will require access to the database or otherexpensive resources. Insecure Configuration ManagementUsually the group developing the application is different from the group responsible foradministering to the site hosting the application. Unfortunately, there is a limit to theamount of security that can be handled from within the application only: server securityconfiguration also plays a large part in determining how secure our application can be.Improper configuration on the server side can bypass all efforts of the developers tosafeguard their application.Here are a couple of server configuration errors that prove to be problematic: • Unpatched security flaws in the server software – administrators are not aware of current releases in security patches for the server. • Server security flaws that allow permit directory listing and/or directory traversal attacks. • Unnecessary backup or sample files, including scripts, applications, configuration files, and web pages. • Improper file and directory permissions. • Unnecessary services such as remote administration and content management are left enabled. • Default accounts with default passwords.
  11. 11. • Accessible administrative or debugging functions.• Overly informative error messages.• Misconfigured SSL certificates and encryption settings.• Use of self-signed certificates to achieve authentication.• Use of default certificates.• Improper authentication with external systems.