SyncUtils.java 19 KB

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