SyncUtils.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.NetworkRecord;
  49. import de.tudarmstadt.informatik.hostage.logging.Record;
  50. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  51. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  52. /**
  53. * Created by abrakowski
  54. */
  55. public class SyncUtils {
  56. private static final long SYNC_FREQUENCY = 60 * 60; // 1 hour (in seconds)
  57. public static final String CONTENT_AUTHORITY = "de.tudarmstadt.informatik.hostage.androidsync";
  58. private static final String PREF_SETUP_COMPLETE = "sync_setup_complete";
  59. private static final Map<String, Integer> protocolsTypeMap;
  60. static {
  61. protocolsTypeMap = new HashMap<String, Integer>();
  62. protocolsTypeMap.put("ECHO", 10);
  63. protocolsTypeMap.put("FTP", 0);
  64. protocolsTypeMap.put("GHOST", 0);
  65. protocolsTypeMap.put("HTTP", 0);
  66. protocolsTypeMap.put("HTTPS", 0);
  67. protocolsTypeMap.put("MySQL", 31);
  68. protocolsTypeMap.put("SIP", 50);
  69. protocolsTypeMap.put("SMB", 40);
  70. protocolsTypeMap.put("TELNET", 0);
  71. }
  72. /**
  73. * Create an entry for this application in the system account list, if it isn't already there.
  74. *
  75. * @param context Context
  76. */
  77. public static void CreateSyncAccount(Context context) {
  78. boolean newAccount = false;
  79. boolean setupComplete = PreferenceManager
  80. .getDefaultSharedPreferences(context).getBoolean(PREF_SETUP_COMPLETE, false);
  81. // Create account, if it's missing. (Either first run, or user has deleted account.)
  82. Account account = HostageAccountService.GetAccount();
  83. AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
  84. if (accountManager.addAccountExplicitly(account, null, null)) {
  85. // Inform the system that this account supports sync
  86. ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
  87. // Inform the system that this account is eligible for auto sync when the network is up
  88. ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
  89. // Recommend a schedule for automatic synchronization. The system may modify this based
  90. // on other scheduled syncs and network utilization.
  91. ContentResolver.addPeriodicSync(
  92. account, CONTENT_AUTHORITY, new Bundle(),SYNC_FREQUENCY);
  93. newAccount = true;
  94. }
  95. // Schedule an initial sync if we detect problems with either our account or our local
  96. // data has been deleted. (Note that it's possible to clear app data WITHOUT affecting
  97. // the account list, so wee need to check both.)
  98. if (newAccount || !setupComplete) {
  99. TriggerRefresh();
  100. PreferenceManager.getDefaultSharedPreferences(context).edit()
  101. .putBoolean(PREF_SETUP_COMPLETE, true).commit();
  102. }
  103. }
  104. public static void TriggerRefresh() {
  105. Bundle b = new Bundle();
  106. // Disable sync backoff and ignore sync preferences. In other words...perform sync NOW!
  107. b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  108. b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  109. ContentResolver.requestSync(
  110. HostageAccountService.GetAccount(), // Sync account
  111. CONTENT_AUTHORITY, // Content authority
  112. b); // Extras
  113. }
  114. public static void appendRecordToStringWriter(Record record, Writer stream){
  115. try {
  116. stream.append(
  117. "{" +
  118. "\"sensor\":{" +
  119. "\"name\":\"HosTaGe\"," +
  120. "\"type\":\"Honeypot\"" +
  121. "}," +
  122. "\"src\":{" +
  123. "\"ip\":\"" + record.getRemoteIP() + "\"," +
  124. "\"port\":" + record.getRemotePort() +
  125. "}," +
  126. "\"dst\":{" +
  127. "\"ip\":\"" + record.getExternalIP() /*record.getLocalIP()*/ + "\"," +
  128. "\"port\":" + record.getLocalPort() +
  129. "}," +
  130. "\"type\":" + (protocolsTypeMap.containsKey(record.getProtocol()) ? protocolsTypeMap.get(record.getProtocol()) : 0) + "," +
  131. "\"log\":\"" + record.getProtocol() + "\"," +
  132. "\"md5sum\":\"\"," +
  133. "\"date\":" + (int)(record.getTimestamp() / 1000) +
  134. "}\n"
  135. );
  136. } catch (IOException e) {
  137. e.printStackTrace();
  138. }
  139. }
  140. public static boolean uploadRecordsToServer(String entity, String serverAddress){
  141. HttpPost httppost;
  142. try {
  143. HttpClient httpClient = createHttpClient();
  144. // Create HttpPost
  145. httppost = new HttpPost(serverAddress);
  146. StringEntity se = new StringEntity(entity);
  147. httppost.addHeader("content-type", "application/json+newline");
  148. httppost.setEntity(se);
  149. // Execute HttpPost
  150. HttpResponse response = httpClient.execute(httppost);
  151. if(response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() < 600){
  152. return false;
  153. }
  154. Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
  155. } catch (Exception e) {
  156. e.printStackTrace();
  157. return false;
  158. }
  159. return true;
  160. }
  161. public static <T> T downloadFromServer(String address, Class<T> klass){
  162. HttpGet httpget;
  163. try {
  164. HttpClient httpClient = createHttpClient();
  165. httpget = new HttpGet(address);
  166. httpget.addHeader("Accept", "application/json");
  167. HttpResponse response = httpClient.execute(httpget);
  168. Log.i("downloadFromServer", "Status Code: " + response.getStatusLine().getStatusCode());
  169. if(response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() < 600){
  170. return klass.newInstance();
  171. }
  172. BufferedReader bReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  173. String line;
  174. StringBuilder builder = new StringBuilder();
  175. while ((line = bReader.readLine()) != null) {
  176. builder.append(line);
  177. }
  178. return klass.getConstructor(klass).newInstance(builder.toString());
  179. } catch (Exception e) {
  180. e.printStackTrace();
  181. return null;
  182. }
  183. }
  184. public static String urlEncodeUTF8(String s) {
  185. try {
  186. return URLEncoder.encode(s, "UTF-8");
  187. } catch (UnsupportedEncodingException e) {
  188. throw new UnsupportedOperationException(e);
  189. }
  190. }
  191. public static String[] convertMapToStringArray(Map<String, String> map){
  192. String[] array = new String[map.size() * 2];
  193. int i = 0;
  194. for(Map.Entry<String, String> entry: map.entrySet()){
  195. array[i] = entry.getKey();
  196. array[i + 1] = entry.getValue();
  197. i += 2;
  198. }
  199. return array;
  200. }
  201. public static String buildUrlFromBase(String baseUrl, String... query){
  202. StringBuilder sb = new StringBuilder(baseUrl);
  203. if(query.length >= 2){
  204. sb.append("?");
  205. }
  206. for(int i=0; i<query.length - 2; i+=2){
  207. if(i > 0){
  208. sb.append("&");
  209. }
  210. sb.append(String.format("%s=%s",
  211. urlEncodeUTF8(query[i]),
  212. urlEncodeUTF8(query[i + 1])
  213. ));
  214. }
  215. return sb.toString();
  216. }
  217. public static String buildUrlFromBase(String baseUrl, Map<String, String> query){
  218. return buildUrlFromBase(baseUrl, convertMapToStringArray(query));
  219. }
  220. public static String buildUrl(String protocol, String domain, int port, String path, String ... query){
  221. return buildUrlFromBase(
  222. String.format("%s://%s:%d/%s", urlEncodeUTF8(protocol), urlEncodeUTF8(domain), port, path),
  223. query
  224. );
  225. }
  226. public static String buildUrl(String protocol, String domain, int port, String path, Map<String, String> query){
  227. return buildUrl(protocol, domain, port, path, convertMapToStringArray(query));
  228. }
  229. public static List<String[]> getCountriesFromServer(String serverAddress){
  230. List<String[]> ret = new ArrayList<String[]>();
  231. JSONArray array = downloadFromServer(serverAddress + "/get_countries", JSONArray.class);
  232. try {
  233. for (int i = 0; i < array.length(); i++) {
  234. JSONObject ob = array.getJSONObject(i);
  235. ret.add(new String[]{ob.getString("cc"), ob.getString("country")});
  236. }
  237. } catch(Exception e){
  238. e.printStackTrace();
  239. }
  240. return ret;
  241. }
  242. public static String fromCalendar(final Calendar calendar) {
  243. Date date = calendar.getTime();
  244. String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
  245. .format(date);
  246. return formatted.substring(0, 22) + ":" + formatted.substring(22);
  247. }
  248. public static Calendar toCalendar(final String iso8601string)
  249. throws ParseException {
  250. Calendar calendar = GregorianCalendar.getInstance();
  251. String s = iso8601string.replace("Z", "+00:00");
  252. try {
  253. s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
  254. } catch (IndexOutOfBoundsException e) {
  255. throw new ParseException("Invalid length", 0);
  256. }
  257. Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
  258. calendar.setTime(date);
  259. return calendar;
  260. }
  261. public static JSONArray retrieveNewAttacks(Context context, boolean fromPosition){
  262. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
  263. String serverAddress = pref.getString("pref_download_server", "http://ssi.cased.de/api");
  264. long lastDownloadTime = pref.getLong("pref_download_last_time", 0);
  265. Calendar calendar = GregorianCalendar.getInstance();
  266. calendar.setTimeInMillis(lastDownloadTime);
  267. String baseUri = serverAddress + "/get_attacks";
  268. Map<String, String> query = new HashMap<String, String>();
  269. query.put("start", fromCalendar(calendar));
  270. if(fromPosition){
  271. Location location = MyLocationManager.getNewestLocation();
  272. if(location != null) {
  273. query.put("latitude", String.valueOf(location.getLatitude()));
  274. query.put("longitude", String.valueOf(location.getLongitude()));
  275. query.put("distance", "300");
  276. }
  277. }
  278. return downloadFromServer(buildUrlFromBase(baseUri, "start", fromCalendar(calendar)), JSONArray.class);
  279. }
  280. public static void logNewAttacks(Context context, JSONArray attacks){
  281. Map<String, NetworkRecord> networks = new HashMap<String, NetworkRecord>();
  282. for(int i=0; i<attacks.length(); i++){
  283. try {
  284. JSONObject obj = attacks.getJSONObject(i);
  285. } catch (JSONException e) {
  286. e.printStackTrace();
  287. }
  288. }
  289. }
  290. public static HttpClient createHttpClient() {
  291. try {
  292. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  293. trustStore.load(null, null);
  294. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  295. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  296. HttpParams params = new BasicHttpParams();
  297. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  298. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  299. SchemeRegistry registry = new SchemeRegistry();
  300. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  301. registry.register(new Scheme("https", sf, 443));
  302. ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  303. return new DefaultHttpClient(ccm, params);
  304. } catch (Exception e) {
  305. e.printStackTrace();
  306. return new DefaultHttpClient();
  307. }
  308. }
  309. }