MainActivity.java 19 KB

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