SyncUtils.java 22 KB

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