SyncUtils.java 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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.os.Bundle;
  7. import android.preference.PreferenceManager;
  8. import android.util.Log;
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.HttpVersion;
  11. import org.apache.http.client.HttpClient;
  12. import org.apache.http.client.methods.HttpGet;
  13. import org.apache.http.client.methods.HttpPost;
  14. import org.apache.http.conn.ClientConnectionManager;
  15. import org.apache.http.conn.scheme.PlainSocketFactory;
  16. import org.apache.http.conn.scheme.Scheme;
  17. import org.apache.http.conn.scheme.SchemeRegistry;
  18. import org.apache.http.conn.ssl.SSLSocketFactory;
  19. import org.apache.http.entity.StringEntity;
  20. import org.apache.http.impl.client.DefaultHttpClient;
  21. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  22. import org.apache.http.params.BasicHttpParams;
  23. import org.apache.http.params.HttpParams;
  24. import org.apache.http.params.HttpProtocolParams;
  25. import org.apache.http.protocol.HTTP;
  26. import org.json.JSONArray;
  27. import org.json.JSONObject;
  28. import java.io.BufferedReader;
  29. import java.io.IOException;
  30. import java.io.InputStreamReader;
  31. import java.io.Writer;
  32. import java.security.KeyStore;
  33. import java.util.ArrayList;
  34. import java.util.HashMap;
  35. import java.util.List;
  36. import java.util.Map;
  37. import de.tudarmstadt.informatik.hostage.logging.Record;
  38. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  39. /**
  40. * Created by abrakowski
  41. */
  42. public class SyncUtils {
  43. private static final long SYNC_FREQUENCY = 60 * 60; // 1 hour (in seconds)
  44. public static final String CONTENT_AUTHORITY = "de.tudarmstadt.informatik.hostage.androidsync";
  45. private static final String PREF_SETUP_COMPLETE = "sync_setup_complete";
  46. private static final Map<String, Integer> protocolsTypeMap;
  47. static {
  48. protocolsTypeMap = new HashMap<String, Integer>();
  49. protocolsTypeMap.put("ECHO", 10);
  50. protocolsTypeMap.put("FTP", 0);
  51. protocolsTypeMap.put("GHOST", 0);
  52. protocolsTypeMap.put("HTTP", 0);
  53. protocolsTypeMap.put("HTTPS", 0);
  54. protocolsTypeMap.put("MySQL", 31);
  55. protocolsTypeMap.put("SIP", 50);
  56. protocolsTypeMap.put("SMB", 40);
  57. protocolsTypeMap.put("TELNET", 0);
  58. }
  59. /**
  60. * Create an entry for this application in the system account list, if it isn't already there.
  61. *
  62. * @param context Context
  63. */
  64. public static void CreateSyncAccount(Context context) {
  65. boolean newAccount = false;
  66. boolean setupComplete = PreferenceManager
  67. .getDefaultSharedPreferences(context).getBoolean(PREF_SETUP_COMPLETE, false);
  68. // Create account, if it's missing. (Either first run, or user has deleted account.)
  69. Account account = HostageAccountService.GetAccount();
  70. AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
  71. if (accountManager.addAccountExplicitly(account, null, null)) {
  72. // Inform the system that this account supports sync
  73. ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
  74. // Inform the system that this account is eligible for auto sync when the network is up
  75. ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
  76. // Recommend a schedule for automatic synchronization. The system may modify this based
  77. // on other scheduled syncs and network utilization.
  78. ContentResolver.addPeriodicSync(
  79. account, CONTENT_AUTHORITY, new Bundle(),SYNC_FREQUENCY);
  80. newAccount = true;
  81. }
  82. // Schedule an initial sync if we detect problems with either our account or our local
  83. // data has been deleted. (Note that it's possible to clear app data WITHOUT affecting
  84. // the account list, so wee need to check both.)
  85. if (newAccount || !setupComplete) {
  86. TriggerRefresh();
  87. PreferenceManager.getDefaultSharedPreferences(context).edit()
  88. .putBoolean(PREF_SETUP_COMPLETE, true).commit();
  89. }
  90. }
  91. public static void TriggerRefresh() {
  92. Bundle b = new Bundle();
  93. // Disable sync backoff and ignore sync preferences. In other words...perform sync NOW!
  94. b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  95. b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  96. ContentResolver.requestSync(
  97. HostageAccountService.GetAccount(), // Sync account
  98. CONTENT_AUTHORITY, // Content authority
  99. b); // Extras
  100. }
  101. public static void appendRecordToStringWriter(Record record, Writer stream){
  102. try {
  103. stream.append(
  104. "{" +
  105. "\"sensor\":{" +
  106. "\"name\":\"HosTaGe\"," +
  107. "\"type\":\"Honeypot\"" +
  108. "}," +
  109. "\"src\":{" +
  110. "\"ip\":\"" + record.getRemoteIP() + "\"," +
  111. "\"port\":" + record.getRemotePort() +
  112. "}," +
  113. "\"dst\":{" +
  114. "\"ip\":\"" + record.getExternalIP() /*record.getLocalIP()*/ + "\"," +
  115. "\"port\":" + record.getLocalPort() +
  116. "}," +
  117. "\"type\":" + (protocolsTypeMap.containsKey(record.getProtocol()) ? protocolsTypeMap.get(record.getProtocol()) : 0) + "," +
  118. "\"log\":\"" + record.getProtocol() + "\"," +
  119. "\"md5sum\":\"\"," +
  120. "\"date\":" + (int)(record.getTimestamp() / 1000) +
  121. "}\n"
  122. );
  123. } catch (IOException e) {
  124. e.printStackTrace();
  125. }
  126. }
  127. public static boolean uploadRecordsToServer(String entity, String serverAddress){
  128. HttpPost httppost;
  129. try {
  130. HttpClient httpClient = createHttpClient();
  131. // Create HttpPost
  132. httppost = new HttpPost(serverAddress);
  133. StringEntity se = new StringEntity(entity);
  134. httppost.addHeader("content-type", "application/json+newline");
  135. httppost.setEntity(se);
  136. // Execute HttpPost
  137. HttpResponse response = httpClient.execute(httppost);
  138. if(response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() < 600){
  139. return false;
  140. }
  141. Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
  142. } catch (Exception e) {
  143. e.printStackTrace();
  144. return false;
  145. }
  146. return true;
  147. }
  148. public static List<String[]> getCountriesFromServer(String serverAddress){
  149. HttpGet httpget;
  150. List<String[]> ret = new ArrayList<String[]>();
  151. try {
  152. HttpClient httpClient = createHttpClient();
  153. // Create HttpPost
  154. httpget = new HttpGet(serverAddress + "/get_countries");
  155. httpget.addHeader("content-type", "application/json+newline");
  156. // Execute HttpPost
  157. HttpResponse response = httpClient.execute(httpget);
  158. if(response.getStatusLine().getStatusCode() >= 400 && response.getStatusLine().getStatusCode() < 600){
  159. return null;
  160. }
  161. BufferedReader bReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  162. String line;
  163. StringBuilder builder = new StringBuilder();
  164. while ((line = bReader.readLine()) != null) {
  165. builder.append(line);
  166. }
  167. JSONArray array = new JSONArray(builder.toString());
  168. for(int i = 0; i < array.length(); i++){
  169. JSONObject ob = array.getJSONObject(i);
  170. ret.add(new String[]{ob.getString("cc"), ob.getString("country")});
  171. }
  172. Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
  173. return ret;
  174. } catch (Exception e) {
  175. e.printStackTrace();
  176. return null;
  177. }
  178. }
  179. public static HttpClient createHttpClient() {
  180. try {
  181. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  182. trustStore.load(null, null);
  183. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  184. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  185. HttpParams params = new BasicHttpParams();
  186. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  187. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  188. SchemeRegistry registry = new SchemeRegistry();
  189. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  190. registry.register(new Scheme("https", sf, 443));
  191. ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
  192. return new DefaultHttpClient(ccm, params);
  193. } catch (Exception e) {
  194. e.printStackTrace();
  195. return new DefaultHttpClient();
  196. }
  197. }
  198. }