HelperUtils.java 13 KB

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