SyncUtils.java 22 KB

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