PsiphonTunnel.java 85 KB

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