HoneyService.java 12 KB

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