SyncUtils.java 21 KB

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