Hostage.java 20 KB

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