HoneyService.java 18 KB

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