HoneyService.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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(getString(R.string.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. 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(getString(R.string.connection_info_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(), new String[]{getString(R.string.broadcast_connectivity)});
  154. }
  155. }
  156. };
  157. /**
  158. * Notifies the GUI about a event.
  159. *
  160. * @param sender
  161. * Source where the event took place.
  162. * @param key
  163. * Detailed information about the event.
  164. */
  165. public void notifyUI(String sender, String[] values) {
  166. createNotification();
  167. // Send Notification
  168. if (sender.equals(HoneyHandler.class.getName()) && values[0].equals(R.string.broadcast_started)) {
  169. attackNotification();
  170. }
  171. // Inform UI of Preference Change
  172. Intent intent = new Intent(getString(R.string.broadcast));
  173. intent.putExtra("SENDER", sender);
  174. intent.putExtra("VALUES", values);
  175. Log.i("Sender" ,sender);
  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 any listener is currently running.
  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. return isRunning(protocolName, port);
  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
  250. */
  251. public int getNumberOfActiveConnections(String protocolName){
  252. int port = getDefaultPort(protocolName);
  253. return getNumberOfActiveConnections(protocolName, port);
  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
  260. */
  261. public int getNumberOfActiveConnections(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 0;
  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. return startListener(protocolName, getDefaultPort(protocolName));
  321. }
  322. /**
  323. * Starts the listener for the specified protocol and port.
  324. * Creates a new HoneyService if no matching HoneyListener is found.
  325. *
  326. * @param protocolName
  327. * Name of the protocol that should be started.
  328. * @param port The port number in which the listener should run.
  329. */
  330. public boolean startListener(String protocolName, int port) {
  331. for (HoneyListener listener : listeners) {
  332. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  333. if (!listener.isRunning()) {
  334. if(listener.start()){
  335. Toast.makeText(getApplicationContext(),protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  336. return true;
  337. }
  338. Toast.makeText(getApplicationContext(),protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  339. return false;
  340. }
  341. }
  342. }
  343. HoneyListener listener = createListener(protocolName, port);
  344. if(listener != null){
  345. if(listener.start()){
  346. Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
  347. return true;
  348. }
  349. }
  350. Toast.makeText(getApplicationContext(),protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
  351. return false;
  352. }
  353. /**
  354. * Stops the listener for the specified protocol.
  355. *
  356. * @param protocolName
  357. * Name of the protocol that should be stopped.
  358. */
  359. public void stopListener(String protocolName) {
  360. stopListener(protocolName, getDefaultPort(protocolName));
  361. }
  362. /**
  363. * Stops the listener for the specified protocol.
  364. *
  365. * @param protocolName
  366. * Name of the protocol that should be stopped.
  367. * @param port The port number in which the listener is running.
  368. */
  369. public void stopListener(String protocolName, int port) {
  370. for (HoneyListener listener : listeners) {
  371. if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
  372. if (listener.isRunning()) {
  373. listener.stop();
  374. }
  375. }
  376. }
  377. Toast.makeText(getApplicationContext(), protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
  378. }
  379. /**
  380. * Task for accuiring a qotd from one of four possible servers.
  381. *
  382. * @author Wulf Pfeiffer
  383. */
  384. private class QotdTask extends AsyncTask<String, Void, String> {
  385. @Override
  386. protected String doInBackground(String... unused) {
  387. String[] sources = new String[] { "djxmmx.net", "ota.iambic.com",
  388. "alpha.mike-r.com", "electricbiscuit.org" };
  389. SecureRandom rndm = new SecureRandom();
  390. StringBuffer sb = new StringBuffer();
  391. try {
  392. Socket client = new Socket(sources[rndm.nextInt(4)], 17);
  393. BufferedReader in = new BufferedReader(new InputStreamReader(
  394. client.getInputStream()));
  395. while (!in.ready())
  396. ;
  397. while (in.ready()) {
  398. sb.append(in.readLine());
  399. }
  400. in.close();
  401. client.close();
  402. } catch (Exception e) {
  403. e.printStackTrace();
  404. }
  405. return sb.toString();
  406. }
  407. @Override
  408. protected void onPostExecute(String result) {
  409. if (result != null)
  410. HTTP.setHtmlDocumentContent(result);
  411. }
  412. };
  413. /**
  414. * Updates the connection info and saves them in the the SharedPreferences
  415. * for session data.
  416. *
  417. * @param context
  418. * Needs a context to get system recourses.
  419. * @see MainActivity#CONNECTION_INFO
  420. */
  421. private void updateConnectionInfo() {
  422. SharedPreferences pref = context.getSharedPreferences(
  423. getString(R.string.connection_info), Context.MODE_PRIVATE);
  424. Editor editor = pref.edit();
  425. editor.putString(getString(R.string.connection_info_ssid), HelperUtils.getSSID(context));
  426. editor.putString(getString(R.string.connection_info_bssid), HelperUtils.getBSSID(context));
  427. editor.putString(getString(R.string.connection_info_internal_ip),
  428. HelperUtils.getInternalIP(context));
  429. editor.commit();
  430. SetExternalIPTask async = new SetExternalIPTask();
  431. async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
  432. }
  433. /**
  434. * Task to find out the external IP.
  435. *
  436. * @author Lars Pandikow
  437. */
  438. private class SetExternalIPTask extends AsyncTask<String, Void, String> {
  439. @Override
  440. protected String doInBackground(String... url) {
  441. String ipAddress = null;
  442. try {
  443. HttpClient httpclient = new DefaultHttpClient();
  444. HttpGet httpget = new HttpGet(url[0]);
  445. HttpResponse response;
  446. response = httpclient.execute(httpget);
  447. HttpEntity entity = response.getEntity();
  448. entity.getContentLength();
  449. String str = EntityUtils.toString(entity);
  450. JSONObject json_data = new JSONObject(str);
  451. ipAddress = json_data.getString("ip");
  452. } catch (Exception e) {
  453. e.printStackTrace();
  454. }
  455. return ipAddress;
  456. }
  457. @Override
  458. protected void onPostExecute(String result) {
  459. connectionInfoEditor.putString(getString(R.string.connection_info_external_ip), result);
  460. connectionInfoEditor.commit();
  461. notifyUI(this.getClass().getName(), new String[]{getString(R.string.broadcast_connectivity)});
  462. }
  463. };
  464. // Notifications
  465. /**
  466. * Creates a Notification in the notification bar.
  467. */
  468. private void createNotification() {
  469. UglyDbHelper dbh = new UglyDbHelper(this);
  470. boolean activeHandlers = false;
  471. boolean bssidSeen = false;
  472. boolean listening = false;
  473. for (HoneyListener listener : listeners) {
  474. if(listener.isRunning())
  475. listening = true;
  476. if (listener.getHandlerCount() > 0) {
  477. activeHandlers = true;
  478. }
  479. if (dbh.bssidSeen(listener.getProtocolName(), HelperUtils.getBSSID(getApplicationContext()))) {
  480. bssidSeen = true;
  481. }
  482. }
  483. builder = new NotificationCompat.Builder(this).setContentTitle(
  484. getString(R.string.app_name)).setWhen(
  485. System.currentTimeMillis());
  486. if(!listening){
  487. builder.setSmallIcon(R.drawable.ic_launcher);
  488. builder.setContentText("HosTaGe is not active.");
  489. } else 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. builder.setOngoing(true);
  506. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  507. mNotificationManager.notify(1, builder.build());
  508. }
  509. /**
  510. * Updates the notification when a attack is registered.
  511. */
  512. private void attackNotification() {
  513. SharedPreferences defaultPref = PreferenceManager
  514. .getDefaultSharedPreferences(this);
  515. String strRingtonePreference = defaultPref.getString(
  516. "pref_notification_sound",
  517. "content://settings/system/notification_sound");
  518. builder = new NotificationCompat.Builder(this)
  519. .setContentTitle(getString(R.string.app_name))
  520. .setTicker("Honeypot under attack!")
  521. .setContentText("Honeypot under attack!")
  522. .setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true)
  523. .setWhen(System.currentTimeMillis())
  524. .setSound(Uri.parse(strRingtonePreference));
  525. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  526. stackBuilder.addParentStack(MainActivity.class);
  527. stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
  528. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
  529. PendingIntent.FLAG_UPDATE_CURRENT);
  530. builder.setContentIntent(resultPendingIntent);
  531. if (defaultPref.getBoolean("pref_vibration", false)) {
  532. builder.setVibrate(new long[] { 100, 200, 100, 200 });
  533. }
  534. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  535. mNotificationManager.notify(2, builder.build());
  536. }
  537. /**
  538. * Cancels the Notification
  539. */
  540. private void cancelNotification() {
  541. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  542. mNotificationManager.cancel(1);
  543. }
  544. }