PsiphonTunnel.java 68 KB

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