Hostage.java 19 KB

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