Browse Source

sync almost finished (wrong record used).

Mihai Plasoianu 10 years ago
parent
commit
c1faad9aa0

+ 80 - 53
src/de/tudarmstadt/informatik/hostage/logging/AttackRecord.java

@@ -8,10 +8,10 @@ import android.os.Parcelable;
 /**
  * Holds all necessary information about a single attack.
  */
-public class AttackRecord implements Parcelable, Serializable{
-	
+public class AttackRecord implements Parcelable, Serializable {
+
 	private static final long serialVersionUID = 6111024905373724227L;
-	
+
 	private long attack_id;
 	private String bssid;
 	private String protocol;
@@ -20,155 +20,182 @@ public class AttackRecord implements Parcelable, Serializable{
 	private String remoteIP;
 	private int remotePort;
 	private String externalIP;
-	
-	
-    public static final Parcelable.Creator<AttackRecord> CREATOR = new Parcelable.Creator<AttackRecord>() {
-    	@Override
-        public AttackRecord createFromParcel(Parcel source) {
-                    return new AttackRecord(source);
-            }
-
-            @Override
-            public AttackRecord[] newArray(int size) {
-            	return new AttackRecord[size];
-            }
-    };
-
-    public AttackRecord() {
-
-    }
-
-    public AttackRecord(Parcel source) {
-            this.attack_id = source.readLong();
-            this.protocol = source.readString();
-            this.localIP = source.readString();
-            this.localPort = source.readInt();
-            this.remoteIP = source.readString();
-            this.remotePort = source.readInt();
-            this.externalIP = source.readString();
-            this.bssid = source.readString();
-    }
-	
+
+	public static final Parcelable.Creator<AttackRecord> CREATOR = new Parcelable.Creator<AttackRecord>() {
+		@Override
+		public AttackRecord createFromParcel(Parcel source) {
+			return new AttackRecord(source);
+		}
+
+		@Override
+		public AttackRecord[] newArray(int size) {
+			return new AttackRecord[size];
+		}
+	};
+
+	public AttackRecord() {
+
+	}
+
+	public AttackRecord(Parcel source) {
+		this.attack_id = source.readLong();
+		this.protocol = source.readString();
+		this.localIP = source.readString();
+		this.localPort = source.readInt();
+		this.remoteIP = source.readString();
+		this.remotePort = source.readInt();
+		this.externalIP = source.readString();
+		this.bssid = source.readString();
+	}
+
 	@Override
 	public int describeContents() {
 		return 0;
 	}
-	
+
 	@Override
 	public void writeToParcel(Parcel dest, int flags) {
-        dest.writeLong(attack_id);
-        dest.writeString(protocol);
-        dest.writeString(localIP);
-        dest.writeInt(localPort);
-        dest.writeString(remoteIP);
-        dest.writeInt(remotePort);
-        dest.writeString(externalIP);
-        dest.writeString(bssid);
+		dest.writeLong(attack_id);
+		dest.writeString(protocol);
+		dest.writeString(localIP);
+		dest.writeInt(localPort);
+		dest.writeString(remoteIP);
+		dest.writeInt(remotePort);
+		dest.writeString(externalIP);
+		dest.writeString(bssid);
 	}
-	
+
 	/**
 	 * @return the attack_id
 	 */
 	public long getAttack_id() {
 		return attack_id;
 	}
+
 	/**
-	 * @param attack_id the attack_id to set
+	 * @param attack_id
+	 *            the attack_id to set
 	 */
 	public void setAttack_id(long attack_id) {
 		this.attack_id = attack_id;
 	}
+
 	/**
 	 * @return the bssid
 	 */
 	public String getBssid() {
 		return bssid;
 	}
+
 	/**
-	 * @param bssid the bssid to set
+	 * @param bssid
+	 *            the bssid to set
 	 */
 	public void setBssid(String bssid) {
 		this.bssid = bssid;
 	}
+
 	/**
 	 * @return the protocol
 	 */
 	public String getProtocol() {
 		return protocol;
 	}
+
 	/**
-	 * @param protocol the protocol to set
+	 * @param protocol
+	 *            the protocol to set
 	 */
 	public void setProtocol(String protocol) {
 		this.protocol = protocol;
 	}
+
 	/**
 	 * @return the localIP
 	 */
 	public String getLocalIP() {
 		return localIP;
 	}
+
 	/**
-	 * @param localIP the localIP to set
+	 * @param localIP
+	 *            the localIP to set
 	 */
 	public void setLocalIP(String localIP) {
 		this.localIP = localIP;
 	}
+
 	/**
 	 * @return the localPort
 	 */
 	public int getLocalPort() {
 		return localPort;
 	}
+
 	/**
-	 * @param localPort the localPort to set
+	 * @param localPort
+	 *            the localPort to set
 	 */
 	public void setLocalPort(int localPort) {
 		this.localPort = localPort;
 	}
+
 	/**
 	 * @return the remoteIP
 	 */
 	public String getRemoteIP() {
 		return remoteIP;
 	}
+
 	/**
-	 * @param remoteIP the remoteIP to set
+	 * @param remoteIP
+	 *            the remoteIP to set
 	 */
 	public void setRemoteIP(String remoteIP) {
 		this.remoteIP = remoteIP;
 	}
+
 	/**
 	 * @return the remotePort
 	 */
 	public int getRemotePort() {
 		return remotePort;
 	}
+
 	/**
-	 * @param remotePort the remotePort to set
+	 * @param remotePort
+	 *            the remotePort to set
 	 */
 	public void setRemotePort(int remotePort) {
 		this.remotePort = remotePort;
 	}
+
 	/**
 	 * @return the externalIP
 	 */
 	public String getExternalIP() {
 		return externalIP;
 	}
+
 	/**
-	 * @param externalIP the externalIP to set
+	 * @param externalIP
+	 *            the externalIP to set
 	 */
 	public void setExternalIP(String externalIP) {
 		this.externalIP = externalIP;
 	}
-	
-	//TEMP ZU TEST
+
+	// TEMP ZU TEST
 	@Override
-	public String toString(){
+	public String toString() {
 		return String
 				.format("{ \"sensor\":{\"type\": \"Honeypot\", \"name\": \"HosTaGe\"}, \"type\": \"%s server access\", \"src\":{\"ip\": \"%s\", \"port\": %d}, \"dst\":{\"ip\": \"%s\", \"port\": %d} }",
 						getProtocol(), getRemoteIP(), getRemotePort(), getExternalIP(), getLocalPort());
 	}
 
+	public String toJSON() {
+		return String.format("{\"bssid\":\"%s\",\"ssid\":\"%s\",\"latitude\":%d,\"longitude\":%d,\"timestamp\":%d,\"attacks\":%d,\"portscans\":%d}", "bssid",
+				"ssid", 23, 32, 123456, 22, 2);
+	}
+
 }

+ 84 - 48
src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java

@@ -1,5 +1,11 @@
 package de.tudarmstadt.informatik.hostage.sync.tracing;
 
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.HttpURLConnection;
+import java.net.URL;
 import java.security.KeyStore;
 import java.util.ArrayList;
 
@@ -34,27 +40,27 @@ import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
 /**
  * Service that synchronizes with a specified remote server.
+ * 
  * @author Lars Pandikow
  */
-public class TracingSyncService extends IntentService{
-	
+public class TracingSyncService extends IntentService {
+
 	public static final String REMOTE_DEVICE = "de.tudarmstadt.informatik.hostage.REMOTE_DEVICE";
-	
+
 	public static final String ACTION_START_SYNC = "de.tudarmstadt.informatik.hostage.ACTION_START_SYNC";
 	public static final String EXTRA_RECEIVER = "de.tudarmstadt.informatik.hostage.EXTRA_HANDLER";
-	
+
 	public static final String UPLOAD_SIZE = "de.tudarmstadt.informatik.hostage.UPLOAD_SIZE";
 	public static final String UPLOAD_PROGRESS = "de.tudarmstadt.informatik.hostage.UPLOAD_PROGRESS";
-	
+
 	public static final int RECORD_UPLOADED = 0x00;
 	public static final int SYNC_COMPLETE = 0x01;
-	
-	
+
 	private HttpClient httpClient;
 	private ResultReceiver receiver;
-	
+
 	HostageDBOpenHelper dbh;
-	
+
 	SharedPreferences pref;
 	Editor editor;
 
@@ -62,7 +68,6 @@ public class TracingSyncService extends IntentService{
 		super(TracingSyncService.class.getName());
 
 	}
-	
 
 	@Override
 	public void onCreate() {
@@ -74,8 +79,8 @@ public class TracingSyncService extends IntentService{
 
 	/**
 	 * The IntentService calls this method from the default worker thread with
-	 * the intent that started the service. When this method returns, IntentService
-	 * stops the service, as appropriate.
+	 * the intent that started the service. When this method returns,
+	 * IntentService stops the service, as appropriate.
 	 */
 	@Override
 	protected void onHandleIntent(Intent intent) {
@@ -83,80 +88,116 @@ public class TracingSyncService extends IntentService{
 			final String action = intent.getAction();
 			if (ACTION_START_SYNC.equals(action)) {
 				receiver = intent.getParcelableExtra(EXTRA_RECEIVER);
-				uploadNewRecords();
-				//TODO add: dbh.clearSyncInfos();
+				syncNewRecords();
+				dbh.clearSyncInfos();
 				getRemoteData();
-				if(receiver != null){
+				if (receiver != null) {
 					receiver.send(SYNC_COMPLETE, null);
 				}
 			}
 
-		}	
-	}	
-	
-	
+		}
+	}
+
 	/**
 	 * Uploads all new Records to a server, specified in the settings.
 	 */
-	private void uploadNewRecords() {
+	private void syncNewRecords() {
 		int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
-		String serverAddress = pref.getString("pref_upload", "https://ssi.cased.de");	
+		// String serverAddress = pref.getString("pref_upload",
+		// "https://ssi.cased.de");
+		String serverAddress = "http://87.230.23.240/hostage/push.php";
 		ArrayList<AttackRecord> recordList = dbh.getRecordOfEachAttack(lastUploadedAttackId);
 		int size = recordList.size();
 		int offset = 1;
-		for(AttackRecord record: recordList){
+		for (AttackRecord record : recordList) {
 			editor.putInt("LAST_UPLOADED_ATTACK_ID", lastUploadedAttackId + offset);
 			editor.commit();
-			
+
 			boolean success = uploadSingleRecord(record, serverAddress);
-			Log.i("Tracing upload", "Upload of record: " + offset +"/" + size + ((success) ? " successful.": " failed."));
-			if(receiver != null){
+			Log.i("Tracing upload", "Upload of record: " + offset + "/" + size + ((success) ? " successful." : " failed."));
+			if (receiver != null) {
 				Bundle data = new Bundle();
-				data.putInt(UPLOAD_SIZE, size); 
+				data.putInt(UPLOAD_SIZE, size);
 				data.putInt(UPLOAD_PROGRESS, offset);
 				receiver.send(RECORD_UPLOADED, data);
 			}
-			offset++;			
+			offset++;
+
+			// TODO pull
+			// getRemoteData(record.getBssid(), record.getTimestamp());
 		}
-	}	
-	
+	}
+
 	/**
 	 * Uploads a single Record to a server, specified in the settings.
 	 * 
-	 * @param record The Record to upload.
+	 * @param record
+	 *            The Record to upload.
 	 * @serverAddress Address of the target server
 	 * @return True if the upload was successful, else false.
 	 */
 	private boolean uploadSingleRecord(AttackRecord record, String serverAddress) {
-		// Create a https client. Uses MySSLSocketFactory to accept all certificates
+		// Create a https client. Uses MySSLSocketFactory to accept all
+		// certificates
 		HttpPost httppost;
 		try {
 			httpClient = createHttpClient();
 			// Create HttpPost
 			httppost = new HttpPost(serverAddress);
 			// Create JSON String of Record
-			//TODO FIX ME
-			//StringEntity se = new StringEntity( record.toString(TraCINgFormatter.getInstance()) );
-			StringEntity se = new StringEntity(record.toString());
+			// TODO StringEntity se = new
+			// StringEntity(record.toString(TraCINgFormatter.getInstance()));
+			StringEntity se = new StringEntity("record=" + record.toJSON()); // FIXME
+			httppost.addHeader("content-type", "application/x-www-form-urlencoded");
 			httppost.setEntity(se);
 			// Execute HttpPost
 			HttpResponse response = httpClient.execute(httppost);
-			Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode()); 
+			Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
 		} catch (Exception e) {
 			e.printStackTrace();
 			return false;
 		}
 		return true;
 	}
-	
+
 	/**
 	 * Gets the data from the server and updates the database.
 	 */
-	private void getRemoteData() {
-		//TODO GET DATA FROM SERVER
-		//TODO SAVE DATA IN DATABASE
+	private void getRemoteData(String bssid, long timestamp) {
+		HttpURLConnection connection;
+		OutputStreamWriter request = null;
+		URL url = null;
+		String response = null;
+		String parameters = "bssid=" + bssid + "timestamp=" + timestamp;
+		try {
+			url = new URL("http://87.230.23.240/hostage/pull.php");
+			connection = (HttpURLConnection) url.openConnection();
+			connection.setDoOutput(true);
+			connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
+			connection.setRequestMethod("POST");
+
+			request = new OutputStreamWriter(connection.getOutputStream());
+			request.write(parameters);
+			request.flush();
+			request.close();
+			String line = "";
+
+			InputStreamReader isr = new InputStreamReader(connection.getInputStream());
+			BufferedReader reader = new BufferedReader(isr);
+			StringBuilder sb = new StringBuilder();
+			while ((line = reader.readLine()) != null) {
+				sb.append(line);
+			}
+			response = sb.toString();
+			isr.close();
+			reader.close();
+			Log.d("TEST", response);
+		} catch (IOException e) {
+			Log.i("NetworkTest", "Network Error: " + e);
+		}
 	}
-	
+
 	/**
 	 * Creates a HttpClient with an own SSL Socket.
 	 * 
@@ -165,8 +206,7 @@ public class TracingSyncService extends IntentService{
 	 */
 	private HttpClient createHttpClient() {
 		try {
-			KeyStore trustStore = KeyStore.getInstance(KeyStore
-					.getDefaultType());
+			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
 			trustStore.load(null, null);
 
 			SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
@@ -177,12 +217,10 @@ public class TracingSyncService extends IntentService{
 			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
 
 			SchemeRegistry registry = new SchemeRegistry();
-			registry.register(new Scheme("http", PlainSocketFactory
-					.getSocketFactory(), 80));
+			registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
 			registry.register(new Scheme("https", sf, 443));
 
-			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
-					params, registry);
+			ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
 
 			return new DefaultHttpClient(ccm, params);
 		} catch (Exception e) {
@@ -191,6 +229,4 @@ public class TracingSyncService extends IntentService{
 		}
 	}
 
-
-
 }

+ 86 - 69
src/de/tudarmstadt/informatik/hostage/ui2/fragment/HomeFragment.java

@@ -4,12 +4,10 @@ import java.util.ArrayList;
 
 import android.annotation.SuppressLint;
 import android.app.Activity;
-import android.app.AlertDialog;
 import android.app.Fragment;
 import android.app.FragmentManager;
 import android.content.BroadcastReceiver;
 import android.content.Context;
-import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.SharedPreferences;
@@ -27,6 +25,7 @@ import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRenderer;
@@ -263,73 +262,91 @@ public class HomeFragment extends Fragment {
 		if (switchChangeListener == null) {
 			switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
 				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-					if (!HelperUtils.isWifiConnected(getActivity())) {
-						new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
-								.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-									public void onClick(DialogInterface dialog, int which) {
-
-									}
-								}).setIcon(android.R.drawable.ic_dialog_info).show();
-
-						setStateNotActive();
-						setStateNotConnected();
-					} else {
-						if (isChecked) {
-							boolean protocolActivated = false;
-							if (ProfileManager.getInstance().getCurrentActivatedProfile() == null) {
-								for (String protocol : getResources().getStringArray(R.array.protocols)) {
-									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
-										MainActivity.getInstance().getHostageService().startListener(protocol);
-										protocolActivated = true;
-									}
-								}
-							} else {
-								ProfileManager profileManager = ProfileManager.getInstance();
-
-								if (profileManager.isRandomActive()) {
-									profileManager.randomizeProtocols(profileManager.getRandomProfile());
-								}
-
-								for (String protocol : profileManager.getCurrentActivatedProfile().getActiveProtocols()) {
-									if (protocol.equals("GHOST"))
-										continue;
-
-									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
-										MainActivity.getInstance().getHostageService().startListener(protocol);
-										protocolActivated = true;
-									}
-								}
-
-								Profile currentProfile = profileManager.getCurrentActivatedProfile();
-
-								if (currentProfile.mGhostActive) {
-									for (int port : currentProfile.getGhostPorts()) {
-										MainActivity.getInstance().getHostageService().startListener("GHOST", port);
-										protocolActivated = true;
-									}
-								}
-							}
-
-							if (protocolActivated) {
-								setStateActive();
-							} else {
-								new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.profile_no_services_msg)
-										.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-											public void onClick(DialogInterface dialog, int which) {
-
-											}
-										}).setIcon(android.R.drawable.ic_dialog_info).show();
-
-								setStateNotActive();
-							}
-						} else {
-							if (MainActivity.getInstance().getHostageService() != null) {
-								MainActivity.getInstance().getHostageService().stopListeners();
-								MainActivity.getInstance().stopAndUnbind();
-							}
-							setStateNotActive();
-						}
-					}
+					startActivity(new Intent(getActivity(), TracingSyncActivity.class));
+					// if (!HelperUtils.isWifiConnected(getActivity())) {
+					// new
+					// AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
+					// .setPositiveButton(android.R.string.ok, new
+					// DialogInterface.OnClickListener() {
+					// public void onClick(DialogInterface dialog, int which) {
+					//
+					// }
+					// }).setIcon(android.R.drawable.ic_dialog_info).show();
+					//
+					// setStateNotActive();
+					// setStateNotConnected();
+					// } else {
+					// if (isChecked) {
+					// boolean protocolActivated = false;
+					// if
+					// (ProfileManager.getInstance().getCurrentActivatedProfile()
+					// == null) {
+					// for (String protocol :
+					// getResources().getStringArray(R.array.protocols)) {
+					// if
+					// (!MainActivity.getInstance().getHostageService().isRunning(protocol))
+					// {
+					// MainActivity.getInstance().getHostageService().startListener(protocol);
+					// protocolActivated = true;
+					// }
+					// }
+					// } else {
+					// ProfileManager profileManager =
+					// ProfileManager.getInstance();
+					//
+					// if (profileManager.isRandomActive()) {
+					// profileManager.randomizeProtocols(profileManager.getRandomProfile());
+					// }
+					//
+					// for (String protocol :
+					// profileManager.getCurrentActivatedProfile().getActiveProtocols())
+					// {
+					// if (protocol.equals("GHOST"))
+					// continue;
+					//
+					// if
+					// (!MainActivity.getInstance().getHostageService().isRunning(protocol))
+					// {
+					// MainActivity.getInstance().getHostageService().startListener(protocol);
+					// protocolActivated = true;
+					// }
+					// }
+					//
+					// Profile currentProfile =
+					// profileManager.getCurrentActivatedProfile();
+					//
+					// if (currentProfile.mGhostActive) {
+					// for (int port : currentProfile.getGhostPorts()) {
+					// MainActivity.getInstance().getHostageService().startListener("GHOST",
+					// port);
+					// protocolActivated = true;
+					// }
+					// }
+					// }
+					//
+					// if (protocolActivated) {
+					// setStateActive();
+					// } else {
+					// new
+					// AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.profile_no_services_msg)
+					// .setPositiveButton(android.R.string.ok, new
+					// DialogInterface.OnClickListener() {
+					// public void onClick(DialogInterface dialog, int which) {
+					//
+					// }
+					// }).setIcon(android.R.drawable.ic_dialog_info).show();
+					//
+					// setStateNotActive();
+					// }
+					// } else {
+					// if (MainActivity.getInstance().getHostageService() !=
+					// null) {
+					// MainActivity.getInstance().getHostageService().stopListeners();
+					// MainActivity.getInstance().stopAndUnbind();
+					// }
+					// setStateNotActive();
+					// }
+					// }
 				}
 			};
 		}