HoneyService.java 19 KB

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