-
-
Notifications
You must be signed in to change notification settings - Fork 326
/
OrbotService.java
1548 lines (1306 loc) · 68.6 KB
/
OrbotService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2009-2011, Nathan Freitas, Orbot / The Guardian Project - https://guardianproject.info/apps/orbot */
/* See LICENSE for licensing information */
package org.torproject.android.service;
import static org.torproject.jni.TorService.ACTION_ERROR;
import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.VpnService;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import net.freehaven.tor.control.TorControlCommands;
import net.freehaven.tor.control.TorControlConnection;
import org.torproject.android.service.util.CustomTorResourceInstaller;
import org.torproject.android.service.util.PowerConnectionReceiver;
import org.torproject.android.service.util.Prefs;
import org.torproject.android.service.util.Utils;
import org.torproject.android.service.vpn.OrbotVpnManager;
import org.torproject.jni.TorService;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import IPtProxy.IPtProxy;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public class OrbotService extends VpnService implements OrbotConstants {
public final static String BINARY_TOR_VERSION = TorService.VERSION_NAME;
static final int NOTIFY_ID = 1;
private static final int ERROR_NOTIFY_ID = 3;
//these will be set dynamically due to build flavors
private static Uri V3_ONION_SERVICES_CONTENT_URI = null;//Uri.parse("content://org.torproject.android.ui.v3onionservice/v3");
private static Uri V3_CLIENT_AUTH_URI = null;//Uri.parse("content://org.torproject.android.ui.v3onionservice.clientauth/v3auth");
private final static String NOTIFICATION_CHANNEL_ID = "orbot_channel_1";
private static final String[] V3_ONION_SERVICE_PROJECTION = new String[]{OnionService._ID, OnionService.NAME, OnionService.DOMAIN, OnionService.PORT, OnionService.ONION_PORT, OnionService.ENABLED, OnionService.PATH};
private static final String[] V3_CLIENT_AUTH_PROJECTION = new String[]{V3ClientAuth._ID, V3ClientAuth.DOMAIN, V3ClientAuth.HASH, V3ClientAuth.ENABLED};
public static int mPortSOCKS = -1;
public static int mPortHTTP = -1;
public static int mPortDns = -1;
public static int mPortTrans = -1;
public static File appBinHome;
public static File appCacheHome;
private final ExecutorService mExecutor = Executors.newCachedThreadPool();
OrbotRawEventListener mOrbotRawEventListener;
OrbotVpnManager mVpnManager;
Handler mHandler;
ActionBroadcastReceiver mActionBroadcastReceiver;
private String mCurrentStatus = STATUS_OFF;
TorControlConnection conn = null;
private ServiceConnection torServiceConnection;
private boolean shouldUnbindTorService;
private NotificationManager mNotificationManager = null;
private NotificationCompat.Builder mNotifyBuilder;
private File mV3OnionBasePath, mV3AuthBasePath;
private PowerConnectionReceiver mPowerReceiver;
private boolean mHasPower = false;
private boolean mHasWifi = false;
/**
* @param bridgeList bridges that were manually entered into Orbot settings
* @return Array with each bridge as an element, no whitespace entries see issue #289...
*/
private static String[] parseBridgesFromSettings(String bridgeList) {
// this regex replaces lines that only contain whitespace with an empty String
bridgeList = bridgeList.trim().replaceAll("(?m)^[ \t]*\r?\n", "");
return bridgeList.split("\\n");
}
public void debug(String msg) {
Log.d(TAG, msg);
if (Prefs.useDebugLogging()) {
sendCallbackLogMessage(msg);
}
}
public void logException(String msg, Exception e) {
if (Prefs.useDebugLogging()) {
Log.e(TAG, msg, e);
var baos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(baos));
sendCallbackLogMessage(msg + '\n' + baos);
} else sendCallbackLogMessage(msg);
}
private void showConnectedToTorNetworkNotification() {
mNotifyBuilder.setProgress(0, 0, false);
showToolbarNotification(getString(R.string.status_activated), NOTIFY_ID, R.drawable.ic_stat_tor);
}
@Override
public void onLowMemory() {
super.onLowMemory();
//this doesn't need to be shown to the user unless there is something to do
debug(getString(R.string.log_notice_low_memory_warning));
}
private void clearNotifications() {
if (mNotificationManager != null) mNotificationManager.cancelAll();
if (mOrbotRawEventListener != null) mOrbotRawEventListener.getNodes().clear();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel() {
var mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
var mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW);
mChannel.setDescription(getString(R.string.app_description));
mChannel.enableLights(false);
mChannel.enableVibration(false);
mChannel.setShowBadge(false);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
mNotificationManager.createNotificationChannel(mChannel);
}
@SuppressLint({"NewApi", "RestrictedApi"})
protected void showToolbarNotification(String notifyMsg, int notifyType, int icon) {
var intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
var pendIntent = PendingIntent.getActivity(OrbotService.this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
if (mNotifyBuilder == null) {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID).setSmallIcon(R.drawable.ic_stat_tor).setContentIntent(pendIntent).setCategory(Notification.CATEGORY_SERVICE);
}
mNotifyBuilder.setOngoing(true);
var title = getString(R.string.status_disabled);
if (mCurrentStatus.equals(STATUS_STARTING) || notifyMsg.equals(getString(R.string.status_starting_up)))
title = getString(R.string.status_starting_up);
else if (mCurrentStatus.equals(STATUS_ON)) {
title = getString(R.string.status_activated);
}
mNotifyBuilder.setContentTitle(title);
mNotifyBuilder.mActions.clear(); // clear out any notification actions, if any
if (conn != null && mCurrentStatus.equals(STATUS_ON)) { // only add new identity action when there is a connection
var pendingIntentNewNym = PendingIntent.getBroadcast(this, 0, new Intent(TorControlCommands.SIGNAL_NEWNYM), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
mNotifyBuilder.addAction(R.drawable.ic_refresh_white_24dp, getString(R.string.menu_new_identity), pendingIntentNewNym);
} else if (mCurrentStatus.equals(STATUS_OFF)) {
var pendingIntentConnect = PendingIntent.getBroadcast(this, 0, new Intent(LOCAL_ACTION_NOTIFICATION_START), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
mNotifyBuilder.addAction(R.drawable.ic_stat_tor, getString(R.string.connect_to_tor), pendingIntentConnect);
}
mNotifyBuilder.setContentText(notifyMsg).setSmallIcon(icon).setTicker(notifyType != NOTIFY_ID ? notifyMsg : null);
if (!mCurrentStatus.equals(STATUS_ON)) {
mNotifyBuilder.setSubText(null);
}
if (!mCurrentStatus.equals(STATUS_STARTING)) {
mNotifyBuilder.setProgress(0, 0, false); // removes progress bar
}
startForeground(NOTIFY_ID, mNotifyBuilder.build());
}
public int onStartCommand(Intent intent, int flags, int startId) {
try {
if (intent == null) {
Log.d(TAG, "Got null onStartCommand() intent");
return Service.START_REDELIVER_INTENT;
}
final boolean shouldStartVpnFromSystemIntent = !intent.getBooleanExtra(OrbotConstants.EXTRA_NOT_SYSTEM, false);
if (mCurrentStatus.equals(STATUS_OFF))
showToolbarNotification(getString(R.string.open_orbot_to_connect_to_tor), NOTIFY_ID, R.drawable.ic_stat_tor);
if (shouldStartVpnFromSystemIntent) {
Log.d(TAG, "Starting VPN from system intent: " + intent);
showToolbarNotification(getString(R.string.status_starting_up), NOTIFY_ID, R.drawable.ic_stat_tor);
if (VpnService.prepare(this) == null) {
// Power-user mode doesn't matter here. If the system is starting the VPN, i.e.
// via always-on VPN, we need to start it regardless.
Prefs.putUseVpn(true);
mExecutor.execute(new IncomingIntentRouter(new Intent(ACTION_START)));
mExecutor.execute(new IncomingIntentRouter(new Intent(ACTION_START_VPN)));
} else {
Log.wtf(TAG, "Could not start VPN from system because it is not prepared, which should be impossible!");
}
} else {
mExecutor.execute(new IncomingIntentRouter(intent));
}
} catch (RuntimeException re) {
//catch this to avoid malicious launches as document Cure53 Audit: ORB-01-009 WP1/2: Orbot DoS via exported activity (High)
}
return Service.START_REDELIVER_INTENT;
}
private void showDeactivatedNotification() {
showToolbarNotification(getString(R.string.open_orbot_to_connect_to_tor), NOTIFY_ID, R.drawable.ic_stat_tor);
}
@Override
public void onDestroy() {
try {
unregisterReceiver(mActionBroadcastReceiver);
unregisterReceiver(mPowerReceiver);
} catch (IllegalArgumentException iae) {
//not registered yet
}
super.onDestroy();
}
private void stopTorAsync(boolean showNotification) {
debug("stopTor");
if (showNotification) sendCallbackLogMessage(getString(R.string.status_shutting_down));
var connectionPathway = Prefs.getConnectionPathway();
// todo this needs to handle a lot of different cases that haven't been defined yet
// todo particularly this is true for the smart connection case...
if (connectionPathway.startsWith(Prefs.PATHWAY_SNOWFLAKE) || Prefs.getPrefSmartTrySnowflake()) {
IPtProxy.stopSnowflake();
} else if (connectionPathway.equals(Prefs.PATHWAY_CUSTOM) || Prefs.getPrefSmartTryObfs4() != null) {
IPtProxy.stopLyrebird();
}
stopTor();
//stop the foreground priority and make sure to remove the persistent notification
stopForeground(!showNotification);
if (showNotification) sendCallbackLogMessage(getString(R.string.status_disabled));
mPortDns = -1;
mPortSOCKS = -1;
mPortHTTP = -1;
mPortTrans = -1;
if (!showNotification) {
clearNotifications();
stopSelf();
}
}
private void stopTorOnError(String message) {
stopTorAsync(false);
showToolbarNotification(getString(R.string.unable_to_start_tor) + ": " + message, ERROR_NOTIFY_ID, R.drawable.ic_stat_notifyerr);
}
private static HashMap<String, String> mFronts;
public static void loadCdnFronts(Context context) {
if (mFronts == null) {
mFronts = new HashMap<>();
try {
var reader = new BufferedReader(new InputStreamReader(context.getAssets().open("fronts")));
String line;
while ((line = reader.readLine()) != null) {
int spaceIdx = line.indexOf(' ');
String key = line.substring(0, spaceIdx);
String val = line.substring(spaceIdx + 1);
mFronts.put(key, val);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getCdnFront(String service) {
return mFronts.get(service);
}
private void startSnowflakeClientDomainFronting() {
//this is using the current, default Tor snowflake infrastructure
var target = getCdnFront("snowflake-target");
var front = getCdnFront("snowflake-front");
var stunServer = getCdnFront("snowflake-stun");
/*
// @param ice Comma-separated list of ICE servers.
// @param url URL of signaling broker.
// @param fronts Comma-separated list of front domains.
// @param ampCache OPTIONAL. URL of AMP cache to use as a proxy for signaling.
// Only needed when you want to do the rendezvous over AMP instead of a domain fronted server.
// @param sqsQueueURL OPTIONAL. URL of SQS Queue to use as a proxy for signaling.
// @param sqsCredsStr OPTIONAL. Credentials to access SQS Queue.
// @param logFile Name of log file. OPTIONAL. Defaults to no log.
// @param logToStateDir Resolve the log file relative to Tor's PT state dir.
// @param keepLocalAddresses Keep local LAN address ICE candidates.
// @param unsafeLogging Prevent logs from being scrubbed.
// @param maxPeers Capacity for number of multiplexed WebRTC peers. DEFAULTs to 1 if less than that.
// @return Port number where Snowflake will listen on, if no error happens during start up.
*/
IPtProxy.startSnowflake(stunServer, target, front, null, null, null, null,true, false, false, 1);
}
private void startSnowflakeClientAmpRendezvous() {
var stunServers = getCdnFront("snowflake-stun");
var target = getCdnFront("snowflake-target-direct");
var front = getCdnFront("snowflake-amp-front");
var ampCache = getCdnFront("snowflake-amp-cache");
IPtProxy.startSnowflake(stunServers, target, front, ampCache, null, null, null, true, false, false, 1);
}
private final SecureRandom mSecureRandGen = new SecureRandom(); //used to randomly select STUN servers for snowflake
public synchronized void enableSnowflakeProxy() { // This is to host a snowflake entrance node / bridge
if (!IPtProxy.isSnowflakeProxyRunning()) {
if (Prefs.limitSnowflakeProxyingWifi() && (!mHasWifi))
return;
if (Prefs.limitSnowflakeProxyingCharging() && (!mHasPower))
return;
var capacity = 1;
var keepLocalAddresses = false;
var unsafeLogging = false;
var stunServers = getCdnFront("snowflake-stun").split(",");
int randomIndex = mSecureRandGen.nextInt(stunServers.length);
var stunUrl = stunServers[randomIndex];
var relayUrl = getCdnFront("snowflake-relay-url");
var natProbeUrl = getCdnFront("snowflake-nat-probe");
var brokerUrl = getCdnFront("snowflake-target-direct");
IPtProxy.startSnowflakeProxy(capacity, brokerUrl, relayUrl, stunUrl, natProbeUrl, null, keepLocalAddresses, unsafeLogging, () -> {
Prefs.addSnowflakeServed();
if (!Prefs.showSnowflakeProxyMessage()) return;
var message = String.format(getString(R.string.snowflake_proxy_client_connected_msg), ONION_EMOJI, ONION_EMOJI);
new Handler(getMainLooper()).post(() -> Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show());
});
logNotice(getString(R.string.log_notice_snowflake_proxy_enabled));
if (Prefs.showSnowflakeProxyMessage()) {
var message = getString(R.string.log_notice_snowflake_proxy_enabled);
new Handler(getMainLooper()).post(() -> Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show());
}
}
}
private void enableSnowflakeProxyNetworkListener () {
if (Prefs.limitSnowflakeProxyingWifi()) {
//check if on wifi
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connMgr.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
checkNetworkForSnowflakeProxy ();
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
checkNetworkForSnowflakeProxy ();
}
});
}
}
}
public void setHasPower (boolean hasPower) {
mHasPower = hasPower;
if (Prefs.beSnowflakeProxy()) {
if (Prefs.limitSnowflakeProxyingCharging()) {
if (mHasPower) enableSnowflakeProxy();
else disableSnowflakeProxy();
}
}
}
private void checkNetworkForSnowflakeProxy () {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities netCap = connMgr.getNetworkCapabilities(connMgr.getActiveNetwork());
if (netCap != null)
mHasWifi = netCap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
else
mHasWifi = false;
}
else {
NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null)
mHasWifi = netInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
if (Prefs.beSnowflakeProxy()) {
if (Prefs.limitSnowflakeProxyingWifi()) {
if (mHasWifi) enableSnowflakeProxy();
else disableSnowflakeProxy();
}
}
}
public synchronized void disableSnowflakeProxy() {
if (IPtProxy.isSnowflakeProxyRunning()) {
IPtProxy.stopSnowflakeProxy();
logNotice(getString(R.string.log_notice_snowflake_proxy_disabled));
if (Prefs.showSnowflakeProxyMessage()) {
var message = getString(R.string.log_notice_snowflake_proxy_disabled);
new Handler(getMainLooper()).post(() -> Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show());
}
}
}
// if someone stops during startup, we may have to wait for the conn port to be setup, so we can properly shutdown tor
private void stopTor() {
if (shouldUnbindTorService) {
unbindService(torServiceConnection); //unbinding from the tor service will stop tor
shouldUnbindTorService = false;
conn = null;
} else {
sendLocalStatusOffBroadcast();
}
}
private void requestTorRereadConfig() {
try {
if (conn != null) {
conn.signal(TorControlCommands.SIGNAL_RELOAD);
}
} catch (IOException e) {
e.printStackTrace();
}
}
protected void logNotice(String msg) {
if (msg != null && msg.trim().length() > 0) {
if (Prefs.useDebugLogging()) Log.d(TAG, msg);
sendCallbackLogMessage(msg);
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void onCreate() {
super.onCreate();
configLanguage();
try {
//set proper content URIs for current build flavor
V3_ONION_SERVICES_CONTENT_URI = Uri.parse("content://" + getApplicationContext().getPackageName() + ".ui.v3onionservice/v3");
V3_CLIENT_AUTH_URI = Uri.parse("content://" + getApplicationContext().getPackageName() + ".ui.v3onionservice.clientauth/v3auth");
try {
mHandler = new Handler();
appBinHome = getFilesDir();
if (!appBinHome.exists()) appBinHome.mkdirs();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
appCacheHome = new File(getDataDir(), DIRECTORY_TOR_DATA);
} else {
appCacheHome = getDir(DIRECTORY_TOR_DATA, Application.MODE_PRIVATE);
}
if (!appCacheHome.exists()) appCacheHome.mkdirs();
mV3OnionBasePath = new File(getFilesDir().getAbsolutePath(), ONION_SERVICES_DIR);
if (!mV3OnionBasePath.isDirectory()) mV3OnionBasePath.mkdirs();
mV3AuthBasePath = new File(getFilesDir().getAbsolutePath(), V3_CLIENT_AUTH_DIR);
if (!mV3AuthBasePath.isDirectory()) mV3AuthBasePath.mkdirs();
if (mNotificationManager == null) {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
IntentFilter filter = new IntentFilter(TorControlCommands.SIGNAL_NEWNYM);
filter.addAction(CMD_ACTIVE);
filter.addAction(ACTION_STATUS);
filter.addAction(ACTION_ERROR);
filter.addAction(LOCAL_ACTION_NOTIFICATION_START);
mActionBroadcastReceiver = new ActionBroadcastReceiver();
registerReceiver(mActionBroadcastReceiver, filter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createNotificationChannel();
var hasGeoip = new File(appBinHome, GEOIP_ASSET_KEY).exists();
var hasGeoip6 = new File(appBinHome, GEOIP6_ASSET_KEY).exists();
// only write out geoip files if there's an app update or they don't exist
if (!hasGeoip || !hasGeoip6 || Prefs.isGeoIpReinstallNeeded()) {
try {
Log.d(TAG, "Installing geoip files...");
new CustomTorResourceInstaller(this, appBinHome).installGeoIP();
Prefs.setIsGeoIpReinstallNeeded(false);
} catch (IOException io) { // user has < 10MB free space on disk...
Log.e(TAG, "Error installing geoip files", io);
}
}
pluggableTransportInstall();
mVpnManager = new OrbotVpnManager(this);
loadCdnFronts(this);
} catch (Exception e) {
Log.e(TAG, "Error setting up Orbot", e);
logNotice(getString(R.string.couldn_t_start_tor_process_) + " " + e.getClass().getSimpleName());
}
mPowerReceiver = new PowerConnectionReceiver(this);
IntentFilter ifilter = new IntentFilter();
ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(mPowerReceiver, ifilter);
enableSnowflakeProxyNetworkListener();
if (Prefs.beSnowflakeProxy()
&& !(Prefs.limitSnowflakeProxyingCharging() || Prefs.limitSnowflakeProxyingWifi()))
enableSnowflakeProxy();
} catch (RuntimeException re) {
//catch this to avoid malicious launches as document Cure53 Audit: ORB-01-009 WP1/2: Orbot DoS via exported activity (High)
}
}
private void configLanguage() {
Configuration config = getBaseContext().getResources().getConfiguration();
Locale locale = new Locale(Prefs.getDefaultLocale());
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
protected String getCurrentStatus() {
return mCurrentStatus;
}
private void pluggableTransportInstall() {
var fileCacheDir = new File(getCacheDir(), "pt");
if (!fileCacheDir.exists())
//noinspection ResultOfMethodCallIgnored
fileCacheDir.mkdir();
try {
IPtProxy.setStateLocation(fileCacheDir.getAbsolutePath());
debug("IPtProxy state: " + IPtProxy.getStateLocation());
} catch (Error e) {
debug("IPtProxy state: not installed; " + e.getLocalizedMessage());
}
}
private File updateTorrcCustomFile() throws IOException {
var prefs = Prefs.getSharedPrefs(getApplicationContext());
var extraLines = new StringBuffer();
extraLines.append("\n");
extraLines.append("RunAsDaemon 0").append('\n');
extraLines.append("AvoidDiskWrites 1").append('\n');
var socksPortPref = prefs.getString(PREF_SOCKS, SOCKS_PROXY_PORT_DEFAULT);
if (socksPortPref.indexOf(':') != -1) socksPortPref = socksPortPref.split(":")[1];
socksPortPref = checkPortOrAuto(socksPortPref);
var httpPortPref = prefs.getString(PREF_HTTP, HTTP_PROXY_PORT_DEFAULT);
if (httpPortPref.indexOf(':') != -1) httpPortPref = httpPortPref.split(":")[1];
httpPortPref = checkPortOrAuto(httpPortPref);
var isolate = "";
if (prefs.getBoolean(PREF_ISOLATE_DEST, false)) {
isolate += " IsolateDestAddr ";
}
if (prefs.getBoolean(PREF_ISOLATE_PORT, false)) {
isolate += " IsolateDestPort ";
}
if (prefs.getBoolean(PREF_ISOLATE_PROTOCOL, false)) {
isolate += " IsolateClientProtocol ";
}
var ipv6Pref = "";
if (prefs.getBoolean(PREF_PREFER_IPV6, true)) {
ipv6Pref += " IPv6Traffic PreferIPv6 ";
}
if (prefs.getBoolean(PREF_DISABLE_IPV4, false)) {
ipv6Pref += " IPv6Traffic NoIPv4Traffic ";
}
if (!Prefs.openProxyOnAllInterfaces()) {
extraLines.append("SOCKSPort ").append(socksPortPref).append(isolate).append(ipv6Pref).append('\n');
} else {
extraLines.append("SOCKSPort 0.0.0.0:").append(socksPortPref).append(ipv6Pref).append(isolate).append("\n");
extraLines.append("SocksPolicy accept *:*").append('\n');
}
extraLines.append("SafeSocks 0").append('\n');
extraLines.append("TestSocks 0").append('\n');
extraLines.append("HTTPTunnelPort ").append(httpPortPref).append(isolate).append('\n');
if (prefs.getBoolean(PREF_CONNECTION_PADDING, false)) {
extraLines.append("ConnectionPadding 1").append('\n');
}
if (prefs.getBoolean(PREF_REDUCED_CONNECTION_PADDING, true)) {
extraLines.append("ReducedConnectionPadding 1").append('\n');
}
if (prefs.getBoolean(PREF_CIRCUIT_PADDING, true)) {
extraLines.append("CircuitPadding 1").append('\n');
} else {
extraLines.append("CircuitPadding 0").append('\n');
}
if (prefs.getBoolean(PREF_REDUCED_CIRCUIT_PADDING, true)) {
extraLines.append("ReducedCircuitPadding 1").append('\n');
}
var transPort = prefs.getString("pref_transport", TOR_TRANSPROXY_PORT_DEFAULT + "");
var dnsPort = prefs.getString("pref_dnsport", TOR_DNS_PORT_DEFAULT + "");
extraLines.append("TransPort ").append(checkPortOrAuto(transPort)).append(isolate).append('\n');
extraLines.append("DNSPort ").append(checkPortOrAuto(dnsPort)).append(isolate).append('\n');
extraLines.append("VirtualAddrNetwork 10.192.0.0/10").append('\n');
extraLines.append("AutomapHostsOnResolve 1").append('\n');
extraLines.append("DormantClientTimeout 10 minutes").append('\n');
// extraLines.append("DormantOnFirstStartup 0").append('\n');
extraLines.append("DormantCanceledByStartup 1").append('\n');
extraLines.append("DisableNetwork 0").append('\n');
if (Prefs.useDebugLogging()) {
extraLines.append("Log debug syslog").append('\n');
extraLines.append("SafeLogging 0").append('\n');
}
extraLines = processSettingsImpl(extraLines);
if (extraLines == null) return null;
extraLines.append('\n');
extraLines.append(prefs.getString("pref_custom_torrc", "")).append('\n');
logNotice(getString(R.string.log_notice_updating_torrc));
debug("torrc.custom=" + extraLines);
var fileTorRcCustom = TorService.getTorrc(this);
updateTorConfigCustom(fileTorRcCustom, extraLines.toString(), false);
return fileTorRcCustom;
}
private String checkPortOrAuto(String portString) {
if (!portString.equalsIgnoreCase("auto")) {
var isPortUsed = true;
var port = Integer.parseInt(portString);
while (isPortUsed) {
isPortUsed = Utils.isPortOpen("127.0.0.1", port, 500);
if (isPortUsed) //the specified port is not available, so let Tor find one instead
port++;
}
return port + "";
}
return portString;
}
public void updateTorConfigCustom(File fileTorRcCustom, String extraLines, boolean append) throws IOException {
var ps = new PrintWriter(new FileWriter(fileTorRcCustom, append));
ps.print(extraLines);
ps.flush();
ps.close();
}
/**
* Send Orbot's status in reply to an
* {@link #ACTION_START} {@link Intent}, targeted only to
* the app that sent the initial request. If the user has disabled auto-
* starts, the reply {@code ACTION_START Intent} will include the extra
* {@link #STATUS_STARTS_DISABLED}
*/
private void replyWithStatus(Intent startRequest) {
String packageName = startRequest.getStringExtra(EXTRA_PACKAGE_NAME);
Intent reply = new Intent(ACTION_STATUS);
reply.putExtra(EXTRA_STATUS, mCurrentStatus);
reply.putExtra(EXTRA_SOCKS_PROXY, "socks://127.0.0.1:" + mPortSOCKS);
reply.putExtra(EXTRA_SOCKS_PROXY_HOST, "127.0.0.1");
reply.putExtra(EXTRA_SOCKS_PROXY_PORT, mPortSOCKS);
reply.putExtra(EXTRA_HTTP_PROXY, "http://127.0.0.1:" + mPortHTTP);
reply.putExtra(EXTRA_HTTP_PROXY_HOST, "127.0.0.1");
reply.putExtra(EXTRA_HTTP_PROXY_PORT, mPortHTTP);
reply.putExtra(EXTRA_DNS_PORT, mPortDns);
if (packageName != null) {
reply.setPackage(packageName);
sendBroadcast(reply);
}
LocalBroadcastManager.getInstance(this).sendBroadcast(reply.setAction(LOCAL_ACTION_STATUS));
if (mPortSOCKS != -1 && mPortHTTP != -1)
sendCallbackPorts(mPortSOCKS, mPortHTTP, mPortDns, mPortTrans);
}
private boolean showTorServiceErrorMsg = false;
private static final int TIMEOUT_MS = 15000;
/**
* The entire process for starting tor and related services is run from this method.
*/
private void startTor() {
try {
if (torServiceConnection != null && conn != null) {
sendCallbackLogMessage(getString(R.string.log_notice_ignoring_start_request));
showConnectedToTorNetworkNotification();
return;
}
mNotifyBuilder.setProgress(100, 0, false);
showToolbarNotification("", NOTIFY_ID, R.drawable.ic_stat_tor);
if (Prefs.getConnectionPathway().equals(Prefs.PATHWAY_SMART)) {
smartConnectionPathwayStartTor();
}
startTorService();
showTorServiceErrorMsg = true;
if (Prefs.hostOnionServicesEnabled()) {
try {
updateV3OnionNames();
} catch (SecurityException se) {
logNotice(getString(R.string.log_notice_unable_to_update_onions));
}
}
} catch (Exception e) {
logException(getString(R.string.unable_to_start_tor) + " " + e.getLocalizedMessage(), e);
stopTorOnError(e.getLocalizedMessage());
}
}
static int TRIES_DELETE = 0;
private void smartConnectionPathwayStartTor() {
Log.d(TAG, "timing out in " + TIMEOUT_MS + "ms");
new Handler(Looper.getMainLooper()).postDelayed(() -> {
Log.d(TAG, "timed out mCurrentStatus=" + mCurrentStatus);
if (!mCurrentStatus.equals(STATUS_ON)) {
Log.d(TAG, "stopping tor...");
if (Prefs.getPrefSmartTrySnowflake()) {
Log.d(TAG, "trying snowflake didnt work");
clearEphemeralSmartConnectionSettings();
sendSmartStatusToActivity(SMART_STATUS_CIRCUMVENTION_ATTEMPT_FAILED);
} else if (Prefs.getPrefSmartTryObfs4() != null) {
Log.d(TAG, "trying obfs4 didnt work");
clearEphemeralSmartConnectionSettings();
sendSmartStatusToActivity(SMART_STATUS_CIRCUMVENTION_ATTEMPT_FAILED);
} else {
sendSmartStatusToActivity(SMART_STATUS_NO_DIRECT);
}
stopTorAsync(true);
} else {
// tor was connected in the allotted time
var obfs4 = Prefs.getPrefSmartTryObfs4();
if (obfs4 != null) {
// set these obfs4 bridges
Prefs.setBridgesList(obfs4);
Prefs.putConnectionPathway(Prefs.PATHWAY_CUSTOM);
} else if (Prefs.getPrefSmartTrySnowflake()) {
// set snowflake
Prefs.putConnectionPathway(Prefs.PATHWAY_SNOWFLAKE);
}
clearEphemeralSmartConnectionSettings();
}
}, ((TRIES_DELETE++) != 2) ? TIMEOUT_MS : 10000);
}
private void clearEphemeralSmartConnectionSettings() {
Prefs.putPrefSmartTryObfs4(null);
Prefs.putPrefSmartTrySnowflake(false);
}
private void sendSmartStatusToActivity(String status) {
var intent = new Intent(LOCAL_ACTION_SMART_CONNECT_EVENT).putExtra(LOCAL_EXTRA_SMART_STATUS, status);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void updateV3OnionNames() throws SecurityException {
var contentResolver = getApplicationContext().getContentResolver();
var onionServices = contentResolver.query(V3_ONION_SERVICES_CONTENT_URI, null, null, null, null);
if (onionServices != null) {
try {
while (onionServices.moveToNext()) {
var domain_index = onionServices.getColumnIndex(OnionService.DOMAIN);
var path_index = onionServices.getColumnIndex(OnionService.PATH);
var id_index = onionServices.getColumnIndex(OnionService._ID);
if (domain_index < 0 || path_index < 0 || id_index < 0) continue;
var domain = onionServices.getString(domain_index);
if (domain == null || TextUtils.isEmpty(domain)) {
var path = onionServices.getString(path_index);
var v3OnionDirPath = new File(mV3OnionBasePath.getAbsolutePath(), path).getCanonicalPath();
var hostname = new File(v3OnionDirPath, "hostname");
if (hostname.exists()) {
int id = onionServices.getInt(id_index);
domain = Utils.readInputStreamAsString(new FileInputStream(hostname)).trim();
var fields = new ContentValues();
fields.put(OnionService.DOMAIN, domain);
contentResolver.update(V3_ONION_SERVICES_CONTENT_URI, fields, OnionService._ID + "=" + id, null);
}
}
}
/*
This old status hack is temporary and fixes the issue reported by syphyr at
https://github.com/guardianproject/orbot/pull/556
Down the line a better approach needs to happen for sending back the onion names updated
status, perhaps just adding it as an extra to the normal Intent callback...
*/
var oldStatus = mCurrentStatus;
var intent = new Intent(LOCAL_ACTION_V3_NAMES_UPDATED);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
mCurrentStatus = oldStatus;
} catch (Exception e) {
e.printStackTrace();
}
onionServices.close();
}
}
private synchronized void startTorService() throws Exception {
updateTorConfigCustom(TorService.getDefaultsTorrc(this), """
DNSPort 0
TransPort 0
DisableNetwork 1
""", false);
var fileTorrcCustom = updateTorrcCustomFile();
if ((!fileTorrcCustom.exists()) || (!fileTorrcCustom.canRead())) return;
sendCallbackLogMessage(getString(R.string.status_starting_up));
torServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//moved torService to a local variable, since we only need it once
TorService torService = ((TorService.LocalBinder) iBinder).getService();
while ((conn = torService.getTorControlConnection()) == null) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//wait another second before we set our own event listener
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mOrbotRawEventListener = new OrbotRawEventListener(OrbotService.this);
if (conn != null) {
try {
initControlConnection();
if (conn == null)
return; // maybe there was an error setting up the control connection
//override the TorService event listener
conn.addRawEventListener(mOrbotRawEventListener);
logNotice(getString(R.string.log_notice_connected_to_tor_control_port));
//now set our own events
ArrayList<String> events = new ArrayList<>(Arrays.asList(TorControlCommands.EVENT_OR_CONN_STATUS, TorControlCommands.EVENT_CIRCUIT_STATUS, TorControlCommands.EVENT_NOTICE_MSG, TorControlCommands.EVENT_WARN_MSG, TorControlCommands.EVENT_ERR_MSG, TorControlCommands.EVENT_BANDWIDTH_USED, TorControlCommands.EVENT_NEW_DESC, TorControlCommands.EVENT_ADDRMAP));
if (Prefs.useDebugLogging()) {
events.add(TorControlCommands.EVENT_DEBUG_MSG);
events.add(TorControlCommands.EVENT_INFO_MSG);
}
if (Prefs.useDebugLogging())
events.add(TorControlCommands.EVENT_STREAM_STATUS);
conn.setEvents(events);
logNotice(getString(R.string.log_notice_added_event_handler));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
if (Prefs.useDebugLogging()) Log.d(TAG, "TorService: onServiceDisconnected");
sendLocalStatusOffBroadcast();
}
@Override
public void onNullBinding(ComponentName componentName) {
Log.w(TAG, "TorService: was unable to bind: onNullBinding");
}
@Override
public void onBindingDied(ComponentName componentName) {
Log.w(TAG, "TorService: onBindingDied");
sendLocalStatusOffBroadcast();
}
};
Intent serviceIntent = new Intent(this, TorService.class);
if (Build.VERSION.SDK_INT < 29) {
shouldUnbindTorService = bindService(serviceIntent, torServiceConnection, BIND_AUTO_CREATE);
} else {
shouldUnbindTorService = bindService(serviceIntent, BIND_AUTO_CREATE, mExecutor, torServiceConnection);
}
}
private void sendLocalStatusOffBroadcast() {
var localOffStatus = new Intent(LOCAL_ACTION_STATUS).putExtra(EXTRA_STATUS, STATUS_OFF);
LocalBroadcastManager.getInstance(this).sendBroadcast(localOffStatus);
}
protected void exec(Runnable run) {
mExecutor.execute(run);