PsiphonTunnel.java 84 KB

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