HoneyService.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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.Protocol;
  41. import de.tudarmstadt.informatik.hostage.protocol.ProtocolSettings;
  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. new QotdTask().execute(new String[] {});
  93. }
  94. @Override
  95. public int onStartCommand(Intent intent, int flags, int startId) {
  96. // We want this service to continue running until it is explicitly
  97. // stopped, so return sticky.
  98. return START_STICKY;
  99. }
  100. @Override
  101. public void onDestroy() {
  102. cancelNotification();
  103. unregisterNetReceiver();
  104. super.onDestroy();
  105. }
  106. /**
  107. * Starts an Instance of MyLocationManager to set the location within this
  108. * class.
  109. */
  110. private void getLocationData() {
  111. // TODO Put time and attempts in settings
  112. MyLocationManager locationManager = new MyLocationManager(this);
  113. locationManager.getUpdates(60 * 1000, 3);
  114. }
  115. /**
  116. * Deletes all session related data.
  117. */
  118. private void deleteConnectionData() {
  119. connectionInfoEditor.clear();
  120. connectionInfoEditor.commit();
  121. }
  122. /**
  123. * Register broadcast receiver for connectivity changes
  124. */
  125. private void registerNetReceiver() {
  126. // register BroadcastReceiver on network state changes
  127. IntentFilter intent = new IntentFilter();
  128. intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
  129. registerReceiver(netReceiver, intent);
  130. }
  131. /**
  132. * Unregister broadcast receiver for connectivity changes
  133. */
  134. private void unregisterNetReceiver() {
  135. unregisterReceiver(netReceiver);
  136. }
  137. /**
  138. * Receiver for connectivity change broadcast.
  139. *
  140. * @see MainActivity#BROADCAST
  141. */
  142. private BroadcastReceiver netReceiver = new BroadcastReceiver() {
  143. @Override
  144. public void onReceive(Context context, Intent intent) {
  145. String bssid_old = connectionInfo.getString(MainActivity.BSSID, "");
  146. String bssid_new = HelperUtils.getBSSID(context);
  147. if (bssid_new == null || !bssid_new.equals(bssid_old)) {
  148. deleteConnectionData();
  149. updateConnectionInfo();
  150. getLocationData();
  151. notifyUI(this.getClass().getName(), "CONNECTIVITY_CHANGE");
  152. }
  153. }
  154. };
  155. /**
  156. * Notifies the GUI about a event.
  157. *
  158. * @param protocol
  159. * The protocol where the event happened.
  160. * @param key
  161. * The key for the event.
  162. */
  163. public void notifyUI(String sender, String key) {
  164. // Send Notification
  165. if (key.equals(MainActivity.HANDLER_COUNT)) {
  166. updateNotification();
  167. }
  168. Log.i("HoneyService", sender + key);
  169. // Inform UI of Preference Change
  170. Intent intent = new Intent(MainActivity.BROADCAST);
  171. intent.putExtra("SENDER", sender);
  172. intent.putExtra("KEY", key);
  173. LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
  174. }
  175. /**
  176. * Returns an LinkedList<String> with the names of all implemented protocols.
  177. *
  178. * @return ArrayList of
  179. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  180. * Protocol}
  181. */
  182. private LinkedList<Protocol> getImplementedProtocols() {
  183. String[] protocols = getResources().getStringArray(R.array.protocols);
  184. String packageName = Protocol.class.getPackage().getName();
  185. LinkedList<Protocol> implementedProtocols = new LinkedList<Protocol>();
  186. for (String protocol : protocols) {
  187. try {
  188. implementedProtocols.add((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance());
  189. } catch (Exception e) {
  190. e.printStackTrace();
  191. }
  192. }
  193. return implementedProtocols;
  194. }
  195. /**
  196. * Returns the default port number, if the protocol is implemented.
  197. * @param protocolName The name of the protocol
  198. * @return Returns the default port number, if the protocol is implemented. Else returns -1.
  199. */
  200. private int getDefaultPort(String protocolName){
  201. for (Protocol protocol : implementedProtocols) {
  202. if(protocolName.equals(protocol.toString())){
  203. return protocol.getPort();
  204. }
  205. }
  206. return -1;
  207. }
  208. /**
  209. * Determines if there are running listeners.
  210. *
  211. * @return True if there is a running listener, else false.
  212. */
  213. public boolean hasRunningListeners() {
  214. for (HoneyListener listener : listeners) {
  215. if (listener.isRunning())
  216. return true;
  217. }
  218. return false;
  219. }
  220. /**
  221. * Determines if a protocol with the given name is running on its default port.
  222. * @param protocolName The protocol name
  223. * @return True if protocol is running, else false.
  224. */
  225. public boolean isRunning(String protocolName){
  226. int port = getDefaultPort(protocolName);
  227. if(port >= 0) return isRunning(protocolName, port);
  228. return false;
  229. }
  230. /**
  231. * Determines if a protocol with the given name is running on the given port.
  232. * @param protocolName The protocol name
  233. * @param port Specific port
  234. * @return True if protocol is running, else false.
  235. */
  236. public boolean isRunning(String protocolName, int port){
  237. for (HoneyListener listener : listeners) {
  238. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  239. return listener.isRunning();
  240. }
  241. }
  242. return false;
  243. }
  244. /**
  245. * Determines the number of active connections for a protocol running on its default port.
  246. * @param protocolName The protocol name
  247. * @return Number of active connections if protocol is implemented, else -1.
  248. */
  249. public int getHandlerCount(String protocolName){
  250. int port = getDefaultPort(protocolName);
  251. if(port >= 0) return getHandlerCount(protocolName, port);
  252. return -1;
  253. }
  254. /**
  255. * Determines the number of active connections for a protocol running on the given port.
  256. * @param protocolName The protocol name
  257. * @param port Specific port
  258. * @return Number of active connections if protocol is implemented, else -1.
  259. */
  260. public int getHandlerCount(String protocolName, int port){
  261. for (HoneyListener listener : listeners) {
  262. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  263. return listener.getHandlerCount();
  264. }
  265. }
  266. return -1;
  267. }
  268. /**
  269. * Creates a Listener for a given protocol on a specific port.
  270. * After creation the Listener is not started.
  271. * Checks if the protocol is implemented first.
  272. *
  273. * @param protocolName Name of the protocol
  274. * @param port Port on which to start the Listener
  275. * @return Returns the created HoneyListener, if creation failed returns null.
  276. */
  277. private HoneyListener createListener(String protocolName, int port){
  278. for(Protocol protocol : implementedProtocols){
  279. if(protocolName.equals(protocol.toString())){
  280. HoneyListener listener = new HoneyListener(this, protocol, port);
  281. listeners.add(listener);
  282. return listener;
  283. }
  284. }
  285. return null;
  286. }
  287. /**
  288. * Starts all listeners which are not already running.
  289. */
  290. public void startListeners() {
  291. for (HoneyListener listener : listeners) {
  292. if (!listener.isRunning()) {
  293. listener.start();
  294. }
  295. }
  296. Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
  297. Toast.LENGTH_SHORT).show();
  298. }
  299. /**
  300. * Stops all running listeners.
  301. */
  302. public void stopListeners() {
  303. for (HoneyListener listener : listeners) {
  304. if (listener.isRunning()) {
  305. listener.stop();
  306. }
  307. }
  308. Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
  309. Toast.LENGTH_SHORT).show();
  310. }
  311. /**
  312. * Starts the listener for the specified protocol.
  313. * Creates a new HoneyService if no matching HoneyListener is found.
  314. *
  315. * @param protocolName
  316. * Name of the protocol that should be started.
  317. */
  318. public boolean startListener(String protocolName) {
  319. int port = getDefaultPort(protocolName);
  320. if(port >= 0) return startListener(protocolName, port);
  321. return false;
  322. }
  323. /**
  324. * Starts the listener for the specified protocol and port.
  325. * Creates a new HoneyService if no matching HoneyListener is found.
  326. *
  327. * @param protocolName
  328. * Name of the protocol that should be started.
  329. * @param port The port number in which the listener should run.
  330. */
  331. public boolean startListener(String protocolName, int port) {
  332. for (HoneyListener listener : listeners) {
  333. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  334. if (!listener.isRunning()) {
  335. if(listener.start()){
  336. Toast.makeText(getApplicationContext(),protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  337. return true;
  338. }
  339. Toast.makeText(getApplicationContext(),protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  340. return false;
  341. }
  342. }
  343. }
  344. HoneyListener listener = createListener(protocolName, port);
  345. if(listener != null){
  346. if(listener.start()){
  347. Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  348. return true;
  349. }
  350. }
  351. Toast.makeText(getApplicationContext(),protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  352. return false;
  353. }
  354. /**
  355. * Stops the listener for the specified protocol.
  356. *
  357. * @param protocolName
  358. * Name of the protocol that should be stopped.
  359. */
  360. public void stopListener(String protocolName) {
  361. int port = getDefaultPort(protocolName);
  362. if(port >= 0) stopListener(protocolName, port);
  363. }
  364. /**
  365. * Stops the listener for the specified protocol.
  366. *
  367. * @param protocolName
  368. * Name of the protocol that should be stopped.
  369. * @param port The port number in which the listener is running.
  370. */
  371. public void stopListener(String protocolName, int port) {
  372. for (HoneyListener listener : listeners) {
  373. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  374. if (listener.isRunning()) {
  375. listener.stop();
  376. }
  377. }
  378. }
  379. Toast.makeText(getApplicationContext(), protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
  380. }
  381. /**
  382. * Task for acquiring a qotd from one of four possible servers.
  383. *
  384. * @author Wulf Pfeiffer
  385. */
  386. private class QotdTask extends AsyncTask<String, Void, String> {
  387. @Override
  388. protected String doInBackground(String... unused) {
  389. String[] sources = new String[] { "djxmmx.net", "ota.iambic.com",
  390. "alpha.mike-r.com", "electricbiscuit.org" };
  391. SecureRandom rndm = new SecureRandom();
  392. StringBuffer sb = new StringBuffer();
  393. try {
  394. Socket client = new Socket(sources[rndm.nextInt(4)], 17);
  395. BufferedReader in = new BufferedReader(new InputStreamReader(
  396. client.getInputStream()));
  397. while (!in.ready())
  398. ;
  399. while (in.ready()) {
  400. sb.append(in.readLine());
  401. }
  402. in.close();
  403. client.close();
  404. } catch (Exception e) {
  405. e.printStackTrace();
  406. }
  407. return sb.toString();
  408. }
  409. @Override
  410. protected void onPostExecute(String result) {
  411. if (result != null)
  412. ProtocolSettings.setHttpQotd(result);
  413. else
  414. ProtocolSettings.setHttpQotd(new String(HelperUtils
  415. .getRandomString(100, false)));
  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. }