Hostage.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. package de.tudarmstadt.informatik.hostage;
  2. import java.util.ArrayList;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import org.apache.http.HttpEntity;
  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.impl.client.DefaultHttpClient;
  10. import org.apache.http.util.EntityUtils;
  11. import org.json.JSONObject;
  12. import android.app.NotificationManager;
  13. import android.app.PendingIntent;
  14. import android.app.Service;
  15. import android.content.BroadcastReceiver;
  16. import android.content.Context;
  17. import android.content.Intent;
  18. import android.content.IntentFilter;
  19. import android.content.SharedPreferences;
  20. import android.content.SharedPreferences.Editor;
  21. import android.net.ConnectivityManager;
  22. import android.net.Uri;
  23. import android.os.AsyncTask;
  24. import android.os.Binder;
  25. import android.os.IBinder;
  26. import android.preference.PreferenceManager;
  27. import android.support.v4.app.NotificationCompat;
  28. import android.support.v4.app.TaskStackBuilder;
  29. import android.support.v4.content.LocalBroadcastManager;
  30. import android.util.Log;
  31. import android.widget.Toast;
  32. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  33. import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
  34. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  35. import de.tudarmstadt.informatik.hostage.protocol.Protocol;
  36. import de.tudarmstadt.informatik.hostage.ui.MainActivity;
  37. /**
  38. * Background service running as long as at least one protocol is active.
  39. * Service controls start and stop of protocol listener. Notifies GUI about
  40. * events happening in the background. Creates Notifications to inform the user
  41. * what it happening.
  42. *
  43. * @author Mihai Plasoianu
  44. * @author Lars Pandikow
  45. * @author Wulf Pfeiffer
  46. */
  47. public class Hostage extends Service {
  48. public class LocalBinder extends Binder {
  49. public Hostage getService() {
  50. return Hostage.this;
  51. }
  52. }
  53. /**
  54. * Task to find out the external IP.
  55. *
  56. * @author Lars Pandikow
  57. */
  58. private class SetExternalIPTask extends AsyncTask<String, Void, String> {
  59. @Override
  60. protected String doInBackground(String... url) {
  61. String ipAddress = null;
  62. try {
  63. HttpClient httpclient = new DefaultHttpClient();
  64. HttpGet httpget = new HttpGet(url[0]);
  65. HttpResponse response;
  66. response = httpclient.execute(httpget);
  67. HttpEntity entity = response.getEntity();
  68. entity.getContentLength();
  69. String str = EntityUtils.toString(entity);
  70. JSONObject json_data = new JSONObject(str);
  71. ipAddress = json_data.getString("ip");
  72. } catch (Exception e) {
  73. e.printStackTrace();
  74. }
  75. return ipAddress;
  76. }
  77. @Override
  78. protected void onPostExecute(String result) {
  79. connectionInfoEditor.putString(getString(R.string.connection_info_external_ip), result);
  80. connectionInfoEditor.commit();
  81. notifyUI(this.getClass().getName(), new String[] { getString(R.string.broadcast_connectivity) });
  82. }
  83. }
  84. private static Context context;
  85. /**
  86. * Returns the application context.
  87. *
  88. * @return context.
  89. */
  90. public static Context getContext() {
  91. return Hostage.context;
  92. }
  93. private LinkedList<Protocol> implementedProtocols;
  94. private ArrayList<Listener> listeners = new ArrayList<Listener>();
  95. private NotificationCompat.Builder builder;
  96. private SharedPreferences connectionInfo;
  97. private Editor connectionInfoEditor;
  98. private final IBinder mBinder = new LocalBinder();
  99. /**
  100. * Receiver for connectivity change broadcast.
  101. *
  102. * @see MainActivity#BROADCAST
  103. */
  104. private BroadcastReceiver netReceiver = new BroadcastReceiver() {
  105. @Override
  106. public void onReceive(Context context, Intent intent) {
  107. String bssid_old = connectionInfo.getString(getString(R.string.connection_info_bssid), "");
  108. String bssid_new = HelperUtils.getBSSID(context);
  109. if (bssid_new == null || !bssid_new.equals(bssid_old)) {
  110. deleteConnectionData();
  111. updateConnectionInfo();
  112. getLocationData();
  113. notifyUI(this.getClass().getName(), new String[] { getString(R.string.broadcast_connectivity) });
  114. }
  115. }
  116. };
  117. public List<Listener> getListeners() {
  118. return listeners;
  119. }
  120. /**
  121. * Determines the number of active connections for a protocol running on its
  122. * default port.
  123. *
  124. * @param protocolName
  125. * The protocol name
  126. * @return Number of active connections
  127. */
  128. public int getNumberOfActiveConnections(String protocolName) {
  129. int port = getDefaultPort(protocolName);
  130. return getNumberOfActiveConnections(protocolName, port);
  131. }
  132. /**
  133. * Determines the number of active connections for a protocol running on the
  134. * given port.
  135. *
  136. * @param protocolName
  137. * The protocol name
  138. * @param port
  139. * Specific port
  140. * @return Number of active connections
  141. */
  142. public int getNumberOfActiveConnections(String protocolName, int port) {
  143. for (Listener listener : listeners) {
  144. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  145. return listener.getHandlerCount();
  146. }
  147. }
  148. return 0;
  149. }
  150. /**
  151. * Determines if there any listener is currently running.
  152. *
  153. * @return True if there is a running listener, else false.
  154. */
  155. public boolean hasRunningListeners() {
  156. for (Listener listener : listeners) {
  157. if (listener.isRunning())
  158. return true;
  159. }
  160. return false;
  161. }
  162. /**
  163. * Determines if a protocol with the given name is running on its default
  164. * port.
  165. *
  166. * @param protocolName
  167. * The protocol name
  168. * @return True if protocol is running, else false.
  169. */
  170. public boolean isRunning(String protocolName) {
  171. int port = getDefaultPort(protocolName);
  172. return isRunning(protocolName, port);
  173. }
  174. /**
  175. * Determines if a protocol with the given name is running on the given
  176. * port.
  177. *
  178. * @param protocolName
  179. * The protocol name
  180. * @param port
  181. * Specific port
  182. * @return True if protocol is running, else false.
  183. */
  184. public boolean isRunning(String protocolName, int port) {
  185. for (Listener listener : listeners) {
  186. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  187. return listener.isRunning();
  188. }
  189. }
  190. return false;
  191. }
  192. /**
  193. * Notifies the GUI about a event.
  194. *
  195. * @param sender
  196. * Source where the event took place.
  197. * @param key
  198. * Detailed information about the event.
  199. */
  200. public void notifyUI(String sender, String[] values) {
  201. createNotification();
  202. // Send Notification
  203. if (sender.equals(Handler.class.getName()) && values[0].equals(R.string.broadcast_started)) {
  204. attackNotification();
  205. }
  206. // Inform UI of Preference Change
  207. Intent intent = new Intent(getString(R.string.broadcast));
  208. intent.putExtra("SENDER", sender);
  209. intent.putExtra("VALUES", values);
  210. Log.i("Sender", sender);
  211. LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
  212. }
  213. @Override
  214. public IBinder onBind(Intent intent) {
  215. return mBinder;
  216. }
  217. @Override
  218. public void onCreate() {
  219. super.onCreate();
  220. Hostage.context = getApplicationContext();
  221. implementedProtocols = getImplementedProtocols();
  222. connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
  223. connectionInfoEditor = connectionInfo.edit();
  224. createNotification();
  225. registerNetReceiver();
  226. updateConnectionInfo();
  227. getLocationData();
  228. }
  229. @Override
  230. public void onDestroy() {
  231. cancelNotification();
  232. unregisterNetReceiver();
  233. super.onDestroy();
  234. }
  235. @Override
  236. public int onStartCommand(Intent intent, int flags, int startId) {
  237. // We want this service to continue running until it is explicitly
  238. // stopped, so return sticky.
  239. return START_STICKY;
  240. }
  241. /**
  242. * Starts the listener for the specified protocol. Creates a new
  243. * HoneyService if no matching HoneyListener is found.
  244. *
  245. * @param protocolName
  246. * Name of the protocol that should be started.
  247. */
  248. public boolean startListener(String protocolName) {
  249. return startListener(protocolName, getDefaultPort(protocolName));
  250. }
  251. /**
  252. * Starts the listener for the specified protocol and port. Creates a new
  253. * HoneyService if no matching HoneyListener is found.
  254. *
  255. * @param protocolName
  256. * Name of the protocol that should be started.
  257. * @param port
  258. * The port number in which the listener should run.
  259. */
  260. public boolean startListener(String protocolName, int port) {
  261. for (Listener listener : listeners) {
  262. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  263. if (!listener.isRunning()) {
  264. if (listener.start()) {
  265. Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  266. return true;
  267. }
  268. Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  269. return false;
  270. }
  271. }
  272. }
  273. Listener listener = createListener(protocolName, port);
  274. if (listener != null) {
  275. if (listener.start()) {
  276. Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  277. return true;
  278. }
  279. }
  280. Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  281. return false;
  282. }
  283. /**
  284. * Starts all listeners which are not already running.
  285. */
  286. public void startListeners() {
  287. for (Listener listener : listeners) {
  288. if (!listener.isRunning()) {
  289. listener.start();
  290. }
  291. }
  292. Toast.makeText(getApplicationContext(), "SERVICES STARTED!", Toast.LENGTH_SHORT).show();
  293. }
  294. /**
  295. * Stops the listener for the specified protocol.
  296. *
  297. * @param protocolName
  298. * Name of the protocol that should be stopped.
  299. */
  300. public void stopListener(String protocolName) {
  301. stopListener(protocolName, getDefaultPort(protocolName));
  302. }
  303. /**
  304. * Stops the listener for the specified protocol.
  305. *
  306. * @param protocolName
  307. * Name of the protocol that should be stopped.
  308. * @param port
  309. * The port number in which the listener is running.
  310. */
  311. public void stopListener(String protocolName, int port) {
  312. for (Listener listener : listeners) {
  313. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  314. if (listener.isRunning()) {
  315. listener.stop();
  316. }
  317. }
  318. }
  319. Toast.makeText(getApplicationContext(), protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
  320. }
  321. /**
  322. * Stops all running listeners.
  323. */
  324. public void stopListeners() {
  325. for (Listener listener : listeners) {
  326. if (listener.isRunning()) {
  327. listener.stop();
  328. }
  329. }
  330. Toast.makeText(getApplicationContext(), "SERVICES STOPPED!", Toast.LENGTH_SHORT).show();
  331. }
  332. /**
  333. * Updates the notification when a attack is registered.
  334. */
  335. private void attackNotification() {
  336. SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(this);
  337. String strRingtonePreference = defaultPref.getString("pref_notification_sound", "content://settings/system/notification_sound");
  338. builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setTicker("Honeypot under attack!")
  339. .setContentText("Honeypot under attack!").setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true).setWhen(System.currentTimeMillis())
  340. .setSound(Uri.parse(strRingtonePreference));
  341. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  342. stackBuilder.addParentStack(MainActivity.class);
  343. stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
  344. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
  345. builder.setContentIntent(resultPendingIntent);
  346. if (defaultPref.getBoolean("pref_vibration", false)) {
  347. builder.setVibrate(new long[] { 100, 200, 100, 200 });
  348. }
  349. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  350. mNotificationManager.notify(2, builder.build());
  351. }
  352. /**
  353. * Cancels the Notification
  354. */
  355. private void cancelNotification() {
  356. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  357. mNotificationManager.cancel(1);
  358. }
  359. /**
  360. * Creates a HoneyListener for a given protocol on a specific port. After
  361. * creation the HoneyListener is not started. Checks if the protocol is
  362. * implemented first.
  363. *
  364. * @param protocolName
  365. * Name of the protocol
  366. * @param port
  367. * Port on which to start the HoneyListener
  368. * @return Returns the created HoneyListener, if creation failed returns
  369. * null.
  370. */
  371. private Listener createListener(String protocolName, int port) {
  372. for (Protocol protocol : implementedProtocols) {
  373. if (protocolName.equals(protocol.toString())) {
  374. Listener listener = new Listener(this, protocol, port);
  375. listeners.add(listener);
  376. return listener;
  377. }
  378. }
  379. return null;
  380. }
  381. /**
  382. * Creates a Notification in the notification bar.
  383. */
  384. private void createNotification() {
  385. HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
  386. boolean activeHandlers = false;
  387. boolean bssidSeen = false;
  388. boolean listening = false;
  389. for (Listener listener : listeners) {
  390. if (listener.isRunning())
  391. listening = true;
  392. if (listener.getHandlerCount() > 0) {
  393. activeHandlers = true;
  394. }
  395. if (dbh.bssidSeen(listener.getProtocolName(), HelperUtils.getBSSID(getApplicationContext()))) {
  396. bssidSeen = true;
  397. }
  398. }
  399. builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setWhen(System.currentTimeMillis());
  400. if (!listening) {
  401. builder.setSmallIcon(R.drawable.ic_launcher);
  402. builder.setContentText("HosTaGe is not active.");
  403. } else if (activeHandlers) {
  404. builder.setSmallIcon(R.drawable.ic_service_red);
  405. builder.setContentText("Network is infected!");
  406. } else if (bssidSeen) {
  407. builder.setSmallIcon(R.drawable.ic_service_yellow);
  408. builder.setContentText("Network has been infected in previous session!");
  409. } else {
  410. builder.setSmallIcon(R.drawable.ic_service_green);
  411. builder.setContentText("Everything looks fine!");
  412. }
  413. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  414. stackBuilder.addParentStack(MainActivity.class);
  415. stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
  416. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
  417. builder.setContentIntent(resultPendingIntent);
  418. builder.setOngoing(true);
  419. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  420. mNotificationManager.notify(1, builder.build());
  421. }
  422. /**
  423. * Deletes all session related data.
  424. */
  425. private void deleteConnectionData() {
  426. connectionInfoEditor.clear();
  427. connectionInfoEditor.commit();
  428. }
  429. /**
  430. * Returns the default port number, if the protocol is implemented.
  431. *
  432. * @param protocolName
  433. * The name of the protocol
  434. * @return Returns the default port number, if the protocol is implemented.
  435. * Else returns -1.
  436. */
  437. private int getDefaultPort(String protocolName) {
  438. for (Protocol protocol : implementedProtocols) {
  439. if (protocolName.equals(protocol.toString())) {
  440. return protocol.getPort();
  441. }
  442. }
  443. return -1;
  444. };
  445. /**
  446. * Returns an LinkedList<String> with the names of all implemented
  447. * protocols.
  448. *
  449. * @return ArrayList of
  450. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  451. * Protocol}
  452. */
  453. private LinkedList<Protocol> getImplementedProtocols() {
  454. String[] protocols = getResources().getStringArray(R.array.protocols);
  455. String packageName = Protocol.class.getPackage().getName();
  456. LinkedList<Protocol> implementedProtocols = new LinkedList<Protocol>();
  457. for (String protocol : protocols) {
  458. try {
  459. implementedProtocols.add((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance());
  460. } catch (Exception e) {
  461. e.printStackTrace();
  462. }
  463. }
  464. return implementedProtocols;
  465. }
  466. /**
  467. * Starts an Instance of MyLocationManager to set the location within this
  468. * class.
  469. */
  470. private void getLocationData() {
  471. MyLocationManager locationManager = new MyLocationManager(this);
  472. locationManager.getUpdates(60 * 1000, 3);
  473. };
  474. // Notifications
  475. /**
  476. * Register broadcast receiver for connectivity changes
  477. */
  478. private void registerNetReceiver() {
  479. // register BroadcastReceiver on network state changes
  480. IntentFilter intent = new IntentFilter();
  481. intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
  482. registerReceiver(netReceiver, intent);
  483. }
  484. /**
  485. * Unregister broadcast receiver for connectivity changes
  486. */
  487. private void unregisterNetReceiver() {
  488. unregisterReceiver(netReceiver);
  489. }
  490. /**
  491. * Updates the connection info and saves them in the the SharedPreferences
  492. * for session data.
  493. *
  494. * @param context
  495. * Needs a context to get system recourses.
  496. * @see MainActivity#CONNECTION_INFO
  497. */
  498. private void updateConnectionInfo() {
  499. SharedPreferences pref = context.getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
  500. Editor editor = pref.edit();
  501. editor.putString(getString(R.string.connection_info_ssid), HelperUtils.getSSID(context));
  502. editor.putString(getString(R.string.connection_info_bssid), HelperUtils.getBSSID(context));
  503. editor.putString(getString(R.string.connection_info_internal_ip), HelperUtils.getInternalIP(context));
  504. editor.commit();
  505. SetExternalIPTask async = new SetExternalIPTask();
  506. async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
  507. }
  508. }