SyncUtils.java 20 KB

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