Hostage.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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.ui2.activity.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
  315. // + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  316. return true;
  317. }
  318. Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  319. return false;
  320. }
  321. }
  322. }
  323. Listener listener = createListener(protocolName, port);
  324. if (listener != null) {
  325. if (listener.start()) {
  326. // Toast.makeText(getApplicationContext(), protocolName +
  327. // " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  328. return true;
  329. }
  330. }
  331. Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  332. return false;
  333. }
  334. /**
  335. * Starts all listeners which are not already running.
  336. */
  337. public void startListeners() {
  338. for (Listener listener : listeners) {
  339. if (!listener.isRunning()) {
  340. listener.start();
  341. }
  342. }
  343. // Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
  344. // Toast.LENGTH_SHORT).show();
  345. }
  346. /**
  347. * Stops the listener for the specified protocol.
  348. *
  349. * @param protocolName
  350. * Name of the protocol that should be stopped.
  351. */
  352. public void stopListener(String protocolName) {
  353. stopListener(protocolName, getDefaultPort(protocolName));
  354. }
  355. /**
  356. * Stops the listener for the specified protocol.
  357. *
  358. * @param protocolName
  359. * Name of the protocol that should be stopped.
  360. * @param port
  361. * The port number in which the listener is running.
  362. */
  363. public void stopListener(String protocolName, int port) {
  364. for (Listener listener : listeners) {
  365. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  366. if (listener.isRunning()) {
  367. listener.stop();
  368. }
  369. }
  370. }
  371. // Toast.makeText(getApplicationContext(), protocolName +
  372. // " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
  373. }
  374. /**
  375. * Stops all running listeners.
  376. */
  377. public void stopListeners() {
  378. for (Listener listener : listeners) {
  379. if (listener.isRunning()) {
  380. listener.stop();
  381. }
  382. }
  383. // Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
  384. // Toast.LENGTH_SHORT).show();
  385. }
  386. /**
  387. * Updates the notification when a attack is registered.
  388. */
  389. private void attackNotification() {
  390. SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(this);
  391. String strRingtonePreference = defaultPref.getString("pref_notification_sound", "content://settings/system/notification_sound");
  392. builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setTicker("Honeypot under attack!")
  393. .setContentText("Honeypot under attack!").setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true).setWhen(System.currentTimeMillis())
  394. .setSound(Uri.parse(strRingtonePreference));
  395. Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
  396. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  397. stackBuilder.addParentStack(MainActivity.class);
  398. stackBuilder.addNextIntent(launchIntent);
  399. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
  400. builder.setContentIntent(resultPendingIntent);
  401. if (defaultPref.getBoolean("pref_vibration", false)) {
  402. builder.setVibrate(new long[] { 100, 200, 100, 200 });
  403. }
  404. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  405. mNotificationManager.notify(1, builder.build());
  406. }
  407. /**
  408. * Cancels the Notification
  409. */
  410. private void cancelNotification() {
  411. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  412. mNotificationManager.cancel(1);
  413. }
  414. /**
  415. * Creates a HoneyListener for a given protocol on a specific port. After
  416. * creation the HoneyListener is not started. Checks if the protocol is
  417. * implemented first.
  418. *
  419. * @param protocolName
  420. * Name of the protocol
  421. * @param port
  422. * Port on which to start the HoneyListener
  423. * @return Returns the created HoneyListener, if creation failed returns
  424. * null.
  425. */
  426. private Listener createListener(String protocolName, int port) {
  427. for (Protocol protocol : implementedProtocols) {
  428. if (protocolName.equals(protocol.toString())) {
  429. Listener listener = new Listener(this, protocol, port);
  430. listeners.add(listener);
  431. return listener;
  432. }
  433. }
  434. return null;
  435. }
  436. /**
  437. * Creates a Notification in the notification bar.
  438. */
  439. private void createNotification() {
  440. HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
  441. boolean activeHandlers = false;
  442. boolean bssidSeen = false;
  443. boolean listening = false;
  444. for (Listener listener : listeners) {
  445. if (listener.isRunning())
  446. listening = true;
  447. if (listener.getHandlerCount() > 0) {
  448. activeHandlers = true;
  449. }
  450. if (dbh.bssidSeen(listener.getProtocolName(), HelperUtils.getBSSID(getApplicationContext()))) {
  451. bssidSeen = true;
  452. }
  453. }
  454. builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setWhen(System.currentTimeMillis());
  455. if (!listening) {
  456. builder.setSmallIcon(R.drawable.ic_launcher);
  457. builder.setContentText("HosTaGe is not active.");
  458. } else if (activeHandlers) {
  459. builder.setSmallIcon(R.drawable.ic_service_red);
  460. builder.setContentText("Network is infected!");
  461. } else if (bssidSeen) {
  462. builder.setSmallIcon(R.drawable.ic_service_yellow);
  463. builder.setContentText("Network has been infected in previous session!");
  464. } else {
  465. builder.setSmallIcon(R.drawable.ic_service_green);
  466. builder.setContentText("Everything looks fine!");
  467. }
  468. Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
  469. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  470. stackBuilder.addParentStack(MainActivity.class);
  471. stackBuilder.addNextIntent(launchIntent);
  472. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
  473. builder.setContentIntent(resultPendingIntent);
  474. builder.setOngoing(true);
  475. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  476. mNotificationManager.notify(1, builder.build());
  477. }
  478. /**
  479. * Deletes all session related data.
  480. */
  481. private void deleteConnectionData() {
  482. connectionInfoEditor.clear();
  483. connectionInfoEditor.commit();
  484. }
  485. /**
  486. * Returns the default port number, if the protocol is implemented.
  487. *
  488. * @param protocolName
  489. * The name of the protocol
  490. * @return Returns the default port number, if the protocol is implemented.
  491. * Else returns -1.
  492. */
  493. private int getDefaultPort(String protocolName) {
  494. for (Protocol protocol : implementedProtocols) {
  495. if (protocolName.equals(protocol.toString())) {
  496. return protocol.getPort();
  497. }
  498. }
  499. return -1;
  500. };
  501. /**
  502. * Returns an LinkedList<String> with the names of all implemented
  503. * protocols.
  504. *
  505. * @return ArrayList of
  506. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  507. * Protocol}
  508. */
  509. private LinkedList<Protocol> getImplementedProtocols() {
  510. String[] protocols = getResources().getStringArray(R.array.protocols);
  511. String packageName = Protocol.class.getPackage().getName();
  512. LinkedList<Protocol> implementedProtocols = new LinkedList<Protocol>();
  513. for (String protocol : protocols) {
  514. try {
  515. implementedProtocols.add((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance());
  516. } catch (Exception e) {
  517. e.printStackTrace();
  518. }
  519. }
  520. return implementedProtocols;
  521. }
  522. /**
  523. * Starts an Instance of MyLocationManager to set the location within this
  524. * class.
  525. */
  526. private void getLocationData() {
  527. MyLocationManager locationManager = new MyLocationManager(this);
  528. locationManager.getUpdates(60 * 1000, 3);
  529. };
  530. // Notifications
  531. /**
  532. * Register broadcast receiver for connectivity changes
  533. */
  534. private void registerNetReceiver() {
  535. // register BroadcastReceiver on network state changes
  536. IntentFilter intent = new IntentFilter();
  537. intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
  538. registerReceiver(netReceiver, intent);
  539. }
  540. /**
  541. * Unregister broadcast receiver for connectivity changes
  542. */
  543. private void unregisterNetReceiver() {
  544. unregisterReceiver(netReceiver);
  545. }
  546. /**
  547. * Updates the connection info and saves them in the the SharedPreferences
  548. * for session data.
  549. *
  550. * @param context
  551. * Needs a context to get system recourses.
  552. * @see MainActivity#CONNECTION_INFO
  553. */
  554. private void updateConnectionInfo() {
  555. SharedPreferences pref = context.getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
  556. Editor editor = pref.edit();
  557. editor.putString(getString(R.string.connection_info_ssid), HelperUtils.getSSID(context));
  558. editor.putString(getString(R.string.connection_info_bssid), HelperUtils.getBSSID(context));
  559. editor.putString(getString(R.string.connection_info_internal_ip), HelperUtils.getInternalIP(context));
  560. editor.commit();
  561. SetExternalIPTask async = new SetExternalIPTask();
  562. async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
  563. }
  564. }