SyncUtils.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. package de.tudarmstadt.informatik.hostage.sync.android;
  2. import android.accounts.Account;
  3. import android.accounts.AccountManager;
  4. import android.content.ContentResolver;
  5. import android.content.Context;
  6. import android.content.SharedPreferences;
  7. import android.location.Location;
  8. import android.os.Bundle;
  9. import android.preference.PreferenceManager;
  10. import android.telephony.TelephonyManager;
  11. import android.util.Log;
  12. import org.apache.http.HttpResponse;
  13. import org.apache.http.HttpVersion;
  14. import org.apache.http.client.HttpClient;
  15. import org.apache.http.client.methods.HttpGet;
  16. import org.apache.http.client.methods.HttpPost;
  17. import org.apache.http.conn.ClientConnectionManager;
  18. import org.apache.http.conn.scheme.PlainSocketFactory;
  19. import org.apache.http.conn.scheme.Scheme;
  20. import org.apache.http.conn.scheme.SchemeRegistry;
  21. import org.apache.http.conn.ssl.SSLSocketFactory;
  22. import org.apache.http.entity.StringEntity;
  23. import org.apache.http.impl.client.DefaultHttpClient;
  24. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  25. import org.apache.http.params.BasicHttpParams;
  26. import org.apache.http.params.HttpParams;
  27. import org.apache.http.params.HttpProtocolParams;
  28. import org.apache.http.protocol.HTTP;
  29. import org.json.JSONArray;
  30. import org.json.JSONException;
  31. import org.json.JSONObject;
  32. import java.io.BufferedReader;
  33. import java.io.IOException;
  34. import java.io.InputStreamReader;
  35. import java.io.UnsupportedEncodingException;
  36. import java.io.Writer;
  37. import java.net.URLEncoder;
  38. import java.security.KeyStore;
  39. import java.text.ParseException;
  40. import java.text.SimpleDateFormat;
  41. import java.util.ArrayList;
  42. import java.util.Calendar;
  43. import java.util.Date;
  44. import java.util.GregorianCalendar;
  45. import java.util.HashMap;
  46. import java.util.List;
  47. import java.util.Map;
  48. import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
  49. import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
  50. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  51. import de.tudarmstadt.informatik.hostage.logging.Record;
  52. import de.tudarmstadt.informatik.hostage.logging.SyncData;
  53. import de.tudarmstadt.informatik.hostage.logging.SyncInfo;
  54. import de.tudarmstadt.informatik.hostage.logging.SyncRecord;
  55. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  56. import de.tudarmstadt.informatik.hostage.sync.Synchronizer;
  57. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  58. /**
  59. * Created by abrakowski
  60. */
  61. public class SyncUtils {
  62. public static final int SYNC_SUCCESSFUL = 0x0;
  63. private static final long SYNC_FREQUENCY = 60 * 60; // 1 hour (in seconds)
  64. public static final String CONTENT_AUTHORITY = "de.tudarmstadt.informatik.hostage.androidsync";
  65. private static final String PREF_SETUP_COMPLETE = "sync_setup_complete";
  66. private static final Map<String, Integer> protocolsTypeMap;
  67. static {
  68. protocolsTypeMap = new HashMap<String, Integer>();
  69. protocolsTypeMap.put("UNKNOWN", 0);
  70. protocolsTypeMap.put("ECHO", 1);
  71. protocolsTypeMap.put("GHOST", 2);
  72. protocolsTypeMap.put("PORTSCAN", 11);
  73. protocolsTypeMap.put("SSH", 20);
  74. protocolsTypeMap.put("MySQL", 31);
  75. protocolsTypeMap.put("SMB", 40);
  76. protocolsTypeMap.put("SIP", 50);
  77. protocolsTypeMap.put("FTP", 60);
  78. protocolsTypeMap.put("HTTP", 70);
  79. protocolsTypeMap.put("HTTPS", 71);
  80. protocolsTypeMap.put("TELNET", 80);
  81. }
  82. /**
  83. * Create an entry for this application in the system account list, if it isn't already there.
  84. *
  85. * @param context Context
  86. */
  87. public static void CreateSyncAccount(Context context) {
  88. boolean newAccount = false;
  89. boolean setupComplete = PreferenceManager
  90. .getDefaultSharedPreferences(context).getBoolean(PREF_SETUP_COMPLETE, false);
  91. // Create account, if it's missing. (Either first run, or user has deleted account.)
  92. Account account = HostageAccountService.GetAccount();
  93. AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
  94. if (accountManager.addAccountExplicitly(account, null, null)) {
  95. // Inform the system that this account supports sync
  96. ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
  97. // Inform the system that this account is eligible for auto sync when the network is up
  98. ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
  99. // Recommend a schedule for automatic synchronization. The system may modify this based
  100. // on other scheduled syncs and network utilization.
  101. ContentResolver.addPeriodicSync(
  102. account, CONTENT_AUTHORITY, new Bundle(),SYNC_FREQUENCY);
  103. newAccount = true;
  104. }
  105. // Schedule an initial sync if we detect problems with either our account or our local
  106. // data has been deleted. (Note that it's possible to clear app data WITHOUT affecting
  107. // the account list, so wee need to check both.)
  108. if (newAccount || !setupComplete) {
  109. TriggerRefresh();
  110. PreferenceManager.getDefaultSharedPreferences(context).edit()
  111. .putBoolean(PREF_SETUP_COMPLETE, true).commit();
  112. }
  113. }
  114. public static void TriggerRefresh() {
  115. Bundle b = new Bundle();
  116. // Disable sync backoff and ignore sync preferences. In other words...perform sync NOW!
  117. b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  118. b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  119. ContentResolver.requestSync(
  120. HostageAccountService.GetAccount(), // Sync account
  121. CONTENT_AUTHORITY, // Content authority
  122. b); // Extras
  123. }
  124. public static String getProtocolFromInt(int p){
  125. for(Map.Entry<String, Integer> entry: protocolsTypeMap.entrySet()){
  126. if(entry.getValue() == p) return entry.getKey();
  127. }
  128. return "UNKNOWN";
  129. }
  130. public static void appendRecordToStringWriter(Record record, Writer stream){
  131. try {
  132. stream.append(
  133. "{" +
  134. "\"sensor\":{" +
  135. "\"name\":\"HosTaGe\"," +
  136. "\"type\":\"Honeypot\"" +
  137. "}," +
  138. "\"src\":{" +
  139. "\"ip\":\"" + record.getRemoteIP() + "\"," +
  140. "\"port\":" + record.getRemotePort() +
  141. "}," +
  142. "\"dst\":{" +
  143. "\"ip\":\"" + record.getLocalIP() + "\"," +
  144. "\"port\":" + record.getLocalPort() +
  145. "}," +
  146. "\"type\":" + (protocolsTypeMap.containsKey(record.getProtocol()) ? protocolsTypeMap.get(record.getProtocol()) : 0) + "," +
  147. "\"log\":\"" + record.getProtocol() + "\"," +
  148. "\"md5sum\":\"\"," +
  149. "\"date\":" + (int)(record.getTimestamp() / 1000) + "," +
  150. "\"bssid\":\"" + record.getBssid() + "\"," +
  151. "\"ssid\":\"" + record.getSsid() + "\"," +
  152. "\"device\":\"" + record.getDevice() + "\"," +
  153. "\"sync_id\":\"" + record.getSync_id() + "\"," +
  154. "\"internal_attack\":\"" + record.getWasInternalAttack() + "\"," +
  155. "\"external_ip\":\"" + record.getExternalIP() + "\"" +
  156. "}\n"
  157. );
  158. } catch (IOException e) {
  159. e.printStackTrace();
  160. }
  161. }
  162. public static boolean uploadRecordsToServer(String entity, String serverAddress){
  163. HttpPost httppost;
  164. try {
  165. HttpClient httpClient = createHttpClient();
  166. // Create HttpPost
  167. httppost = new HttpPost(serverAddress);
  168. StringEntity se = new StringEntity(entity);
  169. httppost.addHeader("content-type", "application/json+newline");
  170. httppost.setEntity(se);
  171. // Execute HttpPost
  172. HttpResponse response = httpClient.execute(httppost);
  173. if(response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() < 600){
  174. return false;
  175. }
  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. public static <T> T downloadFromServer(String address, Class<T> klass){
  184. HttpGet httpget;
  185. try {
  186. HttpClient httpClient = createHttpClient();
  187. httpget = new HttpGet(address);
  188. httpget.addHeader("Accept", "application/json");
  189. HttpResponse response = httpClient.execute(httpget);
  190. Log.i("downloadFromServer", "Status Code: " + response.getStatusLine().getStatusCode());
  191. if(response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() < 600){
  192. return klass.newInstance();
  193. }
  194. return klass.getConstructor(klass).newInstance(readResponseToString(response));
  195. } catch (Exception e) {
  196. e.printStackTrace();
  197. return null;
  198. }
  199. }
  200. public static String readResponseToString(HttpResponse response){
  201. StringBuilder builder = new StringBuilder();
  202. try {
  203. BufferedReader bReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  204. String line;
  205. while ((line = bReader.readLine()) != null) {
  206. builder.append(line);
  207. }
  208. } catch (IOException e) {
  209. e.printStackTrace();
  210. }
  211. return builder.toString();
  212. }
  213. public static SyncData getSyncDataFromTracing(Context context, Synchronizer synchronizer, long fromTime){
  214. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
  215. String serverAddress = pref.getString("pref_upload_server", "https://ssi.cased.de");
  216. HttpPost httppost;
  217. try {
  218. HttpClient httpClient = createHttpClient();
  219. // Create HttpPost
  220. httppost = new HttpPost(serverAddress + "/sync");
  221. SyncInfo info = synchronizer.getSyncInfo();
  222. JSONArray deviceMap = new JSONArray();
  223. for(Map.Entry<String, Long> entry: info.deviceMap.entrySet()){
  224. JSONObject m = new JSONObject();
  225. m.put("sync_id", entry.getValue());
  226. m.put("device", entry.getKey());
  227. deviceMap.put(m);
  228. }
  229. JSONObject condition = new JSONObject();
  230. /**if(fromTime > 0){
  231. Calendar calendar = GregorianCalendar.getInstance();
  232. calendar.setTimeInMillis(fromTime);
  233. condition.put("date", fromCalendar(calendar));
  234. }**/
  235. /**
  236. TODO(alex): UNCOMMENT THIS AGAIN, WHEN WE ARE SURE ABOUT USING LOCATIONS THIS WAY.
  237. =======================================================================
  238. Location location = MyLocationManager.getNewestLocation();
  239. if(location != null){
  240. JSONArray ll = new JSONArray();
  241. ll.put(location.getLongitude());
  242. ll.put(location.getLatitude());
  243. condition.put("location", ll);
  244. condition.put("distance", 500);
  245. } else {
  246. // We could not get the gps coordinates, try to retrieve the country code from the SIM card
  247. TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  248. String countryCodeValue = tm.getNetworkCountryIso();
  249. condition.put("country", countryCodeValue);
  250. }*/
  251. JSONObject req = new JSONObject();
  252. req.put("condition", condition);
  253. req.put("info", deviceMap);
  254. StringEntity se = new StringEntity(req.toString());
  255. httppost.addHeader("content-type", "application/json");
  256. httppost.setEntity(se);
  257. // Execute HttpPost
  258. HttpResponse response = httpClient.execute(httppost);
  259. Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
  260. if(response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() < 600){
  261. return null;
  262. }
  263. String responseBody = readResponseToString(response);
  264. JSONArray syncData;
  265. // ensure, that the received data is an array
  266. try {
  267. syncData = new JSONArray(responseBody);
  268. } catch (JSONException ex){
  269. ex.printStackTrace();
  270. return null;
  271. }
  272. ArrayList<SyncRecord> syncRecords = new ArrayList<SyncRecord>();
  273. Map<String, NetworkRecord> networkRecordMap = new HashMap<String, NetworkRecord>();
  274. SyncData result = new SyncData();
  275. for(int i=0; i<syncData.length(); i++){
  276. try {
  277. JSONObject item = syncData.getJSONObject(i);
  278. JSONObject src = item.getJSONObject("src");
  279. JSONArray src_ll = src.getJSONArray("ll");
  280. JSONObject dst = item.getJSONObject("dst");
  281. JSONArray dst_ll = dst.getJSONArray("ll");
  282. Calendar date = toCalendar(item.getString("date"));
  283. if(!networkRecordMap.containsKey(item.getString("bssid"))){
  284. NetworkRecord networkRecord = new NetworkRecord();
  285. networkRecord.setAccuracy(0);
  286. networkRecord.setBssid(item.getString("bssid"));
  287. networkRecord.setSsid(item.getString("ssid"));
  288. networkRecord.setLatitude(dst_ll.getDouble(1));
  289. networkRecord.setLatitude(dst_ll.getDouble(0));
  290. networkRecord.setTimestampLocation(date.getTimeInMillis());
  291. networkRecordMap.put(item.getString("bssid"), networkRecord);
  292. }
  293. SyncRecord record = new SyncRecord();
  294. record.setBssid(item.getString("bssid"));
  295. record.setAttack_id(i);
  296. record.setDevice(item.getString("device"));
  297. record.setSync_id(item.getLong("sync_id"));
  298. record.setProtocol(getProtocolFromInt(item.getInt("type")));
  299. record.setLocalIP(dst.getString("ip"));
  300. record.setLocalPort(dst.getInt("port"));
  301. record.setRemoteIP(src.getString("ip"));
  302. record.setRemotePort(src.getInt("port"));
  303. record.setExternalIP(item.has("external_ip") ? item.getString("external_ip") : "0.0.0.0");
  304. record.setWasInternalAttack(item.has("internal_attack") && item.getBoolean("internal_attack"));
  305. syncRecords.add(record);
  306. } catch(Exception e){
  307. e.printStackTrace();
  308. continue;
  309. }
  310. }
  311. result.networkRecords = new ArrayList<NetworkRecord>(networkRecordMap.values());
  312. result.syncRecords = syncRecords;
  313. return result;
  314. } catch (Exception e) {
  315. e.printStackTrace();
  316. return null;
  317. }
  318. }
  319. public static String urlEncodeUTF8(String s) {
  320. try {
  321. return URLEncoder.encode(s, "UTF-8");
  322. } catch (UnsupportedEncodingException e) {
  323. throw new UnsupportedOperationException(e);
  324. }
  325. }
  326. public static String[] convertMapToStringArray(Map<String, String> map){
  327. String[] array = new String[map.size() * 2];
  328. int i = 0;
  329. for(Map.Entry<String, String> entry: map.entrySet()){
  330. array[i] = entry.getKey();
  331. array[i + 1] = entry.getValue();
  332. i += 2;
  333. }
  334. return array;
  335. }
  336. public static String buildUrlFromBase(String baseUrl, String... query){
  337. StringBuilder sb = new StringBuilder(baseUrl);
  338. if(query.length >= 2){
  339. sb.append("?");
  340. }
  341. for(int i=0; i<query.length - 2; i+=2){
  342. if(i > 0){
  343. sb.append("&");
  344. }
  345. sb.append(String.format("%s=%s",
  346. urlEncodeUTF8(query[i]),
  347. urlEncodeUTF8(query[i + 1])
  348. ));
  349. }
  350. return sb.toString();
  351. }
  352. public static String buildUrlFromBase(String baseUrl, Map<String, String> query){
  353. return buildUrlFromBase(baseUrl, convertMapToStringArray(query));
  354. }
  355. public static String buildUrl(String protocol, String domain, int port, String path, String ... query){
  356. return buildUrlFromBase(
  357. String.format("%s://%s:%d/%s", urlEncodeUTF8(protocol), urlEncodeUTF8(domain), port, path),
  358. query
  359. );
  360. }
  361. public static String buildUrl(String protocol, String domain, int port, String path, Map<String, String> query){
  362. return buildUrl(protocol, domain, port, path, convertMapToStringArray(query));
  363. }
  364. public static List<String[]> getCountriesFromServer(String serverAddress){
  365. List<String[]> ret = new ArrayList<String[]>();
  366. JSONArray array = downloadFromServer(serverAddress + "/get_countries", JSONArray.class);
  367. try {
  368. for (int i = 0; i < array.length(); i++) {
  369. JSONObject ob = array.getJSONObject(i);
  370. ret.add(new String[]{ob.getString("cc"), ob.getString("country")});
  371. }
  372. } catch(Exception e){
  373. e.printStackTrace();
  374. }
  375. return ret;
  376. }
  377. public static String fromCalendar(final Calendar calendar) {
  378. Date date = calendar.getTime();
  379. String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
  380. .format(date);
  381. return formatted.substring(0, 22) + ":" + formatted.substring(22);
  382. }
  383. public static Calendar toCalendar(final String iso8601string)
  384. throws ParseException {
  385. Calendar calendar = GregorianCalendar.getInstance();
  386. String s = iso8601string.replace("Z", "0+0000");
  387. try {
  388. s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
  389. } catch (IndexOutOfBoundsException e) {
  390. throw new ParseException("Invalid length", 0);
  391. }
  392. Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(s);
  393. calendar.setTime(date);
  394. return calendar;
  395. }
  396. public static JSONArray retrieveNewAttacks(Context context, boolean fromPosition){
  397. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
  398. String serverAddress = pref.getString("pref_download_server", "http://ssi.cased.de/api");
  399. long lastDownloadTime = pref.getLong("pref_download_last_time", 0);
  400. Calendar calendar = GregorianCalendar.getInstance();
  401. calendar.setTimeInMillis(lastDownloadTime);
  402. String baseUri = serverAddress + "/get_attacks";
  403. Map<String, String> query = new HashMap<String, String>();
  404. query.put("start", fromCalendar(calendar));
  405. if(fromPosition){
  406. Location location = MyLocationManager.getNewestLocation();
  407. if(location != null) {
  408. query.put("latitude", String.valueOf(location.getLatitude()));
  409. query.put("longitude", String.valueOf(location.getLongitude()));
  410. query.put("distance", "300");
  411. }
  412. }
  413. return downloadFromServer(buildUrlFromBase(baseUri, "start", fromCalendar(calendar)), JSONArray.class);
  414. }
  415. public static HttpClient createHttpClient() {
  416. try {
  417. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  418. trustStore.load(null, null);
  419. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  420. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  421. HttpParams params = new BasicHttpParams();
  422. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  423. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  424. SchemeRegistry registry = new SchemeRegistry();
  425. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  426. registry.register(new Scheme("https", sf, 443));
  427. ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  428. return new DefaultHttpClient(ccm, params);
  429. } catch (Exception e) {
  430. e.printStackTrace();
  431. return new DefaultHttpClient();
  432. }
  433. }
  434. }