Hostage.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. /**
  213. * Notifies the GUI about a event.
  214. *
  215. * @param sender
  216. * Source where the event took place.
  217. * @param key
  218. * Detailed information about the event.
  219. */
  220. public void notifyUI(String sender, String[] values) {
  221. createNotification();
  222. // Send Notification
  223. if (sender.equals(Handler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
  224. this.mProtocolActiveAttacks.put(values[1], true);
  225. attackNotification();
  226. }
  227. // Inform UI of Preference Change
  228. Intent intent = new Intent(getString(R.string.broadcast));
  229. intent.putExtra("SENDER", sender);
  230. intent.putExtra("VALUES", values);
  231. Log.i("Sender", sender);
  232. LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
  233. }
  234. @Override
  235. public IBinder onBind(Intent intent) {
  236. return mBinder;
  237. }
  238. @Override
  239. public void onCreate() {
  240. super.onCreate();
  241. Hostage.context = getApplicationContext();
  242. implementedProtocols = getImplementedProtocols();
  243. connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
  244. connectionInfoEditor = connectionInfo.edit();
  245. mProtocolActiveAttacks = new HashMap<String, Boolean>();
  246. createNotification();
  247. registerNetReceiver();
  248. updateConnectionInfo();
  249. getLocationData();
  250. }
  251. @Override
  252. public void onDestroy() {
  253. cancelNotification();
  254. unregisterNetReceiver();
  255. super.onDestroy();
  256. }
  257. @Override
  258. public int onStartCommand(Intent intent, int flags, int startId) {
  259. // We want this service to continue running until it is explicitly
  260. // stopped, so return sticky.
  261. return START_STICKY;
  262. }
  263. /**
  264. * Starts the listener for the specified protocol. Creates a new
  265. * HoneyService if no matching HoneyListener is found.
  266. *
  267. * @param protocolName
  268. * Name of the protocol that should be started.
  269. */
  270. public boolean startListener(String protocolName) {
  271. return startListener(protocolName, getDefaultPort(protocolName));
  272. }
  273. /**
  274. * Starts the listener for the specified protocol and port. Creates a new
  275. * HoneyService if no matching HoneyListener is found.
  276. *
  277. * @param protocolName
  278. * Name of the protocol that should be started.
  279. * @param port
  280. * The port number in which the listener should run.
  281. */
  282. public boolean startListener(String protocolName, int port) {
  283. for (Listener listener : listeners) {
  284. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  285. if (!listener.isRunning()) {
  286. if (listener.start()) {
  287. // Toast.makeText(getApplicationContext(), protocolName
  288. // + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  289. return true;
  290. }
  291. Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  292. return false;
  293. }
  294. }
  295. }
  296. Listener listener = createListener(protocolName, port);
  297. if (listener != null) {
  298. if (listener.start()) {
  299. // Toast.makeText(getApplicationContext(), protocolName +
  300. // " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  301. return true;
  302. }
  303. }
  304. Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  305. return false;
  306. }
  307. /**
  308. * Starts all listeners which are not already running.
  309. */
  310. public void startListeners() {
  311. for (Listener listener : listeners) {
  312. if (!listener.isRunning()) {
  313. listener.start();
  314. }
  315. }
  316. // Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
  317. // Toast.LENGTH_SHORT).show();
  318. }
  319. /**
  320. * Stops the listener for the specified protocol.
  321. *
  322. * @param protocolName
  323. * Name of the protocol that should be stopped.
  324. */
  325. public void stopListener(String protocolName) {
  326. stopListener(protocolName, getDefaultPort(protocolName));
  327. }
  328. /**
  329. * Stops the listener for the specified protocol.
  330. *
  331. * @param protocolName
  332. * Name of the protocol that should be stopped.
  333. * @param port
  334. * The port number in which the listener is running.
  335. */
  336. public void stopListener(String protocolName, int port) {
  337. for (Listener listener : listeners) {
  338. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  339. if (listener.isRunning()) {
  340. listener.stop();
  341. mProtocolActiveAttacks.remove(protocolName);
  342. }
  343. }
  344. }
  345. // Toast.makeText(getApplicationContext(), protocolName +
  346. // " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
  347. }
  348. public void stopListenerAllPorts(String protocolName){
  349. for(Listener listener: listeners){
  350. if(listener.getProtocolName().equals(protocolName)){
  351. if(listener.isRunning()){
  352. listener.stop();
  353. mProtocolActiveAttacks.remove(protocolName);
  354. }
  355. }
  356. }
  357. }
  358. /**
  359. * Stops all running listeners.
  360. */
  361. public void stopListeners() {
  362. for (Listener listener : listeners) {
  363. if (listener.isRunning()) {
  364. listener.stop();
  365. mProtocolActiveAttacks.remove(listener.getProtocolName());
  366. }
  367. }
  368. // Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
  369. // Toast.LENGTH_SHORT).show();
  370. }
  371. /**
  372. * Updates the notification when a attack is registered.
  373. */
  374. private void attackNotification() {
  375. SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(this);
  376. String strRingtonePreference = defaultPref.getString("pref_notification_sound", "content://settings/system/notification_sound");
  377. builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setTicker("Honeypot under attack!")
  378. .setContentText("Honeypot under attack!").setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true).setWhen(System.currentTimeMillis())
  379. .setSound(Uri.parse(strRingtonePreference));
  380. Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
  381. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  382. stackBuilder.addParentStack(MainActivity.class);
  383. Intent intent = MainActivity.getInstance().getIntent();
  384. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
  385. intent.setAction("SHOW_HOME");
  386. stackBuilder.addNextIntent(intent);
  387. PendingIntent resultPendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, 0);
  388. builder.setContentIntent(resultPendingIntent);
  389. if (defaultPref.getBoolean("pref_vibration", false)) {
  390. builder.setVibrate(new long[] { 100, 200, 100, 200 });
  391. }
  392. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  393. mNotificationManager.notify(1, builder.build());
  394. }
  395. /**
  396. * Cancels the Notification
  397. */
  398. private void cancelNotification() {
  399. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  400. mNotificationManager.cancel(1);
  401. }
  402. /**
  403. * Creates a HoneyListener for a given protocol on a specific port. After
  404. * creation the HoneyListener is not started. Checks if the protocol is
  405. * implemented first.
  406. *
  407. * @param protocolName
  408. * Name of the protocol
  409. * @param port
  410. * Port on which to start the HoneyListener
  411. * @return Returns the created HoneyListener, if creation failed returns
  412. * null.
  413. */
  414. private Listener createListener(String protocolName, int port) {
  415. for (Protocol protocol : implementedProtocols) {
  416. if (protocolName.equals(protocol.toString())) {
  417. Listener listener = new Listener(this, protocol, port);
  418. listeners.add(listener);
  419. return listener;
  420. }
  421. }
  422. return null;
  423. }
  424. /**
  425. * Creates a Notification in the notification bar.
  426. */
  427. private void createNotification() {
  428. HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
  429. boolean activeHandlers = false;
  430. boolean bssidSeen = false;
  431. boolean listening = false;
  432. for (Listener listener : listeners) {
  433. if (listener.isRunning())
  434. listening = true;
  435. if (listener.getHandlerCount() > 0) {
  436. activeHandlers = true;
  437. }
  438. if (dbh.bssidSeen(listener.getProtocolName(), HelperUtils.getBSSID(getApplicationContext()))) {
  439. bssidSeen = true;
  440. }
  441. }
  442. builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setWhen(System.currentTimeMillis());
  443. if (!listening) {
  444. builder.setSmallIcon(R.drawable.ic_launcher);
  445. builder.setContentText("HosTaGe is not active.");
  446. } else if (activeHandlers) {
  447. builder.setSmallIcon(R.drawable.ic_service_red);
  448. builder.setContentText("Network is infected!");
  449. } else if (bssidSeen) {
  450. builder.setSmallIcon(R.drawable.ic_service_yellow);
  451. builder.setContentText("Network has been infected in previous session!");
  452. } else {
  453. builder.setSmallIcon(R.drawable.ic_service_green);
  454. builder.setContentText("Everything looks fine!");
  455. }
  456. Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
  457. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  458. stackBuilder.addParentStack(MainActivity.class);
  459. Intent intent = MainActivity.getInstance().getIntent();
  460. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
  461. intent.setAction("SHOW_HOME");
  462. stackBuilder.addNextIntent(intent);
  463. PendingIntent resultPendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, 0); //stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
  464. builder.setContentIntent(resultPendingIntent);
  465. builder.setOngoing(true);
  466. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  467. mNotificationManager.notify(1, builder.build());
  468. }
  469. /**
  470. * Deletes all session related data.
  471. */
  472. private void deleteConnectionData() {
  473. connectionInfoEditor.clear();
  474. connectionInfoEditor.commit();
  475. }
  476. /**
  477. * Returns the default port number, if the protocol is implemented.
  478. *
  479. * @param protocolName
  480. * The name of the protocol
  481. * @return Returns the default port number, if the protocol is implemented.
  482. * Else returns -1.
  483. */
  484. private int getDefaultPort(String protocolName) {
  485. for (Protocol protocol : implementedProtocols) {
  486. if (protocolName.equals(protocol.toString())) {
  487. return protocol.getPort();
  488. }
  489. }
  490. return -1;
  491. };
  492. /**
  493. * Returns an LinkedList<String> with the names of all implemented
  494. * protocols.
  495. *
  496. * @return ArrayList of
  497. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  498. * Protocol}
  499. */
  500. private LinkedList<Protocol> getImplementedProtocols() {
  501. String[] protocols = getResources().getStringArray(R.array.protocols);
  502. String packageName = Protocol.class.getPackage().getName();
  503. LinkedList<Protocol> implementedProtocols = new LinkedList<Protocol>();
  504. for (String protocol : protocols) {
  505. try {
  506. implementedProtocols.add((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance());
  507. } catch (Exception e) {
  508. e.printStackTrace();
  509. }
  510. }
  511. return implementedProtocols;
  512. }
  513. /**
  514. * Starts an Instance of MyLocationManager to set the location within this
  515. * class.
  516. */
  517. private void getLocationData() {
  518. MyLocationManager locationManager = new MyLocationManager(this);
  519. locationManager.getUpdates(60 * 1000, 3);
  520. };
  521. // Notifications
  522. /**
  523. * Register broadcast receiver for connectivity changes
  524. */
  525. private void registerNetReceiver() {
  526. // register BroadcastReceiver on network state changes
  527. IntentFilter intent = new IntentFilter();
  528. intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
  529. registerReceiver(netReceiver, intent);
  530. }
  531. /**
  532. * Unregister broadcast receiver for connectivity changes
  533. */
  534. private void unregisterNetReceiver() {
  535. unregisterReceiver(netReceiver);
  536. }
  537. public boolean hasProtocolActiveAttacks(String protocol){
  538. if(!mProtocolActiveAttacks.containsKey(protocol)) return false;
  539. return mProtocolActiveAttacks.get(protocol);
  540. }
  541. public boolean hasActiveAttacks(){
  542. for(boolean b: mProtocolActiveAttacks.values()){
  543. if(b) return true;
  544. }
  545. return false;
  546. }
  547. /**
  548. * Updates the connection info and saves them in the the SharedPreferences
  549. * for session data.
  550. *
  551. * @param context
  552. * Needs a context to get system recourses.
  553. * @see MainActivity#CONNECTION_INFO
  554. */
  555. private void updateConnectionInfo() {
  556. SharedPreferences pref = context.getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
  557. Editor editor = pref.edit();
  558. editor.putString(getString(R.string.connection_info_ssid), HelperUtils.getSSID(context));
  559. editor.putString(getString(R.string.connection_info_bssid), HelperUtils.getBSSID(context));
  560. editor.putString(getString(R.string.connection_info_internal_ip), HelperUtils.getInternalIP(context));
  561. editor.commit();
  562. SetExternalIPTask async = new SetExternalIPTask();
  563. async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
  564. this.mProtocolActiveAttacks.clear();
  565. }
  566. }