HelperUtils.java 14 KB

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