Hostage.java 18 KB

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