SyncUtils.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. Location location = null;
  236. /**
  237. TODO(alex): UNCOMMENT THIS AGAIN, WHEN WE ARE SURE ABOUT USING LOCATIONS THIS WAY.
  238. =======================================================================
  239. location = MyLocationManager.getNewestLocation();
  240. */
  241. if(location != null){
  242. JSONArray ll = new JSONArray();
  243. ll.put(location.getLongitude());
  244. ll.put(location.getLatitude());
  245. condition.put("location", ll);
  246. condition.put("distance", 500);
  247. } else {
  248. // We could not get the gps coordinates, try to retrieve the country code from the SIM card
  249. TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  250. String countryCodeValue = tm.getNetworkCountryIso();
  251. /**
  252. TODO(julien): COMMENT THIS OUT, TO GET ALL SYNC DATA FROM TRACING.
  253. */
  254. condition.put("country", countryCodeValue);
  255. }
  256. JSONObject req = new JSONObject();
  257. req.put("condition", condition);
  258. req.put("info", deviceMap);
  259. StringEntity se = new StringEntity(req.toString());
  260. httppost.addHeader("content-type", "application/json");
  261. httppost.setEntity(se);
  262. // Execute HttpPost
  263. HttpResponse response = httpClient.execute(httppost);
  264. Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
  265. if(response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() < 600){
  266. return null;
  267. }
  268. String responseBody = readResponseToString(response);
  269. JSONArray syncData;
  270. // ensure, that the received data is an array
  271. try {
  272. syncData = new JSONArray(responseBody);
  273. } catch (JSONException ex){
  274. ex.printStackTrace();
  275. return null;
  276. }
  277. ArrayList<SyncRecord> syncRecords = new ArrayList<SyncRecord>();
  278. Map<String, NetworkRecord> networkRecordMap = new HashMap<String, NetworkRecord>();
  279. SyncData result = new SyncData();
  280. for(int i=0; i<syncData.length(); i++){
  281. try {
  282. JSONObject item = syncData.getJSONObject(i);
  283. JSONObject src = item.getJSONObject("src");
  284. JSONArray src_ll = src.getJSONArray("ll");
  285. JSONObject dst = item.getJSONObject("dst");
  286. JSONArray dst_ll = dst.getJSONArray("ll");
  287. Calendar date = toCalendar(item.getString("date"));
  288. if(!networkRecordMap.containsKey(item.getString("bssid"))){
  289. NetworkRecord networkRecord = new NetworkRecord();
  290. networkRecord.setAccuracy(0);
  291. networkRecord.setBssid(item.getString("bssid"));
  292. networkRecord.setSsid(item.getString("ssid"));
  293. networkRecord.setLatitude(dst_ll.getDouble(1));
  294. networkRecord.setLatitude(dst_ll.getDouble(0));
  295. networkRecord.setTimestampLocation(date.getTimeInMillis());
  296. networkRecordMap.put(item.getString("bssid"), networkRecord);
  297. }
  298. SyncRecord record = new SyncRecord();
  299. record.setBssid(item.getString("bssid"));
  300. record.setAttack_id(i);
  301. record.setDevice(item.getString("device"));
  302. record.setSync_id(item.getLong("sync_id"));
  303. record.setProtocol(getProtocolFromInt(item.getInt("type")));
  304. record.setLocalIP(dst.getString("ip"));
  305. record.setLocalPort(dst.getInt("port"));
  306. record.setRemoteIP(src.getString("ip"));
  307. record.setRemotePort(src.getInt("port"));
  308. record.setExternalIP(item.has("external_ip") ? item.getString("external_ip") : "0.0.0.0");
  309. record.setWasInternalAttack(item.has("internal_attack") && item.getBoolean("internal_attack"));
  310. syncRecords.add(record);
  311. } catch(Exception e){
  312. e.printStackTrace();
  313. continue;
  314. }
  315. }
  316. result.networkRecords = new ArrayList<NetworkRecord>(networkRecordMap.values());
  317. result.syncRecords = syncRecords;
  318. return result;
  319. } catch (Exception e) {
  320. e.printStackTrace();
  321. return null;
  322. }
  323. }
  324. public static String urlEncodeUTF8(String s) {
  325. try {
  326. return URLEncoder.encode(s, "UTF-8");
  327. } catch (UnsupportedEncodingException e) {
  328. throw new UnsupportedOperationException(e);
  329. }
  330. }
  331. public static String[] convertMapToStringArray(Map<String, String> map){
  332. String[] array = new String[map.size() * 2];
  333. int i = 0;
  334. for(Map.Entry<String, String> entry: map.entrySet()){
  335. array[i] = entry.getKey();
  336. array[i + 1] = entry.getValue();
  337. i += 2;
  338. }
  339. return array;
  340. }
  341. public static String buildUrlFromBase(String baseUrl, String... query){
  342. StringBuilder sb = new StringBuilder(baseUrl);
  343. if(query.length >= 2){
  344. sb.append("?");
  345. }
  346. for(int i=0; i<query.length - 2; i+=2){
  347. if(i > 0){
  348. sb.append("&");
  349. }
  350. sb.append(String.format("%s=%s",
  351. urlEncodeUTF8(query[i]),
  352. urlEncodeUTF8(query[i + 1])
  353. ));
  354. }
  355. return sb.toString();
  356. }
  357. public static String buildUrlFromBase(String baseUrl, Map<String, String> query){
  358. return buildUrlFromBase(baseUrl, convertMapToStringArray(query));
  359. }
  360. public static String buildUrl(String protocol, String domain, int port, String path, String ... query){
  361. return buildUrlFromBase(
  362. String.format("%s://%s:%d/%s", urlEncodeUTF8(protocol), urlEncodeUTF8(domain), port, path),
  363. query
  364. );
  365. }
  366. public static String buildUrl(String protocol, String domain, int port, String path, Map<String, String> query){
  367. return buildUrl(protocol, domain, port, path, convertMapToStringArray(query));
  368. }
  369. public static List<String[]> getCountriesFromServer(String serverAddress){
  370. List<String[]> ret = new ArrayList<String[]>();
  371. JSONArray array = downloadFromServer(serverAddress + "/get_countries", JSONArray.class);
  372. try {
  373. for (int i = 0; i < array.length(); i++) {
  374. JSONObject ob = array.getJSONObject(i);
  375. ret.add(new String[]{ob.getString("cc"), ob.getString("country")});
  376. }
  377. } catch(Exception e){
  378. e.printStackTrace();
  379. }
  380. return ret;
  381. }
  382. public static String fromCalendar(final Calendar calendar) {
  383. Date date = calendar.getTime();
  384. String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
  385. .format(date);
  386. return formatted.substring(0, 22) + ":" + formatted.substring(22);
  387. }
  388. public static Calendar toCalendar(final String iso8601string)
  389. throws ParseException {
  390. Calendar calendar = GregorianCalendar.getInstance();
  391. String s = iso8601string.replace("Z", "0+0000");
  392. try {
  393. s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
  394. } catch (IndexOutOfBoundsException e) {
  395. throw new ParseException("Invalid length", 0);
  396. }
  397. Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(s);
  398. calendar.setTime(date);
  399. return calendar;
  400. }
  401. public static JSONArray retrieveNewAttacks(Context context, boolean fromPosition){
  402. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
  403. String serverAddress = pref.getString("pref_download_server", "http://ssi.cased.de/api");
  404. long lastDownloadTime = pref.getLong("pref_download_last_time", 0);
  405. Calendar calendar = GregorianCalendar.getInstance();
  406. calendar.setTimeInMillis(lastDownloadTime);
  407. String baseUri = serverAddress + "/get_attacks";
  408. Map<String, String> query = new HashMap<String, String>();
  409. query.put("start", fromCalendar(calendar));
  410. if(fromPosition){
  411. Location location = MyLocationManager.getNewestLocation();
  412. if(location != null) {
  413. query.put("latitude", String.valueOf(location.getLatitude()));
  414. query.put("longitude", String.valueOf(location.getLongitude()));
  415. query.put("distance", "300");
  416. }
  417. }
  418. return downloadFromServer(buildUrlFromBase(baseUri, "start", fromCalendar(calendar)), JSONArray.class);
  419. }
  420. public static HttpClient createHttpClient() {
  421. try {
  422. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  423. trustStore.load(null, null);
  424. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  425. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  426. HttpParams params = new BasicHttpParams();
  427. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  428. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  429. SchemeRegistry registry = new SchemeRegistry();
  430. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  431. registry.register(new Scheme("https", sf, 443));
  432. ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  433. return new DefaultHttpClient(ccm, params);
  434. } catch (Exception e) {
  435. e.printStackTrace();
  436. return new DefaultHttpClient();
  437. }
  438. }
  439. }