MainActivity.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. package de.tudarmstadt.informatik.hostage.ui;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import android.app.Activity;
  5. import android.app.ActivityManager;
  6. import android.app.ActivityManager.RunningServiceInfo;
  7. import android.content.BroadcastReceiver;
  8. import android.content.ComponentName;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import android.content.IntentFilter;
  12. import android.content.ServiceConnection;
  13. import android.content.SharedPreferences;
  14. import android.content.SharedPreferences.Editor;
  15. import android.net.ConnectivityManager;
  16. import android.os.Bundle;
  17. import android.os.IBinder;
  18. import android.support.v4.content.LocalBroadcastManager;
  19. import android.view.GestureDetector;
  20. import android.view.GestureDetector.SimpleOnGestureListener;
  21. import android.view.Menu;
  22. import android.view.MenuItem;
  23. import android.view.MotionEvent;
  24. import android.view.View;
  25. import android.view.View.OnTouchListener;
  26. import android.view.animation.Animation;
  27. import android.view.animation.AnimationUtils;
  28. import android.widget.AdapterView;
  29. import android.widget.AdapterView.OnItemClickListener;
  30. import android.widget.CheckBox;
  31. import android.widget.ImageView;
  32. import android.widget.ListView;
  33. import android.widget.TextView;
  34. import android.widget.Toast;
  35. import android.widget.ToggleButton;
  36. import android.widget.ViewAnimator;
  37. import de.tudarmstadt.informatik.hostage.HoneyService;
  38. import de.tudarmstadt.informatik.hostage.HoneyService.LocalBinder;
  39. import de.tudarmstadt.informatik.hostage.R;
  40. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  41. import de.tudarmstadt.informatik.hostage.logging.Logger;
  42. import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
  43. /**
  44. * MainActivity is the central activity for the GUI of the application.
  45. * MainActivity is launched when the application is first started.
  46. * It shows the user: <br>
  47. * - information about the network<br>
  48. * - light indicators for recorded attacks on each protocol<br>
  49. * - amount of attacks on each protocols<br>
  50. * The user can start and stop services.
  51. * @author Mihai Plasoianu
  52. * @author Lars Pandikow
  53. *
  54. */
  55. public class MainActivity extends Activity {
  56. // String constants for whole application
  57. /**
  58. * Used for Broadcast between service and GUI. String: "de.tudarmstadt.informatik.hostage.BROADCAST"
  59. */
  60. public static final String BROADCAST = "de.tudarmstadt.informatik.hostage.BROADCAST";
  61. /**
  62. * Used to store session related data in a SharedPrefereces. String: "de.tudarmstadt.informatik.hostage.SESSION_DATA"
  63. */
  64. public static final String SESSION_DATA = "de.tudarmstadt.informatik.hostage.SESSION_DATA";
  65. public static final String LISTENER = "_LISTENER";
  66. public static final String HANDLER_COUNT = "_HANDLER_COUNT";
  67. public static final String SSID = "SSID";
  68. public static final String BSSID = "BSSID";
  69. public static final String INTERNAL_IP = "INTERNAL_IP";
  70. public static final String EXTERNAL_IP = "EXTERNAL_IP";
  71. /**
  72. * Integer representing a grey light.
  73. */
  74. public static final int LIGHT_GREY = 0x01;
  75. /**
  76. * Integer representing a green light.
  77. */
  78. public static final int LIGHT_GREEN = 0x02;
  79. /**
  80. * Integer representing a red light.
  81. */
  82. public static final int LIGHT_RED = 0x03;
  83. /**
  84. * Integer representing a yellow light.
  85. */
  86. public static final int LIGHT_YELLOW = 0x04;
  87. private HoneyService mService;
  88. private boolean serviceBound;
  89. private SharedPreferences pref;
  90. private Editor editor;
  91. private Logger logger;
  92. // variables for the swipe animation
  93. private ViewAnimator viewAnimator;
  94. private GestureDetector gestureDetector;
  95. private Animation animFlipInLR;
  96. private Animation animFlipOutLR;
  97. private Animation animFlipInRL;
  98. private Animation animFlipOutRL;
  99. private ListView listView;
  100. private ListViewAdapter adapter;
  101. private String protocolClicked;
  102. @Override
  103. protected void onCreate(Bundle savedInstanceState) {
  104. super.onCreate(savedInstanceState);
  105. setContentView(R.layout.activity_main);
  106. // Create dynamic view elements
  107. initViewAnimator();
  108. initListView();
  109. // Initialize Class variables
  110. pref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
  111. logger = new SQLLogger(this);
  112. editor = pref.edit();
  113. }
  114. @Override
  115. public boolean onCreateOptionsMenu(Menu menu) {
  116. getMenuInflater().inflate(R.menu.main, menu);
  117. return true;
  118. }
  119. @Override
  120. public boolean onOptionsItemSelected(MenuItem item) {
  121. // Handle item selection
  122. switch (item.getItemId()) {
  123. case R.id.action_settings:
  124. startActivity(new Intent(this, SettingsActivity.class));
  125. break;
  126. case R.id.action_about:
  127. startActivity(new Intent(this, AboutActivity.class));
  128. break;
  129. default:
  130. }
  131. return super.onOptionsItemSelected(item);
  132. }
  133. @Override
  134. protected void onStart() {
  135. super.onStart();
  136. //Register Broadcast Receiver
  137. registerReceiver();
  138. registerNetReceiver();
  139. // Bind service if running, else check for connection change and delete sessionData
  140. if (isServiceRunning()) {
  141. bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
  142. } else {
  143. String bssid_old = pref.getString(MainActivity.BSSID, "");
  144. String bssid_new = HelperUtils.getBSSID(this);
  145. if(bssid_new == null || !bssid_new.equals(bssid_old)){
  146. deleteSessionData();
  147. }
  148. }
  149. // Update UI
  150. updateUI();
  151. updateConnectionInfo();
  152. }
  153. @Override
  154. protected void onStop() {
  155. //Unbind running service
  156. if (isServiceRunning()) {
  157. unbindService(mConnection);
  158. }
  159. // Unregister Broadcast Receiver
  160. unregisterNetReceiver();
  161. unregisterReceiver();
  162. super.onStop();
  163. }
  164. @Override
  165. protected void onDestroy(){
  166. super.onDestroy();
  167. // If service not running delete session data
  168. if(!isServiceRunning()){
  169. deleteSessionData();
  170. }
  171. }
  172. /**
  173. * Called when User presses on/off button.
  174. * @param view
  175. */
  176. public void buttonOnOffClick(View view) {
  177. if (((ToggleButton) view).isChecked()) {
  178. if (isParanoid()) {
  179. protocolClicked = "PANIC";
  180. } else {
  181. protocolClicked = "SMB";
  182. }
  183. startAndBind();
  184. } else {
  185. mService.stopListeners();
  186. stopAndUnbind();
  187. }
  188. }
  189. /**
  190. * Starts the ViewLog activity, when the Button is pressed.
  191. * @see ViewLog
  192. * @param view View elements which triggers the method call.
  193. */
  194. public void showLog(View view){
  195. startActivity(new Intent(this, ViewLog.class));
  196. }
  197. /**
  198. * If mobile phone is connected to a wireless network starts the background service ands binds itself to it.
  199. * Else notifies the user that service could not be started.
  200. */
  201. private void startAndBind() {
  202. if(HelperUtils.getBSSID(this) != null){
  203. startService(getServiceIntent());
  204. bindService();
  205. } else{
  206. ToggleButton button = (ToggleButton) findViewById(R.id.toggleButtonOnOff);
  207. button.setChecked(false);
  208. Toast.makeText(getApplicationContext(), "To start a service, first connect to a wireless network.", Toast.LENGTH_SHORT).show();
  209. }
  210. }
  211. /**
  212. * Binds service to Activity
  213. * @see HoneyService
  214. */
  215. private void bindService(){
  216. bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
  217. serviceBound = true;
  218. }
  219. /**
  220. * Stops service and unbinds it.
  221. * @see HoneyService
  222. */
  223. private void stopAndUnbind() {
  224. unbindService();
  225. stopService(getServiceIntent());
  226. }
  227. /**
  228. * Unbinds service.
  229. * @see HoneyService
  230. */
  231. private void unbindService(){
  232. unbindService(mConnection);
  233. serviceBound = false;
  234. }
  235. /**
  236. * Connection to bind the background service
  237. * @see HoneyService
  238. */
  239. private ServiceConnection mConnection = new ServiceConnection() {
  240. /**
  241. * After the service is bound, check which has been clicked and start it.
  242. * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
  243. */
  244. @Override
  245. public void onServiceConnected(ComponentName name, IBinder service) {
  246. mService = ((LocalBinder) service).getService();
  247. if(protocolClicked != null && protocolClicked.equals("PANIC")){
  248. mService.startListeners();
  249. }else if (protocolClicked != null){
  250. mService.toggleListener(protocolClicked);
  251. }
  252. protocolClicked = null;
  253. }
  254. /**
  255. * After the service is unbound, delete reference.
  256. * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
  257. */
  258. @Override
  259. public void onServiceDisconnected(ComponentName name) {
  260. mService = null;
  261. }
  262. };
  263. /**
  264. * Returns an intent to start HoneyService.
  265. * @return An Intent to start HoneyService
  266. */
  267. private Intent getServiceIntent() {
  268. return new Intent(this, HoneyService.class);
  269. }
  270. /**
  271. * Checks if user selected paranoid mode.
  272. * @return True when paranoid mode is selected, else returns false.
  273. */
  274. private boolean isParanoid() {
  275. return ((CheckBox) findViewById(R.id.checkBoxParanoid)).isChecked();
  276. }
  277. /**
  278. * Initializes the ListView. Creating its contents dynamic from protocol res/values/protocols.xml
  279. */
  280. private void initListView() {
  281. ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
  282. for (String protocol : getResources().getStringArray(R.array.protocols)) {
  283. HashMap<String, String> d = new HashMap<String, String>();
  284. d.put("light", String.valueOf(R.drawable.light_grey));
  285. d.put("protocol", protocol);
  286. d.put("connections", "-");
  287. data.add(d);
  288. }
  289. listView = (ListView) findViewById(R.id.listViewProtocols);
  290. adapter = new ListViewAdapter(getLayoutInflater(), data);
  291. listView.setAdapter(adapter);
  292. listView.setOnTouchListener(new OnTouchListener() {
  293. @Override
  294. public boolean onTouch(View v, MotionEvent event) {
  295. return gestureDetector.onTouchEvent(event);
  296. }
  297. });
  298. listView.setOnItemClickListener(new OnItemClickListener() {
  299. @Override
  300. public void onItemClick(AdapterView<?> parent, View view,
  301. int position, long id) {
  302. String protocolName = (String) ((HashMap<?, ?>) adapter
  303. .getItem(position)).get("protocol");
  304. if (isServiceRunning()) {
  305. mService.toggleListener(protocolName);
  306. if(!mService.hasRunningListeners()){
  307. stopAndUnbind();
  308. }
  309. }else{
  310. protocolClicked = protocolName;
  311. startAndBind();
  312. }
  313. }
  314. });
  315. }
  316. /**
  317. * Checks if a {@link HoneyService} instance is running.
  318. * @return True if {@link HoneyService} is running, else false.
  319. */
  320. private boolean isServiceRunning() {
  321. ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
  322. for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
  323. if (service.service.getClassName().equals(HoneyService.class.getName())) {
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. /**
  330. * Deletes all session related Data.
  331. */
  332. private void deleteSessionData(){
  333. editor.clear();
  334. editor.commit();
  335. }
  336. /**
  337. * Register broadcast receiver for custom broadcast.
  338. * @see #BROADCAST
  339. */
  340. private void registerReceiver() {
  341. LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
  342. new IntentFilter(BROADCAST));
  343. }
  344. /**
  345. * Unregisters broadcast receiver for custom broadcast.
  346. * @see #BROADCAST
  347. */
  348. private void unregisterReceiver() {
  349. LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
  350. }
  351. /**
  352. * Receiver for custom broadcast.
  353. * @see #BROADCAST
  354. */
  355. private BroadcastReceiver mReceiver = new BroadcastReceiver() {
  356. @Override
  357. public void onReceive(Context context, Intent intent) {
  358. // Update user interface.
  359. updateUI();
  360. }
  361. };
  362. /**
  363. * Register broadcast receiver for network state changes.
  364. * @see ConnectivityManager#CONNECTIVITY_ACTION
  365. */
  366. private void registerNetReceiver() {
  367. IntentFilter intent = new IntentFilter();
  368. intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); //"android.net.conn.CONNECTIVITY_CHANGE"
  369. registerReceiver(netReceiver, intent);
  370. }
  371. /**
  372. * Unregister broadcast receiver for network state changes.
  373. */
  374. private void unregisterNetReceiver() {
  375. unregisterReceiver(netReceiver);
  376. }
  377. /**
  378. * Receiver for network state change events.
  379. */
  380. private BroadcastReceiver netReceiver = new BroadcastReceiver() {
  381. @Override
  382. public void onReceive(Context context, Intent intent) {
  383. String bssid_old = pref.getString(BSSID, "");
  384. String bssid_new = HelperUtils.getBSSID(context);
  385. if ((bssid_new == null || !bssid_new.equals(bssid_old)) && serviceBound) {
  386. Toast.makeText(getApplicationContext(),"Connection changed! Services stopped!", Toast.LENGTH_LONG).show();
  387. unbindService();
  388. }
  389. updateConnectionInfo();
  390. }
  391. };
  392. /**
  393. * Updates Information shown by the GUI.
  394. */
  395. private void updateUI() {
  396. boolean activeListeners = false;
  397. boolean activeHandlers = false;
  398. boolean yellowLight = false;
  399. //Check for all protocols if listeners are active and attacks have been recorded
  400. //Update protocol lights and connection information.
  401. for(String protocol : getResources().getStringArray(R.array.protocols)){
  402. //Check if protocol is active
  403. if(pref.getBoolean(protocol + LISTENER, false)){
  404. activeListeners = true;
  405. int handlerCount = pref.getInt(protocol + HANDLER_COUNT, 0);
  406. //Check if attacks have been recorded in this session.
  407. if(handlerCount > 0){
  408. activeHandlers = true;
  409. updateProtocolLight(LIGHT_RED, protocol);
  410. updateProtocolConnections(handlerCount, protocol);
  411. } else{
  412. //Check if the bssid of the wireless network has already been recorded as infected.
  413. if(logger.bssidSeen(protocol, HelperUtils.getBSSID(getApplicationContext()))){
  414. updateProtocolLight(LIGHT_YELLOW, protocol);
  415. yellowLight = true;
  416. } else{
  417. updateProtocolLight(LIGHT_GREEN, protocol);
  418. }
  419. updateProtocolConnections(0, protocol);
  420. }
  421. }else{
  422. updateProtocolLight(LIGHT_GREY, protocol);
  423. }
  424. }
  425. //Update the big attack indicator.
  426. if (activeListeners) {
  427. if (activeHandlers) {
  428. updateStatusLight(LIGHT_RED);
  429. } else {
  430. if(yellowLight){
  431. updateStatusLight(LIGHT_YELLOW);
  432. } else {
  433. updateStatusLight(LIGHT_GREEN);
  434. }
  435. }
  436. ((ToggleButton) findViewById(R.id.toggleButtonOnOff))
  437. .setChecked(true);
  438. findViewById(R.id.checkBoxParanoid).setEnabled(false);
  439. } else {
  440. updateStatusLight(LIGHT_GREY);
  441. ((ToggleButton) findViewById(R.id.toggleButtonOnOff))
  442. .setChecked(false);
  443. findViewById(R.id.checkBoxParanoid).setEnabled(true);
  444. }
  445. }
  446. /**
  447. * Sets the big light indicator.
  448. * @param light Integer code to set the light color.
  449. * @see #LIGHT_GREY
  450. * @see #LIGHT_GREEN
  451. * @see #LIGHT_RED
  452. * @see #LIGHT_YELLOW
  453. */
  454. private void updateStatusLight(int light) {
  455. switch (light) {
  456. case LIGHT_GREY:
  457. ((ImageView) findViewById(R.id.imageViewLight))
  458. .setImageResource(R.drawable.light_grey_large);
  459. break;
  460. case LIGHT_GREEN:
  461. ((ImageView) findViewById(R.id.imageViewLight))
  462. .setImageResource(R.drawable.light_green_large);
  463. break;
  464. case LIGHT_RED:
  465. ((ImageView) findViewById(R.id.imageViewLight))
  466. .setImageResource(R.drawable.light_red_large);
  467. break;
  468. case LIGHT_YELLOW:
  469. ((ImageView) findViewById(R.id.imageViewLight))
  470. .setImageResource(R.drawable.light_yellow_large);
  471. break;
  472. }
  473. }
  474. /**
  475. * Sets the light indicator for a given protocol.
  476. * @param light Integer code to set the light color.
  477. * @param protocolName Name of the protocol which should be updated.
  478. */
  479. private void updateProtocolLight(int light, String protocolName) {
  480. for (int i = 0; i < adapter.getCount(); ++i) {
  481. HashMap<String, String> d = (HashMap<String, String>) adapter
  482. .getItem(i);
  483. if (d.get("protocol").equals(protocolName)) {
  484. switch (light) {
  485. case LIGHT_GREY:
  486. d.put("light", String.valueOf(R.drawable.light_grey));
  487. d.put("connections", "-");
  488. break;
  489. case LIGHT_GREEN:
  490. d.put("light", String.valueOf(R.drawable.light_green));
  491. break;
  492. case LIGHT_RED:
  493. d.put("light", String.valueOf(R.drawable.light_red));
  494. break;
  495. case LIGHT_YELLOW:
  496. d.put("light", String.valueOf(R.drawable.light_yellow));
  497. break;
  498. }
  499. }
  500. }
  501. adapter.notifyDataSetChanged();
  502. }
  503. /**
  504. * Sets the connections count for a given protocol
  505. * @param connections New value for recorded connections.
  506. * @param protocolName Name of the protocol which should be updated.
  507. */
  508. private void updateProtocolConnections(int connections, String protocolName) {
  509. for (int i = 0; i < adapter.getCount(); ++i) {
  510. HashMap<String, String> d = ((HashMap<String, String>) adapter
  511. .getItem(i));
  512. if (d.get("protocol").equals(protocolName)) {
  513. d.put("connections", String.valueOf(connections));
  514. }
  515. }
  516. adapter.notifyDataSetChanged();
  517. }
  518. /**
  519. * Gets Information about connection state and updates the GUI.
  520. */
  521. private void updateConnectionInfo() {
  522. //Get text fields
  523. TextView ssidView = (TextView) findViewById(R.id.textViewSSIDValue);
  524. TextView bssidView = (TextView) findViewById(R.id.textViewBSSIDValue);
  525. TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
  526. TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
  527. //Update the connection information
  528. HelperUtils.updateConnectionInfo(this);
  529. //Get connection information
  530. String ssid = pref.getString(SSID, "-");
  531. String bssid = pref.getString(BSSID, "-");
  532. String internalIP = pref.getString(INTERNAL_IP, "-");
  533. String externalIP = pref.getString(EXTERNAL_IP, "-");
  534. //Set text fields
  535. if (ssid != null)
  536. ssidView.setText(ssid);
  537. else
  538. ssidView.setText("-");
  539. if (bssid != null)
  540. bssidView.setText(bssid);
  541. else
  542. bssidView.setText("-");
  543. if (internalIP != null)
  544. internalIPView.setText(internalIP);
  545. else
  546. internalIPView.setText("-");
  547. if (externalIP != null)
  548. externalIPView.setText(externalIP);
  549. else
  550. externalIPView.setText("-");
  551. }
  552. /*############# Help functions for animation ##################*/
  553. @Override
  554. public boolean onTouchEvent(MotionEvent event) {
  555. return gestureDetector.onTouchEvent(event);
  556. }
  557. /**
  558. * Initializes variables for screen animation
  559. */
  560. private void initViewAnimator() {
  561. viewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
  562. gestureDetector = new GestureDetector(this, simpleOnGestureListener);
  563. animFlipInLR = AnimationUtils.loadAnimation(this,
  564. R.anim.in_left_to_right);
  565. animFlipOutLR = AnimationUtils.loadAnimation(this,
  566. R.anim.out_left_to_right);
  567. animFlipInRL = AnimationUtils.loadAnimation(this,
  568. R.anim.in_right_to_left);
  569. animFlipOutRL = AnimationUtils.loadAnimation(this,
  570. R.anim.out_right_to_left);
  571. }
  572. /**
  573. * Called when a swipe to the Left is registered.
  574. */
  575. private void swipeRightToLeft() {
  576. if (viewAnimator.getDisplayedChild() == 0) {
  577. viewAnimator.setInAnimation(animFlipInRL);
  578. viewAnimator.setOutAnimation(animFlipOutRL);
  579. viewAnimator.setDisplayedChild(1);
  580. }
  581. }
  582. /**
  583. * Called when a swipe to the Right is registered.
  584. */
  585. private void swipeLeftToRight() {
  586. if (viewAnimator.getDisplayedChild() == 1) {
  587. viewAnimator.setInAnimation(animFlipInLR);
  588. viewAnimator.setOutAnimation(animFlipOutLR);
  589. viewAnimator.setDisplayedChild(0);
  590. }
  591. }
  592. SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
  593. @Override
  594. public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
  595. float velocityY) {
  596. float sensitvity = 50;
  597. if ((e1.getX() - e2.getX()) > sensitvity) {
  598. swipeRightToLeft();
  599. } else if ((e2.getX() - e1.getX()) > sensitvity) {
  600. swipeLeftToRight();
  601. }
  602. return true;
  603. }
  604. };
  605. }