PsiphonTunnel.java 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package ca.psiphon;
  20. import android.annotation.TargetApi;
  21. import android.content.Context;
  22. import android.net.ConnectivityManager;
  23. import android.net.LinkProperties;
  24. import android.net.Network;
  25. import android.net.NetworkInfo;
  26. import android.net.NetworkRequest;
  27. import android.net.VpnService;
  28. import android.net.wifi.WifiInfo;
  29. import android.net.wifi.WifiManager;
  30. import android.os.Build;
  31. import android.os.ParcelFileDescriptor;
  32. import android.telephony.TelephonyManager;
  33. import android.util.Base64;
  34. import org.json.JSONArray;
  35. import org.json.JSONException;
  36. import org.json.JSONObject;
  37. import java.io.File;
  38. import java.io.FileInputStream;
  39. import java.io.FileOutputStream;
  40. import java.io.IOException;
  41. import java.io.PrintStream;
  42. import java.lang.reflect.InvocationTargetException;
  43. import java.lang.reflect.Method;
  44. import java.net.Inet4Address;
  45. import java.net.InetAddress;
  46. import java.net.NetworkInterface;
  47. import java.net.SocketException;
  48. import java.security.KeyStore;
  49. import java.security.KeyStoreException;
  50. import java.security.NoSuchAlgorithmException;
  51. import java.security.cert.CertificateException;
  52. import java.security.cert.X509Certificate;
  53. import java.util.ArrayList;
  54. import java.util.Collection;
  55. import java.util.Collections;
  56. import java.util.Enumeration;
  57. import java.util.HashMap;
  58. import java.util.List;
  59. import java.util.Locale;
  60. import java.util.Map;
  61. import java.util.concurrent.CountDownLatch;
  62. import java.util.concurrent.atomic.AtomicBoolean;
  63. import java.util.concurrent.atomic.AtomicInteger;
  64. import java.util.concurrent.atomic.AtomicReference;
  65. import java.util.concurrent.Executors;
  66. import java.util.concurrent.ExecutorService;
  67. import java.util.concurrent.Future;
  68. import java.util.concurrent.TimeUnit;
  69. import psi.Psi;
  70. import psi.PsiphonProvider;
  71. import psi.PsiphonProviderNetwork;
  72. import psi.PsiphonProviderNoticeHandler;
  73. import psi.PsiphonProviderFeedbackHandler;
  74. public class PsiphonTunnel {
  75. public interface HostLogger {
  76. default public void onDiagnosticMessage(String message) {}
  77. }
  78. // Protocol used to communicate the outcome of feedback upload operations to the application
  79. // using PsiphonTunnelFeedback.
  80. public interface HostFeedbackHandler {
  81. // Callback which is invoked once the feedback upload has completed.
  82. // If the exception is non-null, then the upload failed.
  83. default public void sendFeedbackCompleted(java.lang.Exception e) {}
  84. }
  85. public interface HostService extends HostLogger {
  86. public String getAppName();
  87. public Context getContext();
  88. public String getPsiphonConfig();
  89. default public Object getVpnService() {return null;} // Object must be a VpnService (Android < 4 cannot reference this class name)
  90. default public Object newVpnServiceBuilder() {return null;} // Object must be a VpnService.Builder (Android < 4 cannot reference this class name)
  91. default public void onAvailableEgressRegions(List<String> regions) {}
  92. default public void onSocksProxyPortInUse(int port) {}
  93. default public void onHttpProxyPortInUse(int port) {}
  94. default public void onListeningSocksProxyPort(int port) {}
  95. default public void onListeningHttpProxyPort(int port) {}
  96. default public void onUpstreamProxyError(String message) {}
  97. default public void onConnecting() {}
  98. default public void onConnected() {}
  99. default public void onHomepage(String url) {}
  100. default public void onClientRegion(String region) {}
  101. default public void onClientUpgradeDownloaded(String filename) {}
  102. default public void onClientIsLatestVersion() {}
  103. default public void onSplitTunnelRegion(String region) {}
  104. default public void onUntunneledAddress(String address) {}
  105. default public void onBytesTransferred(long sent, long received) {}
  106. default public void onStartedWaitingForNetworkConnectivity() {}
  107. default public void onStoppedWaitingForNetworkConnectivity() {}
  108. default public void onActiveAuthorizationIDs(List<String> authorizations) {}
  109. default public void onTrafficRateLimits(long upstreamBytesPerSecond, long downstreamBytesPerSecond) {}
  110. default public void onApplicationParameter(String key, Object value) {}
  111. default public void onServerAlert(String reason, String subject) {}
  112. default public void onExiting() {}
  113. }
  114. private final HostService mHostService;
  115. private AtomicBoolean mVpnMode;
  116. private PrivateAddress mPrivateAddress;
  117. private AtomicReference<ParcelFileDescriptor> mTunFd;
  118. private AtomicInteger mLocalSocksProxyPort;
  119. private AtomicBoolean mRoutingThroughTunnel;
  120. private Thread mTun2SocksThread;
  121. private AtomicBoolean mIsWaitingForNetworkConnectivity;
  122. private AtomicReference<String> mClientPlatformPrefix;
  123. private AtomicReference<String> mClientPlatformSuffix;
  124. private final boolean mShouldRouteThroughTunnelAutomatically;
  125. // Only one PsiphonVpn instance may exist at a time, as the underlying
  126. // psi.Psi and tun2socks implementations each contain global state.
  127. private static PsiphonTunnel mPsiphonTunnel;
  128. public static synchronized PsiphonTunnel newPsiphonTunnel(HostService hostService) {
  129. return newPsiphonTunnelImpl(hostService, true);
  130. }
  131. // The two argument override in case the host app wants to take control over calling routeThroughTunnel()
  132. public static synchronized PsiphonTunnel newPsiphonTunnel(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  133. return newPsiphonTunnelImpl(hostService, shouldRouteThroughTunnelAutomatically);
  134. }
  135. private static PsiphonTunnel newPsiphonTunnelImpl(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  136. if (mPsiphonTunnel != null) {
  137. mPsiphonTunnel.stop();
  138. }
  139. // Load the native go code embedded in psi.aar
  140. System.loadLibrary("gojni");
  141. mPsiphonTunnel = new PsiphonTunnel(hostService, shouldRouteThroughTunnelAutomatically);
  142. return mPsiphonTunnel;
  143. }
  144. // Returns default path where upgrade downloads will be paved. Only applicable if
  145. // DataRootDirectory was not set in the outer config. If DataRootDirectory was set in the
  146. // outer config, use getUpgradeDownloadFilePath with its value instead.
  147. public static String getDefaultUpgradeDownloadFilePath(Context context) {
  148. return Psi.upgradeDownloadFilePath(defaultDataRootDirectory(context).getAbsolutePath());
  149. }
  150. // Returns the path where upgrade downloads will be paved relative to the configured
  151. // DataRootDirectory.
  152. public static String getUpgradeDownloadFilePath(String dataRootDirectoryPath) {
  153. return Psi.upgradeDownloadFilePath(dataRootDirectoryPath);
  154. }
  155. private static File defaultDataRootDirectory(Context context) {
  156. return context.getFileStreamPath("ca.psiphon.PsiphonTunnel.tunnel-core");
  157. }
  158. private PsiphonTunnel(HostService hostService, boolean shouldRouteThroughTunnelAutomatically) {
  159. mHostService = hostService;
  160. mVpnMode = new AtomicBoolean(false);
  161. mTunFd = new AtomicReference<ParcelFileDescriptor>();
  162. mLocalSocksProxyPort = new AtomicInteger(0);
  163. mRoutingThroughTunnel = new AtomicBoolean(false);
  164. mIsWaitingForNetworkConnectivity = new AtomicBoolean(false);
  165. mClientPlatformPrefix = new AtomicReference<String>("");
  166. mClientPlatformSuffix = new AtomicReference<String>("");
  167. mShouldRouteThroughTunnelAutomatically = shouldRouteThroughTunnelAutomatically;
  168. }
  169. public Object clone() throws CloneNotSupportedException {
  170. throw new CloneNotSupportedException();
  171. }
  172. //----------------------------------------------------------------------------------------------
  173. // Public API
  174. //----------------------------------------------------------------------------------------------
  175. // To start, call in sequence: startRouting(), then startTunneling(). After startRouting()
  176. // succeeds, the caller must call stop() to clean up. These functions should not be called
  177. // concurrently. Do not call stop() while startRouting() or startTunneling() is in progress.
  178. // In case the host application requests manual control of routing through tunnel by calling
  179. // PsiphonTunnel.newPsiphonTunnel(HostService hostservice, shouldRouteThroughTunnelAutomatically = false)
  180. // it should also call routeThroughTunnel() at some point, usually after receiving onConnected() callback,
  181. // otherwise it will be called automatically.
  182. // Returns true when the VPN routing is established; returns false if the VPN could not
  183. // be started due to lack of prepare or revoked permissions (called should re-prepare and
  184. // try again); throws exception for other error conditions.
  185. public synchronized boolean startRouting() throws Exception {
  186. // Load tun2socks library embedded in the aar
  187. // If this method is called more than once with the same library name, the second and subsequent calls are ignored.
  188. // http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#loadLibrary%28java.lang.String%29
  189. System.loadLibrary("tun2socks");
  190. return startVpn();
  191. }
  192. // Starts routing traffic via tunnel by starting tun2socks if it is not running already.
  193. // This will be called automatically right after tunnel gets connected in case the host application
  194. // did not request a manual control over this functionality, see PsiphonTunnel.newPsiphonTunnel
  195. public void routeThroughTunnel() {
  196. if (!mRoutingThroughTunnel.compareAndSet(false, true)) {
  197. return;
  198. }
  199. ParcelFileDescriptor tunFd = mTunFd.getAndSet(null);
  200. if (tunFd == null) {
  201. return;
  202. }
  203. String socksServerAddress = "127.0.0.1:" + Integer.toString(mLocalSocksProxyPort.get());
  204. String udpgwServerAddress = "127.0.0.1:" + Integer.toString(UDPGW_SERVER_PORT);
  205. startTun2Socks(
  206. tunFd,
  207. VPN_INTERFACE_MTU,
  208. mPrivateAddress.mRouter,
  209. VPN_INTERFACE_NETMASK,
  210. socksServerAddress,
  211. udpgwServerAddress,
  212. true);
  213. mHostService.onDiagnosticMessage("routing through tunnel");
  214. // TODO: should double-check tunnel routing; see:
  215. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/1dc5e4257dca99790109f3bf374e8ab3a0ead4d7/Android/PsiphonAndroidLibrary/src/com/psiphon3/psiphonlibrary/TunnelCore.java?at=default#cl-779
  216. }
  217. // Throws an exception in error conditions. In the case of an exception, the routing
  218. // started by startRouting() is not immediately torn down (this allows the caller to control
  219. // exactly when VPN routing is stopped); caller should call stop() to clean up.
  220. public synchronized void startTunneling(String embeddedServerEntries) throws Exception {
  221. startPsiphon(embeddedServerEntries);
  222. }
  223. // Note: to avoid deadlock, do not call directly from a HostService callback;
  224. // instead post to a Handler if necessary to trigger from a HostService callback.
  225. // For example, deadlock can occur when a Notice callback invokes stop() since stop() calls
  226. // Psi.stop() which will block waiting for tunnel-core Controller to shutdown which in turn
  227. // waits for Notice callback invoker to stop, meanwhile the callback thread has blocked waiting
  228. // for stop().
  229. public synchronized void stop() {
  230. stopVpn();
  231. stopPsiphon();
  232. mVpnMode.set(false);
  233. mLocalSocksProxyPort.set(0);
  234. }
  235. // Note: same deadlock note as stop().
  236. public synchronized void restartPsiphon() throws Exception {
  237. stopPsiphon();
  238. startPsiphon("");
  239. }
  240. // Creates a temporary dummy VPN interface in order to prevent traffic leaking while performing
  241. // complete VPN and tunnel restart, for example, caused by host app settings change.
  242. // Note: same deadlock note as stop().
  243. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  244. public synchronized void seamlessVpnRestart(VpnService.Builder vpnServiceBuilder) throws Exception {
  245. // Perform seamless VPN interface swap Psiphon VPN -> dummy VPN
  246. //
  247. // From https://developer.android.com/reference/android/net/VpnService.Builder.html#establish()
  248. // "However, it is rare but not impossible to have two interfaces while performing a seamless handover.
  249. // In this case, the old interface will be deactivated when the new one is created successfully. Both
  250. // file descriptors are valid but now outgoing packets will be routed to the new interface. Therefore,
  251. // after draining the old file descriptor, the application MUST close it and start using the new file
  252. // descriptor."
  253. ParcelFileDescriptor dummyVpnFd = startDummyVpn(vpnServiceBuilder);
  254. try {
  255. // Clean up and restart Psiphon VPN interface, which will also do the swap dummy VPN -> Psiphon VPN
  256. stopVpn();
  257. startVpn();
  258. } finally {
  259. // Close dummy VPN file descriptor as per documentation.
  260. if (dummyVpnFd != null) {
  261. try {
  262. dummyVpnFd.close();
  263. } catch (IOException e) {
  264. }
  265. }
  266. }
  267. // Restart the tunnel.
  268. restartPsiphon();
  269. }
  270. public void setClientPlatformAffixes(String prefix, String suffix) {
  271. mClientPlatformPrefix.set(prefix);
  272. mClientPlatformSuffix.set(suffix);
  273. }
  274. public String exportExchangePayload() {
  275. return Psi.exportExchangePayload();
  276. }
  277. public boolean importExchangePayload(String payload) {
  278. return Psi.importExchangePayload(payload);
  279. }
  280. // Writes Go runtime profile information to a set of files in the specifiec output directory.
  281. // cpuSampleDurationSeconds and blockSampleDurationSeconds determines how to long to wait and
  282. // sample profiles that require active sampling. When set to 0, these profiles are skipped.
  283. public void writeRuntimeProfiles(String outputDirectory, int cpuSampleDurationSeconnds, int blockSampleDurationSeconds) {
  284. Psi.writeRuntimeProfiles(outputDirectory, cpuSampleDurationSeconnds, blockSampleDurationSeconds);
  285. }
  286. // The interface for managing the Psiphon feedback upload operations.
  287. // Warnings:
  288. // - Should not be used in the same process as PsiphonTunnel.
  289. // - Only a single instance of PsiphonTunnelFeedback should be used at a time. Using multiple
  290. // instances in parallel, or concurrently, will result in undefined behavior.
  291. public static class PsiphonTunnelFeedback {
  292. final private ExecutorService workQueue;
  293. final private ExecutorService callbackQueue;
  294. public PsiphonTunnelFeedback() {
  295. workQueue = Executors.newSingleThreadExecutor();
  296. callbackQueue = Executors.newSingleThreadExecutor();
  297. }
  298. @Override
  299. protected void finalize() throws Throwable {
  300. // Ensure the queues are cleaned up.
  301. shutdownAndAwaitTermination(callbackQueue);
  302. shutdownAndAwaitTermination(workQueue);
  303. super.finalize();
  304. }
  305. void shutdownAndAwaitTermination(ExecutorService pool) {
  306. try {
  307. // Wait a while for existing tasks to terminate
  308. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  309. pool.shutdownNow(); // Cancel currently executing tasks
  310. // Wait a while for tasks to respond to being cancelled
  311. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  312. System.err.println("PsiphonTunnelFeedback: pool did not terminate");
  313. return;
  314. }
  315. }
  316. } catch (InterruptedException ie) {
  317. // (Re-)Cancel if current thread also interrupted
  318. pool.shutdownNow();
  319. // Preserve interrupt status
  320. Thread.currentThread().interrupt();
  321. }
  322. }
  323. // Upload a feedback package to Psiphon Inc. The app collects feedback and diagnostics
  324. // information in a particular format, then calls this function to upload it for later
  325. // investigation. The feedback compatible config and upload path must be provided by
  326. // Psiphon Inc. This call is asynchronous and returns before the upload completes. The
  327. // operation has completed when sendFeedbackCompleted() is called on the provided
  328. // HostFeedbackHandler. The provided HostLogger will be called to log informational notices,
  329. // including warnings.
  330. //
  331. // Warnings:
  332. // - Only one active upload is supported at a time. An ongoing upload will be cancelled if
  333. // this function is called again before it completes.
  334. // - An ongoing feedback upload started with startSendFeedback() should be stopped with
  335. // stopSendFeedback() before the process exits. This ensures that any underlying resources
  336. // are cleaned up; failing to do so may result in data store corruption or other undefined
  337. // behavior.
  338. // - PsiphonTunnel.startTunneling and startSendFeedback both make an attempt to migrate
  339. // persistent files from legacy locations in a one-time operation. If these functions are
  340. // called in parallel, then there is a chance that the migration attempts could execute at
  341. // the same time and result in non-fatal errors in one, or both, of the migration
  342. // operations.
  343. public void startSendFeedback(Context context, HostFeedbackHandler feedbackHandler, HostLogger logger,
  344. String feedbackConfigJson, String diagnosticsJson, String uploadPath,
  345. String clientPlatformPrefix, String clientPlatformSuffix) {
  346. workQueue.submit(new Runnable() {
  347. @Override
  348. public void run() {
  349. try {
  350. // Adds fields used in feedback upload, e.g. client platform.
  351. String psiphonConfig = buildPsiphonConfig(context, logger, feedbackConfigJson,
  352. clientPlatformPrefix, clientPlatformSuffix, false, 0);
  353. Psi.startSendFeedback(psiphonConfig, diagnosticsJson, uploadPath,
  354. new PsiphonProviderFeedbackHandler() {
  355. @Override
  356. public void sendFeedbackCompleted(java.lang.Exception e) {
  357. callbackQueue.submit(new Runnable() {
  358. @Override
  359. public void run() {
  360. feedbackHandler.sendFeedbackCompleted(e);
  361. }
  362. });
  363. }
  364. },
  365. new PsiphonProviderNetwork() {
  366. @Override
  367. public long hasNetworkConnectivity() {
  368. boolean hasConnectivity = PsiphonTunnel.hasNetworkConnectivity(context);
  369. // TODO: change to bool return value once gobind supports that type
  370. return hasConnectivity ? 1 : 0;
  371. }
  372. @Override
  373. public String getNetworkID() {
  374. return PsiphonTunnel.getNetworkID(context);
  375. }
  376. @Override
  377. public String iPv6Synthesize(String IPv4Addr) {
  378. // Unused on Android.
  379. return PsiphonTunnel.iPv6Synthesize(IPv4Addr);
  380. }
  381. },
  382. new PsiphonProviderNoticeHandler() {
  383. @Override
  384. public void notice(String noticeJSON) {
  385. try {
  386. JSONObject notice = new JSONObject(noticeJSON);
  387. String noticeType = notice.getString("noticeType");
  388. if (noticeType == null) {
  389. return;
  390. }
  391. JSONObject data = notice.getJSONObject("data");
  392. if (data == null) {
  393. return;
  394. }
  395. String diagnosticMessage = noticeType + ": " + data.toString();
  396. callbackQueue.submit(new Runnable() {
  397. @Override
  398. public void run() {
  399. logger.onDiagnosticMessage(diagnosticMessage);
  400. }
  401. });
  402. } catch (java.lang.Exception e) {
  403. callbackQueue.submit(new Runnable() {
  404. @Override
  405. public void run() {
  406. logger.onDiagnosticMessage("Error handling notice " + e.toString());
  407. }
  408. });
  409. }
  410. }
  411. },
  412. // Do not use IPv6 synthesizer for android
  413. false);
  414. } catch (java.lang.Exception e) {
  415. callbackQueue.submit(new Runnable() {
  416. @Override
  417. public void run() {
  418. feedbackHandler.sendFeedbackCompleted(new Exception("Error sending feedback", e));
  419. }
  420. });
  421. }
  422. }
  423. });
  424. }
  425. // Interrupt an in-progress feedback upload operation started with startSendFeedback(). This
  426. // call is asynchronous and returns a future which is fulfilled when the underlying stop
  427. // operation completes.
  428. public Future<Void> stopSendFeedback() {
  429. return workQueue.submit(new Runnable() {
  430. @Override
  431. public void run() {
  432. Psi.stopSendFeedback();
  433. }
  434. }, null);
  435. }
  436. }
  437. //----------------------------------------------------------------------------------------------
  438. // VPN Routing
  439. //----------------------------------------------------------------------------------------------
  440. private final static String VPN_INTERFACE_NETMASK = "255.255.255.0";
  441. private final static int VPN_INTERFACE_MTU = 1500;
  442. private final static int UDPGW_SERVER_PORT = 7300;
  443. private final static String DEFAULT_PRIMARY_DNS_SERVER = "8.8.4.4";
  444. private final static String DEFAULT_SECONDARY_DNS_SERVER = "8.8.8.8";
  445. // Note: Atomic variables used for getting/setting local proxy port, routing flag, and
  446. // tun fd, as these functions may be called via PsiphonProvider callbacks. Do not use
  447. // synchronized functions as stop() is synchronized and a deadlock is possible as callbacks
  448. // can be called while stop holds the lock.
  449. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  450. private boolean startVpn() throws Exception {
  451. mVpnMode.set(true);
  452. mPrivateAddress = selectPrivateAddress();
  453. Locale previousLocale = Locale.getDefault();
  454. final String errorMessage = "startVpn failed";
  455. try {
  456. // Workaround for https://code.google.com/p/android/issues/detail?id=61096
  457. Locale.setDefault(new Locale("en"));
  458. int mtu = VPN_INTERFACE_MTU;
  459. String dnsResolver = mPrivateAddress.mRouter;
  460. ParcelFileDescriptor tunFd =
  461. ((VpnService.Builder) mHostService.newVpnServiceBuilder())
  462. .setSession(mHostService.getAppName())
  463. .setMtu(mtu)
  464. .addAddress(mPrivateAddress.mIpAddress, mPrivateAddress.mPrefixLength)
  465. .addRoute("0.0.0.0", 0)
  466. .addRoute(mPrivateAddress.mSubnet, mPrivateAddress.mPrefixLength)
  467. .addDnsServer(dnsResolver)
  468. .establish();
  469. if (tunFd == null) {
  470. // As per http://developer.android.com/reference/android/net/VpnService.Builder.html#establish%28%29,
  471. // this application is no longer prepared or was revoked.
  472. return false;
  473. }
  474. mTunFd.set(tunFd);
  475. mRoutingThroughTunnel.set(false);
  476. mHostService.onDiagnosticMessage("VPN established");
  477. } catch(IllegalArgumentException e) {
  478. throw new Exception(errorMessage, e);
  479. } catch(IllegalStateException e) {
  480. throw new Exception(errorMessage, e);
  481. } catch(SecurityException e) {
  482. throw new Exception(errorMessage, e);
  483. } finally {
  484. // Restore the original locale.
  485. Locale.setDefault(previousLocale);
  486. }
  487. return true;
  488. }
  489. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  490. private ParcelFileDescriptor startDummyVpn(VpnService.Builder vpnServiceBuilder) throws Exception {
  491. PrivateAddress privateAddress = selectPrivateAddress();
  492. Locale previousLocale = Locale.getDefault();
  493. final String errorMessage = "startDummyVpn failed";
  494. final ParcelFileDescriptor tunFd;
  495. try {
  496. // Workaround for https://code.google.com/p/android/issues/detail?id=61096
  497. Locale.setDefault(new Locale("en"));
  498. int mtu = VPN_INTERFACE_MTU;
  499. String dnsResolver = privateAddress.mRouter;
  500. tunFd = vpnServiceBuilder
  501. .setSession(mHostService.getAppName())
  502. .setMtu(mtu)
  503. .addAddress(privateAddress.mIpAddress, privateAddress.mPrefixLength)
  504. .addRoute("0.0.0.0", 0)
  505. .addRoute(privateAddress.mSubnet, privateAddress.mPrefixLength)
  506. .addDnsServer(dnsResolver)
  507. .establish();
  508. } catch(IllegalArgumentException e) {
  509. throw new Exception(errorMessage, e);
  510. } catch(IllegalStateException e) {
  511. throw new Exception(errorMessage, e);
  512. } catch(SecurityException e) {
  513. throw new Exception(errorMessage, e);
  514. } finally {
  515. // Restore the original locale.
  516. Locale.setDefault(previousLocale);
  517. }
  518. return tunFd;
  519. }
  520. private boolean isVpnMode() {
  521. return mVpnMode.get();
  522. }
  523. private void setLocalSocksProxyPort(int port) {
  524. mLocalSocksProxyPort.set(port);
  525. }
  526. private void stopVpn() {
  527. stopTun2Socks();
  528. ParcelFileDescriptor tunFd = mTunFd.getAndSet(null);
  529. if (tunFd != null) {
  530. try {
  531. tunFd.close();
  532. } catch (IOException e) {
  533. }
  534. }
  535. mRoutingThroughTunnel.set(false);
  536. }
  537. //----------------------------------------------------------------------------------------------
  538. // PsiphonProvider (Core support) interface implementation
  539. //----------------------------------------------------------------------------------------------
  540. // The PsiphonProvider functions are called from Go, and must be public to be accessible
  541. // via the gobind mechanim. To avoid making internal implementation functions public,
  542. // PsiphonProviderShim is used as a wrapper.
  543. private class PsiphonProviderShim implements PsiphonProvider {
  544. private PsiphonTunnel mPsiphonTunnel;
  545. public PsiphonProviderShim(PsiphonTunnel psiphonTunnel) {
  546. mPsiphonTunnel = psiphonTunnel;
  547. }
  548. @Override
  549. public void notice(String noticeJSON) {
  550. mPsiphonTunnel.notice(noticeJSON);
  551. }
  552. @Override
  553. public String bindToDevice(long fileDescriptor) throws Exception {
  554. return mPsiphonTunnel.bindToDevice(fileDescriptor);
  555. }
  556. @Override
  557. public long hasNetworkConnectivity() {
  558. return mPsiphonTunnel.hasNetworkConnectivity();
  559. }
  560. @Override
  561. public String getPrimaryDnsServer() {
  562. return PsiphonTunnel.getPrimaryDnsServer(mHostService.getContext(), mHostService);
  563. }
  564. @Override
  565. public String getSecondaryDnsServer() {
  566. return PsiphonTunnel.getSecondaryDnsServer();
  567. }
  568. @Override
  569. public String iPv6Synthesize(String IPv4Addr) {
  570. return PsiphonTunnel.iPv6Synthesize(IPv4Addr);
  571. }
  572. @Override
  573. public String getNetworkID() {
  574. return PsiphonTunnel.getNetworkID(mHostService.getContext());
  575. }
  576. }
  577. private void notice(String noticeJSON) {
  578. handlePsiphonNotice(noticeJSON);
  579. }
  580. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  581. private String bindToDevice(long fileDescriptor) throws Exception {
  582. if (!((VpnService)mHostService.getVpnService()).protect((int)fileDescriptor)) {
  583. throw new Exception("protect socket failed");
  584. }
  585. return "";
  586. }
  587. private long hasNetworkConnectivity() {
  588. boolean hasConnectivity = hasNetworkConnectivity(mHostService.getContext());
  589. boolean wasWaitingForNetworkConnectivity = mIsWaitingForNetworkConnectivity.getAndSet(!hasConnectivity);
  590. // HasNetworkConnectivity may be called many times, but only invoke
  591. // callbacks once per loss or resumption of connectivity, so, e.g.,
  592. // the HostService may log a single message.
  593. if (!hasConnectivity && !wasWaitingForNetworkConnectivity) {
  594. mHostService.onStartedWaitingForNetworkConnectivity();
  595. } else if (hasConnectivity && wasWaitingForNetworkConnectivity) {
  596. mHostService.onStoppedWaitingForNetworkConnectivity();
  597. }
  598. // TODO: change to bool return value once gobind supports that type
  599. return hasConnectivity ? 1 : 0;
  600. }
  601. private static String getPrimaryDnsServer(Context context, HostLogger logger) {
  602. String dnsResolver = null;
  603. try {
  604. dnsResolver = getFirstActiveNetworkDnsResolver(context);
  605. } catch (Exception e) {
  606. logger.onDiagnosticMessage("failed to get active network DNS resolver: " + e.getMessage());
  607. dnsResolver = DEFAULT_PRIMARY_DNS_SERVER;
  608. }
  609. return dnsResolver;
  610. }
  611. private static String getSecondaryDnsServer() {
  612. return DEFAULT_SECONDARY_DNS_SERVER;
  613. }
  614. private static String iPv6Synthesize(String IPv4Addr) {
  615. // Unused on Android.
  616. return IPv4Addr;
  617. }
  618. private static String getNetworkID(Context context) {
  619. // The network ID contains potential PII. In tunnel-core, the network ID
  620. // is used only locally in the client and not sent to the server.
  621. //
  622. // See network ID requirements here:
  623. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  624. String networkID = "UNKNOWN";
  625. ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  626. NetworkInfo activeNetworkInfo = null;
  627. try {
  628. activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  629. } catch (java.lang.Exception e) {
  630. // May get exceptions due to missing permissions like android.permission.ACCESS_NETWORK_STATE.
  631. // Apps using the Psiphon Library and lacking android.permission.ACCESS_NETWORK_STATE will
  632. // proceed and use tactics, but with "UNKNOWN" as the sole network ID.
  633. }
  634. if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
  635. networkID = "WIFI";
  636. try {
  637. WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
  638. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  639. if (wifiInfo != null) {
  640. String wifiNetworkID = wifiInfo.getBSSID();
  641. if (wifiNetworkID.equals("02:00:00:00:00:00")) {
  642. // "02:00:00:00:00:00" is reported when the app does not have the ACCESS_COARSE_LOCATION permission:
  643. // https://developer.android.com/about/versions/marshmallow/android-6.0-changes#behavior-hardware-id
  644. // The Psiphon client should allow the user to opt-in to this permission. If they decline, fail over
  645. // to using the WiFi IP address.
  646. wifiNetworkID = String.valueOf(wifiInfo.getIpAddress());
  647. }
  648. networkID += "-" + wifiNetworkID;
  649. }
  650. } catch (java.lang.Exception e) {
  651. // May get exceptions due to missing permissions like android.permission.ACCESS_WIFI_STATE.
  652. // Fall through and use just "WIFI"
  653. }
  654. } else if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
  655. networkID = "MOBILE";
  656. try {
  657. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  658. if (telephonyManager != null) {
  659. networkID += "-" + telephonyManager.getNetworkOperator();
  660. }
  661. } catch (java.lang.Exception e) {
  662. // May get exceptions due to missing permissions.
  663. // Fall through and use just "MOBILE"
  664. }
  665. }
  666. return networkID;
  667. }
  668. //----------------------------------------------------------------------------------------------
  669. // Psiphon Tunnel Core
  670. //----------------------------------------------------------------------------------------------
  671. private void startPsiphon(String embeddedServerEntries) throws Exception {
  672. stopPsiphon();
  673. mIsWaitingForNetworkConnectivity.set(false);
  674. mHostService.onDiagnosticMessage("starting Psiphon library");
  675. try {
  676. Psi.start(
  677. loadPsiphonConfig(mHostService.getContext()),
  678. embeddedServerEntries,
  679. "",
  680. new PsiphonProviderShim(this),
  681. isVpnMode(),
  682. false // Do not use IPv6 synthesizer for android
  683. );
  684. } catch (java.lang.Exception e) {
  685. throw new Exception("failed to start Psiphon library", e);
  686. }
  687. mHostService.onDiagnosticMessage("Psiphon library started");
  688. }
  689. private void stopPsiphon() {
  690. mHostService.onDiagnosticMessage("stopping Psiphon library");
  691. Psi.stop();
  692. mHostService.onDiagnosticMessage("Psiphon library stopped");
  693. }
  694. private String loadPsiphonConfig(Context context)
  695. throws IOException, JSONException, Exception {
  696. return buildPsiphonConfig(context, mHostService, mHostService.getPsiphonConfig(),
  697. mClientPlatformPrefix.get(), mClientPlatformSuffix.get(), isVpnMode(),
  698. mLocalSocksProxyPort.get());
  699. }
  700. private static String buildPsiphonConfig(Context context, HostLogger logger, String psiphonConfig,
  701. String clientPlatformPrefix, String clientPlatformSuffix,
  702. boolean isVpnMode, Integer localSocksProxyPort)
  703. throws IOException, JSONException, Exception {
  704. // Load settings from the raw resource JSON config file and
  705. // update as necessary. Then write JSON to disk for the Go client.
  706. JSONObject json = new JSONObject(psiphonConfig);
  707. // On Android, this directory must be set to the app private storage area.
  708. // The Psiphon library won't be able to use its current working directory
  709. // and the standard temporary directories do not exist.
  710. if (!json.has("DataRootDirectory")) {
  711. File dataRootDirectory = defaultDataRootDirectory(context);
  712. if (!dataRootDirectory.exists()) {
  713. boolean created = dataRootDirectory.mkdir();
  714. if (!created) {
  715. throw new Exception("failed to create data root directory: " + dataRootDirectory.getPath());
  716. }
  717. }
  718. json.put("DataRootDirectory", defaultDataRootDirectory(context));
  719. }
  720. // Migrate datastore files from legacy directory.
  721. if (!json.has("DataStoreDirectory")) {
  722. json.put("MigrateDataStoreDirectory", context.getFilesDir());
  723. }
  724. // Migrate remote server list downloads from legacy location.
  725. if (!json.has("RemoteServerListDownloadFilename")) {
  726. File remoteServerListDownload = new File(context.getFilesDir(), "remote_server_list");
  727. json.put("MigrateRemoteServerListDownloadFilename", remoteServerListDownload.getAbsolutePath());
  728. }
  729. // Migrate obfuscated server list download files from legacy directory.
  730. File oslDownloadDir = new File(context.getFilesDir(), "osl");
  731. json.put("MigrateObfuscatedServerListDownloadDirectory", oslDownloadDir.getAbsolutePath());
  732. // Continue to run indefinitely until connected
  733. if (!json.has("EstablishTunnelTimeoutSeconds")) {
  734. json.put("EstablishTunnelTimeoutSeconds", 0);
  735. }
  736. // This parameter is for stats reporting
  737. if (!json.has("TunnelWholeDevice")) {
  738. json.put("TunnelWholeDevice", isVpnMode ? 1 : 0);
  739. }
  740. json.put("EmitBytesTransferred", true);
  741. if (localSocksProxyPort != 0 && (!json.has("LocalSocksProxyPort") || json.getInt("LocalSocksProxyPort") == 0)) {
  742. // When mLocalSocksProxyPort is set, tun2socks is already configured
  743. // to use that port value. So we force use of the same port.
  744. // A side-effect of this is that changing the SOCKS port preference
  745. // has no effect with restartPsiphon(), a full stop() is necessary.
  746. json.put("LocalSocksProxyPort", localSocksProxyPort);
  747. }
  748. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  749. try {
  750. json.put(
  751. "TrustedCACertificatesFilename",
  752. setupTrustedCertificates(context, logger));
  753. } catch (Exception e) {
  754. logger.onDiagnosticMessage(e.getMessage());
  755. }
  756. }
  757. json.put("DeviceRegion", getDeviceRegion(context));
  758. StringBuilder clientPlatform = new StringBuilder();
  759. if (clientPlatformPrefix.length() > 0) {
  760. clientPlatform.append(clientPlatformPrefix);
  761. }
  762. clientPlatform.append("Android_");
  763. clientPlatform.append(Build.VERSION.RELEASE);
  764. clientPlatform.append("_");
  765. clientPlatform.append(context.getPackageName());
  766. if (clientPlatformSuffix.length() > 0) {
  767. clientPlatform.append(clientPlatformSuffix);
  768. }
  769. json.put("ClientPlatform", clientPlatform.toString().replaceAll("[^\\w\\-\\.]", "_"));
  770. return json.toString();
  771. }
  772. private void handlePsiphonNotice(String noticeJSON) {
  773. try {
  774. // All notices are sent on as diagnostic messages
  775. // except those that may contain private user data.
  776. boolean diagnostic = true;
  777. JSONObject notice = new JSONObject(noticeJSON);
  778. String noticeType = notice.getString("noticeType");
  779. if (noticeType.equals("Tunnels")) {
  780. int count = notice.getJSONObject("data").getInt("count");
  781. if (count == 0) {
  782. mHostService.onConnecting();
  783. } else if (count == 1) {
  784. if (isVpnMode() && mShouldRouteThroughTunnelAutomatically) {
  785. routeThroughTunnel();
  786. }
  787. mHostService.onConnected();
  788. }
  789. // count > 1 is an additional multi-tunnel establishment, and not reported.
  790. } else if (noticeType.equals("AvailableEgressRegions")) {
  791. JSONArray egressRegions = notice.getJSONObject("data").getJSONArray("regions");
  792. ArrayList<String> regions = new ArrayList<String>();
  793. for (int i=0; i<egressRegions.length(); i++) {
  794. regions.add(egressRegions.getString(i));
  795. }
  796. mHostService.onAvailableEgressRegions(regions);
  797. } else if (noticeType.equals("SocksProxyPortInUse")) {
  798. mHostService.onSocksProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  799. } else if (noticeType.equals("HttpProxyPortInUse")) {
  800. mHostService.onHttpProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  801. } else if (noticeType.equals("ListeningSocksProxyPort")) {
  802. int port = notice.getJSONObject("data").getInt("port");
  803. setLocalSocksProxyPort(port);
  804. mHostService.onListeningSocksProxyPort(port);
  805. } else if (noticeType.equals("ListeningHttpProxyPort")) {
  806. int port = notice.getJSONObject("data").getInt("port");
  807. mHostService.onListeningHttpProxyPort(port);
  808. } else if (noticeType.equals("UpstreamProxyError")) {
  809. mHostService.onUpstreamProxyError(notice.getJSONObject("data").getString("message"));
  810. } else if (noticeType.equals("ClientUpgradeDownloaded")) {
  811. mHostService.onClientUpgradeDownloaded(notice.getJSONObject("data").getString("filename"));
  812. } else if (noticeType.equals("ClientIsLatestVersion")) {
  813. mHostService.onClientIsLatestVersion();
  814. } else if (noticeType.equals("Homepage")) {
  815. mHostService.onHomepage(notice.getJSONObject("data").getString("url"));
  816. } else if (noticeType.equals("ClientRegion")) {
  817. mHostService.onClientRegion(notice.getJSONObject("data").getString("region"));
  818. } else if (noticeType.equals("SplitTunnelRegion")) {
  819. mHostService.onSplitTunnelRegion(notice.getJSONObject("data").getString("region"));
  820. } else if (noticeType.equals("Untunneled")) {
  821. mHostService.onUntunneledAddress(notice.getJSONObject("data").getString("address"));
  822. } else if (noticeType.equals("BytesTransferred")) {
  823. diagnostic = false;
  824. JSONObject data = notice.getJSONObject("data");
  825. mHostService.onBytesTransferred(data.getLong("sent"), data.getLong("received"));
  826. } else if (noticeType.equals("ActiveAuthorizationIDs")) {
  827. JSONArray activeAuthorizationIDs = notice.getJSONObject("data").getJSONArray("IDs");
  828. ArrayList<String> authorizations = new ArrayList<String>();
  829. for (int i=0; i<activeAuthorizationIDs.length(); i++) {
  830. authorizations.add(activeAuthorizationIDs.getString(i));
  831. }
  832. mHostService.onActiveAuthorizationIDs(authorizations);
  833. } else if (noticeType.equals("TrafficRateLimits")) {
  834. JSONObject data = notice.getJSONObject("data");
  835. mHostService.onTrafficRateLimits(
  836. data.getLong("upstreamBytesPerSecond"), data.getLong("downstreamBytesPerSecond"));
  837. } else if (noticeType.equals("Exiting")) {
  838. mHostService.onExiting();
  839. } else if (noticeType.equals("ActiveTunnel")) {
  840. if (isVpnMode()) {
  841. if (notice.getJSONObject("data").getBoolean("isTCS")) {
  842. disableUdpGwKeepalive();
  843. } else {
  844. enableUdpGwKeepalive();
  845. }
  846. }
  847. } else if (noticeType.equals("ApplicationParameter")) {
  848. mHostService.onApplicationParameter(
  849. notice.getJSONObject("data").getString("key"),
  850. notice.getJSONObject("data").get("value"));
  851. } else if (noticeType.equals("ServerAlert")) {
  852. mHostService.onServerAlert(
  853. notice.getJSONObject("data").getString("reason"),
  854. notice.getJSONObject("data").getString("subject"));
  855. }
  856. if (diagnostic) {
  857. String diagnosticMessage = noticeType + ": " + notice.getJSONObject("data").toString();
  858. mHostService.onDiagnosticMessage(diagnosticMessage);
  859. }
  860. } catch (JSONException e) {
  861. // Ignore notice
  862. }
  863. }
  864. private static String setupTrustedCertificates(Context context, HostLogger logger) throws Exception {
  865. // Copy the Android system CA store to a local, private cert bundle file.
  866. //
  867. // This results in a file that can be passed to SSL_CTX_load_verify_locations
  868. // for use with OpenSSL modes in tunnel-core.
  869. // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html
  870. //
  871. // TODO: to use the path mode of load_verify_locations would require emulating
  872. // the filename scheme used by c_rehash:
  873. // https://www.openssl.org/docs/manmaster/apps/c_rehash.html
  874. // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs
  875. File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE);
  876. final String errorMessage = "copy AndroidCAStore failed";
  877. try {
  878. File file = new File(directory, "certs.dat");
  879. // Pave a fresh copy on every run, which ensures we're not using old certs.
  880. // Note: assumes KeyStore doesn't return revoked certs.
  881. //
  882. // TODO: this takes under 1 second, but should we avoid repaving every time?
  883. file.delete();
  884. PrintStream output = null;
  885. try {
  886. output = new PrintStream(new FileOutputStream(file));
  887. KeyStore keyStore;
  888. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  889. keyStore = KeyStore.getInstance("AndroidCAStore");
  890. keyStore.load(null, null);
  891. } else {
  892. keyStore = KeyStore.getInstance("BKS");
  893. FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks");
  894. try {
  895. keyStore.load(inputStream, "changeit".toCharArray());
  896. } finally {
  897. if (inputStream != null) {
  898. inputStream.close();
  899. }
  900. }
  901. }
  902. Enumeration<String> aliases = keyStore.aliases();
  903. while (aliases.hasMoreElements()) {
  904. String alias = aliases.nextElement();
  905. X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
  906. output.println("-----BEGIN CERTIFICATE-----");
  907. String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8");
  908. // OpenSSL appears to reject the default linebreaking done by Base64.encode,
  909. // so we manually linebreak every 64 characters
  910. for (int i = 0; i < pemCert.length() ; i+= 64) {
  911. output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length())));
  912. }
  913. output.println("-----END CERTIFICATE-----");
  914. }
  915. logger.onDiagnosticMessage("prepared PsiphonCAStore");
  916. return file.getAbsolutePath();
  917. } finally {
  918. if (output != null) {
  919. output.close();
  920. }
  921. }
  922. } catch (KeyStoreException e) {
  923. throw new Exception(errorMessage, e);
  924. } catch (NoSuchAlgorithmException e) {
  925. throw new Exception(errorMessage, e);
  926. } catch (CertificateException e) {
  927. throw new Exception(errorMessage, e);
  928. } catch (IOException e) {
  929. throw new Exception(errorMessage, e);
  930. }
  931. }
  932. private static String getDeviceRegion(Context context) {
  933. String region = "";
  934. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  935. if (telephonyManager != null) {
  936. region = telephonyManager.getSimCountryIso();
  937. if (region == null) {
  938. region = "";
  939. }
  940. if (region.length() == 0 && telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
  941. region = telephonyManager.getNetworkCountryIso();
  942. if (region == null) {
  943. region = "";
  944. }
  945. }
  946. }
  947. if (region.length() == 0) {
  948. Locale defaultLocale = Locale.getDefault();
  949. if (defaultLocale != null) {
  950. region = defaultLocale.getCountry();
  951. }
  952. }
  953. return region.toUpperCase(Locale.US);
  954. }
  955. //----------------------------------------------------------------------------------------------
  956. // Tun2Socks
  957. //----------------------------------------------------------------------------------------------
  958. @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
  959. private void startTun2Socks(
  960. final ParcelFileDescriptor vpnInterfaceFileDescriptor,
  961. final int vpnInterfaceMTU,
  962. final String vpnIpAddress,
  963. final String vpnNetMask,
  964. final String socksServerAddress,
  965. final String udpgwServerAddress,
  966. final boolean udpgwTransparentDNS) {
  967. if (mTun2SocksThread != null) {
  968. return;
  969. }
  970. mTun2SocksThread = new Thread(new Runnable() {
  971. @Override
  972. public void run() {
  973. runTun2Socks(
  974. vpnInterfaceFileDescriptor.detachFd(),
  975. vpnInterfaceMTU,
  976. vpnIpAddress,
  977. vpnNetMask,
  978. socksServerAddress,
  979. udpgwServerAddress,
  980. udpgwTransparentDNS ? 1 : 0);
  981. }
  982. });
  983. mTun2SocksThread.start();
  984. mHostService.onDiagnosticMessage("tun2socks started");
  985. }
  986. private void stopTun2Socks() {
  987. if (mTun2SocksThread != null) {
  988. try {
  989. terminateTun2Socks();
  990. mTun2SocksThread.join();
  991. } catch (InterruptedException e) {
  992. Thread.currentThread().interrupt();
  993. }
  994. mTun2SocksThread = null;
  995. mHostService.onDiagnosticMessage("tun2socks stopped");
  996. }
  997. }
  998. public static void logTun2Socks(String level, String channel, String msg) {
  999. String logMsg = "tun2socks: " + level + "(" + channel + "): " + msg;
  1000. mPsiphonTunnel.mHostService.onDiagnosticMessage(logMsg);
  1001. }
  1002. private native static int runTun2Socks(
  1003. int vpnInterfaceFileDescriptor,
  1004. int vpnInterfaceMTU,
  1005. String vpnIpAddress,
  1006. String vpnNetMask,
  1007. String socksServerAddress,
  1008. String udpgwServerAddress,
  1009. int udpgwTransparentDNS);
  1010. private native static int terminateTun2Socks();
  1011. private native static int enableUdpGwKeepalive();
  1012. private native static int disableUdpGwKeepalive();
  1013. //----------------------------------------------------------------------------------------------
  1014. // Implementation: Network Utils
  1015. //----------------------------------------------------------------------------------------------
  1016. private static boolean hasNetworkConnectivity(Context context) {
  1017. ConnectivityManager connectivityManager =
  1018. (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1019. if (connectivityManager == null) {
  1020. return false;
  1021. }
  1022. NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
  1023. return networkInfo != null && networkInfo.isConnected();
  1024. }
  1025. private static class PrivateAddress {
  1026. final public String mIpAddress;
  1027. final public String mSubnet;
  1028. final public int mPrefixLength;
  1029. final public String mRouter;
  1030. public PrivateAddress(String ipAddress, String subnet, int prefixLength, String router) {
  1031. mIpAddress = ipAddress;
  1032. mSubnet = subnet;
  1033. mPrefixLength = prefixLength;
  1034. mRouter = router;
  1035. }
  1036. }
  1037. private static PrivateAddress selectPrivateAddress() throws Exception {
  1038. // Select one of 10.0.0.1, 172.16.0.1, or 192.168.0.1 depending on
  1039. // which private address range isn't in use.
  1040. Map<String, PrivateAddress> candidates = new HashMap<String, PrivateAddress>();
  1041. candidates.put( "10", new PrivateAddress("10.0.0.1", "10.0.0.0", 8, "10.0.0.2"));
  1042. candidates.put("172", new PrivateAddress("172.16.0.1", "172.16.0.0", 12, "172.16.0.2"));
  1043. candidates.put("192", new PrivateAddress("192.168.0.1", "192.168.0.0", 16, "192.168.0.2"));
  1044. candidates.put("169", new PrivateAddress("169.254.1.1", "169.254.1.0", 24, "169.254.1.2"));
  1045. Enumeration<NetworkInterface> netInterfaces;
  1046. try {
  1047. netInterfaces = NetworkInterface.getNetworkInterfaces();
  1048. } catch (SocketException e) {
  1049. throw new Exception("selectPrivateAddress failed", e);
  1050. }
  1051. if (netInterfaces == null) {
  1052. throw new Exception("no network interfaces found");
  1053. }
  1054. for (NetworkInterface netInterface : Collections.list(netInterfaces)) {
  1055. for (InetAddress inetAddress : Collections.list(netInterface.getInetAddresses())) {
  1056. if (inetAddress instanceof Inet4Address) {
  1057. String ipAddress = inetAddress.getHostAddress();
  1058. if (ipAddress.startsWith("10.")) {
  1059. candidates.remove("10");
  1060. }
  1061. else if (
  1062. ipAddress.length() >= 6 &&
  1063. ipAddress.substring(0, 6).compareTo("172.16") >= 0 &&
  1064. ipAddress.substring(0, 6).compareTo("172.31") <= 0) {
  1065. candidates.remove("172");
  1066. }
  1067. else if (ipAddress.startsWith("192.168")) {
  1068. candidates.remove("192");
  1069. }
  1070. }
  1071. }
  1072. }
  1073. if (candidates.size() > 0) {
  1074. return candidates.values().iterator().next();
  1075. }
  1076. throw new Exception("no private address available");
  1077. }
  1078. public static String getFirstActiveNetworkDnsResolver(Context context)
  1079. throws Exception {
  1080. Collection<InetAddress> dnsResolvers = getActiveNetworkDnsResolvers(context);
  1081. if (!dnsResolvers.isEmpty()) {
  1082. // strip the leading slash e.g., "/192.168.1.1"
  1083. String dnsResolver = dnsResolvers.iterator().next().toString();
  1084. if (dnsResolver.startsWith("/")) {
  1085. dnsResolver = dnsResolver.substring(1);
  1086. }
  1087. return dnsResolver;
  1088. }
  1089. throw new Exception("no active network DNS resolver");
  1090. }
  1091. private static Collection<InetAddress> getActiveNetworkDnsResolvers(Context context)
  1092. throws Exception {
  1093. final String errorMessage = "getActiveNetworkDnsResolvers failed";
  1094. ArrayList<InetAddress> dnsAddresses = new ArrayList<InetAddress>();
  1095. ConnectivityManager connectivityManager =
  1096. (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  1097. if (connectivityManager == null) {
  1098. throw new Exception(errorMessage, new Throwable("couldn't get ConnectivityManager system service"));
  1099. }
  1100. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  1101. NetworkRequest networkRequest = new NetworkRequest.Builder().build();
  1102. final CountDownLatch countDownLatch = new CountDownLatch(1);
  1103. try {
  1104. ConnectivityManager.NetworkCallback networkCallback =
  1105. new ConnectivityManager.NetworkCallback() {
  1106. @Override
  1107. public void onLinkPropertiesChanged(Network network,
  1108. LinkProperties linkProperties) {
  1109. dnsAddresses.addAll(linkProperties.getDnsServers());
  1110. countDownLatch.countDown();
  1111. }
  1112. };
  1113. connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
  1114. countDownLatch.await(1, TimeUnit.SECONDS);
  1115. connectivityManager.unregisterNetworkCallback(networkCallback);
  1116. } catch (RuntimeException ignored) {
  1117. // Failed to register network callback
  1118. } catch (InterruptedException e) {
  1119. Thread.currentThread().interrupt();
  1120. }
  1121. if (!dnsAddresses.isEmpty()) {
  1122. return dnsAddresses;
  1123. }
  1124. }
  1125. try {
  1126. // Hidden API
  1127. // - only available in Android 4.0+
  1128. // - no guarantee will be available beyond 4.2, or on all vendor devices
  1129. Class<?> LinkPropertiesClass = Class.forName("android.net.LinkProperties");
  1130. Method getActiveLinkPropertiesMethod = ConnectivityManager.class.getMethod("getActiveLinkProperties", new Class []{});
  1131. Object linkProperties = getActiveLinkPropertiesMethod.invoke(connectivityManager);
  1132. if (linkProperties != null) {
  1133. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  1134. Method getDnsesMethod = LinkPropertiesClass.getMethod("getDnses", new Class []{});
  1135. Collection<?> dnses = (Collection<?>)getDnsesMethod.invoke(linkProperties);
  1136. for (Object dns : dnses) {
  1137. dnsAddresses.add((InetAddress)dns);
  1138. }
  1139. } else {
  1140. // LinkProperties is public in API 21 (and the DNS function signature has changed)
  1141. for (InetAddress dns : ((LinkProperties)linkProperties).getDnsServers()) {
  1142. dnsAddresses.add(dns);
  1143. }
  1144. }
  1145. }
  1146. } catch (ClassNotFoundException e) {
  1147. throw new Exception(errorMessage, e);
  1148. } catch (NoSuchMethodException e) {
  1149. throw new Exception(errorMessage, e);
  1150. } catch (IllegalArgumentException e) {
  1151. throw new Exception(errorMessage, e);
  1152. } catch (IllegalAccessException e) {
  1153. throw new Exception(errorMessage, e);
  1154. } catch (InvocationTargetException e) {
  1155. throw new Exception(errorMessage, e);
  1156. } catch (NullPointerException e) {
  1157. throw new Exception(errorMessage, e);
  1158. }
  1159. return dnsAddresses;
  1160. }
  1161. //----------------------------------------------------------------------------------------------
  1162. // Exception
  1163. //----------------------------------------------------------------------------------------------
  1164. public static class Exception extends java.lang.Exception {
  1165. private static final long serialVersionUID = 1L;
  1166. public Exception(String message) {
  1167. super(message);
  1168. }
  1169. public Exception(String message, Throwable cause) {
  1170. super(message + ": " + cause.getMessage());
  1171. }
  1172. }
  1173. }