HoneyService.java 12 KB

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