SyncUtils.java 20 KB

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