ThreatMapFragment.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package de.tudarmstadt.informatik.hostage.ui2.fragment;
  2. import static com.google.android.gms.common.GooglePlayServicesUtil.getErrorDialog;
  3. import static com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.Map;
  8. import android.app.Activity;
  9. import android.app.AlertDialog;
  10. import android.app.Fragment;
  11. import android.app.FragmentManager;
  12. import android.content.DialogInterface;
  13. import android.graphics.Color;
  14. import android.location.Location;
  15. import android.os.Bundle;
  16. import android.view.InflateException;
  17. import android.view.LayoutInflater;
  18. import android.view.View;
  19. import android.view.ViewGroup;
  20. import android.widget.TextView;
  21. import com.google.android.gms.common.ConnectionResult;
  22. import com.google.android.gms.common.GooglePlayServicesClient;
  23. import com.google.android.gms.location.LocationClient;
  24. import com.google.android.gms.location.LocationListener;
  25. import com.google.android.gms.location.LocationRequest;
  26. import com.google.android.gms.maps.CameraUpdateFactory;
  27. import com.google.android.gms.maps.GoogleMap;
  28. import com.google.android.gms.maps.MapFragment;
  29. import com.google.android.gms.maps.model.BitmapDescriptor;
  30. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
  31. import com.google.android.gms.maps.model.CircleOptions;
  32. import com.google.android.gms.maps.model.LatLng;
  33. import com.google.android.gms.maps.model.Marker;
  34. import com.google.android.gms.maps.model.MarkerOptions;
  35. import de.tudarmstadt.informatik.hostage.R;
  36. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  37. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  38. import de.tudarmstadt.informatik.hostage.logging.Record;
  39. import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
  40. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  41. import de.tudarmstadt.informatik.hostage.ui.LogFilter;
  42. import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
  43. /**
  44. * ThreatMapFragment
  45. *
  46. * Created by Fabio Arnold on 10.02.14.
  47. */
  48. public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindowClickListener,
  49. GooglePlayServicesClient.ConnectionCallbacks,
  50. GooglePlayServicesClient.OnConnectionFailedListener,
  51. LocationListener {
  52. private static GoogleMap sMap = null;
  53. private static View sView = null;
  54. private static HashMap<String, String> sMarkerIDToSSID = new HashMap<String, String>();
  55. private LocationClient mLocationClient;
  56. private static final LocationRequest REQUEST = LocationRequest.create()
  57. .setExpirationDuration(5000) // 5 seconds
  58. .setInterval(5000) // 5 seconds
  59. .setFastestInterval(16) // 16ms = 60fps
  60. .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  61. /**
  62. * if google play services aren't available an error notification will be displayed
  63. *
  64. * @return true if the google play services are available
  65. */
  66. private boolean isGooglePlay() {
  67. int status = isGooglePlayServicesAvailable(getActivity());
  68. boolean result = status == ConnectionResult.SUCCESS;
  69. if (!result) {
  70. getErrorDialog(status, getActivity(), 10).show();
  71. }
  72. return result;
  73. }
  74. /**
  75. * callback for when the info window of a marker gets clicked
  76. * open the RecordOverviewFragment and display all records belonging to an SSID
  77. *
  78. * @param marker this info window belongs to
  79. */
  80. @Override
  81. public void onInfoWindowClick(Marker marker) {
  82. //MainActivity.getInstance().displayView(MainActivity.MainMenuItem.RECORDS.getValue());
  83. //RecordOverviewFragment recordOverviewFragment = (RecordOverviewFragment)MainActivity.getInstance().getCurrentFragment();
  84. //if (recordOverviewFragment != null) {
  85. String ssid = sMarkerIDToSSID.get(marker.getId());
  86. ArrayList<String> ssids = new ArrayList<String>();
  87. ssids.add(ssid);
  88. LogFilter filter = new LogFilter();
  89. filter.setESSIDs(ssids);
  90. RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
  91. recordOverviewFragment.setFilter(filter);
  92. recordOverviewFragment.setGroupKey("ESSID");
  93. MainActivity.getInstance().injectFragment(recordOverviewFragment, false);
  94. //recordOverviewFragment.showDetailsForSSID(getActivity(), ssid);
  95. //}
  96. }
  97. /**
  98. * callbacks from LocationClient
  99. */
  100. @Override
  101. public void onConnected(Bundle bundle) {
  102. mLocationClient.requestLocationUpdates(REQUEST, this);
  103. }
  104. @Override
  105. public void onDisconnected() {
  106. }
  107. @Override
  108. public void onConnectionFailed(ConnectionResult connectionResult) {
  109. }
  110. @Override
  111. public void onLocationChanged(Location location) {
  112. sMap.animateCamera(CameraUpdateFactory.newLatLng(
  113. new LatLng(location.getLatitude(), location.getLongitude())));
  114. }
  115. /**
  116. * helper class
  117. * easier to use than LatLng
  118. */
  119. private class Point {
  120. public double x, y;
  121. public Point(double sx, double sy) {
  122. x = sx;
  123. y = sy;
  124. }
  125. }
  126. /**
  127. * helper class
  128. * contains heuristic to split SSIDs by location
  129. * see MAX_DISTANCE
  130. */
  131. private class SSIDArea {
  132. public long numAttacks;
  133. public long numPortscans;
  134. Point mMinimum;
  135. Point mMaximum;
  136. public static final int MAX_NUM_ATTACKS = 20;
  137. public static final float MAX_DISTANCE = 1000.0f; // 1km
  138. public SSIDArea(LatLng initLocation, long attacks, long portscans) {
  139. mMinimum = new Point(initLocation.latitude, initLocation.longitude);
  140. mMaximum = new Point(initLocation.latitude, initLocation.longitude);
  141. numAttacks = attacks;
  142. numPortscans = portscans;
  143. }
  144. public boolean doesLocationBelongToArea(LatLng location) {
  145. LatLng center = calculateCenterLocation();
  146. float[] result = new float[1];
  147. Location.distanceBetween(center.latitude, center.longitude, location.latitude, location.longitude, result);
  148. return result[0] < MAX_DISTANCE;
  149. }
  150. public LatLng calculateCenterLocation() {
  151. return new LatLng(0.5 * (mMinimum.x + mMaximum.x), 0.5 * (mMinimum.y + mMaximum.y));
  152. }
  153. public void addLocation(LatLng location, long attacks, long portscans) {
  154. Point point = new Point(location.latitude, location.longitude);
  155. if (point.x < mMinimum.x) mMinimum.x = point.x;
  156. if (point.x > mMaximum.x) mMaximum.x = point.x;
  157. if (point.y < mMinimum.y) mMinimum.y = point.y;
  158. if (point.y > mMaximum.y) mMaximum.y = point.y;
  159. numAttacks += attacks;
  160. numPortscans += portscans;
  161. }
  162. public float calculateRadius() {
  163. float[] result = new float[1];
  164. Location.distanceBetween(mMinimum.x, mMinimum.y, mMaximum.x, mMaximum.y, result);
  165. return 0.5f * result[0];
  166. }
  167. public int calculateColor() {
  168. long threatLevel = numAttacks;
  169. if (threatLevel > MAX_NUM_ATTACKS) threatLevel = MAX_NUM_ATTACKS;
  170. float alpha = 1.0f - (float)(threatLevel-1) / (float)(MAX_NUM_ATTACKS-1);
  171. return Color.argb(127, (int) (240.0 + 15.0 * alpha), (int) (80.0 + 175.0 * alpha), 60);
  172. }
  173. }
  174. /**
  175. * fills the map with markers and circle representing SSIDs
  176. */
  177. private void populateMap() {
  178. HostageDBOpenHelper dbh = new HostageDBOpenHelper(getActivity());
  179. ArrayList<NetworkRecord> netRecords = dbh.getNetworkInformation();
  180. ArrayList<SyncInfoRecord> syncRecords = dbh.getSyncInfo();
  181. HashMap<String, ArrayList<SSIDArea>> threadAreas = new HashMap<String, ArrayList<SSIDArea>>();
  182. for (NetworkRecord netRecord : netRecords) {
  183. LatLng location = new LatLng(netRecord.getLatitude(), netRecord.getLongitude());
  184. long number_of_attack = 0;
  185. long number_of_portscans = 0;
  186. for ( Iterator<SyncInfoRecord> i = syncRecords.iterator(); i.hasNext(); ){
  187. SyncInfoRecord info = i.next();
  188. if(info.getBSSID().equals(netRecord.getBssid())){
  189. number_of_attack += info.getNumber_of_attacks();
  190. number_of_portscans += info.getNumber_of_portscans();
  191. i.remove();
  192. }
  193. }
  194. ArrayList<SSIDArea> areas;
  195. if (threadAreas.containsKey(netRecord.getSsid())) {
  196. areas = threadAreas.get(netRecord.getSsid());
  197. boolean foundArea = false;
  198. for (SSIDArea area : areas) {
  199. if (area.doesLocationBelongToArea(location)) {
  200. area.addLocation(location, number_of_attack, number_of_portscans);
  201. foundArea = true;
  202. break;
  203. }
  204. }
  205. if (!foundArea) {
  206. areas.add(new SSIDArea(location, number_of_attack, number_of_portscans));
  207. }
  208. } else {
  209. areas = new ArrayList<SSIDArea>();
  210. areas.add(new SSIDArea(location, number_of_attack, number_of_portscans));
  211. threadAreas.put(netRecord.getSsid(), areas);
  212. }
  213. }
  214. CircleOptions circleOptions = new CircleOptions().radius(200.0).fillColor(Color.argb(127, 240, 80, 60)).strokeWidth(0.0f);
  215. BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.wifi_marker);
  216. for (Map.Entry<String, ArrayList<SSIDArea>> entry : threadAreas.entrySet()) {
  217. String ssid = entry.getKey();
  218. ArrayList<SSIDArea> areas = entry.getValue();
  219. for (SSIDArea area : areas) {
  220. int color = area.calculateColor();
  221. LatLng center = area.calculateCenterLocation();
  222. float radius = area.calculateRadius();
  223. sMap.addCircle(circleOptions.center(center).radius(100.0 + radius).fillColor(color));
  224. Marker marker = sMap.addMarker(new MarkerOptions()
  225. .title(ssid + ": " + area.numAttacks + (area.numAttacks == 1 ? getResources()
  226. .getString(R.string.attack)
  227. : getResources().getString(R.string.attacks)
  228. + " + " + area.numPortscans + (area.numPortscans == 1 ? getResources()
  229. .getString(R.string.portscan)
  230. : getResources().getString(R.string.portscans)))).position(
  231. center));
  232. marker.setIcon(bitmapDescriptor);
  233. sMarkerIDToSSID.put(marker.getId(), ssid);
  234. }
  235. }
  236. sMap.setMyLocationEnabled(true);
  237. LatLng tudarmstadt = new LatLng(49.86923, 8.6632768); // default location
  238. sMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tudarmstadt, 13));
  239. }
  240. /**
  241. * performs initialization
  242. * checks if google play services are supported
  243. * view must be removed if this object has been created once before
  244. * that is why view is static
  245. *
  246. * @param inflater the inflater
  247. * @param container the container
  248. * @param savedInstanceState the savedInstanceState
  249. * @return the view
  250. */
  251. @Override
  252. public View onCreateView(final LayoutInflater inflater, ViewGroup container,
  253. Bundle savedInstanceState) {
  254. super.onCreateView(inflater, container, savedInstanceState);
  255. final Activity activity = getActivity();
  256. if (activity != null) {
  257. activity.setTitle(getResources().getString(R.string.drawer_threat_map));
  258. }
  259. if (sView != null) {
  260. ViewGroup parent = (ViewGroup) sView.getParent();
  261. if (parent != null)
  262. parent.removeView(sView);
  263. }
  264. try {
  265. sView = inflater.inflate(R.layout.fragment_threatmap, container, false);
  266. if (isGooglePlay()) {
  267. final FragmentManager fragmentManager = getFragmentManager();
  268. if (fragmentManager != null) {
  269. final MapFragment mapFragment = (MapFragment) getFragmentManager()
  270. .findFragmentById(R.id.threatmapfragment);
  271. if (mapFragment != null) {
  272. sMap = mapFragment.getMap();
  273. populateMap();
  274. }
  275. }
  276. }
  277. } catch (InflateException e) {
  278. // map already exists
  279. //e.printStackTrace();
  280. }
  281. if (sMap != null) {
  282. sMap.setOnInfoWindowClickListener(this);
  283. // custom info window layout
  284. sMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
  285. @Override
  286. public View getInfoWindow(Marker marker) {
  287. return null;
  288. }
  289. @Override
  290. public View getInfoContents(Marker marker) {
  291. View view = inflater.inflate(R.layout.fragment_threatmap_infowindow, null);
  292. if (view != null) {
  293. TextView titleTextView = (TextView)view.findViewById(R.id.threatmap_infowindow_title);
  294. if (titleTextView != null) {
  295. titleTextView.setText(marker.getTitle());
  296. }
  297. }
  298. return view;
  299. }
  300. });
  301. }
  302. // tell the user to enable wifi so map data can be streamed
  303. if (activity != null && !HelperUtils.isWifiConnected(activity)) {
  304. new AlertDialog.Builder(activity)
  305. .setTitle(R.string.information)
  306. .setMessage(R.string.no_network_connection_threatmap_msg)
  307. .setPositiveButton(android.R.string.ok,
  308. new DialogInterface.OnClickListener() {
  309. public void onClick(DialogInterface dialog,
  310. int which) {
  311. }
  312. })
  313. .setIcon(android.R.drawable.ic_dialog_info).show();
  314. }
  315. return sView;
  316. }
  317. @Override
  318. public void onResume() {
  319. super.onResume();
  320. if (mLocationClient == null) {
  321. mLocationClient = new LocationClient(MainActivity.getInstance().getApplicationContext(), this, this);
  322. }
  323. mLocationClient.connect();
  324. }
  325. @Override
  326. public void onPause() {
  327. super.onPause();
  328. if (mLocationClient != null) {
  329. mLocationClient.disconnect();
  330. }
  331. }
  332. }