Skip to content
mhattaPublic

About

A Tor client implementation and library written in pure Java

Topics

Resources

Stars

51 stars

Watchers

8 watching

Forks

 
 

Repository files navigation

Orchid

CI Android Maven Central javadoc Debian Java 8+ License

Orchid is a Tor client implementation and library written in pure Java. Orchid's strength is that it can be used to Tor-ify Java and JVM applications with near transparency.

It was written from the Tor specification documents, which are available here.

Orchid targets Java 8 bytecode and builds and runs on current JDKs (tested with JDK 21).

Orchid speaks the current Tor protocols: link protocols 4 and 5, ntor circuit handshakes (CREATE2 and EXTEND2; the obsolete TAP handshake is not implemented), authenticated SENDMEs for circuit flow control (proposal 289), microdescriptors without legacy TAP keys, and version 3 onion services (.onion addresses of 56 characters), implemented from rend-spec v3 including client authorization (restricted discovery). Version 2 onion services were removed from the Tor network in 2021 and are no longer supported.

As Tor does, Orchid uses congestion control (TOR_VEGAS, proposal 324), negotiated in the ntor-v3 handshake (proposal 332) with every hop that supports it (since 2.11.0; 2.10.0 used it with exits only) and with onion services that offer it, with XON/XOFF stream flow control that advises the application's read rate; runs the client side of the padding machines of onion service circuits (proposal 302); and sends RELAY_EARLY cells as Tor does. Since 3.1.0 it encrypts relay cells with Counter Galois Onion (CGO, proposal 359) with every hop that supports it, as Tor (since 0.4.9.12) and Arti do, and fetches the consensus as a diff from the one it has where the directory cache offers one. Like Tor, it refuses to carry streams while the network requires protocols of clients that it lacks (since 3.0.0; TorConfig#setRequireClientProtocols(false) turns that off, and TorClient#getMissingRequiredProtocols() says what is missing).

Where plain bridges are blocked, Orchid reaches bridges through WebTunnel (since 3.0.0), the pluggable transport that looks like a visit to a web site; see Bridges below.

Orchid does not yet speak some newer parts of the protocol that Tor and Arti use: conflux and proof of work for onion services; and of the pluggable transports it has only WebTunnel (others can be plugged in through com.subgraph.orchid.transport.Transport). Relays and network observers can therefore tell an Orchid client from a Tor client, and there are far fewer Orchid users to blend in with: the anonymity set is smaller than Tor's. Use Tor Browser where that matters.

Difference from Tor Who can see it
TLS ClientHello of the Java platform (JSSE, or Conscrypt on Android) the network, censors, the guard
No conflux the exit
No proof of work for onion services onion services under attack
IPv4 only observers of guard choice

How can Orchid be used?

Orchid can be used as a standalone client where the canonical Tor would otherwise be used. Orchid acts as a SOCKS5 proxy.

Orchid can also be used as a library by any application running on the JVM. This is what Orchid was really designed for and this is the recommended way to use it. Orchid can be used as a library in any Java application, or any application written in a language that compiles bytecode that will run on the Java virtual machine, e.g. JRuby, Clojure, Scala...

How to build

Orchid uses Gradle (8.x) as its build system.

gradle build

will compile, run the unit tests and produce the JARs in the build/libs directory:

  • Orchid-<version>.jar, the library and standalone client. It has no dependencies.
  • Orchid-<version>-demo.jar, the example programs in src/demo (com.demo), which need commons-io and jsoup. gradle runDemo runs OrchidDemo.

gradle fatJar produces Orchid-<version>-all.jar, a JAR to run Orchid as a standalone client with java -jar. (Since the library has no dependencies, it is the same as the plain JAR.)

gradle xmlrpcJar produces Orchid-<version>-xmlrpc.jar, the transport for Apache XML-RPC clients in src/xmlrpc (com.subgraph.orchid.xmlrpc). It is no longer part of the library: Apache XML-RPC is unmaintained, and its client deserializes Java objects sent by the server (CVE-2019-17570), so use it only with servers you trust.

If you cannot reach Maven Central, drop the jars needed into lib/ (see lib/README.md).

The version comes from the git tag (git describe): a build of the commit tagged v2.0.0 is version 2.0.0, and a later commit builds as, for example, 2.0.0-3-g1234abcd. There is no version number to edit in the source; to make a release, tag the commit (git tag -a v2.0.1) and build it.

You may find prebuilt JARs in Releases.

How to run

To start the Orchid SOCKS5 proxy, perform the following:

java -jar Orchid-<version>-all.jar

To test Orchid, you can tell your web browser to use Orchid as a SOCKS5 proxy (the default listening port is 9150, on the loopback address 127.0.0.1 only; TorConfig#setSocksListenAddress() changes the address, but do not expose the port to other hosts unless you mean to run an open proxy) - however it is important to note that Orchid + your browser is NOT a secure replacement for Tor Browser, which has many other enhancements beyond Tor.

For example, with Mozilla Firefox, by default, DNS lookups are not sent over a configured SOCKS5 proxy. You can change this potentially de-anonymizing default configuration by going to the URL about:config and setting the property network.proxy.socks_remote_dns to true (this is already done in the Tor Browser).

Stream isolation and SOCKS authentication

As in Tor (IsolateSOCKSAuth), streams that come with different SOCKS credentials never share a circuit, to an exit or to an onion service: the SOCKS 5 user name and password (RFC 1929), or the SOCKS 4 user id, select the circuits. A browser can thus keep its tabs or sites apart by using a different user name for each. Streams without credentials share their own circuits.

TorConfig#setSocksPassword() makes the SOCKS port require a password: SOCKS 5 clients must then authenticate with it (any user name), and SOCKS 4 clients are refused. Applications that use Orchid as a library can isolate streams too, with TorClient#openExitStreamTo(host, port, isolationKey) or TorClient#getSocketFactory(isolationKey).

TorConfig#setSocksPasswords(Map) (since 2.9.0) sets a password for each named application, any of which the ports accept: each application then has circuits of its own, so that it cannot ride on another's circuits or learn from their timing which hosts it went to, and its requests are counted separately (see below). The passwords, the profiles and the isolation options are read for each request, so they can be changed while the client runs.

Applications that look host names up themselves and then give Orchid only an address leak those names to the local network's DNS. Orchid logs a warning for such requests (WarnUnsafeSocks, on by default) and refuses them with TorConfig#setSafeSocks(true): SOCKS 4, SOCKS 5 with an address, and, unlike Tor, host names or CONNECT authorities that are address literals. TorClient#getProxyStatistics() (since 2.9.0) counts them, in total and by profile, so that an application can tell which of its clients do it.

Clients that cannot send credentials, such as apps that follow the Wi-Fi proxy setting of Android, would all share the same circuits. TorConfig#setIsolateDestAddr(true) (Tor's IsolateDestAddr) gives every destination host circuits of its own, on the SOCKS and HTTP tunnel ports, in addition to any isolation by credentials. It costs a circuit per host: the first connection to a host waits for one, and when the limit of isolation groups is reached, the idle group used longest ago is closed.

HTTP CONNECT

For applications and settings that can use only an HTTP proxy, such as the Wi-Fi proxy setting of Android, TorClient#enableHttpTunnelListener(port) opens an HTTP tunnel port (Tor's HTTPTunnelPort). It serves only CONNECT, which clients use for https:// URLs; plain HTTP requests are refused with "405 Method Not Allowed". The port listens on the same address as the SOCKS port and requires the same password, if one is set. The user name and password of a Proxy-Authorization: Basic header isolate streams as SOCKS 5 credentials do, and the same credentials select the same circuits on both ports.

Using the dashboard

Orchid also includes a "dashboard" feature to observe information about the internal state of Tor. To start the dashboard, set the following property when the JAR is run like:

java -Dcom.subgraph.orchid.dashboard.port=10000 -jar Orchid-<version>-all.jar

To access the dashboard, just connect to the port (for this example 10000) with netcat. The dashboard has no authentication and listens on 127.0.0.1 only; on Android, where every app can reach that address, it does not start unless com.subgraph.orchid.dashboard.allowOnAndroid is set to true (for a debug build).

Connecting to onion services

Any v3 onion address can be used as a SOCKS5 destination. For services that use client authorization (restricted discovery), register the client's x25519 private key with the configuration, using the key encoding of Tor's ClientOnionAuthDir files:

TorConfig config = client.getConfig();
config.addOnionClientAuth("xxxx...xxxx.onion", "<52 character base32 private key>");

How to use as a library

Releases from 2.4.0 on are on Maven Central:

dependencies {
    implementation 'org.mhatta:orchid:3.1.0'
}
<dependency>
  <groupId>org.mhatta</groupId>
  <artifactId>orchid</artifactId>
  <version>3.1.0</version>
</dependency>

The jar has no dependencies and runs on Java 8 and later. Older forks of Orchid, such as org.bitcoinj:orchid, contain the same packages (com.subgraph.orchid): do not put both on the classpath. Exclude the old one if another dependency brings it in. Gradle detects the conflict by itself; with Maven, add an <exclusion> for org.bitcoinj:orchid.

The Orchid Tor client exposes a SocketFactory that can be used within a JVM application. The Android sample in samples/android shows one way to use it, and this Stack Overflow discussion has more examples.

Options from a file, bridge lines, timeouts

Applications that keep Orchid's options in a file, such as the I2P plugin, can apply them with TorConfigProperties (since 2.11.0): a properties file (circuitBuildTimeout=60 seconds) or a torrc-like file (UseBridges 1, Bridge ...), with Tor's option names in any case. Unknown and bad options are returned as a list to log.

List<String> problems = TorConfigProperties.apply(client.getConfig(), properties);

TorConfig#addBridge(String) takes a bridge line as BridgeDB gives it, transport and arguments included (see Bridges). The sockets of the socket factory honour setSoTimeout(), and so do streams (Stream#setReadTimeout()).

Bridges

Bridges are used with TorConfig#setUseBridges(true) and a bridge line each, as bridges.torproject.org gives them:

TorConfig config = client.getConfig();
config.setUseBridges(true);
config.addBridge("192.0.2.1:443 4A2F8C1E9B7D3A5F6E0C2B4D8A1F3E5C7B9D0A2E");
config.addBridge("webtunnel [2001:db8::1]:443 4A2F8C1E9B7D3A5F6E0C2B4D8A1F3E5C7B9D0A2E "
        + "url=https://example.com/secret-path ver=0.0.1");
  • Plain bridges are reached directly, over IPv4.
  • WebTunnel bridges (since 3.0.0) are reached through com.subgraph.orchid.transport.WebTunnelTransport, which is built in: TLS to the HTTPS server of url=, checked against the platform's certificate authorities and the host name (or only against the pinned chain of cert=, as the reference client does), an HTTP upgrade to the path, and the Tor link inside. servername= and addr= are read as well. The address of the line is a placeholder. The server's name is looked up with the system's resolver (within the connection's timeout, since 3.1.0) and sent as the TLS server name, so the network sees which site is visited, but not the path, the bridge's secret. The system's lookup usually goes to the network's DNS server in the clear, where a censor can block it; on Android, Private DNS keeps it from the network. To use other certificate authorities (an old Android release without a current root, say), or another resolver (DNS over HTTPS, say; since 3.1.0), register new WebTunnelTransport(trustManager, resolver) with TorConfig#registerTransport().
  • Other transports (obfs4, Snowflake, meek) are not built in: their bridges are skipped with a warning, unless the application registers a Transport for them.
  • Lines that cannot work are left out when they are loaded, with a warning: a transport that is not registered, or a WebTunnel line without a usable url= (bridges.torproject.org sometimes hands out one with an empty url=). TorClient#getUnusableBridges() counts them.
  • Keep the fingerprint: without one, Orchid trusts whatever relay answers at the bridge's address, which a censor on the path can impersonate. TorClient#getBridgesWithoutFingerprint() (since 3.0.0) counts such lines, for applications that do not show Orchid's log.

Traffic counters

TorClient#getTrafficInfo() returns how many bytes the client has sent and received since it was created, for a data usage or bandwidth display:

TrafficInfo t = client.getTrafficInfo();
t.getBytesRead();          // cells received from relays
t.getBytesWritten();       // cells sent to relays
t.getStreamBytesRead();    // data of the applications' streams
t.getStreamBytesWritten();

The first pair counts everything Orchid exchanges with relays, directory downloads and circuit building included, but not the TLS and TCP/IP overhead. The second counts only the data of streams opened through the SOCKS or HTTP CONNECT port, the socket factory or openExitStreamTo(). The counters only grow; for a rate, take two snapshots and divide the difference by the time between them.

Using Orchid on Android

Orchid targets Android 7.0 (API level 24) and later as a library; Android support is still being completed and tested. samples/android is a small app that does all of the following. An app that embeds it should:

  • Set the data directory before start(): the default, ~/.orchid, does not exist on Android, and start() fails without a usable data directory. Use a folder that is not backed up:

    TorClient client = new TorClient();
    client.getConfig().setDataDirectory(new File(context.getNoBackupFilesDir(), "orchid"));
    client.start();
  • Bundle a geoip database as the classpath resource /com/subgraph/orchid/geoip/geoip if node filters name countries; otherwise start() refuses them (see below).

  • Send the log to logcat with Logger.setHandler(); the javadoc of LogHandler has an example. SafeLogging (on by default) keeps stream destinations out of the log, and the addresses of the guards and bridges Orchid connects to (and of the device, which Android's socket errors name). Logcat can still be read with adb and in bug reports, so a release build should forward warnings at most.

  • Report network changes with client.notifyNetworkChanged(), from a ConnectivityManager.NetworkCallback.

  • Let Orchid rest when unused. After DormantClientTimeout without a stream request (24 hours by default, as in Tor; at least 10 minutes), Orchid becomes dormant: it builds no circuits in advance, downloads no directory information, closes the circuits no stream uses and asks its guards to stop padding. The next request wakes it up. On a phone a shorter timeout saves battery:

    client.getConfig().setDormantClientTimeout(30, TimeUnit.MINUTES);

    client.setDormant(true) makes it dormant at once (when the user pauses the app, say), setDormant(false) wakes it up ahead of use, and a DormantListener is told of each change, for the foreground notification. Circuits built in advance and never used are closed after half to all of CircuitIdleTimeout (30 to 60 minutes by default) in any case, so that the connection to the guard can close. TorConfig#setConnectionPadding(false) asks the guards never to pad (Tor's ConnectionPadding 0), for metered networks; padding blurs the connection records ISPs keep, so leave it on otherwise.

  • Keep host names off the device's DNS with HTTP clients that resolve names themselves, such as OkHttp: use torClient.getSocketFactory(key) and a DNS hook that returns OrchidSocketFactory.unresolvedAddress(host).

  • Run TLS through an SSLEngine for HTTPS over Orchid: give the HTTP client new AndroidSSLSocketFactory(sslContext) (for OkHttp, with sslSocketFactory(factory, trustManager)). The platform's SSLSocket needs a socket with a file descriptor, which a Tor stream does not have; on older releases such as Android 7.0 the handshake fails with "Socket closed". It checks the server's certificate against the host name itself, after the handshake, since not every platform's SSLEngine does.

  • Trust the Let's Encrypt roots on Android 7.0 if the app talks to sites with Let's Encrypt certificates: 7.0 (API 24) does not ship ISRG Root X1, so the handshake fails there whether or not Tor is used. The sample adds ISRG Root X1 and X2 with a network security config.

  • Protect the SOCKS port, if the app opens one: every app on the device can connect to 127.0.0.1. Set a random password with TorConfig#setSocksPassword() and give it only to the app's own HTTP client (or one per client app, with TorConfig#setSocksPasswords()).

  • Keep the port while restarting the client: if the app restarts the TorClient (to apply new settings, say), bind the port itself and pass the ServerSocket to TorClient#enableSocksListener(ServerSocket) (since 2.9.0). Orchid's own port is closed by stop(), and until the next client binds it again any other app can bind it and receive the connections meant for Tor.

  • Pause instead of closing the port: TorClient#setProxyPaused(true) (since 2.10.0) keeps the ports bound but resets every new connection, so that the apps set up to use the proxy fail at once and no other app can take the port. setProxyPaused(true, true) (since 2.11.0) also closes the connections already open.

  • Change passwords cleanly: a new password only applies to new connections. When the app removes a profile or makes a new password for it, TorClient#closeProxyConnections(profile) closes what the old one opened, and TorClient#newIdentity(profile) (both since 2.11.0) gives that profile new circuits without disturbing the others.

  • Tell the user to update: since 3.0.0, Orchid refuses streams while the Tor network requires protocols that it lacks, as Tor does. An app that shows TorClient#getMissingRequiredProtocols() to the user and prefers to go on may call setRequireClientProtocols(false).

  • Warn about bridges without a fingerprint, and those that cannot be used: TorClient#getBridgesWithoutFingerprint() and TorClient#getUnusableBridges() (since 3.0.0).

  • Test on a device or an emulator: the sample's instrumented test (gradlew connectedDebugAndroidTest in samples/android) checks that a request through Orchid reaches check.torproject.org from Tor.

Authors

Orchid was originally developed by Bruce Leidl of Subgraph. The original web page can be found here. This README borrows heavily from there.

This fork is currently maintained by Masayuki Hatta (@mhatta.org on Bluesky).

Acknowledgements

The current Orchid has been incorporated with various improvements from the following projects/people:

License

This project is licensed under the 3-clause BSD License - see the LICENSE for details.

Demo

A typical Orchid run will output something like this:

2018-04-06 04:06:10,458 INFO - TorClient - Starting Orchid (version: 1.0.0)
2018-04-06 04:06:10,461 INFO - DirectoryImpl - Loading cached network information from disk
2018-04-06 04:06:10,461 INFO - DirectoryImpl - Loading certificates
2018-04-06 04:06:15,582 INFO - DirectoryImpl - Loading consensus
2018-04-06 04:06:15,615 INFO - DirectoryImpl - Loading microdescriptor cache
2018-04-06 04:06:15,616 INFO - DirectoryImpl - loading state file
2018-04-06 04:06:15,617 INFO - DirectoryDownloadTask - Downloading consensus because we have no consensus document
2018-04-06 04:06:15,713 INFO - TorClient - >>> [ 5% ]: Connecting to directory server
2018-04-06 04:06:15,947 INFO - TorClient - >>> [ 10% ]: Finishing handshake with directory server
2018-04-06 04:10:12,024 INFO - TorClient - >>> [ 15% ]: Establishing an encrypted directory connection
2018-04-06 04:10:12,718 INFO - TorClient - >>> [ 20% ]: Asking for networkstatus consensus
2018-04-06 04:10:13,014 INFO - TorClient - >>> [ 25% ]: Loading networkstatus consensus
2018-04-06 04:10:17,877 INFO - ConsensusDocumentImpl - Certificates need to be retrieved to verify consensus
2018-04-06 04:20:25,616 INFO - TorClient - >>> [ 35% ]: Asking for authority key certs
2018-04-06 04:20:25,900 INFO - TorClient - >>> [ 40% ]: Loading authority key certs
2018-04-06 04:20:31,612 INFO - TorClient - >>> [ 45% ]: Asking for relay descriptors
2018-04-06 04:20:31,662 INFO - TorClient - >>> [ 50% ]: Loading relay descriptors
2018-04-06 04:20:35,680 INFO - TorClient - >>> [ 80% ]: Connecting to the Tor network
2018-04-06 04:20:35,804 INFO - TorClient - >>> [ 85% ]: Finished Handshake with first hop
2018-04-06 04:28:14,594 INFO - TorClient - >>> [ 90% ]: Establishing a Tor circuit
2018-04-06 04:28:15,362 INFO - TorClient - >>> [ 100% ]: Done
2018-04-06 04:28:15,362 INFO - TorClient - Tor is ready to go!

There will be a lot of INFO - CircuitCreationTask - Cannot build circuits because we don't have enough directory information warnings and pauses during the session. It is usually OK, be patient. The first time run will take much longer time than the sessions hereafter.

Country codes (GeoIP)

Node filters such as ExcludeNodes and ExitNodes can name countries ({de}, {us}, or {??} for relays of unknown country). Orchid looks up the country of a relay in Tor's geoip database, which it does not ship. It uses the first of:

  • the file named by -Dcom.subgraph.orchid.geoipFile=/path/to/geoip,
  • data/geoip in the working directory (tools/update-geoip.sh downloads Tor's current one there),
  • the file installed with Tor: /usr/share/tor/geoip (on Debian and Ubuntu, apt install tor-geoipdb), /usr/local/share/tor/geoip or /opt/homebrew/share/tor/geoip,
  • the classpath resource /com/subgraph/orchid/geoip/geoip, for applications (such as Android apps) that bundle it.

Without it the country of every relay is unknown, so ExcludeNodes {cc} would exclude nothing. TorClient#start() therefore refuses to start, with a TorException, when ExcludeNodes, ExcludeExitNodes, EntryNodes or ExitNodes name a country and no database was found ({??} is allowed). Tor makes the database from the IPFire Location database (CC BY-SA 4.0).

Directory information

Like Tor, Orchid downloads the consensus and the relay descriptors from directory caches (relays with the V2Dir flag) over the ORPort. Until it has a consensus it uses the fallback directories that Tor ships, and only rarely a directory authority. The fallback list is compiled into FallbackDirectoryList.java; refresh it from a current Tor release from time to time:

tools/gen-fallback-dirs.py /path/to/tor/src/app/config/fallback_dirs.inc \
    > src/main/java/com/subgraph/orchid/directory/FallbackDirectoryList.java

About

A Tor client implementation and library written in pure Java

Topics

Resources

Stars

51 stars

Watchers

8 watching

Forks

Releases

Packages

Contributors

Languages