Hostage.java 18 KB

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