HoneyService.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package de.tudarmstadt.informatik.hostage;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.net.Socket;
  5. import java.security.SecureRandom;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import android.app.NotificationManager;
  9. import android.app.PendingIntent;
  10. import android.app.Service;
  11. import android.content.BroadcastReceiver;
  12. import android.content.Context;
  13. import android.content.Intent;
  14. import android.content.IntentFilter;
  15. import android.content.SharedPreferences;
  16. import android.content.SharedPreferences.Editor;
  17. import android.net.ConnectivityManager;
  18. import android.net.Uri;
  19. import android.os.AsyncTask;
  20. import android.os.Binder;
  21. import android.os.IBinder;
  22. import android.preference.PreferenceManager;
  23. import android.support.v4.app.NotificationCompat;
  24. import android.support.v4.app.TaskStackBuilder;
  25. import android.support.v4.content.LocalBroadcastManager;
  26. import android.util.Log;
  27. import android.widget.Toast;
  28. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  29. import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
  30. import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
  31. import de.tudarmstadt.informatik.hostage.protocol.HTTP;
  32. import de.tudarmstadt.informatik.hostage.protocol.Protocol;
  33. import de.tudarmstadt.informatik.hostage.ui.MainActivity;
  34. /**
  35. * Background service running as long as at least one protocol is active.
  36. * Service controls start and stop of protocol listener. Notifies GUI about
  37. * events happening in the background. Creates Notifications to inform the user
  38. * what it happening.
  39. *
  40. * @author Mihai Plasoianu
  41. * @author Lars Pandikow
  42. * @author Wulf Pfeiffer
  43. */
  44. public class HoneyService extends Service {
  45. private static Context context;
  46. /**
  47. * Returns the application context.
  48. *
  49. * @return context.
  50. */
  51. public static Context getContext() {
  52. return HoneyService.context;
  53. }
  54. private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
  55. private NotificationCompat.Builder builder;
  56. private SharedPreferences sessionPref;
  57. private Editor editor;
  58. public List<HoneyListener> getListeners() {
  59. return listeners;
  60. }
  61. private final IBinder mBinder = new LocalBinder();
  62. public class LocalBinder extends Binder {
  63. public HoneyService getService() {
  64. return HoneyService.this;
  65. }
  66. }
  67. @Override
  68. public IBinder onBind(Intent intent) {
  69. return mBinder;
  70. }
  71. @Override
  72. public void onCreate() {
  73. super.onCreate();
  74. HoneyService.context = getApplicationContext();
  75. sessionPref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
  76. editor = sessionPref.edit();
  77. deleteSessionData();
  78. createNotification();
  79. for (Protocol protocol : getProtocolArray()) {
  80. listeners.add(new HoneyListener(this, protocol));
  81. }
  82. registerNetReceiver();
  83. getLocationData();
  84. if(getSharedPreferences("de.tudarmstadt.informatik.hostage.http", MODE_PRIVATE).getBoolean("useQotd", true) == true) {
  85. new QotdTask().execute(new String[] {});
  86. }
  87. }
  88. @Override
  89. public int onStartCommand(Intent intent, int flags, int startId) {
  90. // We want this service to continue running until it is explicitly
  91. // stopped, so return sticky.
  92. return START_STICKY;
  93. }
  94. @Override
  95. public void onDestroy() {
  96. cancelNotification();
  97. unregisterNetReceiver();
  98. deleteSessionData();
  99. super.onDestroy();
  100. }
  101. /**
  102. * Starts an Instance of MyLocationManager to set the location within this
  103. * class.
  104. */
  105. private void getLocationData() {
  106. // TODO Put time and attempts in settings
  107. MyLocationManager locationManager = new MyLocationManager(this);
  108. locationManager.getUpdates(60 * 1000, 3);
  109. }
  110. /**
  111. * Deletes all session related data.
  112. */
  113. private void deleteSessionData() {
  114. editor.clear();
  115. editor.commit();
  116. }
  117. /**
  118. * Register broadcast receiver for connectivity changes
  119. */
  120. private void registerNetReceiver() {
  121. // register BroadcastReceiver on network state changes
  122. IntentFilter intent = new IntentFilter();
  123. intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
  124. registerReceiver(netReceiver, intent);
  125. }
  126. /**
  127. * Unregister broadcast receiver for connectivity changes
  128. */
  129. private void unregisterNetReceiver() {
  130. unregisterReceiver(netReceiver);
  131. }
  132. /**
  133. * Receiver for connectivity change broadcast.
  134. *
  135. * @see MainActivity#BROADCAST
  136. */
  137. private BroadcastReceiver netReceiver = new BroadcastReceiver() {
  138. @Override
  139. public void onReceive(Context context, Intent intent) {
  140. String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
  141. String bssid_new = HelperUtils.getBSSID(context);
  142. if (bssid_new == null || !bssid_new.equals(bssid_old)) {
  143. getLocationData();
  144. notifyUI("SERVICE", "CONNECTIVITY_CHANGE");
  145. }
  146. }
  147. };
  148. /**
  149. * Creates a Notification in the notification bar.
  150. */
  151. private void createNotification() {
  152. UglyDbHelper dbh = new UglyDbHelper(this);
  153. boolean activeHandlers = false;
  154. boolean bssidSeen = false;
  155. for (String protocol : getResources().getStringArray(R.array.protocols)) {
  156. int handlerCount = sessionPref.getInt(protocol
  157. + MainActivity.HANDLER_COUNT, 0);
  158. if (handlerCount > 0) {
  159. activeHandlers = true;
  160. }
  161. if (dbh.bssidSeen(protocol,
  162. HelperUtils.getBSSID(getApplicationContext()))) {
  163. bssidSeen = true;
  164. }
  165. }
  166. builder = new NotificationCompat.Builder(this).setContentTitle(
  167. getString(R.string.app_name)).setWhen(
  168. System.currentTimeMillis());
  169. if (activeHandlers) {
  170. builder.setSmallIcon(R.drawable.ic_service_red);
  171. builder.setContentText("Network is infected!");
  172. } else if (bssidSeen) {
  173. builder.setSmallIcon(R.drawable.ic_service_yellow);
  174. builder.setContentText("Network has been infected in previous session!");
  175. } else {
  176. builder.setSmallIcon(R.drawable.ic_service_green);
  177. builder.setContentText("Everything looks fine!");
  178. }
  179. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  180. stackBuilder.addParentStack(MainActivity.class);
  181. stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
  182. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
  183. PendingIntent.FLAG_UPDATE_CURRENT);
  184. builder.setContentIntent(resultPendingIntent);
  185. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  186. mNotificationManager.notify(1, builder.build());
  187. }
  188. /**
  189. * Updates the notification when a attack is registered.
  190. */
  191. private void updateNotification() {
  192. SharedPreferences defaultPref = PreferenceManager
  193. .getDefaultSharedPreferences(this);
  194. String strRingtonePreference = defaultPref.getString(
  195. "pref_notification_sound",
  196. "content://settings/system/notification_sound");
  197. builder = new NotificationCompat.Builder(this)
  198. .setContentTitle(getString(R.string.app_name))
  199. .setTicker("Honeypot under attack!")
  200. .setContentText("Network is infected!")
  201. .setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true)
  202. .setWhen(System.currentTimeMillis())
  203. .setSound(Uri.parse(strRingtonePreference));
  204. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  205. stackBuilder.addParentStack(MainActivity.class);
  206. stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
  207. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
  208. PendingIntent.FLAG_UPDATE_CURRENT);
  209. builder.setContentIntent(resultPendingIntent);
  210. if (defaultPref.getBoolean("pref_vibration", false)) {
  211. builder.setVibrate(new long[] { 100, 200, 100, 200 });
  212. }
  213. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  214. mNotificationManager.notify(1, builder.build());
  215. }
  216. /**
  217. * Cancels the Notification
  218. */
  219. private void cancelNotification() {
  220. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  221. mNotificationManager.cancel(1);
  222. }
  223. /**
  224. * Creates a instance of each protocol defined in /res/values/protocols.xml
  225. * and puts it in a List
  226. *
  227. * @return ArrayList of
  228. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  229. * Protocol}
  230. */
  231. private ArrayList<Protocol> getProtocolArray() {
  232. String[] protocols = getResources().getStringArray(R.array.protocols);
  233. String packageName = Protocol.class.getPackage().getName();
  234. ArrayList<Protocol> protocolArray = new ArrayList<Protocol>();
  235. for (String protocol : protocols) {
  236. try {
  237. protocolArray.add((Protocol) Class.forName(
  238. String.format("%s.%s", packageName, protocol))
  239. .newInstance());
  240. } catch (Exception e) {
  241. e.printStackTrace();
  242. }
  243. }
  244. return protocolArray;
  245. }
  246. /**
  247. * Determines if there are running listeners.
  248. *
  249. * @return True if there is a running listener, else false.
  250. */
  251. public boolean hasRunningListeners() {
  252. for (HoneyListener listener : listeners) {
  253. if (listener.isRunning())
  254. return true;
  255. }
  256. return false;
  257. }
  258. /**
  259. * Notifies the GUI about a event.
  260. *
  261. * @param protocol
  262. * The protocol where the event happened.
  263. * @param key
  264. * The key for the event.
  265. */
  266. public void notifyUI(String sender, String key) {
  267. // Send Notification
  268. if (key.equals(MainActivity.HANDLER_COUNT)) {
  269. updateNotification();
  270. }
  271. Log.i("HoneyService", sender + key);
  272. // Inform UI of Preference Change
  273. Intent intent = new Intent(MainActivity.BROADCAST);
  274. intent.putExtra("SENDER", sender);
  275. intent.putExtra("KEY", key);
  276. LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
  277. }
  278. /**
  279. * Starts all listeners which are not already running
  280. */
  281. public void startListeners() {
  282. for (HoneyListener listener : listeners) {
  283. if (!listener.isRunning()) {
  284. listener.start();
  285. }
  286. }
  287. Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
  288. Toast.LENGTH_SHORT).show();
  289. }
  290. /**
  291. * Stops all running listeners.
  292. */
  293. public void stopListeners() {
  294. for (HoneyListener listener : listeners) {
  295. if (listener.isRunning()) {
  296. listener.stop();
  297. }
  298. }
  299. Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
  300. Toast.LENGTH_SHORT).show();
  301. }
  302. /**
  303. * Starts the listener for the specified protocol.
  304. *
  305. * @param protocolName
  306. * Name of the protocol that should be started.
  307. */
  308. public void startListener(String protocolName) {
  309. for (HoneyListener listener : listeners) {
  310. if (listener.getProtocolName().equals(protocolName)) {
  311. if (!listener.isRunning()) {
  312. listener.start();
  313. }
  314. }
  315. }
  316. Toast.makeText(getApplicationContext(),
  317. protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  318. }
  319. /**
  320. * Stops the listener for the specified protocol.
  321. *
  322. * @param protocolName
  323. * Name of the protocol that should be stopped.
  324. */
  325. public void stopListener(String protocolName) {
  326. for (HoneyListener listener : listeners) {
  327. if (listener.getProtocolName().equals(protocolName)) {
  328. if (listener.isRunning()) {
  329. listener.stop();
  330. }
  331. }
  332. }
  333. Toast.makeText(getApplicationContext(),
  334. protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
  335. }
  336. /**
  337. * Toggles a listener for specified protocol.
  338. *
  339. * @param protocolName
  340. * Name of the protocol that should be toggled.
  341. */
  342. public void toggleListener(String protocolName) {
  343. for (HoneyListener listener : listeners) {
  344. if (listener.getProtocolName().equals(protocolName)) {
  345. if (listener.isRunning()) {
  346. stopListener(protocolName);
  347. } else {
  348. startListener(protocolName);
  349. }
  350. }
  351. }
  352. }
  353. /**
  354. * Task for accuiring a qotd from one of four possible servers.
  355. *
  356. * @author Wulf Pfeiffer
  357. */
  358. private class QotdTask extends AsyncTask<String, Void, String> {
  359. @Override
  360. protected String doInBackground(String... unused) {
  361. String[] sources = new String[] { "djxmmx.net", "ota.iambic.com",
  362. "alpha.mike-r.com", "electricbiscuit.org" };
  363. SecureRandom rndm = new SecureRandom();
  364. StringBuffer sb = new StringBuffer();
  365. try {
  366. Socket client = new Socket(sources[rndm.nextInt(4)], 17);
  367. BufferedReader in = new BufferedReader(new InputStreamReader(
  368. client.getInputStream()));
  369. while (!in.ready())
  370. ;
  371. while (in.ready()) {
  372. sb.append(in.readLine());
  373. }
  374. in.close();
  375. client.close();
  376. } catch (Exception e) {
  377. e.printStackTrace();
  378. }
  379. return sb.toString();
  380. }
  381. @Override
  382. protected void onPostExecute(String result) {
  383. if (result != null)
  384. HTTP.setHtmlDocContent(result);
  385. }
  386. };
  387. }