Pages

Friday, 17 January 2014

Sending Email with java

It is quite important to send email in normal use. So to do it with java is quite simple task firstly we need to have a API file  or jar file which means Java Archive Resource file which consist of special functions and classes which are needed. There are varieties of jars like sendmail, JavaMail and many more. So choice is ours.Below is example of JavaMail jar file. 

To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.

Send a Simple E-mail:
Here is an example to send a simple e-mail from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email.


import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
   public static void main(String [] args)
   {    
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }

}

Uploading and Downloading Files In JAVA

Below is Code for uploading and downloading file or attachment using java!!!!
upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>
</head>
<body>
<form id="form1" enctype="multipart/form-data" action="../upload" method="post">
            <table>
            <tr>
            <td> File Name </td>
            <td><input type="text" name="filename"/>
            </tr>
            <tr>
                    <td>Select File  </td>
                    <td><input type="file"  name="file" />
                 
                </tr>
               
            <tr><td><input type="submit" value="submit"/></td></tr>
            </table>
         
        </form>
           
</body>
</html>


upload.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * Servlet implementation class up
 */
public class up extends HttpServlet {
private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public up() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
/* String f1=request.getParameter("file");
f1.
if(f1.endsWith(".txt"))
{
System.out.println(f1);
}
else
{
System.out.println("not a txt file");
}*/
            // Apache Commons-Fileupload library classes
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu  = new ServletFileUpload(factory);
 
            if (! ServletFileUpload.isMultipartContent(request)) {
                System.out.println("sorry. No file uploaded");
                return;
            }
             Connection con=null;
            java.util.List items = sfu.parseRequest(request);
         
            FileItem FirstName = (FileItem) items.get(0);
            String fn = FirstName.getString();
              System.out.println(fn);
              FileItem Image = (FileItem) items.get(1);
         String type=  Image.getContentType();
         if(type=="image/jpeg"){
         response.setContentType("image/jpeg");
         }
              Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
           System.out.println("get connection");
             
           PreparedStatement ps = (PreparedStatement) con.prepareStatement("insert into files_upload(file_name,file_data,file_type) values (?,?,?)");
           
           System.out.println("prepared statement");
           ps.setString(1,fn);
           ps.setBinaryStream(2, Image.getInputStream(), (int) Image.getSize());
           ps.setString(3, type);
           ps.executeUpdate();
           System.out.println("File Uploaded Successfully.");
}
        catch(Exception ex) {
       
           System.out.println(ex);
        }
}
}

download.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.io.*,java.util.*,java.sql.*" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>view</title>
</head>
<body>

    <br><br>

    <table width="200px" style="border:1px solid #ff0000;background-color:f7f7f7" align="center">

    <tr style="font-weight:bold;">

    <td align="center" align="center" colspan=2 style="border-bottom: 2px solid #000000;">Download Files</td>

    </tr>

 <tr style="font-weight:bold;">

       <td align="center" style="border-bottom: 2px solid #000000;">Id</td>

       <td align="center" style="border-bottom: 2px solid #000000;">File</td>

    </tr>

    

    <%

    

         String connectionURL = "jdbc:mysql://localhost:3306/test";

        //  String url=request.getParameter("WEB_URL");

        //  String Content=new String("");

          Statement stmt=null;

      Connection con=null;

    try

    {

        Class.forName("com.mysql.jdbc.Driver");

        con=DriverManager.getConnection(connectionURL,"root","root"); 

        stmt=con.createStatement();

        String qry = "select * from files_upload";

        ResultSet rst= stmt.executeQuery(qry);
        
    
        
        while(rst.next())

        {

    %>

         <tr>

      <td  align="center"><%=rst.getInt(1)%></td>

      <td align="center">

      <a href="../DBFileDownloadServlet?id=<%=rst.getInt(1)%>"><%=rst.getString(2)%></a>

       </td>

    </tr>

    <%

        }
        
    }

    catch(Exception e){

        e.printStackTrace();

    }

    %>

    </table>

    

</body>
</html>

download.java 


import java.io.*;
import java.util.*;
import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class file_download
 */
public class file_download extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public file_download() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

   

   int id=0;

   if(request.getParameter("id")!=null && request.getParameter("id")!="")

   {

 id = Integer.parseInt(request.getParameter("id").toString());

   }

        String connectionURL = "jdbc:mysql://localhost/test";

         String url=request.getParameter("WEB_URL");

         String Content=new String("");

         Statement stmt=null;

     Connection con=null;

   try

   {

       String filename="data"+id+".docx";

        Class.forName("com.mysql.jdbc.Driver").newInstance();

     con=DriverManager.getConnection(connectionURL,"root","root"); 

     stmt=con.createStatement();

         String qry = "select * from file where id='"+id+"'";

         ResultSet rst= stmt.executeQuery(qry);

                       if(rst.next())

                       {

   

                               Content=rst.getString("file_data");

                       }

                       

               byte requestBytes[] = Content.getBytes();

               ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);

               response.reset();

               response.setContentType("application/*");

               response.setHeader("Content-disposition","attachment; filename=" +filename);

               byte[] buf = new byte[1024];

                 int len;

                 while ((len = bis.read(buf)) > 0){

                                 response.getOutputStream().write(buf, 0, len);

                                }

               bis.close();

               response.getOutputStream().flush(); 

   }

   catch(Exception e){

       e.printStackTrace();

   }

   
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}


Wednesday, 15 January 2014

Java Beans

A Java Bean is a reusable software component (actually, a Java class) that can be manipulated visually in a builder tool
Java Beans are just ordinary Java classes that follow certain conventions - you don't need special tools to create them
It is useful to have some tools to help assemble and configure a Bean-based application

Examples of "builder tools":
1.BeanBox (part of Sun's basic Beans Development Kit (BDK) - available free from java.sun.com)
2.Sun Java Workshop
3.IBM VisualAge for Java
4,Symantec Visual Cafe
5.Borland JBuilder
6.Java Bean conventions

There are two primary conventions that must be followed in creating Java Bean classes:
each "property" of the Java Bean class is implemented by defining two public functions (a "get" function and a "set" function)
the "operations" of the Java Bean class are the other public functions defined in the class
/* file Thermometer.java */
public class Thermometer {
  /* these two functions define the "currentTemperature" property */
  public int getCurrentTemperature() { return temp; }
  public void setCurrentTemperature(int aTemp) { temp = aTemp; }

  private int temp;

  public void temperatureChanged(TempChangedEvent ev) { ... }
  ... other implementation details ...
}

Reflection in Java

The "builder" programs can use special functions in Java 1.1 to discover which operations are part of each class
the special Java functions are called the Java Reflection API
they are used in many places in the builders
Java builders can display a "property sheet" for each Java Bean

More Java Bean configuration

The reflection interface may also be used by the builder tool to help the "programmer" tie user interface events to particular operations:
Java code is generated by the Builder tools

Java applications can use the "set" operations to initialize properties
Builder tools can also create the code for new objects that can be "registered" to receive events from the appropriate user interface objects
this means: a Java Bean doesn't have to be modified by the builder tools
all of the tailoring code can be put into newly-created classes
this is almost like "callbacks" in C and C++-based framework software
Creating a Java Bean

Design an ordinary Java class:
decide what properties and public operations it will support
Make sure that each property has a "get" and "set" operation in the public interface of the Java Bean class
Make sure that the class conforms to the Java 1.1 event model
If the class is a "visual Bean", then it should probably be a derived class of one of the AWT classes (probably Component or Container)
A Java Bean may also use some other helper classes
You can bundle the ".class" files for the main Java Bean class and all of the helper classes into a "Java Archive" file (JAR file)
Java Beans make good interfaces

Java Beans can be used to provide an interface to other non-Java applications that use Microsoft's ActiveX component technology
there is a "bridge" between Java Beans and ActiveX
Java Beans can be used to encapsulate the interface to an external database
the "get" and "set" operations in a Java Bean might actually use the Java database interface classes (the JDBC classes) to interact with a relational database
Not all Java Beans are graphical - but they can still be used to assemble applications using an application builder tool
Alternative ways to make a Java Bean

It isn't necessary to make changes to an existing class to convert it to a Java Bean
instead, you can create a "BeanInfo" class that defines the properties and public operations
for example, the BeanInfo class for the Temperature class would be called TemperatureBeanInfo
this class can define functions that permit the builder tools to access the characteristics of the Java Bean
public class TemperatureBeanInfo extends java.beans.SimpleBeanInfo {
 /* the following function will return an array of PropertyDescriptor
    objects, one object per Java Bean property */
  public PropertyDescriptor[] getPropertyDescriptors() {
   ...
  }
}


Using Java Beans for Web programs

Java applets are programs designed to run within a Web browser
An applet is a Java class that is derived from the java.applet.Applet class
Applets usually define the following functions:
init() - this function will define what will be done when the applet is first downloaded (it will usually create some user interface objects and set them up to be displayed, but it might also connect to a database or set up some other resources)
paint() - this function will be used to draw fixed strings and images, which might need to be redrawn any time the window is moved or becomes visible
Under standard conditions, applets can access files on the Web server, but not on the local "client" machine


Conclusion

Java Beans is a technology that makes it possible to build flexible Java applications
Applications can be built by non-programmers (using a builder tool)

Creating new Java Bean classes requires certain skills:
1.the developer needs to understand and use the Java 1.1 event model
2.the developer must follow certain "naming conventions" when creating the operation names in a Java Bean class
3.extra information for the builder tools can be added in a BeanInfo class
4.Java Beans is supported by many of the new Java development tools
5.Java Beans can be used in tandem with many other technologies
ActiveX
relational databases

Tuesday, 14 January 2014

Attributes Of Servlets

An attribute in servlet is an object that can be set, get or removed from one of the following scopes:

request scope
session scope
application scope
The servlet programmer can pass information from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again.

Attribute specific methods of ServletRequest, HttpSession and ServletContext interface

There are following 4 attribute specific methods. They are as follows:
public void setAttribute(String name,Object object):sets the given object in the application scope.
public Object getAttribute(String name):Returns the attribute for the specified name.
public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects.
public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

Model View and Controller

MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data.

Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.

Model represents the state of the application i.e. data. It can also have business logic.

View represents the presentaion i.e. UI(User Interface).





Example of following MVC in JSP

In this example, we are using servlet as a controller, jsp as a view component, Java Bean class as a model.

In this example, we have created 5 pages:

index.jsp a page that gets input from the user.
ControllerServlet.java a servlet that acts as a controller.
login-success.jsp and login-error.jsp files acts as view components.
web.xml file for mapping the servlet.
File: index.jsp
<form action="ControllerServlet" method="post">  
Name:<input type="text" name="name"><br>  
Password:<input type="password" name="password"><br>  
<input type="submit" value="login">  
</form>  
File: ControllerServlet
package com.javatpoint;  
import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.RequestDispatcher;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
public class ControllerServlet extends HttpServlet {  
    protected void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        response.setContentType("text/html");  
        PrintWriter out=response.getWriter();  
          
        String name=request.getParameter("name");  
        String password=request.getParameter("password");  
          
        LoginBean bean=new LoginBean();  
        bean.setName(name);  
        bean.setPassword(password);  
        request.setAttribute("bean",bean);  
          
        boolean status=bean.validate();  
          
        if(status){  
            RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");  
            rd.forward(request, response);  
        }  
        else{  
            RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");  
            rd.forward(request, response);  
        }  
      
    }  
  
    @Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        doPost(req, resp);  
    }  
}  
File: LoginBean.java
package com.javatpoint;  
public class LoginBean {  
private String name,password;  
  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public String getPassword() {  
    return password;  
}  
public void setPassword(String password) {  
    this.password = password;  
}  
public boolean validate(){  
    if(password.equals("admin")){  
        return true;  
    }  
    else{  
        return false;  
    }  
}  
}  
File: login-success.jsp
<%@page import="com.javatpoint.LoginBean"%>  
  
<p>You are successfully logged in!</p>  
<%  
LoginBean bean=(LoginBean)request.getAttribute("bean");  
out.print("Welcome, "+bean.getName());  
%>  
File: login-error.jsp
<p>Sorry! username or password error</p>  
<%@ include file="index.jsp" %>  
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
id="WebApp_ID" version="3.0">  
    
  <servlet>  
  <servlet-name>s1</servlet-name>  
  <servlet-class>com.javatpoint.ControllerServlet</servlet-class>  
  </servlet>  
  <servlet-mapping>  
  <servlet-name>s1</servlet-name>  
  <url-pattern>/ControllerServlet</url-pattern>  
  </servlet-mapping>  
</web-app>  




JSP VS SERVLETS

Following Points are noted for Java Server Pages:-

1. JSP is a webpage scripting language that can generate dynamic content.
2. JSP run slower compared to Servlet as it takes compilation time to convert into Java Servlets.
3. It’s easier to code in JSP than in Java Servlets.
4. In MVC, jsp act as a view.
5. JSP are generally preferred when there is not much processing of data required.
6.The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans.
7.We can achieve functionality of JSP at client side by running JavaScript at client side.


Following Points are noted for Java Servlets:-

1. Servlets are Java programs that are already compiled which also creates dynamic web content.
2. Servlets run faster compared to JSP.
3. Its little much code to write here.
4. In MVC, servlet act as a controller.
5. Servlets are best for use when there is more processing and manipulation involved.
6. There is no such custom tag facility in servlets.

7. There are no such methods for servlets.


Sunday, 6 October 2013

Scans and Counter Measures

Before Starting scanning and its methodology we must start with discussing types of scans.
First of all there are 3 types of scans possible based on their operation performed.
These are Port Scanning, Network Scanning and vulnerability scanning.
1.Port Scanning is used to determine open ports and services.
2.Network Scanning is used to locate working IP Addresses from a list and find out which are more      useful.
3.Vulnerability Scanning is for knowing the weaknesses in a network computers.

Know,Let us know about some popular services and ports used by them.FTP uses port no 21, Telnet uses port no 23, HTTP uses port 80, SMTP-25,POP3-110,HTTPS-443.

Scanning Methodology:-

1.Check for Live Systems.
we can check for live systems by performing Ping Sweep of IP Addresses.The systems responding to PING are active or live others might be Inactive or possibility of firewalls.

2.Check Open Ports.
3.Service Identification.
4.banner Grabbing or OS FingerPrinting.
5.Vulnerability Scanning.

NOTE:-
ICMP Scanning or Ping Sweep :-
Sending ICMP requests to all hosts on network to determine which are up and responding.It runs parallel on all systems because it can be run on all Systems simultaneously.

CounterMeasures to Port Scanning:-
Following steps could be followed:-
1.Implementation Of Intrusion Detection Systems or firewalls, should be followed.
2.After implementation of IDS or firewalls perform port scanning using tools such as Pinger, Friendly Pinger, WS_PING_PRO and many more so as to know whether firewall correctly works or not.
3.Check whether firewall able to detect probes set up by Port scanning tool.
It is to be noted that firewall must scan both data and packet not only TCP Header to determine whether traffic is allowed to pass through Firewall.
4.Network IDS should be used to hold on Operating System Detection Methods.
5.Onlu Needed Ports should be opened and rest closed.

Thursday, 26 September 2013

Introduction to FootPrinting

FootPrinting is the first step of Gathering Information about the systems of the organization we are trying to exploit.
Footprinting is a simple concept of revealing vulnerabilities in systems and the ease with which it can be exploited.
Purpose:-
Find ways to intrude into the systems and environments. It also includes creation of a map or BluePrint of Organization's Network.

A simple way for gathering information is GOOGLE the GURU.
So as to find out parameters , Some file types or some content in the URL.
Some Tools like samSpade, NSlookUp, WhoIs, DNSLookUp and many more are available.

DNS ENUMERATION:-
DNS or Domain Name Server is the process of locating all DNS servers and corresponding records.
Serching out for information about servers is made easy with help of various online available resources like

1.ARIN (American Registry for Internet Numbers)
Click here to view ARIN Website .
2.APNIC (Asia Pacific Network Information Centre)
Click Here to view APNIC Website .
3.LACNIC (Latin America And  Caribbean Network Information Centre)
Click Here to view LACNIC Website
4.RIPENCC for europe continent.
5.AFRINIC for africa continent.

DNS Record Types
1.A(Address):- Map Host Name to IP Address.
2.SDA(Start Of Authority):- Identify DNS Server responsible for Domain Information.
3.CNAME(Canonical Name):- Provide Additional Name of aliases for Address Records
4.MX(Mail Exchange):- Identify Mail Server For Domain.
5.SRV(Service):- Identify Services such as Directory Services.
6.PTR(Pointer):- Map IP Address To Host Names.
7.NS(Name Server):-Identify other Name services for Domain.


Friday, 6 September 2013

Introduction To Network Mapping

Network Mapping In Simple terms means connecting Networks physically.Network mapping discovers all the devices on the network and their connectivity with that Network.

Let us Know Discuss about Network Mapping and actually ways of Network Mapping
1.Identify Live Hosts
2.Determine running Services
.TCP Port Scanning
.UDP Port Scanning
.Banner Grabbing
.ARP Discovery
3.Identify Perimeter Network (Router / Firewalls)‏
.Tracerouting
.Scan Default Firewall/Router Ports
.Perform FIN/ACK Scan
.Map Router / Firewall Rule-Base
4.Passive OS Guessing
5.Active OS Guessing
.TCP/IP Stack Fingerprinting
.HTTP Packet Analysis
.ICMP Packet Analysis
.Telnet Handshake Analysis
6.Host Enumeration
.Systems Enumeration

Identify Live Hosts:-
In this we discuss various tools which are used to detect Live Hosts Over the Network .
Here,Project Scope will restrict scan spectrum.
Tools Used for Identifying Live Hosts.
1.ping
2.nmap
3.hping
3.traceroute
4.tpctraceroute

ping as we all know is a pc network tool used to test whether a particular host is reachable across an IP network.

Nmap or Network Mapper is a security scanner tool used to discover Host and services on a computer network, thus creating a "map" of the network. To complete its goal, Nmap sends specially crafted packets to the target host and then analyzes the responses.
Some Of Features Of Nmap are:-
1.Host discovery - Identifying hosts on a network. For example, listing the hosts that respond to pings or have a particular port open.
2.Port scanning - Enumerating the open ports on target hosts.
3.Version detection - Interrogating network services on remote devices to determine application name and version number.
4.OS detection - Determining the operating system and hardware characteristics of network devices.
5.Scriptable interaction with the target - using Nmap Scripting Engine (NSE) and Lua programming language.(Lightweight Scripting Language written in ANSI C)
6.Nmap can provide further information on targets, including reverse DNS names, device types, and MAC addresses.
Typical uses of Nmap:
1.Auditing the security of a device by identifying the network connections which can be made to it.
2.Identifying open ports on a target host in preparation for auditing.
3.Network inventory, network mapping, maintenance and asset management.
4.Auditing the security of a network by identifying new servers.

hping is a free packet generator and analyzer for the TCP/IP protocol. Hping is one of the de facto tools for security auditing and testing of firewalls and networks, and was used to exploit the idle scan scanning technique, and now implemented in the Nmap Security Scanner. The Version hping3, is scriptable using the Tcl language and implements an engine for string based, human readable description of TCP/IP packets, so that the programmer can write scripts related to low level TCP/IP packet manipulation and analysis in very short time.
Like most tools used in computer security, hping is useful to both system administrators and hackers.




Thursday, 5 September 2013

Controls Assessment and Scheduling

Controls Assessment and Scheduling in Networks include steps or phases. Some of these are:-
1.Information Gathering.
2.Network Mapping.
3.Vulnerability Identification.
4.Penetration.
5.Gaining Access & Escalation
6.Enumerating Further.
7.Compromise Remote Users/Sites.
8.Maintaining Sites.
9.Covering Tracks.
We will Know discuss all of above One by One.

Information Gathering 

Following are the steps followed during Information Gathering Phase.
1.Locate the target Web presence.
2.Examine the target using search engines.
3.Search Web groups.
4.Search employee personal Web sites.
5.Search Security & Exchange Commission and finance sites.
6.Search uptime statistics sites.
7.Search system/network survey sites.
8.Search on P2P networks.
9.Search on Internet Relay Chat (IRC).
10.Search job databases.
11.Search newsgroups (NNTP).
12.Gain information from domain registrar.
13.Check for reverse DNS lookup presence.
14.Check more DNS information.
15.Check Spam database lookup.
16.Check to change WHOIS information.
Tools used for purpose of Information Gathering:
Firefox
Dogpile.com
Alexa.org
Archive.org

Saturday, 31 August 2013

Introduction to Network Packet Crafting

Hello all, Before beginning Network Packet Crafting or NPC we shall brush up crafting.
We Know that data is sent in form of Packet. Packet Crafting simply means to make data arranged or edited such that it gets tougher to understand or decode the Data or Information stored over Network.
We know discuss abilities and limits of Network Packet Crafting
Abilities Of Network Packet Crafting:-
1.Shape data to make it look the way You want.
2.Possible to evade firewalls and Intrusion detection system.
3.Create scripts around encrypted Packets.

Limits Of NPC:-
1.We can craft only those packets that are allowed by the Network.That means we can not craft packets that violate rules.
2.Learning Curve:-
NPC require a deep understanding of Protocols like TCP/IP, Firewall Rules, Hardware Requirements, and many more.

Now we discuss various evasions and there targets.
1.Firewall Evasion:- Targeting Ports.
2.System Exploit:- Attacks like Denial Of Service(DOS), un-authorized access etc
3.Network Device Exploit:- DOS, Sniffing, invalid access.
4.Intrusion Detection System Evasion:- It relates to change in content or invalid transactions.


Penetration Testing and Types

Hello All, Welcome Again Today we discuss an intro to Penetration Testing and its four common types.

First of all we need to know what is Penetration. Penetration in simple terms means to intrude into some Network, Computer, Database or some other way of accessing the data and use it for some personal interests. We already know about Hackers (Black hat & White Hat). Penetration testers are  those expert people which are paid to detect vulnerability in our Systems or to detect loopholes which could be dangerous for the company. Loopholes may be in security settings, Password Settings, Network Operating Systems and many more like Programming flaws. So Penetration Testers are there to do there job.

Types of Penetration Testing:-

There are basically four types of Penetration Testing (On Basis Of Target) which are as follows:-
1.Network
2.Host Attacking
3.Application
4.Database

Network:-
This type of Penetration Testing include Password Detection, Attacking Switches and Routers, Firewalls, Intrusion Detection, Information about Virtual Private Networks and Storage systems.

Host:-
It means to detect gaps and loopholes in Operating Systems, Servers, Server OS .

Application:-
This includes detection of flaws in Web Application, Source Code Auditing and Binary Auditing.

Database:-
It include two phases or steps. They are Database Security and Social Engineering.

Thursday, 29 August 2013

BOSS Operating System

BOSS or Bharat Operating System Solutions
BOSS (Bharat Operating System Solutions) is GNU/Linux distribution developed by C-DAC
(Centre for Development of Advanced Computing) derived from Debian for enhancing the use of Free/ Open Source Software throughout India.The Beta Release of BOSS GNU/Linux Version 5.0 is coupled with GNOME Desktop Environment with wide Indian language support & packages, relevant for use in the Government domain. This release aims more at the security part and comes with an easy to use application to harden your Desktop. Currently BOSS GNU/Linux Desktop is available in all the Official Indian Languages such as Assamese, Bengali, Gujarati, Hindi, Kannada, Malayalam, Marathi, Oriya, Punjabi, Sanskrit, Tamil, Telugu, Bodo, Urdu, Kashmiri, Maithili, Konkani, Manipuri which will enable the mainly non-English literate users in the country.

Versions Of BOSS :-
Version                                     Code name      Kernel number     Desktop   
BOSS GNU/LinuxEvaluation     Sethu           2.6.14-2-smp     GNOME 2.8    
BOSS GNU/Linux v1.0              Tarang         2.6.17-1-i386     GNOME 2.14    
BOSS GNU/Linux v2.0              Anant          2.6.21-1-486       GNOME 2.18    
BOSS GNU/Linux Server                               2.6.21                                          
BOSS GNU/Linux v3.0              Tejas            2.6.22-3-486     GNOME 2.20 and KDE 3.5   
BOSS GNU/Linux v4.0              Savir            2.6.32-5-686     GNOME 2.30.2 and KDE 4.4.5   
BOSS GNU/Linux v5.0              Aasaan         2.6.32-5-686     GNOME 2.30.2 and KDE 4.4.5

SEO for Mobile Devices

Today we discuss points to consider while considering Search Engine Optimization for Mobile Devices.
Mobile SEO Guide to Building a Great Site

 1.Responsive Design
 2.Mobile Crawling
 3.Mobile Keywords
 4.Meta View port
 5.URL Structure
 6.Page Load Times
 7.UX
 8.Obstacles to Crawling
 9.Content Optimization
 10.Rel = “alternate”
 11.Rel = “canonical”
 12.Rel = “next/previous”
 13.Vary: User-Agent HTTP Header:
 14.Mobile Only Pages
 15.Supported Content
 16.Analytics

1. Responsive Design :
While responsive design is not an issue it is important to know that the site should also be configured for non-responsive design. Other than responsive design the two other methods used for mobile site design are Separate Mobile URL’s and Dynamic Serving. No matter how intelligent Google’s mobile user agents are, you need to configure your site with the unique configuration required specifically for these methods of delivering mobile-specific content.

2. Mobile Crawling : 
While responsive design allows for a reduction in the number of considerations.  Googlebot-Mobile specific crawling, it cannot be completely done away with. As part of regular checks on your site, you need to look at the regular and mobile user agents specifically at consistent times. For this you can make use of Google and Bing Webmaster Tools or a search engine spider and crawling tool like Screaming Frog SEO Spider.

3. Mobile Keywords : 
Do not forget that mobile searchers are not identical to desktop searchers. What this simply means is that the sort of searches that people do on mobiles are different from the ones done on desktops and for this reason context needs to always be considered on your site. For this reason, try to separate your keyword search and consider mobile on your on-page optimization.

4. Meta Viewport: 
When you find yourself optimizing for mobile, remember to define your Meta tags to either alter or disable the “zoom” function of mobile browsers. This is to clue your mobile browser that it is not, in fact, a desktop browser and that its response needs to accommodate the device.

5. URL Structure:
Based on Google’s directions, a single-URL strategy is the way to go, but remember to budget for ample amounts of planning, redesign and re-engineering.

6. Page Load Times: 
3G and 4G connections aren’t always the fastest. Make the effort to reduce your page-load times for a strong user experience.

7. UX: 
Speaking of which, strong UX also incorporates being able to help your audience find what they’re looking for.

8. Obstacles to Crawling:
Let’s just all take a moment and admit that Flash is dying. And then, let’s move forward and leave Flash at the door when we code our sites. Along with excessive Java.

9. Content Optimization: 
This one’s a “gimme”. Remember to optimize the important page elements and content around the important keywords.

10. Rel = “alternate”: 
To point towards the mobile URL of the desktop version of the page and make your mobile page discoverable.

11. Rel = “canonical”: 
To point towards the desktop URL of the mobile version; it also helps Google understand which version of the content has been duplicated.

12. Rel = “next/previous”: 
For sites with paginated content.

13. Vary: 
User-Agent HTTP Header: Regardless of device redirects or dynamic serving, the server needs to be configured to return the Vary: User-Agent HTTP response header.

14. Mobile Only Pages:
Skip these. Because Google accommodates mobile and desktop versions to compile ranks.

15. Supported Content: 
If you’re putting out content that a browser can’t support – say, a video, for instance – then your rankings will take a hit. Make sure you work with content that’s supported.
16. Analytics : 
For a site that is going to go mobile, it is very important to understand the audience and their browsing habits using a good analytics platform such as Google Analytics. Once you have done this, you should be segmenting your data based on the results of how different users are using your site differently. When determining usage habits, areas to consider are organic, engagement metrics and conversions. Keeping these common aspects in mind will mean allowing your mobile website to work to its full potential and deliver desired results. If you need a little help getting started with mobile optimization, give us a call.

Monday, 26 August 2013

Introduction To Session Management

Let us start with Session Tracking:-

Session tracking is the process of maintaining information about Web site visitors as they move from page to page. It requires some work on the part of the Web developer since there's no built-in mechanism for it. The connection from a browser to a Web server occurs over the stateless Hypertext Transfer Protocol (HTTP).
There are a number of ways to handle session tracking, but our focus is on the easy-to-use yet powerful HttpSession interface provided by the Java Servlet specification. Before we get into the HttpSession interface, let's look at some other ways of maintaining state.
Session-Tracking Techniques 
At one time Web developers used Web site visitors' IP addresses to track the sessions. This approach was inflexible and had many flaws. The main problem was that proxy servers eliminated the use of individual IP addresses. Users no longer had unique addresses, so this technique couldn't work properly. Another way of handling session tracking is the use of the HTML hidden field:
<INPUT TYPE="hidden" NAME="user"VALUE="BAJAJ">
This technique required server-side scripting that would dynamically generate the HTML code that contained the "user" field. Server-side code was also required to read the field and match it to information about this user on the server.
Another session-tracking technique is URL rewriting. In this approach, identification field(s) are appended to the end of each URL for a Web site. The following HTML code demonstrates this method:
<a href ="/orderform.htm?user=bajaj">Order Now!</A>
This approach is similar to hidden fields. The difference is that hidden fields can only be used in a form.
A common way of session tracking is the use of cookies. A cookie is information that's stored as a name/value pair and transmitted from the server to the browser. Cookies containing unique user information can be used to tie specific visitors to information about them on the server.
 The following code shows how to create a new cookie:
Cookie user = new Cookie("user","bajaj");
user.setMaxAge(3600);
response.addCookie(user);
This code creates a cookie with a name of "user" and a value of "bajaj". The cookie's expiration date is set with the setMaxAge() method to 3,600 seconds from the time the browser receives the cookie. The following code demonstrates how you would retrieve the value for a specific cookie:
String user = "";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("user")) user =
cookies[i].getValue();
}
}
In this code, an array of cookies is retrieved from the HttpServletRequest object using the getCookies() method. The array is walked through until a cookie with the name of "user" is returned by the getName() method. Once the cookie is found, the getValue() method is called to retrieve the value of the cookie.
The use of cookies provides a flexible and easy option for handling session tracking; however, it does present some problems. The information in the cookie is stored on the client's browser in a text file that can be easily read and manipulated, and this information is transmitted unsecured across the Internet. But the main problem is that they can be disabled through a setting in the Web browser. Web sites that rely on cookies for session tracking will be unable to track users who have disabled cookies.
Sessions in Java
The session management techniques we have looked at so far all have a common security issue: they transmit data in plain text. A powerful session-tracking solution is needed that's more secure and flexible. This is where the Java HttpSession API comes in. The HttpSession API provides a simple mechanism for storing information about individual users on the application server. The API provides access to a session object that can be used to store other objects. The ability to tie objects to a particular user is important when working in an object-oriented environment. It allows you to quickly and efficiently save and retrieve JavaBeans that you may be using to identify your site's visitors, to hold product information for display on your online store, or to track products that potential customers have placed in their shopping carts.
A session object is created on the application server, usually in a Java servlet or a JavaServer Page. The object is stored on the application server and a unique identifier called a session ID is assigned to it. The session object and session ID are handled by a session manager on the application server. Figure 1 illustrates this relationship. Each session ID assigned by the application server has zero or more key/value pairs tied to it. The values are objects that you place in the session. Assign each of those objects a name, and each name must have an object with it because a null is not allowed.
For this session-tracking technique to work, the session ID must be sent to the client's computer. A cookie is used to store the session ID on the Web site visitor's computer. This is automatically handled by the application server. Simply create the session object and begin using it. The application server will, by default, create the session ID and store it in a cookie. The browser will send the cookie back to the server every time a page is requested. The application server, via the server's session manager, will match the session ID from the cookie to a session object. The session object is then placed in the HttpServletRequest object and you retrieve it with the getSession() method.

Some Web site visitors have cookies disabled in their browsers. So we get around this problem and continue using sessions, use URL rewriting in your code. URL rewriting appends the session ID to the URL for every page that's requested. The only problem here is that you must rewrite every link in your HTML code as well as those from servlet to servlet, or servlet to JSP.
The procedure for URL rewriting is quite simple and requires only the use of two methods found in the HttpServletResponse interface. These two methods, encodeURL() and encodeRedirectURL(), are used to append the session ID to the URL. This allows the server to track users as they move through your Web pages, but it requires that every URL be rewritten. The string returned by the methods will have the session ID appended to it only if the server determines that it's required. If the user's browser supports cookies, the returned URL will not be altered. Also, the returned URL won't be altered if the application server is configured to not use URL rewriting. The format of the altered URL will vary based on different application server implementations; however, the common format will be the addition of a parameter, such as "sessionID=uniqueIDnumber". The parameter name (in this case "sessionID") is usually controlled through a configuration setting on the server. The value of the parameter ("uniqueIDnumber" in this example) is the unique session ID assigned by the server's session manager and is a long series of letters and numbers. The following line of HTML code from a JSP creates a link to another JSP:
<a href="/products/product.jsp">Product Listing</a>
Clicking on this link would send the user to the product.jsp page. Using URL rewriting, the same code would be written as follows:
<a href="<%= response.encodeURL("/products/product.jsp")
%>">Product Listing</a>
The returned string from the encodeURL() method would contain the session ID. On a Tomcat 3.2 application server, the result of this line of code would be:
<a href="http://www.yourservername.com/products/
product.jsp;$sessionid$xxxx">Product Listing</A>
The xxxx would actually be a unique session ID generated by the server. The other method you can use for rewriting URLs is the encodeRedirectURL(). It's used only in a servlet or JSP that calls the sendRedirect() method of the HttpServlet-Response interface. The following code is a standard redirection statement:
response.sendRedirect("http://www.yourservername.com/
products/sale.jsp");
Using URL rewriting, the code would be:
response.sendRedirect(response.encodeRedirectURL(
"http://www.yourservername.com/products/sale.jsp"));
The application server handles the encodeRedirectURL() method a little differently than the encodeURL() method; however, each method produces the same result.
You should now have a good understanding of how the session ID is tracked and matched to a session object on the server. The first step in using the session object is creating it. The method getSession() is used to create a new session object and to retrieve an already existing one. The getSession() method is passed a Boolean flag of true or false. A false parameter indicates that you want to retrieve a session object that already exists. A true parameter lets the session manager know that a session object needs to be created if one does not already exist. The following line of code demonstrates the use of getSession():
HttpSession session = request.getSession(true);
The getSession() method will return the session object. A new session object is created if one does not already exist. The server uses the session ID to find the session object. If a session ID is not found in a cookie or the URL, a new session object is created. You would probably use only the getSession() method with a true parameter at one point in your Web application. This would be the starting point of your site, possibly after the visitor has successfully logged in. Other servlets in your application should use the getSession(false) method. This will return a current session object or null. It does not generate a new session if one doesn't already exist.
A number of methods are defined in the Java Servlet specification.The methods you'll use most often and the ones we'll focus on are:
setAttribute(String name, Object value): Binds an object to this session using the name specified. Returns nothing (void).
getAttribute(String name): Returns the object bound with the specified name in this session, or null if no object is bound under this name.
removeAttribute(String name): Removes the object bound with the specified name from this session. Returns nothing (void).
invalidate(): Invalidates this session and unbinds any objects bound to it. Returns nothing (void).
isNew(): Returns a Boolean with a value of true if the client does not yet know about the session or if the client chooses not to join the session.
For an example in using sessions, we'll look at session management code that could be used for an online banking application that will allow customers to view their account information. The design of the application will follow the Model-View-Controller (MVC) architecture. The model, or data and business logic, will be represented by JavaBeans; the view will be through JavaServer Pages; and the control of the application will be handled by servlets. The ideas in these examples can easily be implemented in other types of Web applications.
An online banking application should have an HTML login page where the customer can enter a login name and password in a form. The form will submit (or post) the name and password to a login servlet. The first thing the servlet needs to do is verify the username and password. To stick with the topic at hand (sessions), we'll look only at the code needed to handle the session. After the customer has been verified, a Customer JavaBean can be created. The Customer bean will contain the basic information about this visitor and will be stored in the session. We want to create a new session object, but we also want to invalidate a session that may already exist. To do this, we need to retrieve the existing object (or create a new one) and check if it's a new session using the isNew() method. If it's not a new session object, we need to invalidate it using the invalidate() method. In the servlet, we can accomplish this with the following code:
HttpSession session = request.getSession (true);
if (session.isNew() == false) {
session.invalidate();
session = request.getSession(true);
}
The first line of code generates a new session object, or retrieves an existing one. The second line sees if the session is new by checking the value from isNew(). A true tells you the session was just created; a false means this user already had a session and you need to invalidate it. One possible reason the user would have an old session is that he or she has two accounts and logged in on one, then tried to log in on the other.
You can now add the Customer JavaBean to the session for future use. The process of placing an object into the session object is known as binding. The Customer object can be bound to the session using the setAttribute() method as follows:
session.setAttribute("CustomerBean", Customer);
Since we're working on a bank's Web site, security is a priority. To be secure, every JSP and servlet needs to verify that this user is an authorized customer before displaying any information. To accomplish this, each servlet should contain code that looks in the session for a Customer object and sends any customers who do not have this object to a login page. The following code handles this:
Customer customerBean = (Customer)
session.getAttribute('CustomerBean');
if (customerBean == null) {
response.sendRedirect
("https://www.yourservername.com/login.htm");
return;
}
The customer will have a valid Customer JavaBean in the session if he or she logged in properly. A getAttribute() on a name that does not exist in the session will always return null. Visitors with a null value need to log in, so we redirect them to a login page. This code should be placed at the top of the JSPs to prevent unauthorized use of the site. The code should also be placed in the servlets. Remember that the JSP creates the session variable for you, and in a servlet you must create it yourself. Keep in mind that this is just one way of handling security for a Web site. Some Web application servers will handle authentication and authorization for you. This example is just a simple demonstration on session management. Your Web application may require more advanced security measures.
You may have noticed that the object returned by the getAttribute() method is cast into a Customer object. This is necessary for any object bound to the session. The object is stored in the session as an Object type. To use the object in your code, you must convert it (or cast it) back to the type of object it is.
As customers move through your site, they may wish to retrieve various pieces of information about their accounts. For example, they may be able to view their checking account balance by clicking on a menu option. Following the MVC architecture, the link would send them to a servlet that would verify who they are and then create a CheckingAccount JavaBean. This object would then be stored in the session using the setAttribute() method, then the servlet would send the customer to a JSP that uses the CheckingAccount JavaBean to display the information about the customer's account.
There may be times when you want to store something in the session other than a JavaBean, such as a text string or a number. You need to remember that you can only bind objects to the session. Text may be stored as a String object. You can put a number in the session as an Integer object. The following code demonstrates how to save a line of text and a number in the session:
session.setAttribute("text","A line of text.");
session.setAttribute("number", new Integer(10750));
Remember to cast the objects when they are retrieved:
String myText = (String) session.getAttribute("text");
int myNumber = ((Integer) session.getAttribute
('number')).intValue();
Because the session is so easy to use, you may overuse it. Simple messages from a servlet to a JSP can be placed in the session as String objects, but this is not the most efficient way. Soon you'll find that your session is loaded with messages, and most of them are no longer needed. If you find that you're passing simple strings back and forth in the session, perhaps you should consider wrapping up those messages in a special JavaBean. This would keep the session more organized. The session objects for each user of a Web site are stored in memory on the server. Throwing unnecessary information into the session reduces the server's memory resources. Store only essential information in the session and use the removeAttribute() method to clean out objects after you're finished with them.
The use of the session will not only make it easier for you to program a site, but it should also help make the Web visit better for the user. The use of the beans and the session allows you to write JSPs that are customized for each user. For our bank scenario, we could use the information in the Customer bean to create personalized pages for each visitor. We can also use the bean to prepopulate forms for the customer. For example, you could use a JavaBean to store the results from a form that a visitor fills out to request information about services offered. If the user forgot to fill in a required field, you could use the JavaBean to store error messages from a servlet and then display them in the JSP. You could also populate the fields that the visitor just filled in instead of making the visitor fill out the form again.
The session is not intended to be used as a persistent place to store information about a visitor. Each visitor will be assigned a new session every time he or she logs in. A back-end database will be needed if you want to store information about individual users. The session should just be used to track the user during one visit to your site. In cases where you have a large Web site and are running multiple, redundant application servers, you'll need an application server that can handle sessions across servers. This is usually handled by placing session information into a database instead of local memory so each application server can access the information. And many of the commercial application servers will be able to do this for you.
Conclusion
The use of session tracking is an important design issue because of the complexity of today's Web sites. As Java developers, we have access to a powerful and robust session manager through the use of the HttpSession API. The session examples that we went over in this article cover the main capabilities of the session API. Learning all of Java's session management features will make your job as a Web developer easier and help you create a better experience for your Web site visitors.