HoneyService.java 18 KB

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