HelperUtils.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package de.tudarmstadt.informatik.hostage.commons;
  2. import junit.framework.Assert;
  3. import org.apache.http.HttpVersion;
  4. import org.apache.http.client.HttpClient;
  5. import org.apache.http.client.methods.HttpPost;
  6. import org.apache.http.conn.ClientConnectionManager;
  7. import org.apache.http.conn.scheme.PlainSocketFactory;
  8. import org.apache.http.conn.scheme.Scheme;
  9. import org.apache.http.conn.scheme.SchemeRegistry;
  10. import org.apache.http.conn.ssl.SSLSocketFactory;
  11. import org.apache.http.entity.StringEntity;
  12. import org.apache.http.impl.client.DefaultHttpClient;
  13. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  14. import org.apache.http.params.BasicHttpParams;
  15. import org.apache.http.params.HttpParams;
  16. import org.apache.http.params.HttpProtocolParams;
  17. import org.apache.http.protocol.HTTP;
  18. import java.io.BufferedReader;
  19. import java.io.File;
  20. import java.io.FileNotFoundException;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.InputStreamReader;
  25. import java.io.OutputStream;
  26. import java.net.InetAddress;
  27. import java.net.UnknownHostException;
  28. import java.security.KeyStore;
  29. import java.security.SecureRandom;
  30. import android.app.Activity;
  31. import android.content.Context;
  32. import android.content.res.AssetManager;
  33. import android.net.ConnectivityManager;
  34. import android.net.NetworkInfo;
  35. import android.net.wifi.WifiInfo;
  36. import android.net.wifi.WifiManager;
  37. import android.os.Environment;
  38. import android.preference.PreferenceManager;
  39. import android.text.TextUtils;
  40. import android.util.Log;
  41. import de.tudarmstadt.informatik.hostage.logging.Record;
  42. import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
  43. import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
  44. import de.tudarmstadt.informatik.hostage.system.Device;
  45. import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
  46. /**
  47. * Helper class with some static methods for general usage.
  48. *
  49. * @author Lars Pandikow
  50. * @author Wulf Pfeiffer
  51. *
  52. */
  53. public final class HelperUtils {
  54. //Getter and setters for detection of file injection
  55. public static String filePath;
  56. public static String getFilePath() {
  57. return filePath;
  58. }
  59. public static void setFilePath(String filePath) {
  60. HelperUtils.filePath = filePath;
  61. }
  62. public static String fileName;
  63. public static String getFileName() {
  64. return fileName;
  65. }
  66. public static void setFileName(String fileName) {
  67. HelperUtils.fileName = fileName;
  68. }
  69. public static String fileSHA256;
  70. public static String getFileSHA256() {
  71. return fileSHA256;
  72. }
  73. public static void setFileSHA256(String fileSHA256) {
  74. HelperUtils.fileSHA256 = fileSHA256;
  75. }
  76. public static boolean isFileInjected;
  77. public static boolean isFileInjected() {return isFileInjected;}
  78. public static void setIsFileInjected(boolean isFileInjected) {HelperUtils.isFileInjected = isFileInjected;}
  79. /**
  80. * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to
  81. * "00, 01".
  82. *
  83. * @param bytes
  84. * that will be converted.
  85. * @return converted String.
  86. */
  87. public static String bytesToHexString(byte[] bytes) {
  88. char[] hexArray = "0123456789ABCDEF".toCharArray();
  89. int v;
  90. StringBuffer buffer = new StringBuffer();
  91. for (int j = 0; j < bytes.length; j++) {
  92. v = bytes[j] & 0xFF;
  93. buffer.append(hexArray[v >>> 4]);
  94. buffer.append(hexArray[v & 0x0F]);
  95. if (j < bytes.length - 1)
  96. buffer.append(", ");
  97. }
  98. return buffer.toString();
  99. }
  100. /**
  101. * Converts a byte[] to a String, but only characters in ASCII between 32
  102. * and 127
  103. *
  104. * @param bytes
  105. * that are converted
  106. * @return converted String
  107. */
  108. public static String byteToStr(byte[] bytes) {
  109. int size = 0;
  110. for(byte b : bytes) {
  111. if(isLetter((char) b)) {
  112. size++;
  113. }
  114. }
  115. char[] chars = new char[size];
  116. for (int i = 0, j = 0; i < bytes.length && j < size; i++) {
  117. if (isLetter((char) bytes[i])) {
  118. chars[j] = (char) bytes[i];
  119. j++;
  120. }
  121. }
  122. return new String(chars);
  123. }
  124. /**
  125. * Concatenates several byte arrays.
  126. *
  127. * @param bytes
  128. * The byte arrays.
  129. * @return A single byte arrays containing all the bytes from the given
  130. * arrays in the order they are given.
  131. */
  132. public static byte[] concat(byte[]... bytes) {
  133. int newSize = 0;
  134. for (byte[] b : bytes)
  135. if (b != null)
  136. newSize += b.length;
  137. byte[] dst = new byte[newSize];
  138. int currentPos = 0;
  139. int newPos;
  140. for (byte[] b : bytes) {
  141. if (b != null) {
  142. newPos = b.length;
  143. System.arraycopy(b, 0, dst, currentPos, newPos);
  144. currentPos += newPos;
  145. }
  146. }
  147. return dst;
  148. }
  149. /**
  150. * Puts a 0x00 byte between each byte in a byte array.
  151. *
  152. * @param bytes
  153. * that need to be filled with 0x00.
  154. * @return filled byte array.
  155. */
  156. public static byte[] fillWithZero(byte[] bytes) {
  157. byte[] newBytes = new byte[(bytes.length * 2)];
  158. for (int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j = j + 2) {
  159. newBytes[j] = bytes[i];
  160. newBytes[j + 1] = 0x00;
  161. }
  162. return newBytes;
  163. }
  164. /**
  165. * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of
  166. * a byte array.
  167. *
  168. * @param bytes
  169. * that need to be filled with 0x00.
  170. * @return filled byte array.
  171. */
  172. public static byte[] fillWithZeroExtended(byte[] bytes) {
  173. byte[] zeroBytes = fillWithZero(bytes);
  174. byte[] newBytes = new byte[zeroBytes.length + 2];
  175. newBytes = HelperUtils.concat(zeroBytes, new byte[] { 0x00, 0x00 });
  176. return newBytes;
  177. }
  178. /**
  179. * Gets BSSID of the wireless network.
  180. *
  181. * @param context
  182. * Needs a context to get system recourses.
  183. * @return BSSID of wireless network if connected, else null.
  184. */
  185. public static String getBSSID(Context context) {
  186. String bssid = null;
  187. ConnectivityManager connManager = (ConnectivityManager) context
  188. .getSystemService(Context.CONNECTIVITY_SERVICE);
  189. NetworkInfo networkInfo = connManager
  190. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  191. if (networkInfo != null && networkInfo.isConnected()) {
  192. final WifiManager wifiManager = (WifiManager) context
  193. .getSystemService(Context.WIFI_SERVICE);
  194. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  195. if (connectionInfo != null
  196. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  197. bssid = connectionInfo.getBSSID();
  198. }
  199. }
  200. return bssid;
  201. }
  202. public static HttpClient createHttpClient() {
  203. try {
  204. KeyStore trustStore = KeyStore.getInstance(KeyStore
  205. .getDefaultType());
  206. trustStore.load(null, null);
  207. SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  208. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  209. HttpParams params = new BasicHttpParams();
  210. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  211. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  212. SchemeRegistry registry = new SchemeRegistry();
  213. registry.register(new Scheme("http", PlainSocketFactory
  214. .getSocketFactory(), 80));
  215. registry.register(new Scheme("https", sf, 443));
  216. ClientConnectionManager ccm = new ThreadSafeClientConnManager(
  217. params, registry);
  218. return new DefaultHttpClient(ccm, params);
  219. } catch (Exception e) {
  220. e.printStackTrace();
  221. return new DefaultHttpClient();
  222. }
  223. }
  224. public static boolean uploadSingleRecord(Context context, Record record) {
  225. // Create a https client. Uses MySSLSocketFactory to accept all
  226. // certificates
  227. HttpClient httpclient = HelperUtils.createHttpClient();
  228. HttpPost httppost;
  229. try {
  230. // Create HttpPost
  231. httppost = new HttpPost(PreferenceManager
  232. .getDefaultSharedPreferences(context).getString(
  233. "pref_upload", "https://www.tracingmonitor.org"));
  234. // Create JSON String of Record
  235. StringEntity se = new StringEntity(record.toString(TraCINgFormatter.getInstance()));
  236. httppost.setEntity(se);
  237. // Execute HttpPost
  238. httpclient.execute(httppost);
  239. } catch (Exception e) {
  240. e.printStackTrace();
  241. return false;
  242. }
  243. return true;
  244. }
  245. /**
  246. * Gets internal IP address of the device in a wireless network.
  247. *
  248. * @param context
  249. * Needs a context to get system recourses.
  250. * @return internal IP of the device in a wireless network if connected,
  251. * else null.
  252. */
  253. public static String getInternalIP(Context context) {
  254. String ipAddress = null;
  255. ConnectivityManager connManager = (ConnectivityManager) context
  256. .getSystemService(Context.CONNECTIVITY_SERVICE);
  257. NetworkInfo networkInfo = connManager
  258. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  259. if (networkInfo != null && networkInfo.isConnected()) {
  260. final WifiManager wifiManager = (WifiManager) context
  261. .getSystemService(Context.WIFI_SERVICE);
  262. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  263. if (connectionInfo != null) {
  264. try {
  265. ipAddress = InetAddress.getByAddress(
  266. unpackInetAddress(connectionInfo.getIpAddress()))
  267. .getHostAddress();
  268. } catch (UnknownHostException e) {
  269. e.printStackTrace();
  270. }
  271. }
  272. }
  273. return ipAddress;
  274. }
  275. /**
  276. * Gets SSID of the wireless network.
  277. *
  278. * @param context
  279. * Needs a context to get system recourses
  280. * @return SSID of wireless network if connected, else null.
  281. */
  282. public static String getSSID(Context context) {
  283. String ssid = null;
  284. ConnectivityManager connManager = (ConnectivityManager) context
  285. .getSystemService(Context.CONNECTIVITY_SERVICE);
  286. NetworkInfo networkInfo = connManager
  287. .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  288. if (networkInfo != null && networkInfo.isConnected()) {
  289. final WifiManager wifiManager = (WifiManager) context
  290. .getSystemService(Context.WIFI_SERVICE);
  291. final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  292. if (connectionInfo != null
  293. && !TextUtils.isEmpty(connectionInfo.getSSID())) {
  294. ssid = connectionInfo.getSSID();
  295. if (ssid.startsWith("\"") && ssid.endsWith("\"")) { // trim those quotes
  296. ssid = ssid.substring(1, ssid.length() - 1);
  297. }
  298. }
  299. }
  300. return ssid;
  301. }
  302. /**
  303. * Gets the mac address of the devicek.
  304. *
  305. * @param context
  306. * Needs a context to get system recourses
  307. * @return MAC address of the device.
  308. */
  309. public static String getMacAdress(Context context) {
  310. String mac = null;
  311. WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  312. WifiInfo connectionInfo = wifiManager.getConnectionInfo();
  313. mac = connectionInfo.getMacAddress();
  314. return mac;
  315. }
  316. /**
  317. * Produces a random String. The String can be of random length (minimum 1)
  318. * with a maximum length, or it can be forced to have the length that was
  319. * given.
  320. *
  321. * @param length
  322. * maximal / forced length of String.
  323. * @param forceLength
  324. * forces the String to be exact the given length instead of
  325. * maximum
  326. * @return random String.
  327. */
  328. public static String getRandomString(int length, boolean forceLength) {
  329. SecureRandom rndm = new SecureRandom();
  330. char[] c = new char[forceLength ? length : rndm.nextInt(length - 1) + 1];
  331. for (int i = 0; i < c.length; i++) {
  332. c[i] = (char) (rndm.nextInt(95) + 32);
  333. }
  334. return new String(c);
  335. }
  336. /**
  337. * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
  338. *
  339. * @param string
  340. * that will be converted.
  341. * @return converted byte array.
  342. */
  343. public static byte[] hexStringToBytes(String string) {
  344. String[] hexStrings = string.split(", ");
  345. byte[] bytes = new byte[hexStrings.length];
  346. for (int j = 0; j < hexStrings.length; j++) {
  347. bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4) + Character
  348. .digit(hexStrings[j].charAt(1), 16));
  349. }
  350. return bytes;
  351. }
  352. /**
  353. * Generates a random byte[] of a specified size
  354. *
  355. * @param size
  356. * of the byte[]
  357. * @return random byte[]
  358. */
  359. public static byte[] randomBytes(int size) {
  360. byte[] bytes = new byte[size];
  361. SecureRandom rdm = new SecureRandom();
  362. rdm.nextBytes(bytes);
  363. return bytes;
  364. }
  365. /**
  366. * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into
  367. * {0x02, 0x01, 0x00}.
  368. *
  369. * @param bytes
  370. * array that is turned.
  371. * @return turned array.
  372. */
  373. public static byte[] turnByteArray(byte[] bytes) {
  374. byte[] tmp = new byte[bytes.length];
  375. for (int i = 0; i < bytes.length; i++) {
  376. tmp[i] = bytes[bytes.length - 1 - i];
  377. }
  378. return tmp;
  379. }
  380. /**
  381. * Determines if a character is in ASCII between 32 and 126
  382. *
  383. * @param character
  384. * that is checked
  385. * @return true if the character is between 32 and 126, else false
  386. */
  387. private static boolean isLetter(char character) {
  388. return (character > 31 && character < 127);
  389. }
  390. public static byte[] unpackInetAddress(int bytes) {
  391. return new byte[] { (byte) ((bytes) & 0xff),
  392. (byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
  393. (byte) ((bytes >>> 24) & 0xff) };
  394. }
  395. public static int packInetAddress(byte[] bytes) {
  396. /*
  397. FUCK YOU JAVA!!! WHY DON'T YOU HAVE UNSIGNED TYPES???
  398. */
  399. long b0 = bytes[0]; if (b0 < 0) b0 = 256 + b0;
  400. long b1 = bytes[1]; if (b1 < 0) b1 = 256 + b1;
  401. long b2 = bytes[2]; if (b2 < 0) b2 = 256 + b2;
  402. long b3 = bytes[3]; if (b3 < 0) b3 = 256 + b3;
  403. long packed = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
  404. if (packed >= (1l << 31)) {
  405. packed -= (1l << 32) - 1l;
  406. }
  407. return (int)packed;
  408. }
  409. public static String inetAddressToString(int address) {
  410. return String.valueOf(address & 0xFF) + "."
  411. + String.valueOf((address >>> 8) & 0xFF) + "."
  412. + String.valueOf((address >>> 16) & 0xFF) + "."
  413. + String.valueOf((address >>> 24) & 0xFF);
  414. }
  415. public static boolean isWifiConnected(Context context){
  416. if(context == null) return false;
  417. ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  418. NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  419. return mWifi.isConnected();
  420. }
  421. public static boolean isNetworkAvailable(Context context) {
  422. if(context == null) return false;
  423. ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  424. NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  425. return activeNetworkInfo != null && activeNetworkInfo.isConnected();
  426. }
  427. public static int getRedirectedPort(int port){
  428. return port + 1024 + 27113;
  429. }
  430. }