Translate

Wednesday, December 19, 2012

Ten Things You Can Do With Spring Security

Source: http://www.captaindebug.com/2012/11/a-list-of-things-you-can-do-with-spring.html

Ten Things You Can Do With Spring Security

One

You can specify the authorisation provider of your choice in your Spring XML config file. You do this by configuring anauthentication-manager as defined in Spring’s http://www.springframework.org/schema/security/spring-security-3.1.xsd schema. The simplified authentication-manager element definition looks something like this:

<xs:element name="authentication-manager">
 <xs:complexType>
  <xs:choice minOccurs="0" maxOccurs="unbounded">
   <xs:element name="authentication-provider">
    <xs:complexType>
     <xs:choice minOccurs="0" maxOccurs="unbounded">
      <xs:element ref="security:any-user-service"/>
      <xs:element name="password-encoder">...</xs:element>
     </xs:choice>
     <xs:attributeGroup ref="security:ap.attlist"/>
    </xs:complexType>
   </xs:element>
   <!-- This is BIG -->
   <xs:element name="ldap-authentication-provider">...</xs:element>
  </xs:choice>
  <xs:attributeGroup ref="security:authman.attlist"/>
 </xs:complexType>
</xs:element>

This means that, for example, you can use any number of authentication providers including basic authentication and JDBC authentication as shown in the snippet below:

<authentication-manager alias="authenticationManager">
  <authentication-provider>
   <user-service>
    <user authorities="ROLE_GUEST" name="guest" password=""/>
   </user-service>
  </authentication-provider>
  <authentication-provider>
   <jdbc-user-service data-source-ref="dataSource"/>
  </authentication-provider>
 </authentication-manager>


Two

You can configure authorisation rules in your Spring XML file by linking URLs to user roles using the intercept-url element. The intercept-url element is a child element of the http element, whose abridged definition looks like this:

<xs:element name="http">
 <xs:complexType>
  <xs:choice minOccurs="0" maxOccurs="unbounded">
   <xs:element name="intercept-url">
    <xs:complexType>
     <xs:attributeGroup ref="security:intercept-url.attlist"/>
    </xs:complexType>
   </xs:element>
   <!-- Details omitted for clarity -->
   <xs:element name="access-denied-handler">...</xs:element>
   <xs:element name="form-login">...</xs:element>
   <xs:element name="openid-login">...</xs:element>
   <xs:element name="x509">...</xs:element>
   <xs:element ref="security:jee"/>
   <xs:element name="http-basic">...</xs:element>
   <xs:element name="logout">...</xs:element>
   <xs:element name="session-management">...</xs:element>
   <xs:element name="remember-me">...</xs:element>
   <xs:element name="anonymous">...</xs:element>
   <xs:element name="port-mappings">...</xs:element>
   <xs:element ref="security:custom-filter"/>
   <xs:element ref="security:request-cache"/>
   <xs:element name="expression-handler">...</xs:element>
  </xs:choice>
  <xs:attributeGroup ref="security:http.attlist"/>
 </xs:complexType>
</xs:element>

Example usage:

<security:http>
 <security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
 <security:intercept-url pattern="/account/**" access="hasRole('ROLE_USER')" />
 <security:intercept-url pattern="/**" access="hasRole('ROLE_ANONYMOUS')" />
 <!-- other elements removed for clarity -->
</security:http>


Three

You can encode and validate passwords using several classes that implement Spring’sorg.springframework.security.authentication.encoding.PasswordEncoder interface. This only has two methods:encodePassword and isPasswordValid. Its many implementations include:
  • BaseDigestPasswordEncoder
  • BasePasswordEncoder
  • LdapShaPasswordEncoder
  • Md4PasswordEncoder,
  • Md5PasswordEncoder
  • MessageDigestPasswordEncoder
  • MessageDigestPasswordEncoder
  • PlaintextPasswordEncoder
  • ShaPasswordEncoder

Four

You can restrict access to page elements using Spring Security’s tag library. To use this library you include the following taglib definition in your JSP:

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

The taglib contains three useful tags:
  • authorize
  • authentication
  • accesscontrollist

The most useful seems to be the authorize tag, which, taking examples from the Spring documentation, can be used in two ways. Firstly, you can authorize against roles:

<sec:authorize access="hasRole('supervisor')">
This content will only be visible to users who have
the "supervisor" authority in their list of <tt>GrantedAuthority</tt>s.
</sec:authorize>

...and secondly you can authorize against URLs

<sec:authorize url="/admin">
This content will only be visible to users who are authorized to send requests to the "/admin" URL.
</sec:authorize>

The URL specified must tie in with the intercept-url tag described in item 2.


Five

You can perform method level authorization using Spring’s in-house annotations

  • @PreAuthorize("spEL expression")
  • @PostAuthorize("spEL expression")
  • @Secure

where the spEL expression can be anything, but is usually something like: hasRole('ROLE_USER').

To enable @PreAuthorize(...) and @PostAuthorize(...) add the following to your XML config file:

<global-method-security pre-post-annotations="enabled" />

@PreAuthorize(...) is used as shown in the following example:


  
@PreAuthorize("hasRole('ROLE_ADMIN')")
  
public void deleteUser(String username);

To enable @Secure add the following to your Spring config file:

<global-method-security pre-post-annotations="enabled" />


Six

You can perform method level security using Spring’s JSR-250 implementation by adding the following to your Spring config file:

<global-method-security jsr250-annotations=”enabled”/>

The JSR-250 security annotations are a sub set of the JSR-250 annotations and include:

  • @RolesAllowed({“ROLE_USER”,”ROLE_ADMIN”})
  • @PermitAll
  • @DenyAll

When used, a JSR-250 annotation looks something like this:

 
  
@RolesAllowed({"ROLE_ADMIN","ROLE_USER"})
  
public void deleteUser(String username);


Seven

You can integrate Spring Security with OpenID authentication with a few simple steps. The first of these is writing a simple JSP form where the action value is set to j_spring_openid_security_check, which at its most minimal looks something like this:

<form action="j_spring-openid-security-check" method="post">
 <label for="openid_idenifier">Login</label>: 
 <input id="openid_identifier" name="openid_identifier" type="text"/>
 <input type="submit" value="Login" />
</form>

The next step is add the openid-login element to http:

<xs:element name="http">
 <xs:complexType>
  <xs:choice minOccurs="0" maxOccurs="unbounded">
   <xs:element name="openid-login">
    <xs:annotation>
     <xs:documentation>
      Sets up form login for authentication with an
      Open ID identity
     </xs:documentation>
    </xs:annotation>
    <xs:complexType>
     <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="unbounded"
       ref="security:attribute-exchange" />
     </xs:sequence>
     <xs:attributeGroup ref="security:form-login.attlist" />
     <xs:attribute name="user-service-ref" type="xs:token">
      <xs:annotation>
       <xs:documentation>
        A reference to a user-service (or
        UserDetailsService bean) Id
       </xs:documentation>
      </xs:annotation>
     </xs:attribute>
    </xs:complexType>
   </xs:element>
   <!-- Other elements omitted for clarity -->
  </xs:choice>
 </xs:complexType>
</xs:element>

As all of openid-login child elements are optional, the simplest way to enable OpenID is to write:

<http auto-config="true">
 <openid-login/>
 <!-- other tags and attributes omitted for clarity -->
</http>

Lastly, you’ll need to add the spring-security-openid.jar to your project.


Eight

You can configure your app to authenticate users with an embedded LDAP (Lightweight Directory Access Protocol) Server using XML config. This is described in the abridged XML schema show below:

<xs:element name="ldap-server">
 <xs:complexType>
  <xs:attributeGroup ref="security:ldap-server.attlist" />
 </xs:complexType>
</xs:element>
<xs:attributeGroup name="ldap-server.attlist">
 <xs:attribute name="id" type="xs:token">
  <xs:annotation>
   <xs:documentation>
    A bean identifier, used for referring to the bean elsewhere in the context.
   </xs:documentation>
  </xs:annotation>
 </xs:attribute>
 <xs:attribute name="port" type="xs:positiveInteger"/>
 <xs:attribute name="ldif" type="xs:string">
  <xs:annotation>
   <xs:documentation>
    Explicitly specifies an ldif file resource to load
    into an embedded LDAP
    server. The default is classpath*:*.ldiff
   </xs:documentation>
  </xs:annotation>
 </xs:attribute>
 <xs:attribute name="root" type="xs:string">
  <xs:annotation>
   <xs:documentation>
    Optional root suffix for the embedded LDAP server. Default is
    "dc=springframework,dc=org"
   </xs:documentation>
  </xs:annotation>
 </xs:attribute>
</xs:attributeGroup>

The LDIF file, where LDIF stands for LDAP Interchange Format, is a plain text file format used to describe a set of LDAP records.

An example of the ldap-server element usage would be:

<ldap-server ldif="classpath:my-ldif-file.ldif" id="localserver" /> 

To use Spring Security LDAP integration, remember to include the spring-security-ldap.jar jar in your project’s POM.XML.


Nine

You can configure your app to authenticate users with remote LDAP (Lightweight Directory Access Protocol) Server using XML config. This is described in the abridged XML schema show below:

<xs:element name="ldap-server">
 <xs:complexType>
  <xs:attributeGroup ref="security:ldap-server.attlist" />
 </xs:complexType>
</xs:element>
<xs:attributeGroup name="ldap-server.attlist">
 <xs:attribute name="id" type="xs:token">
  <xs:annotation>
   <xs:documentation>
    A bean identifier, used for referring to the bean elsewhere 
    in the context.
   </xs:documentation>
  </xs:annotation>
 </xs:attribute>
 <xs:attribute name="url" type="xs:token"/>
 <xs:attribute name="port" type="xs:positiveInteger"/>
 <xs:attribute name="manager-dn" type="xs:string">
  <xs:annotation>
   <xs:documentation>
    Username (DN) of the "manager" user identity which will be used to
    authenticate to a (non-embedded) LDAP server. If omitted, anonymous
    access will be used.
   </xs:documentation>
  </xs:annotation>
 </xs:attribute>
 <xs:attribute name="manager-password" type="xs:string">
  <xs:annotation>
   <xs:documentation>
    The password for the manager DN. This is required
    if the manager-dn is specified.
   </xs:documentation>
  </xs:annotation>
 </xs:attribute>
</xs:attributeGroup>

The documentation states that the ldap-server element “Defines an LDAP server location or starts an embedded server. The url indicates the location of a remote server. If no url is given, an embedded server will be started, listening on the supplied port number. The port is optional and defaults to 33389. A Spring LDAP ContextSource bean will be registered for the server with the id supplied”.

This is an example of a really minimal configuration:

<ldap-server url="ldap://myServer/dc=captaindebug,dc=com:389" id="ldapExternal" 
  manager-dn="uid=admin,ou=users,ou=systems" manager-password="s3cret"/>

Having configured the server, you also need to configure the LDAP authentication provider. There seem to be several methods of doing this and it’s not so straightforward, so more on that later, possibly...

Ten

You can add the requires-channel="https" attribute to your Spring Security Config's <intercept-url /> element to force any matching URL to use HTTPS. For example, if you wanted to ensure that password were always encrypted before being sent, then you could add this abridged XML to your config:

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/login" requires-channel="https"/>
    <!-- Other attributes and elements omitted -->    
</https>

There are another couple of things to do here, but more on that later...

You may have noticed that I’ve used the Spring Security XML schema file (http://www.springframework.org/schema/security/spring-security-3.1.xsd) to explain some of the features in my list of things you can do with Spring Security. That’s because I always treat the Spring XSDs as the definitive reference point for all things Spring. In November 2011 I wrote a blog on Spring’s JSR-250’s @PostConstruct Annotation that contained a mistake (Yes, it true it does happen), which was quite rightly pointed out by Spring’s Chris Beams - @CBeams, who left a comment on the JavaLobby Version of this blog. I decided to check the schemas and found that we were both wrong (although I was a lot more wrong than Chris) - the Captain Debug article is now, so far as I can tell, correct.

Application security is a pretty complex subject and if it’s something you’ll be looking at in depth then I suggest that you get a copy of Spring Security 3 by Peter Mularien - it’s also recommended by the Guys at Spring.

Finally, if there’s one key idea to appreciate about Spring Security is that, as an application bolt-on, it provides a really rich security feature set. You should therefore try to let Spring Security handle as much possible of your app’s security details rather than diving in and unnecessarily writing your own code.

Job Interview Preparation For Geeks




Failing an interview due to a lack of qualifications is forgivable, but it is tragic when highly qualified candidates do not get an offer due to being unprepared. With the amount of information freely available today, the time and effort required to prepare for an interview is extremely low and a relatively small investment to make in your career.
Typically a candidate will have at least two or three days advance notice to do some research and prepare for any interview. Here is a checklist of things for technologists to investigate to be sure you are ready for what will come your way.
  • Company intel – Learn as much as you can about the company, and try to have at least one minute of material memorized to answer the “What do you know about us?” question. Be prepared to present on the company history, the products or services the company provides, details on the business model, and the industry itself (competitors, health of the market, etc.). For technologists, the ability to give an eloquent response to the “Describe what the company does” question is a hugeasset that should not be overlooked and could be a significant factor in your success. Gathering substantial information on a young company’s funding status or finances might be difficult, but there will generally be at least some info in press releases from venture partners.
  • Tech environment – Get specific details about the technical environment by doing some basic web research, reviewing any available job descriptions or LinkedIn employee profiles, and talking to your recruiter or any appropriate company contacts you may have. What frameworks, languages, databases, operating systems, and hardware are they using? Even if the details aren’t all entirely relevant to your interview, it will show that you are taking this process seriously. Look up any buzzwords or acronyms you don’t recognize so you can at least discover if you may have experience with a related item (“I haven’t worked with ______, but I’m familiar with ________ which appears to be a similar tool/language”).
  • Tech moves – Knowing the company’s current tech details is valuable, but knowing about some of the company’s technical history will show great initiative while also providing potential insight into how the company views technology and makes tech decisions. Has the company made significant changes to their stack, and if so, why? Are they heavily invested in open source? Do they seem closely linked to a specific vendor? Does the company have an engineering blog or a company GitHub account for you to explore that might contain this information?
  • Interviewer intel – Insight into the technical background and past employers of the individual(s) you will meet is a great advantage, as you may have some similar history. Personal GitHub or Twitter accounts? Technical blog posts? A LinkedIn or web search of the interviewer(s) might turn up some helpful details to use during the interview, as long as you use the info wisely. Showing that you did some research displays initiative, as long as you respect personal space.
  • Confirm the basics – Where are you going and who should you ask for when you get there? Who are you meeting with and what is his/her/their role in the company? What is the preferred dress code? (NOTE: Some companies actually ask that candidates dress more casual, so be sure to ask)
  • Prepare questions and anecdotes – Most interviews will provide you with at least a brief opportunity to ask questions. Although you ideally want to have these memorized, it is generally a good idea to have some questions listed so you don’t forget them under possible duress. There are also some fairly standard questions in the “tell me about a time when…” family which are commonly answered with anecdotes. Give some thought to past challenges, failures, and successes, and especially what lessons you learned from each project.
  • Documents – Some companies may ask you to fill out an application and other relevant documents before the interview. Find out if this is the case and if so get those completed before interview day. Make sure to print out at least three copies of your resume and one copy of your list of questions. Think about who you will list as references if asked on the application, and have their info (name, email) available.
Keep in mind that making a solid impression in an interview is something that can make a huge impact down the road, whether or not you get the job. Interviewers remembercandidates who impressed, and they absolutely will remember those who crashed and burned as well. Do your homework and take interviews seriously, not just for the sake of getting this job but for opportunities later in your career.


Source: http://jobtipsforgeeks.com/2012/11/27/interviewprepforgeeks/

Beware of SQLInjection in Java Application

Source:

http://www.ramkitech.com/2011/12/beware-of-sqlinjection-in-java.html



Hi In this post we will discuss what is SQL Injection attack. and how its may affect ur any  web application its use the backend database. Here i concentrate on java web application. Open Web Application Security Project(OWAP) listed that SQL Injection is the top vulnerability attack for web application. Hacker's they Inject the SQL code in web request to the web application and take the control of backend database, even that backend database is not directly connected to internet. And we will see how to solve and prevent the SQL Injection in java Web Application.

For this purpose we need 1 tools. these tool are completely open source.

SQL Map - SqlMap is an open source penetration testing tool that automates the process of detecting and exploiting SQL Injection. we can get it from here.

SQLInjection
      SQL injection is the technique to extract the database information through web application.

Scenario:
we have one database server [MySQL] and web application server [Tomcat]. consider that database server is not connected to internet. but its connected with application server. Now we will see using web application how to extract the information using sql-injection method.

Before see the sql-injection, we create small web application. It contain single jsp page like this


 <form action="userCheck">
            <input type="text" name="user" value=""/>
            <input type="submit" value="Submit"/>
  </form>


 In userCheck Servlet receives the user input field and connect to databse server and fire the sql query based on user input and receive the ResultSet and iterate it print into the web page.

userCheck servlet
  1. protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.         response.setContentType("text/html;charset=UTF-8");  
  4.         PrintWriter out = response.getWriter();  
  5.         try {  
  6.   
  7.             String user = request.getParameter("user");  
  8.             Connection conn = null;  
  9.             String url = "jdbc:mysql://192.168.2.128:3306/";  
  10.             String dbName = "anvayaV2";  
  11.             String driver = "com.mysql.jdbc.Driver";  
  12.             String userName = "root";  
  13.             String password = "";  
  14.             try {  
  15.                 Class.forName(driver).newInstance();  
  16.                 conn = DriverManager.getConnection(url + dbName, userName, password);  
  17.   
  18.                 Statement st = conn.createStatement();  
  19.                 String query = "SELECT * FROM  User where userId='" + user + "'";  
  20.                 out.println("Query : " + query);  
  21.                 System.out.printf(query);  
  22.                 ResultSet res = st.executeQuery(query);  
  23.   
  24.                 out.println("  
  25.   
  26. Results");  
  27.                 while (res.next()) {  
  28.                     String s = res.getString("username");  
  29.                     out.println("  
  30.   
  31. \t\t" + s);  
  32.                 }  
  33.                 conn.close();  
  34.   
  35.             } catch (Exception e) {  
  36.                 e.printStackTrace();  
  37.             }  
  38.         } finally {  
  39.             out.close();  
  40.         }  
  41.       
When we execute the above code. In normal input execution look like follows
When we give the normal value like "ramki" then click the submit button then output like this
Its perfectly correct in normal behaviour. what happen when i put some special character or some sql statement in input box like this
when we click the submit button then it show all rows in my table like this

Its big security breach in my application. what happen... Its one kind of sql injection

lets see what happen
when i enter normal value in input box my servlet receives and substitute in the sql query and execute it.

SELECT * FROM  User where userId=' ramki '
its correct and we got correct output.

what happen when i put sdfssd' or '1'='1 
SELECT * FROM  User where userId=' sdfssd' or '1'='1'
its means

SELECT * FROM  User where userId=' sdfssd' or '1'='1'
like this. so our query is altered. now new query have 2 condition. 2nd condition always true. 1st condition may be or may not be true. but these 2 condition are connected with or logic. so where clause always true for all rows. the result is they bring all rows from our tables.

This is called blind sql injection. If u want more details of sql injection the check here
http://www.unixwiz.net/techtips/sql-injection.html
https://www.imperva.com/app-security/threatglossary/sql-injection/
http://www.applicure.com/blog/owasp-top-10-2010

Now we can enter the sql statement directly in input box
like ramki' UNION SELECT * FROM mysql.`user` u --
then
SELECT * FROM  User where userId='ramki' UNION SELECT * FROM mysql.`user` u --'
then its means
SELECT * FROM  User where userId='ramki' UNION SELECT * FROM mysql.`user` u --'
here they wont use * because its not matched with first table. so they find how many columns then use Union with second table.the user particular column they want . as result the get mysql database user information its exposed through our web application.

sqlmap
It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database

Install the sqlmap in ur system or use BackTrack Linux
Here I used backtrack linux. because its already pre installed lots of applications like sqlmap.
In backtrack, sqlmap is located in /pentest/web/scanner/sqlmap

sqlmap commands

retrieve all databases
./sqlmap.py -u http://localhost:8080/SQLInject/userCheck?user=ramki  --dbs


retrieve all tables
./sqlmap.py -u http://localhost:8080/SQLInject/userCheck?user=ramki  -D test --tables


retrieve all columns from particular table
./sqlmap.py -u http://localhost:8080/SQLInject/userCheck?user=ramki  -D test -T User --columns


Dump all column valued  from particular table
./sqlmap.py -u http://localhost:8080/SQLInject/userCheck?user=ramki  -D test -T User --dump

Dump some column valued  from particular table
./sqlmap.py -u http://localhost:8080/SQLInject/userCheck?user=ramki  -D test -T User -C userId,password --dump




See the video for full demo (watch in HD)
http://www.youtube.com/embed/C5PQ86nWMkM


How To Prevent SQL Injection
  •  Before substitute into query, we need to do the validation. for remove ir escaped the special character like single quote, key words like select, Union...
  • Use Prepared Statement with placeholder
  1. PreparedStatement  preparedStatement=conn.prepareStatement("SELECT * FROM  usercheck where username=?") ;  
  2. preparedStatement.setString(1, user);  
that setXXX() method do all the validation and escaping the special charcter
Now if use same blind sql injection like sdfssd' or '1'='1 then 

SELECT * FROM  User where userId=' sdfssd\' or \'1\'=\'1'

here all special character are escaped

When we use JPA kind of ORM tools like Hibernate, EclipseLink, TopLink that time also may be sqlinjection is possible.
Preventing the SQL injection we need to use NamedQuery instead of normal Query. Because NamedQuery internally used PreparedStement but normal query used norma Stement in java.

Normal Query in JPA
  1. String q="SELECT r FROM  User r where r.userId='"+user+"'";  
  2.  Query query=em.createQuery(q);  
  3.  List users=query.getResultList();  

so dont use normal query, use Named query like this 
  1. Query query=em.createNamedQuery("User.findByUserId");  
  2.  query.setParameter("userId", user);  
  3.  List users=query.getResultList();  


U can download the demo code from GitHub (or) Google code