HoneyService.java 12 KB

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