PsiphonTunnel.java 47 KB

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