HoneyService.java 12 KB

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