Hostage.java 19 KB

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