PsiphonTunnel.java 83 KB

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