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