PsiphonTunnel.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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.wifi.WifiManager;
  24. import android.net.wifi.WifiInfo;
  25. import android.net.LinkProperties;
  26. import android.net.NetworkInfo;
  27. import android.net.VpnService;
  28. import android.os.Build;
  29. import android.os.ParcelFileDescriptor;
  30. import android.telephony.TelephonyManager;
  31. import android.util.Base64;
  32. import org.apache.http.conn.util.InetAddressUtils;
  33. import org.json.JSONArray;
  34. import org.json.JSONException;
  35. import org.json.JSONObject;
  36. import java.io.File;
  37. import java.io.FileInputStream;
  38. import java.io.FileOutputStream;
  39. import java.io.IOException;
  40. import java.io.PrintStream;
  41. import java.lang.reflect.InvocationTargetException;
  42. import java.lang.reflect.Method;
  43. import java.net.InetAddress;
  44. import java.net.NetworkInterface;
  45. import java.net.SocketException;
  46. import java.security.KeyStore;
  47. import java.security.KeyStoreException;
  48. import java.security.NoSuchAlgorithmException;
  49. import java.security.cert.CertificateException;
  50. import java.security.cert.X509Certificate;
  51. import java.util.ArrayList;
  52. import java.util.Collection;
  53. import java.util.Collections;
  54. import java.util.Enumeration;
  55. import java.util.HashMap;
  56. import java.util.List;
  57. import java.util.Locale;
  58. import java.util.Map;
  59. import java.util.concurrent.atomic.AtomicBoolean;
  60. import java.util.concurrent.atomic.AtomicInteger;
  61. import java.util.concurrent.atomic.AtomicReference;
  62. import go.psi.Psi;
  63. public class PsiphonTunnel extends Psi.PsiphonProvider.Stub {
  64. public interface HostService {
  65. public String getAppName();
  66. public Context getContext();
  67. public Object getVpnService(); // Object must be a VpnService (Android < 4 cannot reference this class name)
  68. public Object newVpnServiceBuilder(); // Object must be a VpnService.Builder (Android < 4 cannot reference this class name)
  69. public String getPsiphonConfig();
  70. public void onDiagnosticMessage(String message);
  71. public void onAvailableEgressRegions(List<String> regions);
  72. public void onSocksProxyPortInUse(int port);
  73. public void onHttpProxyPortInUse(int port);
  74. public void onListeningSocksProxyPort(int port);
  75. public void onListeningHttpProxyPort(int port);
  76. public void onUpstreamProxyError(String message);
  77. public void onConnecting();
  78. public void onConnected();
  79. public void onHomepage(String url);
  80. public void onClientRegion(String region);
  81. public void onClientUpgradeDownloaded(String filename);
  82. public void onClientIsLatestVersion();
  83. public void onSplitTunnelRegion(String region);
  84. public void onUntunneledAddress(String address);
  85. public void onBytesTransferred(long sent, long received);
  86. public void onStartedWaitingForNetworkConnectivity();
  87. public void onActiveAuthorizationIDs(List<String> authorizations);
  88. public void onExiting();
  89. }
  90. private final HostService mHostService;
  91. private AtomicBoolean mVpnMode;
  92. private PrivateAddress mPrivateAddress;
  93. private AtomicReference<ParcelFileDescriptor> mTunFd;
  94. private AtomicInteger mLocalSocksProxyPort;
  95. private AtomicBoolean mRoutingThroughTunnel;
  96. private Thread mTun2SocksThread;
  97. private AtomicBoolean mIsWaitingForNetworkConnectivity;
  98. private AtomicReference<String> mClientPlatformPrefix;
  99. private AtomicReference<String> mClientPlatformSuffix;
  100. // mUsePacketTunnel specifies whether to use the packet
  101. // tunnel instead of tun2socks; currently this is for
  102. // testing only and is disabled.
  103. private boolean mUsePacketTunnel = false;
  104. // Only one PsiphonVpn instance may exist at a time, as the underlying
  105. // go.psi.Psi and tun2socks implementations each contain global state.
  106. private static PsiphonTunnel mPsiphonTunnel;
  107. public static synchronized PsiphonTunnel newPsiphonTunnel(HostService hostService) {
  108. if (mPsiphonTunnel != null) {
  109. mPsiphonTunnel.stop();
  110. }
  111. // Load the native go code embedded in psi.aar
  112. System.loadLibrary("gojni");
  113. mPsiphonTunnel = new PsiphonTunnel(hostService);
  114. return mPsiphonTunnel;
  115. }
  116. private PsiphonTunnel(HostService hostService) {
  117. mHostService = hostService;
  118. mVpnMode = new AtomicBoolean(false);
  119. mTunFd = new AtomicReference<ParcelFileDescriptor>();
  120. mLocalSocksProxyPort = new AtomicInteger(0);
  121. mRoutingThroughTunnel = new AtomicBoolean(false);
  122. mIsWaitingForNetworkConnectivity = new AtomicBoolean(false);
  123. mClientPlatformPrefix = new AtomicReference<String>("");
  124. mClientPlatformSuffix = new AtomicReference<String>("");
  125. }
  126. public Object clone() throws CloneNotSupportedException {
  127. throw new CloneNotSupportedException();
  128. }
  129. //----------------------------------------------------------------------------------------------
  130. // Public API
  131. //----------------------------------------------------------------------------------------------
  132. // To start, call in sequence: startRouting(), then startTunneling(). After startRouting()
  133. // succeeds, the caller must call stop() to clean up. These functions should not be called
  134. // concurrently. Do not call stop() while startRouting() or startTunneling() is in progress.
  135. // Returns true when the VPN routing is established; returns false if the VPN could not
  136. // be started due to lack of prepare or revoked permissions (called should re-prepare and
  137. // try again); throws exception for other error conditions.
  138. public synchronized boolean startRouting() throws Exception {
  139. // Note: tun2socks is loaded even in mUsePacketTunnel mode,
  140. // as disableUdpGwKeepalive will still be called.
  141. // Load tun2socks library embedded in the aar
  142. // If this method is called more than once with the same library name, the second and subsequent calls are ignored.
  143. // http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#loadLibrary%28java.lang.String%29
  144. System.loadLibrary("tun2socks");
  145. return startVpn();
  146. }
  147. // Throws an exception in error conditions. In the case of an exception, the routing
  148. // started by startRouting() is not immediately torn down (this allows the caller to control
  149. // exactly when VPN routing is stopped); caller should call stop() to clean up.
  150. public synchronized void startTunneling(String embeddedServerEntries) throws Exception {
  151. startPsiphon(embeddedServerEntries);
  152. }
  153. // Note: to avoid deadlock, do not call directly from a HostService callback;
  154. // instead post to a Handler if necessary to trigger from a HostService callback.
  155. // For example, deadlock can occur when a Notice callback invokes stop() since stop() calls
  156. // Psi.Stop() which will block waiting for tunnel-core Controller to shutdown which in turn
  157. // waits for Notice callback invoker to stop, meanwhile the callback thread has blocked waiting
  158. // for stop().
  159. public synchronized void stop() {
  160. stopVpn();
  161. stopPsiphon();
  162. mVpnMode.set(false);
  163. mLocalSocksProxyPort.set(0);
  164. }
  165. // Note: same deadlock note as stop().
  166. public synchronized void restartPsiphon() throws Exception {
  167. stopPsiphon();
  168. startPsiphon("");
  169. }
  170. public void setClientPlatformAffixes(String prefix, String suffix) {
  171. mClientPlatformPrefix.set(prefix);
  172. mClientPlatformSuffix.set(suffix);
  173. }
  174. // Writes Go runtime profile information to a set of files in the specifiec output directory.
  175. // cpuSampleDurationSeconds and blockSampleDurationSeconds determines how to long to wait and
  176. // sample profiles that require active sampling. When set to 0, these profiles are skipped.
  177. public void writeRuntimeProfiles(String outputDirectory, int cpuSampleDurationSeconnds, int blockSampleDurationSeconds) {
  178. Psi.WriteRuntimeProfiles(outputDirectory, cpuSampleDurationSeconnds, blockSampleDurationSeconds);
  179. }
  180. //----------------------------------------------------------------------------------------------
  181. // VPN Routing
  182. //----------------------------------------------------------------------------------------------
  183. private final static String VPN_INTERFACE_NETMASK = "255.255.255.0";
  184. private final static int VPN_INTERFACE_MTU = 1500;
  185. private final static int UDPGW_SERVER_PORT = 7300;
  186. private final static String DEFAULT_PRIMARY_DNS_SERVER = "8.8.4.4";
  187. private final static String DEFAULT_SECONDARY_DNS_SERVER = "8.8.8.8";
  188. // Note: Atomic variables used for getting/setting local proxy port, routing flag, and
  189. // tun fd, as these functions may be called via PsiphonProvider callbacks. Do not use
  190. // synchronized functions as stop() is synchronized and a deadlock is possible as callbacks
  191. // can be called while stop holds the lock.
  192. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  193. private boolean startVpn() throws Exception {
  194. mVpnMode.set(true);
  195. mPrivateAddress = selectPrivateAddress();
  196. Locale previousLocale = Locale.getDefault();
  197. final String errorMessage = "startVpn failed";
  198. try {
  199. // Workaround for https://code.google.com/p/android/issues/detail?id=61096
  200. Locale.setDefault(new Locale("en"));
  201. int mtu = VPN_INTERFACE_MTU;
  202. String dnsResolver = mPrivateAddress.mRouter;
  203. if (mUsePacketTunnel) {
  204. mtu = (int)Psi.GetPacketTunnelMTU();
  205. dnsResolver = Psi.GetPacketTunnelDNSResolverIPv4Address();
  206. }
  207. ParcelFileDescriptor tunFd =
  208. ((VpnService.Builder) mHostService.newVpnServiceBuilder())
  209. .setSession(mHostService.getAppName())
  210. .setMtu(mtu)
  211. .addAddress(mPrivateAddress.mIpAddress, mPrivateAddress.mPrefixLength)
  212. .addRoute("0.0.0.0", 0)
  213. .addRoute(mPrivateAddress.mSubnet, mPrivateAddress.mPrefixLength)
  214. .addDnsServer(dnsResolver)
  215. .establish();
  216. if (tunFd == null) {
  217. // As per http://developer.android.com/reference/android/net/VpnService.Builder.html#establish%28%29,
  218. // this application is no longer prepared or was revoked.
  219. return false;
  220. }
  221. mTunFd.set(tunFd);
  222. mRoutingThroughTunnel.set(false);
  223. mHostService.onDiagnosticMessage("VPN established");
  224. } catch(IllegalArgumentException e) {
  225. throw new Exception(errorMessage, e);
  226. } catch(IllegalStateException e) {
  227. throw new Exception(errorMessage, e);
  228. } catch(SecurityException e) {
  229. throw new Exception(errorMessage, e);
  230. } finally {
  231. // Restore the original locale.
  232. Locale.setDefault(previousLocale);
  233. }
  234. return true;
  235. }
  236. private boolean isVpnMode() {
  237. return mVpnMode.get();
  238. }
  239. private void setLocalSocksProxyPort(int port) {
  240. mLocalSocksProxyPort.set(port);
  241. }
  242. private void routeThroughTunnel() {
  243. if (!mRoutingThroughTunnel.compareAndSet(false, true)) {
  244. return;
  245. }
  246. if (!mUsePacketTunnel) {
  247. ParcelFileDescriptor tunFd = mTunFd.getAndSet(null);
  248. if (tunFd == null) {
  249. return;
  250. }
  251. String socksServerAddress = "127.0.0.1:" + Integer.toString(mLocalSocksProxyPort.get());
  252. String udpgwServerAddress = "127.0.0.1:" + Integer.toString(UDPGW_SERVER_PORT);
  253. startTun2Socks(
  254. tunFd,
  255. VPN_INTERFACE_MTU,
  256. mPrivateAddress.mRouter,
  257. VPN_INTERFACE_NETMASK,
  258. socksServerAddress,
  259. udpgwServerAddress,
  260. true);
  261. }
  262. mHostService.onDiagnosticMessage("routing through tunnel");
  263. // TODO: should double-check tunnel routing; see:
  264. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/1dc5e4257dca99790109f3bf374e8ab3a0ead4d7/Android/PsiphonAndroidLibrary/src/com/psiphon3/psiphonlibrary/TunnelCore.java?at=default#cl-779
  265. }
  266. private void stopVpn() {
  267. if (!mUsePacketTunnel) {
  268. stopTun2Socks();
  269. }
  270. ParcelFileDescriptor tunFd = mTunFd.getAndSet(null);
  271. if (tunFd != null) {
  272. try {
  273. tunFd.close();
  274. } catch (IOException e) {
  275. }
  276. }
  277. mRoutingThroughTunnel.set(false);
  278. }
  279. //----------------------------------------------------------------------------------------------
  280. // PsiphonProvider (Core support) interface implementation
  281. //----------------------------------------------------------------------------------------------
  282. @Override
  283. public void Notice(String noticeJSON) {
  284. handlePsiphonNotice(noticeJSON);
  285. }
  286. @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  287. @Override
  288. public String BindToDevice(long fileDescriptor) throws Exception {
  289. if (!((VpnService)mHostService.getVpnService()).protect((int)fileDescriptor)) {
  290. throw new Exception("protect socket failed");
  291. }
  292. return "";
  293. }
  294. @Override
  295. public long HasNetworkConnectivity() {
  296. boolean hasConnectivity = hasNetworkConnectivity(mHostService.getContext());
  297. boolean wasWaitingForNetworkConnectivity = mIsWaitingForNetworkConnectivity.getAndSet(!hasConnectivity);
  298. if (!hasConnectivity && !wasWaitingForNetworkConnectivity) {
  299. // HasNetworkConnectivity may be called many times, but only call
  300. // onStartedWaitingForNetworkConnectivity once per loss of connectivity,
  301. // so the HostService may log a single message.
  302. mHostService.onStartedWaitingForNetworkConnectivity();
  303. }
  304. // TODO: change to bool return value once gobind supports that type
  305. return hasConnectivity ? 1 : 0;
  306. }
  307. @Override
  308. public String GetPrimaryDnsServer() {
  309. String dnsResolver = null;
  310. try {
  311. dnsResolver = getFirstActiveNetworkDnsResolver(mHostService.getContext());
  312. } catch (Exception e) {
  313. mHostService.onDiagnosticMessage("failed to get active network DNS resolver: " + e.getMessage());
  314. dnsResolver = DEFAULT_PRIMARY_DNS_SERVER;
  315. }
  316. return dnsResolver;
  317. }
  318. @Override
  319. public String GetSecondaryDnsServer() {
  320. return DEFAULT_SECONDARY_DNS_SERVER;
  321. }
  322. @Override
  323. public String IPv6Synthesize(String IPv4Addr) { return IPv4Addr; }
  324. @Override
  325. public String GetNetworkID() {
  326. // The network ID contains potential PII. In tunnel-core, the network ID
  327. // is used only locally in the client and not sent to the server.
  328. //
  329. // See network ID requirements here:
  330. // https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  331. String networkID = "UNKNOWN";
  332. Context context = mHostService.getContext();
  333. ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  334. NetworkInfo activeNetworkInfo = null;
  335. try {
  336. activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  337. } catch (java.lang.Exception e) {
  338. // May get exceptions due to missing permissions like android.permission.ACCESS_NETWORK_STATE.
  339. // Apps using the Psiphon Library and lacking android.permission.ACCESS_NETWORK_STATE will
  340. // proceed and use tactics, but with "UNKNOWN" as the sole network ID.
  341. }
  342. if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
  343. networkID = "WIFI";
  344. try {
  345. WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
  346. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  347. if (wifiInfo != null) {
  348. String wifiNetworkID = wifiInfo.getBSSID();
  349. if (wifiNetworkID.equals("02:00:00:00:00:00")) {
  350. // "02:00:00:00:00:00" is reported when the app does not have the ACCESS_COARSE_LOCATION permission:
  351. // https://developer.android.com/about/versions/marshmallow/android-6.0-changes#behavior-hardware-id
  352. // The Psiphon client should allow the user to opt-in to this permission. If they decline, fail over
  353. // to using the WiFi IP address.
  354. wifiNetworkID = String.valueOf(wifiInfo.getIpAddress());
  355. }
  356. networkID += "-" + wifiNetworkID;
  357. }
  358. } catch (java.lang.Exception e) {
  359. // May get exceptions due to missing permissions like android.permission.ACCESS_WIFI_STATE.
  360. // Fall through and use just "WIFI"
  361. }
  362. } else if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
  363. networkID = "MOBILE";
  364. try {
  365. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  366. if (telephonyManager != null) {
  367. networkID += "-" + telephonyManager.getNetworkOperator();
  368. }
  369. } catch (java.lang.Exception e) {
  370. // May get exceptions due to missing permissions.
  371. // Fall through and use just "MOBILE"
  372. }
  373. }
  374. return networkID;
  375. }
  376. //----------------------------------------------------------------------------------------------
  377. // Psiphon Tunnel Core
  378. //----------------------------------------------------------------------------------------------
  379. private void startPsiphon(String embeddedServerEntries) throws Exception {
  380. stopPsiphon();
  381. mHostService.onDiagnosticMessage("starting Psiphon library");
  382. // In packet tunnel mode, Psi.Start will dup the tun file descriptor
  383. // passed in via the config. So here we "check out" mTunFd, to ensure
  384. // it can't be closed before it's duplicated. (This would only happen
  385. // if stop() is called concurrently with startTunneling(), which should
  386. // not be done -- this could also cause file descriptor issues in
  387. // tun2socks mode. With the "check out", a closed and recycled file
  388. // descriptor will not be copied; but a different race condition takes
  389. // the place of that one: stop() may fail to close the tun fd. So the
  390. // prohibition on concurrent calls remains.)
  391. //
  392. // In tun2socks mode, the ownership of the fd is transferred to tun2socks.
  393. // In packet tunnel mode, tunnel code dups the fd and manages that copy
  394. // while PsiphonTunnel retains ownership of the original mTunFd copy. Both
  395. // file descriptors must be closed to halt VpnService, and stop() does
  396. // this.
  397. ParcelFileDescriptor tunFd = null;
  398. int fd = -1;
  399. if (mUsePacketTunnel) {
  400. tunFd = mTunFd.getAndSet(null);
  401. if (tunFd != null) {
  402. fd = tunFd.getFd();
  403. }
  404. }
  405. try {
  406. Psi.Start(
  407. loadPsiphonConfig(mHostService.getContext(), fd),
  408. embeddedServerEntries,
  409. "",
  410. this,
  411. isVpnMode(),
  412. false // Do not use IPv6 synthesizer for android
  413. );
  414. } catch (java.lang.Exception e) {
  415. throw new Exception("failed to start Psiphon library", e);
  416. } finally {
  417. if (mUsePacketTunnel) {
  418. mTunFd.getAndSet(tunFd);
  419. }
  420. }
  421. mHostService.onDiagnosticMessage("Psiphon library started");
  422. }
  423. private void stopPsiphon() {
  424. mHostService.onDiagnosticMessage("stopping Psiphon library");
  425. Psi.Stop();
  426. mHostService.onDiagnosticMessage("Psiphon library stopped");
  427. }
  428. private String loadPsiphonConfig(Context context, int tunFd)
  429. throws IOException, JSONException {
  430. // Load settings from the raw resource JSON config file and
  431. // update as necessary. Then write JSON to disk for the Go client.
  432. JSONObject json = new JSONObject(mHostService.getPsiphonConfig());
  433. // On Android, this directory must be set to the app private storage area.
  434. // The Psiphon library won't be able to use its current working directory
  435. // and the standard temporary directories do not exist.
  436. if (!json.has("DataStoreDirectory")) {
  437. json.put("DataStoreDirectory", context.getFilesDir());
  438. }
  439. if (!json.has("RemoteServerListDownloadFilename")) {
  440. File remoteServerListDownload = new File(context.getFilesDir(), "remote_server_list");
  441. json.put("RemoteServerListDownloadFilename", remoteServerListDownload.getAbsolutePath());
  442. }
  443. File oslDownloadDir = new File(context.getFilesDir(), "osl");
  444. if (!oslDownloadDir.exists()
  445. && !oslDownloadDir.mkdirs()) {
  446. // Failed to create osl directory
  447. // TODO: proceed anyway?
  448. throw new IOException("failed to create OSL download directory");
  449. }
  450. json.put("ObfuscatedServerListDownloadDirectory", oslDownloadDir.getAbsolutePath());
  451. // Note: onConnecting/onConnected logic assumes 1 tunnel connection
  452. json.put("TunnelPoolSize", 1);
  453. // Continue to run indefinitely until connected
  454. if (!json.has("EstablishTunnelTimeoutSeconds")) {
  455. json.put("EstablishTunnelTimeoutSeconds", 0);
  456. }
  457. // This parameter is for stats reporting
  458. if (!json.has("TunnelWholeDevice")) {
  459. json.put("TunnelWholeDevice", isVpnMode() ? 1 : 0);
  460. }
  461. json.put("EmitBytesTransferred", true);
  462. if (mLocalSocksProxyPort.get() != 0 && (!json.has("LocalSocksProxyPort") || json.getInt("LocalSocksProxyPort") == 0)) {
  463. // When mLocalSocksProxyPort is set, tun2socks is already configured
  464. // to use that port value. So we force use of the same port.
  465. // A side-effect of this is that changing the SOCKS port preference
  466. // has no effect with restartPsiphon(), a full stop() is necessary.
  467. json.put("LocalSocksProxyPort", mLocalSocksProxyPort);
  468. }
  469. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  470. try {
  471. json.put(
  472. "TrustedCACertificatesFilename",
  473. setupTrustedCertificates(mHostService.getContext()));
  474. } catch (Exception e) {
  475. mHostService.onDiagnosticMessage(e.getMessage());
  476. }
  477. }
  478. json.put("DeviceRegion", getDeviceRegion(mHostService.getContext()));
  479. if (mUsePacketTunnel) {
  480. json.put("PacketTunnelTunFileDescriptor", tunFd);
  481. json.put("DisableLocalSocksProxy", true);
  482. json.put("DisableLocalHTTPProxy", true);
  483. }
  484. StringBuilder clientPlatform = new StringBuilder();
  485. String prefix = mClientPlatformPrefix.get();
  486. if (prefix.length() > 0) {
  487. clientPlatform.append(prefix);
  488. }
  489. clientPlatform.append("Android_");
  490. clientPlatform.append(Build.VERSION.RELEASE);
  491. clientPlatform.append("_");
  492. clientPlatform.append(mHostService.getContext().getPackageName());
  493. String suffix = mClientPlatformSuffix.get();
  494. if (suffix.length() > 0) {
  495. clientPlatform.append(suffix);
  496. }
  497. json.put("ClientPlatform", clientPlatform.toString().replaceAll("[^\\w\\-\\.]", "_"));
  498. return json.toString();
  499. }
  500. private void handlePsiphonNotice(String noticeJSON) {
  501. try {
  502. // All notices are sent on as diagnostic messages
  503. // except those that may contain private user data.
  504. boolean diagnostic = true;
  505. JSONObject notice = new JSONObject(noticeJSON);
  506. String noticeType = notice.getString("noticeType");
  507. if (noticeType.equals("Tunnels")) {
  508. int count = notice.getJSONObject("data").getInt("count");
  509. if (count > 0) {
  510. if (isVpnMode()) {
  511. routeThroughTunnel();
  512. }
  513. mHostService.onConnected();
  514. } else {
  515. mHostService.onConnecting();
  516. }
  517. } else if (noticeType.equals("AvailableEgressRegions")) {
  518. JSONArray egressRegions = notice.getJSONObject("data").getJSONArray("regions");
  519. ArrayList<String> regions = new ArrayList<String>();
  520. for (int i=0; i<egressRegions.length(); i++) {
  521. regions.add(egressRegions.getString(i));
  522. }
  523. mHostService.onAvailableEgressRegions(regions);
  524. } else if (noticeType.equals("SocksProxyPortInUse")) {
  525. mHostService.onSocksProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  526. } else if (noticeType.equals("HttpProxyPortInUse")) {
  527. mHostService.onHttpProxyPortInUse(notice.getJSONObject("data").getInt("port"));
  528. } else if (noticeType.equals("ListeningSocksProxyPort")) {
  529. int port = notice.getJSONObject("data").getInt("port");
  530. setLocalSocksProxyPort(port);
  531. mHostService.onListeningSocksProxyPort(port);
  532. } else if (noticeType.equals("ListeningHttpProxyPort")) {
  533. int port = notice.getJSONObject("data").getInt("port");
  534. mHostService.onListeningHttpProxyPort(port);
  535. } else if (noticeType.equals("UpstreamProxyError")) {
  536. mHostService.onUpstreamProxyError(notice.getJSONObject("data").getString("message"));
  537. } else if (noticeType.equals("ClientUpgradeDownloaded")) {
  538. mHostService.onClientUpgradeDownloaded(notice.getJSONObject("data").getString("filename"));
  539. } else if (noticeType.equals("ClientIsLatestVersion")) {
  540. mHostService.onClientIsLatestVersion();
  541. } else if (noticeType.equals("Homepage")) {
  542. mHostService.onHomepage(notice.getJSONObject("data").getString("url"));
  543. } else if (noticeType.equals("ClientRegion")) {
  544. mHostService.onClientRegion(notice.getJSONObject("data").getString("region"));
  545. } else if (noticeType.equals("SplitTunnelRegion")) {
  546. mHostService.onSplitTunnelRegion(notice.getJSONObject("data").getString("region"));
  547. } else if (noticeType.equals("Untunneled")) {
  548. mHostService.onUntunneledAddress(notice.getJSONObject("data").getString("address"));
  549. } else if (noticeType.equals("BytesTransferred")) {
  550. diagnostic = false;
  551. JSONObject data = notice.getJSONObject("data");
  552. mHostService.onBytesTransferred(data.getLong("sent"), data.getLong("received"));
  553. } else if (noticeType.equals("ActiveAuthorizationIDs")) {
  554. JSONArray activeAuthorizationIDs = notice.getJSONObject("data").getJSONArray("IDs");
  555. ArrayList<String> authorizations = new ArrayList<String>();
  556. for (int i=0; i<activeAuthorizationIDs.length(); i++) {
  557. authorizations.add(activeAuthorizationIDs.getString(i));
  558. }
  559. mHostService.onActiveAuthorizationIDs(authorizations);
  560. } else if (noticeType.equals("Exiting")) {
  561. mHostService.onExiting();
  562. } else if (noticeType.equals("ActiveTunnel")) {
  563. if (isVpnMode()) {
  564. if (notice.getJSONObject("data").getBoolean("isTCS")) {
  565. disableUdpGwKeepalive();
  566. } else {
  567. enableUdpGwKeepalive();
  568. }
  569. }
  570. }
  571. if (diagnostic) {
  572. String diagnosticMessage = noticeType + ": " + notice.getJSONObject("data").toString();
  573. mHostService.onDiagnosticMessage(diagnosticMessage);
  574. }
  575. } catch (JSONException e) {
  576. // Ignore notice
  577. }
  578. }
  579. private String setupTrustedCertificates(Context context) throws Exception {
  580. // Copy the Android system CA store to a local, private cert bundle file.
  581. //
  582. // This results in a file that can be passed to SSL_CTX_load_verify_locations
  583. // for use with OpenSSL modes in tunnel-core.
  584. // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html
  585. //
  586. // TODO: to use the path mode of load_verify_locations would require emulating
  587. // the filename scheme used by c_rehash:
  588. // https://www.openssl.org/docs/manmaster/apps/c_rehash.html
  589. // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs
  590. File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE);
  591. final String errorMessage = "copy AndroidCAStore failed";
  592. try {
  593. File file = new File(directory, "certs.dat");
  594. // Pave a fresh copy on every run, which ensures we're not using old certs.
  595. // Note: assumes KeyStore doesn't return revoked certs.
  596. //
  597. // TODO: this takes under 1 second, but should we avoid repaving every time?
  598. file.delete();
  599. PrintStream output = null;
  600. try {
  601. output = new PrintStream(new FileOutputStream(file));
  602. KeyStore keyStore;
  603. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  604. keyStore = KeyStore.getInstance("AndroidCAStore");
  605. keyStore.load(null, null);
  606. } else {
  607. keyStore = KeyStore.getInstance("BKS");
  608. FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks");
  609. try {
  610. keyStore.load(inputStream, "changeit".toCharArray());
  611. } finally {
  612. if (inputStream != null) {
  613. inputStream.close();
  614. }
  615. }
  616. }
  617. Enumeration<String> aliases = keyStore.aliases();
  618. while (aliases.hasMoreElements()) {
  619. String alias = aliases.nextElement();
  620. X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
  621. output.println("-----BEGIN CERTIFICATE-----");
  622. String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8");
  623. // OpenSSL appears to reject the default linebreaking done by Base64.encode,
  624. // so we manually linebreak every 64 characters
  625. for (int i = 0; i < pemCert.length() ; i+= 64) {
  626. output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length())));
  627. }
  628. output.println("-----END CERTIFICATE-----");
  629. }
  630. mHostService.onDiagnosticMessage("prepared PsiphonCAStore");
  631. return file.getAbsolutePath();
  632. } finally {
  633. if (output != null) {
  634. output.close();
  635. }
  636. }
  637. } catch (KeyStoreException e) {
  638. throw new Exception(errorMessage, e);
  639. } catch (NoSuchAlgorithmException e) {
  640. throw new Exception(errorMessage, e);
  641. } catch (CertificateException e) {
  642. throw new Exception(errorMessage, e);
  643. } catch (IOException e) {
  644. throw new Exception(errorMessage, e);
  645. }
  646. }
  647. private static String getDeviceRegion(Context context) {
  648. String region = "";
  649. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  650. if (telephonyManager != null) {
  651. region = telephonyManager.getSimCountryIso();
  652. if (region == null) {
  653. region = "";
  654. }
  655. if (region.length() == 0 && telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
  656. region = telephonyManager.getNetworkCountryIso();
  657. if (region == null) {
  658. region = "";
  659. }
  660. }
  661. }
  662. if (region.length() == 0) {
  663. Locale defaultLocale = Locale.getDefault();
  664. if (defaultLocale != null) {
  665. region = defaultLocale.getCountry();
  666. }
  667. }
  668. return region.toUpperCase(Locale.US);
  669. }
  670. //----------------------------------------------------------------------------------------------
  671. // Tun2Socks
  672. //----------------------------------------------------------------------------------------------
  673. @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
  674. private void startTun2Socks(
  675. final ParcelFileDescriptor vpnInterfaceFileDescriptor,
  676. final int vpnInterfaceMTU,
  677. final String vpnIpAddress,
  678. final String vpnNetMask,
  679. final String socksServerAddress,
  680. final String udpgwServerAddress,
  681. final boolean udpgwTransparentDNS) {
  682. if (mTun2SocksThread != null) {
  683. return;
  684. }
  685. mTun2SocksThread = new Thread(new Runnable() {
  686. @Override
  687. public void run() {
  688. runTun2Socks(
  689. vpnInterfaceFileDescriptor.detachFd(),
  690. vpnInterfaceMTU,
  691. vpnIpAddress,
  692. vpnNetMask,
  693. socksServerAddress,
  694. udpgwServerAddress,
  695. udpgwTransparentDNS ? 1 : 0);
  696. }
  697. });
  698. mTun2SocksThread.start();
  699. mHostService.onDiagnosticMessage("tun2socks started");
  700. }
  701. private void stopTun2Socks() {
  702. if (mTun2SocksThread != null) {
  703. try {
  704. terminateTun2Socks();
  705. mTun2SocksThread.join();
  706. } catch (InterruptedException e) {
  707. Thread.currentThread().interrupt();
  708. }
  709. mTun2SocksThread = null;
  710. mHostService.onDiagnosticMessage("tun2socks stopped");
  711. }
  712. }
  713. public static void logTun2Socks(String level, String channel, String msg) {
  714. String logMsg = "tun2socks: " + level + "(" + channel + "): " + msg;
  715. mPsiphonTunnel.mHostService.onDiagnosticMessage(logMsg);
  716. }
  717. private native static int runTun2Socks(
  718. int vpnInterfaceFileDescriptor,
  719. int vpnInterfaceMTU,
  720. String vpnIpAddress,
  721. String vpnNetMask,
  722. String socksServerAddress,
  723. String udpgwServerAddress,
  724. int udpgwTransparentDNS);
  725. private native static int terminateTun2Socks();
  726. private native static int enableUdpGwKeepalive();
  727. private native static int disableUdpGwKeepalive();
  728. //----------------------------------------------------------------------------------------------
  729. // Implementation: Network Utils
  730. //----------------------------------------------------------------------------------------------
  731. private static boolean hasNetworkConnectivity(Context context) {
  732. ConnectivityManager connectivityManager =
  733. (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  734. if (connectivityManager == null) {
  735. return false;
  736. }
  737. NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
  738. return networkInfo != null && networkInfo.isConnected();
  739. }
  740. private static class PrivateAddress {
  741. final public String mIpAddress;
  742. final public String mSubnet;
  743. final public int mPrefixLength;
  744. final public String mRouter;
  745. public PrivateAddress(String ipAddress, String subnet, int prefixLength, String router) {
  746. mIpAddress = ipAddress;
  747. mSubnet = subnet;
  748. mPrefixLength = prefixLength;
  749. mRouter = router;
  750. }
  751. }
  752. private static PrivateAddress selectPrivateAddress() throws Exception {
  753. // Select one of 10.0.0.1, 172.16.0.1, or 192.168.0.1 depending on
  754. // which private address range isn't in use.
  755. Map<String, PrivateAddress> candidates = new HashMap<String, PrivateAddress>();
  756. candidates.put( "10", new PrivateAddress("10.0.0.1", "10.0.0.0", 8, "10.0.0.2"));
  757. candidates.put("172", new PrivateAddress("172.16.0.1", "172.16.0.0", 12, "172.16.0.2"));
  758. candidates.put("192", new PrivateAddress("192.168.0.1", "192.168.0.0", 16, "192.168.0.2"));
  759. candidates.put("169", new PrivateAddress("169.254.1.1", "169.254.1.0", 24, "169.254.1.2"));
  760. List<NetworkInterface> netInterfaces;
  761. try {
  762. netInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
  763. } catch (SocketException e) {
  764. throw new Exception("selectPrivateAddress failed", e);
  765. }
  766. for (NetworkInterface netInterface : netInterfaces) {
  767. for (InetAddress inetAddress : Collections.list(netInterface.getInetAddresses())) {
  768. String ipAddress = inetAddress.getHostAddress();
  769. if (InetAddressUtils.isIPv4Address(ipAddress)) {
  770. if (ipAddress.startsWith("10.")) {
  771. candidates.remove("10");
  772. }
  773. else if (
  774. ipAddress.length() >= 6 &&
  775. ipAddress.substring(0, 6).compareTo("172.16") >= 0 &&
  776. ipAddress.substring(0, 6).compareTo("172.31") <= 0) {
  777. candidates.remove("172");
  778. }
  779. else if (ipAddress.startsWith("192.168")) {
  780. candidates.remove("192");
  781. }
  782. }
  783. }
  784. }
  785. if (candidates.size() > 0) {
  786. return candidates.values().iterator().next();
  787. }
  788. throw new Exception("no private address available");
  789. }
  790. public static String getFirstActiveNetworkDnsResolver(Context context)
  791. throws Exception {
  792. Collection<InetAddress> dnsResolvers = getActiveNetworkDnsResolvers(context);
  793. if (!dnsResolvers.isEmpty()) {
  794. // strip the leading slash e.g., "/192.168.1.1"
  795. String dnsResolver = dnsResolvers.iterator().next().toString();
  796. if (dnsResolver.startsWith("/")) {
  797. dnsResolver = dnsResolver.substring(1);
  798. }
  799. return dnsResolver;
  800. }
  801. throw new Exception("no active network DNS resolver");
  802. }
  803. @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  804. private static Collection<InetAddress> getActiveNetworkDnsResolvers(Context context)
  805. throws Exception {
  806. final String errorMessage = "getActiveNetworkDnsResolvers failed";
  807. ArrayList<InetAddress> dnsAddresses = new ArrayList<InetAddress>();
  808. try {
  809. // Hidden API
  810. // - only available in Android 4.0+
  811. // - no guarantee will be available beyond 4.2, or on all vendor devices
  812. ConnectivityManager connectivityManager =
  813. (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  814. Class<?> LinkPropertiesClass = Class.forName("android.net.LinkProperties");
  815. Method getActiveLinkPropertiesMethod = ConnectivityManager.class.getMethod("getActiveLinkProperties", new Class []{});
  816. Object linkProperties = getActiveLinkPropertiesMethod.invoke(connectivityManager);
  817. if (linkProperties != null) {
  818. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  819. Method getDnsesMethod = LinkPropertiesClass.getMethod("getDnses", new Class []{});
  820. Collection<?> dnses = (Collection<?>)getDnsesMethod.invoke(linkProperties);
  821. for (Object dns : dnses) {
  822. dnsAddresses.add((InetAddress)dns);
  823. }
  824. } else {
  825. // LinkProperties is public in API 21 (and the DNS function signature has changed)
  826. for (InetAddress dns : ((LinkProperties)linkProperties).getDnsServers()) {
  827. dnsAddresses.add(dns);
  828. }
  829. }
  830. }
  831. } catch (ClassNotFoundException e) {
  832. throw new Exception(errorMessage, e);
  833. } catch (NoSuchMethodException e) {
  834. throw new Exception(errorMessage, e);
  835. } catch (IllegalArgumentException e) {
  836. throw new Exception(errorMessage, e);
  837. } catch (IllegalAccessException e) {
  838. throw new Exception(errorMessage, e);
  839. } catch (InvocationTargetException e) {
  840. throw new Exception(errorMessage, e);
  841. } catch (NullPointerException e) {
  842. throw new Exception(errorMessage, e);
  843. }
  844. return dnsAddresses;
  845. }
  846. //----------------------------------------------------------------------------------------------
  847. // Exception
  848. //----------------------------------------------------------------------------------------------
  849. public static class Exception extends java.lang.Exception {
  850. private static final long serialVersionUID = 1L;
  851. public Exception(String message) {
  852. super(message);
  853. }
  854. public Exception(String message, Throwable cause) {
  855. super(message + ": " + cause.getMessage());
  856. }
  857. }
  858. }