HoneyService.java 18 KB

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