HoneyService.java 12 KB

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