TracingSyncService.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package de.tudarmstadt.informatik.hostage.sync.tracing;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStream;
  6. import java.io.OutputStreamWriter;
  7. import java.io.StringWriter;
  8. import java.io.Writer;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11. import java.security.KeyStore;
  12. import java.util.ArrayList;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.HttpVersion;
  17. import org.apache.http.client.HttpClient;
  18. import org.apache.http.client.methods.HttpPost;
  19. import org.apache.http.conn.ClientConnectionManager;
  20. import org.apache.http.conn.scheme.PlainSocketFactory;
  21. import org.apache.http.conn.scheme.Scheme;
  22. import org.apache.http.conn.scheme.SchemeRegistry;
  23. import org.apache.http.conn.ssl.SSLSocketFactory;
  24. import org.apache.http.entity.StringEntity;
  25. import org.apache.http.impl.client.DefaultHttpClient;
  26. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  27. import org.apache.http.params.BasicHttpParams;
  28. import org.apache.http.params.HttpParams;
  29. import org.apache.http.params.HttpProtocolParams;
  30. import org.apache.http.protocol.HTTP;
  31. import org.json.JSONException;
  32. import org.json.JSONObject;
  33. import android.app.IntentService;
  34. import android.content.Intent;
  35. import android.content.SharedPreferences;
  36. import android.content.SharedPreferences.Editor;
  37. import android.os.Bundle;
  38. import android.os.ResultReceiver;
  39. import android.preference.PreferenceManager;
  40. import android.util.Log;
  41. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  42. import de.tudarmstadt.informatik.hostage.logging.Record;
  43. import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
  44. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  45. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  46. import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
  47. /**
  48. * Service that synchronizes with a specified remote server.
  49. *
  50. * @author Lars Pandikow
  51. */
  52. public class TracingSyncService extends IntentService {
  53. public static final String REMOTE_DEVICE = "de.tudarmstadt.informatik.hostage.REMOTE_DEVICE";
  54. public static final String ACTION_START_SYNC = "de.tudarmstadt.informatik.hostage.ACTION_START_SYNC";
  55. public static final String EXTRA_RECEIVER = "de.tudarmstadt.informatik.hostage.EXTRA_HANDLER";
  56. public static final String UPLOAD_SIZE = "de.tudarmstadt.informatik.hostage.UPLOAD_SIZE";
  57. public static final String UPLOAD_PROGRESS = "de.tudarmstadt.informatik.hostage.UPLOAD_PROGRESS";
  58. public static final int RECORD_UPLOADED = 0x00;
  59. public static final int SYNC_COMPLETE = 0x01;
  60. public static Map<String, Integer> protocolsTypeMap;
  61. private HttpClient httpClient;
  62. private ResultReceiver receiver;
  63. HostageDBOpenHelper dbh;
  64. SharedPreferences pref;
  65. Editor editor;
  66. static {
  67. protocolsTypeMap = new HashMap<String, Integer>();
  68. protocolsTypeMap.put("ECHO", 10);
  69. protocolsTypeMap.put("FTP", 0);
  70. protocolsTypeMap.put("GHOST", 0);
  71. protocolsTypeMap.put("HTTP", 0);
  72. protocolsTypeMap.put("HTTPS", 0);
  73. protocolsTypeMap.put("MySQL", 31);
  74. protocolsTypeMap.put("SIP", 50);
  75. protocolsTypeMap.put("SMB", 40);
  76. protocolsTypeMap.put("TELNET", 0);
  77. }
  78. public TracingSyncService() {
  79. super(TracingSyncService.class.getName());
  80. }
  81. @Override
  82. public void onCreate() {
  83. super.onCreate();
  84. pref = PreferenceManager.getDefaultSharedPreferences(this);
  85. editor = pref.edit();
  86. dbh = new HostageDBOpenHelper(this);
  87. }
  88. /**
  89. * The IntentService calls this method from the default worker thread with
  90. * the intent that started the service. When this method returns,
  91. * IntentService stops the service, as appropriate.
  92. */
  93. @Override
  94. protected void onHandleIntent(Intent intent) {
  95. if (intent != null) {
  96. final String action = intent.getAction();
  97. if (ACTION_START_SYNC.equals(action)) {
  98. receiver = intent.getParcelableExtra(EXTRA_RECEIVER);
  99. syncNewRecords();
  100. dbh.clearSyncInfos();
  101. if (receiver != null) {
  102. receiver.send(SYNC_COMPLETE, null);
  103. }
  104. }
  105. }
  106. }
  107. /**
  108. * Uploads all new Records to a server, specified in the settings.
  109. */
  110. private void syncNewRecords() {
  111. long lastSyncTime = pref.getLong("LAST_SYNC_TIME", 0);
  112. String serverAddress = pref.getString("pref_upload", "https://ssi.cased.de"); //"https://192.168.1.118:9999"
  113. LogFilter filter = new LogFilter();
  114. filter.setAboveTimestamp(lastSyncTime);
  115. ArrayList<Record> records = dbh.getRecordsForFilter(filter);
  116. StringWriter writer = new StringWriter();
  117. int size = records.size();
  118. int offset = 1;
  119. int currOffset = 1;
  120. for (Record record : records) {
  121. appendRecordToStringWriter(record, writer);
  122. if(currOffset == 5 || offset == size){
  123. boolean success = uploadRecordsToServer(writer.toString(), serverAddress);
  124. Log.i("Tracing upload", "Upload of record: " + offset + "/" + size + ((success) ? " successful." : " failed."));
  125. if (receiver != null) {
  126. Bundle data = new Bundle();
  127. data.putInt(UPLOAD_SIZE, size);
  128. data.putInt(UPLOAD_PROGRESS, offset);
  129. receiver.send(RECORD_UPLOADED, data);
  130. }
  131. writer.getBuffer().setLength(0);
  132. currOffset = 0;
  133. }
  134. offset++;
  135. currOffset++;
  136. }
  137. pref.edit().putLong("LAST_SYNC_TIME", System.currentTimeMillis()).apply();
  138. }
  139. private void appendRecordToStringWriter(Record record, Writer stream){
  140. try {
  141. stream.append(
  142. "{" +
  143. "\"sensor\":{" +
  144. "\"name\":\"HosTaGe\"," +
  145. "\"type\":\"Honeypot\"" +
  146. "}," +
  147. "\"src\":{" +
  148. "\"ip\":\"" + record.getRemoteIP() + "\"," +
  149. "\"port\":" + record.getRemotePort() +
  150. "}," +
  151. "\"dst\":{" +
  152. "\"ip\":\"" + record.getExternalIP() /*record.getLocalIP()*/ + "\"," +
  153. "\"port\":" + record.getLocalPort() +
  154. "}," +
  155. "\"type\":" + (protocolsTypeMap.containsKey(record.getProtocol()) ? protocolsTypeMap.get(record.getProtocol()) : 0) + "," +
  156. "\"log\":\"" + record.getProtocol() + "\"," +
  157. "\"md5sum\":\"\"," +
  158. "\"date\":" + (int)(record.getTimestamp() / 1000) +
  159. "}\n"
  160. );
  161. } catch (IOException e) {
  162. e.printStackTrace();
  163. }
  164. }
  165. private boolean uploadRecordsToServer(String entity, String serverAddress){
  166. HttpPost httppost;
  167. try {
  168. httpClient = createHttpClient();
  169. // Create HttpPost
  170. httppost = new HttpPost(serverAddress);
  171. StringEntity se = new StringEntity(entity);
  172. httppost.addHeader("content-type", "application/json+newline");
  173. httppost.setEntity(se);
  174. // Execute HttpPost
  175. HttpResponse response = httpClient.execute(httppost);
  176. Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
  177. } catch (Exception e) {
  178. e.printStackTrace();
  179. return false;
  180. }
  181. return true;
  182. }
  183. /**
  184. * Gets the data from the server and updates the database.
  185. */
  186. private void getRemoteData(String bssid, long timestamp) {
  187. HttpURLConnection connection;
  188. OutputStreamWriter request = null;
  189. URL url = null;
  190. String response = null;
  191. String parameters = "bssid=" + bssid;
  192. try {
  193. url = new URL("http://87.230.23.240/hostage/pull.php");
  194. connection = (HttpURLConnection) url.openConnection();
  195. connection.setDoOutput(true);
  196. connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
  197. connection.setRequestMethod("POST");
  198. request = new OutputStreamWriter(connection.getOutputStream());
  199. request.write(parameters);
  200. request.flush();
  201. request.close();
  202. String line = "";
  203. InputStreamReader isr = new InputStreamReader(connection.getInputStream());
  204. BufferedReader reader = new BufferedReader(isr);
  205. StringBuilder sb = new StringBuilder();
  206. while ((line = reader.readLine()) != null) {
  207. sb.append(line);
  208. }
  209. response = sb.toString();
  210. JSONObject jsonObj = new JSONObject(response);
  211. NetworkRecord net = new NetworkRecord();
  212. net.setBssid(jsonObj.getString("bssid"));
  213. net.setSsid(jsonObj.getString("ssid"));
  214. net.setLatitude(jsonObj.getDouble("latitude"));
  215. net.setLongitude(jsonObj.getDouble("longitude"));
  216. net.setTimestampLocation(jsonObj.getLong("timestamp"));
  217. SyncInfoRecord sync = new SyncInfoRecord();
  218. sync.setBSSID(jsonObj.getString("bssid"));
  219. sync.setDeviceID("-1");
  220. sync.setNumber_of_attacks(jsonObj.getLong("attacks"));
  221. sync.setNumber_of_portscans(jsonObj.getLong("portscans"));
  222. dbh.updateNetworkInformation(net);
  223. isr.close();
  224. reader.close();
  225. } catch (IOException e) {
  226. Log.i("NetworkTest", "Network Error: " + e);
  227. } catch (JSONException e) {
  228. e.printStackTrace();
  229. }
  230. }
  231. /**
  232. * Creates a HttpClient with an own SSL Socket.
  233. *
  234. * @return HttpsClient who accepts accepts all certificates.
  235. * @see MySSLSocketFactory
  236. */
  237. private HttpClient createHttpClient() {
  238. try {
  239. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  240. trustStore.load(null, null);
  241. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  242. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  243. HttpParams params = new BasicHttpParams();
  244. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  245. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  246. SchemeRegistry registry = new SchemeRegistry();
  247. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  248. registry.register(new Scheme("https", sf, 443));
  249. ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  250. return new DefaultHttpClient(ccm, params);
  251. } catch (Exception e) {
  252. e.printStackTrace();
  253. return new DefaultHttpClient();
  254. }
  255. }
  256. }