Hostage.java 19 KB

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