Java/Servlets/Security

Материал из Java эксперт
Перейти к: навигация, поиск

Password Servlet

/*
Wireless Java 2nd edition 
Jonathan Knudsen
Publisher: Apress
ISBN: 1590590775 
*/
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
public class PasswordServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("user = " + request.getParameter("user"));
    System.out.println("timestamp = " + request.getParameter("timestamp"));
    System.out.println("random = " + request.getParameter("random"));
    System.out.println("digest = " + request.getParameter("digest"));
    
    // Retrieve the user name.
    String user = request.getParameter("user");
    // Look up the password for this user.
    String password = lookupPassword(user);
    // Pull the timestamp and random number (hex encoded) out
    //   of the request.
    String timestamp = request.getParameter("timestamp");
    String randomNumber = request.getParameter("random");
    
    // Compare the timestamp with the last saved
    //   timestamp for this user. Accept only timestamps
    //   that are greater than the last saved timestamp for this user.
    // [not implemented]
    
    // Gather values for the message digest.
    byte[] userBytes = user.getBytes();
    byte[] timestampBytes = HexCodec.hexToBytes(timestamp);
    byte[] randomBytes = HexCodec.hexToBytes(randomNumber);
    byte[] passwordBytes = password.getBytes();
    // Create the message digest.
    Digest digest = new SHA1Digest();
    // Calculate the digest value.
    digest.update(userBytes, 0, userBytes.length);
    digest.update(timestampBytes, 0, timestampBytes.length);
    digest.update(randomBytes, 0, randomBytes.length);
    digest.update(passwordBytes, 0, passwordBytes.length);
    byte[] digestValue = new byte[digest.getDigestSize()];
    digest.doFinal(digestValue, 0);
    
    // Now compare the digest values.
    String message = "";
    String clientDigest = request.getParameter("digest");
    if (isEqual(digestValue, HexCodec.hexToBytes(clientDigest)))
      message = "User " + user + " logged in.";
    else
      message = "Login was unsuccessful.";
    // Send a response to the client.
    response.setContentType("text/plain");
    response.setContentLength(message.length());
    PrintWriter out = response.getWriter();
    out.println(message);
  }
  
  private String lookupPassword(String user) {
    // Here you could do a real lookup based on the user name.
    //   You might look in a text file or a database. Here, I
    //   just use a hardcoded value.
    return "happy8";
  }
  
  private boolean isEqual(byte[] one, byte[] two) {
    if (one.length != two.length) return false;
    for (int i = 0; i < one.length; i++)
      if (one[i] != two[i]) return false;
    return true;
  }
}
class HexCodec {
  private static final char[] kDigits = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    "a", "b", "c", "d", "e", "f"
  };
  
  public static char[] bytesToHex(byte[] raw) {
    int length = raw.length;
    char[] hex = new char[length * 2];
    for (int i = 0; i < length; i++) {
      int value = (raw[i] + 256) % 256;
      int highIndex = value >> 4;
      int lowIndex = value & 0x0f;
      hex[i * 2 + 0] = kDigits[highIndex];
      hex[i * 2 + 1] = kDigits[lowIndex];
    }
    return hex;
  }
  
  public static byte[] hexToBytes(char[] hex) {
    int length = hex.length / 2;
    byte[] raw = new byte[length];
    for (int i = 0; i < length; i++) {
      int high = Character.digit(hex[i * 2], 16);
      int low = Character.digit(hex[i * 2 + 1], 16);
      int value = (high << 4) | low;
      if (value > 127) value -= 256;
      raw[i] = (byte)value;
    }
    return raw;
  }
  
  public static byte[] hexToBytes(String hex) {
    return hexToBytes(hex.toCharArray());
  }
}





Restrict User IP

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RestrictUserIP extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    PrintWriter out;
    /**
     * Status code (401) indicating that the request requires HTTP
     * authentication.
     */
    if (req.getRemoteAddr().equals("142.3.28.87")) {
      resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    resp.setContentType("text/html");
    out = resp.getWriter();
    out.println("<HTML>");
    out.println("<BODY>");
    out.println("<H1>");
    out.println("Hello!");
    out.println("<BR>");
    out.println("Your IP Address: " + req.getRemoteAddr());
    out.println("</H1>");
    out.println("</body>");
    out.println("</html>");
    out.close();
  }
}





Test Security

import  java.io.*;
import  java.net.*;
import  javax.servlet.*;
import  javax.servlet.http.*;
public class TestSecurity extends HttpServlet {
    String h2o = "<H2>";
    String h2c = "</H2>";
    String p = "<p>";
    /**
     * put your documentation comment here
     * @param req
     * @param res
     * @exception ServletException, IOException
     */
    public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        out.println("<HTML>");
        out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("<BIG>Test Security</BIG>");
        try {
            out.println(h2o + "Information..." + h2c);
            out.println("  Security Manager: " + getSecurityManager().getClass().getName()
                    + p);
            out.println("  ClassLoader: " + this.getClass().getClassLoader()
                    + p);
            //            weblogic.utils.classloaders.GenericClassLoader gcl = (weblogic.utils.classloaders.GenericClassLoader)this.getClass().getClassLoader();
            //            gcl.setDebug( true );
            out.println("  CodeSource: " + this.getClass().getProtectionDomain().getCodeSource().getLocation()
                    + p);
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        /*
         try
         {
         out.println( h2o + "Trying some dangerous J2EE calls..." + h2c );
         String hack = request.getParameter( "hack" );
         Cookie[] cookies = request.getCookies();
         out.println( " -- allowed -- " + p );
         int x = 1 + 2 + 3;
         out.println( hack );  // use it
         int y = 1 + 2 + 3;
         out.println( cookies );  // use it
         String m = "COOKIE: " + cookies[0]; // use it again
         cookies = new Cookie[10]; // reset it
         String n = "COOKIE: " + cookies[5]; // use it again
         }
         catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() + p ); }
         */
        try {
            out.println(h2o + "Attempting file write to d:/Java..." + h2c);
            File f = new File("d:/Java/blah.txt");
            FileWriter fw = new FileWriter(f);
            fw.write("test\n");
            fw.close();
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        try {
            out.println(h2o + "Attempting file write to d:/Java/TestServlet..."
                    + h2c);
            File f = new File("d:/Java/TestServlet/blah.txt");
            FileWriter fw = new FileWriter(f);
            fw.write("test\n");
            fw.close();
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        try {
            out.println(h2o + "Attempting file read to c:/Ntdetect..." + h2c);
            File f = new File("c:/Ntdetect.ru");
            FileReader fr = new FileReader(f);
            int c = fr.read();
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        try {
            out.println(h2o + "Attempting file read to c:/weblogic/weblogic.properties..."
                    + h2c);
            File f = new File("c:/weblogic/weblogic.properties");
            FileReader fr = new FileReader(f);
            int c = fr.read();
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        try {
            out.println(h2o + "Attempting to connect to yahoo.ru..." + h2c);
            Socket s = new Socket("yahoo.ru", 8080);
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        try {
            out.println(h2o + "Attempting to connect to hacker.ru..." + h2c);
            Socket s = new Socket("hacker.ru", 8080);
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        try {
            out.println(h2o + "Attempting to listen on port 37337..." + h2c);
            ServerSocket s = new ServerSocket(37337);
            Socket c = s.accept();
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        try {
            out.println(h2o + "Attempting to listen on port 7001..." + h2c);
            ServerSocket s = new ServerSocket(7001);
            Socket c = s.accept();
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        /*
         try
         {
         out.println( h2o + "Attempting native call..." + h2c );
         native0( 1 );
         out.println( " -- allowed -- " + p );
         }           
         catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() + p ); }
         */
        try {
            out.println(h2o + "Attempting exec..." + h2c);
            Runtime.getRuntime().exec("dir");
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        try {
            out.println(h2o + "Attempting system exit..." + h2c);
            out.println(" -- allowed -- " + p);
        } catch (Exception e) {
            out.println(" -- rejected -- " + e.getMessage() + p);
        }
        out.println("</BODY></HTML>");
    }
}