HelperUtils.java 14 KB

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