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