HoneyService.java 18 KB

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