Hostage.java 19 KB

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