Hostage.java 18 KB

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