PsiphonTunnel.java 83 KB

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