HoneyService.java 20 KB

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