Hostage.java 19 KB

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