PsiphonTunnel.java 66 KB

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