HelperUtils.java 13 KB

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